AI Wiki中文/EN

Batch normalization: statistics have a training mode

批量归一化

Calculate batch and running variances separately, compare training with evaluation, and verify a cross-example Jacobian.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Your neighbors can change your normalized value

A feature value of three is high in a batch containing one, two and three. It is low in a batch containing three, ten and twenty. Batch normalization makes that comparison inside the network: it centers and rescales activations using a batch’s statistics, then applies a learned scale and shift.

The 2015 paper by Ioffe and Szegedy, Algorithm 1 defines this operation. It acts separately on feature dimensions; it does not remove all correlations between features. During training, a sample’s result depends on its batch companions. During ordinary inference with stored statistics, the same sample can be processed alone.

This distinction matters when reproducing a model. The fixed PyTorch 2.8 BatchNorm 1d documentation uses one variance denominator for the training forward pass and another for updating its stored running variance. Calling both quantities “the variance” can hide a real numerical difference.

One feature, two statistics paths

For one feature across m training observations, let μ be the batch mean and v its variance with divisor m. The normalized value and affine output are:

μ=1m∑ixi,v=1m∑i(xi−μ)2,x^i=xi−μv+ϵ,yi=γx^i+β.\mu=\frac1m\sum_i x_i,\qquad v=\frac1m\sum_i(x_i-\mu)^2,\qquad \widehat x_i=\frac{x_i-\mu}{\sqrt{v+\epsilon}},\qquad y_i=\gamma\widehat x_i+\beta.

The positive ε prevents a zero denominator. The trainable γ and β allow scale and shift after normalization. They are parameters; running statistics are state updated by a separate rule, not ordinary gradient-learned parameters.

Even before applying γ and β, the empirical variance of normalized activations is v/(v+ε), not exactly one for positive ε. The empirical mean is zero up to floating-point error. Standardizing each coordinate also does not make the joint distribution Gaussian or independent.

Running variance uses a correction

For our tracked two-dimensional implementation, m is the number of rows. Following the fixed documented convention, let a be the new-statistic weight called momentum by this API:

μ‾+=(1−a)μ‾+aμ,v‾+=(1−a)v‾+amm−1v,yieval=γxi−μ‾+v‾++ϵ+β.\overline\mu^+=(1-a)\overline\mu+a\mu,\qquad \overline v^+=(1-a)\overline v+a\frac{m}{m-1}v,\qquad y_i^{\mathrm{eval}}=\gamma\frac{x_i-\overline\mu^+}{\sqrt{\overline v^++\epsilon}}+\beta.

The factor m/(m−1) converts the batch variance to the usual unbiased sample-variance estimator under independent identically distributed observations with finite variance. It does not make an arbitrary moving average an exact population variance, especially while the model and data distribution change. The forward pass still uses v, without that correction.

Here a=1 uses only the newest statistics; a=0 retains the old ones. This is a running-statistic convention, not the momentum equation of a gradient optimizer. The displayed evaluation expression uses the state after this batch; subsequent inference keeps that state fixed.

Gradients connect examples within a batch

Centering and dividing by a batch-dependent scale makes the derivative more than γ divided by the standard deviation. For one feature, holding γ fixed and writing s=√(v+ε):

∂yi∂xj=γs[δij−1m−(xi−μ)(xj−μ)m(v+ϵ)].\frac{\partial y_i}{\partial x_j} =\frac{\gamma}{s}\left[\delta_{ij}-\frac1m -\frac{(x_i-\mu)(x_j-\mu)}{m(v+\epsilon)}\right].

Differentiate the mean to get 1/m; differentiate v to get 2(xⱼ−μ)/m; applying the chain and product rules gives the expression. Off-diagonal entries need not vanish: changing another example can change this one’s normalized output. Every row sums to zero because adding the same constant to every input leaves training normalization unchanged. Positive ε means arbitrary rescaling does not give exact scale invariance.

Train and evaluate the same three rows

