"""Shape and gradient-flow checks for src.models.heads.""" import torch import torch.nn as nn from src.models.heads import MTPHead, ResBlock HIDDEN_SIZE = 16 VOCAB_SIZE = 32 BATCH, SEQ = 2, 5 def test_resblock_preserves_shape_and_starts_as_identity() -> None: block = ResBlock(HIDDEN_SIZE) x = torch.randn(BATCH, SEQ, HIDDEN_SIZE) out = block(x) assert out.shape == x.shape assert torch.allclose(out, x) # zero-init -> identity map at construction def test_mtp_head_output_shape() -> None: unembedding = nn.Linear(HIDDEN_SIZE, VOCAB_SIZE, bias=False) for p in unembedding.parameters(): p.requires_grad = False head = MTPHead(HIDDEN_SIZE, unembedding) hidden_states = torch.randn(BATCH, SEQ, HIDDEN_SIZE) logits = head(hidden_states) assert logits.shape == (BATCH, SEQ, VOCAB_SIZE) def test_gradient_flows_to_resblock_not_unembedding() -> None: unembedding = nn.Linear(HIDDEN_SIZE, VOCAB_SIZE, bias=False) for p in unembedding.parameters(): p.requires_grad = False head = MTPHead(HIDDEN_SIZE, unembedding) hidden_states = torch.randn(BATCH, SEQ, HIDDEN_SIZE, requires_grad=True) logits = head(hidden_states) logits.sum().backward() assert head.resblock.linear.weight.grad is not None assert unembedding.weight.grad is None