Download src/macjev/data_gates.py from VTN-TokenFactory/Telasap-0.8B-v1.0: direct link, hf CLI and curl.
- Browser
- Download file 30.8 kB
-
https://huggingface.co/VTN-TokenFactory/Telasap-0.8B-v1.0/resolve/main/src/macjev/data_gates.py
- Command line
-
hf download hf://VTN-TokenFactory/Telasap-0.8B-v1.0/src/macjev/data_gates.py
-
curl -L -o data_gates.py https://huggingface.co/VTN-TokenFactory/Telasap-0.8B-v1.0/resolve/main/src/macjev/data_gates.py
30.8 kB
| """Data gates for the assembled pool. Both gates fail loudly (non-zero exit, ``pass: false``). | |
| PYTHONPATH=src python -m macjev.data_gates [--pool data/master-v3/pool] [--raw data/master-v3/raw] | |
| [--config configs/macjev/quotas.json] [--gates g1,g2] | |
| G1 integrity — recomputed from the raw files, the ledger and the pool, not trusted from the report: | |
| pool file sha256 vs manifests; raw/exclusion/config files unchanged since assembly; every exclusion-like | |
| file under data/master-v3 + data/eval-v3 read or explicitly ignored; 100% raw line | |
| coverage (every raw line exactly once in the ledger, kept == pooled, identical membership across | |
| tokenizers); no raw errors (strict); schema + licence of every pooled row; pooled fields agree | |
| with the raw record; no exclusion hash (per-suite policy) and no component/builder losing > 5% to | |
| exclusions without an allowlisted reason; group/state/near-state/rare-long-string isolation across | |
| train/dev/cal/test; no exact/near duplicates; ablation sources present; no question-only label | |
| shortcut (state-skeleton shortcuts are warnings); zero silent truncation (every row within budget, | |
| budget drops carry a reason, pieces equal a fresh tokenisation on a sample). | |
| G2 rendering — every pooled row assembles for both readouts with the stored token counts; | |
| permutation invariants for choice rows (length, header, prefix, slot -> option mapping); | |
| score/noul refuse permutation; slot integrity; head budget rule; no control/added-token ids | |
| anywhere in the pooled ids; a control-token escaping probe per tokenizer. | |
| Reports: ``<pool>/gates/g1.json`` and ``g2.json``. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import random | |
| import sys | |
| import time | |
| from collections import Counter, defaultdict | |
| from pathlib import Path | |
| import numpy as np | |
| from . import pool as poolmod | |
| from .assemble import (DEFAULT_CONFIG, RAW_ERROR_REASONS, exact_key, head_max_for, is_nc, load_config, max_len_for, | |
| render_budgets, | |
| load_exclusions, load_tokenizer, exclusion_decision, exclusion_drop_gate, exclusion_file_audit, | |
| exclusion_policies, near_key, raw_files, scan_raw, component_map) | |
| from .paths import POOL_V3, RAW_V3 | |
| from .schema import TRAINABLE_LICENSE_PREFIXES, option_names | |
| MAX_EXAMPLES = 20 | |
| def _log(*a): | |
| print(*a, flush=True) | |
| class Checks: | |
| def __init__(self): | |
| self.items: list[dict] = [] | |
| def add(self, name: str, ok: bool, **detail): | |
| self.items.append({"check": name, "pass": bool(ok), **detail}) | |
| return ok | |
| def ok(self) -> bool: | |
| return all(c["pass"] for c in self.items) | |
| def report(self, gate: str, extra: dict | None = None) -> dict: | |
| return {"gate": gate, "pass": self.ok, "failed": [c["check"] for c in self.items if not c["pass"]], | |
| "checks": self.items, **(extra or {})} | |
| def _read_rows_meta(tok_dir: Path, split: str) -> list[dict]: | |
| with open(tok_dir / poolmod.split_files(split)[1], encoding="utf-8") as f: | |
| return [json.loads(line) for line in f] | |
| def _skeleton(x) -> str: | |
| if isinstance(x, dict): | |
| return "{" + ",".join(f"{k}:{_skeleton(v)}" for k, v in sorted(x.items())) + "}" | |
| if isinstance(x, list): | |
| return "[" + (_skeleton(x[0]) if x else "") + "]" | |
| return type(x).__name__[:1] | |
| def shortcut_audit(train: list[dict], dev: list[dict], cfg: dict) -> dict: | |
| """Round-1 failure mode: labels predictable from the template instead of the content. | |
| Per (category, source) with enough dev rows, fit a majority label on train keyed by | |
| (a) the option set only (the legitimate label prior), (b) + question text, (c) + the state's key skeleton, | |
| and score dev. ``question_gain`` = (b) - (a) must stay below ``max_question_only_gain`` (FAIL otherwise, unless | |
| allowlisted); ``skeleton_gain`` = (c) - (a) above ``warn_skeleton_gain`` is reported as a warning.""" | |
| sc = cfg.get("shortcut_audit", {}) | |
| min_dev, max_q, warn_s = int(sc.get("min_dev_rows", 100)), float(sc.get("max_question_only_gain", 0.10)), \ | |
| float(sc.get("warn_skeleton_gain", 0.15)) | |
| allow = sc.get("allowlist", {}) | |
| def fam(r): | |
| q = r["question"] | |
| return q["t"], (tuple(q["crit"]) if q["t"] == "choice" else len(q["crit"]) if q["t"] == "score" else 2) | |
| def lab(r): | |
| return tuple(sorted(r["label"]["valid"])) | |
| keys = {"prior": fam, "question": lambda r: (fam(r), r["question"]["ins"]), | |
| "skeleton": lambda r: (fam(r), _skeleton(r["state"]))} | |
| by = defaultdict(lambda: ([], [])) | |
| for i, rows in enumerate((train, dev)): | |
| for r in rows: | |
| by[f"{r['category']}|{r['source']}"][i].append(r) | |
| table, failing, warnings = {}, [], [] | |
| for name, (tr, dv) in sorted(by.items()): | |
| if len(dv) < min_dev or not tr: | |
| continue | |
| acc = {} | |
| for kname, fn in keys.items(): | |
| tab, prior = defaultdict(Counter), defaultdict(Counter) | |
| for r in tr: | |
| tab[fn(r)][lab(r)] += 1 | |
| prior[fam(r)][lab(r)] += 1 | |
| hit = 0 | |
| for r in dv: | |
| c = tab.get(fn(r)) or prior.get(fam(r)) | |
| hit += bool(c) and c.most_common(1)[0][0] == lab(r) | |
| acc[kname] = hit / len(dv) | |
| qg, sg = acc["question"] - acc["prior"], acc["skeleton"] - acc["prior"] | |
| table[name] = {"dev_rows": len(dv), **{k: round(v, 4) for k, v in acc.items()}, | |
| "question_gain": round(qg, 4), "skeleton_gain": round(sg, 4)} | |
| if qg > max_q: | |
| (warnings.append(f"{name}: question-only gain {qg:.3f} allowlisted ({allow[name]})") if name in allow | |
| else failing.append(name)) | |
| if sg > warn_s: | |
| warnings.append(f"{name}: state-skeleton-only baseline {acc['skeleton']:.3f} vs option-set prior " | |
| f"{acc['prior']:.3f} on dev (+{sg:.3f}); structure alone predicts many labels") | |
| return {"pass": not failing, "failing": failing, "warnings": warnings, "by": table, | |
| "max_question_only_gain": max_q, "warn_skeleton_gain": warn_s, "min_dev_rows": min_dev} | |
| # ============================================================================================= | |
| # G1 | |
| def gate_g1(pool_dir: Path, raw_dir: Path, cfg_path: Path, allow_raw_errors: bool = False, | |
| sample: int = 400, log=_log) -> dict: | |
| t0 = time.time() | |
| C = Checks() | |
| cfg = load_config(cfg_path) | |
| tags = list(cfg["tokenizers"]) | |
| report = json.loads((pool_dir / "assembly_report.json").read_text()) | |
| # 1. pool files vs manifests | |
| metas: dict[str, dict[str, list[dict]]] = {} | |
| bad_files, extra_files = [], [] | |
| for tag in tags: | |
| tok_dir = pool_dir / tag | |
| man = json.loads((tok_dir / "manifest.json").read_text()) | |
| for name, entry in man["files"].items(): | |
| p = tok_dir / name | |
| if not p.exists() or poolmod.sha256_file(p) != entry["sha256"] or p.stat().st_size != entry["bytes"]: | |
| bad_files.append(f"{tag}/{name}") | |
| listed = set(man["files"]) | {"manifest.json"} | |
| extra_files += [f"{tag}/{p.name}" for p in tok_dir.iterdir() if p.name not in listed] | |
| metas[tag] = {s: _read_rows_meta(tok_dir, s) for s in poolmod.POOLED_SPLITS} | |
| for s in poolmod.POOLED_SPLITS: | |
| if man["counts"][s] != len(metas[tag][s]): | |
| bad_files.append(f"{tag}/{s}: manifest count {man['counts'][s]} != rows {len(metas[tag][s])}") | |
| C.add("pool_files_match_manifest", not bad_files and not extra_files, bad=bad_files[:MAX_EXAMPLES], | |
| unlisted=extra_files[:MAX_EXAMPLES]) | |
| # 2. inputs unchanged since assembly | |
| files_now, ignored = raw_files(raw_dir) | |
| now = {f"{b}/{s}.jsonl": poolmod.sha256_file(p) for b, s, p in files_now} | |
| then = {k: v["sha256"] for k, v in report["raw"]["files"].items()} | |
| stale = sorted(k for k in set(now) | set(then) if now.get(k) != then.get(k)) | |
| excl, excl_info = load_exclusions(raw_dir.parent, cfg) | |
| stale_excl = sorted(k for k in set(excl_info) | set(report["exclusion_files"]) | |
| if excl_info.get(k, {}).get("sha256") != report["exclusion_files"].get(k, {}).get("sha256")) | |
| cfg_changed = poolmod.sha256_file(cfg_path) != report["config_sha256"] | |
| C.add("inputs_unchanged_since_assembly", not stale and not stale_excl and not cfg_changed, | |
| stale_raw_files=stale, stale_exclusion_files=stale_excl, config_changed=cfg_changed, | |
| hint="re-run python -m macjev.assemble" if (stale or stale_excl or cfg_changed) else None) | |
| C.add("nested_raw_files_listed", sorted(ignored) == sorted(report["raw"]["ignored_nested_jsonl"]), | |
| ignored_nested_jsonl=ignored, note="nested *.jsonl (pilots, candidates) are never pooled") | |
| audit = exclusion_file_audit(raw_dir.parent, cfg, excl_info) | |
| C.add("all_exclusion_files_consumed", not audit["unconsumed"], unconsumed=audit["unconsumed"], | |
| ignored=audit["ignored"], consumed=len(audit["consumed"]), | |
| hint="add a glob to assembly.extra_exclusion_globs (or a reasoned entry to assembly.ignored_exclusion_files)" | |
| if audit["unconsumed"] else None) | |
| # 3. coverage accounting | |
| rows, _ = scan_raw(raw_dir, cfg, component_map(cfg)) | |
| by_ref = {r.ref: r for r in rows} | |
| ledger = [json.loads(line) for line in open(pool_dir / "ledger.jsonl", encoding="utf-8")] | |
| ref_counts = Counter(e["ref"] for e in ledger) | |
| dup_refs = [k for k, v in ref_counts.items() if v != 1] | |
| missing = sorted(set(by_ref) - set(ref_counts)) | |
| unknown = sorted(set(ref_counts) - set(by_ref)) | |
| per_file = defaultdict(Counter) | |
| for e in ledger: | |
| per_file[f"{e['builder']}/{e['split']}.jsonl"][e["status"]] += 1 | |
| lines_ok = all(sum(per_file[k].values()) == v["lines"] for k, v in report["raw"]["files"].items()) | |
| status_ok = all(e["status"] in ("kept", "dropped", "sealed_test") and (e["status"] != "dropped" or e["reason"]) | |
| for e in ledger) | |
| test_pooled = [e["ref"] for e in ledger if e["split"] == "test" and e["status"] == "kept"] | |
| C.add("raw_coverage_100pct", not dup_refs and not missing and not unknown and lines_ok and status_ok | |
| and not test_pooled, raw_lines=len(rows), ledger_lines=len(ledger), duplicated=dup_refs[:MAX_EXAMPLES], | |
| missing=missing[:MAX_EXAMPLES], unknown=unknown[:MAX_EXAMPLES], test_rows_pooled=test_pooled[:MAX_EXAMPLES], | |
| statuses=dict(Counter(e["status"] if e["status"] != "dropped" else "dropped:" + e["reason"] | |
| for e in ledger))) | |
| kept_refs = {e["ref"] for e in ledger if e["status"] == "kept"} | |
| member_bad = [] | |
| for tag in tags: | |
| pooled = {m["raw_ref"] for s in poolmod.POOLED_SPLITS for m in metas[tag][s]} | |
| if pooled != kept_refs: | |
| member_bad.append({tag: {"kept_not_pooled": sorted(kept_refs - pooled)[:5], | |
| "pooled_not_kept": sorted(pooled - kept_refs)[:5]}}) | |
| order_same = all([m["raw_ref"] for m in metas[tags[0]][s]] == [m["raw_ref"] for m in metas[t][s]] | |
| for t in tags for s in poolmod.POOLED_SPLITS) | |
| C.add("kept_equals_pooled_all_tokenizers", not member_bad and order_same, mismatches=member_bad, | |
| identical_order=order_same) | |
| # 4. raw errors | |
| raw_err = Counter(e["reason"] for e in ledger if e["status"] == "dropped" and e["reason"] in RAW_ERROR_REASONS) | |
| strict = cfg["assembly"].get("strict_raw", True) and not allow_raw_errors | |
| C.add("no_raw_errors" if strict else "raw_errors_allowed", not raw_err or not strict, counts=dict(raw_err), | |
| examples=[e for e in ledger if e["reason"] in RAW_ERROR_REASONS][:MAX_EXAMPLES]) | |
| # 5. pooled rows vs raw record, schema, licence | |
| comp_of = component_map(cfg) | |
| field_bad, lic_bad = [], [] | |
| pooled_rows = [(m, by_ref.get(m["raw_ref"])) for s in poolmod.POOLED_SPLITS for m in metas[tags[0]][s]] | |
| for m, r in pooled_rows: | |
| if r is None or r.rec is None: | |
| field_bad.append({"id": m["id"], "why": "raw record missing or invalid now"}) | |
| continue | |
| rec = r.rec | |
| names = option_names(rec["question"]) | |
| soft = rec["label"].get("soft") | |
| expect = {"id": rec["id"], "group_id": rec["group_id"], "source": rec["source"], "category": rec["category"], | |
| "component": comp_of[rec["category"]], "lang": rec["lang"], "qtype": rec["question"]["t"], | |
| "names": names, "valid_idx": [names.index(v) for v in rec["label"]["valid"]], | |
| "soft": None if soft is None else [float(soft[n]) for n in names], "license": rec["license"], | |
| "split": rec["split"], "head_max": head_max_for(cfg, rec["category"], len(names)), | |
| "max_len": max_len_for(cfg, rec["category"])} | |
| diff = [k for k, v in expect.items() if m.get(k) != v] | |
| if diff: | |
| field_bad.append({"id": m["id"], "fields": diff}) | |
| lic = str(rec["license"]).lower() | |
| if is_nc(lic, cfg) or not lic.startswith(TRAINABLE_LICENSE_PREFIXES): | |
| lic_bad.append({"id": m["id"], "license": rec["license"]}) | |
| C.add("pooled_fields_match_raw", not field_bad, n=len(pooled_rows), bad=field_bad[:MAX_EXAMPLES]) | |
| lic_counts = Counter(m["license"] for m, _ in pooled_rows) | |
| C.add("licence_trainable_no_nc", not lic_bad, bad=lic_bad[:MAX_EXAMPLES], | |
| unclear_rows=sum(n for k, n in lic_counts.items() if k.lower().startswith("unclear")), | |
| by_license=dict(sorted(lic_counts.items()))) | |
| # 6. exclusions (per-suite policy) + per-component / per-builder drop-fraction limit | |
| ex_bad = [] | |
| kept_rows = [r for r in rows if r.ref in kept_refs and r.rec is not None] | |
| policies = exclusion_policies(cfg, excl_info) | |
| for r in kept_rows: | |
| enforced, _ = exclusion_decision(r.keys, excl, policies, cfg) | |
| if enforced: | |
| ex_bad.append({"id": r.id, "suites": enforced}) | |
| C.add("no_exclusion_hash_in_pool", not ex_bad, exclusion_hashes=len(excl), bad=ex_bad[:MAX_EXAMPLES], | |
| modes={fk: p["mode"] for fk, p in sorted(policies.items())}) | |
| gate = exclusion_drop_gate([(e.get("component"), e["builder"], e["split"], e["reason"]) for e in ledger | |
| if e["split"] != "test" and e["reason"] not in RAW_ERROR_REASONS | |
| and e.get("component") is not None], cfg) | |
| C.add("exclusion_drop_fraction_within_limit", gate["pass"], failing=gate["failing"], | |
| allowlisted=gate["allowlisted"], max_drop_fraction=gate["max_drop_fraction"], | |
| by={k: v for k, v in gate["by"].items() if v["excluded"]}, | |
| suites=report["exclusions"].get("dropped_rows_by_suite")) | |
| # 7. isolation (kept pooled rows + sealed test rows); rare-string fanout over all parsed rows as assembled | |
| cap = int(cfg["assembly"]["isolation_max_group_fanout"]) | |
| long_groups = defaultdict(set) | |
| for r in rows: | |
| if r.keys is not None and r.reason not in ("json_error", "duplicate_id", "duplicate_id_test"): | |
| for h in r.keys["long"]: | |
| long_groups[h].add(r.group) | |
| universe = kept_rows + [r for r in rows if r.split == "test" and r.keys is not None] | |
| for kind in ("group", "state", "near_state", "string"): | |
| where = defaultdict(set) | |
| for r in universe: | |
| keys = ([r.group] if kind == "group" else [r.keys[kind]] if kind in ("state", "near_state") | |
| else [h for h in r.keys["long"] if len(long_groups[h]) <= cap]) | |
| for k in keys: | |
| where[k].add(r.split) | |
| clash = [k for k, s in where.items() if len(s) > 1] | |
| C.add(f"isolation_{kind}", not clash, clashes=len(clash), | |
| examples=[{"key": k[:80], "splits": sorted(where[k])} for k in clash[:MAX_EXAMPLES]]) | |
| # 8. dedup | |
| dup = Counter() | |
| for split in cfg["assembly"]["dedup_splits"]: | |
| for fn, name in ((exact_key, "exact"), (near_key, "near")): | |
| keys = Counter(fn(r.rec["state"], r.rec["question"]) for r in kept_rows if r.split == split) | |
| dup[f"{split}:{name}"] = sum(v - 1 for v in keys.values() if v > 1) | |
| C.add("no_duplicates_within_split", not any(dup.values()), counts=dict(dup)) | |
| # 8b. ablations really remove their sources (a renamed source would silently make "heldout" a no-op) | |
| # A drop source may only be absent when its category is absent too (partial pools stay assemblable). | |
| train_sources = Counter(r.rec["source"] for r in kept_rows if r.split == "train") | |
| train_cats = Counter(r.rec["category"] for r in kept_rows if r.split == "train") | |
| missing_src, unmapped = {}, {} | |
| for name, a in cfg["ablations"].items(): | |
| cats = a.get("source_categories", {}) | |
| for src in a["drop_sources"]: | |
| if train_sources.get(src): | |
| continue | |
| if src not in cats: | |
| unmapped.setdefault(name, []).append(src) | |
| elif train_cats.get(cats[src]): | |
| missing_src.setdefault(name, []).append(f"{src} (category {cats[src]} has " | |
| f"{train_cats[cats[src]]} train rows under other sources)") | |
| C.add("ablation_sources_present", not missing_src and not unmapped, missing=missing_src, | |
| sources_without_category_mapping=unmapped, | |
| rows={name: {s: train_sources.get(s, 0) for s in a["drop_sources"]} for name, a in cfg["ablations"].items()}) | |
| # 8c. label shortcuts: question-only (FAIL) and state-skeleton-only (warning) baselines, train -> dev | |
| sc = shortcut_audit([r.rec for r in kept_rows if r.split == "train"], [r.rec for r in kept_rows if r.split == "dev"], | |
| cfg) | |
| C.add("question_only_shortcut", sc["pass"], failing=sc["failing"], max_gain=sc["max_question_only_gain"], | |
| by=sc["by"]) | |
| warnings = list(sc["warnings"]) | |
| # 9. zero silent truncation; per-category budgets (long_*/mac_* up to the 25,600 context limit) | |
| max_len = render_budgets(cfg)["max"] | |
| over = [m["id"] for t in tags for s in poolmod.POOLED_SPLITS for m in metas[t][s] | |
| if not (0 < m["n_tokens"]["verdict"] <= max_len_for(cfg, m["category"])) or | |
| (m["n_tokens"]["letter"] is not None and m["n_tokens"]["letter"] > max_len_for(cfg, m["category"]))] | |
| budget_no_reason = [e["ref"] for e in ledger if e["reason"] == "budget" and not e.get("detail")] | |
| C.add("token_counts_within_budget", not over and not budget_no_reason, over=over[:MAX_EXAMPLES], | |
| budget_drops=sum(e["reason"] == "budget" for e in ledger), budget_drops_without_reason=budget_no_reason[:5]) | |
| from .render import Renderer | |
| rng = random.Random(0) | |
| retok_bad, checked = [], 0 | |
| for tag in tags: | |
| tok = load_tokenizer(cfg["tokenizers"][tag]) | |
| rv = Renderer(tok, "verdict", max_len=max_len) | |
| view = poolmod.open_split(tag, "train", root=pool_dir, verify=False) | |
| allm = [(s, i, m) for s in poolmod.POOLED_SPLITS for i, m in enumerate(metas[tag][s])] | |
| picks = rng.sample(allm, min(sample, len(allm))) + sorted(allm, key=lambda x: -x[2]["n_tokens"]["verdict"])[:50] | |
| views = {s: (view if s == "train" else poolmod.open_split(tag, s, root=pool_dir, verify=False)) | |
| for s in poolmod.POOLED_SPLITS} | |
| for s, i, m in picks: | |
| row = views[s][i] | |
| src = by_ref.get(m["raw_ref"]) | |
| if src is None or src.rec is None or src.rec.get("id") != m["id"]: | |
| retok_bad.append({"tok": tag, "id": m["id"], "piece": "raw record missing/changed"}) | |
| continue | |
| rec = src.rec | |
| fresh = rv.pieces(rec["state"], rec["question"]) | |
| checked += 1 | |
| for key in ("prefix", "head", "opts", "names", "qtype", "template"): | |
| if fresh[key] != row["pieces"][key]: | |
| retok_bad.append({"tok": tag, "id": m["id"], "piece": key}) | |
| break | |
| C.add("pieces_equal_fresh_tokenisation_sample", not retok_bad, checked=checked, bad=retok_bad[:MAX_EXAMPLES]) | |
| out = C.report("G1", {"warnings": warnings, "elapsed_s": round(time.time() - t0, 1)}) | |
| for w in warnings: | |
| log(f"[gates] G1 WARNING {w}") | |
| log(f"[gates] G1 {'PASS' if out['pass'] else 'FAIL'} {out['failed']} ({out['elapsed_s']}s)") | |
| return out | |
| # ============================================================================================= | |
| # G2 | |
| def _slot_problem(rend, row, order, nl_ids, arrow, answer_last) -> str | None: | |
| ids, pieces = rend.ids, row["pieces"] | |
| if ids[:rend.prefix_len] != pieces["prefix"] or rend.prefix_len != len(pieces["prefix"]): | |
| return "prefix" | |
| if rend.order != list(order): | |
| return "order" | |
| if rend.readout == "verdict": | |
| if len(rend.slots) != len(order) or rend.slots != sorted(rend.slots): | |
| return "slot_count" | |
| for j, s in enumerate(rend.slots): | |
| opt = pieces["opts"][order[j]] | |
| if ids[s] != arrow or ids[s - len(opt):s] != opt or ids[s + 1:s + 1 + len(nl_ids)] != nl_ids: | |
| return f"slot_{j}" | |
| if rend.slots[-1] != len(ids) - len(nl_ids) - 1: | |
| return "last_slot" | |
| else: | |
| if len(rend.slots) != 1 or rend.slots[0] != len(ids) - 1 or ids[-1] != answer_last: | |
| return "answer_slot" | |
| return None | |
| def gate_g2_tok(pool_dir: Path, cfg_path: Path, tag: str, log=_log) -> dict: | |
| from .render import TEMPLATE_VERSION, InputBudgetError, Renderer, canonical_probs | |
| t0 = time.time() | |
| cfg = load_config(cfg_path) | |
| C = Checks() | |
| tok = load_tokenizer(cfg["tokenizers"][tag]) | |
| max_len = render_budgets(cfg)["max"] # renderers at the largest budget; rows checked against their own | |
| rv, rl = Renderer(tok, "verdict", max_len=max_len), Renderer(tok, "letter", max_len=max_len) | |
| nl_ids, arrow = rv._newline, rv._arrow[0] | |
| answer_last = rl._glue()["answer"][-1] | |
| added = {i: a for i, a in tok.added_tokens_decoder.items()} | |
| added_ids = np.array(sorted(added), dtype=np.int64) | |
| # glue never contains control tokens | |
| glue = rv._glue() | |
| glue_ids = set(glue["dash"] + glue["judge"] + glue["answer"] + sum(glue["letters"], []) + rv._arrow + nl_ids | |
| + rv.prefix_ids("")) | |
| C.add("glue_has_no_added_tokens", not (glue_ids & set(added))) | |
| # escaping probe | |
| unescaped_special, unescaped_nonspecial = [], [] | |
| for i, a in added.items(): | |
| ids = rv.render(f"x {a.content} y", {"t": "noul", "ins": f"q {a.content}?"}).ids | |
| if i in ids: | |
| (unescaped_special if a.special else unescaped_nonspecial).append(a.content) | |
| C.add("probe_special_tokens_escaped", not unescaped_special, unescaped=unescaped_special[:MAX_EXAMPLES], | |
| n_special=sum(a.special for a in added.values())) | |
| probe_warning = None | |
| if unescaped_nonspecial: | |
| probe_warning = (f"{len(unescaped_nonspecial)} non-special added tokens (e.g. {unescaped_nonspecial[:4]}) " | |
| "are NOT escaped by macjev.render (split_special_tokens only splits special tokens); " | |
| "pooled rows are checked below") | |
| stats = Counter() | |
| bad = defaultdict(list) | |
| ctrl_rows = [] | |
| for split in poolmod.POOLED_SPLITS: | |
| view = poolmod.open_split(tag, split, root=pool_dir, verify=True) | |
| flat = np.asarray(view.ids) | |
| hit_pos = np.nonzero(np.isin(flat, added_ids))[0] if len(flat) else np.array([], dtype=np.int64) | |
| if len(hit_pos): | |
| starts = np.array([m["seg"]["prefix"][0] for m in view.meta]) | |
| for p in hit_pos[:1000]: | |
| k = int(np.searchsorted(starts, p, side="right") - 1) | |
| ctrl_rows.append({"split": split, "id": view.meta[k]["id"], "token": added[int(flat[p])].content}) | |
| for i in range(len(view)): | |
| row = view[i] | |
| k = len(row["names"]) | |
| stats["rows"] += 1 | |
| p = row["pieces"] | |
| if p["template"] != TEMPLATE_VERSION or p["names"] != row["names"] or p["qtype"] != row["qtype"] \ | |
| or len(p["opts"]) != k: | |
| bad["pieces_meta"].append(row["id"]) | |
| continue | |
| if row["head_max"] != head_max_for(cfg, row["category"], k): | |
| bad["head_max_rule"].append(row["id"]) | |
| row_max = max_len_for(cfg, row["category"]) | |
| if row.get("max_len", row_max) != row_max: | |
| bad["max_len_rule"].append(row["id"]) | |
| canon = list(range(k)) | |
| try: | |
| r_v = rv.assemble(p, canon, head_max=row["head_max"], max_len=row_max) | |
| except (InputBudgetError, ValueError) as exc: | |
| bad["verdict_render"].append(f"{row['id']}: {exc}"[:200]) | |
| continue | |
| if len(r_v.ids) != row["n_tokens"]["verdict"] or len(r_v.ids) > row_max: | |
| bad["verdict_len"].append(row["id"]) | |
| prob = _slot_problem(r_v, row, canon, nl_ids, arrow, answer_last) | |
| if prob: | |
| bad["verdict_slots"].append(f"{row['id']}:{prob}") | |
| r_l = None | |
| try: | |
| r_l = rl.assemble(p, canon, head_max=row["head_max"], max_len=row_max) | |
| if row["n_tokens"]["letter"] is None or len(r_l.ids) != row["n_tokens"]["letter"]: | |
| bad["letter_len"].append(row["id"]) | |
| elif (prob := _slot_problem(r_l, row, canon, nl_ids, arrow, answer_last)): | |
| bad["letter_slots"].append(f"{row['id']}:{prob}") | |
| except InputBudgetError: | |
| if row["n_tokens"]["letter"] is not None: | |
| bad["letter_len"].append(row["id"]) | |
| stats["letter_unsupported"] += 1 | |
| if k < 2: | |
| continue | |
| perm = canon[:] | |
| random.Random(row["id"]).shuffle(perm) | |
| if perm == canon: | |
| perm = canon[1:] + canon[:1] | |
| if row["qtype"] != "choice": | |
| try: | |
| rv.assemble(p, perm, head_max=row["head_max"]) | |
| bad["non_choice_permutable"].append(row["id"]) | |
| except ValueError: | |
| pass | |
| continue | |
| stats["permuted"] += 1 | |
| r_vp = rv.assemble(p, perm, head_max=row["head_max"]) | |
| if (len(r_vp.ids) != len(r_v.ids) or r_vp.header_tokens != r_v.header_tokens | |
| or r_vp.prefix_len != r_v.prefix_len): | |
| bad["perm_invariant_verdict"].append(row["id"]) | |
| elif (prob := _slot_problem(r_vp, row, perm, nl_ids, arrow, answer_last)): | |
| bad["perm_slots_verdict"].append(f"{row['id']}:{prob}") | |
| probe = [float(j) for j in range(k)] | |
| if canonical_probs([probe[o] for o in perm], perm) != probe: | |
| bad["canonical_probs"].append(row["id"]) | |
| if r_l is not None: | |
| r_lp = rl.assemble(p, perm, head_max=row["head_max"]) | |
| if len(r_lp.ids) != len(r_l.ids) or r_lp.slots != r_l.slots: | |
| bad["perm_invariant_letter"].append(row["id"]) | |
| stats[f"rows_{split}"] = len(view) | |
| for name in ("pieces_meta", "head_max_rule", "max_len_rule", "verdict_render", "verdict_len", "verdict_slots", "letter_len", | |
| "letter_slots", "non_choice_permutable", "perm_invariant_verdict", "perm_slots_verdict", | |
| "canonical_probs", "perm_invariant_letter"): | |
| C.add(name, not bad[name], n_bad=len(bad[name]), examples=bad[name][:MAX_EXAMPLES]) | |
| C.add("no_control_token_ids_in_pool", not ctrl_rows, n_hits=len(ctrl_rows), examples=ctrl_rows[:MAX_EXAMPLES], | |
| remedy="fix escaping in macjev.render (non-special added tokens) or remove the strings in the builder" | |
| if ctrl_rows else None) | |
| out = C.report("G2", {"tok_tag": tag, "stats": dict(stats), "warnings": [probe_warning] if probe_warning else [], | |
| "unescaped_nonspecial_added_tokens": unescaped_nonspecial, | |
| "elapsed_s": round(time.time() - t0, 1)}) | |
| log(f"[gates] G2[{tag}] {'PASS' if out['pass'] else 'FAIL'} {out['failed']} ({out['elapsed_s']}s)") | |
| return out | |
| def _g2_worker(args): | |
| pool_dir, cfg_path, tag = args | |
| return gate_g2_tok(Path(pool_dir), Path(cfg_path), tag, log=lambda *_: None) | |
| def gate_g2(pool_dir: Path, cfg_path: Path, parallel: bool = True, log=_log) -> dict: | |
| tags = list(load_config(cfg_path)["tokenizers"]) | |
| if parallel and len(tags) > 1: | |
| import multiprocessing as mp | |
| from concurrent.futures import ProcessPoolExecutor | |
| with ProcessPoolExecutor(len(tags), mp_context=mp.get_context("spawn")) as ex: | |
| per = dict(zip(tags, ex.map(_g2_worker, [(str(pool_dir), str(cfg_path), t) for t in tags]))) | |
| for t, r in per.items(): | |
| log(f"[gates] G2[{t}] {'PASS' if r['pass'] else 'FAIL'} {r['failed']} ({r['elapsed_s']}s)") | |
| else: | |
| per = {t: gate_g2_tok(pool_dir, cfg_path, t, log=log) for t in tags} | |
| return {"gate": "G2", "pass": all(r["pass"] for r in per.values()), | |
| "failed": {t: r["failed"] for t, r in per.items() if not r["pass"]}, "tokenizers": per} | |
| def run_gates(pool_dir: Path, raw_dir: Path, cfg_path: Path, gates=("g1", "g2"), allow_raw_errors: bool = False, | |
| log=_log, parallel: bool = True) -> dict: | |
| pool_dir, raw_dir, cfg_path = Path(pool_dir), Path(raw_dir), Path(cfg_path) | |
| out = {} | |
| (pool_dir / "gates").mkdir(exist_ok=True) | |
| if "g1" in gates: | |
| out["g1"] = gate_g1(pool_dir, raw_dir, cfg_path, allow_raw_errors=allow_raw_errors, log=log) | |
| if "g2" in gates: | |
| out["g2"] = gate_g2(pool_dir, cfg_path, parallel=parallel, log=log) | |
| for name, rep in out.items(): | |
| (pool_dir / "gates" / f"{name}.json").write_text(json.dumps(rep, indent=1, ensure_ascii=False)) | |
| return out | |
| def main(argv: list[str] | None = None) -> int: | |
| ap = argparse.ArgumentParser(description="MacJev data gates G1 (integrity) and G2 (rendering)") | |
| ap.add_argument("--pool", default=str(POOL_V3)) | |
| ap.add_argument("--raw", default=str(RAW_V3)) | |
| ap.add_argument("--config", default=str(DEFAULT_CONFIG)) | |
| ap.add_argument("--gates", default="g1,g2") | |
| ap.add_argument("--allow-raw-errors", action="store_true") | |
| a = ap.parse_args(argv) | |
| res = run_gates(Path(a.pool), Path(a.raw), Path(a.config), tuple(a.gates.split(",")), a.allow_raw_errors) | |
| summary = {k: {"pass": v["pass"], "failed": v["failed"]} for k, v in res.items()} | |
| print(json.dumps(summary, indent=1)) | |
| if not all(v["pass"] for v in res.values()): | |
| print("DATA GATES FAILED", file=sys.stderr) | |
| return 1 | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |