Normalize activations with RMSNorm

Many recent LLMs replace LayerNorm with RMSNorm: it skips subtracting the mean and only divides by the root mean square, then multiplies by a learned weight per feature.

Write rmsnorm(x, weight, eps=1e-6) where x has shape (..., d) and weight has shape (d,):

rms = sqrt(mean(x**2 over the last axis) + eps)
return x / rms * weight

Keep the input's shape. It must work for a single vector and for a batch.

Signaturedef rmsnorm(x, weight, eps=1e-6)

Understand the idea

RMSNorm rescales each vector so its typical size is about 1, then multiplies by a learned weight per feature. Unlike LayerNorm it does not subtract the mean; it only divides by the root mean square. It is like adjusting the volume of a song without changing the tune. Worked example: x = [3, 4], weight = [1, 1], tiny eps ignored. Squares are 9 and 16, mean 12.5, square root 3.536. So output = [3/3.536, 4/3.536] = [0.849, 1.131]. Each vector in a batch is normalised on its own, over the last axis only, so one row never affects another. Rule: rms = sqrt(mean(x^2 over last axis) + eps); output = x / rms * weight. Keep dims when taking the mean so it broadcasts back. Llama, Mistral and many recent LLMs use RMSNorm because it is simpler and slightly faster than LayerNorm.

Part of the advanced LLM architecture track.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: vectorrmsnorm([3.0, 4.0], [1.0, 1.0], eps=0.0)
  • Sample 2: weight scales featuresrmsnorm([1.0, 1.0], [2.0, 0.5], eps=0.0)
  • Test 3: batch is per rowrmsnorm(_x, np.ones(3), eps=0.0)[1]
  • Test 4: keeps shapelist(np.asarray(rmsnorm(np.ones((2, 3, 4)), np.ones(4))).shape)