"""Tests for the Phase 3 training stack: BPB, boundary flags, gradient isolation.""" import math import torch import torch.nn as nn from src.train.evaluate import bits_per_byte, word_start_flags from src.train.model import MTPStack from src.train.trainer import _shifted_loss HIDDEN, VOCAB = 32, 64 BATCH, SEQ = 2, 12 def _frozen_unembedding() -> nn.Module: unemb = nn.Linear(HIDDEN, VOCAB, bias=False) for p in unemb.parameters(): p.requires_grad = False return unemb def test_bits_per_byte_on_uniform_distribution(): """A uniform distribution over 256 symbols costs exactly 8 bits, so N tokens covering N bytes must come to 8.0 bits per byte.""" n = 10 total_nats = n * math.log(256) assert bits_per_byte(total_nats, n) == 8.0 def test_bits_per_byte_scales_with_byte_count(): """Halving the bytes the same loss covers doubles bits per byte.""" assert bits_per_byte(math.log(256) * 10, 5) == 16.0 def test_word_start_flags_on_hand_checked_example(): text = "ab cd" # tokens: "ab" (0,2), " cd" (2,5) -- the second opens with whitespace offsets = [(0, 2), (2, 5)] assert word_start_flags(text, offsets) == [True, True] def test_word_start_flags_marks_word_continuation(): text = "abcd" # "ab" then "cd": the second token continues the same word offsets = [(0, 2), (2, 4)] assert word_start_flags(text, offsets) == [True, False] def test_word_start_flags_ignores_zero_width_tokens(): assert word_start_flags("ab", [(0, 0)]) == [False] def test_shifted_loss_drops_positions_without_targets(): logits = torch.randn(BATCH, SEQ, VOCAB) ids = torch.randint(0, VOCAB, (BATCH, SEQ)) loss = _shifted_loss(logits, ids, 3, nn.CrossEntropyLoss()) assert loss.ndim == 0 and torch.isfinite(loss) def test_shared_trunk_couples_heads_so_d_is_measurable(): """With a shared trunk, the later heads' objectives reach head 1's input path, so training the multi-head stack is not identical to training a lone head.""" torch.manual_seed(0) unemb = _frozen_unembedding() stack = MTPStack(HIDDEN, unemb, n_heads=4, use_shared_trunk=True) hidden = torch.randn(BATCH, SEQ, HIDDEN) ids = torch.randint(0, VOCAB, (BATCH, SEQ)) loss_fn = nn.CrossEntropyLoss() trunk = stack.trunk_states(hidden) # gradient into the trunk from a later head alone must be non-zero loss = _shifted_loss(stack.head_logits(trunk, 3), ids, 4, loss_fn) loss.backward() trunk_grad = stack.trunk.linear.weight.grad assert trunk_grad is not None and trunk_grad.abs().sum() > 0 def test_without_shared_trunk_head_one_is_isolated(): """The degenerate arrangement: with no shared trunk, head 4's objective leaves head 1's parameters untouched, which is why D would be zero by construction.""" torch.manual_seed(0) unemb = _frozen_unembedding() stack = MTPStack(HIDDEN, unemb, n_heads=4, use_shared_trunk=False) hidden = torch.randn(BATCH, SEQ, HIDDEN) ids = torch.randint(0, VOCAB, (BATCH, SEQ)) trunk = stack.trunk_states(hidden) loss = _shifted_loss(stack.head_logits(trunk, 3), ids, 4, nn.CrossEntropyLoss()) loss.backward() assert stack.heads[0].resblock.linear.weight.grad is None def test_mtp_and_ntp_stacks_share_no_trainable_parameters(): """The control must be a control: no trainable tensor may be common to both.""" unemb = _frozen_unembedding() mtp = MTPStack(HIDDEN, unemb, n_heads=4, use_shared_trunk=True) ntp = MTPStack(HIDDEN, unemb, n_heads=1, use_shared_trunk=True) mtp_ids = {id(p) for p in mtp.trainable_parameters()} ntp_ids = {id(p) for p in ntp.trainable_parameters()} assert mtp_ids.isdisjoint(ntp_ids) def test_unembedding_never_enters_trainable_parameters(): unemb = _frozen_unembedding() stack = MTPStack(HIDDEN, unemb, n_heads=4, use_shared_trunk=True) trainable = {id(p) for p in stack.trainable_parameters()} assert all(id(p) not in trainable for p in unemb.parameters())