The neural notebook
← All chapters

IV-31 / Part VII · Transformer Blocks

Layer Normalization and RMS Normalization

Hand-calculate feature-only mean, population variance, stabilized denominators and affine outputs, comparing LayerNorm with standard scale-only RMSNorm.

Review the ideas this chapter uses

Two token rows can have similar differences between their features but very different common offsets or magnitudes. Normalization calculates a scale from each row before passing values onward. Layer normalization also subtracts the row’s mean; RMS normalization keeps that mean information. We will calculate both on the same tiny inputs and see why their outputs can disagree even for a constant row.

Learning objective: Compute mean, variance/RMS, epsilon and affine scale parameters.

Follow IV-30 — Residual Connections and Gradient Paths for the residual path being composed with these components. Book II’s VIII.3 — Error propagation and conditioning explains conditioning: how sensitive a result is to input errors. Book III’s III-41 — Composition and Learned Representations supplies neural-network context. This chapter isolates forward normalization; it neither trains a network nor demonstrates a guarantee about training gradients.

Edit one token; inspect both variants

Compute it yourself

Layer Normalization and RMS Normalization

These controls recompute the actual example. Trace navigation shows saved calculation steps; editing starts a new trace from the displayed inputs.

Complete results from this trace’s starting inputs

Starting inputs for these results
B
1
T
3
x000
3
x001
1
x010
2
x011
2
x020
-1
x021
1
x100
1
x101
-1
x110
0
x111
0
x120
-2
x121
3
gamma0
1
gamma1
1
beta0
0
beta1
0
epsilon
3
B1
T3
epsilon3
ln0000.5
Input token rows X
Feature scales gamma
LayerNorm offsets beta

B 1. T 3. epsilon 3. ln000 0.5. Validate all feature-normalization inputs. All 19 stored fields are validated, including inactive X. Both LN and scale-only RMS are always computed. Epsilon=3 is a hand-friendly teaching default, not a production recommendation.. B 1. T 3. D 2. epsilon 3

Validate all feature-normalization inputs

D=2; normalize each X[b,t,:] independently; epsilon>0 inside sqrt

All 19 stored fields are validated, including inactive X. Both LN and scale-only RMS are always computed. Epsilon=3 is a hand-friendly teaching default, not a production recommendation.

Inputs

B
1
T
3
x000
3
x001
1
x010
2
x011
2
x020
-1
x021
1
x100
1
x101
-1
x110
0
x111
0
x120
-2
x121
3
gamma0
1
gamma1
1
beta0
0
beta1
0
epsilon
3

Outputs

B
1
T
3
D
2
epsilon
3

Two feature-only normalization variants, computed side by side

Showing batch 0, token 0, feature 0. Selectors change the view only; the graded live question always uses batch 0, token 0, feature 0. Trace navigation selects a saved operation independently.

Selected trace operation: setup. Matching saved rows below are marked current. Operations outside this view remain available in Calculation step above.

X: batch 0

B=1 × T=3 × D=2 · float64 · precision 8. Feature-last active rows, two features per token.

X: batch 0; actual saved binary64 values without display rounding
TokenFeature 0Feature 1
031
122
2-11

Each row has D=2 features. LN subtracts this row’s mean; RMS uses the original features. Both put strictly positive epsilon inside the square root. Neither mixes tokens or batches. Epsilon=3; the default 3 makes hand examples friendly and is not a recommended production setting.

gamma: shared feature scales

D=2 · float64 · precision 8. Per-feature scale shared across batches and tokens, used by both variants.

gamma: shared feature scales; actual saved binary64 values without display rounding
Scale rowFeature 0Feature 1
011

beta: LN-only shared offsets

D=2 · float64 · precision 8. Per-feature offset used only by LN; validated but never applied to scale-only RMS.

beta: LN-only shared offsets; actual saved binary64 values without display rounding
Offset rowFeature 0Feature 1
000

Full saved LayerNorm statistics and affine operations

LN statistics for batch 0, token 0; actual saved binary64 values without display rounding
Saved stepInput x0Input x1Input epsilonResult sumResult meanResult centered0Result centered1Result square0Result square1Result squareSumResult varianceResult variancePlusEpsilonResult denominator
ln_0_0_statistics313421-1112142

Saved ln_0_0_statistics: sum=4, mean=2; centered features (1, -1); squares (1, 1); square sum=2; population variance=1; variance+epsilon=4; denominator=2.

LN feature affines for batch 0, token 0; actual saved binary64 values without display rounding
Saved stepInput dInput sourceInput denominatorInput gammaInput betaResult normalizedResult scaledResult value
ln_0_0_feature_0012100.50.50.5
ln_0_0_feature_11-1210-0.5-0.5-0.5

Saved ln_0_0_feature_0: source/denominator=1/2=0.5; gamma×normalized=0.5; plus beta 0 gives LN[0,0,0]=0.5.

mean: batch 0

B=1 × T=3 × Statistic=1 · float64 · precision 8. LN sum of two features divided by D=2, separately per token.

mean: batch 0; actual saved binary64 values without display rounding
TokenStatistic 0
02
12
20

variance: batch 0

B=1 × T=3 × Statistic=1 · float64 · precision 8. Population variance: sum of centered feature squares divided by 2, not 1.

variance: batch 0; actual saved binary64 values without display rounding
TokenStatistic 0
01
10
21

lnDenominator: batch 0

B=1 × T=3 × Statistic=1 · float64 · precision 8. sqrt(variance+epsilon); epsilon is strictly positive and inside sqrt.

lnDenominator: batch 0; actual saved binary64 values without display rounding
TokenStatistic 0
02
11.7320508075688772
22

centered: batch 0

B=1 × T=3 × D=2 · float64 · precision 8. X minus that token’s feature mean.

centered: batch 0; actual saved binary64 values without display rounding
TokenFeature 0Feature 1
01-1
100
2-11

LNNormalized: batch 0

