287. 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)LayerNorm on one token's features
Each feature becomes (x − mean) / √(var + ε) · γ + β. Drag a feature and every output moves, because they share one mean and variance.
- mean
- 0.75
- variance
- 3.813
- output mean
- 1.39e-17
Example 1
Input: layer_norm([[-4.2, 3.3, 2.0, 4.5], [-4.6, 7.5, 2.5, -3.9], [-4.8, -4.5, -1.6, 7.9]], [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0])
Output: [[-1.6707, 0.5668, 0.179, 0.9249], [-1.0035, 1.4372, 0.4286, -0.8623], [-0.7867, -0.7284, -0.1651, 1.6802]]
Constraints
xhas shape(..., d)betahas shape(d,)- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
Each token vector is normalised on its own, so all the statistics are taken over the last axis only.
Hint 2
Compute the mean and population variance with axis=-1, subtract and divide by np.sqrt(var + eps), then multiply by gamma and add beta.
Hint 3
Pass keepdims=True to mean and var so they keep shape (..., 1) and broadcast back against x; np.var already uses the population variance.
Common mistakes
- Normalising over axis 0 is BatchNorm's axis, which is the bug in the buggy version.
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.
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.
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.
Topics
Companies1
- ByteDance a candidate reported this question TikTok Machine Learning Engineer Interview (questions, process, prep)
From public interview reports and guides. Not affiliated with or endorsed by these companies.