18/30
Part 4 of 6 · Positions, targets, shapes and twinsLearn and do

A library twin checks a whole part

PyTorch already has a correct attention, and you can test yours against it.

def twin(attn: nn.Module, x: torch.Tensor) -> torch.Tensor:
    """x: (B, T, C). Returns attn's output, rebuilt on F.scaled_dot_product_attention."""
    B, T, C = x.shape
    H = attn.n_head
    q, k, v = attn.qkv(x).split(C, dim=2)
    q, k, v = (t.view(B, T, H, C // H).transpose(1, 2) for t in (q, k, v))
    y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
    return attn.proj(y.transpose(1, 2).reshape(B, T, C))

attn = model.blocks[0].attn
x = torch.randn(2, 9, attn.proj.in_features)
with torch.no_grad():
    print("max diff:", (attn(x) - twin(attn, x)).abs().max().item())

Some parts have a library version you can trust: F.scaled_dot_product_attention for attention, F.layer_norm, F.cross_entropy. A twin is your part rebuilt around that library call. Write it from what you know, not by copying the lines under test. Then give both the same weights and the same input, and print the largest difference between them.

Predict

Your attention and its twin differ by about 1e-2 on the same weights and input. What does that mean?

Pick an answer above to see the rest
Predict

You set the twin's is_causal=False, and now it matches yours exactly. What does your module do?

Pick an answer above to see the rest