Download scripts/phase5_linear_allocator.py from Anupam-Rawat-IITB/code-switch-mtp: direct link, hf CLI and curl.
- Browser
- Download file 35.8 kB
-
https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase5_linear_allocator.py
- Command line
-
hf download hf://Anupam-Rawat-IITB/code-switch-mtp/scripts/phase5_linear_allocator.py
-
curl -L -o phase5_linear_allocator.py https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase5_linear_allocator.py
35.8 kB
| """Phase 5: a linear allocator for head nodes and copied nodes, inside the real decoder, timed. | |
| phase5_calibrated_copy_tree.py showed that a calibrator which ranks head | |
| nodes and copied nodes against one budget gains a little in tokens per pass | |
| when it also sees linguistic features, and phase5_tree_decode_timing.py | |
| showed that scoring every candidate with a small network costs more time per | |
| round than that gain returns. This script tests the cheapest version: a | |
| logistic regression whose features come from per-token tables that live on | |
| the GPU, folded into a few gathers and one fused multiply-add per round. | |
| Every candidate node gets the probability that it is accepted given that its | |
| parent is. A node's score is the sum of the log-probabilities along its | |
| path, head nodes and copied nodes compete for the same N verified tokens, | |
| and the N best are verified. Scores never rise along a path, so the chosen | |
| set always contains the ancestors of its nodes. | |
| Features of a head node | |
| confidence and source bias per (depth, rank among siblings); the head's | |
| log-probability and the top sibling's, with a | |
| slope per depth; matched suffix length of the | |
| round; the token equals the copied token at that | |
| depth | |
| linguistic word-group class, script and length of the token | |
| (per-token tables); log-probability times class; | |
| script and word start of the parent token crossed | |
| with those of the token; tokens since the word | |
| start at the exact next token | |
| Features of a copied node: bias per (matched suffix length, position in the | |
| branch), and the same linguistic features. | |
| The running count of tokens since the word start is carried up to the exact | |
| next token and, below it, through the parent/token word-start cross; it is | |
| not accumulated over deeper levels. | |
| The two regressions (head, copied) are fitted on the calibration documents | |
| (even-indexed documents of the first 256 plus documents 257-512), teacher | |
| forced along the frozen model's greedy continuation, with the decoder's own | |
| candidate generation (shortlist, pool of 24 per level). The explicit feature | |
| matrix used for fitting and the folded tables used in the decoder are | |
| checked against each other on real nodes. | |
| Timing follows phase5_tree_decode_timing.py: the odd-indexed test documents, | |
| 64 new tokens, shortlist drafting, every step synchronised, output compared | |
| with greedy decoding. For each stack and budget it times the fixed rule | |
| (N - 5 tree nodes and 5 copied tokens when the matched suffix has at least | |
| two tokens) and the allocator without and with the linguistic features. | |
| --copy-length sets the length of the copied branch for the fit, the fixed rule | |
| and the allocator; --anchors adds the fixed rule with other lengths. | |
| """ | |
| import argparse | |
| import json | |
| import math | |
| 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_calibrated_tree import fit_model, vocab_tables | |
| from phase5_decode_timing import DEVICE, greedy, prefill | |
| from phase5_deep_tree import head_features | |
| from phase5_copy_branch import ngram_share | |
| from phase5_tree_decode_timing import K, LOOKAHEAD, STEPS, SuffixIndex, TreeDrafter, select_cache, tree_decode | |
| from phase5_tree_draft import bootstrap_gain | |
| COPY = 5 # tokens in the copied branch; --copy-length changes it | |
| POOL_FIT = 24 # candidates expanded per level when collecting fitting data | |
| NM = 4 # matched suffix length 0..3 | |
| NQ = 4 # tokens since the word start at the exact next token: 0, 1, 2, 3 or more | |
| NCODE = 6 # script (3) x starts a word (2) | |
| SETS = ("conf", "ling") | |
| hot = torch.nn.functional.one_hot | |
| def level_sizes(depth: int, pool: int) -> list: | |
| """Candidate nodes per level when the best `pool` nodes of a level are expanded.""" | |
| sizes, p = [], 1 | |
| for _ in range(depth): | |
| sizes.append(p * K) | |
| p = min(p * K, pool) | |
| return sizes | |
| class Aranges: | |
| def __init__(self, device): | |
| self.device, self.cache = device, {} | |
| self.root = torch.full((1,), -1, dtype=torch.long, device=device) | |
| def get(self, base: int, n: int) -> torch.Tensor: | |
| if (base, n) not in self.cache: | |
| self.cache[(base, n)] = base + torch.arange(n, device=self.device) | |
| return self.cache[(base, n)] | |
| def expand(drafter: TreeDrafter, trunk: torch.Tensor, nxt: torch.Tensor, pool: int, ar: Aranges) -> tuple: | |
| """All candidates below the exact next token, level by level, expanding the `pool` most confident nodes of a level. | |
| Returns per level: tokens (p*K,), head log-probabilities (p*K,), parent tokens (p,), parent index among all | |
| candidates (p*K,, -1 for the exact next token); and per expansion the kept indices of the level (None: all). | |
| """ | |
| hist, score, frontier = [nxt.view(1)], torch.zeros(1, device=trunk.device), ar.root | |
| toks, lps, ptoks, pars, keeps, base = [], [], [], [], [], 0 | |
| for d in range(1, drafter.depth + 1): | |
| p = score.shape[0] | |
| tok, lp = drafter.candidates(head_features(drafter.stack, trunk.expand(p, -1), d, hist, None), hist[-1], True) | |
| tok = tok.reshape(-1) | |
| toks.append(tok) | |
| lps.append(lp.reshape(-1)) | |
| ptoks.append(hist[-1]) | |
| pars.append(frontier.repeat_interleave(K)) | |
| if d == drafter.depth: | |
| break | |
| child = (score[:, None] + lp).reshape(-1) | |
| if p * K > pool: | |
| keep = child.topk(pool).indices | |
| hist = [x.repeat_interleave(K)[keep] for x in hist] + [tok[keep]] | |
| score, frontier = child[keep], base + keep | |
| else: | |
| keep = None | |
| hist = [x.repeat_interleave(K) for x in hist] + [tok] | |
| score, frontier = child, ar.get(base, p * K) | |
| keeps.append(keep) | |
| base += p * K | |
| return toks, lps, ptoks, pars, keeps | |
| class Tables: | |
| """Per-token tables, built once.""" | |
| def __init__(self, is_start: np.ndarray, gclass: np.ndarray, script: np.ndarray, length: np.ndarray, device): | |
| self.start = [bool(x) for x in is_start] | |
| self.gclass = torch.from_numpy(gclass.astype(np.int64)).to(device) | |
| self.script = torch.from_numpy(script.astype(np.int64)).to(device) | |
| self.length = torch.from_numpy(length.astype(np.float32) / 8.0).to(device) | |
| self.code = self.script * 2 + torch.from_numpy(is_start.astype(np.int64)).to(device) | |
| self.code_hi = self.code * NCODE | |
| self.code_list = self.code.tolist() | |
| class LinearAllocator: | |
| def __init__(self, depth: int, tables: Tables, ling: bool, device): | |
| self.depth, self.t, self.ling, self.device = depth, tables, ling, device | |
| self.start = tables.start | |
| self.ar = Aranges(device) | |
| self.zero1 = torch.zeros(1, dtype=torch.long, device=device) | |
| self.arange = torch.arange(64, device=device) | |
| self.const = {} | |
| # ---- explicit features, used for fitting and for checking the folded form ---- | |
| def head_matrix(self, tok, ptok, lp, lp_top, didx, ridx, eq, m, bucket) -> torch.Tensor: | |
| """m and bucket: python ints for one round, or (n,) tensors.""" | |
| n, d = tok.shape[0], self.depth | |
| m = m if torch.is_tensor(m) else torch.full((n,), m, dtype=torch.long, device=tok.device) | |
| dh = hot(didx, d).float() | |
| cols = [hot(didx * K + ridx, d * K).float(), dh * lp[:, None], dh * lp_top[:, None], dh * eq[:, None].float(), hot(m, NM).float()] | |
| if self.ling: | |
| bucket = bucket if torch.is_tensor(bucket) else torch.full((n,), bucket, dtype=torch.long, device=tok.device) | |
| ch = hot(self.t.gclass[tok], 3).float() | |
| cols += [ch, hot(self.t.script[tok], 3).float(), self.t.length[tok][:, None], ch * lp[:, None], | |
| hot(self.t.code_hi[ptok] + self.t.code[tok], NCODE * NCODE).float(), hot(bucket, NQ).float()] | |
| return torch.cat(cols, 1) | |
| def copy_matrix(self, tok, prev, m, j, bucket) -> torch.Tensor: | |
| cols = [hot((m - 1) * COPY + j, 3 * COPY).float()] | |
| if self.ling: | |
| cols += [hot(self.t.gclass[tok], 3).float(), hot(self.t.script[tok], 3).float(), self.t.length[tok][:, None], | |
| hot(self.t.code_hi[prev] + self.t.code[tok], NCODE * NCODE).float(), hot(bucket, NQ).float()] | |
| return torch.cat(cols, 1) | |
| # ---- folding the fitted weights into tables ---- | |
| def fold(self, head: torch.nn.Linear, copy: torch.nn.Linear) -> None: | |
| d = self.depth | |
| w, b = head.weight.detach()[0], float(head.bias.detach()) | |
| self.w_head, self.b_head = w, b | |
| o = 0 | |
| self.wB, o = w[o : o + d * K] + b, o + d * K | |
| self.wS, o = w[o : o + d], o + d | |
| self.wT, o = w[o : o + d], o + d | |
| self.wE, o = w[o : o + d], o + d | |
| self.wM, o = w[o : o + NM].tolist(), o + NM | |
| self.wQ = [0.0] * NQ | |
| if self.ling: | |
| w_cls, o = w[o : o + 3], o + 3 | |
| w_scr, o = w[o : o + 3], o + 3 | |
| w_len, o = w[o], o + 1 | |
| w_lpc, o = w[o : o + 3], o + 3 | |
| self.wpair, o = w[o : o + NCODE * NCODE].contiguous(), o + NCODE * NCODE | |
| self.wQ, o = w[o : o + NQ].tolist(), o + NQ | |
| self.tab = torch.stack([w_cls[self.t.gclass] + w_scr[self.t.script] + w_len * self.t.length, w_lpc[self.t.gclass]], 1).contiguous() | |
| assert o == w.shape[0] | |
| w, b = copy.weight.detach()[0], float(copy.bias.detach()) | |
| self.w_copy, self.b_copy = w, b | |
| self.cB = [[0.0] * COPY] + [[float(w[(m - 1) * COPY + j]) + b for j in range(COPY)] for m in (1, 2, 3)] | |
| o = 3 * COPY | |
| self.cTok, self.cPair, self.cQ = None, None, [0.0] * NQ | |
| if self.ling: | |
| w_cls, o = w[o : o + 3], o + 3 | |
| w_scr, o = w[o : o + 3], o + 3 | |
| w_len, o = w[o], o + 1 | |
| self.cTok = (w_cls[self.t.gclass] + w_scr[self.t.script] + w_len * self.t.length).tolist() | |
| self.cPair, o = w[o : o + NCODE * NCODE].tolist(), o + NCODE * NCODE | |
| self.cQ, o = w[o : o + NQ].tolist(), o + NQ | |
| assert o == w.shape[0] | |
| def budget_constants(self, budget: int) -> dict: | |
| if budget not in self.const: | |
| sizes = level_sizes(self.depth, budget) | |
| didx = torch.cat([torch.full((n,), d, dtype=torch.long, device=self.device) for d, n in enumerate(sizes)]) | |
| ridx = torch.arange(didx.shape[0], device=self.device) % K | |
| n_all = didx.shape[0] | |
| self.const[budget] = {"sizes": sizes, "n": n_all, "didx": didx, "ridx": ridx, "bias": self.wB[didx * K + ridx].contiguous(), | |
| "slope": self.wS[didx].contiguous(), "wtop": self.wT[didx].contiguous(), "weq": self.wE[didx].contiguous(), | |
| "cpar": torch.tensor([-1] + [n_all + j for j in range(COPY - 1)], dtype=torch.long, device=self.device)} | |
| return self.const[budget] | |
| # ---- the decoder's side ---- | |
| def copy_scores(self, x1: int, branch: list, m: int, bucket: int) -> list: | |
| """Path scores of the copied nodes: summed log-probabilities of being accepted given the node before.""" | |
| out, s, prev, row, code = [], 0.0, x1, self.cB[m], self.t.code_list | |
| for j, tk in enumerate(branch): | |
| logit = row[j] | |
| if self.ling: | |
| logit += self.cTok[tk] + self.cPair[code[prev] * NCODE + code[tk]] + self.cQ[bucket] | |
| s += logit if logit < -30.0 else -math.log1p(math.exp(-logit)) | |
| out.append(s) | |
| prev = tk | |
| return out | |
| def select(self, drafter: TreeDrafter, trunk: torch.Tensor, nxt: torch.Tensor, budget: int, branch: list, cs: list, m: int, bucket: int, | |
| check: bool = False) -> tuple: | |
| """The `budget` best nodes among the head candidates and the copied branch: tokens, and parents as indices into | |
| the returned nodes (-1 for the exact next token), parents before children.""" | |
| c0 = self.budget_constants(budget) | |
| toks, lps, ptoks, pars, keeps = expand(drafter, trunk, nxt, budget, self.ar) | |
| tok_all, lp_all = torch.cat(toks), torch.cat(lps) | |
| lp_top = lp_all.view(-1, K)[:, 0].repeat_interleave(K) | |
| if self.ling: | |
| ptok_all = torch.cat(ptoks).repeat_interleave(K) | |
| g = self.tab[tok_all] | |
| logit = c0["bias"] + g[:, 0] | |
| logit += self.wpair[self.t.code_hi[ptok_all] + self.t.code[tok_all]] | |
| logit.addcmul_(lp_all, c0["slope"] + g[:, 1]) | |
| else: | |
| logit = torch.addcmul(c0["bias"], lp_all, c0["slope"]) | |
| logit.addcmul_(lp_top, c0["wtop"]) | |
| c = len(branch) | |
| if c: | |
| bt = torch.tensor([branch + [-1] * (COPY - c), cs + [0.0] * (COPY - c)], dtype=torch.float32, device=self.device) | |
| logit += c0["weq"] * (tok_all == bt[0][c0["didx"]]) | |
| logit += self.wM[m] + self.wQ[bucket] | |
| if check: | |
| eq = tok_all == bt[0][c0["didx"]] if c else torch.zeros_like(tok_all, dtype=torch.bool) | |
| ptok_all = torch.cat(ptoks).repeat_interleave(K) | |
| ref = self.head_matrix(tok_all, ptok_all, lp_all, lp_top, c0["didx"], c0["ridx"], eq, m, bucket) @ self.w_head + self.b_head | |
| assert float((ref - logit).abs().max()) < 1e-3, "folded head logits differ from the explicit features" | |
| if c: | |
| dev = self.device | |
| tk = torch.tensor(branch, device=dev) | |
| pv = torch.tensor([int(nxt)] + branch[:-1], device=dev) | |
| x = self.copy_matrix(tk, pv, torch.full((c,), m, device=dev), torch.arange(c, device=dev), torch.full((c,), bucket, device=dev)) | |
| ref = torch.nn.functional.logsigmoid(x @ self.w_copy + self.b_copy).cumsum(0) | |
| assert float((ref - torch.tensor(cs, device=dev)).abs().max()) < 1e-3, "folded copy scores differ from the explicit features" | |
| ls = torch.nn.functional.logsigmoid(logit) | |
| s_prev, off = ls[:K], K | |
| parts = [s_prev] | |
| for d in range(1, self.depth): | |
| n_d, kp = c0["sizes"][d], keeps[d - 1] | |
| s_prev = (ls[off : off + n_d].view(-1, K) + (s_prev if kp is None else s_prev[kp])[:, None]).reshape(-1) | |
| parts.append(s_prev) | |
| off += n_d | |
| if c: | |
| parts.append(bt[1, :c]) | |
| tok_all = torch.cat([tok_all, bt[0, :c].long()]) | |
| pars = pars + [c0["cpar"][:c]] | |
| chosen = torch.argsort(torch.cat(parts), descending=True, stable=True)[:budget].sort().values # ties keep the earlier node | |
| where = torch.full((c0["n"] + COPY + 1,), -1, dtype=torch.long, device=self.device) | |
| where[chosen] = self.arange[: chosen.shape[0]] | |
| return tok_all[chosen], where[torch.cat(pars)[chosen]] | |
| def tokens_since_start(start: list, tokens: list, count: int = 0) -> int: | |
| for t in tokens: | |
| count = 0 if start[t] else count + 1 | |
| return count | |
| def alloc_decode(backbone, drafter: TreeDrafter, alloc: LinearAllocator, prompt: list, n_new: int, budget: int, check: bool = False) -> tuple: | |
| """Lossless decoding with the allocator. Returns the generated tokens, passes, committed tokens, seconds per step.""" | |
| past, z, nxt = prefill(backbone, prompt) | |
| index = SuffixIndex(prompt) | |
| start = alloc.start | |
| since = tokens_since_start(start, prompt) | |
| sec = dict.fromkeys(STEPS, 0.0) | |
| gen, passes, length = [], 0, len(prompt) | |
| dev = z.device | |
| def lap(step: str, t: float) -> float: | |
| torch.cuda.synchronize() | |
| now = time.perf_counter() | |
| sec[step] += now - t | |
| return now | |
| torch.cuda.synchronize() | |
| t = time.perf_counter() | |
| while len(gen) < n_new: | |
| x1 = int(nxt) | |
| index.add(x1) | |
| branch, m = index.branch(COPY) | |
| bucket = min(0 if start[x1] else since + 1, NQ - 1) | |
| cs = alloc.copy_scores(x1, branch, m, bucket) if branch else None | |
| t = lap("copy_lookup", t) | |
| tok, par = alloc.select(drafter, drafter.stack.trunk_states(z[None]), nxt, budget, branch, cs, m, bucket, check) | |
| t = lap("draft", t) | |
| q = 1 + tok.shape[0] | |
| inp = torch.cat([nxt.view(1), tok]) | |
| parent = torch.cat([alloc.zero1, par + 1]) | |
| anc = torch.eye(q, dtype=torch.bool, device=dev) | |
| for _ in range(max(drafter.depth, len(branch))): | |
| anc = anc | anc[parent] | |
| mask = torch.zeros(1, 1, q, length + q, device=dev) | |
| mask[0, 0, :, length:].masked_fill_(~anc, torch.finfo(mask.dtype).min) | |
| pos = (length + anc.sum(1) - 1)[None] | |
| t = lap("build_inputs", t) | |
| out = backbone.model(input_ids=inp[None], past_key_values=past, attention_mask=mask, position_ids=pos, use_cache=True) | |
| hidden = out.last_hidden_state[0] | |
| preds = backbone.lm_head(hidden).argmax(-1) | |
| t = lap("backbone_pass", t) | |
| ok = inp == preds[parent] | |
| ok[0] = True | |
| for _ in range(max(drafter.depth, len(branch))): | |
| ok = ok & ok[parent] | |
| best = (ok * anc.sum(1)).argmax() | |
| path = anc[best].nonzero()[:, 0] | |
| past = out.past_key_values | |
| select_cache(past, length, path) | |
| accepted = inp[path].tolist() | |
| gen.extend(accepted) | |
| for token in accepted[1:]: | |
| index.add(token) | |
| since = tokens_since_start(start, accepted, since) | |
| nxt, z = preds[best], hidden[best] | |
| length += len(accepted) | |
| passes += 1 | |
| t = lap("accept", t) | |
| return gen[:n_new], passes, len(gen), sec | |
| def collect(backbone, drafter: TreeDrafter, tables: Tables, docs: list, look: int) -> tuple: | |
| """Raw fitting rows from teacher-forced positions: head nodes and copied nodes whose parent is accepted.""" | |
| dev, depth, ar = DEVICE, drafter.depth, Aranges(DEVICE) | |
| sizes = level_sizes(depth, POOL_FIT) | |
| didx = torch.cat([torch.full((n,), d, dtype=torch.long, device=dev) for d, n in enumerate(sizes)]) | |
| ridx = torch.arange(didx.shape[0], device=dev) % K | |
| head = {k: [] for k in ("tok", "ptok", "lp", "lp_top", "didx", "ridx", "eq", "m", "bucket", "y", "doc")} | |
| copy = {k: [] for k in ("tok", "prev", "m", "j", "bucket", "y", "doc")} | |
| for di, (prompt, cont) in enumerate(docs): | |
| horizon = min(64, len(cont) - look + 1) # every scored position has COPY true tokens after it | |
| if horizon < 1: | |
| continue | |
| seq = prompt + cont | |
| p0 = len(prompt) - 1 | |
| trunk = drafter.stack.trunk_states(backbone.model(input_ids=torch.tensor([seq], device=dev)).last_hidden_state[0, p0 : p0 + horizon]) | |
| seq_t = torch.tensor(seq, device=dev) | |
| index = SuffixIndex(prompt) | |
| since = tokens_since_start(tables.start, prompt) | |
| for j in range(horizon): | |
| x1 = seq[p0 + 1 + j] | |
| index.add(x1) | |
| branch, m = index.branch(COPY) | |
| since = 0 if tables.start[x1] else since + 1 | |
| bucket = min(since, NQ - 1) | |
| truth = seq_t[p0 + 2 + j : p0 + 2 + j + max(COPY, depth)] | |
| toks, lps, ptoks, pars, _ = expand(drafter, trunk[j : j + 1], seq_t[p0 + 1 + j], POOL_FIT, ar) | |
| tok_all, lp_all, par_all = torch.cat(toks), torch.cat(lps), torch.cat(pars) | |
| ptok_all = torch.cat(ptoks).repeat_interleave(K) | |
| lp_top = lp_all.view(-1, K)[:, 0].repeat_interleave(K) | |
| y = tok_all == truth[didx] | |
| acc = torch.zeros_like(y) | |
| rows = torch.zeros_like(y) | |
| off = 0 | |
| for d, n in enumerate(sizes): | |
| sl = slice(off, off + n) | |
| pa = torch.ones(n, dtype=torch.bool, device=dev) if d == 0 else acc[par_all[sl]] | |
| rows[sl] = pa | |
| acc[sl] = pa & y[sl] | |
| off += n | |
| c = len(branch) | |
| eq = torch.zeros_like(y) | |
| if c: | |
| bpad = torch.tensor(branch + [-1] * (COPY - c), device=dev) | |
| eq = tok_all == bpad[didx] | |
| ok = True | |
| for jj, tk in enumerate(branch): | |
| if not ok: | |
| break | |
| hit = tk == seq[p0 + 2 + j + jj] | |
| for k, v in zip(("tok", "prev", "m", "j", "bucket", "y", "doc"), (tk, x1 if jj == 0 else branch[jj - 1], m, jj, bucket, int(hit), di)): | |
| copy[k].append(v) | |
| ok = hit | |
| n_rows = int(rows.sum()) | |
| for k, v in (("tok", tok_all), ("ptok", ptok_all), ("lp", lp_all), ("lp_top", lp_top), ("didx", didx), ("ridx", ridx), ("eq", eq), ("y", y)): | |
| head[k].append(v[rows]) | |
| for k, v in (("m", m), ("bucket", bucket), ("doc", di)): | |
| head[k].append(torch.full((n_rows,), v, dtype=torch.long, device=dev)) | |
| return {k: torch.cat(v) for k, v in head.items()}, {k: torch.tensor(v, device=dev) for k, v in copy.items()} | |
| def fit(alloc: LinearAllocator, head: dict, copy: dict, is_val: torch.Tensor, seed: int) -> dict: | |
| """Fits the two regressions of one allocator and folds them; returns validation log-losses and the weights.""" | |
| xh = alloc.head_matrix(head["tok"], head["ptok"], head["lp"], head["lp_top"], head["didx"], head["ridx"], head["eq"], head["m"], head["bucket"]) | |
| yh, vh = head["y"].float(), is_val[head["doc"]] | |
| xc = alloc.copy_matrix(copy["tok"], copy["prev"], copy["m"], copy["j"], copy["bucket"]) | |
| yc, vc = copy["y"].float(), is_val[copy["doc"]] | |
| m_head, loss_head = fit_model("lr", xh[~vh], yh[~vh], xh[vh], yh[vh], seed) | |
| m_copy, loss_copy = fit_model("lr", xc[~vc], yc[~vc], xc[vc], yc[vc], seed) | |
| alloc.fold(m_head, m_copy) | |
| return {"head_rows": int(xh.shape[0]), "copy_rows": int(xc.shape[0]), "head_features": int(xh.shape[1]), "copy_features": int(xc.shape[1]), | |
| "head_validation_log_loss": loss_head, "copy_validation_log_loss": loss_copy, | |
| "head_accept_rate": float(yh.mean()), "copy_accept_rate": float(yc.mean()), | |
| "head_weight": m_head.weight.detach()[0].tolist(), "head_bias": float(m_head.bias.detach()), | |
| "copy_weight": m_copy.weight.detach()[0].tolist(), "copy_bias": float(m_copy.bias.detach())} | |
| def feature_names(depth: int, ling: bool) -> dict: | |
| head = ([f"bias_depth{d + 1}_rank{r}" for d in range(depth) for r in range(K)] + [f"log_prob_depth{d + 1}" for d in range(depth)] | |
| + [f"top_sibling_log_prob_depth{d + 1}" for d in range(depth)] + [f"equals_copied_token_depth{d + 1}" for d in range(depth)] | |
| + [f"matched_suffix_{m}" for m in range(NM)]) | |
| copy = [f"matched_suffix_{m}_position_{j + 1}" for m in (1, 2, 3) for j in range(COPY)] | |
| if ling: | |
| cls, scr = ("inside_word", "function_word_start", "group_start"), ("other", "devanagari", "latin") | |
| tok = [f"class_{c}" for c in cls] + [f"script_{s}" for s in scr] + ["length_chars_over_8"] | |
| pair = [f"parent_{scr[a // 2]}_{'start' if a % 2 else 'inside'}_x_token_{scr[b // 2]}_{'start' if b % 2 else 'inside'}" for a in range(NCODE) for b in range(NCODE)] | |
| since = [f"tokens_since_word_start_{q}" for q in range(NQ)] | |
| head += tok + [f"log_prob_x_class_{c}" for c in cls] + pair + since | |
| copy += tok + pair + since | |
| return {"head": head, "copy": copy} | |
| def main() -> None: | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("--name", required=True) | |
| p.add_argument("--scheme", default="", help="Devanagari, ITRANS, IAST or ISO for the Hindi function-word list; empty for English") | |
| p.add_argument("--seed", default="0") | |
| 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("--train-ids", required=True) | |
| p.add_argument("--heldout", required=True) | |
| p.add_argument("--spec-docs", type=int, default=256) | |
| p.add_argument("--extra-fit-docs", type=int, default=256) | |
| p.add_argument("--budgets", default="8,16,24") | |
| p.add_argument("--heads", default="3,5", help="look-ahead heads of the stacks to run: 3, 5 or 3,5") | |
| p.add_argument("--copy-length", type=int, default=5, help="tokens in the copied branch") | |
| p.add_argument("--anchors", default="", help="the fixed rule with other branch lengths, as length:budget, comma-separated") | |
| p.add_argument("--out", required=True) | |
| p.add_argument("--coef-out", required=True, help="coefficient file; {heads} in it is replaced by 3 or 5") | |
| args = p.parse_args() | |
| t0 = time.perf_counter() | |
| global COPY | |
| COPY = args.copy_length | |
| look = max(LOOKAHEAD, COPY + 2) | |
| budgets = [int(x) for x in args.budgets.split(",")] | |
| anchors = [tuple(int(v) for v in x.split(":")) for x in args.anchors.split(",") if x] | |
| 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 phase5_shortlist_pilot import successor_table | |
| 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 | |
| unembed = backbone.lm_head.weight | |
| starts = pb.word_start_table(tok) | |
| is_start = np.array(starts + [False] * (vocab - len(starts))) | |
| script, length = vocab_tables(tok, vocab) | |
| train_ids = np.load(args.train_ids) | |
| gclass = np.where(is_start, wg.GROUP_START, wg.WITHIN_WORD).astype(np.int64) | |
| if args.scheme: | |
| gclass, _ = wg.token_group_table(train_ids, is_start, tok, wg.function_words(args.scheme)) | |
| tables = Tables(is_start, gclass, script, length, DEVICE) | |
| succ, freq_rank = successor_table(train_ids, vocab) | |
| eos = backbone.generation_config.eos_token_id | |
| eos_ids = set(eos if isinstance(eos, list) else [eos]) | |
| texts = load_heldout_texts(args.heldout) | |
| def continuations(chunk: list) -> list: # the usable documents are those of the other scripts, whatever the branch length | |
| pairs = pb.generate_continuations(backbone, tok, chunk, 256, 64 + look, 16, eos_ids) | |
| return [(pr, c) for pr, c in pairs if min(64, len(c) - LOOKAHEAD + 1) >= 1] | |
| first = continuations(texts[: args.spec_docs]) | |
| extra = continuations(texts[args.spec_docs : args.spec_docs + args.extra_fit_docs]) | |
| test = [(prompt, min(64, min(len(c), 64 + LOOKAHEAD) - LOOKAHEAD + 1)) for prompt, c in first[1::2]] | |
| low = np.array([ngram_share(c[:64], None) <= 0.1 for _, c in first[1::2]]) # documents whose continuation hardly loops | |
| calib = first[0::2] + extra | |
| is_val = torch.tensor([i % 5 == 4 for i in range(len(calib))], device=DEVICE) # every fifth calibration document validates | |
| print(f"{args.name} seed {args.seed}: {len(test)} test documents ({int(low.sum())} with at most 10% looping), {len(calib)} calibration documents " | |
| f"({int(is_val.sum())} for validation), copied branch of {COPY}, {time.perf_counter() - t0:.0f}s", flush=True) | |
| stacks, fits = {}, {} | |
| for label, root, n_heads in (("3 heads", args.base_root, 4), ("5 heads", args.deep_root, 6)): | |
| if str(n_heads - 1) not in args.heads.split(","): | |
| continue | |
| stack = load_arm(backbone, Path(root) / f"{args.name}_seed{args.seed}" / f"{args.arm}.pt", True, n_heads=n_heads) | |
| drafter = TreeDrafter(stack, n_heads - 1, unembed, succ, freq_rank) | |
| head, copy = collect(backbone, drafter, tables, calib, look) | |
| allocs, fits[label] = {}, {} | |
| for s in SETS: | |
| allocs[s] = LinearAllocator(n_heads - 1, tables, s == "ling", DEVICE) | |
| fits[label][s] = fit(allocs[s], head, copy, is_val, int(args.seed)) | |
| f = fits[label][s] | |
| print(f"{label}, {s}: head rows {f['head_rows']} (accepted {f['head_accept_rate']:.3f}), {f['head_features']} features, validation log-loss " | |
| f"{f['head_validation_log_loss']:.4f}; copied rows {f['copy_rows']} (accepted {f['copy_accept_rate']:.3f}), {f['copy_features']} features, " | |
| f"validation log-loss {f['copy_validation_log_loss']:.4f}; {time.perf_counter() - t0:.0f}s", flush=True) | |
| stacks[label] = (drafter, allocs) | |
| coef = {"name": args.name, "seed": args.seed, "stack": label, "copied_tokens": COPY, "fit_pool_per_level": POOL_FIT, "calibration_documents": len(calib), | |
| "sets": {s: {"feature_names": feature_names(n_heads - 1, s == "ling"), **fits[label][s]} for s in SETS}} | |
| path = Path(args.coef_out.replace("{heads}", str(n_heads - 1))) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_text(json.dumps(coef, indent=1)) | |
| del head, copy | |
| kinds = ("fixed rule", "allocator, confidence + source", "allocator, + linguistic") | |
| systems = [(f"{label}, {n} verified, {kind}", label, n, kind) for label in stacks for n in budgets for kind in kinds] | |
| systems += [(f"{label}, {n} verified, fixed rule with a copied branch of {length}", label, n, length) for label in stacks for length, n in anchors] | |
| def run(label: str, n: int, kind: str, prompt: list, n_new: int, check: bool = False) -> tuple: | |
| drafter, allocs = stacks[label] | |
| if kind == kinds[0] or isinstance(kind, int): # an int is the branch length of an anchor | |
| gen, passes, committed, steps, _ = tree_decode(backbone, drafter, prompt, n_new, n, COPY if kind == kinds[0] else kind, True) | |
| return gen, passes, committed, steps | |
| return alloc_decode(backbone, drafter, allocs["conf" if kind == kinds[1] else "ling"], prompt, n_new, n, check) | |
| stats = {name: {"seconds": 0.0, "tokens": 0, "committed": 0, "passes": 0, "identical_docs": 0, "token_match": 0, "steps": dict.fromkeys(STEPS, 0.0), | |
| "per_document": []} for name, *_ in systems} | |
| base = {"seconds": 0.0, "tokens": 0, "words": 0, "per_document": []} | |
| greedy(backbone, test[0][0], 8) | |
| for name, label, n, kind in systems: # warm-up, not timed; the allocators check folded against explicit features here | |
| run(label, n, kind, test[0][0], 16, check=True) | |
| run(label, n, kind, test[0][0], 8) | |
| print(f"folded scores equal the explicit features on the warm-up rounds; timing starts, {time.perf_counter() - t0:.0f}s", flush=True) | |
| for i, (prompt, n_new) in enumerate(test): | |
| ref, _, sec = greedy(backbone, prompt, n_new) | |
| words = len(tok.decode(ref).split()) | |
| base["seconds"] += sec | |
| base["tokens"] += len(ref) | |
| base["words"] += words | |
| base["per_document"].append([sec, len(ref), words]) | |
| for name, label, n, kind in systems: | |
| gen, passes, committed, steps = run(label, n, kind, prompt, n_new) | |
| s = stats[name] | |
| total = sum(steps.values()) | |
| s["seconds"] += total | |
| s["tokens"] += len(gen) | |
| s["committed"] += committed | |
| s["passes"] += passes | |
| s["identical_docs"] += int(gen == ref) | |
| s["token_match"] += sum(int(x == y) for x, y in zip(gen, ref)) | |
| for k, v in steps.items(): | |
| s["steps"][k] += v | |
| s["per_document"].append([total, committed, passes]) | |
| if i in (0, 4, 19) or (i + 1) % 40 == 0: | |
| line = "; ".join(f"{name}: {1000 * s['seconds'] / s['committed']:.2f} ms/token, {s['committed'] / s['passes']:.3f} tokens/pass" | |
| for name, s in list(stats.items())[:3]) | |
| print(f" after {i + 1} documents, {time.perf_counter() - t0:.0f}s: greedy {1000 * base['seconds'] / base['tokens']:.2f} ms/token; {line}; " | |
| f"identical at worst {min(x['identical_docs'] for x in stats.values())}/{i + 1}", flush=True) | |
| words_per_token = base["words"] / base["tokens"] | |
| base_ms = 1000 * base["seconds"] / base["tokens"] | |
| res = {"name": args.name, "seed": args.seed, "arm": args.arm, "gpu": torch.cuda.get_device_name(DEVICE), "docs": len(test), "documents_with_little_looping": int(low.sum()), | |
| "candidates_per_node": K, "copied_tokens": COPY, "fit_pool_per_level": POOL_FIT, "words_per_token": words_per_token, | |
| "fit": {label: {s: {k: v for k, v in f.items() if not k.endswith(("weight", "bias"))} for s, f in d.items()} for label, d in fits.items()}, | |
| "greedy": {"ms_per_token": base_ms, "ms_per_word": base_ms / words_per_token, "per_document": base["per_document"]}, "systems": {}, "paired": {}} | |
| print(f"{args.name}: greedy {base_ms:.2f} ms/token, {base_ms / words_per_token:.2f} ms/word", flush=True) | |
| g_all = np.array(base["per_document"], dtype=float) | |
| for name, label, n, kind in systems: | |
| s = stats[name] | |
| ms, per_pass = 1000 * s["seconds"] / s["committed"], {k: 1000 * v / s["passes"] for k, v in s["steps"].items()} | |
| d_all = np.array(s["per_document"], dtype=float) | |
| low_speedup = float((g_all[low, 0].sum() / g_all[low, 1].sum()) / (d_all[low, 0].sum() / d_all[low, 1].sum())) | |
| fixed = stats[f"{label}, {n} verified, {kinds[0]}"] | |
| row = {"ms_per_token": ms, "ms_per_word": ms / words_per_token, "speedup": base_ms / ms, "tokens_per_pass": s["committed"] / s["passes"], | |
| "ms_per_pass": 1000 * s["seconds"] / s["passes"], "ms_per_pass_by_step": per_pass, | |
| "ms_per_pass_over_fixed_rule": 1000 * (s["seconds"] / s["passes"] - fixed["seconds"] / fixed["passes"]), | |
| "speedup_on_documents_with_little_looping": low_speedup, | |
| "tokens_per_pass_on_documents_with_little_looping": float(d_all[low, 1].sum() / d_all[low, 2].sum()), | |
| "identical_docs": s["identical_docs"], "token_match": s["token_match"] / s["tokens"], "per_document": s["per_document"]} | |
| res["systems"][name] = row | |
| print(f" {name:52s} {ms:6.2f} ms/token {base_ms / ms:.2f}x {row['tokens_per_pass']:.3f} tokens/pass {row['ms_per_pass']:.2f} ms/pass " | |
| f"({row['ms_per_pass_over_fixed_rule']:+.2f} vs fixed) little looping {low_speedup:.2f}x identical {s['identical_docs']}/{len(test)} " | |
| + " ".join(f"{k} {v:.2f}" for k, v in per_pass.items()), flush=True) | |
| for label in stacks: | |
| for n in budgets: | |
| a = {kind: np.array(stats[f"{label}, {n} verified, {kind}"]["per_document"], dtype=float) for kind in kinds} | |
| out = {} | |
| for x, y in ((kinds[2], kinds[1]), (kinds[1], kinds[0]), (kinds[2], kinds[0])): | |
| out[f"{x} vs {y}"] = {"tokens_per_pass_percent": bootstrap_gain(a[x][:, [1, 2]], a[y][:, [1, 2]]), | |
| "tokens_per_second_percent": bootstrap_gain(a[x][:, [1, 0]], a[y][:, [1, 0]])} | |
| res["paired"][f"{label}, {n} verified"] = out | |
| for k, v in out.items(): | |
| tp, ts = v["tokens_per_pass_percent"], v["tokens_per_second_percent"] | |
| print(f" {label}, {n} verified, {k}: tokens per pass {tp[0]:+.2f}% [{tp[1]:+.2f}, {tp[2]:+.2f}] " | |
| f"tokens per second {ts[0]:+.2f}% [{ts[1]:+.2f}, {ts[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() | |