The complete program uses Python 3.12 and NumPy 1.26.4. Its input has shape N by C: rows are observations, columns are features. It implements tracked training and evaluation, returning fresh arrays without mutating the supplied state. Epsilon is deliberately 1/3 in the example, much larger than the documented library default 1e−5, to make the arithmetic readable.

The rows are (1,2), (2,4), (3,6), with means (2,4) and forward variances (2/3,8/3). Set γ=(2,√3) and β=(1,−1). The training output is exactly (−1,−3), (1,−1), (3,1) in real arithmetic. From initial running mean zero and variance one, a=1/2 gives new running mean (1,2) and variance (1,5/2).

import numpy as np


def array(value):
    a=np.array(value,dtype=np.float64,copy=True)
    if not np.isfinite(a).all() or np.any(np.abs(a)>1000):
        raise ValueError('finite entries with magnitude at most 1000 required')
    return a


def batchnorm(x,gamma,beta,running_mean,running_var,training=True,eps=1e-5,momentum=0.1):
    x=array(x)
    if x.ndim!=2 or not 1<=x.shape[0]<=32 or not 1<=x.shape[1]<=8:raise ValueError('bounded N by C array required')
    gamma,beta,old_mean,old_var=[array(v) for v in (gamma,beta,running_mean,running_var)]
    if any(v.shape!=(x.shape[1],) for v in (gamma,beta,old_mean,old_var)):raise ValueError('C-element state vectors required')
    if np.any(old_var<0):raise ValueError('nonnegative running variance required')
    if type(training) is not bool:raise ValueError('Boolean training flag required')
    if type(eps) not in (int,float) or not np.isfinite(eps) or not 1e-12<=eps<=1000:raise ValueError('bounded positive epsilon required')
    if type(momentum) not in (int,float) or not np.isfinite(momentum) or not 0<=momentum<=1:raise ValueError('momentum must be in [0,1]')
    if training:
        n=len(x)
        if n<2:raise ValueError('tracked training needs at least two observations')
        mean=x.mean(axis=0);var=((x-mean)**2).mean(axis=0)
        new_mean=(1-momentum)*old_mean+momentum*mean
        new_var=(1-momentum)*old_var+momentum*var*n/(n-1)
    else:
        mean,var=old_mean,old_var
        new_mean,new_var=old_mean.copy(),old_var.copy()
    normalized=(x-mean)/np.sqrt(var+eps)
    return gamma*normalized+beta,new_mean,new_var


def training_jacobians(x,gamma,eps):
    x=array(x);gamma=array(gamma)
    # Reuse the public forward contract before constructing a dense Jacobian.
    c=x.shape[1] if x.ndim==2 else 0
    batchnorm(x,gamma,np.zeros(c),np.zeros(c),np.ones(c),eps=eps)
    n=len(x);centered=x-x.mean(axis=0);var=(centered**2).mean(axis=0)
    result=[]
    for j in range(c):
        v=centered[:,j];s=np.sqrt(var[j]+eps)
        result.append(gamma[j]/s*(np.eye(n)-np.ones((n,n))/n-np.outer(v,v)/(n*(var[j]+eps))))
    return np.stack(result)


if __name__=='__main__':
    x=np.array([[1,2],[2,4],[3,6]],dtype=float)
    gamma=np.array([2,np.sqrt(3)]);beta=np.array([1,-1])
    y,mean,var=batchnorm(x,gamma,beta,[0,0],[1,1],eps=1/3,momentum=0.5)
    evaluated,_,_=batchnorm(x,gamma,beta,mean,var,training=False,eps=1/3,momentum=0.5)
    print('training output:',np.round(y,6).tolist())
    print('running mean:',mean.tolist(),'running variance:',var.tolist())
    print('evaluation output:',np.round(evaluated,6).tolist())
    print('first-channel Jacobian:',np.round(training_jacobians(x,gamma,1/3)[0],6).tolist())

