laghu-evals / join_items.py
jiteshkprasad's picture
Stage Laghu release data (private) (part 3)
4854535 verified
Raw History Blame Contribute Delete
8.77 kB
"""Re-attach benchmark item text to the Laghu evaluation release from pinned public dataset revisions, and check it.
python join_items.py DATASET_DIR --out OUT_DIR [--what math500,base] [--models laghu-base,smollm2-135m] [--cache DIR]
The release ships some benchmarks as ids and scores only, because their text may not be re-published by us (MATH-500,
HellaSwag, PIQA) or would change the dataset's licence (ARC is CC-BY-SA-4.0), or to keep one rule for every
multiple-choice benchmark (MMLU, WinoGrande). This script puts the text back on your machine:
- math500: downloads HuggingFaceH4/MATH-500 `test.jsonl` at a pinned revision, rebuilds
`chat_suite/prompts/math500_l123.jsonl` (id, problem, gold, level, subject; levels 1-3, in dataset order) and checks
its sha256 against `chat_suite/prompts/ITEMS.json`. It then fills every ⟦MATH500#k⟧ marker (a model's verbatim copy
of MATH-500 problem text, removed from the release; `math500_spans[k]` says which problem, which words and which
whitespace) in `chat_suite/generations/*/*/*.jsonl.gz` and in the GSM8K outputs of `base_suite/*/gsm8k.jsonl.gz`, and
checks each restored output against its `raw_sha256` / `resps_sha256`.
- base: for every `base_suite/<model>/<task>.jsonl.gz` and `long_context/gate_base_suite/<model>/<task>.jsonl.gz`, adds
`doc`, the document exactly as lm-eval 0.4.13 saw it, and checks lm-eval's own `doc_hash` on every row.
Writes only under OUT_DIR (same relative paths). Needs: huggingface_hub, pyarrow. Each source keeps its own licence.
"""
import argparse
import collections
import glob
import gzip
import hashlib
import json
import os
import re
import sys
PINS = {
"math500": ("HuggingFaceH4/MATH-500", "6e4ed1a2a79af7d8630a6b768ec859cb5af4d3be", "test.jsonl"),
"arc_easy": ("allenai/ai2_arc", "210d026faf9955653af8916fad021475a3f00453", "ARC-Easy/test-00000-of-00001.parquet"),
"arc_challenge": ("allenai/ai2_arc", "210d026faf9955653af8916fad021475a3f00453", "ARC-Challenge/test-00000-of-00001.parquet"),
"arc_easy_val": ("allenai/ai2_arc", "210d026faf9955653af8916fad021475a3f00453", "ARC-Easy/validation-00000-of-00001.parquet"),
"arc_challenge_val": ("allenai/ai2_arc", "210d026faf9955653af8916fad021475a3f00453", "ARC-Challenge/validation-00000-of-00001.parquet"),
"hellaswag": ("Rowan/hellaswag", "218ec52e09a7e7462a5400043bb9a69a41d06b76", "data/validation-00000-of-00001.parquet"),
"piqa": ("baber/piqa", "142f6d7367fd9877f0fb3b5734ea6a545f54cdd1", "piqa_validation.parquet"),
"winogrande": ("allenai/winogrande", "01e74176c63542e6b0bcb004dcdea22d94fb67b5", "winogrande_xl/validation-00000-of-00001.parquet"),
"mmlu": ("cais/mmlu", "c30699e8356da336a370243923dbaf21066bb9fe", "{subject}/test-00000-of-00001.parquet"),
}
MARK = re.compile("\u27e6MATH500#(\\d+)\u27e7")
def fetch(key, cache, subject=None):
from huggingface_hub import hf_hub_download
repo, rev, path = PINS[key]
return hf_hub_download(repo, path.format(subject=subject), repo_type="dataset", revision=rev, cache_dir=cache)
def read_parquet(p):
import pyarrow.parquet as pq
return pq.read_table(p).to_pylist()
def rjsonl(path):
op = gzip.open if path.endswith(".gz") else open
with op(path, "rt", encoding="utf-8") as f:
return [json.loads(l) for l in f]
def wjsonl(path, rows):
os.makedirs(os.path.dirname(path), exist_ok=True)
op = gzip.open if path.endswith(".gz") else open
with op(path, "wt", encoding="utf-8") as f:
for r in rows:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
def sha(s):
return hashlib.sha256(s.encode("utf-8")).hexdigest()
# lm-eval 0.4.13 tasks/hellaswag/utils.py
def hs_preprocess(text):
text = text.strip()
text = text.replace(" [title]", ". ")
text = re.sub("\\[.*?\\]", "", text)
text = text.replace(" ", " ")
return text
def hs_doc(doc):
ctx = doc["ctx_a"] + " " + doc["ctx_b"].capitalize()
return dict(doc, query=hs_preprocess(doc["activity_label"] + ": " + ctx),
choices=[hs_preprocess(e) for e in doc["endings"]], gold=int(doc["label"]))
def join_math(ds, out, cache):
rows = [json.loads(l) for l in open(fetch("math500", cache), encoding="utf-8")]
items = [dict(id=r["unique_id"], problem=r["problem"], gold=r["answer"], level=int(r["level"]), subject=r["subject"])
for r in rows if int(r["level"]) <= 3]
ids = [r["id"] for r in rjsonl(os.path.join(ds, "chat_suite", "prompts", "math500_l123_ids.jsonl"))]
assert [r["id"] for r in items] == ids, "MATH-500 ids differ from the release"
p = os.path.join(out, "chat_suite", "prompts", "math500_l123.jsonl")
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "w", encoding="utf-8") as f:
for r in items:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
want = json.load(open(os.path.join(ds, "chat_suite", "prompts", "ITEMS.json")))["math"]["sha256"]
got = hashlib.sha256(open(p, "rb").read()).hexdigest()
print(f"math500: {len(items)} items; sha256 {'matches' if got == want else 'DIFFERS from'} ITEMS.json")
words = [r["problem"].split() for r in items]
def fill(text, spans):
def one(m):
s = spans[int(m.group(1))]
if "a" in s:
return items[s["item"]]["problem"][s["a"]:s["b"]]
w = words[s["item"]][s["w"]:s["w"] + s["n"]]
seps = s["seps"] or [" "] * (len(w) - 1)
return w[0] + "".join(a + b for a, b in zip(seps, w[1:]))
return MARK.sub(one, text)
n_rows = n_spans = bad = 0
files = sorted(glob.glob(os.path.join(ds, "chat_suite", "generations", "*", "*", "*.jsonl.gz")) +
glob.glob(os.path.join(ds, "base_suite", "*", "gsm8k.jsonl.gz")))
for f in files:
rows, changed = [], False
for r in rjsonl(f):
if r.get("math500_spans"):
changed = True
n_rows += 1
n_spans += len(r["math500_spans"])
if "raw" in r:
r["raw"] = fill(r["raw"], r["math500_spans"])
bad += sha(r["raw"]) != r.pop("raw_sha256")
else:
r["resps"][0][0] = fill(r["resps"][0][0], r["math500_spans"])
bad += sha(r["resps"][0][0]) != r.pop("resps_sha256")
del r["math500_spans"]
rows.append(r)
if changed:
wjsonl(os.path.join(out, os.path.relpath(f, ds)), rows)
print(f"math500: {n_rows} outputs with spans, {n_spans} spans restored, {bad} outputs failing their sha256")
return got == want and bad == 0
def join_base(ds, out, cache, models):
docs = {}
def get(task):
if task in docs:
return docs[task]
if task.startswith("mmlu_"):
subject = task[5:].removesuffix("_continuation")
docs[task] = read_parquet(fetch("mmlu", cache, subject))
elif task == "hellaswag":
docs[task] = [hs_doc(d) for d in read_parquet(fetch("hellaswag", cache))]
else:
docs[task] = read_parquet(fetch(task, cache))
return docs[task]
files = sorted(glob.glob(os.path.join(ds, "base_suite", "*", "*.jsonl.gz")) +
glob.glob(os.path.join(ds, "long_context", "gate_base_suite", "*", "*.jsonl.gz")))
ok = True
for f in files:
model = os.path.basename(os.path.dirname(f))
if models and model not in models:
continue
if f.endswith("gsm8k.jsonl.gz"): # GSM8K ships with its text
continue
rows, c = [], collections.Counter()
for r in rjsonl(f):
doc = get(r["task"])[r["doc_id"]]
same = sha(json.dumps(doc, indent=2, ensure_ascii=False)) == r["doc_hash"]
c["match" if same else "mismatch"] += 1
rows.append(dict(r, doc=doc))
wjsonl(os.path.join(out, os.path.relpath(f, ds)), rows)
ok &= c["mismatch"] == 0
print(f"{os.path.relpath(f, ds)}: {c['match']} rows, doc_hash matches; {c['mismatch']} mismatches")
return ok
def main():
ap = argparse.ArgumentParser()
ap.add_argument("dataset_dir")
ap.add_argument("--out", required=True)
ap.add_argument("--what", default="math500,base")
ap.add_argument("--models", default="")
ap.add_argument("--cache", default=None, help="Hugging Face download cache (default: the usual HF cache)")
a = ap.parse_args()
ok = True
if "math500" in a.what:
ok &= join_math(a.dataset_dir, a.out, a.cache)
if "base" in a.what:
ok &= join_base(a.dataset_dir, a.out, a.cache, set(filter(None, a.models.split(","))))
sys.exit(0 if ok else 1)
if __name__ == "__main__":
main()