Implement LayerNorm forward
Every transformer block normalises each token vector: subtract its mean, divide by its standard deviation, then apply a learned scale and shift.
Write layer_norm(x, gamma, beta, eps=1e-5) where x has shape (..., d) and gamma, beta have shape (d,). Normalise over the last axis using the population variance:
y = (x - mean) / sqrt(var + eps) * gamma + beta
def layer_norm(x, gamma, beta, eps=1e-5)Understand the idea
LayerNorm makes each token vector have mean 0 and variance 1 across its own features, then applies a learned scale gamma and shift beta. Each token is handled on its own, independent of the rest of the batch. Like converting each student's marks to how far they are from their own average. Worked example: x = [1, 2, 3], gamma = [1, 1, 1], beta = [0, 0, 0], eps tiny. Mean = 2. Population variance = ((-1)^2 + 0 + 1^2) / 3 = 0.667, square root 0.8165. y = [-1/0.8165, 0, 1/0.8165] = [-1.225, 0, 1.225]. With gamma = [2, 2, 2] and beta = [1, 1, 1] it becomes [-1.449, 1, 3.449]. Normalising over axis 0 instead would be BatchNorm's axis, a common bug. Rule: mean and var over the last axis (keepdims); y = (x - mean) / sqrt(var + eps) * gamma + beta. Every transformer block, including GPT and BERT, uses LayerNorm or a close variant.