Datasets:
Download scripts/bench.py from Cross-Mergeability/crossarch-accuracy: direct link, hf CLI and curl.
- Browser
- Download file 6.64 kB
-
https://huggingface.co/datasets/Cross-Mergeability/crossarch-accuracy/resolve/main/scripts/bench.py
- Command line
-
hf download hf://datasets/Cross-Mergeability/crossarch-accuracy/scripts/bench.py
-
curl -L -o bench.py https://huggingface.co/datasets/Cross-Mergeability/crossarch-accuracy/resolve/main/scripts/bench.py
6.64 kB
| """Direct loglikelihood benchmark scorers (lm-eval-harness compatible formats). | |
| Every task is scored the way lm-eval-harness scores it: for each document we build one | |
| (context, continuation) request per answer option, take the summed token loglikelihood of the | |
| continuation under teacher forcing, and pick the argmax. Two aggregations are reported: | |
| acc -- argmax of raw summed loglikelihood | |
| acc_norm -- argmax of loglikelihood divided by continuation length in *characters* | |
| LAMBADA is scored as exact-match of the greedy continuation (harness `acc`). | |
| Chance level is recorded per task so a number can never be read without it. | |
| """ | |
| import os, json, math, re | |
| import torch | |
| from datasets import load_dataset | |
| DATA_CACHE = {} | |
| # --------------------------------------------------------------------------- task builders | |
| def _arc_easy(limit=None): | |
| d = load_dataset("allenai/ai2_arc", "ARC-Easy", split="test") | |
| docs = [] | |
| for x in d: | |
| labels = list(x["choices"]["label"]); texts = list(x["choices"]["text"]) | |
| if x["answerKey"] not in labels: continue | |
| docs.append(dict(ctx=f"Question: {x['question']}\nAnswer:", | |
| conts=[" " + t for t in texts], | |
| gold=labels.index(x["answerKey"]))) | |
| return docs[:limit], 0.25 # 4-way (a handful are 3/5-way; chance reported nominally) | |
| def _sciq(limit=None): | |
| d = load_dataset("allenai/sciq", split="test") | |
| docs = [] | |
| for x in d: | |
| sup = x["support"].strip() | |
| ctx = (sup + "\n" if sup else "") + f"Question: {x['question']}\nAnswer:" | |
| conts = [x["distractor1"], x["distractor2"], x["distractor3"], x["correct_answer"]] | |
| docs.append(dict(ctx=ctx, conts=[" " + c for c in conts], gold=3)) | |
| return docs[:limit], 0.25 | |
| def _piqa(limit=None): | |
| try: | |
| d = load_dataset("ybisk/piqa", split="validation", revision="refs/convert/parquet") | |
| except Exception: | |
| d = load_dataset("baber/piqa", split="validation") | |
| docs = [] | |
| for x in d: | |
| docs.append(dict(ctx=f"Question: {x['goal']}\nAnswer:", | |
| conts=[" " + x["sol1"], " " + x["sol2"]], gold=int(x["label"]))) | |
| return docs[:limit], 0.5 | |
| def _lambada(limit=None): | |
| d = load_dataset("EleutherAI/lambada_openai", "en", split="test") | |
| docs = [] | |
| for x in d: | |
| t = x["text"] | |
| i = t.rfind(" ") | |
| docs.append(dict(ctx=t[:i], conts=[t[i:]], gold=0, exact=True)) | |
| return docs[:limit], 0.0 | |
| def _belebele(lang): | |
| def f(limit=None): | |
| d = load_dataset("facebook/belebele", lang, split="test") | |
| docs = [] | |
| for x in d: | |
| ctx = (f"P: {x['flores_passage']}\nQ: {x['question'].strip()}\n" | |
| f"A: {x['mc_answer1']}\nB: {x['mc_answer2']}\n" | |
| f"C: {x['mc_answer3']}\nD: {x['mc_answer4']}\nAnswer:") | |
| docs.append(dict(ctx=ctx, conts=[" A", " B", " C", " D"], | |
| gold=int(x["correct_answer_num"]) - 1)) | |
| return docs[:limit], 0.25 | |
| return f | |
| TASKS = { | |
| "arc_easy": dict(build=_arc_easy, chance=0.25, lang="en", limit=None), | |
| "sciq": dict(build=_sciq, chance=0.25, lang="en", limit=None), | |
| "piqa": dict(build=_piqa, chance=0.50, lang="en", limit=None), | |
| "lambada": dict(build=_lambada, chance=0.0, lang="en", limit=2000), | |
| "belebele_en": dict(build=_belebele("eng_Latn"), chance=0.25, lang="en", limit=None), | |
| "belebele_zh": dict(build=_belebele("zho_Hans"), chance=0.25, lang="zh", limit=None), | |
| } | |
| EN_CORE = ["arc_easy", "sciq", "piqa", "lambada"] | |
| def get_docs(task): | |
| if task not in DATA_CACHE: | |
| b = TASKS[task] | |
| DATA_CACHE[task] = b["build"](b["limit"])[0] | |
| return DATA_CACHE[task] | |
| # --------------------------------------------------------------------------- scoring | |
| def score_task(model, tok, task, device, batch_size=16, max_len=1024, token_budget=4096): | |
| """Score one task. Batches are built to a fixed TOKEN budget rather than a fixed row | |
| count, so the peak logit tensor is bounded regardless of context length -- these GPUs are | |
| shared with another agent's jobs and a fixed row count OOMs on the long-context tasks.""" | |
| docs = get_docs(task) | |
| reqs = [] # (doc_idx, cont_idx, ctx, cont) | |
| for di, d in enumerate(docs): | |
| for ci, c in enumerate(d["conts"]): | |
| reqs.append((di, ci, d["ctx"], c)) | |
| enc = [] | |
| for di, ci, ctx, cont in reqs: | |
| a = tok(ctx, add_special_tokens=False)["input_ids"] | |
| b = tok(cont, add_special_tokens=False)["input_ids"] | |
| if len(b) == 0: b = [tok.eos_token_id] | |
| ids = (a + b)[-max_len:] | |
| nb = min(len(b), len(ids) - 1) | |
| enc.append((di, ci, ids, nb, len(cont))) | |
| enc.sort(key=lambda e: -len(e[2])) | |
| pad = tok.pad_token_id if tok.pad_token_id is not None else 0 | |
| out = {} | |
| i = 0 | |
| while i < len(enc): | |
| L = len(enc[i][2]) | |
| bs = max(1, min(batch_size, token_budget // max(L, 1))) | |
| chunk = enc[i:i + bs]; i += len(chunk) | |
| L = max(len(e[2]) for e in chunk) | |
| ids = torch.full((len(chunk), L), pad, dtype=torch.long) | |
| am = torch.zeros((len(chunk), L), dtype=torch.long) | |
| for r, e in enumerate(chunk): | |
| n = len(e[2]); ids[r, L - n:] = torch.tensor(e[2]); am[r, L - n:] = 1 # left pad | |
| ids = ids.to(device); am = am.to(device) | |
| lg = model(input_ids=ids, attention_mask=am).logits[:, :-1] | |
| tgt = ids[:, 1:] | |
| greedy = lg.argmax(-1) | |
| lgf = lg.float() | |
| lp = lgf.gather(-1, tgt[..., None])[..., 0] - torch.logsumexp(lgf, dim=-1) | |
| del lgf, lg | |
| for r, e in enumerate(chunk): | |
| nb = e[3] | |
| s_lp = float(lp[r, -nb:].sum()) | |
| ok = bool((greedy[r, -nb:] == tgt[r, -nb:]).all()) | |
| out[(e[0], e[1])] = (s_lp, e[4], ok) | |
| del lp, greedy | |
| # aggregate | |
| n = len(docs); c_acc = c_norm = 0 | |
| for di, d in enumerate(docs): | |
| if d.get("exact"): | |
| c_acc += out[(di, 0)][2]; c_norm += out[(di, 0)][2]; continue | |
| scores = [out[(di, ci)][0] for ci in range(len(d["conts"]))] | |
| norms = [out[(di, ci)][0] / max(out[(di, ci)][1], 1) for ci in range(len(d["conts"]))] | |
| c_acc += int(max(range(len(scores)), key=lambda i: scores[i]) == d["gold"]) | |
| c_norm += int(max(range(len(norms)), key=lambda i: norms[i]) == d["gold"]) | |
| acc, accn = c_acc / n, c_norm / n | |
| se = math.sqrt(max(acc * (1 - acc), 1e-12) / n) | |
| return dict(task=task, n=n, acc=acc, acc_norm=accn, acc_stderr=se, | |
| chance=TASKS[task]["chance"]) | |