B=1 × T=3 × D=2 · float64 · precision 8. centered/sqrt(variance+epsilon), before gamma and beta.

LNNormalized: batch 0; actual saved binary64 values without display rounding
TokenFeature 0Feature 1
00.5-0.5
100
2-0.50.5

LN: batch 0

B=1 × T=3 × D=2 · float64 · precision 8. gamma*LNNormalized+beta; no promise of output zero mean or unit variance.

LN: batch 0; actual saved binary64 values without display rounding
TokenFeature 0Feature 1
00.5-0.5
100
2-0.50.5

Full saved scale-only RMS statistics and feature operations

RMS statistics for batch 0, token 0; actual saved binary64 values without display rounding
Saved stepInput x0Input x1Input epsilonResult square0Result square1Result squareSumResult meanSquareResult meanSquarePlusEpsilonResult denominator
rms_0_0_statistics3139110582.8284271247461903

Saved rms_0_0_statistics: original feature squares (9, 1); sum=10; mean square=5; meanSquare+epsilon=8; denominator=2.8284271247461903. There is no mean subtraction.

RMS feature scales for batch 0, token 0; actual saved binary64 values without display rounding
Saved stepInput dInput sourceInput denominatorInput gammaResult normalizedResult scaledResult value
rms_0_0_feature_0032.828427124746190311.06066017177982121.06066017177982121.0606601717798212
rms_0_0_feature_1112.828427124746190310.353553390593273730.353553390593273730.35355339059327373

Saved rms_0_0_feature_0: source/denominator=3/2.8284271247461903=1.0606601717798212; gamma×normalized gives RMS[0,0,0]=1.0606601717798212. Beta is validated but unused in this standard scale-only RMS choice.

meanSquare: batch 0

B=1 × T=3 × Statistic=1 · float64 · precision 8. RMS sum of original feature squares divided by 2, with no mean subtraction.

meanSquare: batch 0; actual saved binary64 values without display rounding
TokenStatistic 0
05
14
21

rmsDenominator: batch 0

B=1 × T=3 × Statistic=1 · float64 · precision 8. sqrt(meanSquare+epsilon).

rmsDenominator: batch 0; actual saved binary64 values without display rounding
TokenStatistic 0
02.8284271247461903
12.6457513110645907
22

RMSNormalized: batch 0

B=1 × T=3 × D=2 · float64 · precision 8. Original X divided by the token’s rmsDenominator.

RMSNormalized: batch 0; actual saved binary64 values without display rounding
TokenFeature 0Feature 1
01.06066017177982120.35355339059327373
10.75592894601845440.7559289460184544
2-0.50.5

RMS: batch 0

B=1 × T=3 × D=2 · float64 · precision 8. gamma*RMSNormalized; standard scale-only RMS has no beta addition.

RMS: batch 0; actual saved binary64 values without display rounding
TokenFeature 0Feature 1
01.06066017177982120.35355339059327373
10.75592894601845440.7559289460184544
2-0.50.5

A constant LN row maps to beta; a nonzero constant RMS row generally stays nonzero. Before gamma/beta, LN’s population variance is variance/(variance+epsilon), generally below 1. The affine parameters can change its mean and scale further. Epsilon breaks exact positive rescale invariance; RMS is not generally invariant to additive shifts. This lab makes no training or norm-gradient guarantee.

Inspect tensor shapes and full precision

All computed outputs

B
1
T
3
epsilon
3
ln000
0.5
ln001
-0.5
ln010
0
ln011
0
ln020
-0.5
ln021
0.5
rms000
1.0606601717798212
rms001
0.35355339059327373
rms010
0.7559289460184544
rms011
0.7559289460184544
rms020
-0.5
rms021
0.5
mu00
2
var00
1
ms00
5
mu01
2
var01
0
ms01
4
mu02
0
var02
1
ms02
1
setup_B
1
setup_T
3
setup_D
2
setup_epsilon
3
ln_0_0_statistics_sum
4
ln_0_0_statistics_mean
2
ln_0_0_statistics_centered0
1
ln_0_0_statistics_centered1
-1
ln_0_0_statistics_square0
1
ln_0_0_statistics_square1
1
ln_0_0_statistics_squareSum
2
ln_0_0_statistics_variance
1
ln_0_0_statistics_variancePlusEpsilon
4
ln_0_0_statistics_denominator
2
ln_0_0_feature_0_normalized
0.5
ln_0_0_feature_0_scaled
0.5
ln_0_0_feature_0_value
0.5
ln_0_0_feature_1_normalized
-0.5
ln_0_0_feature_1_scaled
-0.5
ln_0_0_feature_1_value
-0.5
ln_0_1_statistics_sum
4
ln_0_1_statistics_mean
2
ln_0_1_statistics_centered0
0
ln_0_1_statistics_centered1
0
ln_0_1_statistics_square0
0
ln_0_1_statistics_square1
0
ln_0_1_statistics_squareSum
0
ln_0_1_statistics_variance
0
ln_0_1_statistics_variancePlusEpsilon
3
ln_0_1_statistics_denominator
1.7320508075688772
ln_0_1_feature_0_normalized
0
ln_0_1_feature_0_scaled
0
ln_0_1_feature_0_value
0
ln_0_1_feature_1_normalized
0
ln_0_1_feature_1_scaled
0
ln_0_1_feature_1_value
0
ln_0_2_statistics_sum
0
ln_0_2_statistics_mean
0
ln_0_2_statistics_centered0
-1
ln_0_2_statistics_centered1
1
ln_0_2_statistics_square0
1
ln_0_2_statistics_square1
1
ln_0_2_statistics_squareSum
2
ln_0_2_statistics_variance
1
ln_0_2_statistics_variancePlusEpsilon
4
ln_0_2_statistics_denominator
2
ln_0_2_feature_0_normalized
-0.5
ln_0_2_feature_0_scaled
-0.5
ln_0_2_feature_0_value
-0.5
ln_0_2_feature_1_normalized
0.5
ln_0_2_feature_1_scaled
0.5
ln_0_2_feature_1_value
0.5
rms_0_0_statistics_square0
9
rms_0_0_statistics_square1
1
rms_0_0_statistics_squareSum
10
rms_0_0_statistics_meanSquare
5
rms_0_0_statistics_meanSquarePlusEpsilon
8
rms_0_0_statistics_denominator
2.8284271247461903
rms_0_0_feature_0_normalized
1.0606601717798212
rms_0_0_feature_0_scaled
1.0606601717798212
rms_0_0_feature_0_value
1.0606601717798212
rms_0_0_feature_1_normalized
0.35355339059327373
rms_0_0_feature_1_scaled
0.35355339059327373
rms_0_0_feature_1_value
0.35355339059327373
rms_0_1_statistics_square0
4
rms_0_1_statistics_square1
4
rms_0_1_statistics_squareSum
8
rms_0_1_statistics_meanSquare
4
rms_0_1_statistics_meanSquarePlusEpsilon
7
rms_0_1_statistics_denominator
2.6457513110645907
rms_0_1_feature_0_normalized
0.7559289460184544
rms_0_1_feature_0_scaled
0.7559289460184544
rms_0_1_feature_0_value
0.7559289460184544
rms_0_1_feature_1_normalized
0.7559289460184544
rms_0_1_feature_1_scaled
0.7559289460184544
rms_0_1_feature_1_value
0.7559289460184544
rms_0_2_statistics_square0
1
rms_0_2_statistics_square1
1
rms_0_2_statistics_squareSum
2
rms_0_2_statistics_meanSquare
1
rms_0_2_statistics_meanSquarePlusEpsilon
4
rms_0_2_statistics_denominator
2
rms_0_2_feature_0_normalized
-0.5
rms_0_2_feature_0_scaled
-0.5
rms_0_2_feature_0_value
-0.5
rms_0_2_feature_1_normalized
0.5
rms_0_2_feature_1_scaled
0.5
rms_0_2_feature_1_value
0.5

Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.

