code-switch-mtp / scripts /phase5_dependence_probe.py
Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
10.7 kB
"""Probe: does conditioning draft token k on draft token k-1 help, and where?
Training-free. Existing Medusa-style heads give p_k(x_{t+k} | ctx). We add a
product-of-experts correction from a token-bigram table counted on the
training stream:
score(x) = log p_k(x | ctx) + beta * [log p_big(x | prev) - log p_uni(x)]
Variants restrict the correction to within-word structure (which continuation
piece) or cross-word structure (which word-start piece), the other class only
receiving the class-level ratio.
Part A: teacher-forced accuracy on held-out text, split by target type.
Part B: replay against the backbone's greedy continuation (tokens per
verification pass, 4 drafts + 1 bonus token), same protocol as
scripts/phase4_boundary_decoding.py.
"""
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("/home/cs769_mtp/code-switch-mtp")
sys.path.insert(0, str(REPO))
sys.path.insert(0, str(REPO / "scripts"))
import numpy as np
import torch
import torch.nn.functional as F
DEVICE = "cuda:0"
N_HEADS = 4
ALPHA = 1.0
class Bigram:
def __init__(self, ids: np.ndarray, vocab: int, is_start: torch.Tensor):
ids = ids.astype(np.int64)
a, b = ids[:-1], ids[1:]
keys, counts = np.unique(a * vocab + b, return_counts=True)
ka, kb = keys // vocab, keys % vocab
c1 = np.bincount(a, minlength=vocab).astype(np.float64)
pu = (np.bincount(ids, minlength=vocab) + 0.5).astype(np.float64)
pu /= pu.sum()
vals = np.log((counts + ALPHA * pu[kb]) / ((c1[ka] + ALPHA) * pu[kb]))
row_ptr = np.searchsorted(ka, np.arange(vocab + 1))
st = is_start.cpu().numpy()
cs = np.bincount(a, weights=st[b].astype(np.float64), minlength=vocab)
ps = float((pu * st).sum())
p_start = (cs + ALPHA * ps) / (c1 + ALPHA)
self.vocab = vocab
self.is_start = is_start.to(DEVICE)
self.cols = torch.from_numpy(kb).to(DEVICE)
self.vals = torch.from_numpy(vals).float().to(DEVICE)
self.row_ptr = torch.from_numpy(row_ptr).to(DEVICE)
self.base = torch.from_numpy(np.log(ALPHA / (c1 + ALPHA))).float().to(DEVICE)
self.start_ratio = torch.from_numpy(np.log(p_start / ps)).float().to(DEVICE)
self.cont_ratio = torch.from_numpy(np.log((1 - p_start) / (1 - ps))).float().to(DEVICE)
self.nnz = len(keys)
def rows(self, prev: torch.Tensor, variant: str) -> torch.Tensor:
"""prev: (n,) token ids -> (n, vocab) log-ratio correction."""
n = prev.shape[0]
lo, hi = self.row_ptr[prev], self.row_ptr[prev + 1]
lens = hi - lo
R = self.base[prev][:, None].expand(n, self.vocab).clone()
if int(lens.sum()) > 0:
row_idx = torch.repeat_interleave(torch.arange(n, device=DEVICE), lens)
starts = torch.repeat_interleave(lo, lens)
offs = torch.arange(int(lens.sum()), device=DEVICE) - torch.repeat_interleave(torch.cumsum(lens, 0) - lens, lens)
idx = starts + offs
R[row_idx, self.cols[idx]] = self.vals[idx]
if variant == "full":
return R
if variant == "within": # which continuation piece; word-start class only by class ratio
return torch.where(self.is_start[None, :], self.start_ratio[prev][:, None], R)
if variant == "cross": # which word-start piece; continuation class only by class ratio
return torch.where(self.is_start[None, :], R, self.cont_ratio[prev][:, None])
raise ValueError(variant)
def main():
p = argparse.ArgumentParser()
p.add_argument("--name", required=True)
p.add_argument("--ckpt", required=True)
p.add_argument("--train-ids", required=True)
p.add_argument("--heldout", required=True)
p.add_argument("--out", required=True)
p.add_argument("--n-docs", type=int, default=128)
p.add_argument("--spec-docs", type=int, default=256)
p.add_argument("--betas", default="0.25,0.5,1.0")
args = p.parse_args()
betas = [float(x) for x in args.betas.split(",")]
t0 = time.perf_counter()
from transformers import AutoModelForCausalLM, AutoTokenizer
import phase4_boundary_decoding as pb
from src.train.data import load_heldout_texts
from src.train.evaluate import word_start_flags
tok = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B")
backbone = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B", dtype=torch.float32).to(DEVICE).eval()
for q in backbone.parameters():
q.requires_grad = False
V = backbone.config.vocab_size
starts_table = pb.word_start_table(tok)
is_start = torch.zeros(V, dtype=torch.bool)
is_start[: len(starts_table)] = torch.tensor(starts_table)
bg = Bigram(np.load(args.train_ids), V, is_start)
stack = pb.load_stack(backbone, Path(args.ckpt), shared_trunk=True)
texts = load_heldout_texts(args.heldout)
res = {"name": args.name, "bigram_nnz": bg.nnz, "betas": betas}
variants = ["full", "within", "cross"]
CH = 96
# ---------- Part A: teacher-forced accuracy on held-out text ----------
keys = ["marginal", "oracle_backbone"] + [f"{v}_b{b}" for v in variants for b in betas]
acc = {k: {h: {"intra": [0, 0], "bound": [0, 0]} for h in range(1, N_HEADS + 1)} for k in keys}
with torch.no_grad():
for text in texts[: args.n_docs]:
enc = tok(text, add_special_tokens=False, return_offsets_mapping=True, truncation=True, max_length=512)
ids = enc.input_ids
if len(ids) < 16:
continue
flags = torch.tensor(word_start_flags(text, enc.offset_mapping), device=DEVICE)
block = torch.tensor([ids], device=DEVICE)
hidden = backbone.model(input_ids=block).last_hidden_state
trunk = stack.trunk_states(hidden)
base_pred = backbone.lm_head(hidden).argmax(-1)[0] # predicts ids[t+1]
x = block[0]
L = len(ids)
for h in range(1, N_HEADS + 1):
n = L - h
tgt = x[h:]
tflag = flags[h:]
logp = F.log_softmax(stack.head_logits(trunk, h - 1)[0, :n], dim=-1)
preds = {"marginal": logp.argmax(-1), "oracle_backbone": base_pred[h - 1 : h - 1 + n]}
if h >= 2:
prev = x[h - 1 : h - 1 + n]
for v in variants:
outs = {b: [] for b in betas}
for s in range(0, n, CH):
R = bg.rows(prev[s : s + CH], v)
for b in betas:
outs[b].append((logp[s : s + CH] + b * R).argmax(-1))
del R
for b in betas:
preds[f"{v}_b{b}"] = torch.cat(outs[b])
else:
for v in variants:
for b in betas:
preds[f"{v}_b{b}"] = preds["marginal"]
for k, pr in preds.items():
ok = pr == tgt
acc[k][h]["bound"][0] += int((ok & tflag).sum()); acc[k][h]["bound"][1] += int(tflag.sum())
acc[k][h]["intra"][0] += int((ok & ~tflag).sum()); acc[k][h]["intra"][1] += int((~tflag).sum())
res["teacher_forced"] = {
k: {str(h): {"intra": d["intra"][0] / max(1, d["intra"][1]), "bound": d["bound"][0] / max(1, d["bound"][1]),
"all": (d["intra"][0] + d["bound"][0]) / max(1, d["intra"][1] + d["bound"][1]),
"n_intra": d["intra"][1], "n_bound": d["bound"][1]} for h, d in hd.items()}
for k, hd in acc.items()
}
res["partA_seconds"] = time.perf_counter() - t0
Path(args.out).write_text(json.dumps(res, indent=1))
print(args.name, "part A done", f"{res['partA_seconds']:.0f}s", flush=True)
# ---------- Part B: replay on the backbone's greedy continuation ----------
t1 = time.perf_counter()
eos = backbone.generation_config.eos_token_id
eos_ids = set(eos if isinstance(eos, list) else [eos])
pairs = pb.generate_continuations(backbone, tok, texts[: args.spec_docs], 256, 64 + pb.LOOKAHEAD, 16, eos_ids)
pol = ["marginal"] + [f"{v}_b{b}" for v in variants for b in betas]
tot = {k: [0, 0] for k in pol} # committed, rounds
pos_acc = {k: [[0, 0] for _ in range(N_HEADS)] for k in pol} # per draft position: accepted, reached
with torch.no_grad():
for prompt, cont in pairs:
horizon = min(64, len(cont) - pb.LOOKAHEAD + 1)
if horizon < 1:
continue
full = torch.tensor([prompt + cont], device=DEVICE)
p0 = len(prompt) - 1
hidden = backbone.model(input_ids=full).last_hidden_state[:, p0 : p0 + horizon, :]
trunk = stack.trunk_states(hidden)
logps = [F.log_softmax(stack.head_logits(trunk, i)[0], dim=-1) for i in range(N_HEADS)]
continuation = [prompt[-1]] + cont
drafts = {"marginal": torch.stack([lp.argmax(-1) for lp in logps], 1).tolist()}
for v in variants:
for b in betas:
d = [logps[0].argmax(-1)]
for i in range(1, N_HEADS):
out = []
for s in range(0, horizon, CH):
out.append((logps[i][s : s + CH] + b * bg.rows(d[-1][s : s + CH], v)).argmax(-1))
d.append(torch.cat(out))
drafts[f"{v}_b{b}"] = torch.stack(d, 1).tolist()
for k in pol:
j = 0
while j < horizon:
n_acc = pb.accepted_count(drafts[k][j], continuation, j, N_HEADS)
for i in range(N_HEADS):
if i <= n_acc:
pos_acc[k][i][1] += 1
pos_acc[k][i][0] += int(i < n_acc)
tot[k][0] += n_acc + 1
tot[k][1] += 1
j += n_acc + 1
res["replay"] = {k: {"tokens_per_step": tot[k][0] / tot[k][1], "rounds": tot[k][1],
"accept_by_position": [a / max(1, r) for a, r in pos_acc[k]]} for k in pol}
res["replay_docs"] = len(pairs)
res["partB_seconds"] = time.perf_counter() - t1
res["peak_gpu_mib"] = torch.cuda.max_memory_allocated(DEVICE) / 2**20
res["gpu"] = torch.cuda.get_device_name(DEVICE)
Path(args.out).write_text(json.dumps(res, indent=1))
print(args.name, "done", f"{time.perf_counter() - t0:.0f}s", flush=True)
if __name__ == "__main__":
main()