8/29
Part 2 of 5 · The blockLearn and do

LayerNorm keeps each token steady

LayerNorm works on one token at a time: it moves the token's C numbers to mean 0 and spread 1. Here it is on one token's four numbers:

ln = nn.LayerNorm(4)
with torch.no_grad():
    print(ln(torch.tensor([[1., 2., 3., 10.]])).round(decimals=2))
tensor([[-0.8500, -0.5700, -0.2800,  1.7000]])

The order stays the same, the big number stays big, and the scale is now steady. LayerNorm also learns a scale and a shift of its own, which start at 1 and 0.

In the editor, x holds two tokens, four numbers each. Compute LayerNorm by hand: set mean, then var, then by_hand. The last line prints nn.LayerNorm(4) on the same x, so you can compare.