X

B=1 × T=3 × D=2 · float64 · display precision 8 · Feature-last active rows, two features per token.

Storage indexValue
03
11
22
32
4-1
51

gamma

D=2 · float64 · display precision 8 · Per-feature scale shared across batches and tokens, used by both variants.

Storage indexValue
01
11

beta

D=2 · float64 · display precision 8 · Per-feature offset used only by LN; validated but never applied to scale-only RMS.

Storage indexValue
00
10

mean

B=1 × T=3 × Statistic=1 · float64 · display precision 8 · LN sum of two features divided by D=2, separately per token.

Storage indexValue
02
12
20

variance

B=1 × T=3 × Statistic=1 · float64 · display precision 8 · Population variance: sum of centered feature squares divided by 2, not 1.

Storage indexValue
01
10
21

lnDenominator

B=1 × T=3 × Statistic=1 · float64 · display precision 8 · sqrt(variance+epsilon); epsilon is strictly positive and inside sqrt.

Storage indexValue
02
11.7320508075688772
22

centered

B=1 × T=3 × D=2 · float64 · display precision 8 · X minus that token’s feature mean.

Storage indexValue
01
1-1
20
30
4-1
51

LNNormalized

B=1 × T=3 × D=2 · float64 · display precision 8 · centered/sqrt(variance+epsilon), before gamma and beta.

Storage indexValue
00.5
1-0.5
20
30
4-0.5
50.5

LN

B=1 × T=3 × D=2 · float64 · display precision 8 · gamma*LNNormalized+beta; no promise of output zero mean or unit variance.

Storage indexValue
00.5
1-0.5
20
30
4-0.5
50.5

meanSquare

B=1 × T=3 × Statistic=1 · float64 · display precision 8 · RMS sum of original feature squares divided by 2, with no mean subtraction.

Storage indexValue
05
14
21

rmsDenominator

B=1 × T=3 × Statistic=1 · float64 · display precision 8 · sqrt(meanSquare+epsilon).

Storage indexValue
02.8284271247461903
12.6457513110645907
22

RMSNormalized

B=1 × T=3 × D=2 · float64 · display precision 8 · Original X divided by the token’s rmsDenominator.

Storage indexValue
01.0606601717798212
10.35355339059327373
20.7559289460184544
30.7559289460184544
4-0.5
50.5

RMS

B=1 × T=3 × D=2 · float64 · display precision 8 · gamma*RMSNormalized; standard scale-only RMS has no beta addition.

Storage indexValue
01.0606601717798212
10.35355339059327373
20.7559289460184544
30.7559289460184544
4-0.5
50.5

Open Input token rows X, Feature scales gamma or LayerNorm offsets beta before editing their entries. B, T and epsilon remain visible. Both variants always recompute from the same starting inputs; native view selectors inspect saved rows without changing them. All 19 fields are validated, including inactive X and beta even though scale-only RMS never applies beta.

Reset uses rows (3,1),(2,2),(-1,1), gamma=(1,1), beta=(0,0), epsilon=3. LN means are 2,2,0; population variances are 1,0,1; denominators are 2,sqrt(3),2; outputs are (0.5,-0.5),(0,0),(-0.5,0.5). Mean and variance use only the two features of each row, with no token or batch mixing.

RMS mean squares are 5,4,1, with denominators sqrt(8),sqrt(7),2. Outputs are (3/sqrt(8),1/sqrt(8)),(2/sqrt(7),2/sqrt(7)),(-0.5,0.5). These symbolic forms describe the exact real formulas; the tables display actual stored binary64 values. RMS has neither mean subtraction nor beta addition. Epsilon=3 is deliberately hand-friendly, not a recommended production hyperparameter; smaller positive values down to 1e-8 are editable.

Check your understanding

Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.

