"""Gated two-axis tree (inference-only): share the N-node budget between a WIDTH axis (Hydra confidence tree, sibling added only where the first-draft top1-top2 margin < tau_w) and a DEPTH axis (word-head whole-word branch, added only where the word head's calibrated prob > tau_d). Thresholds (tau_w, tau_d) and the hybrid offset are fit on EVEN docs to maximize tokens/pass, tested on ODD. Conditions on the same odd docs at N=8 and 16: (1) width only = confidence tree (2) depth only = word-head branches only (no confidence tree) (3) ungated hybrid = joint top-N by path probability (phase5_vac_sim.simulate) (4) gated two-axis = width+depth gates above, budget to whichever axis has higher marginal yield Reuses the VAC tree dump (same docs as Job A) + the trained word head. """ import argparse import json import pickle import sys from pathlib import Path 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 phase4_boundary_decoding as pb from phase5_tree_draft import path_scores, accepted_depth, replay, bootstrap_gain, K, DEPTH import phase5_vac_sim as V from phase5_wordhead_eval import word_at DEVICE = "cuda:0" TOPK = 4 BUDGETS = (8, 16, 24) # node indices whose top-level (depth-1) rank != 0 (the "width siblings" of the first draft) _R0 = np.array([(i if i < K else (i - K) // K if i < K + K * K else (i - K - K * K) // (K * K)) for i in range(K + K * K + K ** 3)]) SIBLING_MASK = _R0 != 0 def round_gated(j, budget, conf84, margin, ranks, cont, horizon, tail, tail_prob, tau_w, tau_d, width_on, depth_on): """Committed draft depth at round position j under the two gated axes. Returns (depth, axis).""" scores = conf84.copy() if not width_on: scores = scores.copy(); scores[SIBLING_MASK] = -np.inf # chain only (no width) elif tau_w is not None and margin >= tau_w: scores = scores.copy(); scores[SIBLING_MASK] = -np.inf # confident -> no sibling width here use_tail = depth_on and tail is not None and (tau_d is None or tail_prob > tau_d) allscores = scores if not use_tail else np.concatenate([scores, np.full(len(tail), 1e9)]) # tail always selected if gated-in k = min(budget, int(np.isfinite(allscores).sum())) finite = np.where(np.isfinite(allscores))[0] sel = set(finite[np.argsort(-allscores[finite])[:k]].tolist()) r = ranks[j].clip(min=0); valid = ranks[j] >= 0 didx = [int(r[0]), K + int(r[0]) * K + int(r[1]), K + K * K + (int(r[0]) * K + int(r[1])) * K + int(r[2])] dd = 0 for d in range(DEPTH): if valid[d] and didx[d] in sel: dd = d + 1 else: break td = 0 if use_tail: for d in range(len(tail)): tp = j + 1 + d if (84 + d) in sel and tp < horizon and int(cont[tp]) == int(tail[d]): td = d + 1 else: break if td > dd: return td, "depth" return dd, "width" def walk_gated(doc, budget, conf, margin, tails, tau_w, tau_d, width_on, depth_on): cont, ranks, horizon = doc["cont"], doc["ranks"], doc["horizon"] j = c = r = 0 wtok = wfire = dfire = 0 while j < horizon: tail = tp = None if j in tails: tail, pr = tails[j]; tp = float(pr[0]) dep, axis = round_gated(j, budget, conf[j], float(margin[j]), ranks, cont, horizon, tail, tp, tau_w, tau_d, width_on, depth_on) if width_on and tau_w is not None and float(margin[j]) < tau_w: wfire += 1 if tail is not None and (tau_d is None or tp > tau_d): dfire += 1 if axis == "depth": wtok += dep c += 1 + dep; r += 1; j += 1 + dep return c, r, wtok, wfire, dfire def main() -> None: p = argparse.ArgumentParser(description=__doc__) p.add_argument("--tree-dump", required=True) p.add_argument("--wordhead", required=True) p.add_argument("--out", required=True) p.add_argument("--backbone", default="meta-llama/Llama-3.2-1B") p.add_argument("--dtype", default="float32") p.add_argument("--yield-words-per-token", type=float, default=0.380) args = p.parse_args() from transformers import AutoModelForCausalLM, AutoTokenizer from src.models.heads import ResBlock import torch.nn as nn tok = AutoTokenizer.from_pretrained(args.backbone) backbone = AutoModelForCausalLM.from_pretrained(args.backbone, dtype=getattr(torch, args.dtype)).to(DEVICE).eval() starts = pb.word_start_table(tok) is_start = np.array(starts + [False] * (backbone.config.vocab_size - len(starts))) wh = torch.load(args.wordhead, map_location=DEVICE, weights_only=False) words = wh["words"]; word2class = {w: i for i, w in enumerate(words)}; OOV = len(words) class WordHead(nn.Module): def __init__(s, h, n): super().__init__(); s.resblock = ResBlock(h); s.out = nn.Linear(h, n + 1) def forward(s, x): return s.out(s.resblock(x)) head = WordHead(wh["hidden_size"], wh["n_words"]).to(DEVICE).eval() head.load_state_dict(wh["state_dict"]) with open(args.tree_dump, "rb") as f: dump = pickle.load(f) docs = dump["docs"] conf = [path_scores(d["lps"]) for d in docs] margin = [d["lps"][0][:, 0] - d["lps"][0][:, 1] for d in docs] # depth-1 top1-top2 logprob margin import functools @functools.lru_cache(maxsize=None) def class_tokens(c): # predicted word class -> its token chain (re-encode; lossless for this data) return tuple(tok.encode(words[c], add_special_tokens=False)) def word_spans(ids): s = [i for i in range(len(ids)) if is_start[ids[i]]] if not s or s[0] != 0: s = [0] + s return [(s[k], s[k + 1] if k + 1 < len(s) else len(ids)) for k in range(len(s))] # DEPLOYABLE tails: at each word start draft the head's TOP-1 predicted word (not the truth), # carrying the head's top-1 probability as the gate. round_gated/simulate verify the predicted # tokens against the continuation and charge the branch's nodes to the budget even when wrong. tails_all, seen_hits_all = [], [] with torch.no_grad(): for d in docs: prompt, cont, horizon = d["prompt"], d["cont"], d["horizon"] full = torch.tensor([prompt + cont], device=DEVICE) hid = backbone.model(input_ids=full).last_hidden_state[0] base = len(prompt) full_ids = list(prompt) + list(cont) seen_flag, seen_strs = {}, set() # was each word's surface already in the context? for s, e in word_spans(full_ids): wsurf = tok.decode(full_ids[s:e]) seen_flag[s] = wsurf in seen_strs seen_strs.add(wsurf) js, feats, wc = [], [], [] for j in range(horizon): w = word_at(cont, j + 1, is_start, horizon) if w is None or base + j >= hid.shape[0]: continue js.append(j); feats.append(base + j) wc.append(word2class.get(tok.decode(w), OOV)) tails, recs = {}, [] if js: logits = head(hid[torch.tensor(feats, device=DEVICE)]) top1 = logits.topk(TOPK, -1).indices.cpu().numpy()[:, 0] probs = torch.softmax(logits.float(), -1).cpu().numpy() for i, j in enumerate(js): t1 = int(top1[i]) if t1 != OOV: pt = class_tokens(t1) if pt: tails[j] = (list(pt), np.array([float(probs[i, t1])] + [0.9] * (len(pt) - 1))) recs.append((bool(seen_flag.get(len(prompt) + j + 1, False)), wc[i] != OOV and t1 == wc[i], wc[i] != OOV)) tails_all.append(tails) seen_hits_all.append(recs) fit, test = list(range(0, len(docs), 2)), list(range(1, len(docs), 2)) empty = [{} for _ in docs] y = args.yield_words_per_token def agg(rows): a = np.array([r[:2] for r in rows], float); return float(a[:, 0].sum() / a[:, 1].sum()) # seen-vs-new split of the word head's top-1 HITS (predicted == true word) on test docs: # a hit is a word the depth branch would fully accept. If most hits are already-in-context # words, the head is a learned (weaker) lookup; if new, it is complementary to a copy branch. sh = np.zeros((2, 3)) # [new, seen] x [top1_hits, invocab_positions, all_positions] for i in test: for seen_b, hit, inv in seen_hits_all[i]: sh[1 if seen_b else 0] += [int(hit), int(inv), 1] tot_hits = sh[:, 0].sum() seen_split = {"share_of_word_starts_seen_before": float(sh[1, 2] / max(1, sh[:, 2].sum())), "share_of_top1_hits_seen_before": float(sh[1, 0] / max(1, tot_hits))} for b, nm in [(0, "new_word"), (1, "seen_in_context")]: seen_split[nm] = {"top1_hit_rate_invocab": float(sh[b, 0] / max(1, sh[b, 1])), "positions": int(sh[b, 2]), "invocab_positions": int(sh[b, 1]), "top1_hits": int(sh[b, 0])} results = {"meta": {**dump["meta"], "topk": TOPK, "yield_words_per_token": y, "n_fit": len(fit), "n_test": len(test), "tail_rule": "deployable: head top-1 predicted word, re-encoded; gate on top-1 prob; " "tokens/pass counts only verified (accepted) tokens; branch nodes charged to budget", "copy_branch_bar_devanagari": {"copy_tok_per_pass": 3.579, "confidence_ref": 2.671, "note": "from coordinator's box, different doc set; indicative bar"}}, "word_head_seen_split": seen_split, "budgets": {}} tau_w_grid = [0.5, 1.0, 1.5, 2.0, 3.0, 5.0, 100.0] # 100 ~ always allow width tau_d_grid = [0.0, 0.1, 0.2, 0.3, 0.5, 0.7] for budget in BUDGETS: # (1) width only w1 = [replay(accepted_depth(conf[i], docs[i]["ranks"], budget)) for i in test] # (2) depth only w2 = [walk_gated(docs[i], budget, conf[i], margin[i], tails_all[i], None, None, False, True)[:2] for i in test] # (3) ungated hybrid off = V.fit_offset([docs[i] for i in fit], [conf[i] for i in fit], [tails_all[i] for i in fit], budget) w3 = [V.simulate(docs[i], budget, conf[i], tails_all[i], off)[:2] for i in test] # (4) gated two-axis: grid-search (tau_w, tau_d) on EVEN docs best = (-1, None, None) for tw in tau_w_grid: for td in tau_d_grid: rows = [walk_gated(docs[i], budget, conf[i], margin[i], tails_all[i], tw, td, True, True) for i in fit] t = agg(rows) if t > best[0]: best = (t, tw, td) tw, td = best[1], best[2] g = [walk_gated(docs[i], budget, conf[i], margin[i], tails_all[i], tw, td, True, True) for i in test] w4 = [x[:2] for x in g] wtok = sum(x[2] for x in g); wfire = sum(x[3] for x in g); dfire = sum(x[4] for x in g) tot_committed = sum(x[0] for x in w4) c1, c2, c3, c4 = agg(w1), agg(w2), agg(w3), agg(w4) results["budgets"][str(budget)] = { "width_only_confidence": {"tok_per_pass": c1, "words_per_pass": c1 * y}, "depth_only_wordhead": {"tok_per_pass": c2, "words_per_pass": c2 * y}, "ungated_hybrid": {"tok_per_pass": c3, "words_per_pass": c3 * y, "offset": off}, "gated_two_axis": {"tok_per_pass": c4, "words_per_pass": c4 * y, "tau_w": tw, "tau_d": td, "width_check_fires": wfire, "depth_check_fires": dfire, "committed_tokens_from_depth_axis": int(wtok), "total_committed": int(tot_committed)}, "gated_vs_width_pct": 100 * (c4 / c1 - 1), "gated_vs_ungated_pct": 100 * (c4 / c3 - 1), "gated_vs_width_boot": bootstrap_gain(np.array(w4, float), np.array(w1, float))} Path(args.out).parent.mkdir(parents=True, exist_ok=True) Path(args.out).write_text(json.dumps(results, indent=1, ensure_ascii=False)) ss = results["word_head_seen_split"] print(f"DEPLOYABLE tails (head top-1, pay-for-misses). Copy-branch bar (Deva, indicative): 3.579 vs conf 2.671") print(f"word-head top-1 hit rate: new {ss['new_word']['top1_hit_rate_invocab']:.3f} (n={ss['new_word']['invocab_positions']}) | " f"seen-in-ctx {ss['seen_in_context']['top1_hit_rate_invocab']:.3f} (n={ss['seen_in_context']['invocab_positions']}) | " f"{ss['share_of_top1_hits_seen_before']:.1%} of hits are seen-before words") for b in BUDGETS: r = results["budgets"][str(b)] print(f"N={b}: width {r['width_only_confidence']['tok_per_pass']:.4f} | depth {r['depth_only_wordhead']['tok_per_pass']:.4f} | " f"ungated {r['ungated_hybrid']['tok_per_pass']:.4f} | gated {r['gated_two_axis']['tok_per_pass']:.4f} " f"({r['gated_vs_width_pct']:+.1f}% vs width, tau_w={r['gated_two_axis']['tau_w']}, tau_d={r['gated_two_axis']['tau_d']}, " f"depth-axis tokens {r['gated_two_axis']['committed_tokens_from_depth_axis']})") if __name__ == "__main__": main()