Actual output, rounded only for display:

training output: [[-1.0, -3.0], [1.0, -1.0], [3.0, 1.0]]
running mean: [1.0, 2.0] running variance: [1.0, 2.5]
evaluation output: [[1.0, -1.0], [2.732051, 1.057983], [4.464102, 3.115966]]
first-channel Jacobian: [[0.666667, -0.666667, 0.0], [-0.666667, 1.333333, -0.666667], [0.0, -0.666667, 0.666667]]

The same first input row now evaluates to (1,−1), although its training output was (−1,−3). That is expected because evaluation uses the stored state. Tests compare the literal training results and state, check both channels’ full Jacobians by finite differences, verify shift invariance and check constant batches, singleton evaluation, invalid variances and nonfinite inputs.

Forward computation costs O(NC). The optional dense Jacobian audit costs O(CN²) space and time; ordinary backpropagation can multiply by the Jacobian without materializing this matrix and retain O(NC) work. The example fixes γ and β to inspect normalization, rather than running an optimizer to learn them.

A mode switch changes the computation

Our tracked training requires at least two rows because the running-variance correction divides by m−1. Evaluation accepts one row. This is the contract of this small N-by-C implementation, not a claim that every normalization operation mathematically requires multiple samples. Spatial or sequence axes can contribute additional observations in other layer variants.

The documented track_running_stats=False mode uses batch statistics during evaluation too; we do not implement that option. Microbatch accumulation therefore cannot automatically reproduce one larger batch’s normalization: each forward pass may use different companions even if the later gradients are added correctly.

Stored statistics can mismatch deployment inputs. Running test inputs through training mode can alter both outputs and state; restoring weights while forgetting running means and variances can also change predictions. Checkpoints and evaluation procedures must account for this state.

The original paper motivated the method through internal covariate shift. Santurkar and colleagues’ 2018 paper questions that explanation and studies optimization smoothness instead. That is a later research interpretation, not a theorem that every normalized architecture has one universally established mechanism of improvement.

Which variance did you use?

  1. For the first feature values 1,2,3, what are the forward and unbiased sample variances?

Answer 1: 2/3 and 1, respectively.

  1. With old running variance (1,1) and a=1/2, what state follows the example batch?

Answer 2: Running variance (1,5/2).

  1. Does positive ε give normalized empirical variance exactly one?

Answer 3: No. Before γ and β, it is v/(v+ε).

  1. Why can a training output change when only a different row changes?

Answer 4: The other row changes the shared batch mean and variance; the off-diagonal Jacobian entries express that dependence.

Separate the operation, state convention and explanation

The original paper defines batch normalization and distinguishes inference statistics. The fixed API documents the two variance estimators and its running-average convention. The later paper’s abstract supports the narrow statement about a competing explanation, not a reproduced proof or benchmark.

The NumPy implementation, three-row calculation, derivative audit and exercises are original. PyTorch itself was not executed. Continue with minibatches and forward propagation to locate this cross-example computation inside a full training loop.

Make a prediction, then check

For values1,2,3, which variance does the displayed training normalization use?

Choose one answer

Learning objectives

  • Distinguish forward variance from running-state updates.
  • Explain training/evaluation and cross-example derivatives.

Prerequisites & connections

Explore related knowledge →

References

  1. Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift
    Sergey Ioffe; Christian Szegedy · 2015
  2. BatchNorm1d — PyTorch 2.8
    PyTorch contributors
  3. How Does Batch Normalization Help Optimization?
    Shibani Santurkar; Dimitris Tsipras; Andrew Ilyas; Aleksander Madry · 2018

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.

  • Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
  • Four focused CPython3.12.4 tests passed per chapter. Decay paths, exact dropout distributions, checkpoint restoration and batch-normalization derivatives/state are checked against literal references, analytic identities and finite differences. Three examples use the standard library; BatchNorm uses NumPy1.26.4.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.