"""Tests for the auxiliary-loss weight sweep.""" import copy import importlib.util from pathlib import Path import torch import torch.nn as nn from src.train.model import MTPStack from src.train.trainer import train_step HIDDEN, VOCAB = 32, 64 _SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "phase4_lambda_sweep_train.py" _spec = importlib.util.spec_from_file_location("phase4_lambda_sweep_train", _SCRIPT) sweep = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(sweep) def _frozen_unembedding() -> nn.Module: unemb = nn.Linear(HIDDEN, VOCAB, bias=False) for p in unemb.parameters(): p.requires_grad = False return unemb def _setup(seed: int): torch.manual_seed(seed) unemb = _frozen_unembedding() stack = MTPStack(HIDDEN, unemb, 4) with torch.no_grad(): for p in stack.trainable_parameters(): p.add_(0.05 * torch.randn_like(p)) return unemb, stack, torch.randn(2, 12, HIDDEN), torch.randint(0, VOCAB, (2, 12)) def _arm(stack: MTPStack, lam: float) -> "sweep.LambdaArm": return sweep.LambdaArm( name=f"lambda_{lam:g}", lam=lam, stack=stack, optimizer=torch.optim.AdamW(stack.trainable_parameters(), lr=1e-3), loss_sums=[0.0] * stack.n_heads, ) def test_head_weights(): assert sweep.head_weight(0, 0.1) == 1.0 assert [sweep.head_weight(k, 0.25) for k in (1, 2, 3)] == [0.25, 0.25, 0.25] def test_lambda_one_is_vanilla_mtp_exactly(): """lambda = 1 must give bit-identical gradients to the Phase 3 trainer's vanilla MTP step.""" unemb, reference, hidden, block = _setup(0) pilot = copy.deepcopy(reference) ntp = MTPStack(HIDDEN, unemb, 1) train_step( hidden, block, reference, ntp, torch.optim.AdamW(reference.trainable_parameters(), lr=1e-3), torch.optim.AdamW(ntp.trainable_parameters(), lr=1e-3), nn.CrossEntropyLoss(), ) sweep.lambda_step(_arm(pilot, 1.0), hidden, block) for p_ref, p_pilot in zip(reference.trainable_parameters(), pilot.trainable_parameters()): assert torch.equal(p_ref.grad, p_pilot.grad) def test_lambda_scales_only_the_look_ahead_gradients(): """With lambda, head 1's ResBlock gradient is unchanged, look-ahead heads' ResBlock gradients scale by lambda, and the trunk gradient is g1 + lambda * (g2 + g3 + g4).""" lam = 0.25 _, base, hidden, block = _setup(1) vanilla, weighted = copy.deepcopy(base), copy.deepcopy(base) sweep.lambda_step(_arm(vanilla, 1.0), hidden, block) arm = _arm(weighted, lam) sweep.lambda_step(arm, hidden, block) for k, (hv, hw) in enumerate(zip(vanilla.heads, weighted.heads)): scale = 1.0 if k == 0 else lam for a, b in zip(hv.resblock.parameters(), hw.resblock.parameters()): assert torch.allclose(b.grad, scale * a.grad, atol=1e-7, rtol=1e-5) # rebuild the per-head trunk gradients of the vanilla model to check the mix trunk_params = list(base.trunk.parameters()) trunk_out = base.trunk_states(hidden) per_head = [] for k in range(4): logits = base.head_logits(trunk_out, k)[:, : 12 - (k + 1), :] loss = nn.functional.cross_entropy(logits.reshape(-1, VOCAB), block[:, k + 1 :].reshape(-1)) per_head.append(torch.autograd.grad(loss, trunk_params, retain_graph=True)) expected = [per_head[0][i] + lam * sum(per_head[k][i] for k in (1, 2, 3)) for i in range(len(trunk_params))] for p, e in zip(weighted.trunk.parameters(), expected): assert torch.allclose(p.grad, e, atol=1e-6, rtol=1e-5) assert arm.applied_norm_ratio > 0 and abs(arm.raw_norm_ratio - arm.applied_norm_ratio / lam) < 1e-4