1. For X[B,T,2], which values contribute to the statistics for batch b, token t?
2. For the specific row (3,1), what is the population variance used by this LayerNorm before epsilon is added?
3. Using the current starting inputs, saved ln_0_0_feature_0 has source=1, denominator=2, gamma=1, beta=0. What is LN[0,0,0]?
4. Hold X,gamma,epsilon,B,T fixed and edit only beta0. What changes?
5. Counterexample: for row (2,2), gamma=(1,1), beta=(0,0), epsilon=3, which outputs are correct?

Reset uses B=1,T=3,D=2 and input rows (3,1),(2,2),(−1,1). Open the initially closed native groups Input token rows X, Feature scales gamma and LayerNorm offsets beta before editing their entries. Dimensions and epsilon remain visible. Select batch zero and token zero; compare its statistics, normalized features and final outputs. Change only beta0 from zero to one: LayerNorm feature zero increases by one while RMSNorm stays fixed. Reset before following the worked example.

The default epsilon is 3, chosen to make the hand-worked LayerNorm square roots simple. It is a teaching choice, not a recommended production hyperparameter. You can edit it to a smaller positive value. Both variants are always computed; selecting a row changes the view, not which normalization runs. Each exercise identifies its own coordinates independently of those selectors.

Vocabulary, axes and parameters

B counts sequences, T positions within each sequence, and D=2 features at each position. A feature is one coordinate of a token’s representation. For one selected row write x=(x0,x1), suppressing its batch and token indices. A mean is an arithmetic average; variance is an average of squared deviations from that mean. RMS, root mean square, is the square root of the average of squared original values.

Gamma, written γ, provides one multiplicative scale per feature. Beta, β, provides one additive offset per feature in LayerNorm. These parameters are shared across tokens and sequences; here they are hand-set editable values. Affine means scale followed by offset. We use standard scale-only RMSNorm: gamma is applied, but beta is never added. The helper validates beta as part of its complete input boundary even though RMSNorm does not use it.

Tensor recordsShapeNamed axes
X[B,T,2]B,T,D
gamma, beta[2]D
mean, variance, lnDenominator[B,T,1]B,T,Statistic
centered, LNNormalized, LN[B,T,2]B,T,D
meanSquare, rmsDenominator[B,T,1]B,T,Statistic
RMSNormalized, RMS[B,T,2]B,T,D

Each statistic has one entry per token, retained with a length-one Statistic axis. Epsilon, ε, is one positive scalar setting, not a fake scalar tensor. Every reduction averages only the two features of one token. There is no average across time or batch, so changing one input row cannot alter another row’s statistics or outputs. This feature-only operation is not batch normalization.

LayerNorm: center, divide, then apply the affine map

For a selected row, first form the sum and divide by D=2:

μ=(x0+x1)/2,c0=x0−μ,c1=x1−μ.\mu=(x_0+x_1)/2,\qquad c_0=x_0-\mu,\quad c_1=x_1-\mu.

Here μ is the row mean and c the centered row. Next square each deviation, sum the squares and divide by two:

v=(c02+c12)/2,q=v+ϵ,s=q.v=(c_0^2+c_1^2)/2,\qquad q=v+\epsilon,\qquad s=\sqrt q.

Because c0=(x0−x1)/2 and c1=−c0, the same two-feature variance can also be written (x0−x1)²/4. This identity provides another way to check the hand arithmetic.

v is the population, or biased, variance. We describe the complete feature row; we do not estimate an unknown population from a sample, so there is no D−1 divisor. The denominator s includes epsilon inside the square root. Finally for feature d,

nd=cd/s,scaledd=γdnd,LNd=scaledd+βd.n_d=c_d/s,\qquad scaled_d=\gamma_d n_d,\qquad LN_d=scaled_d+\beta_d.

Centering removes a common offset. Dividing by s adjusts the magnitude of the remaining deviations. Gamma and beta then allow the next component to receive a chosen feature scale and offset. “Normalized” names an intermediate computation, not a promise that final outputs have zero mean and variance one.

Here is every default statistic, in code order:

t, xSum → mean μCentered cSquares → squareSumDivide by 2 → vAdd ε → qDenominator s
0, (3,1)3+1=4 → 4/2=2(3−2,1−2)=(1,−1)(1·1, (−1)·(−1))=(1,1) → 1+1=22/2=11+3=4√4=2
1, (2,2)2+2=4 → 4/2=2(2−2,2−2)=(0,0)(0·0,0·0)=(0,0) → 0+0=00/2=00+3=3√3
2, (−1,1)−1+1=0 → 0/2=0(−1−0,1−0)=(−1,1)((−1)·(−1),1·1)=(1,1) → 1+1=22/2=11+3=4√4=2

At reset gamma=(1,1), beta=(0,0). All six divisions, multiplications and offset additions are:

t,dDivide → normalized nMultiply by gamma → scaledAdd beta → LN
0,01/21·(1/2)=1/21/2+0=1/2
0,1−1/21·(−1/2)=−1/2−1/2+0=−1/2
1,00/√3=01·0=00+0=0
1,10/√3=01·0=00+0=0
2,0−1/21·(−1/2)=−1/2−1/2+0=−1/2
2,11/21·(1/2)=1/21/2+0=1/2

The complete LN rows are (1/2,−1/2),(0,0),(−1/2,1/2). For a constant row, centered features are zero, but epsilon keeps the denominator positive. Its LayerNorm output is exactly beta in real arithmetic, including when the constant is nonzero.

RMSNorm: square the original row and keep its offset

RMSNorm skips mean subtraction. Let m be the mean square, qR the stabilized mean square, and r the denominator:

m=(x02+x12)/2,qR=m+ϵ,r=qR,ud=xd/r,RMSd=γdud.m=(x_0^2+x_1^2)/2,\qquad q_R=m+\epsilon,\qquad r=\sqrt{q_R},\qquad u_d=x_d/r,\qquad RMS_d=\gamma_d u_d.

Without epsilon, √m is the row’s RMS. With epsilon the actual divisor is √(m+ε), which is larger. u names the RMS-normalized intermediate, distinct from the centered LayerNorm n. There is no beta addition in this variant.

