code-switch-mtp / scripts /phase4_lambda_sweep_train.py
Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
12.3 kB
"""Auxiliary-loss weight sweep: does down-weighting the look-ahead heads shrink the MTP cost?
The capacity test found that a deeper shared trunk raises the MTP cost and
that the NTP control gains far more from the added depth, which suggests the
look-ahead objectives dominate the trunk: vanilla MTP sums four
equal-weight losses, three look-ahead heads to one next-token head. Here
the objective is
L = L1 + lambda * (L2 + L3 + L4),
uniform over positions, for several lambda. lambda = 1 is vanilla MTP
exactly (each head's loss is scaled by 1.0 before its backward pass, which
leaves every gradient bit-identical).
All arms (depth-1 trunk) train in one process off one frozen-backbone
forward pass per batch, sharing one NTP control, so they see identical
batches in identical order. Besides held-out BPB, per-head accuracy and
verified acceptance, the trainer records the ratio of the look-ahead heads'
trunk-gradient norm to head 1's -- both as applied (lambda-weighted) and
unweighted -- and the cosine between the two.
"""
import argparse
import csv
import json
import logging
import os
import sys
import time
from dataclasses import dataclass, field
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 torch.nn.functional as F
import yaml
from scripts.phase4_boundary_weighted_train import build_whitespace_tables, evaluate_stacks, git_hash, ntp_step
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.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-lambda")
DEVICE = "cuda:0" # the process is already restricted to one physical GPU by the caller
LOG_EVERY_STEPS = 50
def head_weight(head_index: int, lam: float) -> float:
"""Loss weight of head `head_index` (0-based): 1 for the next-token head, lambda for look-ahead heads."""
return 1.0 if head_index == 0 else lam
def _flat_grad(module) -> torch.Tensor:
return torch.cat([p.grad.reshape(-1) for p in module.parameters()])
@dataclass
class LambdaArm:
"""One auxiliary-weight arm: an MTP stack, its optimizer, lambda and running statistics."""
name: str
lam: float
stack: MTPStack
optimizer: torch.optim.Optimizer
loss_sums: list = field(default_factory=list)
applied_norm_ratio: float = 0.0
raw_norm_ratio: float = 0.0
cos_sum: float = 0.0
def lambda_step(arm: LambdaArm, hidden: torch.Tensor, block: torch.Tensor) -> list:
"""One optimizer step on L1 + lambda * (L2 + ... + Lk); returns per-head unweighted losses."""
stack = arm.stack
arm.optimizer.zero_grad(set_to_none=True)
trunk = stack.trunk_states(hidden)
previous = None
head_grads = []
losses = []
for k in range(stack.n_heads):
offset = k + 1
logits = stack.head_logits(trunk, k)
used = logits[:, : logits.shape[1] - offset, :]
loss = F.cross_entropy(used.reshape(-1, used.shape[-1]), block[:, offset:].reshape(-1))
(head_weight(k, arm.lam) * loss).backward(retain_graph=(k < stack.n_heads - 1))
cumulative = _flat_grad(stack.trunk)
head_grads.append(cumulative if previous is None else cumulative - previous)
previous = cumulative
losses.append(float(loss.detach()))
del logits, used, loss
arm.optimizer.step()
g1 = head_grads[0]
lookahead = torch.stack(head_grads[1:]).sum(0) # as applied, i.e. already lambda-weighted
g1_norm = g1.norm().clamp_min(1e-30)
arm.applied_norm_ratio += float(lookahead.norm() / g1_norm)
if arm.lam > 0:
arm.raw_norm_ratio += float(lookahead.norm() / arm.lam / g1_norm)
arm.cos_sum += float(F.cosine_similarity(g1, lookahead, dim=0))
for k in range(stack.n_heads):
arm.loss_sums[k] += losses[k]
return losses
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("--lambdas", default="1.0,0.5,0.25,0.1")
p.add_argument("--seed", type=int, default=0)
p.add_argument("--max-steps", type=int, default=2245)
p.add_argument("--train-seconds", type=float, default=30000.0)
p.add_argument("--spec-docs", type=int, default=64)
p.add_argument("--eval-docs", type=int, default=None, help="limit held-out documents (smoke tests only)")
p.add_argument("--out", required=True)
p.add_argument("--checkpoint-dir", default="/data/cs769_mtp/scratch/checkpoints/phase4_lambda")
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)
lambdas = [float(x) for x in args.lambdas.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
opens, closes = build_whitespace_tables(tokenizer, backbone.config.vocab_size)
hidden_size = backbone.config.hidden_size
n_heads = cfg["n_heads"]
lr = cfg["learning_rate"]
arms = []
for lam in lambdas:
stack = MTPStack(hidden_size, backbone.lm_head, n_heads, True).to(DEVICE)
arms.append(LambdaArm(
name=f"lambda_{lam:g}", lam=lam, stack=stack,
optimizer=torch.optim.AdamW(stack.trainable_parameters(), lr=lr),
loss_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=lr)
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"))[: args.eval_docs]
batches = iter_batches(train_ids, cfg["batch_size"], cfg["seq_len"], args.seed, max_steps=args.max_steps)
logger.info("arms %s; max %d steps", [a.name for a in arms], args.max_steps)
torch.cuda.reset_peak_memory_stats(DEVICE)
train_start = time.perf_counter()
steps = 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()
latest = {arm.name: lambda_step(arm, hidden, block) 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} ratio {a.applied_norm_ratio / steps:.2f}" for a in arms)
logger.info("step %d tokens %d %.0f tok/s peak %.0f MiB | %s", steps, tokens, tokens / elapsed,
torch.cuda.max_memory_allocated(DEVICE) / 1024**2, 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()
stacks = {arm.name: arm.stack for arm in arms}
stacks["ntp"] = ntp
eval_start = time.perf_counter()
held = evaluate_stacks(backbone, stacks, tokenizer, heldout, DEVICE, cfg["eval_max_tokens_per_doc"])
eval_seconds = time.perf_counter() - eval_start
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", "gpu", torch.cuda.get_device_name(DEVICE), 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"]
logger.info("%s: BPB %.6f ntp %.6f D %.6f (%.2f%%); look-ahead/head-1 trunk grad norm %.2f applied, %.2f unweighted",
arm.name, h["bpb"], held["ntp"]["bpb"], d, 100 * d / held["ntp"]["bpb"],
arm.applied_norm_ratio / max(steps, 1), arm.raw_norm_ratio / max(steps, 1))
add(arm.name, "lambda", arm.lam, 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"])
add(arm.name, "trunk_grad_norm_ratio_lookahead_to_head1_applied", f"{arm.applied_norm_ratio / max(steps, 1):.6f}", steps)
add(arm.name, "trunk_grad_norm_ratio_lookahead_to_head1_unweighted", f"{arm.raw_norm_ratio / max(steps, 1):.6f}", steps)
add(arm.name, "trunk_grad_cos_head1_lookahead", f"{arm.cos_sum / max(steps, 1):.6f}", steps)
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"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"])
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():
torch.save({k: v for k, v in stack.state_dict().items() if "unembedding" not in k}, ckpt_dir / f"{name}.pt")
logger.info("saved checkpoints to %s", ckpt_dir)
if args.spec_docs > 0:
for arm in arms:
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, closes,
)
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 tokens per verification pass", arm.name, spec.mean_accepted_per_forward)
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)}, f, indent=2)
logger.info("done in %.0fs", wall)
if __name__ == "__main__":
main()