File size: 13,382 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 | """Phase 5: when the first draft misses, was the frozen model's own choice a close call?
Lossless decoding accepts a draft only if it equals the frozen model's greedy
token. A miss can therefore have two sources: the frozen model itself was
nearly undecided between two tokens (a fragile target, which no drafter can
predict reliably), or the frozen model was sure and the draft head still
missed (a limit of the drafter). On the frozen model's greedy continuations
of held-out documents this script records, for every position, the frozen
model's top-1 probability and its margin over the second choice for the
token that the first draft has to match, and whether the first draft (the
head that predicts two tokens ahead, given the exact next token) matched.
Agreement is then split by word-group position of the target token (inside
a word, start of a function word that continues a group, group start), by
margin, by script of the token, by training frequency of the word the token
belongs to, by whether the token is in the draft shortlist, and by whether
the word (or the token) already occurs in the 256-token prompt, which the
frozen model can copy through attention and a draft head cannot.
"""
import argparse
import collections
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
DEVICE = "cuda:0"
MARGIN_EDGES = (0.0, 0.1, 0.3, 0.6, 0.9, 1.0001)
MARGIN_NAMES = ("0.0-0.1", "0.1-0.3", "0.3-0.6", "0.6-0.9", "0.9-1.0")
CLASS_NAMES = ("inside_word", "function_word_start", "group_start")
SCRIPT_NAMES = ("other", "devanagari", "latin")
FREQ_NAMES = ("top_100", "101_to_1000", "1001_to_10000", "rarer", "unseen")
WORD_TOKENS = 5_000_000 # training tokens read for word frequencies
def word_ranks(tokenizer, train_ids: np.ndarray, strip: str) -> dict:
"""Frequency rank (0 = most frequent) of every whitespace word in the first WORD_TOKENS training tokens."""
counts = collections.Counter()
for s in range(0, min(len(train_ids), WORD_TOKENS), 100_000):
counts.update(w.strip(strip) for w in tokenizer.decode(train_ids[s : s + 100_000].tolist()).split())
counts.pop("", None)
return {w: r for r, (w, _) in enumerate(counts.most_common())}
def freq_bucket(rank) -> int:
if rank is None:
return 4
return 0 if rank < 100 else 1 if rank < 1000 else 2 if rank < 10000 else 3
def rate_table(match: np.ndarray, rows: np.ndarray, n_rows: int, cols: np.ndarray, n_cols: int) -> list:
"""[[agreement, positions] per column] per row."""
out = []
for r in range(n_rows):
line = []
for c in range(n_cols):
sel = (rows == r) & (cols == c)
line.append([float(match[sel].mean()) if sel.any() else None, int(sel.sum())])
out.append(line)
return out
@torch.no_grad()
def main() -> None:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--name", required=True)
p.add_argument("--ckpt", required=True)
p.add_argument("--heldout", required=True)
p.add_argument("--train-ids", required=True)
p.add_argument("--scheme", default="", help="Devanagari, ITRANS, IAST or ISO for the function-word list; empty for English")
p.add_argument("--docs", type=int, default=512)
p.add_argument("--out", required=True)
p.add_argument("--positions-out", default="", help="optional .npz with one row per position")
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 phase5_shortlist_pilot import successor_table
from phase5_tree_draft import K, head_features, top_candidates
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, script, _ = wg.prefix_tables(tok, vocab)
fwords = wg.function_words(args.scheme) if args.scheme else set()
train_ids = np.load(args.train_ids)
ranks = word_ranks(tok, train_ids, wg.STRIP)
succ, freq_rank = successor_table(train_ids, vocab)
in_static = torch.zeros(vocab, dtype=torch.bool, device=DEVICE).index_fill_(0, freq_rank[:4096], True)
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)[: args.docs]
pairs = pb.generate_continuations(backbone, tok, texts, 256, 64 + pb.LOOKAHEAD, 16, eos_ids)
pairs = [(pr, c) for pr, c in pairs if min(64, len(c) - pb.LOOKAHEAD + 1) >= 1]
stack = load_arm(backbone, Path(args.ckpt), True)
print(f"{args.name}: {len(pairs)} documents, {len(ranks)} distinct training words, {time.perf_counter() - t0:.0f}s", flush=True)
cols = {k: [] for k in ("doc", "cls", "match", "p1", "margin", "script", "covered", "freq", "head_p", "in_top_k", "valid", "word_in_prompt", "token_in_prompt", "word_gap")}
for d, (prompt, cont) in enumerate(pairs):
horizon = min(64, len(cont) - pb.LOOKAHEAD + 1)
seq = prompt + cont
p0 = len(prompt) - 1
hidden = backbone.model(input_ids=torch.tensor([seq], device=DEVICE)).last_hidden_state[0, p0 : p0 + horizon + 1]
exact_next = torch.tensor(seq[p0 + 1 : p0 + 1 + horizon], device=DEVICE)
target = torch.tensor(seq[p0 + 2 : p0 + 2 + horizon], device=DEVICE) # the frozen model's greedy token after exact_next
probs = torch.softmax(backbone.lm_head(hidden[1:]), -1) # the frozen model's distribution for the target
top2 = probs.topk(2, -1)
cand, lp = top_candidates(head_features(stack, stack.trunk_states(hidden[:-1]), 1, [exact_next]), unembed)
covered = in_static[target] | (succ[exact_next] == target[:, None]).any(1)
classes = wg.token_classes(seq, is_start, tok, fwords)
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
idx = np.arange(p0 + 2, p0 + 2 + horizon)
n_prompt_words = int(word_of[len(prompt) - 1]) # words that end inside the prompt
prompt_words, prompt_tokens = set(words[:n_prompt_words]), set(prompt)
cols["word_in_prompt"].append(np.array([words[word_of[i]] in prompt_words for i in idx]))
cols["token_in_prompt"].append(np.array([seq[i] in prompt_tokens for i in idx]))
last, gap = {}, np.full(len(words), -1) # words back to the previous occurrence of the same word anywhere before it; -1 if none
for w, word in enumerate(words):
if word and word in last:
gap[w] = w - last[word]
last[word] = w
cols["word_gap"].append(gap[word_of[idx]])
cols["doc"].append(np.full(horizon, d))
cols["cls"].append(classes[idx])
cols["match"].append((cand[:, 0] == target).cpu().numpy())
cols["p1"].append(top2.values[:, 0].cpu().numpy())
cols["margin"].append((top2.values[:, 0] - top2.values[:, 1]).cpu().numpy())
cols["script"].append(script[target.cpu().numpy()])
cols["covered"].append(covered.cpu().numpy())
cols["freq"].append(np.array([freq_bucket(ranks.get(words[word_of[i]])) for i in idx]))
cols["head_p"].append(lp[:, 0].exp().cpu().numpy())
cols["in_top_k"].append((cand == target[:, None]).any(1).cpu().numpy())
cols["valid"].append((top2.indices[:, 0] == target).cpu().numpy()) # recomputed greedy token equals the generated one
c = {k: np.concatenate(v) for k, v in cols.items()}
if args.positions_out:
Path(args.positions_out).parent.mkdir(parents=True, exist_ok=True)
np.savez_compressed(args.positions_out, **c)
ok = c["valid"]
match, cls = c["match"][ok].astype(float), c["cls"][ok]
mbin = np.digitize(c["margin"][ok], MARGIN_EDGES[1:-1])
res = {
"name": args.name, "ckpt": args.ckpt, "docs": len(pairs), "gpu": torch.cuda.get_device_name(DEVICE),
"positions": int(len(ok)), "positions_dropped_recomputed_choice_differs": int((~ok).sum()),
"margin_bins": MARGIN_NAMES, "classes": CLASS_NAMES, "scripts": SCRIPT_NAMES, "word_frequency_buckets": FREQ_NAMES,
"agreement_all": float(match.mean()),
"by_class": {CLASS_NAMES[k]: {
"positions": int((cls == k).sum()), "agreement": float(match[cls == k].mean()) if (cls == k).any() else None,
"target_in_head_top_k": float(c["in_top_k"][ok][cls == k].mean()) if (cls == k).any() else None,
"mean_top1_probability": float(c["p1"][ok][cls == k].mean()) if (cls == k).any() else None,
"mean_margin": float(c["margin"][ok][cls == k].mean()) if (cls == k).any() else None,
"share_of_positions_by_margin_bin": [float(((cls == k) & (mbin == b)).sum() / max(1, (cls == k).sum())) for b in range(5)],
"share_of_misses_by_margin_bin": [float(((cls == k) & (mbin == b) & (match == 0)).sum() / max(1, ((cls == k) & (match == 0)).sum())) for b in range(5)],
} for k in range(3)},
"agreement_by_class_and_margin": rate_table(match, cls, 3, mbin, 5),
"agreement_by_class_and_script": rate_table(match, cls, 3, c["script"][ok], 3),
"agreement_by_class_and_word_frequency": rate_table(match, cls, 3, c["freq"][ok], 5),
"agreement_by_class_and_shortlist_coverage": rate_table(match, cls, 3, c["covered"][ok].astype(int), 2),
"agreement_by_class_and_word_in_prompt": rate_table(match, cls, 3, c["word_in_prompt"][ok].astype(int), 2),
"agreement_by_class_and_token_in_prompt": rate_table(match, cls, 3, c["token_in_prompt"][ok].astype(int), 2),
"group_start_agreement_by_word_in_prompt_and_margin": rate_table(match[cls == 2], c["word_in_prompt"][ok][cls == 2].astype(int), 2, mbin[cls == 2], 5),
"group_start_mean_margin_by_word_in_prompt": [float(c["margin"][ok][(cls == 2) & (c["word_in_prompt"][ok] == v)].mean()) for v in (False, True)],
"group_start_agreement_by_word_frequency_and_margin": rate_table(match[cls == 2], c["freq"][ok][cls == 2], 5, mbin[cls == 2], 5),
"wall_seconds": time.perf_counter() - t0, "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))
def row(cells: list) -> str:
return " ".join(f"{(100 * a if a is not None else float('nan')):5.1f}% (n={n:5d})" for a, n in cells)
print(f"{args.name}: {res['positions']} positions ({res['positions_dropped_recomputed_choice_differs']} dropped), first-draft agreement {res['agreement_all']:.3f}", flush=True)
print(f" agreement by class x margin of the frozen model's choice ({' | '.join(MARGIN_NAMES)})", flush=True)
for k in range(3):
b = res["by_class"][CLASS_NAMES[k]]
if b["positions"]:
print(f" {CLASS_NAMES[k]:20s} {row(res['agreement_by_class_and_margin'][k])} all {100 * b['agreement']:.1f}% mean p1 {b['mean_top1_probability']:.3f}", flush=True)
print(f" {'':20s} share of positions " + " ".join(f"{100 * v:5.1f}%" for v in b["share_of_positions_by_margin_bin"])
+ " share of misses " + " ".join(f"{100 * v:5.1f}%" for v in b["share_of_misses_by_margin_bin"]), flush=True)
for title, key, names in (("script", "agreement_by_class_and_script", SCRIPT_NAMES), ("word frequency", "agreement_by_class_and_word_frequency", FREQ_NAMES),
("in shortlist (no | yes)", "agreement_by_class_and_shortlist_coverage", ("no", "yes")),
("word already in the prompt", "agreement_by_class_and_word_in_prompt", ("no", "yes")),
("token already in the prompt", "agreement_by_class_and_token_in_prompt", ("no", "yes"))):
print(f" agreement by class x {title} ({' | '.join(names)})", flush=True)
for k in range(3):
if res["by_class"][CLASS_NAMES[k]]["positions"]:
print(f" {CLASS_NAMES[k]:20s} {row(res[key][k])}", flush=True)
print(f" group starts: word already in the prompt (rows no, yes) x margin (columns); mean margin {res['group_start_mean_margin_by_word_in_prompt']}", flush=True)
for v in range(2):
print(f" {('no', 'yes')[v]:20s} {row(res['group_start_agreement_by_word_in_prompt_and_margin'][v])}", flush=True)
print(f" group starts: word frequency (rows) x margin (columns)", flush=True)
for f in range(5):
print(f" {FREQ_NAMES[f]:20s} {row(res['group_start_agreement_by_word_frequency_and_margin'][f])}", flush=True)
print(f"{args.name}: {res['wall_seconds']:.0f}s, peak {res['peak_gpu_mib']:.0f} MiB", flush=True)
if __name__ == "__main__":
main()
|