code-switch-mtp / scripts /phase4_boundary_weighted_train.py
Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
19.6 kB
"""Pilot: word-boundary-aware loss weighting for multi-token-prediction heads.
Phase 3 found that the far-ahead heads fail mostly where their target sits in
a later word than the next token: per-head accuracy inside a word is far
above accuracy at a word start. The hypothesis tested here is that those
cross-word targets are near-unpredictable from position t, so their
gradients are high-variance and pull the shared trunk away from what the
next-token head needs -- which is the MTP cost D.
Method: head 1's loss is untouched. For heads k = 2..4, the loss at
position t is weighted by alpha when the target token t+k lies past the
word that token t+1 belongs to (some token in t+2..t+k starts a word), and
by 1 otherwise. Each head's loss is the weighted mean sum(w * l) / sum(w),
so its scale stays comparable to the unweighted mean and alpha changes
which positions a head learns from, not how hard the head pulls overall.
alpha = 1 reproduces the Phase 3 objective exactly.
Every arm trains in one process off one frozen-backbone forward pass per
batch, together with a single NTP control. The arms therefore see
identical batches in identical order and share one baseline by
construction; they own disjoint parameters and optimizers, so sharing the
forward pass cannot couple them.
Word starts come from two vocabulary-level lookup tables -- a token's
decoded piece opens with whitespace, or the previous token's piece ends
with whitespace -- which is the packed-stream equivalent of
src.train.evaluate.word_start_flags.
For each arm the trainer also records the cosine between head 1's trunk
gradient and each far head's trunk gradient, the direct measure of the
interference the method is meant to reduce.
Speculative decoding uses scripts/phase4_speculative_eval.py's verified
loop rather than src.train.evaluate.speculative_decode, whose probe omits
the last draft and so commits an unverified duplicate when every draft is
accepted.
"""
import argparse
import csv
import json
import logging
import os
import subprocess
import time
os.environ.setdefault("CUDA_DEVICE_ORDER", "PCI_BUS_ID")
import sys
from dataclasses import dataclass, field
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import torch
import torch.nn.functional as F
import yaml
from scripts.phase4_speculative_eval import acceptance_rows, speculative_decode_verified
from src.train.data import iter_batches, load_heldout_texts, load_train_ids
from src.train.evaluate import bits_per_byte, word_start_flags
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("phase4")
DEVICE = "cuda:0" # the process is already restricted to one physical GPU by the caller
LOG_EVERY_STEPS = 50
def build_whitespace_tables(tokenizer, vocab_size: int) -> tuple:
"""Per token id: does its decoded piece open with whitespace, and does it end with whitespace."""
pieces = tokenizer.batch_decode([[i] for i in range(vocab_size)])
opens = torch.tensor([p[:1].isspace() for p in pieces], dtype=torch.bool)
closes = torch.tensor([p[-1:].isspace() for p in pieces], dtype=torch.bool)
return opens, closes
def word_start_mask(block: torch.Tensor, opens: torch.Tensor, closes: torch.Tensor) -> torch.Tensor:
"""block: (batch, seq) ids -> (batch, seq) bool, True where the token begins a word.
Position 0 has no visible predecessor in a packed block and is marked by
its own piece only; it never falls inside a t+2..t+k window anyway.
"""
starts = opens[block]
starts[:, 1:] |= closes[block[:, :-1]]
return starts
def boundary_weights(word_start: torch.Tensor, offset: int, alpha: float) -> torch.Tensor:
"""Loss weights for the head predicting `offset` tokens ahead.
Returns (batch, seq - offset) weights aligned with targets
input_ids[:, offset:]: alpha where some token in t+2..t+offset starts a
word (the target lies past the word holding token t+1), else 1.
"""
batch, seq = word_start.shape
weights = torch.ones(batch, seq - offset, dtype=torch.float32, device=word_start.device)
if offset <= 1:
return weights
cumulative = torch.cumsum(word_start.to(torch.int32), dim=1)
crossings = cumulative[:, offset:seq] - cumulative[:, 1 : seq - offset + 1]
weights[crossings > 0] = alpha
return weights
def weighted_shifted_loss(logits: torch.Tensor, input_ids: torch.Tensor, offset: int, weights: torch.Tensor) -> tuple:
"""Weighted-mean cross-entropy for the head predicting `offset` ahead.
Returns (objective, plain_mean): the objective sum(w * l) / sum(w) to
backpropagate, and the unweighted mean loss (detached) for logging.
"""
used = logits[:, : logits.shape[1] - offset, :]
targets = input_ids[:, offset:]
per_token = F.cross_entropy(used.reshape(-1, used.shape[-1]), targets.reshape(-1), reduction="none")
w = weights.reshape(-1)
objective = (per_token * w).sum() / w.sum().clamp_min(1e-8)
return objective, per_token.mean().detach()
def _flat_grad(module: torch.nn.Module) -> torch.Tensor:
return torch.cat([p.grad.reshape(-1) for p in module.parameters()])
@dataclass
class Arm:
"""One training arm: an MTP stack, its optimizer, its alpha and running statistics."""
name: str
alpha: float
stack: MTPStack
optimizer: torch.optim.Optimizer
loss_sums: list = field(default_factory=list)
cos_sums: list = field(default_factory=list)
cos_negative: list = field(default_factory=list)
weight_fraction_sums: list = field(default_factory=list)
def arm_step(arm: Arm, hidden: torch.Tensor, block: torch.Tensor, word_start: torch.Tensor) -> list:
"""One optimizer step for one arm; returns per-head unweighted mean losses."""
n_heads = arm.stack.n_heads
arm.optimizer.zero_grad(set_to_none=True)
trunk = arm.stack.trunk_states(hidden)
previous = None
head_grads = []
plain_losses = []
for k in range(n_heads):
offset = k + 1
weights = boundary_weights(word_start, offset, arm.alpha)
logits = arm.stack.head_logits(trunk, k)
objective, plain = weighted_shifted_loss(logits, block, offset, weights)
objective.backward(retain_graph=(k < n_heads - 1))
cumulative = _flat_grad(arm.stack.trunk)
head_grads.append(cumulative if previous is None else cumulative - previous)
previous = cumulative
plain_losses.append(float(plain))
arm.weight_fraction_sums[k] += float((weights < 1).float().mean())
del logits, objective
arm.optimizer.step()
for k in range(1, n_heads):
cos = float(F.cosine_similarity(head_grads[0], head_grads[k], dim=0))
arm.cos_sums[k] += cos
arm.cos_negative[k] += int(cos < 0)
for k in range(n_heads):
arm.loss_sums[k] += plain_losses[k]
return plain_losses
def ntp_step(ntp: MTPStack, optimizer: torch.optim.Optimizer, hidden: torch.Tensor, block: torch.Tensor) -> float:
optimizer.zero_grad(set_to_none=True)
logits = ntp.head_logits(ntp.trunk_states(hidden), 0)
loss = F.cross_entropy(logits[:, :-1, :].reshape(-1, logits.shape[-1]), block[:, 1:].reshape(-1))
loss.backward()
optimizer.step()
return float(loss.detach())
@torch.no_grad()
def evaluate_stacks(backbone, stacks: dict, tokenizer, texts: list, device: str, max_tokens_per_doc: int) -> dict:
"""BPB of head 1 and per-head accuracy split by word boundary, for several stacks.
Mirrors src.train.evaluate.evaluate_stack, but runs the frozen backbone
once per document for all stacks and scores every stack on the same
document set (the skip threshold uses the largest head count), so the
paired difference D compares identical text.
"""
max_heads = max(s.n_heads for s in stacks.values())
stats = {
name: {
"nats": 0.0,
"correct": [0] * s.n_heads, "seen": [0] * s.n_heads,
"correct_intra": [0] * s.n_heads, "seen_intra": [0] * s.n_heads,
"correct_bound": [0] * s.n_heads, "seen_bound": [0] * s.n_heads,
"n_tokens": 0,
}
for name, s in stacks.items()
}
total_bytes = 0
for text in texts:
enc = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True, truncation=True, max_length=max_tokens_per_doc)
ids = enc.input_ids
if len(ids) < max_heads + 2:
continue
offsets = enc.offset_mapping
starts = word_start_flags(text, offsets)
block = torch.tensor([ids], dtype=torch.long, device=device)
hidden = backbone.model(input_ids=block).last_hidden_state
total_bytes += len(text[offsets[1][0] : offsets[len(ids) - 1][1]].encode("utf-8"))
for name, stack in stacks.items():
st = stats[name]
trunk = stack.trunk_states(hidden)
for k in range(stack.n_heads):
offset = k + 1
logits = stack.head_logits(trunk, k)[:, : len(ids) - offset, :]
targets = block[:, offset:]
if k == 0:
st["nats"] += float(F.cross_entropy(logits.reshape(-1, logits.shape[-1]), targets.reshape(-1), reduction="sum"))
st["n_tokens"] += targets.numel()
hits = logits.argmax(dim=-1)[0] == targets[0]
is_start = torch.tensor(starts[offset : offset + hits.numel()], device=device, dtype=torch.bool)
st["correct"][k] += int(hits.sum())
st["seen"][k] += int(hits.numel())
st["correct_bound"][k] += int((hits & is_start).sum())
st["seen_bound"][k] += int(is_start.sum())
st["correct_intra"][k] += int((hits & ~is_start).sum())
st["seen_intra"][k] += int((~is_start).sum())
del logits
def ratio(c: int, s: int) -> float:
return c / s if s else float("nan")
out = {}
for name, st in stats.items():
n = len(st["correct"])
out[name] = {
"bpb": bits_per_byte(st["nats"], total_bytes),
"acc": [ratio(st["correct"][k], st["seen"][k]) for k in range(n)],
"acc_intra": [ratio(st["correct_intra"][k], st["seen_intra"][k]) for k in range(n)],
"acc_bound": [ratio(st["correct_bound"][k], st["seen_bound"][k]) for k in range(n)],
"n_tokens": st["n_tokens"],
"n_bytes": total_bytes,
}
return out
def git_hash() -> str:
try:
return subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
except subprocess.CalledProcessError:
return "unknown"
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--config", default="configs/phase3.yaml")
p.add_argument("--condition", default="L2", choices=["L2", "L4", "E1"])
p.add_argument("--alphas", default="1.0,0.25,0.0", help="comma-separated alpha per arm; 1.0 is the Phase 3 objective")
p.add_argument("--seed", type=int, default=0)
p.add_argument("--max-steps", type=int, default=9765)
p.add_argument("--train-seconds", type=float, required=True, help="wall-clock training budget; every arm stops at the same step")
p.add_argument("--spec-docs", type=int, default=64)
p.add_argument("--spec-deadline-unix", type=float, default=None, help="skip speculative decoding for arms not started by this time")
p.add_argument("--out", required=True, help="output CSV path")
p.add_argument("--checkpoint-dir", default="/data/cs769_mtp/scratch/checkpoints/phase4")
return p.parse_args()
def main() -> None:
from transformers import AutoModelForCausalLM, AutoTokenizer
args = parse_args()
with open(args.config, encoding="utf-8") as f:
cfg = yaml.safe_load(f)
alphas = [float(a) for a in args.alphas.split(",")]
torch.manual_seed(args.seed)
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
vocab_size = backbone.config.vocab_size
opens, closes = build_whitespace_tables(tokenizer, vocab_size)
opens, closes = opens.to(DEVICE), closes.to(DEVICE)
logger.info("word-start tables: %d of %d pieces open with whitespace", int(opens.sum()), vocab_size)
hidden_size = backbone.config.hidden_size
n_heads = cfg["n_heads"]
arms = []
for alpha in alphas:
stack = MTPStack(hidden_size, backbone.lm_head, n_heads, True).to(DEVICE)
arms.append(Arm(
name=f"alpha_{alpha:g}", alpha=alpha, stack=stack,
optimizer=torch.optim.AdamW(stack.trainable_parameters(), lr=cfg["learning_rate"]),
loss_sums=[0.0] * n_heads, cos_sums=[0.0] * n_heads, cos_negative=[0] * n_heads,
weight_fraction_sums=[0.0] * n_heads,
))
ntp = MTPStack(hidden_size, backbone.lm_head, 1, True).to(DEVICE)
ntp_optimizer = torch.optim.AdamW(ntp.trainable_parameters(), lr=cfg["learning_rate"])
ntp_loss_sum = 0.0
data_dir = Path(cfg["data_dir"])
train_ids = load_train_ids(str(data_dir / f"{args.condition}_train_ids.npy"))
heldout = load_heldout_texts(str(data_dir / f"{args.condition}_heldout.jsonl"))
batches = iter_batches(train_ids, cfg["batch_size"], cfg["seq_len"], args.seed, max_steps=args.max_steps)
logger.info("arms %s; %d train tokens available; budget %.0fs", [a.name for a in arms], len(train_ids), args.train_seconds)
torch.cuda.reset_peak_memory_stats(DEVICE)
train_start = time.perf_counter()
steps = 0
tokens = 0
for block in batches:
if time.perf_counter() - train_start >= args.train_seconds:
break
block = block.to(DEVICE)
with torch.no_grad():
hidden = backbone.model(input_ids=block).last_hidden_state.detach()
starts = word_start_mask(block, opens, closes)
latest = {arm.name: arm_step(arm, hidden, block, starts) for arm in arms}
ntp_loss_sum += ntp_step(ntp, ntp_optimizer, hidden, block)
steps += 1
tokens += block.numel()
if steps % LOG_EVERY_STEPS == 0:
elapsed = time.perf_counter() - train_start
parts = " | ".join(
f"{a.name} h1 {latest[a.name][0]:.4f} cos12 {a.cos_sums[1] / steps:+.3f}" for a in arms
)
logger.info("step %d tokens %d %.0f tok/s | %s", steps, tokens, tokens / elapsed, parts)
train_seconds = time.perf_counter() - train_start
logger.info("training done: %d steps, %d tokens per arm, %.0fs, %.1f tok/s", steps, tokens, train_seconds, tokens / train_seconds)
for arm in arms:
arm.stack.eval()
ntp.eval()
eval_start = time.perf_counter()
stacks = {arm.name: arm.stack for arm in arms}
stacks["ntp"] = ntp
held = evaluate_stacks(backbone, stacks, tokenizer, heldout, DEVICE, cfg["eval_max_tokens_per_doc"])
eval_seconds = time.perf_counter() - eval_start
for arm in arms:
d = held[arm.name]["bpb"] - held["ntp"]["bpb"]
logger.info("%s: BPB %.6f ntp %.6f D %.6f (%.2f%%)", arm.name, held[arm.name]["bpb"], held["ntp"]["bpb"], d, 100 * d / held["ntp"]["bpb"])
rows = [["arm", "metric", "value", "n"]]
def add(arm_name: str, metric: str, value, n) -> None:
rows.append([arm_name, metric, value, n])
def write_rows() -> None:
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)
add("all", "condition", args.condition, 1)
add("all", "seed", args.seed, 1)
add("all", "train_steps", steps, 1)
add("all", "train_tokens_per_arm", tokens, 1)
add("all", "train_seconds", f"{train_seconds:.1f}", 1)
add("all", "train_tokens_per_second", f"{tokens / train_seconds:.3f}", 1)
add("all", "eval_seconds", f"{eval_seconds:.1f}", 1)
add("ntp", "train_loss_nats", f"{ntp_loss_sum / max(steps, 1):.6f}", steps)
add("ntp", "bpb", f"{held['ntp']['bpb']:.6f}", held["ntp"]["n_bytes"])
add("ntp", "head1_accuracy", f"{held['ntp']['acc'][0]:.6f}", held["ntp"]["n_tokens"])
for arm in arms:
h = held[arm.name]
d = h["bpb"] - held["ntp"]["bpb"]
add(arm.name, "alpha", arm.alpha, 1)
add(arm.name, "bpb_head1", f"{h['bpb']:.6f}", h["n_bytes"])
add(arm.name, "d_bpb_mtp_minus_ntp", f"{d:.6f}", h["n_bytes"])
add(arm.name, "d_relative_pct", f"{100 * d / held['ntp']['bpb']:.4f}", h["n_bytes"])
for k in range(n_heads):
add(arm.name, f"train_loss_head{k + 1}_nats", f"{arm.loss_sums[k] / max(steps, 1):.6f}", steps)
add(arm.name, f"downweighted_fraction_head{k + 1}", f"{arm.weight_fraction_sums[k] / max(steps, 1):.6f}", steps)
add(arm.name, f"head{k + 1}_accuracy", f"{h['acc'][k]:.6f}", h["n_tokens"])
add(arm.name, f"head{k + 1}_accuracy_intraword", f"{h['acc_intra'][k]:.6f}", h["n_tokens"])
add(arm.name, f"head{k + 1}_accuracy_boundary", f"{h['acc_bound'][k]:.6f}", h["n_tokens"])
for k in range(1, n_heads):
add(arm.name, f"trunk_grad_cos_head1_head{k + 1}", f"{arm.cos_sums[k] / max(steps, 1):.6f}", steps)
add(arm.name, f"trunk_grad_cos_negative_frac_head{k + 1}", f"{arm.cos_negative[k] / max(steps, 1):.6f}", steps)
add("all", "peak_gpu_mib_train_eval", f"{torch.cuda.max_memory_allocated(DEVICE) / 1024**2:.1f}", 1)
write_rows()
logger.info("wrote held-out rows to %s", args.out)
ckpt_dir = Path(args.checkpoint_dir) / f"{args.condition}_seed{args.seed}"
ckpt_dir.mkdir(parents=True, exist_ok=True)
for name, stack in stacks.items():
trainable = {k: v for k, v in stack.state_dict().items() if "unembedding" not in k}
torch.save(trainable, ckpt_dir / f"{name}.pt")
for arm in arms:
if args.spec_deadline_unix is not None and time.time() > args.spec_deadline_unix:
add(arm.name, "mean_accepted_per_forward", "skipped_time", 0)
logger.info("%s: speculative decoding skipped (deadline)", arm.name)
continue
spec_start = time.perf_counter()
spec = speculative_decode_verified(
backbone, arm.stack, tokenizer, heldout[: args.spec_docs], DEVICE,
cfg["spec_prompt_tokens"], cfg["spec_completion_tokens"], opens.cpu(), closes.cpu(),
)
rows.extend(acceptance_rows(arm.name, spec))
add(arm.name, "spec_seconds", f"{time.perf_counter() - spec_start:.1f}", args.spec_docs)
logger.info("%s: %.4f accepted/forward over %d rounds", arm.name, spec.mean_accepted_per_forward, spec.n_rounds)
write_rows()
wall = time.perf_counter() - started
add("all", "wall_seconds", f"{wall:.1f}", 1)
add("all", "peak_gpu_mib", f"{torch.cuda.max_memory_allocated(DEVICE) / 1024**2:.1f}", 1)
write_rows()
with open(Path(args.out).with_suffix(".json"), "w", encoding="utf-8") as f:
json.dump({"command": " ".join(sys.argv), "git_hash": git_hash(), "wall_seconds": round(wall, 1),
"gpu": torch.cuda.get_device_name(DEVICE)}, f, indent=2)
logger.info("done in %.0fs", wall)
if __name__ == "__main__":
main()