t, xSquares → squareSumMean square mAdd ε → qRDenominator rDivide original x → uMultiply gamma → RMS
0, (3,1)(3·3,1·1)=(9,1) → 9+1=1010/2=55+3=8√8(3/√8,1/√8)(1·3/√8,1·1/√8)
1, (2,2)(2·2,2·2)=(4,4) → 4+4=88/2=44+3=7√7(2/√7,2/√7)(1·2/√7,1·2/√7)
2, (−1,1)((−1)·(−1),1·1)=(1,1) → 1+1=22/2=11+3=42(−1/2,1/2)(1·(−1/2),1·1/2)

These radical expressions describe exact real arithmetic. The implementation stores binary64 (64-bit floating-point) approximations to square roots and divisions; lab tables expose those stored values without additional display rounding. The constant nonzero row (2,2) becomes a positive RMS row, whereas its LN row vanishes at beta=0. The zero row (0,0) has m=0, denominator √ε and RMS=(0,0); its LN output is beta. Positive epsilon makes both divisions defined without inventing a zero-over-zero convention.

Why “unit variance” and “invariant” need qualifications

Before gamma/beta, LayerNorm’s centered normalized row has variance

(n02+n12)/2=v/(v+ϵ).(n_0^2+n_1^2)/2=v/(v+\epsilon).

At reset token zero this is (1/4+1/4)/2=1/4, not one. RMS’s normalized mean square is similarly m/(m+ε), here 5/8. Gamma can rescale features differently and beta can shift them, so final outputs need not retain the intermediate statistics.

Try gamma=(2,−1), beta=(1,−1) for token zero. LN’s scaled row becomes (2·1/2,(−1)·(−1/2))=(1,1/2); adding beta gives (2,−1/2). RMS becomes (6/√8,−1/√8); beta is unused. These are explicit affine and scale-only operations, not a hidden second normalization.

In exact real arithmetic, adding the same constant k to both features shifts μ by k and leaves c, v and LN unchanged. Within the input bounds, (3,1) and (4,2) both center to (1,−1). RMS instead changes its mean square from 5 to (16+4)/2=10 and gives (4/√13,2/√13), different from (3/√8,1/√8). It is not generally invariant to additive shifts.

Positive rescaling also needs care. Scale reset row (−1,1) to (−2,2) while keeping ε=3. Variance and mean square both rise from one to four. Both normalized rows change from (−1/2,1/2) to (−2/√7,2/√7). For positive scale factor a, the new denominator is √(a²v+ε), not a√(v+ε). Epsilon therefore breaks exact positive rescale invariance; it may be approximately small relative to the statistic. Rounding and input bounds further limit numerical experiments with these identities.

Read the actual implementation and its boundary

The chapter wrapper, iv31.py:

Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""IV-31 — Layer Normalization and RMS Normalization.

Prerequisites: IV-30 and VIII.3. Normalize only the two features of EACH token,
independently across batch/time. LayerNorm subtracts mean, uses population
variance, divides by sqrt(variance+epsilon), multiplies gamma, then adds beta.
Scale-only RMSNorm uses sqrt(meanSquare+epsilon), original features and gamma;
it deliberately has neither mean subtraction nor beta addition.

