Download scripts/phase5_j7_lowloop.py from Anupam-Rawat-IITB/code-switch-mtp: direct link, hf CLI and curl.
- Browser
- Download file 5.37 kB
-
https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase5_j7_lowloop.py
- Command line
-
hf download hf://Anupam-Rawat-IITB/code-switch-mtp/scripts/phase5_j7_lowloop.py
-
curl -L -o phase5_j7_lowloop.py https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase5_j7_lowloop.py
5.37 kB
| """J7 post-processor: split the box decode-timing results into all-docs and low-looping subsets. | |
| phase5_tree_decode_timing.py reports ms/token, ms/word and speedup over the whole document set and | |
| saves per-document [seconds, committed_tokens, passes] for every system (and [seconds, tokens, words] | |
| for greedy). It does not emit the low-looping split. This reproduces the EXACT same document set | |
| (generate_continuations + the same filter + [1::2]) deterministically, computes a per-document | |
| self-loop share (phase5_copy_branch.ngram_share of the decoded region), and recomputes ms/token, | |
| ms/word and speedup on (a) all documents and (b) documents with <=10% looping. | |
| ms/word here = system time / whitespace words of the decoded (greedy) output over the subset; because | |
| the decode is lossless (output == greedy output), committed tokens over a subset equal that subset's | |
| greedy token count, so speedup = greedy_seconds / system_seconds on the subset. An alignment guard | |
| checks the reproduced per-document word counts against the timing JSON before trusting the split. | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| from pathlib import Path | |
| os.environ.setdefault("CUDA_DEVICE_ORDER", "PCI_BUS_ID") | |
| REPO = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(REPO)) | |
| sys.path.insert(0, str(REPO / "scripts")) | |
| import numpy as np | |
| import torch | |
| LOOKAHEAD = 7 | |
| LOOP_MAX = 0.10 | |
| def subset_rows(per_doc, mask): | |
| a = np.array(per_doc, float)[mask] | |
| return a | |
| def main() -> None: | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("--heldout", required=True) | |
| p.add_argument("--timing-json", required=True) | |
| p.add_argument("--spec-docs", type=int, default=256) | |
| p.add_argument("--out", required=True) | |
| args = p.parse_args() | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| import phase4_boundary_decoding as pb | |
| from phase5_copy_branch import ngram_share | |
| from phase5_decode_timing import greedy | |
| from phase5_dependent_eval import BACKBONE | |
| from src.train.data import load_heldout_texts | |
| tok = AutoTokenizer.from_pretrained(BACKBONE) | |
| backbone = AutoModelForCausalLM.from_pretrained(BACKBONE, dtype=torch.float32).to("cuda:0").eval() | |
| eos = backbone.generation_config.eos_token_id | |
| eos_ids = set(eos if isinstance(eos, list) else [eos]) | |
| pairs = pb.generate_continuations(backbone, tok, load_heldout_texts(args.heldout)[: args.spec_docs], 256, 64 + LOOKAHEAD, 16, eos_ids) | |
| pairs = [(pr, c) for pr, c in pairs if min(64, len(c) - LOOKAHEAD + 1) >= 1][1::2] | |
| n_new = [min(64, len(c) - LOOKAHEAD + 1) for _, c in pairs] | |
| # Build the mask from the DECODER's own ground truth: single-sequence greedy(prompt, n_new) = ref, | |
| # not the batched continuation c (they differ for some backbones). This matches the timing JSON exactly. | |
| refs = [greedy(backbone, pr, k)[0] for (pr, _), k in zip(pairs, n_new)] | |
| mask = np.array([ngram_share(r, None) <= LOOP_MAX for r in refs]) | |
| repro_words = [len(tok.decode(r).split()) for r in refs] | |
| res = json.load(open(args.timing_json)) | |
| gper = res["greedy"]["per_document"] # [sec, tokens, words] | |
| if len(gper) != len(pairs): | |
| raise SystemExit(f"ALIGNMENT FAIL: timing has {len(gper)} docs, reproduced {len(pairs)}") | |
| tim_words = [int(r[2]) for r in gper] | |
| mism = sum(int(a != b) for a, b in zip(repro_words, tim_words)) | |
| if mism > 0: | |
| raise SystemExit(f"ALIGNMENT FAIL: {mism}/{len(pairs)} docs have mismatched word counts (nondeterministic regen?)") | |
| out = {"backbone": BACKBONE, "timing_json": args.timing_json, "docs": len(pairs), | |
| "low_looping_docs": int(mask.sum()), "loop_threshold": LOOP_MAX, "subsets": {}} | |
| for subset, m in (("all", np.ones(len(pairs), bool)), ("low_looping", mask)): | |
| g = subset_rows(gper, m) # [sec, tokens, words] | |
| g_sec, g_tok, g_words = g[:, 0].sum(), g[:, 1].sum(), g[:, 2].sum() | |
| g_mst = 1000 * g_sec / g_tok | |
| block = {"n_docs": int(m.sum()), | |
| "greedy": {"ms_per_token": g_mst, "ms_per_word": 1000 * g_sec / g_words, | |
| "words_per_token": float(g_words / g_tok)}, | |
| "systems": {}} | |
| for name, s in res["systems"].items(): | |
| a = subset_rows(s["per_document"], m) # [sec, committed, passes] | |
| sec, comm, pas = a[:, 0].sum(), a[:, 1].sum(), a[:, 2].sum() | |
| mst = 1000 * sec / comm | |
| block["systems"][name] = {"ms_per_token": mst, "ms_per_word": 1000 * sec / g_words, | |
| "speedup_vs_greedy": g_sec / sec, "tokens_per_pass": float(comm / pas)} | |
| out["subsets"][subset] = block | |
| Path(args.out).parent.mkdir(parents=True, exist_ok=True) | |
| Path(args.out).write_text(json.dumps(out, indent=1)) | |
| for subset in ("all", "low_looping"): | |
| b = out["subsets"][subset] | |
| print(f"[{subset}] n={b['n_docs']} greedy {b['greedy']['ms_per_word']:.2f} ms/word " | |
| f"({b['greedy']['ms_per_token']:.2f} ms/tok, {b['greedy']['words_per_token']:.3f} w/tok)", flush=True) | |
| for name, r in b["systems"].items(): | |
| print(f" {name:62s} {r['ms_per_word']:6.2f} ms/word {r['ms_per_token']:6.2f} ms/tok {r['speedup_vs_greedy']:.2f}x {r['tokens_per_pass']:.3f} tok/pass", flush=True) | |
| if __name__ == "__main__": | |
| main() | |