Download scripts/phase5_deep_tree.py from Anupam-Rawat-IITB/code-switch-mtp: direct link, hf CLI and curl.
- Browser
- Download file 13.7 kB
-
https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase5_deep_tree.py
- Command line
-
hf download hf://Anupam-Rawat-IITB/code-switch-mtp/scripts/phase5_deep_tree.py
-
curl -L -o phase5_deep_tree.py https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase5_deep_tree.py
13.7 kB
| """Phase 5: chains and confidence trees of any depth, for stacks with more than three look-ahead heads. | |
| phase5_tree_draft.py expands the full 4-ary tree of depth three. With five | |
| look-ahead heads the full tree has 1,364 nodes per position, so this script | |
| keeps, at every level, only the `beam` nodes with the highest path | |
| confidence before expanding them. Any node among the best N <= beam nodes of | |
| the full tree is among the best N of its own level, and so are its | |
| ancestors, so the verified set for a budget N <= beam is the same as with | |
| the full tree. At depth three and beam >= 16 nothing is pruned and the | |
| numbers equal those of phase5_tree_draft.py ("confidence" rule). | |
| For one checkpoint and each requested depth D (using only its first D | |
| look-ahead heads) it reports, on the odd-indexed held-out documents: tokens | |
| per pass of the chain of D drafts and of the confidence tree at each budget, | |
| how many drafts are accepted per pass, how often each head is right given | |
| that the earlier drafts were, first-draft accuracy by word-group position, | |
| and the time of a backbone pass over as many tokens. | |
| """ | |
| 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_tree_draft import DEVICE, K, pass_timings, replay, top_candidates, visited | |
| BUDGETS = (8, 16, 24) | |
| def head_features(stack, trunk: torch.Tensor, d: int, hist: list, since: torch.Tensor) -> torch.Tensor: | |
| """Features of look-ahead head d given the d tokens before its target (oldest first). | |
| since: tokens since the last word start at the context token, used only by stacks with prefix features. | |
| """ | |
| h = trunk | |
| if hasattr(stack, "feat_proj"): | |
| h = h + stack.feat_proj[d - 1](stack.prefix_features(since, hist)) | |
| if hasattr(stack, "proj"): | |
| for i, tokens in enumerate(hist): | |
| h = h + stack.proj[d - 1][i](stack.embed(tokens)) | |
| return stack.heads[d].resblock(h) | |
| def chain_drafts(stack, unembed: torch.Tensor, trunk: torch.Tensor, exact_next: torch.Tensor, depth: int, since: torch.Tensor) -> torch.Tensor: | |
| """(H, depth) the top choice of each head given the exact next token and the earlier top choices.""" | |
| hist = [exact_next] | |
| for d in range(1, depth + 1): | |
| hist.append(top_candidates(head_features(stack, trunk, d, hist, since), unembed)[0][:, 0]) | |
| return torch.stack(hist[1:], 1) | |
| def beam_tree(stack, unembed: torch.Tensor, trunk: torch.Tensor, exact_next: torch.Tensor, truth: torch.Tensor, depth: int, beam: int, since: torch.Tensor) -> list: | |
| """Per level: (path log-confidence, node is on the true path) for every expanded node, shapes (H, nodes).""" | |
| h = trunk.shape[0] | |
| hist = [exact_next[:, None]] # tokens before a node's target, one (H, parents) tensor per earlier position | |
| score = torch.zeros(h, 1, device=trunk.device) | |
| on_true = torch.ones(h, 1, dtype=torch.bool, device=trunk.device) | |
| levels = [] | |
| for d in range(1, depth + 1): | |
| p = score.shape[1] | |
| feat = head_features(stack, trunk.repeat_interleave(p, 0), d, [x.reshape(-1) for x in hist], since.repeat_interleave(p)) | |
| tok, lp = top_candidates(feat, unembed) | |
| tok, lp = tok.view(h, p, K), lp.view(h, p, K) | |
| child_score = (score[:, :, None] + lp).reshape(h, p * K) | |
| child_true = (on_true[:, :, None] & (tok == truth[:, d - 1, None, None])).reshape(h, p * K) | |
| levels.append((child_score, child_true)) | |
| if d == depth: | |
| break | |
| hist = [x.repeat_interleave(K, 1) for x in hist] + [tok.reshape(h, p * K)] | |
| score, on_true = child_score, child_true | |
| if p * K > beam: | |
| keep = child_score.topk(beam, 1).indices | |
| score, on_true = child_score.gather(1, keep), child_true.gather(1, keep) | |
| hist = [x.gather(1, keep) for x in hist] | |
| return levels | |
| def accepted_depth(levels: list, budget: int) -> np.ndarray: | |
| """Drafts accepted at each position when the `budget` most confident nodes are verified.""" | |
| scores = torch.cat([s for s, _ in levels], 1) | |
| order = torch.argsort(scores, dim=1, descending=True, stable=True) # ties keep the shallower node first | |
| place = torch.empty_like(order) | |
| place.scatter_(1, order, torch.arange(scores.shape[1], device=scores.device).expand_as(order)) | |
| chosen = place < budget | |
| ok = torch.ones(scores.shape[0], dtype=torch.bool, device=scores.device) | |
| depth = torch.zeros(scores.shape[0], dtype=torch.long, device=scores.device) | |
| off = 0 | |
| for s, on_true in levels: | |
| n = s.shape[1] | |
| ok = ok & (on_true & chosen[:, off : off + n]).any(1) | |
| depth += ok | |
| off += n | |
| return depth.cpu().numpy() | |
| def main() -> None: | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("--name", required=True) | |
| p.add_argument("--label", required=True, help="name of this checkpoint in the output") | |
| p.add_argument("--ckpt", required=True, help="path of the arm's .pt file") | |
| p.add_argument("--n-heads", type=int, default=4, help="heads in the checkpoint: next-token head plus look-ahead heads") | |
| p.add_argument("--depths", default="3", help="comma-separated numbers of look-ahead heads to use") | |
| p.add_argument("--lookahead", type=int, default=7, help="tokens generated past the scored horizon; at least deepest depth + 2") | |
| p.add_argument("--beam", type=int, default=24) | |
| p.add_argument("--heldout", required=True) | |
| p.add_argument("--scheme", default="Devanagari") | |
| p.add_argument("--spec-docs", type=int, default=256) | |
| p.add_argument("--prefix-features", action="store_true", help="load the checkpoint into a stack with prefix features; " | |
| "a checkpoint without them keeps the feature weights at zero") | |
| p.add_argument("--out", required=True) | |
| args = p.parse_args() | |
| t0 = time.perf_counter() | |
| depths = [int(x) for x in args.depths.split(",")] | |
| assert max(depths) <= args.n_heads - 1 and args.lookahead >= max(depths) + 2 and args.beam >= max(BUDGETS) | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| import phase4_boundary_decoding as pb | |
| import phase5_word_groups as wg | |
| 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() | |
| vocab = backbone.config.vocab_size | |
| starts = pb.word_start_table(tok) | |
| is_start = np.array(starts + [False] * (vocab - len(starts))) | |
| fwords = wg.function_words(args.scheme) if args.scheme else set() | |
| 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 + args.lookahead, 16, eos_ids) | |
| pairs = [(pr, c) for pr, c in pairs if min(64, len(c) - args.lookahead + 1) >= 1] | |
| test = pairs[1::2] | |
| if args.prefix_features: | |
| from src.train.dependent import PrefixFeatureStack | |
| tables = [torch.from_numpy(t) for t in wg.prefix_tables(tok, vocab)] | |
| stack = PrefixFeatureStack(backbone.config.hidden_size, backbone.lm_head, args.n_heads, backbone.get_input_embeddings(), 1.0, *tables) | |
| state = {k: v for k, v in torch.load(args.ckpt, 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 and not m.startswith(("feat_proj.", "tok_")) for m in missing): | |
| raise RuntimeError(f"checkpoint mismatch: missing={missing} unexpected={unexpected}") | |
| print(f"{args.label}: prefix features, feature weights {'trained' if 'feat_proj.0.weight' in state else 'absent from the checkpoint (zero)'}", flush=True) | |
| stack = stack.to(DEVICE).eval() | |
| else: | |
| stack = load_arm(backbone, Path(args.ckpt), True, n_heads=args.n_heads) | |
| res = {"name": args.name, "label": args.label, "ckpt": args.ckpt, "n_heads": args.n_heads, "lookahead": args.lookahead, "beam": args.beam, | |
| "candidates_per_node": K, "gpu": torch.cuda.get_device_name(DEVICE), "docs": len(pairs), "test_docs": len(test), "depths": {}} | |
| for depth in depths: | |
| chain, tree = [], {n: [] for n in BUDGETS} | |
| hist_chain = np.zeros(depth + 1, dtype=np.int64) | |
| hist_tree = {n: np.zeros(depth + 1, dtype=np.int64) for n in BUDGETS} | |
| cond = np.zeros((depth, 2), dtype=np.int64) # per head: right, and reached with all earlier drafts right | |
| by_class = np.zeros((3, 2), dtype=np.int64) | |
| for prompt, cont in test: | |
| horizon = min(64, len(cont) - args.lookahead + 1) | |
| seq = prompt + cont | |
| p0 = len(prompt) - 1 | |
| trunk = stack.trunk_states(backbone.model(input_ids=torch.tensor([seq], device=DEVICE)).last_hidden_state[0, p0 : p0 + horizon]) | |
| continuation = [prompt[-1]] + cont | |
| exact_next = torch.tensor(continuation[1 : horizon + 1], device=DEVICE) | |
| truth = torch.tensor([continuation[j + 2 : j + 2 + depth] for j in range(horizon)], device=DEVICE) | |
| since = torch.zeros(horizon, dtype=torch.long, device=DEVICE) | |
| if hasattr(stack, "feat_proj"): # count at the context token of each position, from the text decoded so far | |
| since = stack.tokens_since_word_start(torch.tensor([seq], device=DEVICE))[0, p0 : p0 + horizon] | |
| match = (chain_drafts(stack, unembed, trunk, exact_next, depth, since) == truth).cpu().numpy() | |
| lead = np.cumprod(match, 1) | |
| chain_depth = lead.sum(1) | |
| chain.append(replay(chain_depth)) | |
| hist_chain += np.bincount(chain_depth[visited(chain_depth)], minlength=depth + 1) | |
| reached = np.concatenate([np.ones((horizon, 1), dtype=np.int64), lead[:, :-1]], 1) | |
| cond += np.stack([(match & (reached > 0)).sum(0), reached.sum(0)], 1) | |
| classes = wg.token_classes(seq, is_start, tok, fwords)[len(prompt) + 1 : len(prompt) + 1 + horizon] | |
| for c in range(3): | |
| by_class[c] += [match[classes == c, 0].sum(), (classes == c).sum()] | |
| levels = beam_tree(stack, unembed, trunk, exact_next, truth, depth, args.beam, since) | |
| for n in BUDGETS: | |
| d = accepted_depth(levels, n) | |
| tree[n].append(replay(d)) | |
| hist_tree[n] += np.bincount(d[visited(d)], minlength=depth + 1) | |
| def tpp(rows: list) -> float: | |
| a = np.array(rows) | |
| return float(a[:, 0].sum() / a[:, 1].sum()) | |
| out = { | |
| "chain_tokens_per_pass": tpp(chain), | |
| "tree_tokens_per_pass": {str(n): tpp(tree[n]) for n in BUDGETS}, | |
| "chain_accepted_drafts_per_pass_share": (hist_chain / hist_chain.sum()).tolist(), | |
| "tree_accepted_drafts_per_pass_share": {str(n): (hist_tree[n] / hist_tree[n].sum()).tolist() for n in BUDGETS}, | |
| "head_right_given_earlier_drafts_right": (cond[:, 0] / np.maximum(1, cond[:, 1])).tolist(), | |
| "first_draft_accuracy": {wg.CLASS_NAMES[c]: float(by_class[c, 0] / max(1, by_class[c, 1])) for c in range(3)}, | |
| "first_draft_accuracy_all": float(by_class[:, 0].sum() / by_class[:, 1].sum()), | |
| "per_document": {"chain": np.array(chain).tolist(), **{f"tree_{n}": np.array(tree[n]).tolist() for n in BUDGETS}}, | |
| } | |
| res["depths"][str(depth)] = out | |
| print(f"{args.label} depth {depth}: chain {out['chain_tokens_per_pass']:.3f} tree " + " ".join(f"N={n}: {out['tree_tokens_per_pass'][str(n)]:.3f}" for n in BUDGETS) | |
| + f" {time.perf_counter() - t0:.0f}s", flush=True) | |
| print(" head right given earlier right: " + " ".join(f"{v:.3f}" for v in out["head_right_given_earlier_drafts_right"]), flush=True) | |
| print(" chain accepted drafts per pass (0..D): " + " ".join(f"{v:.3f}" for v in out["chain_accepted_drafts_per_pass_share"]), flush=True) | |
| print(" tree N=8 accepted drafts per pass (0..D): " + " ".join(f"{v:.3f}" for v in out["tree_accepted_drafts_per_pass_share"]["8"]), flush=True) | |
| print(" first draft: " + " ".join(f"{k} {v:.3f}" for k, v in out["first_draft_accuracy"].items()), flush=True) | |
| # cost: drafting D tokens for one position over the full vocabulary, and a backbone pass over n new tokens | |
| trunk1, next1, since1 = trunk[:1], exact_next[:1], since[:1] | |
| res["draft_chain_ms"] = {} | |
| for depth in depths: | |
| chain_drafts(stack, unembed, trunk1, next1, depth, since1) | |
| torch.cuda.synchronize() | |
| t = time.perf_counter() | |
| for _ in range(30): | |
| chain_drafts(stack, unembed, trunk1, next1, depth, since1) | |
| torch.cuda.synchronize() | |
| res["draft_chain_ms"][str(depth)] = 1000 * (time.perf_counter() - t) / 30 | |
| res["backbone_pass_ms_by_new_tokens"] = pass_timings(backbone, pairs[0][0], (1, 4, 6, 9, 17, 25)) | |
| 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.label}: draft ms {res['draft_chain_ms']}, pass ms {res['backbone_pass_ms_by_new_tokens']}, {res['wall_seconds']:.0f}s, peak {res['peak_gpu_mib']:.0f} MiB", flush=True) | |
| if __name__ == "__main__": | |
| main() | |