v9.1.1
Menu

Layer Normalization

easyFREETransformer ComponentsLLM 1: Foundations

Implement layer normalization for a single vector.

Layer normalization normalizes across the feature dimension: LayerNorm(x)=x−μσ2+ϵ⋅γ+β\text{LayerNorm}(x) = \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}} \cdot \gamma + \beta

where μ and σ² are the mean and variance of x (variance over the n features, dividing by n), γ (gain) and β (bias) are learnable parameters.

For this problem, use γ = 1 and β = 0 (no affine transform), and ε = 1e-5.

Input: x, a 1-D NumPy array of floats (the vector x), and eps (default 1e-5) Output: The normalized vector as a NumPy array of the same length (the tests print each value rounded to 4 decimal places).

Example

Input
1.0 2.0 3.0
Output
-1.2247 0.0000 1.2247
Reasoning
  • Input: x is one feature vector, here [1.0,2.0,3.0][1.0, 2.0, 3.0] (three features of a single token); eps is the small constant ϵ=10−5\epsilon = 10^{-5}.
  • Mean: μ=1+2+33=2\mu = \frac{1 + 2 + 3}{3} = 2.
  • Variance: average squared distance from the mean, dividing by the number of features n=3n = 3 (not n−1n-1): σ2=(−1)2+02+123=23≈0.6667\sigma^2 = \frac{(-1)^2 + 0^2 + 1^2}{3} = \frac{2}{3} \approx 0.6667.
  • Scale: σ2+ϵ=0.66668≈0.81650\sqrt{\sigma^2 + \epsilon} = \sqrt{0.66668} \approx 0.81650, so each centred value xi−μ∈{−1,0,1}x_i - \mu \in \{-1, 0, 1\} is divided by it: ±10.81650≈±1.2247\frac{\pm 1}{0.81650} \approx \pm 1.2247.
  • Output: a vector of the same length, -1.2247 0.0000 1.2247, with mean 00 and variance just under 11 (ϵ\epsilon shrinks it very slightly).
  • Notice the role of ϵ\epsilon: for a constant vector like [5,5][5, 5] the variance is 00, and ϵ\epsilon keeps the denominator nonzero so the result is all zeros instead of undefined.

Constraints

  • 1 <= dimension <= 100
  • Use ε = 1e-5 for numerical stability
  • γ = 1, β = 0
  • Round to 4 decimal places

Learn this in

More from LLM 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.