"""Screen D4's rendered splits, count state tokens, write the dataset files and stats, and push them to the public hub repo ChrisMcCormick/encoder-rtx-d4-records. The screen is the phase1 session's screen.py (Kev's overlap rule against every evaluation partition in holdouts.json), with Cookbook-dev's labelled records added as a partition, so no D4 record overlaps a Cookbook-dev 10-K (whose filers fetch_d4.py already left out by CIK). python build_d4.py [--push] Reads /rendered/.jsonl (render_d4.py); writes /data/.jsonl, /stats.json and /screen_report.json, and pushes them with README.md (HF_README.md). """ import json import multiprocessing as mp import os import sys from collections import Counter, defaultdict from pathlib import Path import numpy as np from huggingface_hub import HfApi, hf_hub_download from tokenizers import Tokenizer import screen as S REPO = "ChrisMcCormick/encoder-rtx-d4-records" WORK = Path(os.environ.get("D4_WORK", "/content/d4")) HERE = Path(__file__).parent COOKBOOK_REPO, COOKBOOK_REV = "ChrisMcCormick/encoder-rtx-cookbook-dev", "406c2af0245737cd29c83f0d941be63156ba5990" TOKENIZER_REPO, TOKENIZER_REV = "ChrisMcCormick/climbmix_unigram16k_14_170", "a42ad58143e636b2ed7ee60f661ad7fdf1df5bf7" SPLITS = ("train", "dev", "holdout") screen = None # built in main, inherited by the forked workers def check(r): return screen.check(r) def pct(xs, p): return int(np.percentile(xs, p)) if xs else 0 def stats(records, tokens): by = defaultdict(lambda: dict(records=0, questions=0, kinds=Counter(), options=defaultdict(list), layouts=Counter(), regimes=Counter(), tokens=[], nouls=defaultdict(lambda: [0, 0]))) for r, n_tok in zip(records, tokens): m = r["_meta"] s = by[m["source"]] s["records"] += 1 s["questions"] += len(r["questions"]) s["layouts"][m["layout"]] += 1 s["tokens"].append(n_tok) for name, q in r["questions"].items(): ph = m["phrasing"][name] kind = ph["key"].split(":")[0] s["kinds"][kind] += 1 if q["type"] == "choice": s["options"][kind].append(len(q["criteria"])) s["regimes"][f"{kind}:{ph['options']}"] += 1 else: s["nouls"][ph["key"]][0 if q["label"] else 1] += 1 out = {} for src, s in sorted(by.items()): t = s["tokens"] out[src] = dict(records=s["records"], questions=s["questions"], question_kinds=dict(s["kinds"]), options_per_choice={k: dict(p50=pct(v, 50), max=max(v)) for k, v in s["options"].items()}, option_sets=dict(sorted(s["regimes"].items())), layouts=dict(s["layouts"]), state_tokens=dict(p50=pct(t, 50), p90=pct(t, 90), max=max(t), over_2048=sum(x > 2048 for x in t), over_8192=sum(x > 8192 for x in t)), noul_true_false_per_template=dict(sorted((k, v) for k, v in s["nouls"].items()))) return out def main(push: bool): global screen rendered = {s: [json.loads(l) for l in (WORK / "rendered" / f"{s}.jsonl").open(encoding="utf-8")] for s in SPLITS} print({s: len(v) for s, v in rendered.items()}, flush=True) cookbook = [json.loads(l) for l in Path(hf_hub_download(COOKBOOK_REPO, "data/cookbook_dev.jsonl", repo_type="dataset", revision=COOKBOOK_REV, local_dir=WORK / "cookbook")).open(encoding="utf-8")] screen = S.Screen(holdouts_path=HERE / "holdouts.json", extra_partitions={"cookbook/dev": cookbook}) print(f"index: {screen.n_items:,} reference items ({screen.n_distinct:,} distinct), {len(screen.h):,} grams", flush=True) tok = Tokenizer.from_file(hf_hub_download(TOKENIZER_REPO, "tokenizer/tokenizer.json", repo_type="dataset", revision=TOKENIZER_REV, local_dir=WORK / "tokenizer")) kept, reports, summary = {}, {}, {} with mp.get_context("fork").Pool(os.cpu_count()) as pool: for split in SPLITS: recs = rendered[split] verdicts = pool.map(check, recs, chunksize=64) kept[split] = [r for r, v in zip(recs, verdicts) if not v] reports[split] = S.summarise(recs, verdicts) dropped = [{**r, "_screen": v} for r, v in zip(recs, verdicts) if v] with (WORK / f"{split}.dropped.jsonl").open("w", encoding="utf-8") as f: for r in dropped: f.write(json.dumps(r, ensure_ascii=False) + "\n") print(f"[{split}] screen dropped {reports[split]['dropped']:,} of {len(recs):,}: {reports[split]['by_reason']} " f"{reports[split]['by_partition']}", flush=True) for split in SPLITS: texts = [" ".join(S.strings(r["state"])) for r in kept[split]] tokens = [len(e.ids) for e in tok.encode_batch(texts)] summary[split] = stats(kept[split], tokens) print(f"[{split}]", json.dumps({k: (v["records"], v["questions"], v["state_tokens"]) for k, v in summary[split].items()}), flush=True) (WORK / "data").mkdir(exist_ok=True) for split in SPLITS: with (WORK / "data" / f"{split}.jsonl").open("w", encoding="utf-8") as f: for r in kept[split]: f.write(json.dumps(r, ensure_ascii=False) + "\n") (WORK / "stats.json").write_text(json.dumps(summary, indent=1) + "\n", encoding="utf-8") (WORK / "screen_report.json").write_text(json.dumps(reports, indent=1) + "\n", encoding="utf-8") if push: api = HfApi() (WORK / "README.md").write_text((HERE / "HF_README.md").read_text(encoding="utf-8"), encoding="utf-8") for name in ("render_d4.py", "build_d4.py", "fetch_d4.py"): if (HERE / name).exists(): (WORK / "code").mkdir(exist_ok=True) (WORK / "code" / name).write_bytes((HERE / name).read_bytes()) counts = " / ".join(f"{s} {len(kept[s]):,}" for s in SPLITS) info = api.upload_folder(repo_id=REPO, repo_type="dataset", folder_path=str(WORK), allow_patterns=["data/*.jsonl", "README.md", "stats.json", "screen_report.json", "code/*.py"], commit_message=f"D4 records: {counts}") print(f"pushed {REPO}@{info.oid}", flush=True) print("ALL DONE", flush=True) if __name__ == "__main__": main("--push" in sys.argv)