Only the Scale

TransformersEasy+10 XP+10

Only the Scale

Layer normalization does two things to each position's vector. It recentres it (subtract the mean) and rescales it (divide by the spread), then applies a learned scale and shift. Many recent language models keep only the rescaling. Their version, RMSNorm, divides each vector by its root mean square and multiplies by a learned gain, one per slot. No mean is subtracted, and there is no shift.

For a vector x\mathbf{x}x of length ddd and gains g1,…,gdg_1, \dots, g_dg1​,…,gd​:

rms(x)=1d∑i=1dxi2+ϵ,yi=gi⋅xirms(x)\text{rms}(\mathbf{x}) = \sqrt{\frac{1}{d}\sum_{i=1}^{d} x_i^{2} + \epsilon}, \qquad y_i = g_i \cdot \frac{x_i}{\text{rms}(\mathbf{x})}rms(x)=d1​i=1∑d​xi2​+ϵ​,yi​=gi​⋅rms(x)xi​​

Here ϵ\epsilonϵ is a tiny number that prevents a division by zero when every slot is 000. It sits inside the square root.

Like layer norm, RMSNorm works on each position's vector separately: one root mean square per vector, computed from that vector alone.

Task: write rms_norm(vectors, gain, eps), where vectors is a list of position vectors, all of length ddd, and gain is a list of ddd gains. Return the normalized vectors, with every number rounded to 4 decimal places.

Dropping the recentring saves work on every vector in every layer, and in practice it works about as well. The rescaling is the part that keeps the numbers from drifting through a deep stack.

Examples

vectors = [[3.0, -1.0, 1.0, -3.0]]
gain = [1.0, 1.0, 1.0, 1.0]
eps = 0.0
returns [[1.3416, -0.4472, 0.4472, -1.3416]]
vectors = [[2.0, 2.0, 2.0, 2.0], [1.0, 2.0, 3.0, 6.0]]
gain = [0.5, 1.0, 1.5, 2.0]
eps = 0.0
returns [[0.5, 1.0, 1.5, 2.0], [0.1414, 0.5657, 1.2728, 3.3941]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run