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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
glint_parity_eval.py - EXACT port of Glint-1.3/benchmark.py eval-protocol,
|
| 4 |
+
model-agnostic. Measures OUR checkpoint on the BOARD's protocol so recon-position
|
| 5 |
+
is defensible (patrz labvault .../90-Ewaluacja/EvalHarnessParity.md).
|
| 6 |
+
|
| 7 |
+
Protocol fidelity (verbatim z Glint-1.3/benchmark.py):
|
| 8 |
+
- BLiMP: 67 configs, split='train', clip-first-256-tokens, raw-sum-logprobs
|
| 9 |
+
(NO BOS, NO length-norm), acc = good_ll > bad_ll.
|
| 10 |
+
- ARC-Easy: ai2_arc/ARC-Easy/test, zero-shot, candidate = question+" "+choice,
|
| 11 |
+
score = LL(q+choice) - LL(q), RAW acc (nie acc_norm).
|
| 12 |
+
- WikiText-2: wikitext-2-raw-v1/test, " ".join(rows).strip(),
|
| 13 |
+
non-overlapping 256-token chunks, context-RESET per chunk,
|
| 14 |
+
ppl = exp(total_NLL / n_token_predictions) <-- TOKEN-PPL (nasz tokenizer),
|
| 15 |
+
NIE BPB. To jest board-input dla WikiScore.
|
| 16 |
+
|
| 17 |
+
WIRING (Monter): wypelnij load_our_model() ponizej - import naszej GPT-klasy,
|
| 18 |
+
zaladuj ckpt, zwroc (model, logits_fn, tokenizer). logits_fn(input_ids_LongTensor[B,T])
|
| 19 |
+
MUSI zwrocic logits[B,T,vocab] (tylko realne vocab, bez padded-vocab).
|
| 20 |
+
Reszta = protokol Glint bez zmian. Odpal: python glint_parity_eval.py <ckpt> <tokenizer.json>
|
| 21 |
+
"""
|
| 22 |
+
import math, json, sys, time
|
| 23 |
+
import torch
|
| 24 |
+
import torch.nn.functional as F
|
| 25 |
+
import numpy as np
|
| 26 |
+
from datasets import load_dataset, concatenate_datasets
|
| 27 |
+
from tokenizers import Tokenizer as HFTokenizer
|
| 28 |
+
|
| 29 |
+
# ---------------------------------------------------------------------------
|
| 30 |
+
# GLINT EVAL-LOGIC (verbatim, model-agnostic: uzywa logits_fn + tokenizer)
|
| 31 |
+
# ---------------------------------------------------------------------------
|
| 32 |
+
def tokenize_many(tokenizer, texts, max_length=256):
|
| 33 |
+
all_ids = []
|
| 34 |
+
for text in texts:
|
| 35 |
+
ids = tokenizer.encode(text).ids
|
| 36 |
+
ids = [i for i in ids if i < tokenizer.get_vocab_size()]
|
| 37 |
+
if len(ids) > max_length:
|
| 38 |
+
ids = ids[:max_length]
|
| 39 |
+
all_ids.append(ids)
|
| 40 |
+
return all_ids
|
| 41 |
+
|
| 42 |
+
def batch_log_probs(logits_fn, tokenizer, texts, device, max_length=256, batch_size=128):
|
| 43 |
+
all_ids = tokenize_many(tokenizer, texts, max_length)
|
| 44 |
+
results = [-float("inf")] * len(all_ids)
|
| 45 |
+
with torch.inference_mode():
|
| 46 |
+
for start in range(0, len(all_ids), batch_size):
|
| 47 |
+
end = min(start + batch_size, len(all_ids))
|
| 48 |
+
batch = all_ids[start:end]
|
| 49 |
+
batch_indices = [j for j in range(start, end) if len(batch[j-start]) >= 2]
|
| 50 |
+
batch_seqs = [batch[j-start] for j in range(start, end) if len(batch[j-start]) >= 2]
|
| 51 |
+
if not batch_seqs:
|
| 52 |
+
continue
|
| 53 |
+
max_len = max(len(s) for s in batch_seqs)
|
| 54 |
+
B = len(batch_seqs)
|
| 55 |
+
padded_np = np.zeros((B, max_len - 1), dtype=np.int64)
|
| 56 |
+
targets_np = np.zeros((B, max_len - 1), dtype=np.int64)
|
| 57 |
+
mask_np = np.zeros((B, max_len - 1), dtype=bool)
|
| 58 |
+
for j, ids in enumerate(batch_seqs):
|
| 59 |
+
padded_np[j, :len(ids)-1] = ids[:-1]
|
| 60 |
+
targets_np[j, :len(ids)-1] = ids[1:]
|
| 61 |
+
mask_np[j, :len(ids)-1] = True
|
| 62 |
+
padded = torch.from_numpy(padded_np).to(device)
|
| 63 |
+
targets = torch.from_numpy(targets_np).to(device)
|
| 64 |
+
mask = torch.from_numpy(mask_np).to(device)
|
| 65 |
+
logits = logits_fn(padded)
|
| 66 |
+
log_probs = F.log_softmax(logits, dim=-1)
|
| 67 |
+
log_probs_flat = log_probs.view(-1, logits.size(-1))
|
| 68 |
+
targets_flat = targets.view(-1)
|
| 69 |
+
gathered = log_probs_flat[torch.arange(targets_flat.size(0), device=device), targets_flat]
|
| 70 |
+
gathered = gathered.view(B, -1)
|
| 71 |
+
gathered[~mask] = 0.0
|
| 72 |
+
sums = gathered.sum(dim=-1).tolist()
|
| 73 |
+
for bi, val in zip(batch_indices, sums):
|
| 74 |
+
results[bi] = val
|
| 75 |
+
return results
|
| 76 |
+
|
| 77 |
+
def compute_perplexity(logits_fn, tokenizer, text, device, max_length=256):
|
| 78 |
+
ids = tokenizer.encode(text).ids
|
| 79 |
+
ids = [i for i in ids if i < tokenizer.get_vocab_size()]
|
| 80 |
+
if len(ids) < 2:
|
| 81 |
+
return float("inf")
|
| 82 |
+
nll = 0.0; n_tokens = 0
|
| 83 |
+
for i in range(0, len(ids) - 1, max_length):
|
| 84 |
+
chunk = ids[i:i + max_length + 1]
|
| 85 |
+
if len(chunk) < 2:
|
| 86 |
+
continue
|
| 87 |
+
inputs = torch.tensor([chunk[:-1]], device=device)
|
| 88 |
+
targets = torch.tensor([chunk[1:]], device=device)
|
| 89 |
+
with torch.no_grad():
|
| 90 |
+
logits = logits_fn(inputs)
|
| 91 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), reduction="sum")
|
| 92 |
+
nll += loss.item(); n_tokens += targets.numel()
|
| 93 |
+
return math.exp(nll / n_tokens) if n_tokens > 0 else float("inf")
|
| 94 |
+
|
| 95 |
+
BLIMP_CONFIGS = [
|
| 96 |
+
"adjunct_island","anaphor_gender_agreement","anaphor_number_agreement","animate_subject_passive",
|
| 97 |
+
"animate_subject_trans","causative","complex_NP_island","coordinate_structure_constraint_complex_left_branch",
|
| 98 |
+
"coordinate_structure_constraint_object_extraction","determiner_noun_agreement_1","determiner_noun_agreement_2",
|
| 99 |
+
"determiner_noun_agreement_irregular_1","determiner_noun_agreement_irregular_2","determiner_noun_agreement_with_adj_2",
|
| 100 |
+
"determiner_noun_agreement_with_adj_irregular_1","determiner_noun_agreement_with_adj_irregular_2",
|
| 101 |
+
"determiner_noun_agreement_with_adjective_1","distractor_agreement_relational_noun",
|
| 102 |
+
"distractor_agreement_relative_clause","drop_argument","ellipsis_n_bar_1","ellipsis_n_bar_2",
|
| 103 |
+
"existential_there_object_raising","existential_there_quantifiers_1","existential_there_quantifiers_2",
|
| 104 |
+
"existential_there_subject_raising","expletive_it_object_raising","inchoative","intransitive",
|
| 105 |
+
"irregular_past_participle_adjectives","irregular_past_participle_verbs","irregular_plural_subject_verb_agreement_1",
|
| 106 |
+
"irregular_plural_subject_verb_agreement_2","left_branch_island_echo_question","left_branch_island_simple_question",
|
| 107 |
+
"matrix_question_npi_licensor_present","npi_present_1","npi_present_2","only_npi_licensor_present","only_npi_scope",
|
| 108 |
+
"passive_1","passive_2","principle_A_c_command","principle_A_case_1","principle_A_case_2","principle_A_domain_1",
|
| 109 |
+
"principle_A_domain_2","principle_A_domain_3","principle_A_reconstruction","regular_plural_subject_verb_agreement_1",
|
| 110 |
+
"regular_plural_subject_verb_agreement_2","sentential_negation_npi_licensor_present","sentential_negation_npi_scope",
|
| 111 |
+
"sentential_subject_island","superlative_quantifiers_1","superlative_quantifiers_2","tough_vs_raising_1",
|
| 112 |
+
"tough_vs_raising_2","transitive","wh_island","wh_questions_object_gap","wh_questions_subject_gap",
|
| 113 |
+
"wh_questions_subject_gap_long_distance","wh_vs_that_no_gap","wh_vs_that_no_gap_long_distance",
|
| 114 |
+
"wh_vs_that_with_gap","wh_vs_that_with_gap_long_distance",
|
| 115 |
+
]
|
| 116 |
+
|
| 117 |
+
def _tok_path():
|
| 118 |
+
import os
|
| 119 |
+
for p in ("/workspace/.cache/huggingface/token", os.path.expanduser("~/.cache/huggingface/token"),
|
| 120 |
+
"/mnt/c/Users/Maggio03/.cache/huggingface/token"):
|
| 121 |
+
if os.path.exists(p):
|
| 122 |
+
return open(p).read().strip()
|
| 123 |
+
return None
|
| 124 |
+
|
| 125 |
+
def _rows(repo, config, split):
|
| 126 |
+
"""Robust loader: pyarrow-parquet via hf_hub_download (omija datasets-5.x load_dataset URI-bug)."""
|
| 127 |
+
import os, pyarrow.parquet as pq
|
| 128 |
+
from huggingface_hub import hf_hub_download, list_repo_files
|
| 129 |
+
tk = _tok_path()
|
| 130 |
+
files = list_repo_files(repo, repo_type="dataset", token=tk)
|
| 131 |
+
def match(f):
|
| 132 |
+
if not f.endswith(".parquet"): return False
|
| 133 |
+
base = os.path.basename(f).lower()
|
| 134 |
+
if split not in base and ("/"+split+"/") not in ("/"+f.lower()): return False
|
| 135 |
+
if config is not None and config not in f: return False
|
| 136 |
+
return True
|
| 137 |
+
cands = [f for f in files if match(f)]
|
| 138 |
+
rows = []
|
| 139 |
+
for f in sorted(cands):
|
| 140 |
+
p = hf_hub_download(repo, f, repo_type="dataset", token=tk)
|
| 141 |
+
rows.extend(pq.read_table(p).to_pylist())
|
| 142 |
+
if not rows:
|
| 143 |
+
raise RuntimeError(f"_rows: brak parquet dla {repo} config={config} split={split}; kandydaci={cands[:5]}")
|
| 144 |
+
return rows
|
| 145 |
+
|
| 146 |
+
def evaluate_wikitext2(logits_fn, tokenizer, device):
|
| 147 |
+
rows = _rows("Salesforce/wikitext", "wikitext-2-raw-v1", "test")
|
| 148 |
+
text = " ".join(r["text"] for r in rows).strip()
|
| 149 |
+
ppl = compute_perplexity(logits_fn, tokenizer, text, device)
|
| 150 |
+
return {"wikitext2_ppl": round(ppl, 4)}
|
| 151 |
+
|
| 152 |
+
def evaluate_blimp(logits_fn, tokenizer, device):
|
| 153 |
+
import os
|
| 154 |
+
ds = []
|
| 155 |
+
for c in BLIMP_CONFIGS:
|
| 156 |
+
ds.extend(_rows("nyu-mll/blimp", c, "train"))
|
| 157 |
+
cap = os.environ.get("BLIMP_SAMPLE")
|
| 158 |
+
if cap: # opcjonalna próbka dla szybkości CPU (zaznaczyć w notatce)
|
| 159 |
+
import random; random.seed(1337); random.shuffle(ds); ds = ds[:int(cap)]
|
| 160 |
+
good = batch_log_probs(logits_fn, tokenizer, [e["sentence_good"] for e in ds], device)
|
| 161 |
+
bad = batch_log_probs(logits_fn, tokenizer, [e["sentence_bad"] for e in ds], device)
|
| 162 |
+
correct = sum(1 for g, b in zip(good, bad) if g > b)
|
| 163 |
+
return {"blimp_acc": round(correct/len(ds)*100, 2), "blimp_n": len(ds)}
|
| 164 |
+
|
| 165 |
+
def evaluate_arc_easy(logits_fn, tokenizer, device):
|
| 166 |
+
ds = _rows("allenai/ai2_arc", "ARC-Easy", "test")
|
| 167 |
+
correct = 0; total = 0
|
| 168 |
+
for ex in ds:
|
| 169 |
+
q = ex["question"]; ch = ex["choices"]
|
| 170 |
+
full = [q + " " + t for t in ch["text"]]
|
| 171 |
+
lps = batch_log_probs(logits_fn, tokenizer, full, device, batch_size=4)
|
| 172 |
+
lpq = batch_log_probs(logits_fn, tokenizer, [q], device)[0]
|
| 173 |
+
best = max(range(len(lps)), key=lambda j: lps[j] - lpq)
|
| 174 |
+
if ch["label"][best] == ex["answerKey"]:
|
| 175 |
+
correct += 1
|
| 176 |
+
total += 1
|
| 177 |
+
return {"arc_easy_acc": round(correct/total*100, 2), "arc_n": total}
|
| 178 |
+
|
| 179 |
+
# ---------------------------------------------------------------------------
|
| 180 |
+
# WIRING NASZEGO MODELU (Monter: wypelnij) -- to jedyna czesc nie-Glint.
|
| 181 |
+
# ---------------------------------------------------------------------------
|
| 182 |
+
def load_our_model(ckpt_path, tokenizer_path, device):
|
| 183 |
+
"""Zwroc (logits_fn, tokenizer). logits_fn(ids[B,T]) -> logits[B,T,REAL_VOCAB].
|
| 184 |
+
TODO Monter: zaimportuj nasza GPT-klase (z train-kodu gollem), zaladuj ckpt,
|
| 185 |
+
ustaw eval()+to(device). Nasz block=1024 > 256 chunki Glinta wiec forward OK.
|
| 186 |
+
Wazne: przytnij logits do realnego vocab (bez padded-vocab) jesli mamy padding.
|
| 187 |
+
Ponizej szkielet - dopasuj do naszej sygnatury forward()."""
|
| 188 |
+
import importlib.util, os
|
| 189 |
+
tokenizer = HFTokenizer.from_file(tokenizer_path) # BPE-12k tokenizer.json
|
| 190 |
+
# import naszej klasy GPT z train_gpt_ref.py (typowe lokalizacje: pod / lokalnie)
|
| 191 |
+
gpt_src = None
|
| 192 |
+
for cand in ("/workspace/gollem/corpus/scripts/train_gpt_ref.py",
|
| 193 |
+
os.path.join(os.path.dirname(os.path.abspath(__file__)), "train_gpt_ref.py"),
|
| 194 |
+
"/mnt/c/Projekty/Slayer/train-bdh-25m/train_gpt_ref.py"):
|
| 195 |
+
if os.path.exists(cand):
|
| 196 |
+
gpt_src = cand; break
|
| 197 |
+
if gpt_src is None:
|
| 198 |
+
raise FileNotFoundError("train_gpt_ref.py (klasa GPT) nie znaleziony")
|
| 199 |
+
spec = importlib.util.spec_from_file_location("tgr_glint", gpt_src)
|
| 200 |
+
tgr = importlib.util.module_from_spec(spec); spec.loader.exec_module(tgr)
|
| 201 |
+
GPT = tgr.GPT
|
| 202 |
+
ck = torch.load(ckpt_path, map_location="cpu", weights_only=False)
|
| 203 |
+
sd = ck["model"] if isinstance(ck, dict) and "model" in ck else ck
|
| 204 |
+
sd = {k.replace("_orig_mod.", ""): v for k, v in sd.items()} # strip torch.compile
|
| 205 |
+
vocab, n_embd = sd["tok.weight"].shape
|
| 206 |
+
block = sd["pos.weight"].shape[0]
|
| 207 |
+
n_layer = 1 + max(int(k.split(".")[1]) for k in sd if k.startswith("blocks."))
|
| 208 |
+
n_head = int(os.environ.get("N_HEAD", "6")) # nie w wagach; 16M-scan=6, 32M=9
|
| 209 |
+
model = GPT(int(vocab), int(n_layer), int(n_embd), int(n_head), int(block))
|
| 210 |
+
model.load_state_dict(sd, strict=True)
|
| 211 |
+
model.eval().to(device)
|
| 212 |
+
print(f"[load_our_model] vocab={vocab} L={n_layer} d={n_embd} h={n_head} block={block} dev={device}", flush=True)
|
| 213 |
+
def logits_fn(ids):
|
| 214 |
+
out = model(ids)
|
| 215 |
+
logits = out[0] if isinstance(out, (tuple, list)) else out
|
| 216 |
+
return logits[..., :tokenizer.get_vocab_size()]
|
| 217 |
+
return logits_fn, tokenizer
|
| 218 |
+
|
| 219 |
+
def main():
|
| 220 |
+
ckpt = sys.argv[1] if len(sys.argv) > 1 else "run_bpe16m_10b_e/ckpt.pt"
|
| 221 |
+
tok = sys.argv[2] if len(sys.argv) > 2 else "tokenizer.json"
|
| 222 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 223 |
+
logits_fn, tokenizer = load_our_model(ckpt, tok, device)
|
| 224 |
+
results = {}
|
| 225 |
+
print("1/3 WikiText-2 (token-PPL)...", flush=True)
|
| 226 |
+
results.update(evaluate_wikitext2(logits_fn, tokenizer, device))
|
| 227 |
+
print("2/3 BLiMP...", flush=True)
|
| 228 |
+
results.update(evaluate_blimp(logits_fn, tokenizer, device))
|
| 229 |
+
print("3/3 ARC-Easy...", flush=True)
|
| 230 |
+
results.update(evaluate_arc_easy(logits_fn, tokenizer, device))
|
| 231 |
+
print("GLINT-PROTOCOL RESULTS:", json.dumps(results, indent=2))
|
| 232 |
+
with open("glint_parity_results.json", "w") as f:
|
| 233 |
+
json.dump(results, f, indent=2)
|
| 234 |
+
|
| 235 |
+
if __name__ == "__main__":
|
| 236 |
+
main()
|