857. Fix the LayerNorm that normalises the wrong axis
Why it matters LayerNorm versus BatchNorm is a classic question, and the axis bug turns one into the other silently.
The starter code below runs, but it has a realistic bug. Read the spec, find the bug and fix it. Keep the function name and signature.
layer_norm_tokens(x, gamma, beta, eps=1e-5) should normalise each token (each row) over its features, then scale and shift: y = (x - mean) / sqrt(var + eps) * gamma + beta, with mean and population variance (ddof=0) taken over the last axis.
Inputs: x is a list or ndarray of shape (n, d). gamma and beta are lists or ndarrays of shape (d,).
Return an ndarray of floats with shape (n, d). No rounding.
def layer_norm_tokens(x, gamma, beta, eps=1e-5)Example 1
Input: layer_norm_tokens([[1.0, 2.0, 3.0]], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0])
Output: [[-1.2247, 0.0, 1.2247]]
Example 2
Input: x = [[1.0, 3.0], [10.0, 30.0]], gamma = [2.0, 1.0], beta = [0.0, 1.0]
Output: [[-1.99999, 1.999995], [-2, 2]]
Example 3
Input: x = [[5.0, 5.0, 5.0], [0.0, 1.0, 2.0]], gamma = [1.0, 1.0, 1.0], beta = [0.5, 0.5, 0.5]
Output: [[0.5, 0.5, 0.5], [-0.724736, 0.5, 1.724736]]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Run the one-row example: why is every output 0?
Hint 2
Which axis holds the features?
Hint 3
Use axis=-1 for both mean and var.
Common mistakes
- Using unbiased variance (ddof=1).
- Putting eps outside the sqrt.
- Normalising over the batch axis.
Understand the idea
LayerNorm computes statistics per example over its features, so it does not depend on the batch. Taking the mean over axis 0 computes statistics per feature over the batch, which is BatchNorm. With one row, axis 0 statistics make every value zero, which is how the first test catches it.
Shapes and data flow
x: (n, d). mean and var: (n, 1). gamma, beta: (d,).