Download scripts/phase5_dependent_eval.py from Anupam-Rawat-IITB/code-switch-mtp: direct link, hf CLI and curl.
- Browser
- Download file 14.8 kB
-
https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase5_dependent_eval.py
- Command line
-
hf download hf://Anupam-Rawat-IITB/code-switch-mtp/scripts/phase5_dependent_eval.py
-
curl -L -o phase5_dependent_eval.py https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase5_dependent_eval.py
14.8 kB
| """Phase 5 evaluation: independent vs dependent draft heads. | |
| Part A (held-out text, teacher forced): per-head accuracy and loss, split by | |
| whether the target token starts a word or continues one; head-1 loss against | |
| the NTP control (negative transfer); a control that feeds the dependent heads | |
| the wrong predecessor tokens. | |
| Part B (lossless greedy drafting, replayed on the backbone's own greedy | |
| continuation). Two accountings: | |
| one_pass The hidden state z_p of the last verified token gives the next | |
| token exactly (the backbone's own argmax), and heads 2-4 draft the | |
| three tokens after it. One backbone pass per round, at most 4 | |
| tokens per pass. This is what a deployed drafter can do. | |
| legacy Heads 1-4 draft four tokens from the hidden state of the last | |
| committed token, plus one bonus token (the phase-4 accounting). | |
| It assumes the hidden state of the bonus token is available | |
| without a pass, so it overstates tokens per pass; kept only to | |
| link to earlier numbers. | |
| Drafting policies: plain argmax, and argmax after the training-free lexical | |
| correction beta * [log p_pair(x | previous token) - log p_unigram(x)]. | |
| Per-document counts are stored so beta can be chosen on one half of the | |
| documents and reported on the other. | |
| Part C: wall-clock cost of drafting and of a cached verification pass. | |
| """ | |
| 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 | |
| import torch.nn.functional as F | |
| from src.train.dependent import DependentStack, teacher_forced_logits | |
| from src.train.model import MTPStack | |
| DEVICE = "cuda:0" | |
| BACKBONE = os.environ.get("CS769_BACKBONE", "meta-llama/Llama-3.2-1B") | |
| N_HEADS = 4 | |
| CHUNK = 96 | |
| BETAS = (0.25, 0.5, 1.0) | |
| ARMS = ("independent", "dependent", "dependent_accept", "independent_teacher", "dependent_teacher") | |
| def load_arm(backbone, path: Path, dependent: bool, n_heads: int = N_HEADS) -> MTPStack: | |
| hidden = backbone.config.hidden_size | |
| if dependent: | |
| stack = DependentStack(hidden, backbone.lm_head, n_heads, backbone.get_input_embeddings(), 1.0) | |
| else: | |
| stack = MTPStack(hidden, backbone.lm_head, n_heads, True) | |
| state = {k: v for k, v in torch.load(path, map_location="cpu", weights_only=True).items() if ".unembedding." not in k} | |
| missing, unexpected = stack.load_state_dict(state, strict=False) | |
| if unexpected or any(".unembedding." not in m for m in missing): | |
| raise RuntimeError(f"checkpoint mismatch: missing={missing} unexpected={unexpected}") | |
| return stack.to(DEVICE).eval() | |
| def corrected_argmax(logp: torch.Tensor, prev: torch.Tensor, table, beta: float) -> torch.Tensor: | |
| """argmax over logp + beta * lexical log-ratio rows of the previous tokens, in chunks.""" | |
| out = [] | |
| for s in range(0, logp.shape[0], CHUNK): | |
| out.append((logp[s : s + CHUNK] + beta * table.rows(prev[s : s + CHUNK], "full")).argmax(-1)) | |
| return torch.cat(out) | |
| def draft_tokens(stack: MTPStack, trunk: torch.Tensor, first_prev, first_head: int, table, beta: float) -> list: | |
| """Sequentially draft with heads first_head .. N_HEADS-1 at every position. | |
| trunk: (n, hidden). first_prev: (n,) known token before the first draft | |
| (the backbone's exact next token in one_pass), or None when the first | |
| draft comes from head 1 (legacy). Returns a list of (n,) draft tensors. | |
| """ | |
| dependent = isinstance(stack, DependentStack) | |
| history = [] if first_prev is None else [first_prev] | |
| drafts = [] | |
| for k in range(first_head, N_HEADS): | |
| logits = stack.dependent_logits(trunk, k, history[-k:] if k else []) if dependent else stack.head_logits(trunk, k) | |
| if beta > 0 and history: | |
| d = corrected_argmax(F.log_softmax(logits, -1), history[-1], table, beta) | |
| else: | |
| d = logits.argmax(-1) | |
| drafts.append(d) | |
| history.append(d) | |
| del logits | |
| return drafts | |
| def replay(drafts: list, cont: list, horizon: int, first_target: int, is_start: list) -> dict: | |
| """Replay draft/verify rounds over one continuation. | |
| drafts[j][i] targets cont[j + first_target + i]; each round commits the | |
| accepted prefix plus one exact token. Returns committed tokens, rounds, | |
| and per-draft-position [accepted, reached] counts split by whether the | |
| true token at that position starts a word. | |
| """ | |
| n_draft = len(drafts[0]) | |
| pos = np.zeros((n_draft, 2, 2), dtype=np.int64) # position, word-start flag, (accepted, reached) | |
| j = committed = rounds = 0 | |
| while j < horizon: | |
| n = 0 | |
| while n < n_draft and drafts[j][n] == cont[j + first_target + n]: | |
| n += 1 | |
| for i in range(min(n + 1, n_draft)): | |
| flag = int(is_start[cont[j + first_target + i]]) | |
| pos[i, flag, 1] += 1 | |
| pos[i, flag, 0] += int(i < n) | |
| committed += n + 1 | |
| rounds += 1 | |
| j += n + 1 | |
| return {"committed": committed, "rounds": rounds, "pos": pos} | |
| def part_a(backbone, tok, stacks: dict, ntp, texts: list, word_start_flags) -> dict: | |
| keys = list(stacks) + [f"{n}_wrong_prev" for n in stacks if isinstance(stacks[n], DependentStack)] | |
| acc = {k: np.zeros((N_HEADS, 2, 2), dtype=np.int64) for k in keys} # head, word-start flag, (correct, seen) | |
| agree = {k: np.zeros(N_HEADS, dtype=np.int64) for k in keys} # matches the backbone's own next-token choice | |
| nll = {k: np.zeros(N_HEADS) for k in keys} | |
| ntp_nll = 0.0 | |
| n_bytes = n_tokens = 0 | |
| for text in texts: | |
| enc = tok(text, add_special_tokens=False, return_offsets_mapping=True, truncation=True, max_length=512) | |
| ids = enc.input_ids | |
| if len(ids) < 16: | |
| continue | |
| flags = torch.tensor(word_start_flags(text, enc.offset_mapping), device=DEVICE) | |
| block = torch.tensor([ids], device=DEVICE) | |
| hidden = backbone.model(input_ids=block).last_hidden_state | |
| n_bytes += len(text[enc.offset_mapping[1][0] : enc.offset_mapping[len(ids) - 1][1]].encode("utf-8")) | |
| n_tokens += len(ids) - 1 | |
| if ntp is not None: | |
| lg = ntp.head_logits(ntp.trunk_states(hidden), 0)[0, :-1] | |
| ntp_nll += float(F.cross_entropy(lg, block[0, 1:], reduction="sum")) | |
| choice = backbone.lm_head(hidden).argmax(-1)[0] # choice[j] = backbone's token for position j + 1 | |
| wrong = block.roll(shifts=7, dims=1) # same token statistics, wrong positions | |
| for name in keys: | |
| stack = stacks[name.replace("_wrong_prev", "")] | |
| source = wrong if name.endswith("_wrong_prev") else block | |
| trunk = stack.trunk_states(hidden) | |
| for k in range(N_HEADS): | |
| logits = teacher_forced_logits(stack, trunk, source, k)[0] | |
| tgt = block[0, k + 1 :] | |
| tflag = flags[k + 1 :] | |
| ok = logits.argmax(-1) == tgt | |
| agree[name][k] += int((logits.argmax(-1) == choice[k:-1]).sum()) | |
| nll[name][k] += float(F.cross_entropy(logits, tgt, reduction="sum")) | |
| for f in (0, 1): | |
| m = tflag == bool(f) | |
| acc[name][k, f, 0] += int((ok & m).sum()) | |
| acc[name][k, f, 1] += int(m.sum()) | |
| del logits | |
| out = {"n_bytes": n_bytes, "n_tokens": n_tokens, "arms": {}} | |
| for name in keys: | |
| a = acc[name] | |
| out["arms"][name] = { | |
| "accuracy": (a[:, :, 0].sum(1) / a[:, :, 1].sum(1)).tolist(), | |
| "accuracy_within_word": (a[:, 0, 0] / a[:, 0, 1]).tolist(), | |
| "accuracy_word_start": (a[:, 1, 0] / a[:, 1, 1]).tolist(), | |
| "n_within_word": a[:, 0, 1].tolist(), "n_word_start": a[:, 1, 1].tolist(), | |
| "nll_nats_per_token": (nll[name] / a[:, :, 1].sum(1)).tolist(), | |
| "backbone_agreement": (agree[name] / a[:, :, 1].sum(1)).tolist(), | |
| "head1_bpb": nll[name][0] / np.log(2) / n_bytes, | |
| } | |
| if ntp is not None: | |
| ntp_bpb = ntp_nll / np.log(2) / n_bytes | |
| out["ntp_bpb"] = ntp_bpb | |
| for name in stacks: | |
| out["arms"][name]["d_relative_pct"] = 100 * (out["arms"][name]["head1_bpb"] - ntp_bpb) / ntp_bpb | |
| return out | |
| def part_b(backbone, stacks: dict, pairs: list, table, is_start: list, lookahead: int) -> dict: | |
| policies = [(n, b) for n in stacks for b in (0.0,) + BETAS] | |
| res = {acct: {f"{n}_beta{b:g}": {"committed": [], "rounds": [], "pos": 0} for n, b in policies} for acct in ("one_pass", "legacy")} | |
| for prompt, cont in pairs: | |
| horizon = min(64, len(cont) - lookahead + 1) | |
| if horizon < 1: | |
| continue | |
| full = torch.tensor([prompt + cont], device=DEVICE) | |
| p0 = len(prompt) - 1 | |
| hidden = backbone.model(input_ids=full).last_hidden_state[0, p0 : p0 + horizon] | |
| continuation = [prompt[-1]] + cont | |
| exact_next = torch.tensor(continuation[1 : horizon + 1], device=DEVICE) | |
| for name, stack in stacks.items(): | |
| trunk = stack.trunk_states(hidden) | |
| for beta in (0.0,) + BETAS: | |
| key = f"{name}_beta{beta:g}" | |
| for acct, first_prev, first_head, first_target in (("one_pass", exact_next, 1, 2), ("legacy", None, 0, 1)): | |
| drafts = torch.stack(draft_tokens(stack, trunk, first_prev, first_head, table, beta), 1).tolist() | |
| r = replay(drafts, continuation, horizon, first_target, is_start) | |
| slot = res[acct][key] | |
| slot["committed"].append(r["committed"]) | |
| slot["rounds"].append(r["rounds"]) | |
| slot["pos"] = slot["pos"] + r["pos"] | |
| for acct in res: | |
| for key, slot in res[acct].items(): | |
| pos = slot.pop("pos") | |
| slot["tokens_per_pass"] = sum(slot["committed"]) / sum(slot["rounds"]) | |
| slot["accept_by_position"] = (pos[:, :, 0].sum(1) / np.maximum(1, pos[:, :, 1].sum(1))).tolist() | |
| slot["accept_within_word"] = (pos[:, 0, 0] / np.maximum(1, pos[:, 0, 1])).tolist() | |
| slot["accept_word_start"] = (pos[:, 1, 0] / np.maximum(1, pos[:, 1, 1])).tolist() | |
| slot["reached_within_word"] = pos[:, 0, 1].tolist() | |
| slot["reached_word_start"] = pos[:, 1, 1].tolist() | |
| return res | |
| def part_c(backbone, stacks: dict, prompt: list, reps: int = 30) -> dict: | |
| """Milliseconds per round: drafting three tokens, and backbone passes with a key-value cache.""" | |
| ids = torch.tensor([prompt], device=DEVICE) | |
| out = backbone.model(input_ids=ids, use_cache=True) | |
| past, hidden = out.past_key_values, out.last_hidden_state[0, -1:] | |
| nxt = backbone.lm_head(hidden).argmax(-1) | |
| def timed(fn) -> float: | |
| fn() | |
| torch.cuda.synchronize() | |
| t = time.perf_counter() | |
| for _ in range(reps): | |
| fn() | |
| torch.cuda.synchronize() | |
| return 1000 * (time.perf_counter() - t) / reps | |
| import copy | |
| def backbone_pass(n_tokens: int): | |
| backbone.model(input_ids=ids[:, :n_tokens], past_key_values=copy.deepcopy(past), use_cache=True) | |
| res = {"backbone_pass_1_token_ms": timed(lambda: backbone_pass(1)), "backbone_pass_4_tokens_ms": timed(lambda: backbone_pass(4)), | |
| "cache_copy_ms": timed(lambda: copy.deepcopy(past)), "next_token_argmax_ms": timed(lambda: backbone.lm_head(hidden).argmax(-1))} | |
| for name, stack in stacks.items(): | |
| res[f"draft_3_tokens_{name}_ms"] = timed(lambda: draft_tokens(stack, stack.trunk_states(hidden), nxt, 1, None, 0.0)) | |
| return res | |
| def main() -> None: | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("--name", required=True) | |
| p.add_argument("--ckpt-dir", required=True) | |
| p.add_argument("--train-ids", required=True) | |
| p.add_argument("--heldout", required=True) | |
| p.add_argument("--ntp-ckpt", default=None) | |
| p.add_argument("--out", required=True) | |
| p.add_argument("--n-docs", type=int, default=512) | |
| p.add_argument("--spec-docs", type=int, default=256) | |
| p.add_argument("--arms", default=None, help="default: every known arm with a checkpoint in --ckpt-dir") | |
| args = p.parse_args() | |
| t0 = time.perf_counter() | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| import phase4_boundary_decoding as pb | |
| from phase5_dependence_probe import Bigram | |
| from src.train.data import load_heldout_texts | |
| from src.train.evaluate import word_start_flags | |
| tok = AutoTokenizer.from_pretrained(BACKBONE) | |
| backbone = AutoModelForCausalLM.from_pretrained(BACKBONE, dtype=torch.float32).to(DEVICE).eval() | |
| for q in backbone.parameters(): | |
| q.requires_grad = False | |
| vocab = backbone.config.vocab_size | |
| starts_table = pb.word_start_table(tok) | |
| is_start = torch.zeros(vocab, dtype=torch.bool) | |
| is_start[: len(starts_table)] = torch.tensor(starts_table) | |
| table = Bigram(np.load(args.train_ids), vocab, is_start) | |
| is_start_list = is_start.tolist() | |
| arm_names = args.arms.split(",") if args.arms else [n for n in ARMS if (Path(args.ckpt_dir) / f"{n}.pt").exists()] | |
| stacks = {n: load_arm(backbone, Path(args.ckpt_dir) / f"{n}.pt", n.startswith("dependent")) for n in arm_names} | |
| ntp = load_arm(backbone, Path(args.ntp_ckpt), False, n_heads=1) if args.ntp_ckpt else None | |
| texts = load_heldout_texts(args.heldout) | |
| res = {"name": args.name, "ckpt_dir": args.ckpt_dir, "betas": list(BETAS), "gpu": torch.cuda.get_device_name(DEVICE)} | |
| def save() -> None: | |
| Path(args.out).parent.mkdir(parents=True, exist_ok=True) | |
| Path(args.out).write_text(json.dumps(res, indent=1)) | |
| res["teacher_forced"] = part_a(backbone, tok, stacks, ntp, texts[: args.n_docs], word_start_flags) | |
| res["part_a_seconds"] = time.perf_counter() - t0 | |
| save() | |
| print(args.name, "part A", f"{res['part_a_seconds']:.0f}s", flush=True) | |
| t1 = time.perf_counter() | |
| eos = backbone.generation_config.eos_token_id | |
| eos_ids = set(eos if isinstance(eos, list) else [eos]) | |
| pairs = pb.generate_continuations(backbone, tok, texts[: args.spec_docs], 256, 64 + pb.LOOKAHEAD, 16, eos_ids) | |
| res["replay"] = part_b(backbone, stacks, pairs, table, is_start_list, pb.LOOKAHEAD) | |
| res["replay_docs"] = len(pairs) | |
| res["part_b_seconds"] = time.perf_counter() - t1 | |
| save() | |
| res["timing_ms"] = part_c(backbone, stacks, pairs[0][0]) | |
| res["peak_gpu_mib"] = torch.cuda.max_memory_allocated(DEVICE) / 2**20 | |
| res["wall_seconds"] = time.perf_counter() - t0 | |
| save() | |
| print(args.name, "done", f"{res['wall_seconds']:.0f}s", flush=True) | |
| if __name__ == "__main__": | |
| main() | |