Download scripts/phase5_depth_copy.py from Anupam-Rawat-IITB/code-switch-mtp: direct link, hf CLI and curl.
- Browser
- Download file 7.09 kB
-
https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase5_depth_copy.py
- Command line
-
hf download hf://Anupam-Rawat-IITB/code-switch-mtp/scripts/phase5_depth_copy.py
-
curl -L -o phase5_depth_copy.py https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase5_depth_copy.py
7.09 kB
| """Phase 5: do deeper heads and a copied branch add up, or do they pay in the same places? | |
| Five look-ahead heads raise tokens per pass where three drafts were already | |
| accepted (phase5_deep_tree.py), and a branch copied from the context does the | |
| same where the frozen model reuses its context (phase5_copy_branch.py). For | |
| each seed this script compares, on the odd-indexed held-out documents and at | |
| the same number of verified tokens N: | |
| tree confidence tree with N nodes | |
| tree + copy if a suffix of at least two tokens occurred earlier in the | |
| context: the N - 5 most confident nodes plus the 5 tokens | |
| that followed that suffix; otherwise the tree with N nodes | |
| for the stack with three look-ahead heads and the stack with five. Nothing is | |
| fitted, so no documents are held back. | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| import time | |
| 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 | |
| from phase5_copy_branch import copied_branch, ngram_share | |
| from phase5_deep_tree import accepted_depth, beam_tree | |
| from phase5_tree_draft import DEVICE, bootstrap_gain, replay | |
| LOOKAHEAD = 7 | |
| COPY = 5 | |
| BUDGETS = (8, 16) | |
| def main() -> None: | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("--name", required=True) | |
| p.add_argument("--base-root", required=True, help="directory holding {name}_seed{s}/{arm}.pt with three look-ahead heads") | |
| p.add_argument("--deep-root", required=True, help="the same for five look-ahead heads") | |
| p.add_argument("--arm", default="dependent_teacher") | |
| p.add_argument("--seeds", default="0,1") | |
| p.add_argument("--heldout", required=True) | |
| p.add_argument("--spec-docs", type=int, default=256) | |
| p.add_argument("--out", required=True) | |
| args = p.parse_args() | |
| t0 = time.perf_counter() | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| import phase4_boundary_decoding as pb | |
| from phase5_dependent_eval import BACKBONE, load_arm | |
| from src.train.data import load_heldout_texts | |
| tok = AutoTokenizer.from_pretrained(BACKBONE) | |
| backbone = AutoModelForCausalLM.from_pretrained(BACKBONE, dtype=torch.float32).to(DEVICE).eval() | |
| unembed = backbone.lm_head.weight | |
| eos = backbone.generation_config.eos_token_id | |
| eos_ids = set(eos if isinstance(eos, list) else [eos]) | |
| texts = load_heldout_texts(args.heldout) | |
| pairs = pb.generate_continuations(backbone, tok, texts[: 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] | |
| docs = [] | |
| for prompt, cont in pairs[1::2]: | |
| horizon = min(64, len(cont) - LOOKAHEAD + 1) | |
| seq = prompt + cont | |
| p0 = len(prompt) - 1 | |
| branches = [copied_branch(seq, p0 + 1 + j, COPY) for j in range(horizon)] | |
| truth = [seq[p0 + 2 + j : p0 + 2 + j + COPY] for j in range(horizon)] | |
| docs.append({"seq": seq, "p0": p0, "horizon": horizon, | |
| "copy": np.array([int(np.cumprod([a == b for a, b in zip(br, truth[j])]).sum()) if br else 0 for j, (br, _) in enumerate(branches)]), | |
| "gate": np.array([m >= 2 for _, m in branches]), "self_loop": ngram_share(cont[:64], None)}) | |
| low = np.array([d["self_loop"] <= 0.1 for d in docs]) | |
| print(f"{args.name}: {len(docs)} test documents ({int(low.sum())} with at most 10% looping), {time.perf_counter() - t0:.0f}s", flush=True) | |
| res = {"name": args.name, "arm": args.arm, "gpu": torch.cuda.get_device_name(DEVICE), "test_docs": len(docs), "documents_with_little_looping": int(low.sum()), "seeds": {}} | |
| for seed in args.seeds.split(","): | |
| rows = {} | |
| for label, root, n_heads, depth in (("3_heads", args.base_root, 4, 3), ("5_heads", args.deep_root, 6, 5)): | |
| stack = load_arm(backbone, Path(root) / f"{args.name}_seed{seed}" / f"{args.arm}.pt", True, n_heads=n_heads) | |
| per = {f"{label}_tree_{n}": [] for n in BUDGETS} | {f"{label}_tree_plus_copy_{n}": [] for n in BUDGETS} | |
| for d in docs: | |
| seq, p0, horizon = d["seq"], d["p0"], d["horizon"] | |
| trunk = stack.trunk_states(backbone.model(input_ids=torch.tensor([seq], device=DEVICE)).last_hidden_state[0, p0 : p0 + horizon]) | |
| exact_next = torch.tensor(seq[p0 + 1 : p0 + 1 + horizon], device=DEVICE) | |
| truth = torch.tensor([seq[p0 + 2 + j : p0 + 2 + j + depth] for j in range(horizon)], device=DEVICE) | |
| since = torch.zeros(horizon, dtype=torch.long, device=DEVICE) | |
| levels = beam_tree(stack, unembed, trunk, exact_next, truth, depth, 24, since) | |
| for n in BUDGETS: | |
| full, small = accepted_depth(levels, n), accepted_depth(levels, n - COPY) | |
| per[f"{label}_tree_{n}"].append(replay(full)) | |
| per[f"{label}_tree_plus_copy_{n}"].append(replay(np.where(d["gate"], np.maximum(small, d["copy"]), full))) | |
| rows.update({k: np.array(v, dtype=float) for k, v in per.items()}) | |
| del stack | |
| def tpp(a: np.ndarray) -> float: | |
| return float(a[:, 0].sum() / a[:, 1].sum()) | |
| out = {"tokens_per_pass": {k: tpp(v) for k, v in rows.items()}, "tokens_per_pass_little_looping": {k: tpp(v[low]) for k, v in rows.items()}, | |
| "percent_gain": {}, "per_document": {k: v.tolist() for k, v in rows.items()}} | |
| for n in BUDGETS: | |
| g = out["percent_gain"] | |
| g[f"depth_without_copy_{n}"] = bootstrap_gain(rows[f"5_heads_tree_{n}"], rows[f"3_heads_tree_{n}"]) | |
| g[f"depth_with_copy_{n}"] = bootstrap_gain(rows[f"5_heads_tree_plus_copy_{n}"], rows[f"3_heads_tree_plus_copy_{n}"]) | |
| g[f"copy_with_3_heads_{n}"] = bootstrap_gain(rows[f"3_heads_tree_plus_copy_{n}"], rows[f"3_heads_tree_{n}"]) | |
| g[f"copy_with_5_heads_{n}"] = bootstrap_gain(rows[f"5_heads_tree_plus_copy_{n}"], rows[f"5_heads_tree_{n}"]) | |
| g[f"both_{n}"] = bootstrap_gain(rows[f"5_heads_tree_plus_copy_{n}"], rows[f"3_heads_tree_{n}"]) | |
| res["seeds"][seed] = out | |
| print(f"{args.name} seed {seed}: " + " ".join(f"{k} {v:.3f}" for k, v in out["tokens_per_pass"].items()) + f" {time.perf_counter() - t0:.0f}s", flush=True) | |
| print(" little looping: " + " ".join(f"{k} {v:.3f}" for k, v in out["tokens_per_pass_little_looping"].items()), flush=True) | |
| for k, v in out["percent_gain"].items(): | |
| print(f" {k:26s} {v[0]:+.2f}% [{v[1]:+.2f}, {v[2]:+.2f}]", flush=True) | |
| res["wall_seconds"] = time.perf_counter() - t0 | |
| res["peak_gpu_mib"] = torch.cuda.max_memory_allocated(DEVICE) / 2**20 | |
| Path(args.out).parent.mkdir(parents=True, exist_ok=True) | |
| Path(args.out).write_text(json.dumps(res, indent=1)) | |
| print(f"{args.name}: {res['wall_seconds']:.0f}s, peak {res['peak_gpu_mib']:.0f} MiB", flush=True) | |
| if __name__ == "__main__": | |
| main() | |