Hand default epsilon=3: means=(2,2,0), variances=(1,0,1), LN denominators
(2,sqrt(3),2), LN rows=(.5,-.5),(0,0),(-.5,.5). RMS mean squares=(5,4,1),
denominators=(sqrt(8),sqrt(7),2), rows=(3/sqrt(8),1/sqrt(8)),
(2/sqrt(7),2/sqrt(7)),(-.5,.5). These are hand identities, not executed values.
Epsilon=3 is a teaching choice, not a production recommendation. Keep
component_reference.py beside this program. Runtime validation is deferred.
"""
from types import MappingProxyType
import numpy as np
from component_reference import NORM_DEFAULTS, component_state, component_trace, feature_norm, guarded, run, tensor

DEFAULT_IV31 = MappingProxyType(dict(NORM_DEFAULTS))


@guarded
def derive_iv31(state):
    """Save all LayerNorm rows, then all RMSNorm rows, with every scalar statistic."""
    s = component_state(state, 31)
    B, T, epsilon = s["B"], s["T"], s["epsilon"]
    shape, axes = [B, T, 2], ["B", "T", "D"]
    statistic_shape, statistic_axes = [B, T, 1], ["B", "T", "Statistic"]
    trace = component_trace()
    trace.add("setup", "Validate every scalar before selecting active rows",
              "D=2; normalize each X[b,t,:] independently; epsilon>0",
              "All inactive X slots are validated. Both variants always compute; beta affects LayerNorm only.",
              s, dict(B=B, T=T, D=2, epsilon=epsilon))
    X = np.empty(shape, dtype=np.float64)
    for b in range(B):
        for t in range(T):
            for d in range(2):
                X[b, t, d] = s[f"x{b}{t}{d}"]
    gamma = np.array([s["gamma0"], s["gamma1"]], dtype=np.float64)
    beta = np.array([s["beta0"], s["beta1"]], dtype=np.float64)
    mean, variance = np.empty(statistic_shape, dtype=np.float64), np.empty(statistic_shape, dtype=np.float64)
    ln_denominator = np.empty(statistic_shape, dtype=np.float64)
    centered, ln_normalized, LN = (np.empty(shape, dtype=np.float64) for _ in range(3))
    mean_square, rms_denominator = np.empty(statistic_shape, dtype=np.float64), np.empty(statistic_shape, dtype=np.float64)
    rms_normalized, RMS = np.empty(shape, dtype=np.float64), np.empty(shape, dtype=np.float64)
    # All LayerNorm trace records precede all RMSNorm records, rather than interleaving variants.
    for b in range(B):
        for t in range(T):
            row = feature_norm("layer", f"ln_{b}_{t}", X[b, t].tolist(), gamma.tolist(), beta.tolist(), epsilon, trace)
            statistics = row["statistics"]
            mean[b, t, 0], variance[b, t, 0] = statistics["mean"], statistics["variance"]
            ln_denominator[b, t, 0] = statistics["denominator"]
            for d in range(2):
                centered[b, t, d] = statistics[f"centered{d}"]
                ln_normalized[b, t, d] = row["normalized"][d]
                LN[b, t, d] = row["values"][d]
    for b in range(B):
        for t in range(T):
            row = feature_norm("rms", f"rms_{b}_{t}", X[b, t].tolist(), gamma.tolist(), beta.tolist(), epsilon, trace)
            statistics = row["statistics"]
            mean_square[b, t, 0], rms_denominator[b, t, 0] = statistics["meanSquare"], statistics["denominator"]
            for d in range(2):
                rms_normalized[b, t, d] = row["normalized"][d]
                RMS[b, t, d] = row["values"][d]
    summary = dict(B=B, T=T, epsilon=epsilon)
    for prefix, values in (("ln", LN), ("rms", RMS)):
        for b in range(B):
            for t in range(T):
                for d in range(2):
                    summary[f"{prefix}{b}{t}{d}"] = float(values[b, t, d])
    for b in range(B):
        for t in range(T):
            summary[f"mu{b}{t}"] = float(mean[b, t, 0])
            summary[f"var{b}{t}"] = float(variance[b, t, 0])
            summary[f"ms{b}{t}"] = float(mean_square[b, t, 0])
    # Keep scalar statistics [B,T,1], with their explicit Statistic axis; no rank-zero placeholder.
    tensors = [
        tensor("X", shape, axes, X.reshape(-1).tolist(), "Active token vectors, with two features per token."),
        tensor("gamma", [2], ["D"], gamma.tolist(), "Per-feature scale shared by both normalization variants."),
        tensor("beta", [2], ["D"], beta.tolist(), "Per-feature LayerNorm offset; validated but unused by scale-only RMSNorm."),
        tensor("mean", statistic_shape, statistic_axes, mean.reshape(-1).tolist(), "Feature sum divided by 2, separately per token."),
        tensor("variance", statistic_shape, statistic_axes, variance.reshape(-1).tolist(), "Population variance: centered squares summed then divided by 2."),
        tensor("lnDenominator", statistic_shape, statistic_axes, ln_denominator.reshape(-1).tolist(), "sqrt(variance+epsilon), with epsilon inside the root."),
        tensor("centered", shape, axes, centered.reshape(-1).tolist(), "Original feature minus its token's own feature mean."),
        tensor("LNNormalized", shape, axes, ln_normalized.reshape(-1).tolist(), "Centered feature divided by saved LayerNorm denominator."),
        tensor("LN", shape, axes, LN.reshape(-1).tolist(), "LayerNorm normalized feature times gamma, then plus beta."),
        tensor("meanSquare", statistic_shape, statistic_axes, mean_square.reshape(-1).tolist(), "Original feature squares summed then divided by 2, without centering."),
        tensor("rmsDenominator", statistic_shape, statistic_axes, rms_denominator.reshape(-1).tolist(), "sqrt(meanSquare+epsilon), with epsilon inside the root."),
        tensor("RMSNormalized", shape, axes, rms_normalized.reshape(-1).tolist(), "Original feature divided by saved RMS denominator."),
        tensor("RMS", shape, axes, RMS.reshape(-1).tolist(), "Scale-only RMSNorm: normalized feature times gamma; beta is not added."),
    ]
    return trace.result(summary, tensors)


if __name__ == "__main__":
    run(derive_iv31, DEFAULT_IV31)

The shared helper, component_reference.py:

Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""Part VII component kernels: real NumPy storage, explicit float operations.

Keep this file beside iv30.py and iv31.py. NumPy represents actual shaped arrays;
Python floats perform each product/addition/division separately in signed trace
order. No matmul, vector reduction, broadcast, fused multiply-add or hidden norm.
Authored under the resource hold: this source has NOT been executed or validated.
"""
import argparse
from functools import wraps
import json
import math
import sys
from types import MappingProxyType
import numpy as np


class NumericalFault(ValueError):
    def __init__(self, code, reason):
        super().__init__(reason)
        self.code = code


