The interview problem

Practice prompt

A model behaves differently when the same request is evaluated alone versus alongside other requests. Explain batch normalization and layer normalization, calculate both on a small matrix, and diagnose whether this behavior is expected. How do small batches, padding and saved inference statistics affect your answer?

Original fundamentals practice, not a reported company interview. Numerical examples are hypothetical. Official PyTorch documentation retrieved September 27, 2026.

1. Name the reduction axes first

Both operations can take the form y = γ(x − μ)/√(v + ε) + β. Their difference is which values determine μ and v. For a matrix shaped [batch, features], training-mode batch normalization computes one mean and variance per feature across examples. Layer normalization over the last dimension computes one mean and variance across features within each example.

For a sequence shaped [batch, time, hidden], layer normalization configured for hidden size reduces only the last axis. Each token has its own statistics. It does not automatically normalize across all tokens in the sequence. Configuring multiple trailing dimensions changes the operation. The shape and reduction axes are part of the model specification, not implementation trivia.

Learned scale γ and offset β then transform normalized values. Therefore the final output need not retain zero mean or unit variance. When statistics are computed from the same reduction group, positive ε makes its pre-affine divisor-n variance v/(v+ε), less than one for finite nonzero v. This does not apply to arbitrary inference inputs normalized with frozen statistics. Saying “normalization makes all activations standard normal” is wrong: it neither makes a distribution Gaussian nor guarantees those final moments.

2. Normalize the same matrix both ways

Take X = [[1,3],[5,7]], with examples in rows and features in columns. Use γ=1 and β=0. For this hand calculation only, set ε=0; all reduced groups have positive variance. Define variance using the average squared deviation, dividing by the number of values.

OperationMeansVariancesOutput
Batch normalization across rows[3,5][4,4][[-1,-1],[1,1]]
Layer normalization across columns[2,6][1,1][[-1,1],[-1,1]]

For the first batch-normalized feature, mean is (1+5)/2=3 and variance is ((1−3)²+(5−3)²)/2=4. The value 1 becomes (1−3)/2=−1. For the first layer-normalized row, mean is 2 and variance is 1, so [1,3] becomes [−1,1]. The same input yields different outputs because the comparison groups differ.

Now use ε=0.01. Batch-normalized magnitudes become 2/√4.01≈0.998752, while layer-normalized magnitudes become 1/√1.01≈0.995037. ε belongs inside the square root in this formula. Adding it afterward defines a different computation, especially when variance is small.

3. Change the batch without changing the request

Keep the first request [1,3], but change its batch companion from [5,7] to [1,7]. The first feature now has mean 1 and variance zero; with positive ε its centered output is 0. The second feature still has mean 5 and variance 4, yielding approximately −1 for the first request with small ε. Thus training-mode batch normalization changes that request's output from approximately [−1,−1] to [0,−1].

Layer normalization of [1,3] is unchanged because its reduction group does not include the other row. This statement assumes the input to this layer is unchanged and no other batch-coupled computation modifies it. It is not a claim that any entire network containing a LayerNorm layer is batch-independent.

This suggests a diagnostic: hold a request fixed, vary unrelated batch members, and compare intermediate activations at the first layer where outputs diverge. Disable unrelated randomness during the comparison. Batch dependence may be intentional in training, but surprising in a serving path that was supposed to use frozen batch-normalization statistics.

4. Separate forward statistics from saved statistics

PyTorch's documented BatchNorm1d training forward uses variance with divisor n, while its running-variance update uses the corrected n−1 estimate. With tracking enabled, evaluation uses running statistics; disabling tracking also makes evaluation batch-dependent. Its momentum m updates a running statistic as new=(1−m)old+m×observed, unlike optimizer momentum.

For the original matrix, the forward feature variances are [4,4], but the corrected estimates are [8,8]. Suppose running means start at [0,0], running variances at [1,1], and m=0.1. After this one training batch, running means are [0.3,0.5] and running variances are [1.7,1.7]. These are not the batch's exact statistics.

Immediately evaluating [1,3] with these saved values and ε=0.01 gives [(1−0.3)/√1.71,(3−0.5)/√1.71]≈[0.535303,1.911798]. That differs from its training output. This contrived one-batch example illustrates initialization and estimator effects, not a recommendation to deploy after one update.

