code-switch-mtp / tests /test_phase4_capacity.py
Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
4.2 kB
"""Tests for the capacity test's deeper shared trunk."""
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
BLOCK_PARAMS = HIDDEN * HIDDEN + HIDDEN # one ResBlock: Linear weight + bias
_SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "phase4_capacity_train.py"
_spec = importlib.util.spec_from_file_location("phase4_capacity_train", _SCRIPT)
capacity = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(capacity)
def _frozen_unembedding() -> nn.Module:
unemb = nn.Linear(HIDDEN, VOCAB, bias=False)
for p in unemb.parameters():
p.requires_grad = False
return unemb
def _perturb(stack: nn.Module, seed: int) -> None:
torch.manual_seed(seed)
with torch.no_grad():
for p in stack.trainable_parameters():
p.add_(0.05 * torch.randn_like(p))
def test_depth_one_is_the_phase3_stack_exactly():
unemb = _frozen_unembedding()
reference = MTPStack(HIDDEN, unemb, 4, use_shared_trunk=True)
_perturb(reference, 0)
deep = capacity.DeepTrunkMTPStack(HIDDEN, unemb, 4, trunk_depth=1)
assert list(deep.state_dict().keys()) == list(reference.state_dict().keys())
deep.load_state_dict(reference.state_dict())
x = torch.randn(2, 7, HIDDEN)
assert torch.equal(deep.trunk_states(x), reference.trunk_states(x))
for k in range(4):
assert torch.equal(deep.head_logits(deep.trunk_states(x), k), reference.head_logits(reference.trunk_states(x), k))
assert capacity.count_trainable(deep) == capacity.count_trainable(reference)
def test_depth_n_trunk_shapes_and_parameter_counts():
unemb = _frozen_unembedding()
for depth in (2, 4):
for n_heads in (1, 4):
stack = capacity.DeepTrunkMTPStack(HIDDEN, unemb, n_heads, trunk_depth=depth)
assert len(stack.trunk) == depth
x = torch.randn(3, 5, HIDDEN)
assert stack.trunk_states(x).shape == x.shape
assert stack.head_logits(stack.trunk_states(x), 0).shape == (3, 5, VOCAB)
assert capacity.count_trainable(stack) == (depth + n_heads) * BLOCK_PARAMS
def test_zero_initialised_deep_trunk_starts_as_identity_and_every_block_learns():
"""Every ResBlock starts as the identity, so all depths begin from the same function;
each block still receives a nonzero gradient on the first step."""
stack = capacity.DeepTrunkMTPStack(HIDDEN, _frozen_unembedding(), 4, trunk_depth=4)
x = torch.randn(2, 6, HIDDEN)
assert torch.equal(stack.trunk_states(x), x)
logits = stack.head_logits(stack.trunk_states(x), 0)
nn.functional.cross_entropy(logits[:, :-1].reshape(-1, VOCAB), torch.randint(0, VOCAB, (2 * 5,))).backward()
for block in stack.trunk:
assert block.linear.weight.grad.abs().sum() > 0
def test_depth_one_mtp_step_matches_phase3_gradients():
unemb = _frozen_unembedding()
reference = MTPStack(HIDDEN, unemb, 4, use_shared_trunk=True)
_perturb(reference, 1)
deep = capacity.DeepTrunkMTPStack(HIDDEN, unemb, 4, trunk_depth=1)
deep.load_state_dict(reference.state_dict())
ntp = MTPStack(HIDDEN, unemb, 1)
hidden = torch.randn(2, 12, HIDDEN)
block = torch.randint(0, VOCAB, (2, 12))
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(),
)
control = capacity.DeepTrunkMTPStack(HIDDEN, unemb, 1, trunk_depth=1)
arm = capacity.CapacityArm(
name="depth1", depth=1, stack=deep, control=control,
optimizer=torch.optim.AdamW(deep.trainable_parameters(), lr=1e-3),
control_optimizer=torch.optim.AdamW(control.trainable_parameters(), lr=1e-3),
loss_sums=[0.0] * 4, cos_sums=[0.0] * 4,
)
capacity.mtp_step(arm, hidden, block)
for p_ref, p_deep in zip(reference.trainable_parameters(), deep.trainable_parameters()):
assert torch.allclose(p_ref.grad, p_deep.grad, atol=1e-6, rtol=1e-5)
assert -1.0 <= arm.cos_lookahead_sum <= 1.0