Layer Normalization
The stabilizer wrapped around every Transformer sub-layer: re-center and re-scale a vector to mean 0 and variance 1, then let two learned parameters stretch and shift it back. Keeps activations well-behaved so deep nets actually train. No numpy — just the math.
The problem
Implement layer normalization over a single vector x. Compute the mean and (population) variance of x, normalize each element to zero mean and unit variance, then apply a per-element scale gamma and shift beta: y[i] = gamma[i] · (x[i] − mean) / √(var + eps) + beta[i]. Use eps = 1e-5 for numerical stability (so a constant input does not divide by zero). Return the list y.
x=[1,2,3,4], gamma=[1,1,1,1], beta=[0,0,0,0]≈[-1.34, -0.45, 0.45, 1.34]x=[0,10], gamma=[1,1], beta=[0,0]≈[-1.0, 1.0]x=[7,7,7], gamma=[1,1,1], beta=[0,0,0][0.0, 0.0, 0.0]- Use the population variance:
mean((x − mean)²), dividing byn(notn−1). - Add
eps = 1e-5inside the square root before dividing. - gamma and beta are per-element (same length as
x) — scale then shift each normalized value. - Pyodide has no numpy — use the
mathstdlib and plain lists only.
Your turn — write it
Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.
Implement layer_norm(x, gamma, beta, eps=1e-5). Center and scale x to mean 0 / variance 1, then apply the per-element scale gamma and shift beta.
- mean = sum(x) / n; var = sum((xi - mean)**2 for xi in x) / n (divide by n).
- The denominator is sqrt(var + eps) — the eps is what saves you when var is 0.
- Normalize each element: (x[i] - mean) / denom.
- Then scale and shift: gamma[i] * normalized + beta[i].
Explore the topic
See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.