LayerNorm, by contrast, uses current input statistics in both training and evaluation. Its affine parameters are learned and saved, but it does not need a batch running-mean buffer for this operation. Record module configuration and buffers with the model artifact; saving only trainable tensors can omit state needed to reproduce inference.

5. Reason about small batches and accumulation

The number of values contributing to each statistic matters more than the batch-size label alone. A channel reduced across many spatial positions can have multiple values even with one example; correlated positions still provide less independent information than their raw count suggests. A reduction containing only one value has zero divisor-n variance and no defined divisor-(n−1) estimate. Do not assume a particular library accepts that training configuration.

Combining gradients from several microbatches does not combine their forward-pass statistics. For a scalar feature, microbatch values [0,2] have mean 1 and variance 1; [10,12] have mean 11 and variance 1. Each separately normalizes to [−1,1] when ε=0. A single combined batch [0,2,10,12] has mean 6 and variance 26, producing approximately [−1.176697,−0.784465,0.784465,1.176697]. Accumulating the separate gradients cannot retroactively replace those forward activations.

Synchronizing statistics across workers can enlarge the reduction group within a forward step, but separate accumulation steps still remain separate unless the algorithm explicitly couples them. Consider communication cost, correlated data and actual per-worker composition when selecting a remedy. Replacing normalization changes the model's computation and may require retraining rather than a configuration-only serving fix.

6. Check padding and deployment shifts

Suppose valid scalar values are [2,4]. Their mean is 3 and divisor-n variance is 1. If two padding zeros are included, the reduction becomes [2,4,0,0], with mean 1.5 and variance 2.75. The valid value 2 now normalizes to approximately 0.301511 instead of −1 when ε=0. A padding convention can therefore change genuine activations if the reduction includes padded positions.

Layer normalization over hidden features separately at each token avoids mixing other padded time positions into that token's statistics. It still processes the padded token itself, and the rest of the network must mask invalid tokens appropriately. Normalizing across both time and hidden dimensions reintroduces sensitivity to padding unless it is explicitly handled.

For an inference shift example with γ=1 and β=0, freeze a scalar running mean at 0 and variance at 1. A new population with mean 5 and variance 1 emerges with normalized mean about 5 for small ε. Frozen statistics do not automatically adapt. But updating them from arbitrary live requests changes the model during use and can create cross-request dependence. Diagnose upstream feature changes, evaluate representative adaptation data and version any recalibration instead of silently mutating production state.

7. Build a reproducible diagnosis

input shape + preprocessing
             ↓
reduction axes + train/eval configuration
             ↓
current statistics or saved buffers
             ↓
epsilon + affine parameters + dtype
             ↓
activation comparison → downstream prediction check

Start with a small deterministic tensor and a hand-computed expected output. Verify axes, variance convention, ε placement and affine broadcasting. Then compare the real training and serving artifacts using the same input. Inspect running buffers and module flags, not just the weights. Gradient recording settings and a layer's training/evaluation behavior are separate concerns.

Test the same request in several batch compositions, representative batch sizes and sequence lengths. Include constant inputs, heavily padded inputs and small-variance cases. Compare intermediate outputs in a sufficiently precise dtype before blaming approximate kernels. Small numerical differences and a completely wrong reduction axis demand different fixes.

Report the behavior expected by the architecture and the observed discrepancy. Batch normalization and layer normalization encode different invariances; neither is universally better. The decision should match the tensor structure, optimization behavior, deployment batch composition and validation results.

8. Follow-ups and self-review

Follow-ups: Does LayerNorm normalize across the batch? Not in the configuration described here. Does evaluation always freeze BatchNorm statistics? Check whether tracking is enabled. Does a learned affine transform preserve zero mean? Not generally. Does normalization remove all distribution shift? No. Can gradient accumulation reproduce large-batch normalization? Not by itself.

Score 0–2 each for explicit axes, matrix arithmetic, training/inference state, small-batch and padding reasoning, and a reproducible diagnosis. A strong answer explains the changed output numerically instead of relying on a rule such as “BatchNorm for images, LayerNorm for text.”

Sources and next steps

All tensors and numerical counterexamples are original. Continue with gradient accumulation for other conditions behind large-batch equivalence.

Continue your preparation

Choose a connected learning path or browse more ML fundamentals questions. Read our editorial method and attribution policy.