File size: 35,788 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 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 | """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
@torch.no_grad()
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
@torch.no_grad()
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}
@torch.no_grad()
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()
|