Download scripts/phase4_capacity_train.py from Anupam-Rawat-IITB/code-switch-mtp: direct link, hf CLI and curl.
- Browser
- Download file 13.2 kB
-
https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase4_capacity_train.py
- Command line
-
hf download hf://Anupam-Rawat-IITB/code-switch-mtp/scripts/phase4_capacity_train.py
-
curl -L -o phase4_capacity_train.py https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase4_capacity_train.py
13.2 kB
| """Capacity test: does a deeper shared trunk shrink the MTP cost? | |
| Hypothesis: the MTP cost D exists because one small shared trunk (a single | |
| ResBlock, ~4.2M parameters) has to serve four heads. If so, giving the | |
| trunk more depth should shrink D. | |
| Arms differ only in trunk depth (1, 2 or 4 zero-initialised ResBlocks, so | |
| every trunk starts as the identity). Each arm owns its own single-head | |
| control with a trunk of the SAME depth, so D = BPB(MTP head 1) - BPB(control) | |
| always compares equal per-path capacity, as in Phase 3. Every arm and | |
| control trains in one process off one frozen-backbone forward pass per | |
| batch, so all of them see identical batches in identical order. | |
| Besides held-out BPB, per-head accuracy and verified acceptance, the | |
| trainer records the cosine between head 1's trunk gradient and the summed | |
| look-ahead heads' trunk gradient on the shared parameters. | |
| """ | |
| 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 as nn | |
| 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.models.heads import ResBlock | |
| 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-capacity") | |
| DEVICE = "cuda:0" # the process is already restricted to one physical GPU by the caller | |
| LOG_EVERY_STEPS = 50 | |
| class DeepTrunkMTPStack(MTPStack): | |
| """MTPStack whose shared trunk is `trunk_depth` ResBlocks in sequence. | |
| Depth 1 keeps MTPStack's own single ResBlock untouched, so it is the | |
| Phase 3 stack exactly (same modules, same state_dict keys). | |
| """ | |
| def __init__(self, hidden_size: int, unembedding: nn.Module, n_heads: int, trunk_depth: int) -> None: | |
| super().__init__(hidden_size, unembedding, n_heads, use_shared_trunk=True) | |
| if trunk_depth < 1: | |
| raise ValueError("trunk_depth must be >= 1") | |
| self.trunk_depth = trunk_depth | |
| if trunk_depth > 1: | |
| self.trunk = nn.Sequential(*[ResBlock(hidden_size) for _ in range(trunk_depth)]) | |
| def count_trainable(stack: MTPStack) -> int: | |
| return sum(p.numel() for p in stack.trainable_parameters()) | |
| def _flat_grad(module: nn.Module) -> torch.Tensor: | |
| return torch.cat([p.grad.reshape(-1) for p in module.parameters()]) | |
| class CapacityArm: | |
| """One trunk depth: an MTP stack, its same-depth control, their optimizers and running statistics.""" | |
| name: str | |
| depth: int | |
| stack: DeepTrunkMTPStack | |
| control: DeepTrunkMTPStack | |
| optimizer: torch.optim.Optimizer | |
| control_optimizer: torch.optim.Optimizer | |
| loss_sums: list = field(default_factory=list) | |
| control_loss_sum: float = 0.0 | |
| cos_sums: list = field(default_factory=list) | |
| cos_lookahead_sum: float = 0.0 | |
| cos_lookahead_negative: int = 0 | |
| def mtp_step(arm: CapacityArm, hidden: torch.Tensor, block: torch.Tensor) -> list: | |
| """One optimizer step of the MTP stack, recording per-head trunk-gradient cosines; returns per-head 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)) | |
| 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() | |
| for k in range(1, stack.n_heads): | |
| arm.cos_sums[k] += float(F.cosine_similarity(head_grads[0], head_grads[k], dim=0)) | |
| lookahead_cos = float(F.cosine_similarity(head_grads[0], torch.stack(head_grads[1:]).sum(0), dim=0)) | |
| arm.cos_lookahead_sum += lookahead_cos | |
| arm.cos_lookahead_negative += int(lookahead_cos < 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("--depths", default="1,2,4") | |
| 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_capacity") | |
| 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) | |
| depths = [int(d) for d in args.depths.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 depth in depths: | |
| stack = DeepTrunkMTPStack(hidden_size, backbone.lm_head, n_heads, depth).to(DEVICE) | |
| control = DeepTrunkMTPStack(hidden_size, backbone.lm_head, 1, depth).to(DEVICE) | |
| arms.append(CapacityArm( | |
| name=f"depth{depth}", depth=depth, stack=stack, control=control, | |
| optimizer=torch.optim.AdamW(stack.trainable_parameters(), lr=lr), | |
| control_optimizer=torch.optim.AdamW(control.trainable_parameters(), lr=lr), | |
| loss_sums=[0.0] * n_heads, cos_sums=[0.0] * n_heads, | |
| )) | |
| logger.info("depth %d: trainable mtp=%d control=%d", depth, count_trainable(stack), count_trainable(control)) | |
| 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) | |
| 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 = {} | |
| for arm in arms: | |
| latest[arm.name] = mtp_step(arm, hidden, block) | |
| arm.control_loss_sum += ntp_step(arm.control, arm.control_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} cosLA {a.cos_lookahead_sum / steps:+.3f}" 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) | |
| stacks = {} | |
| for arm in arms: | |
| arm.stack.eval() | |
| arm.control.eval() | |
| stacks[arm.name] = arm.stack | |
| stacks[f"{arm.name}_control"] = arm.control | |
| 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) | |
| for arm in arms: | |
| h, c = held[arm.name], held[f"{arm.name}_control"] | |
| d = h["bpb"] - c["bpb"] | |
| logger.info("%s: BPB %.6f control %.6f D %.6f (%.2f%%), cos(head1, look-ahead) %+.3f", | |
| arm.name, h["bpb"], c["bpb"], d, 100 * d / c["bpb"], arm.cos_lookahead_sum / max(steps, 1)) | |
| add(arm.name, "trunk_depth", arm.depth, 1) | |
| add(arm.name, "trainable_params_mtp", count_trainable(arm.stack), 1) | |
| add(arm.name, "trainable_params_control", count_trainable(arm.control), 1) | |
| add(arm.name, "bpb_head1", f"{h['bpb']:.6f}", h["n_bytes"]) | |
| add(arm.name, "bpb_control", f"{c['bpb']:.6f}", c["n_bytes"]) | |
| add(arm.name, "d_bpb_mtp_minus_control", f"{d:.6f}", h["n_bytes"]) | |
| add(arm.name, "d_relative_pct", f"{100 * d / c['bpb']:.4f}", h["n_bytes"]) | |
| add(arm.name, "control_head1_accuracy", f"{c['acc'][0]:.6f}", c["n_tokens"]) | |
| add(arm.name, "control_train_loss_nats", f"{arm.control_loss_sum / max(steps, 1):.6f}", steps) | |
| add(arm.name, "trunk_grad_cos_head1_lookahead", f"{arm.cos_lookahead_sum / max(steps, 1):.6f}", steps) | |
| add(arm.name, "trunk_grad_cos_head1_lookahead_negative_frac", f"{arm.cos_lookahead_negative / 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"]) | |
| if k > 0: | |
| add(arm.name, f"trunk_grad_cos_head1_head{k + 1}", f"{arm.cos_sums[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(): | |
| 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() | |