def finite(value, label):
    """Reject booleans, numeric strings, complex numbers and nonfinite scalars."""
    if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = float(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


RESIDUAL_DEFAULTS = MappingProxyType(dict(
    B=1, T=3,
    x000=1, x001=0, x010=0, x011=1, x020=1, x021=1,
    x100=1, x101=1, x110=-1, x111=0, x120=0, x121=2,
    w00=0.5, w01=0, w10=0, w11=-0.5, b0=0, b1=0,
    g000=1, g001=2, g010=1, g011=2, g020=1, g021=2,
    g100=1, g101=2, g110=1, g111=2, g120=1, g121=2,
    residual=1,
))
NORM_DEFAULTS = MappingProxyType(dict(
    B=1, T=3,
    x000=3, x001=1, x010=2, x011=2, x020=-1, x021=1,
    x100=1, x101=-1, x110=0, x111=0, x120=-2, x121=3,
    gamma0=1, gamma1=1, beta0=0, beta1=0, epsilon=3,
))


def component_state(state, stage):
    """Validate all 33/19 own fields, including inactive X/g, before selecting."""
    if type(stage) is not int or stage not in (30, 31):
        raise NumericalFault("INVALID_INPUT", "Use component stage 30 or 31.")
    defaults = RESIDUAL_DEFAULTS if stage == 30 else NORM_DEFAULTS
    if type(state) not in (dict, MappingProxyType):
        raise NumericalFault("INVALID_INPUT", "Use a plain object containing exactly the named scalar fields.")
    if set(state) != set(defaults):
        raise NumericalFault("INVALID_INPUT", "Provide every own scalar field and no extra fields, including inactive slots.")
    integer_bounds = dict(B=(1, 2), T=(1, 3), residual=(0, 1))
    result = {}
    for key in defaults:
        value = finite(state[key], key)
        low, high = integer_bounds.get(key, (1e-8, 4) if key == "epsilon" else (-4, 4))
        if value < low or value > high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
        if key in integer_bounds and not value.is_integer():
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
        result[key] = int(value) if key in integer_bounds else value
    return result


def guarded(derive):
    @wraps(derive)
    def call(state):
        try:
            return derive(state)
        except NumericalFault as error:
            return dict(status="unavailable", code=error.code, reason=str(error))
        except (OverflowError, FloatingPointError) as error:
            return dict(status="unavailable", code="NONFINITE", reason=str(error))
    return call


def numbers(values):
    return {key: finite(value, key) for key, value in values.items()}


class ComponentTrace:
    def __init__(self):
        self.outputs = {}
        self.steps = []

    def add(self, identifier, label, equation, explanation, inputs, values):
        # Finite clones detach each saved operand/result from mutable arrays/state.
        inputs, values = numbers(inputs), numbers(values)
        if len(self.steps) >= 512:
            raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 trace steps are supported.")
        self.steps.append(dict(id=identifier, label=label, equation=equation,
                               explanation=explanation, inputs=inputs, outputs=values))
        self.outputs.update({f"{identifier}_{key}": value for key, value in values.items()})

    def result(self, summary, tensors):
        # Aliases first, then ALL flattened step outputs in their insertion order.
        return dict(status="defined", outputs=numbers({**summary, **self.outputs}),
                    steps=self.steps, tensors=tensors)


def component_trace():
    return ComponentTrace()


def tensor(identifier, shape, axes, values, provenance):
    """Platform-style float64 boundary: explicit named shape and dense flat list."""
    if type(shape) is not list or type(axes) is not list or not 1 <= len(shape) <= 4 or len(shape) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name each of 1–4 axes uniquely.")
    if any(type(axis) is not str or not axis for axis in axes) or len(set(axes)) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: each axis needs a unique name.")
    if any(type(d) is not int or not 1 <= d <= 64 for d in shape) or math.prod(shape) > 4096:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: dimensions 1–64 and at most 4096 elements required.")
    if type(values) is not list or len(values) != math.prod(shape):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage does not match dimensions.")
    flat = [finite(value, f"{identifier}[{n}]") for n, value in enumerate(values)]
    return dict(id=identifier, shape=list(shape), axes=list(axes), dtype="float64",
                values=flat, provenance=provenance, precision=8)


def same_shape_add(identifier, left, right):
    """Add validated float64 TensorRecords; equal element count is insufficient."""
    checked = []
    for n, record in enumerate((left, right)):
        if type(record) not in (dict, MappingProxyType) or record.get("dtype") != "float64":
            raise NumericalFault("INVALID_INPUT", f"{identifier}: operand {n} must be a float64 tensor.")
        checked.append(tensor(record.get("id"), record.get("shape"), record.get("axes"),
                              record.get("values"), record.get("provenance")))
    a, b = checked
    if a["shape"] != b["shape"] or a["axes"] != b["axes"]:
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: addition needs identical dimensions and named axes; no broadcasting.")
    values = [finite(value + b["values"][n], f"{identifier}[{n}]") for n, value in enumerate(a["values"])]
    return tensor(identifier, a["shape"], a["axes"], values,
                  f"Exact named-shape addition of {left['id']} and {right['id']}; no broadcasting.")


def feature_norm(kind, prefix, x, gamma, beta, epsilon, trace):
    """Normalize one width-two token; no chapter bounds on derived IV33 rows.

    Inputs are dense lists, as in the TS kernel. Validate beta even for RMS,
    then deliberately omit it from RMS arithmetic and feature trace inputs.
    """
    if kind not in ("layer", "rms"):
        raise NumericalFault("INVALID_INPUT", "Use layer or rms normalization.")
    checked = []
    for name, values in (("x", x), ("gamma", gamma), ("beta", beta)):
        if type(values) is not list or len(values) != 2:
            raise NumericalFault("SHAPE_MISMATCH", f"{name} needs exactly two dense features.")
        checked.append([finite(value, f"{name}[{d}]") for d, value in enumerate(values)])
    x, gamma, beta = checked
    epsilon = finite(epsilon, "epsilon")
    if epsilon <= 0:
        raise NumericalFault("INVALID_INPUT", "epsilon must be strictly positive.")
    statistics = {}
    if kind == "layer":
        # Population variance: two centered squares, then sum, then divide by 2.
        statistics["sum"] = finite(x[0] + x[1], "feature sum")
        statistics["mean"] = finite(statistics["sum"] / 2, "feature mean")
        statistics["centered0"] = finite(x[0] - statistics["mean"], "centered0")
        statistics["centered1"] = finite(x[1] - statistics["mean"], "centered1")
        statistics["square0"] = finite(statistics["centered0"] * statistics["centered0"], "centered square0")
        statistics["square1"] = finite(statistics["centered1"] * statistics["centered1"], "centered square1")
        statistics["squareSum"] = finite(statistics["square0"] + statistics["square1"], "centered square sum")
        statistics["variance"] = finite(statistics["squareSum"] / 2, "population variance")
        statistics["variancePlusEpsilon"] = finite(statistics["variance"] + epsilon, "variance plus epsilon")
        statistics["denominator"] = finite(math.sqrt(statistics["variancePlusEpsilon"]), "LN denominator")
        source = [statistics["centered0"], statistics["centered1"]]
    else:
        # RMS uses original features, with neither mean subtraction nor beta.
        statistics["square0"] = finite(x[0] * x[0], "square0")
        statistics["square1"] = finite(x[1] * x[1], "square1")
        statistics["squareSum"] = finite(statistics["square0"] + statistics["square1"], "square sum")
        statistics["meanSquare"] = finite(statistics["squareSum"] / 2, "mean square")
        statistics["meanSquarePlusEpsilon"] = finite(statistics["meanSquare"] + epsilon, "mean square plus epsilon")
        statistics["denominator"] = finite(math.sqrt(statistics["meanSquarePlusEpsilon"]), "RMS denominator")
        source = list(x)
    trace.add(f"{prefix}_statistics", f"{prefix}: feature-only statistics",
              "mean=(x0+x1)/2; variance=(centered0²+centered1²)/2; denominator=sqrt(variance+epsilon)" if kind == "layer" else
              "meanSquare=(x0²+x1²)/2; denominator=sqrt(meanSquare+epsilon)",
              "Only this token's two features contribute. Epsilon stays inside the square root.",
              dict(x0=x[0], x1=x[1], epsilon=epsilon), statistics)
    normalized, values = [], []
    for d in range(2):
        n = finite(source[d] / statistics["denominator"], "normalized feature")
        scaled = finite(gamma[d] * n, "scaled feature")
        value = finite(scaled + beta[d], "LN affine feature") if kind == "layer" else scaled
        normalized.append(n)
        values.append(value)
        inputs = dict(d=d, source=source[d], denominator=statistics["denominator"], gamma=gamma[d])
        if kind == "layer":
            inputs["beta"] = beta[d]
        trace.add(f"{prefix}_feature_{d}", f"{prefix}: affine feature {d}",
                  "normalized=source/denominator; scaled=gamma*normalized; value=scaled+beta" if kind == "layer" else
                  "normalized=source/denominator; scaled=gamma*normalized; value=scaled",
                  "LayerNorm uses centered features and beta; scale-only RMS uses original features and no beta.",
                  inputs, dict(normalized=n, scaled=scaled, value=value))
    return dict(values=values, normalized=normalized, statistics=statistics)


_JSON_INT = int


def run(derive, defaults):
    """No argument uses defaults; one JSON argument replaces all; '-' reads stdin."""
    class ParseFault(ValueError):
        """Only locally owned JSON profile/conversion faults."""

    def _members(pairs):
        value = {}
        for key, member in pairs:
            if key in value:
                raise ParseFault("Duplicate JSON object members are not allowed.")
            value[key] = member
        return value

    def _constant(token):
        raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")

    def _integer(token):
        if token == "-0":
            return -0.0
        try:
            return _JSON_INT(token)
        except ValueError as fault:
            if type(fault) is not ValueError:
                raise
            raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from fault

    parser = argparse.ArgumentParser(description=derive.__doc__)
    parser.add_argument("state", nargs="?")
    args = parser.parse_args()
    if args.state is not None:
        source = sys.stdin.read() if args.state == "-" else args.state
        try:
            state = json.loads(source, object_pairs_hook=_members,
                               parse_constant=_constant, parse_int=_integer)
        except (json.JSONDecodeError, ParseFault) as error:
            result = dict(status="unavailable", code="INVALID_INPUT", reason=str(error))
        else:
            result = derive(state)
    else:
        result = derive(dict(defaults))
    print(json.dumps(result, allow_nan=False, separators=(",", ":")))

derive_iv31 validates all state fields before selecting active rows. np.empty allocates actual float64 X and result arrays; loops fill X, while np.array constructs the two-entry gamma and beta arrays. The wrapper calls feature_norm for all LN rows in b/t order, then all RMS rows. That helper explicitly forms each scalar sum, square, division and square root, saving the statistics before feature divisions and affine operations. Its returned statistics, normalized and values are copied to their named arrays; reshaping to flat storage at serialization preserves the row-major coordinate order. For example, ln_0_0_statistics stores mean, both centered values, both squares, their sum, variance, variance-plus-epsilon and denominator. ln_0_0_feature_0 then stores normalized, scaled and final value. rms_0_0_statistics starts from original squares; its feature records have no beta input. The comments map source variables to these saved operands; tables consume the computed records rather than recomputing a different formula in the view.

The lab accepts B=1–2,T=1–3, fixed D=2, finite X/gamma/beta entries in [−4,4], and ε in [10⁻⁸,4]. Epsilon must be positive. Hidden inactive rows remain validated, and invalid input is unavailable rather than silently repaired. The reusable width-two kernel requires finite dense rows but can accept derived values outside this chapter’s raw-input bounds for later block composition. Small epsilon can make sensitivity to nearly constant rows substantial; normalization is not a universal conditioning or gradient guarantee. This source lesson makes no runtime parity claim.

Five exercises matched to the lab

Each question has immediate corrective feedback. Use the named row and saved fields for a live question, regardless of the inspector selection.

  1. feature-axis: Which coordinates supply statistics? Reduce only D within each [b,t,:] row. Averaging across T would mix different token positions and change the specified mechanism; B also remains separate.
  2. population-variance: Find the variance of (3,1). Mean is (3+1)/2=2, centered features are (1,−1), squares are (1,1), and population variance is (1+1)/2=1. Dividing by D−1 would give sample variance two and violate this lesson’s rule.
  3. live-ln: Calculate the saved LN[0,0,0]. Read ln_0_0_feature_0: divide its saved source by its denominator, multiply by gamma, then add beta. At reset this is 1·(1/2)+0=1/2. After edits use those current saved fields, independently of inspector selectors.
  4. beta-edit: Predict an edit to beta0 only. Only final LN feature zero changes in each active row. Feature one, all statistics and normalized values stay fixed; every RMS record stays fixed because standard scale-only RMSNorm has no beta addition. The helper still validates beta for both variants.
  5. constant-row: Compare a constant nonzero row. With x=(2,2), gamma=(1,1), beta=(0,0), ε=3, LN=(0,0) and RMS=(2/√7,2/√7). Centering removes the common value in LN; RMS retains it. A positive denominator alone cannot make the variants equal.

Recap and bridge

Normalize over each token’s features, keeping batch and token rows separate. LayerNorm uses population variance after centering and then gamma plus beta. Standard RMSNorm uses original mean squares and gamma only. Epsilon sits inside the square root, prevents zero division and changes exact scale identities. IV-32 — Position-Wise Feed-Forward Networks next develops the position-wise feed-forward component before these pieces are assembled into a complete block.