code-switch-mtp / scripts /phase5_shortlist_pilot.py
Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
9.67 kB
"""Phase 5 pilot: draft over a short candidate list instead of the full vocabulary.
Each draft token costs one projection onto all 128,256 vocabulary rows (a
1 GB matrix read in fp32), and three drafts cost about as much as 60% of a
cached backbone pass. Two ways to shrink the candidate set, no retraining:
static M the M most frequent training tokens (frequency-ranked
shortlist, as in FR-Spec)
successors N the N tokens that most often follow the previous token in
the training stream, optionally joined with a static list
Reports tokens per pass (one backbone pass per round, three drafts plus the
backbone's own next token), how often the true next token is in the list
split by word position, drafting time, and how repetitive the greedy
continuations are.
"""
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
DEVICE = "cuda:0"
N_HEADS = 4
MAX_SUCC = 256
CONFIGS = [("full", 0, 0)] + [(f"static{m}", 0, m) for m in (1024, 4096, 16384)] + [
(f"succ{n}+static{m}", n, m) for n in (16, 64, 256) for m in (0, 1024, 4096)]
def successor_table(ids: np.ndarray, vocab: int) -> tuple:
"""Top successors of every token by count, padded with the most frequent tokens; and the frequency ranking."""
ids = ids.astype(np.int64)
freq_rank = np.argsort(-np.bincount(ids, minlength=vocab), kind="stable")
keys, counts = np.unique(ids[:-1] * vocab + ids[1:], return_counts=True)
ka, kb = keys // vocab, keys % vocab
order = np.lexsort((-counts, ka))
ka, kb = ka[order], kb[order]
rank = np.arange(len(ka)) - np.searchsorted(ka, ka)
keep = rank < MAX_SUCC
succ = np.tile(freq_rank[:MAX_SUCC], (vocab, 1))
succ[ka[keep], rank[keep]] = kb[keep]
return torch.from_numpy(succ).to(DEVICE), torch.from_numpy(freq_rank.copy()).to(DEVICE)
class ShortlistDrafter:
def __init__(self, stack, unembed: torch.Tensor, succ: torch.Tensor, freq_rank: torch.Tensor):
self.stack, self.U, self.succ, self.freq_rank = stack, unembed, succ, freq_rank
self.static_rows = {}
def features(self, trunk: torch.Tensor, k: int, history: list) -> torch.Tensor:
h = trunk
if hasattr(self.stack, "proj"): # independent stacks have no predecessor projections
for i, tokens in enumerate(history[-k:]):
h = h + self.stack.proj[k - 1][i](self.stack.embed(tokens))
return self.stack.heads[k].resblock(h)
def pick(self, feat: torch.Tensor, prev: torch.Tensor, n_succ: int, n_static: int) -> torch.Tensor:
"""feat: (n, hidden); prev: (n,) previous tokens -> (n,) drafted token ids."""
if n_succ == 0 and n_static == 0:
return (feat @ self.U.T).argmax(-1)
scores, cands = [], []
if n_succ:
c = self.succ[prev, :n_succ]
scores.append(torch.bmm(self.U[c], feat[:, :, None])[:, :, 0])
cands.append(c)
if n_static:
if n_static not in self.static_rows:
self.static_rows[n_static] = self.U[self.freq_rank[:n_static]].contiguous()
scores.append(feat @ self.static_rows[n_static].T)
cands.append(self.freq_rank[:n_static][None, :].expand(feat.shape[0], -1))
best = torch.cat(scores, 1).argmax(-1)
return torch.cat(cands, 1).gather(1, best[:, None])[:, 0]
def draft(self, trunk: torch.Tensor, exact_next: torch.Tensor, n_succ: int, n_static: int) -> torch.Tensor:
history = [exact_next]
for k in range(1, N_HEADS):
history.append(self.pick(self.features(trunk, k, history), history[-1], n_succ, n_static))
return torch.stack(history[1:], 1)
def repeated_fraction(tokens: list, n: int = 4) -> float:
"""Share of tokens covered by an n-gram that already occurred earlier in the same continuation."""
seen, covered = set(), [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
seen.add(gram)
return sum(covered) / max(1, len(tokens))
@torch.no_grad()
def main() -> None:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--name", required=True)
p.add_argument("--ckpt-dir", required=True)
p.add_argument("--arm", default="dependent_teacher")
p.add_argument("--train-ids", required=True)
p.add_argument("--heldout", required=True)
p.add_argument("--out", required=True)
p.add_argument("--spec-docs", type=int, default=256)
args = p.parse_args()
t0 = time.perf_counter()
from transformers import AutoModelForCausalLM, AutoTokenizer
import phase4_boundary_decoding as pb
from phase5_dependent_eval import BACKBONE, load_arm, replay
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
starts = pb.word_start_table(tok)
is_start = starts + [False] * (vocab - len(starts))
is_start_t = torch.tensor(is_start, device=DEVICE)
succ, freq_rank = successor_table(np.load(args.train_ids), vocab)
stack = load_arm(backbone, Path(args.ckpt_dir) / f"{args.arm}.pt", True)
drafter = ShortlistDrafter(stack, backbone.lm_head.weight, succ, freq_rank)
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 + pb.LOOKAHEAD, 16, eos_ids)
totals = {name: {"committed": [], "rounds": []} for name, _, _ in CONFIGS}
in_list = {name: np.zeros((2, 2), dtype=np.int64) for name, _, _ in CONFIGS[1:]} # word-start flag, (covered, seen)
static_member = {m: torch.zeros(vocab, dtype=torch.bool, device=DEVICE).index_fill_(0, freq_rank[:m], True) for m in (1024, 4096, 16384)}
repeats = []
for prompt, cont in pairs:
horizon = min(64, len(cont) - pb.LOOKAHEAD + 1)
if horizon < 1:
continue
repeats.append(repeated_fraction(cont))
full = torch.tensor([prompt + cont], device=DEVICE)
p0 = len(prompt) - 1
trunk = stack.trunk_states(backbone.model(input_ids=full).last_hidden_state[0, p0 : p0 + horizon])
continuation = [prompt[-1]] + cont
exact_next = torch.tensor(continuation[1 : horizon + 1], device=DEVICE)
target = torch.tensor(continuation[2 : horizon + 2], device=DEVICE) # true token after exact_next
flag = is_start_t[target]
for name, n_succ, n_static in CONFIGS:
drafts = drafter.draft(trunk, exact_next, n_succ, n_static).tolist()
r = replay(drafts, continuation, horizon, 2, is_start)
totals[name]["committed"].append(r["committed"])
totals[name]["rounds"].append(r["rounds"])
if name != "full":
covered = torch.zeros_like(flag)
if n_succ:
covered |= (succ[exact_next, :n_succ] == target[:, None]).any(1)
if n_static:
covered |= static_member[n_static][target]
for f in (0, 1):
in_list[name][f, 0] += int((covered & (flag == bool(f))).sum())
in_list[name][f, 1] += int((flag == bool(f)).sum())
# drafting time for one position, three drafts
trunk1, next1 = trunk[:1], exact_next[:1]
def timed(fn, reps: int = 50) -> float:
fn()
torch.cuda.synchronize()
t = time.perf_counter()
for _ in range(reps):
fn()
torch.cuda.synchronize()
return 1000 * (time.perf_counter() - t) / reps
res = {"name": args.name, "arm": args.arm, "docs": len(repeats), "gpu": torch.cuda.get_device_name(DEVICE),
"mean_repeated_4gram_fraction": float(np.mean(repeats)), "configs": {}}
for name, n_succ, n_static in CONFIGS:
slot = totals[name]
res["configs"][name] = {
"tokens_per_pass": sum(slot["committed"]) / sum(slot["rounds"]),
"committed": slot["committed"], "rounds": slot["rounds"],
"draft_3_tokens_ms": timed(lambda: drafter.draft(trunk1, next1, n_succ, n_static)),
}
if name != "full":
c = in_list[name]
res["configs"][name]["true_token_in_list_within_word"] = c[0, 0] / max(1, c[0, 1])
res["configs"][name]["true_token_in_list_word_start"] = c[1, 0] / max(1, c[1, 1])
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))
full_tpp = res["configs"]["full"]["tokens_per_pass"]
print(f"{args.name} {args.arm}: {len(repeats)} docs, repeated 4-gram share {res['mean_repeated_4gram_fraction']:.3f}, {res['wall_seconds']:.0f}s")
for name, c in res["configs"].items():
cov = f" in-list within {c['true_token_in_list_within_word']:.3f} start {c['true_token_in_list_word_start']:.3f}" if name != "full" else ""
print(f" {name:20s} {c['tokens_per_pass']:.3f} ({100 * (c['tokens_per_pass'] / full_tpp - 1):+.1f}%) draft {c['draft_3_tokens_ms']:.2f} ms{cov}")
if __name__ == "__main__":
main()