"""Phase 4c: how much the Phase 3 speculative-decoding loop's verification bug moved its numbers. src.train.evaluate.speculative_decode verifies only the first n_heads - 1 drafts (its probe is seq + drafts[:-1]). When every draft matches, it commits the fourth draft a second time as the "backbone's next token", so that token is unverified and the generated text diverges from the backbone's greedy output from then on. This runs the original loop unchanged and the corrected offline replay (scripts/phase4_boundary_decoding.py) on the same documents and checkpoints, and reports both tokens-per-verification-step values side by side with the fraction of rounds in which all four drafts were accepted. """ import argparse import csv import json import logging import os 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 scripts.phase4_boundary_decoding import ( LOOKAHEAD, aggregate, drafts_for_doc, load_stack, simulate_doc, word_start_table, ) from src.train.evaluate import speculative_decode 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("phase4c") DEVICE = "cuda:0" 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", "L2_seed0", "E1_seed0"]) p.add_argument("--n-eligible", type=int, default=64, help="documents (with a full prompt) scored per run") p.add_argument("--prompt-tokens", type=int, default=256) p.add_argument("--completion-tokens", type=int, default=64) p.add_argument("--continuations", default="/data/cs769_mtp/scratch/runs/phase4/continuations/{condition}_p256_c64_n256.json") p.add_argument("--out", default="results/phase4_decode_bug_check.csv") 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 starts_table = word_start_table(tokenizer) rows = [["run", "condition", "seed", "loop", "metric", "value", "n"]] for run in args.runs: condition, seed = run.split("_") stack = load_stack(backbone, Path(cfg["checkpoint_dir"]) / run / "mtp.pt", shared_trunk=True) # the same eligibility rule as both loops: the first held-out documents with a full prompt texts = load_heldout_texts(str(Path(cfg["data_dir"]) / f"{condition}_heldout.jsonl"))[: cfg["spec_docs"]] eligible = [t for t in texts if len(tokenizer(t, add_special_tokens=False, truncation=True, max_length=args.prompt_tokens).input_ids) >= args.prompt_tokens] subset = eligible[: args.n_eligible] t0 = time.perf_counter() buggy = speculative_decode(backbone, stack, tokenizer, subset, DEVICE, args.prompt_tokens, args.completion_tokens) buggy_seconds = time.perf_counter() - t0 pairs = json.loads(Path(args.continuations.format(condition=condition)).read_text())[: args.n_eligible] rounds = [] for prompt, cont in pairs: horizon = min(args.completion_tokens, len(cont) - LOOKAHEAD + 1) if horizon < 1: continue d = drafts_for_doc(backbone, stack, prompt, cont, horizon, starts_table) rounds += simulate_doc(d["drafts"], d["draft_starts"], d["continuation"], d["token_starts"], horizon, "fixed4") fixed = aggregate(rounds) scored = [r["next_round_starts_word"] for r in rounds if r["next_round_starts_word"] is not None] def add(loop, metric, value, n): rows.append([run, condition, seed, loop, metric, f"{value:.6f}" if isinstance(value, float) else value, n]) add("phase3_buggy", "tokens_per_step", buggy.mean_accepted_per_forward, buggy.n_rounds) add("phase3_buggy", "boundary_completion_rate", buggy.boundary_completion_rate, buggy.n_spans_scored) add("phase3_buggy", "wall_seconds", buggy_seconds, len(subset)) add("corrected", "tokens_per_step", fixed["tokens_per_step"], fixed["verification_steps"]) add("corrected", "full_accept_rate", fixed["full_accept_rate"], fixed["verification_steps"]) add("corrected", "boundary_completion_rate", sum(scored) / len(scored), len(scored)) add("both", "docs", len(subset), len(subset)) logger.info( "%s: buggy %.3f tok/step (%d rounds, %.0fs) | corrected %.3f tok/step (%d rounds), all-4-accepted %.3f", run, buggy.mean_accepted_per_forward, buggy.n_rounds, buggy_seconds, fixed["tokens_per_step"], fixed["verification_steps"], fixed["full_accept_rate"], ) del stack torch.cuda.empty_cache() rows.append(["all", "all", "all", "all", "total_wall_seconds", f"{time.perf_counter() - started:.1f}", 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()