code-switch-mtp / scripts /phase4_boundary_decoding.py
Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
17.7 kB
"""Phase 4b: where speculative drafts fail relative to word boundaries, and
what cutting drafts at predicted word starts would buy.
Greedy blockwise speculative decoding (draft k tokens with the heads, verify
them with one backbone pass, keep the longest matching prefix plus the
backbone's own next token) is lossless: its output is exactly the
backbone's greedy continuation, whatever the drafter does. So instead of
re-running the draft/verify loop once per policy, this script
1. generates each prompt's greedy continuation once (with a KV cache),
2. runs the backbone once over prompt + continuation and reads every
head's draft at every position,
3. replays the draft/verify loop offline for any drafting policy.
Step 3 is exact rather than approximate: a round starting at position p
drafts from the hidden state at p, which depends only on the (shared)
continuation prefix, and a draft token is accepted iff it equals the
continuation token at its position. The agreement between the continuation
and the backbone's argmax in the single re-encoding pass is logged as a
numerical sanity check.
This also corrects the Phase 3 loop (src.train.evaluate.speculative_decode),
whose verification pass covers only the first n_heads - 1 drafts: when all
four drafts are accepted it commits the fourth draft a second time instead
of the backbone's next token. Here every committed token is the backbone's.
Word starts use the Phase 3 decoding rule: a token starts a word when its
decoded piece begins with whitespace (or decodes to nothing).
"""
import argparse
import csv
import json
import logging
import os
import random
import sys
import time
from pathlib import Path
os.environ.setdefault("CUDA_DEVICE_ORDER", "PCI_BUS_ID")
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import torch
import yaml
from src.train.model import MTPStack
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("huggingface_hub").setLevel(logging.WARNING)
logger = logging.getLogger("phase4b")
DEVICE = "cuda:0" # the caller restricts the process to one physical GPU
N_HEADS = 4
LOOKAHEAD = N_HEADS + 1 # tokens past the scored horizon needed to verify the last round
FIXED_POLICIES = ("fixed1", "fixed2", "fixed3", "fixed4")
GATED_POLICIES = ("gate_before", "gate_after")
def policy_length(policy: str, draft_starts_word: list, sampled_length: int = None) -> int:
"""Number of draft tokens a policy submits for verification this round.
Args:
policy: fixedK (always K tokens), gate_before (stop before the first
draft token after the first that is predicted to start a new
word), gate_after (include that token, then stop), or
random_matched (use sampled_length, drawn to match a gated
policy's length distribution without looking at the drafts).
draft_starts_word: word-start flag of each of the n_heads draft tokens.
sampled_length: the pre-drawn length for random_matched.
"""
if policy.startswith("fixed"):
return int(policy[len("fixed"):])
if policy == "random_matched":
return sampled_length
first_start = next((i for i in range(1, len(draft_starts_word)) if draft_starts_word[i]), None)
if first_start is None:
return len(draft_starts_word)
if policy == "gate_before":
return first_start # drafts 0 .. first_start-1
if policy == "gate_after":
return first_start + 1 # drafts 0 .. first_start
raise ValueError(f"unknown policy {policy}")
def accepted_count(drafts: list, continuation: list, j: int, n_draft: int) -> int:
"""Longest prefix of the first n_draft drafts matching the continuation.
Args:
drafts: drafts[i] predicts continuation[j + 1 + i].
continuation: token ids indexed so continuation[j] is the last
committed token when the round starts at offset j.
j: round start offset.
n_draft: how many drafts the policy submits.
"""
n = 0
while n < n_draft and drafts[n] == continuation[j + 1 + n]:
n += 1
return n
def simulate_doc(drafts: list, draft_starts: list, continuation: list, token_starts: list, horizon: int, policy: str, length_draws=None) -> list:
"""Replay the draft/verify loop over one continuation; one record per verification round.
Args:
drafts: drafts[j] = the n_heads draft tokens read at offset j.
draft_starts: word-start flags of those drafts.
continuation: continuation[0] is the last prompt token, continuation[1:]
the greedy continuation (horizon + LOOKAHEAD - 1 tokens at least).
token_starts: word-start flags aligned with continuation.
horizon: commit until at least this many tokens are produced.
policy: see policy_length.
length_draws: iterator of lengths for random_matched.
"""
rounds = []
j = 0
while j < horizon:
sampled = next(length_draws) if policy == "random_matched" else None
n_draft = policy_length(policy, draft_starts[j], sampled)
n_acc = accepted_count(drafts[j], continuation, j, n_draft)
committed = n_acc + 1 # accepted drafts plus the backbone's own next token
nxt = j + committed
rounds.append(
{
"j": j,
"n_draft": n_draft,
"n_acc": n_acc,
"committed": committed,
# accepted drafts equal the continuation, and the extra token is the
# backbone's own prediction after them -- verified even when all drafts pass
"committed_tokens": continuation[j + 1 : j + 1 + committed],
"draft_starts": list(draft_starts[j]),
"true_starts": [token_starts[j + 1 + i] for i in range(N_HEADS)],
"failed_at_word_start": token_starts[j + 1 + n_acc] if n_acc < n_draft else None,
"next_round_starts_word": token_starts[nxt + 1] if nxt < horizon else None,
}
)
j = nxt
return rounds
def word_start_table(tokenizer) -> list:
"""Per vocabulary id: does the decoded piece begin with whitespace (or decode to nothing)?"""
table = []
for tid in range(len(tokenizer)):
piece = tokenizer.decode([tid])
table.append(piece[:1].isspace() or piece[:1] == "")
return table
def generate_continuations(backbone, tokenizer, texts: list, prompt_tokens: int, n_new: int, batch_size: int, eos_ids: set) -> list:
"""Greedy continuations for every document with at least prompt_tokens tokens.
Returns a list of (prompt_ids, continuation_ids); continuations stop at
the first end-of-sequence token.
"""
prompts = []
for text in texts:
ids = tokenizer(text, add_special_tokens=False, truncation=True, max_length=prompt_tokens).input_ids
if len(ids) >= prompt_tokens:
prompts.append(ids[:prompt_tokens])
out = []
for b in range(0, len(prompts), batch_size):
batch = torch.tensor(prompts[b : b + batch_size], dtype=torch.long, device=DEVICE)
with torch.no_grad():
gen = backbone.generate(
input_ids=batch,
attention_mask=torch.ones_like(batch),
max_new_tokens=n_new,
do_sample=False,
num_beams=1,
temperature=None,
top_p=None,
pad_token_id=next(iter(eos_ids)),
)
for row, prompt in zip(gen.tolist(), prompts[b : b + batch_size]):
cont = row[prompt_tokens:]
cut = next((i for i, t in enumerate(cont) if t in eos_ids), len(cont))
out.append((prompt, cont[:cut]))
return out
def load_stack(backbone, ckpt_path: Path, shared_trunk: bool) -> MTPStack:
"""Rebuild a trained stack around the backbone's frozen unembedding (skipping its stored copies)."""
stack = MTPStack(backbone.config.hidden_size, backbone.lm_head, N_HEADS, use_shared_trunk=shared_trunk).to(DEVICE)
state = torch.load(ckpt_path, map_location="cpu", weights_only=True)
state = {k: v for k, v in state.items() if ".unembedding." not in k}
missing, unexpected = stack.load_state_dict(state, strict=False)
if unexpected or any(".unembedding." not in m for m in missing):
raise RuntimeError(f"checkpoint mismatch: missing={missing} unexpected={unexpected}")
stack.eval()
return stack
@torch.no_grad()
def drafts_for_doc(backbone, stack: MTPStack, prompt: list, cont: list, horizon: int, starts_table: list) -> dict:
"""Drafts at every round-start offset 0 .. horizon-1, plus the base-argmax sanity check."""
full = torch.tensor([prompt + cont], dtype=torch.long, device=DEVICE)
p0 = len(prompt) - 1
hidden = backbone.model(input_ids=full).last_hidden_state[:, p0 : p0 + horizon, :]
trunk = stack.trunk_states(hidden)
drafts = torch.stack([stack.head_logits(trunk, i).argmax(dim=-1)[0] for i in range(N_HEADS)], dim=1).tolist()
base = backbone.lm_head(hidden).argmax(dim=-1)[0].tolist()
continuation = [prompt[-1]] + cont
agree = sum(int(base[j] == continuation[j + 1]) for j in range(horizon))
return {
"drafts": drafts,
"draft_starts": [[starts_table[t] for t in row] for row in drafts],
"continuation": continuation,
"token_starts": [starts_table[t] for t in continuation],
"base_agree": agree,
}
def aggregate(rounds: list) -> dict:
n = len(rounds)
drafted = sum(r["n_draft"] for r in rounds)
accepted = sum(r["n_acc"] for r in rounds)
committed = sum(r["committed"] for r in rounds)
return {
"verification_steps": n,
"tokens_committed": committed,
"tokens_per_step": committed / n,
"drafted_per_step": drafted / n,
"accepted_per_step": accepted / n,
"wasted_per_step": (drafted - accepted) / n,
"draft_efficiency": accepted / drafted if drafted else float("nan"),
"full_accept_rate": sum(1 for r in rounds if r["n_draft"] == N_HEADS and r["n_acc"] == N_HEADS) / n,
}
def boundary_stats(rounds: list, base_rate: float) -> dict:
"""Fixed-draft diagnostics: acceptance by draft position split by word starts, and failure location."""
stats = {}
for i in range(N_HEADS):
reached = [r for r in rounds if r["n_draft"] > i and r["n_acc"] >= i]
for label, key, flag in (
("draft_starts_word", "draft_starts", True),
("draft_continues_word", "draft_starts", False),
("true_starts_word", "true_starts", True),
("true_continues_word", "true_starts", False),
):
group = [r for r in reached if r[key][i] == flag]
acc = sum(1 for r in group if r["n_acc"] > i)
stats[f"accept_pos{i + 1}_{label}"] = (acc / len(group) if group else float("nan"), len(group))
acc_all = sum(1 for r in reached if r["n_acc"] > i)
stats[f"accept_pos{i + 1}_all"] = (acc_all / len(reached) if reached else float("nan"), len(reached))
scored = [r["next_round_starts_word"] for r in rounds if r["next_round_starts_word"] is not None]
bcr = sum(scored) / len(scored)
stats["boundary_completion_rate"] = (bcr, len(scored))
stats["word_start_base_rate_generated"] = (base_rate, None)
stats["boundary_completion_normalized"] = (bcr / base_rate, len(scored))
failed = [r["failed_at_word_start"] for r in rounds if r["failed_at_word_start"] is not None]
fail_rate = sum(failed) / len(failed)
stats["failure_token_starts_word"] = (fail_rate, len(failed))
stats["failure_token_starts_word_over_base"] = (fail_rate / base_rate, len(failed))
return stats
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--config", default="configs/phase3.yaml")
p.add_argument("--runs", nargs="+", default=["L4_seed0", "L4_seed1", "L4_notrunk", "L2_seed0", "E1_seed0"])
p.add_argument("--n-docs", type=int, default=256, help="held-out documents considered (Phase 3 used 256)")
p.add_argument("--prompt-tokens", type=int, default=256)
p.add_argument("--completion-tokens", type=int, default=64)
p.add_argument("--gen-batch", type=int, default=16)
p.add_argument("--cache-dir", default="/data/cs769_mtp/scratch/runs/phase4/continuations")
p.add_argument("--out", default="results/phase4_boundary_decoding.csv")
p.add_argument("--seed", type=int, default=0)
return p.parse_args()
def main() -> None:
from transformers import AutoModelForCausalLM, AutoTokenizer
from src.train.data import load_heldout_texts
args = parse_args()
with open(args.config, encoding="utf-8") as f:
cfg = yaml.safe_load(f)
started = time.perf_counter()
tokenizer = AutoTokenizer.from_pretrained(cfg["backbone"]["hf_id"])
backbone = AutoModelForCausalLM.from_pretrained(cfg["backbone"]["hf_id"], dtype=torch.float32).to(DEVICE)
backbone.eval()
for param in backbone.parameters():
param.requires_grad = False
eos = backbone.generation_config.eos_token_id
eos_ids = set(eos if isinstance(eos, list) else [eos])
starts_table = word_start_table(tokenizer)
cache_dir = Path(args.cache_dir)
cache_dir.mkdir(parents=True, exist_ok=True)
rows = [["run", "condition", "seed", "policy", "metric", "value", "n"]]
def add(run, policy, metric, value, n):
condition, seed = run.split("_")
rows.append([run, condition, seed, policy, metric, f"{value:.6f}" if isinstance(value, float) else value, n if n is not None else ""])
continuations = {}
for run in args.runs:
condition = run.split("_")[0]
if condition in continuations:
continue
cache = cache_dir / f"{condition}_p{args.prompt_tokens}_c{args.completion_tokens}_n{args.n_docs}.json"
if cache.exists():
continuations[condition] = json.loads(cache.read_text())
continue
gen_start = time.perf_counter()
texts = load_heldout_texts(str(Path(cfg["data_dir"]) / f"{condition}_heldout.jsonl"))[: args.n_docs]
pairs = generate_continuations(backbone, tokenizer, texts, args.prompt_tokens, args.completion_tokens + LOOKAHEAD, args.gen_batch, eos_ids)
continuations[condition] = pairs
cache.write_text(json.dumps(pairs))
logger.info("%s: %d continuations in %.0fs", condition, len(pairs), time.perf_counter() - gen_start)
for run in args.runs:
condition = run.split("_")[0]
run_start = time.perf_counter()
stack = load_stack(backbone, Path(cfg["checkpoint_dir"]) / run / "mtp.pt", shared_trunk="notrunk" not in run)
docs = []
agree = 0
scored = 0
for prompt, cont in continuations[condition]:
horizon = min(args.completion_tokens, len(cont) - LOOKAHEAD + 1)
if horizon < 1:
continue
d = drafts_for_doc(backbone, stack, prompt, cont, horizon, starts_table)
d["horizon"] = horizon
docs.append(d)
agree += d["base_agree"]
scored += horizon
base_rate = sum(sum(d["token_starts"][1 : d["horizon"] + 1]) for d in docs) / sum(d["horizon"] for d in docs)
by_policy = {}
for policy in FIXED_POLICIES + GATED_POLICIES:
by_policy[policy] = [r for d in docs for r in simulate_doc(d["drafts"], d["draft_starts"], d["continuation"], d["token_starts"], d["horizon"], policy)]
for gated in GATED_POLICIES:
lengths = [r["n_draft"] for r in by_policy[gated]]
rng = random.Random(args.seed)
draws = iter(lambda: rng.choice(lengths), None)
by_policy[f"random_matched_{gated}"] = [
r for d in docs for r in simulate_doc(d["drafts"], d["draft_starts"], d["continuation"], d["token_starts"], d["horizon"], "random_matched", draws)
]
for policy, rounds in by_policy.items():
for metric, value in aggregate(rounds).items():
add(run, policy, metric, float(value) if not isinstance(value, int) else value, len(rounds))
for metric, (value, n) in boundary_stats(by_policy["fixed4"], base_rate).items():
add(run, "fixed4", metric, float(value), n)
add(run, "all", "docs", len(docs), len(docs))
add(run, "all", "base_argmax_agreement", agree / scored, scored)
add(run, "all", "wall_seconds", time.perf_counter() - run_start, 1)
f4 = aggregate(by_policy["fixed4"])
gb = aggregate(by_policy["gate_before"])
rb = aggregate(by_policy["random_matched_gate_before"])
logger.info(
"%s: fixed4 %.3f tok/step eff %.3f | gate_before %.3f tok/step eff %.3f | length-matched random %.3f eff %.3f | %.0fs",
run, f4["tokens_per_step"], f4["draft_efficiency"], gb["tokens_per_step"], gb["draft_efficiency"],
rb["tokens_per_step"], rb["draft_efficiency"], time.perf_counter() - run_start,
)
del stack
torch.cuda.empty_cache()
add("all_all", "all", "peak_gpu_mib", torch.cuda.max_memory_allocated(DEVICE) / (1024**2), 1)
add("all_all", "all", "total_wall_seconds", time.perf_counter() - started, 1)
rows.append(["all", "all", "all", "all", "gpu", torch.cuda.get_device_name(DEVICE), 1])
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
with open(args.out, "w", newline="", encoding="utf-8") as f:
csv.writer(f).writerows(rows)
logger.info("wrote %s", args.out)
if __name__ == "__main__":
main()