Download src/macjev/v4data/classa_hellaswag_train.py from VTN-TokenFactory/Telasap-0.8B-v1.0: direct link, hf CLI and curl.
- Browser
- Download file 27.8 kB
-
https://huggingface.co/VTN-TokenFactory/Telasap-0.8B-v1.0/resolve/main/src/macjev/v4data/classa_hellaswag_train.py
- Command line
-
hf download hf://VTN-TokenFactory/Telasap-0.8B-v1.0/src/macjev/v4data/classa_hellaswag_train.py
-
curl -L -o classa_hellaswag_train.py https://huggingface.co/VTN-TokenFactory/Telasap-0.8B-v1.0/resolve/main/src/macjev/v4data/classa_hellaswag_train.py
27.8 kB
| """Class A ingest: HellaSwag TRAIN -> 4-option continuation choice (component di_language, source labels). | |
| Contract: V4_DATA_CONTRACT_2026-09-25.md (§0 U1, §2 class A, §3 fields, §4.1 forbidden splits, §6 di_language | |
| "HellaSwag train", §7 splits). Output: ``data/synth-v4/classA/hellaswag_train/{train,dev}.jsonl`` + | |
| ``manifest.json``. Nothing here enters a pool; the DI gate (T11) runs later over these files. | |
| Source. ``Rowan/hellaswag`` on the HF Hub, main @ 218ec52e (parquet ``data/train-00000-of-00001.parquet`` only). | |
| The validation split is the scored test split of the target benchmark and the test split is unlabelled: neither | |
| file is ever downloaded or read. Licence: MIT (HF card "Licensing Information: MIT | |
| https://github.com/rowanz/hellaswag/blob/master/LICENSE"; LICENSE text "Copyright (c) 2019 Rowan Zellers" read from | |
| the Wayback snapshot 2025-08-28 because the GitHub repository has been access-blocked since 2026-09-14). | |
| WikiHow-sourced rows are excluded. The upstream GitHub repository was disabled by a DMCA notice from wikiHow, | |
| Inc. (github/dmca 2026/09/2026-09-14-wikihow.md) naming it as an unauthorised copy of wikiHow articles, and | |
| wikiHow's own content licence is non-commercial. Only ``source_id`` ``activitynet~*`` rows (ActivityNet Captions | |
| video descriptions) are used; the wikiHow rows are counted under ``drops`` as ``excluded_wikihow_dmca``. | |
| Rows. One ``choice`` question per source row: the context (``ctx`` = ``ctx_a`` + unfinished ``ctx_b``) and the four | |
| original endings as options A–D in a seeded per-row order; gold = the source ``label`` ending. Instructions come | |
| from this module's own paraphrase pools (24 for state rows, 22 for self-contained rows). About 38 % of rows are | |
| self-contained (``state = {}``, context written into the question); the rest use one of three JSON state layouts | |
| whose field names are defined here. About 18 % of rows carry ``meta.translate_zh = true`` (to be translated later | |
| by the translation pass; nothing is machine-translated here, ``lang`` stays ``en``). | |
| Clusters and splits. ``group_id`` = the ActivityNet video (``source_id``); consecutive rows of one video share | |
| context, so a video's rows never straddle splits. At most 2 rows per video are kept (diversity). ~7 % of the | |
| selected videos form the dev slice (``split = dev``, ``meta.dev_pool = "DIS"``), drawn from TRAIN only. | |
| Identical inputs are deduplicated; rows with repeated/empty/punctuation-only endings or an invalid label are dropped; rows whose | |
| context or an ending matches a ``data/master-v3/exclusions`` hash are dropped. | |
| Run: ``PYTHONPATH=src:. python -m macjev.v4data.classa_hellaswag_train [--no-token-check] [--no-exclusions]``. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import collections | |
| import hashlib | |
| import json | |
| import random | |
| import re | |
| import statistics | |
| from pathlib import Path | |
| from typing import Any, Callable | |
| from ..paths import DATA_V3, ROOT | |
| from ..schema import TRAINABLE_LICENSE_PREFIXES, content_hash, make_record, normalise_text | |
| from . import rowspec | |
| BUILDER_VERSION = "classa_hellaswag_train-v1" | |
| MODULE = "macjev.v4data.classa_hellaswag_train" | |
| NAME = "hellaswag_train" | |
| FAMILY = "hellaswag_train" | |
| COMPONENT = "di_language" | |
| CATEGORY = "v4A_continuation_choice" | |
| SEED = 20260925 | |
| OUT_DIR = ROOT / "data" / "synth-v4" / "classA" / NAME | |
| SOURCE_DIR = OUT_DIR / "_source" # raw pinned train parquet (not a row file) | |
| EXCLUSIONS = DATA_V3 / "exclusions" | |
| TOKENIZER_DIR = ROOT / "models" / "bases" / "Qwen--Qwen3.5-2B" / "15852e8c16360a2fea060d615a32b45270f8a8fc" | |
| REPO = "Rowan/hellaswag" | |
| REVISION = "218ec52e09a7e7462a5400043bb9a69a41d06b76" | |
| TRAIN_FILE = "data/train-00000-of-00001.parquet" | |
| TRAIN_SHA256 = "cacb12587faa63d7f723a72d61d12bfa94b140446f5a6a0a2e1c6906ab88bf02" | |
| LICENSE = "mit" | |
| BENCHMARK_NAME = "HellaSwag" | |
| FORBIDDEN_SPLITS = { | |
| "validation": "never read (scored test split of the target benchmark; file never downloaded)", | |
| "test": "never read (unlabelled; file never downloaded)", | |
| } | |
| LICENSE_EVIDENCE = { | |
| "hf_card": "Rowan/hellaswag README.md @ " + REVISION + ": 'Licensing Information: MIT " | |
| "https://github.com/rowanz/hellaswag/blob/master/LICENSE' (no cardData.license field)", | |
| "license_text": "MIT License, 'Copyright (c) 2019 Rowan Zellers' -- read from " | |
| "http://web.archive.org/web/20250828143311/https://github.com/rowanz/hellaswag/blob/master/LICENSE " | |
| "(snapshot sha256 of the gzip body 5647cc73b4d217dc73a5929f386f1fab0f4a7c841f9e524c7091a7f4199c2234)", | |
| "github_status": "api.github.com/repos/rowanz/hellaswag returns 'Repository access blocked' (reason dmca, " | |
| "2026-09-14, github/dmca 2026/09/2026-09-14-wikihow.md: wikiHow, Inc. claims the repo hosts " | |
| "unauthorised copies of wikiHow articles)", | |
| "consequence": "wikiHow-sourced rows (source_id wikihow~*) are excluded; only ActivityNet-caption rows are used", | |
| "gated": False, | |
| "spdx": "MIT", | |
| "attribution": "HellaSwag (Zellers et al., ACL 2019), MIT licence, Copyright (c) 2019 Rowan Zellers", | |
| } | |
| ALLOWED_SOURCE_PREFIX = "activitynet~" | |
| TRAIN_TARGET = 15_000 # v4 10-25: x5 (HellaSwag gap) | |
| DEV_FRACTION = 0.07 | |
| MAX_ROWS_PER_VIDEO = 2 | |
| STATE_EMPTY_SHARE = 0.38 | |
| TRANSLATE_ZH_SHARE = 0.18 | |
| LETTERS = ("A", "B", "C", "D") | |
| # --------------------------------------------------------------------------------------------- | |
| # Instruction pools (written for this module; field names are ours) | |
| # --------------------------------------------------------------------------------------------- | |
| STATE_INS = [ | |
| "The description of a video clip stops mid-sentence. Which ending continues it most plausibly?", | |
| "Read the unfinished description and pick the continuation that most sensibly comes next.", | |
| "Which of the four endings is the most natural way for this scene description to go on?", | |
| "The narration breaks off. Choose the option that a careful writer would most likely have written next.", | |
| "Pick the continuation that fits the scene: consistent with what has happened and physically sensible.", | |
| "Complete the unfinished sentence. Which ending makes the whole passage coherent?", | |
| "Of these candidate endings, which one best follows the text about the activity?", | |
| "Several endings were proposed for this clip description; only one is the real continuation. Which?", | |
| "Which option describes what most plausibly happens next in the clip?", | |
| "Choose the ending that keeps the people, objects and actions of the passage consistent.", | |
| "The last sentence of the description is incomplete. Select the most likely completion.", | |
| "Using common sense about the activity, which continuation is most believable?", | |
| "Decide which ending a human would judge as the natural next part of this description.", | |
| "Which continuation best matches both the topic of the clip and the half-finished sentence?", | |
| "Select the ending that flows grammatically and logically from the passage.", | |
| "Given the scene so far, what is the most sensible way to finish the description?", | |
| "One ending is the genuine continuation of this video caption; the others are implausible. Pick it.", | |
| "Which of the endings would you expect to read next in this account of the activity?", | |
| "Find the continuation that is coherent with the earlier sentences and the activity being shown.", | |
| "The caption was cut off. Which option completes it in the most plausible way?", | |
| "Pick the most reasonable next event for the scene described.", | |
| "Which option is the best continuation, taking into account what the people are doing?", | |
| "Choose the ending that does not contradict the passage and describes a likely next step.", | |
| "What comes next? Select the continuation that fits the described activity best.", | |
| ] | |
| INLINE_INS = [ | |
| "Activity: {activity}\nText: {ctx}\n\nThe text stops mid-sentence. Which ending continues it most plausibly?", | |
| "Here is an unfinished description of a video about \"{activity}\":\n\n{ctx} ...\n\nWhich option is the most " | |
| "natural continuation?", | |
| "Finish the description sensibly.\n\n{ctx}", | |
| "Topic: {activity}\n\"{ctx} ...\"\nChoose the ending that best completes the passage.", | |
| "A clip caption was cut off:\n{ctx}\nWhich of the endings is the real continuation?", | |
| "{ctx} ...\n\nWhat most plausibly comes next in this scene?", | |
| "Read the passage about {activity_lc} and pick the continuation that makes the most sense.\n\nPassage: {ctx}", | |
| "Complete the unfinished sentence at the end of this text:\n\n{ctx}", | |
| "Scene ({activity}): {ctx}\n\nWhich option describes what happens next?", | |
| "The following narration breaks off before the sentence ends.\n\n{ctx}\n\nSelect the most sensible ending.", | |
| "Using common sense, choose how this description of a video continues:\n{ctx}", | |
| "Video subject: {activity}.\nDescription so far: {ctx}\nWhich ending would a careful writer have used?", | |
| "Which continuation keeps this passage coherent?\n\n\"{ctx}\"", | |
| "{ctx}\n\nThe passage above is incomplete. Pick the ending that fits it best.", | |
| "Pick the next part of this caption about {activity_lc}:\n{ctx}", | |
| "Only one of the endings is a believable continuation of the text below. Which one?\n\n{ctx}", | |
| "Description of someone doing \"{activity}\", cut short:\n{ctx}\nChoose the likely continuation.", | |
| "What is the most reasonable way to finish this?\n\n{ctx}", | |
| "Context: {ctx}\n\nSelect the ending that is consistent with the people, objects and actions described.", | |
| "An account of a clip ({activity}) stops here: \"{ctx}\". Which option completes it?", | |
| "Continue the text in the most plausible way.\nText: {ctx}", | |
| "Given the scene below, which next event is most likely?\n\n{ctx}", | |
| ] | |
| STATE_LAYOUTS = ("activity_text", "narration_split", "caption_only") | |
| # --------------------------------------------------------------------------------------------- | |
| # Licence, download, loading | |
| # --------------------------------------------------------------------------------------------- | |
| class LicenseRefused(ValueError): | |
| pass | |
| def license_gate(license_: str) -> str: | |
| lic = str(license_ or "").strip().lower() | |
| refused = ("-nc", "nc-", "noncommercial", "-nd", "nd-", "research", "unknown", "unclear", "other") | |
| if not lic or not lic.startswith(TRAINABLE_LICENSE_PREFIXES) or any(m in lic for m in refused): | |
| raise LicenseRefused(f"licence {license_!r} is not trainable") | |
| return lic | |
| def sha256_file(path: Path) -> str: | |
| h = hashlib.sha256() | |
| with Path(path).open("rb") as f: | |
| for chunk in iter(lambda: f.read(1 << 20), b""): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def verify_repo() -> dict: | |
| """Anonymous HF API check at the pinned revision: not gated, revision exists, only train file is fetched.""" | |
| from huggingface_hub import HfApi | |
| info = HfApi().dataset_info(REPO, revision=REVISION, token=False, files_metadata=True) | |
| if info.sha != REVISION: | |
| raise RuntimeError(f"revision mismatch {info.sha} != {REVISION}") | |
| if info.gated: | |
| raise LicenseRefused(f"{REPO} is gated") | |
| sizes = {s.rfilename: s.size for s in info.siblings} | |
| if sizes.get(TRAIN_FILE, 0) > 400 * 1024 * 1024: | |
| raise RuntimeError("train file exceeds the 400 MB per-source cap") | |
| license_gate(LICENSE) | |
| return {"revision": info.sha, "gated": bool(info.gated), "train_bytes": sizes.get(TRAIN_FILE)} | |
| def download() -> Path: | |
| """Fetch ONLY the train parquet at the pinned revision into this module's own _source dir.""" | |
| from huggingface_hub import hf_hub_download | |
| if "validation" in TRAIN_FILE or "test" in TRAIN_FILE: | |
| raise RuntimeError("only the train file may be fetched") | |
| path = Path(hf_hub_download(REPO, TRAIN_FILE, repo_type="dataset", revision=REVISION, token=False, | |
| local_dir=str(SOURCE_DIR))) | |
| if sha256_file(path) != TRAIN_SHA256: | |
| raise RuntimeError(f"sha256 mismatch for {REPO}/{TRAIN_FILE}") | |
| return path | |
| def _clean(text: Any) -> str: | |
| return " ".join(str(text or "").split()) | |
| def load_train(path: Path) -> list[dict]: | |
| import pyarrow.parquet as pq | |
| rows = [] | |
| for i, r in enumerate(pq.read_table(path).to_pylist()): | |
| rows.append({"line": i, "ind": int(r["ind"]), "activity_label": _clean(r["activity_label"]), | |
| "ctx_a": _clean(r["ctx_a"]), "ctx_b": _clean(r["ctx_b"]), "ctx": _clean(r["ctx"]), | |
| "endings": [_clean(e) for e in (r["endings"] or [])], "source_id": str(r["source_id"]), | |
| "split": str(r["split"]), "split_type": str(r["split_type"]), "label": str(r["label"])}) | |
| return rows | |
| # --------------------------------------------------------------------------------------------- | |
| # Helpers | |
| # --------------------------------------------------------------------------------------------- | |
| def _h(*parts: Any) -> int: | |
| return int.from_bytes(hashlib.sha256("\x1f".join(map(str, parts)).encode()).digest()[:8], "big") | |
| def _u(*parts: Any) -> float: | |
| return _h(*parts) / 2 ** 64 | |
| def row_rng(*parts: Any) -> random.Random: | |
| return random.Random(_h(SEED, *parts)) | |
| def group_of(row: dict) -> str: | |
| return "hellaswag_video:" + hashlib.sha256(row["source_id"].encode()).hexdigest()[:16] | |
| def context_text(row: dict) -> str: | |
| ctx = row["ctx"] or _clean(f"{row['ctx_a']} {row['ctx_b']}") | |
| return ctx | |
| def input_key(row: dict) -> str: | |
| return content_hash([context_text(row), sorted(normalise_text(e) for e in row["endings"])]) | |
| # --------------------------------------------------------------------------------------------- | |
| # Rendering | |
| # --------------------------------------------------------------------------------------------- | |
| def render_state(row: dict, layout: str) -> dict: | |
| if layout == "activity_text": | |
| return {"activity": row["activity_label"], "text_so_far": context_text(row)} | |
| if layout == "narration_split": | |
| return {"scene_topic": row["activity_label"], "narration": row["ctx_a"], | |
| "unfinished_sentence": row["ctx_b"]} | |
| if layout == "caption_only": | |
| return {"clip_caption_so_far": context_text(row)} | |
| raise ValueError(layout) | |
| def render_record(row: dict, split: str, dev_pool: str | None) -> dict: | |
| key = f"{row['source_id']}#{row['ind']}" | |
| rng = row_rng("row", key) | |
| gold_src = int(row["label"]) | |
| order = list(range(4)) | |
| rng.shuffle(order) | |
| crit = {LETTERS[i]: row["endings"][src] for i, src in enumerate(order)} | |
| gold_letter = LETTERS[order.index(gold_src)] | |
| empty = _u(SEED, "state_empty", key) < STATE_EMPTY_SHARE | |
| if empty: | |
| tmpl_i = rng.randrange(len(INLINE_INS)) | |
| ins = INLINE_INS[tmpl_i].format(activity=row["activity_label"], activity_lc=row["activity_label"].lower(), | |
| ctx=context_text(row)) | |
| state: dict = {} | |
| layout = "inline" | |
| ins_id = f"inline_{tmpl_i:02d}" | |
| else: | |
| tmpl_i = rng.randrange(len(STATE_INS)) | |
| ins = STATE_INS[tmpl_i] | |
| layout = STATE_LAYOUTS[rng.randrange(len(STATE_LAYOUTS))] | |
| state = render_state(row, layout) | |
| ins_id = f"state_{tmpl_i:02d}" | |
| translate = _u(SEED, "translate_zh", key) < TRANSLATE_ZH_SHARE | |
| rec = make_record( | |
| id=f"v4A_{NAME}/{split}/{row['ind']}", group_id=group_of(row), split=split, source=REPO, category=CATEGORY, | |
| lang="en", license=LICENSE, state=state, question={"t": "choice", "ins": ins, "crit": crit}, | |
| valid=[gold_letter], | |
| provenance={"dataset": REPO, "revision": REVISION, "file": TRAIN_FILE, "line": row["line"], | |
| "ind": row["ind"], "source_id": row["source_id"], "source_split": "train"}, | |
| meta={"builder": BUILDER_VERSION, "source_split": "train", "source_label": gold_src, | |
| "gold_position": LETTERS.index(gold_letter), "option_source_order": order, | |
| "activity_label": row["activity_label"], "layout": layout, "ins_id": ins_id, | |
| "translate_zh": translate, "dev_pool": dev_pool, "source_subset": "activitynet"}) | |
| return rowspec.enrich(rec, data_class="A", component=COMPONENT, family=FAMILY, label_method="source_label", | |
| teacher=[], generator={"name": BUILDER_VERSION, "version": "1", "seed": SEED}, | |
| twin_id=None, di=[benchmark_id()], jevbench=None, overlap="in_domain_train") | |
| _DI_ID: int | None = None | |
| def benchmark_id() -> int: | |
| global _DI_ID | |
| if _DI_ID is None: | |
| _DI_ID = int(rowspec.di_ids()[BENCHMARK_NAME]) | |
| return _DI_ID | |
| # --------------------------------------------------------------------------------------------- | |
| # Build | |
| # --------------------------------------------------------------------------------------------- | |
| def row_problem(row: dict) -> str | None: | |
| if row["split"] != "train": | |
| return "not_train_split" | |
| if not row["source_id"].startswith(ALLOWED_SOURCE_PREFIX): | |
| return "excluded_wikihow_dmca" if row["source_id"].startswith("wikihow") else "excluded_other_source" | |
| if len(row["endings"]) != 4 or any(not e for e in row["endings"]): | |
| return "bad_endings" | |
| if len({normalise_text(e) for e in row["endings"]}) != 4: | |
| return "repeated_ending" | |
| if any(not re.search(r"[A-Za-z0-9]", e) for e in row["endings"]): | |
| return "degenerate_ending" | |
| if row["label"] not in ("0", "1", "2", "3"): | |
| return "bad_label" | |
| if not context_text(row) or not row["activity_label"]: | |
| return "empty_context" | |
| return None | |
| def build(rows: list[dict], *, excluded: Callable[[dict], bool] | None = None, | |
| train_target: int = TRAIN_TARGET, dev_fraction: float = DEV_FRACTION) -> dict: | |
| dropped: collections.Counter = collections.Counter() | |
| ok = [] | |
| for r in rows: | |
| p = row_problem(r) | |
| if p: | |
| dropped[p] += 1 | |
| elif excluded is not None and excluded(r): | |
| dropped["matches_eval_exclusion_hash"] += 1 | |
| else: | |
| ok.append(r) | |
| # identical inputs: keep one (the first by line); conflicting labels -> drop all copies | |
| by_key: dict[str, list[dict]] = collections.defaultdict(list) | |
| for r in ok: | |
| by_key[input_key(r)].append(r) | |
| uniq = [] | |
| for k in sorted(by_key, key=lambda k: min(r["line"] for r in by_key[k])): | |
| grp = sorted(by_key[k], key=lambda r: r["line"]) | |
| gold_texts = {normalise_text(r["endings"][int(r["label"])]) for r in grp} | |
| if len(gold_texts) > 1: | |
| dropped["conflicting_labels_same_input"] += len(grp) | |
| continue | |
| dropped["duplicate_input"] += len(grp) - 1 | |
| uniq.append(grp[0]) | |
| if not dropped["duplicate_input"]: | |
| del dropped["duplicate_input"] | |
| # clusters = videos; at most MAX_ROWS_PER_VIDEO rows each (seeded pick, kept in source order) | |
| videos: dict[str, list[dict]] = collections.defaultdict(list) | |
| for r in uniq: | |
| videos[group_of(r)].append(r) | |
| for g, rs in videos.items(): | |
| if len(rs) > MAX_ROWS_PER_VIDEO: | |
| keep = sorted(rs, key=lambda r: _h(SEED, "pick", r["source_id"], r["ind"]))[:MAX_ROWS_PER_VIDEO] | |
| dropped["over_rows_per_video_cap"] += len(rs) - len(keep) | |
| videos[g] = sorted(keep, key=lambda r: r["line"]) | |
| order = sorted(videos, key=lambda g: (_h(SEED, "video", g), g)) | |
| train_g, dev_g = [], [] | |
| n_train = n_dev = 0 | |
| dev_target = max(1, round(train_target * dev_fraction / (1 - dev_fraction))) if dev_fraction > 0 else 0 | |
| for g in order: | |
| is_dev = _u(SEED, "dev", g) < dev_fraction | |
| if is_dev and n_dev < dev_target: | |
| dev_g.append(g) | |
| n_dev += len(videos[g]) | |
| elif not is_dev and n_train < train_target: | |
| train_g.append(g) | |
| n_train += len(videos[g]) | |
| if n_train >= train_target and n_dev >= dev_target: | |
| break | |
| selected = set(train_g) | set(dev_g) | |
| dropped["not_selected_sample_cap"] += sum(len(v) for g, v in videos.items() if g not in selected) | |
| train = [render_record(r, "train", None) for g in train_g for r in videos[g]] | |
| dev = [render_record(r, "dev", "DIS") for g in dev_g for r in videos[g]] | |
| bad = collections.Counter() | |
| out = {} | |
| for name, recs in (("train", train), ("dev", dev)): | |
| good = [] | |
| for rec in recs: | |
| errs = rowspec.validate_v4(rec) | |
| if errs: | |
| bad[f"{name}:validate_v4:{errs[0][:40]}"] += 1 | |
| else: | |
| good.append(rec) | |
| out[name] = sorted(good, key=lambda r: (_h(SEED, "order", r["id"]), r["id"])) | |
| dropped.update(bad) | |
| assert not ({r["group_id"] for r in out["train"]} & {r["group_id"] for r in out["dev"]}) | |
| return {"train": out["train"], "dev": out["dev"], "dropped": dropped} | |
| # --------------------------------------------------------------------------------------------- | |
| # Exclusions, tokens, manifest | |
| # --------------------------------------------------------------------------------------------- | |
| def load_exclusion_hashes() -> set[str]: | |
| hashes: set[str] = set() | |
| for path in sorted(EXCLUSIONS.glob("*.jsonl")): | |
| with path.open() as f: | |
| for line in f: | |
| i = line.find('"hash": "') | |
| if i >= 0: | |
| hashes.add(line[i + 9:i + 73]) | |
| return hashes | |
| def exclusion_checker(hashes: set[str]) -> Callable[[dict], bool]: | |
| def excluded(r: dict) -> bool: | |
| texts = [context_text(r), r["ctx_a"]] + [e for e in r["endings"] if len(e.split()) >= 6] | |
| return any(t and content_hash(t) in hashes for t in texts) | |
| return excluded | |
| def prompt_text(rec: dict) -> str: | |
| q = rec["question"] | |
| crit = "\n".join(f"{k}: {v}" for k, v in q["crit"].items()) | |
| st = "" if rec["meta"]["state_empty"] else json.dumps(rec["state"], ensure_ascii=False) + "\n" | |
| return f"{st}{q['ins']}\n{crit}" | |
| def _stats(xs: list[int]) -> dict: | |
| if not xs: | |
| return {} | |
| s = sorted(xs) | |
| return {"n": len(s), "mean": round(statistics.fmean(s), 1), "p50": s[len(s) // 2], | |
| "p95": s[min(len(s) - 1, int(0.95 * len(s)))], "max": s[-1], "total": sum(s)} | |
| def token_stats(splits: dict[str, list[dict]], tok) -> dict: | |
| out = {} | |
| for split, recs in splits.items(): | |
| prompts = [prompt_text(r) for r in recs] | |
| pt = [len(x) for x in tok(prompts, add_special_tokens=False)["input_ids"]] if recs else [] | |
| out[split] = {"prompt_tokens": _stats(pt)} | |
| return out | |
| def summary(recs: list[dict]) -> dict: | |
| c = collections.Counter | |
| n = len(recs) | |
| return {"rows": n, "groups": len({r["group_id"] for r in recs}), | |
| "by_qtype": dict(c(r["question"]["t"] for r in recs)), "by_lang": dict(c(r["lang"] for r in recs)), | |
| "state_empty": sum(r["meta"]["state_empty"] for r in recs), | |
| "state_empty_share": round(sum(r["meta"]["state_empty"] for r in recs) / max(1, n), 4), | |
| "translate_zh": sum(r["meta"]["translate_zh"] for r in recs), | |
| "translate_zh_share": round(sum(r["meta"]["translate_zh"] for r in recs) / max(1, n), 4), | |
| "by_layout": dict(sorted(c(r["meta"]["layout"] for r in recs).items())), | |
| "gold_position": dict(sorted(c(r["meta"]["gold_position"] for r in recs).items())), | |
| "source_label": dict(sorted(c(r["meta"]["source_label"] for r in recs).items())), | |
| "activity_labels": len({r["meta"]["activity_label"] for r in recs}), | |
| "instruction_ids_used": len({r["meta"]["ins_id"] for r in recs})} | |
| def build_manifest(res: dict, *, file_sha: str, file_bytes: int, n_source_rows: int, out_sha: dict, | |
| tok_stats: dict | None, exclusions_used: bool, repo_check: dict | None) -> dict: | |
| return { | |
| "builder": BUILDER_VERSION, "module": MODULE, "seed": SEED, "name": NAME, "family": FAMILY, | |
| "component": COMPONENT, "data_class": "A", "category": CATEGORY, | |
| "repo": REPO, "revision": REVISION, "repo_check": repo_check, | |
| "license": LICENSE, "license_evidence": LICENSE_EVIDENCE, | |
| "source_files": {"train": {"path": TRAIN_FILE, "sha256": file_sha, "bytes": file_bytes, | |
| "rows": n_source_rows, | |
| "local_copy": str((SOURCE_DIR / TRAIN_FILE).relative_to(ROOT))}}, | |
| "splits_used": {"train": "HellaSwag train (activitynet~* rows only)", | |
| "dev": f"held-out HellaSwag TRAIN videos (~{int(DEV_FRACTION * 100)}% of selected " | |
| "clusters), meta.dev_pool = DIS"}, | |
| "forbidden_splits": FORBIDDEN_SPLITS, | |
| "class_A_benchmark": {"id": benchmark_id(), "name": BENCHMARK_NAME}, | |
| "label_method": "source_label", | |
| "label_prior": {"gold_position": "uniform over A-D by a seeded per-row shuffle of the four source endings", | |
| "source": "generator shuffle (this module); source label distribution is the natural " | |
| "HellaSwag train distribution"}, | |
| "decontamination": { | |
| "exclusions": ("content_hash of ctx / ctx_a / endings (>=6 words) vs data/master-v3/exclusions/*.jsonl" | |
| if exclusions_used else None), | |
| "di_gate": "pending (T11 runs later; rows carry meta.gate = null)", | |
| "never_read": ["validation", "test"]}, | |
| "grouping": "group_id = ActivityNet video (source_id); <= %d rows per video" % MAX_ROWS_PER_VIDEO, | |
| "instruction_pools": {"state": len(STATE_INS), "inline": len(INLINE_INS)}, | |
| "state_layouts": list(STATE_LAYOUTS) + ["inline (state = {})"], | |
| "translate_zh": "rows with meta.translate_zh = true are to be translated by the later translation pass; " | |
| "nothing is machine-translated here", | |
| "teacher_jobs": [], | |
| "outputs": {s: {"file": f"{s}.jsonl", "sha256": out_sha[s], **summary(res[s])} for s in ("train", "dev")}, | |
| "token_stats": ({"tokenizer": str(TOKENIZER_DIR.relative_to(ROOT)), **tok_stats} if tok_stats else None), | |
| "drops": dict(sorted(res["dropped"].items())), | |
| } | |
| def write_jsonl(path: Path, recs: list[dict]) -> str: | |
| rowspec.write_jsonl(path, recs) | |
| return sha256_file(path) | |
| def main(argv: list[str] | None = None) -> dict: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--no-token-check", action="store_true") | |
| ap.add_argument("--no-exclusions", action="store_true") | |
| ap.add_argument("--train-target", type=int, default=TRAIN_TARGET) | |
| args = ap.parse_args(argv) | |
| repo_check = verify_repo() | |
| path = download() | |
| rows = load_train(path) | |
| excluded = None if args.no_exclusions else exclusion_checker(load_exclusion_hashes()) | |
| res = build(rows, excluded=excluded, train_target=args.train_target) | |
| out_sha = {s: write_jsonl(OUT_DIR / f"{s}.jsonl", res[s]) for s in ("train", "dev")} | |
| tok_stats = None | |
| if not args.no_token_check: | |
| from transformers import AutoTokenizer | |
| tok = AutoTokenizer.from_pretrained(str(TOKENIZER_DIR)) | |
| tok_stats = token_stats({s: res[s] for s in ("train", "dev")}, tok) | |
| manifest = build_manifest(res, file_sha=sha256_file(path), file_bytes=path.stat().st_size, | |
| n_source_rows=len(rows), out_sha=out_sha, tok_stats=tok_stats, | |
| exclusions_used=not args.no_exclusions, repo_check=repo_check) | |
| errs = rowspec.validate_manifest_v4(manifest, data_class="A") | |
| if errs: | |
| raise RuntimeError(f"manifest invalid: {errs}") | |
| (OUT_DIR / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n") | |
| return manifest | |
| if __name__ == "__main__": | |
| m = main() | |
| print(json.dumps({k: m[k] for k in ("outputs", "token_stats", "drops")}, indent=2, ensure_ascii=False)) | |