File size: 20,189 Bytes
3ef3d94 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | """Phase 5: does a branch copied from the context recover what the draft heads miss?
phase5_margin_audit.py shows that the frozen model is often sure about a
word because the word already occurred in the context, and that the draft
heads miss those words: a head reads one hidden state and the embeddings of
the tokens drafted so far, so it cannot look the word up. Here a second
draft branch is taken from the context itself, with no training: find the
most recent earlier place where the last tokens of the text (three, else
two, else one) occurred, and propose the tokens that followed them
(prompt-lookup / suffix-match drafting). The heads' chain and the copied
branch are verified in the same backbone pass; the longer accepted branch is
committed.
A gated rule spends the copied branch only where it is likely to pay: a
suffix of at least two tokens matches and the head is unsure about its first
draft (top-1 minus top-2 probability below a threshold fitted on the
even-indexed documents); elsewhere the whole budget stays with the heads.
The output also has, per document, how much of the continuation is the model
looping on itself (tokens inside a 4-gram that occurred earlier in the same
continuation) and how much is taken from the prompt (inside a 4-gram of the
prompt).
Reported on the odd-indexed held-out documents, per seed: tokens per pass and
verified tokens per pass for the heads' chain, the copied branch alone, both
together, the confidence tree at the same budget, and the confidence tree
with a copied branch; and how often the first token is right at each
word-group position, for words that already occurred and for new words.
"""
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_deep_tree import accepted_depth, beam_tree, chain_drafts, head_features
from phase5_tree_draft import DEVICE, bootstrap_gain, replay, top_candidates
DEPTH = 3
LOOKAHEAD = 7
COPY_LENGTHS = (3, 5)
MATCH_LENGTHS = (3, 2, 1)
CLASS_NAMES = ("inside_word", "function_word_start", "group_start")
THRESHOLDS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.01) # head margin below which the gate opens; 1.01 = always
def ngram_share(tokens: list, reference: list, n: int = 4) -> float:
"""Share of tokens covered by an n-gram that occurs in reference; with reference None, earlier in tokens itself."""
seen = set() if reference is None else {tuple(reference[i : i + n]) for i in range(len(reference) - n + 1)}
covered = [False] * len(tokens)
for i in range(len(tokens) - n + 1):
gram = tuple(tokens[i : i + n])
if gram in seen:
covered[i : i + n] = [True] * n
if reference is None:
seen.add(gram)
return sum(covered) / max(1, len(tokens))
def copied_branch(seq: list, end: int, length: int) -> tuple:
"""Tokens that followed the most recent earlier occurrence of the suffix ending at seq[end]; and the suffix length matched."""
for m in MATCH_LENGTHS:
if end - m + 1 < 0:
continue
key = seq[end - m + 1 : end + 1]
for q in range(end - 1, m - 2, -1):
if seq[q - m + 1 : q + 1] == key:
return seq[q + 1 : min(q + 1 + length, end + 1)], m
return [], 0
@torch.no_grad()
def main() -> None:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--name", required=True)
p.add_argument("--ckpt-root", required=True, help="directory holding {name}_seed{s}/{arm}.pt")
p.add_argument("--arm", default="dependent_teacher")
p.add_argument("--seeds", default="0,1,2")
p.add_argument("--heldout", required=True)
p.add_argument("--scheme", default="")
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
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
is_start, _, _ = wg.prefix_tables(tok, vocab)
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 + LOOKAHEAD, 16, eos_ids)
pairs = [(pr, c) for pr, c in pairs if min(64, len(c) - LOOKAHEAD + 1) >= 1]
# everything that does not depend on the heads: copied branches, classes, whether the word occurred before
static = []
for prompt, cont in pairs:
horizon = min(64, len(cont) - LOOKAHEAD + 1)
seq = prompt + cont
p0 = len(prompt) - 1
truth = np.array([seq[p0 + 2 + j : p0 + 2 + j + max(COPY_LENGTHS)] for j in range(horizon)])
copies = {c: [copied_branch(seq, p0 + 1 + j, c) for j in range(horizon)] for c in COPY_LENGTHS}
depth = {c: 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(copies[c])]) for c in COPY_LENGTHS}
starts = [i for i, t in enumerate(seq) if is_start[t]]
if not starts or starts[0] != 0:
starts = [0] + starts
words = [w.strip().strip(wg.STRIP) for w in tok.batch_decode([seq[a:b] for a, b in zip(starts, starts[1:] + [len(seq)])])]
word_of = np.searchsorted(np.array(starts), np.arange(len(seq)), side="right") - 1
seen, earlier = np.zeros(len(words), dtype=bool), set()
for w, word in enumerate(words):
seen[w] = bool(word) and word in earlier
earlier.add(word)
idx = np.arange(p0 + 2, p0 + 2 + horizon)
static.append({"horizon": horizon, "seq": seq, "p0": p0, "truth": truth, "copies": copies, "copy_depth": depth,
"cls": wg.token_classes(seq, is_start, tok, fwords)[idx], "seen": seen[word_of[idx]],
"copy_first": np.array([bool(br) and br[0] == truth[j, 0] for j, (br, _) in enumerate(copies[3])]),
"match_len": np.array([m for _, m in copies[3]]),
"self_loop": ngram_share(cont[:64], None), "from_prompt": ngram_share(cont[:64], prompt)})
is_test = np.arange(len(static)) % 2 == 1
test = [d for d, t in zip(static, is_test) if t]
loop = np.array([d["self_loop"] for d in static])
reuse = np.array([d["from_prompt"] for d in static])
print(f"{args.name}: {len(static)} documents, {len(test)} test; continuation tokens inside a 4-gram repeated within the continuation {loop.mean():.3f} "
f"(documents above 10%: {np.mean(loop > 0.1):.3f}, above 50%: {np.mean(loop > 0.5):.3f}); inside a 4-gram of the prompt {reuse.mean():.3f}; {time.perf_counter() - t0:.0f}s", flush=True)
policies = ("heads_chain", "copy_3", "copy_5", "heads_plus_copy_3", "heads_plus_copy_5", "tree_5", "tree_8", "tree_16",
"tree_5_plus_copy_3", "tree_8_plus_copy_5", "tree_3_plus_copy_5")
res = {"name": args.name, "arm": args.arm, "gpu": torch.cuda.get_device_name(DEVICE), "docs": len(static), "test_docs": len(test), "copy_match_lengths": list(MATCH_LENGTHS),
"continuation_share_in_4gram_repeated_within_continuation": {"mean": float(loop.mean()), "documents_above_10_percent": float(np.mean(loop > 0.1)),
"documents_above_50_percent": float(np.mean(loop > 0.5))},
"continuation_share_in_4gram_of_prompt": {"mean": float(reuse.mean()), "documents_above_10_percent": float(np.mean(reuse > 0.1))},
"share_of_positions_by_suffix_length_matched": {str(m): float(np.mean(np.concatenate([d["match_len"] for d in static]) == m)) for m in (0, 1, 2, 3)},
"seeds": {}}
for seed in args.seeds.split(","):
stack = load_arm(backbone, Path(args.ckpt_root) / f"{args.name}_seed{seed}" / f"{args.arm}.pt", True)
per_doc = {pol: [] for pol in policies}
nodes = {pol: [0, 0] for pol in policies} # verified tokens, passes
# first token right, by class and by whether the word occurred before: heads, copy, either; positions
first = np.zeros((3, 2, 4))
gate_data = [] # per document, for the gated rules: what each option accepts at every position
for d, in_test in zip(static, is_test):
horizon, seq, p0 = d["horizon"], d["seq"], d["p0"]
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(d["truth"][:, :DEPTH], device=DEVICE)
since = torch.zeros(horizon, dtype=torch.long, device=DEVICE)
drafts = chain_drafts(stack, unembed, trunk, exact_next, DEPTH, since)
head_depth = np.cumprod((drafts == truth).cpu().numpy(), 1).sum(1)
drafts = drafts.tolist()
levels = beam_tree(stack, unembed, trunk, exact_next, truth, DEPTH, 24, since)
tree = {n: accepted_depth(levels, n) for n in (3, 5, 8, 16)}
lp = top_candidates(head_features(stack, trunk, 1, [exact_next], since), unembed)[1].exp()
gate_data.append({"margin": (lp[:, 0] - lp[:, 1]).cpu().numpy(), "match": d["match_len"], "head": head_depth, "copy": d["copy_depth"][5],
"tree3": tree[3], "tree8": tree[8], "copy_len": np.array([len(br) for br, _ in d["copies"][5]]), "self_loop": d["self_loop"]})
if not in_test:
continue
head_first = head_depth > 0
for c in range(3):
for s in (0, 1):
sel = (d["cls"] == c) & (d["seen"] == bool(s))
first[c, s] += [head_first[sel].sum(), d["copy_first"][sel].sum(), (head_first | d["copy_first"])[sel].sum(), sel.sum()]
# verified tokens of a pass that starts at position j: branch lengths minus the prefix the two branches share
shared = {c: np.array([int(np.cumprod([a == b for a, b in zip(br, drafts[j])]).sum()) if br else 0 for j, (br, _) in enumerate(d["copies"][c])]) for c in COPY_LENGTHS}
copy_len = {c: np.array([len(br) for br, _ in d["copies"][c]]) for c in COPY_LENGTHS}
depth_of = {
"heads_chain": (head_depth, np.full(horizon, DEPTH)),
"copy_3": (d["copy_depth"][3], copy_len[3]), "copy_5": (d["copy_depth"][5], copy_len[5]),
"heads_plus_copy_3": (np.maximum(head_depth, d["copy_depth"][3]), DEPTH + copy_len[3] - shared[3]),
"heads_plus_copy_5": (np.maximum(head_depth, d["copy_depth"][5]), DEPTH + copy_len[5] - shared[5]),
"tree_5": (tree[5], np.full(horizon, 5)), "tree_8": (tree[8], np.full(horizon, 8)), "tree_16": (tree[16], np.full(horizon, 16)),
"tree_5_plus_copy_3": (np.maximum(tree[5], d["copy_depth"][3]), 5 + copy_len[3]),
"tree_8_plus_copy_5": (np.maximum(tree[8], d["copy_depth"][5]), 8 + copy_len[5]),
"tree_3_plus_copy_5": (np.maximum(tree[3], d["copy_depth"][5]), 3 + copy_len[5]),
}
for pol, (depth, used) in depth_of.items():
per_doc[pol].append(replay(depth))
j = 0
while j < horizon: # verified tokens at the positions where a pass actually starts
nodes[pol][0] += int(used[j])
nodes[pol][1] += 1
j += 1 + int(depth[j])
def tpp(rows: list) -> float:
a = np.array(rows)
return float(a[:, 0].sum() / a[:, 1].sum())
arr = {pol: np.array(per_doc[pol], dtype=float) for pol in policies}
out = {
"tokens_per_pass": {pol: tpp(per_doc[pol]) for pol in policies},
"verified_tokens_per_pass": {pol: nodes[pol][0] / nodes[pol][1] for pol in policies},
"percent_gain": {
"heads_plus_copy_3_vs_heads_chain": bootstrap_gain(arr["heads_plus_copy_3"], arr["heads_chain"]),
"heads_plus_copy_5_vs_heads_chain": bootstrap_gain(arr["heads_plus_copy_5"], arr["heads_chain"]),
"heads_plus_copy_5_vs_tree_8": bootstrap_gain(arr["heads_plus_copy_5"], arr["tree_8"]),
"tree_5_plus_copy_3_vs_tree_8": bootstrap_gain(arr["tree_5_plus_copy_3"], arr["tree_8"]),
"tree_3_plus_copy_5_vs_tree_8": bootstrap_gain(arr["tree_3_plus_copy_5"], arr["tree_8"]),
"tree_8_plus_copy_5_vs_tree_16": bootstrap_gain(arr["tree_8_plus_copy_5"], arr["tree_16"]),
"tree_8_plus_copy_5_vs_tree_8": bootstrap_gain(arr["tree_8_plus_copy_5"], arr["tree_8"]),
},
"first_token_right": {CLASS_NAMES[c]: {("word_seen_before" if s else "new_word"): {
"positions": int(first[c, s, 3]), "heads": float(first[c, s, 0] / max(1, first[c, s, 3])),
"copy": float(first[c, s, 1] / max(1, first[c, s, 3])), "heads_or_copy": float(first[c, s, 2] / max(1, first[c, s, 3]))} for s in (0, 1)} for c in range(3)},
"per_document": {pol: np.array(per_doc[pol]).tolist() for pol in policies},
}
def gated(g: dict, tau: float, base: str) -> tuple:
"""Accepted drafts, verified tokens and gate state at every position of one document."""
gate = (g["match"] >= 2) & (g["margin"] < tau)
if base == "tree": # gate closed: confidence tree with 8 nodes; open: the 3 most confident nodes plus the copied branch
return np.where(gate, np.maximum(g["tree3"], g["copy"]), g["tree8"]), np.where(gate, 3 + g["copy_len"], 8), gate
return np.where(gate, np.maximum(g["head"], g["copy"]), g["head"]), np.where(gate, DEPTH + g["copy_len"], DEPTH), gate # closed: the chain alone
def run(docs: list, tau: float, base: str) -> tuple:
rows, tot = [], np.zeros(5) # verified tokens, passes, passes with the gate open, open passes where the copy went further, drafts accepted in open passes
for g in docs:
depth, used, gate = gated(g, tau, base)
rows.append(replay(depth))
other = g["tree3"] if base == "tree" else g["head"]
j = 0
while j < len(depth):
tot += [used[j], 1, gate[j], gate[j] and g["copy"][j] > other[j], depth[j] if gate[j] else 0]
j += 1 + int(depth[j])
return rows, tot
fit_docs = [g for g, t in zip(gate_data, is_test) if not t]
test_docs = [g for g, t in zip(gate_data, is_test) if t]
low = np.array([g["self_loop"] <= 0.1 for g in test_docs])
out["documents_with_little_looping"] = {"documents": int(low.sum()), "tokens_per_pass": {
pol: float(arr[pol][low, 0].sum() / arr[pol][low, 1].sum()) for pol in ("heads_chain", "copy_5", "tree_8", "heads_plus_copy_5", "tree_3_plus_copy_5", "tree_16", "tree_8_plus_copy_5")},
"percent_gain_tree_3_plus_copy_5_vs_tree_8": bootstrap_gain(arr["tree_3_plus_copy_5"][low], arr["tree_8"][low]),
"percent_gain_heads_plus_copy_5_vs_heads_chain": bootstrap_gain(arr["heads_plus_copy_5"][low], arr["heads_chain"][low])}
out["gated"] = {}
for base in ("tree", "chain"):
fit = {tau: tpp(run(fit_docs, tau, base)[0]) for tau in THRESHOLDS}
tau = max(fit, key=fit.get)
rows, tot = run(test_docs, tau, base)
always_rows, always_tot = run(test_docs, THRESHOLDS[-1], base)
a, ref = np.array(rows, dtype=float), arr["tree_8" if base == "tree" else "heads_chain"]
out["gated"][base] = {
"threshold_fitted_on_even_documents": tau, "tokens_per_pass_on_even_documents_by_threshold": {str(k): v for k, v in fit.items()},
"tokens_per_pass": tpp(rows), "verified_tokens_per_pass": float(tot[0] / tot[1]), "share_of_passes_with_gate_open": float(tot[2] / tot[1]),
"share_of_open_passes_where_copy_went_further": float(tot[3] / max(1, tot[2])), "accepted_drafts_per_open_pass": float(tot[4] / max(1, tot[2])),
"percent_gain_vs_gate_always_closed": bootstrap_gain(a, ref),
"percent_gain_vs_gate_always_closed_on_documents_with_little_looping": bootstrap_gain(a[low], ref[low]),
"gate_on_suffix_match_only": {"tokens_per_pass": tpp(always_rows), "verified_tokens_per_pass": float(always_tot[0] / always_tot[1]),
"share_of_passes_with_gate_open": float(always_tot[2] / always_tot[1])},
"per_document": a.tolist(),
}
res["seeds"][seed] = out
print(f"{args.name} seed {seed}: " + " ".join(f"{pol} {out['tokens_per_pass'][pol]:.3f} ({out['verified_tokens_per_pass'][pol]:.1f})" for pol in policies) + f" {time.perf_counter() - t0:.0f}s", flush=True)
for k, v in out["percent_gain"].items():
print(f" {k:34s} {v[0]:+.2f}% [{v[1]:+.2f}, {v[2]:+.2f}]", flush=True)
for c in range(3):
for s in (1, 0):
f = out["first_token_right"][CLASS_NAMES[c]]["word_seen_before" if s else "new_word"]
if f["positions"]:
print(f" first token right, {CLASS_NAMES[c]:20s} {'word seen before' if s else 'new word':16s} n={f['positions']:5d} heads {f['heads']:.3f} copy {f['copy']:.3f} either {f['heads_or_copy']:.3f}", flush=True)
for base, closed in (("tree", "confidence tree at 8"), ("chain", "heads chain")):
g = out["gated"][base]
print(f" gated, closed = {closed}: threshold {g['threshold_fitted_on_even_documents']}, {g['tokens_per_pass']:.3f} tokens/pass, {g['verified_tokens_per_pass']:.2f} verified, "
f"gate open {100 * g['share_of_passes_with_gate_open']:.1f}% of passes, copy went further in {100 * g['share_of_open_passes_where_copy_went_further']:.1f}% of open passes, "
f"{g['accepted_drafts_per_open_pass']:.2f} drafts per open pass, gain {g['percent_gain_vs_gate_always_closed'][0]:+.2f}% "
f"[{g['percent_gain_vs_gate_always_closed'][1]:+.2f}, {g['percent_gain_vs_gate_always_closed'][2]:+.2f}]; little looping: "
f"{g['percent_gain_vs_gate_always_closed_on_documents_with_little_looping'][0]:+.2f}%; suffix match only: {g['gate_on_suffix_match_only']['tokens_per_pass']:.3f} "
f"({g['gate_on_suffix_match_only']['verified_tokens_per_pass']:.2f} verified, open {100 * g['gate_on_suffix_match_only']['share_of_passes_with_gate_open']:.1f}%)", flush=True)
ll = out["documents_with_little_looping"]
print(f" documents with at most 10% looping ({ll['documents']}): " + " ".join(f"{k} {v:.3f}" for k, v in ll["tokens_per_pass"].items())
+ f" tree 3 + copy 5 vs tree 8 {ll['percent_gain_tree_3_plus_copy_5_vs_tree_8'][0]:+.2f}% [{ll['percent_gain_tree_3_plus_copy_5_vs_tree_8'][1]:+.2f}, {ll['percent_gain_tree_3_plus_copy_5_vs_tree_8'][2]:+.2f}]", flush=True)
del stack
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}: suffix length matched {res['share_of_positions_by_suffix_length_matched']}, {res['wall_seconds']:.0f}s, peak {res['peak_gpu_mib']:.0f} MiB", flush=True)
if __name__ == "__main__":
main()
|