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

Every shape and every scale has a reason

When the parts look right but the numbers don't, trace them through the model.

def trace(model: nn.Module, idx: torch.Tensor) -> None:
    """Prints each embedding, LayerNorm and linear output's shape and spread."""

    def show(name: str) -> Callable:
        def hook(module: nn.Module, inputs: tuple, out: torch.Tensor) -> None:
            shape = str(tuple(out.shape))
            print(f"{name:18} {shape:14} std {out.std().item():.3f}")
        return hook
    kinds = (nn.Embedding, nn.LayerNorm, nn.Linear)
    hooks = [m.register_forward_hook(show(n))
             for n, m in model.named_modules() if isinstance(m, kinds)]
    try:
        with torch.no_grad():
            model(idx)
    finally:
        for h in hooks:
            h.remove()

In one pass, this prints the shape and the spread of what every embedding, LayerNorm and linear layer puts out. Here is part of what the healthy V=65V = 65 model prints at init, for idx of shape (2, 12):

tok_emb            (2, 12, 64)    std 0.020
pos_emb            (12, 64)       std 0.021
blocks.0.ln1       (2, 12, 64)    std 0.994
blocks.0.attn.qkv  (2, 12, 192)   std 0.161
blocks.0.attn.proj (2, 12, 64)    std 0.012
blocks.0.mlp.0     (2, 12, 256)   std 0.157
ln_f               (2, 12, 64)    std 0.998
lm_head            (2, 12, 65)    std 0.174
Predict

A linear layer with weights of spread 0.02 reads 64 inputs of spread 1. About what spread comes out?

Pick an answer above to see the rest