AI Wiki中文/EN

Group normalization: define the channel neighborhood

组归一化

Expose group statistics, affine sharing, independence across samples and the exact conditions for matching layer normalization.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Keep the sample, choose its channel neighbors

An image may have hundreds of feature channels but a training batch of only one image. Group normalization computes statistics within that image: it divides channels into groups, and each group pools its channel and spatial values. Another image in the batch contributes nothing to that group’s mean.

Wu and He’s 2018 paper, Section 3 defines these groups through index sets. The fixed PyTorch 2.8 GroupNorm documentation requires the group count to divide the channel count, uses a biased variance and learns one scale and shift per channel. Training and evaluation both use current input statistics.

The grouping is a specified partition, not a clustering algorithm that discovers similar channels. It also does not require grouped convolutions in the preceding layer.

Write down the values in one group

Use input shape (N,C,S), where S flattens the spatial positions. Let G divide C, and let c and s be zero-based channel and spatial indices. For example n and group g, the normalized set is:

Sn,g={(n,c,s):gC/G≤c<(g+1)C/G, 0≤s<S},m=∣Sn,g∣=(C/G)S.\mathcal S_{n,g}=\{(n,c,s):gC/G\le c<(g+1)C/G,\ 0\le s<S\}, \qquad m=|\mathcal S_{n,g}|=(C/G)S.

Only one sample index appears in this set. Each group contains adjacent channel indices under the chosen layout and all S positions. Rearranging channels across group boundaries changes the operation unless the grouping and parameters are rearranged consistently.

For the group containing channel c, compute:

μn,g=1m∑i∈Sn,gxi,vn,g=1m∑i∈Sn,g(xi−μn,g)2,yn,c,s=γcxn,c,s−μn,gvn,g+ϵ+βc.\mu_{n,g}=\frac1m\sum_{i\in\mathcal S_{n,g}}x_i,\quad v_{n,g}=\frac1m\sum_{i\in\mathcal S_{n,g}}(x_i-\mu_{n,g})^2,\quad y_{n,c,s}=\gamma_c\frac{x_{n,c,s}-\mu_{n,g}}{\sqrt{v_{n,g}+\epsilon}}+\beta_c.

The mean and variance are shared within a group, but γ and β remain channel-specific. Two channels in the same group need not have the same output mean after this affine transform. The variance divisor is m; no running population estimate is being updated here.

One group, two groups, four groups

Our single sample has four channels, each with two positions: (0,2), (4,6), (10,12), (14,16). With two groups, the groups have means 3 and 13 and variances 5 and 5. Choosing ε=4 gives denominator three, so both normalized groups are (−1,−1/3,1/3,1).

With one group, all eight numbers share mean 8 and variance 30. With four groups, every channel uses its own spatial mean (1,5,11,15), each with variance one. Changing G changes which offsets and contrasts remain; it is not merely a speed setting.

When does one group match layer normalization?

Before the affine transform, one group normalizes the same values as layer normalization over the full (C,S) slice. Including affine transforms, equality requires:

GN⁡G=1(x;γc,βc)=LN⁡(C,S)(x;Γc,s,Bc,s)ifΓc,s=γc, Bc,s=βc\operatorname{GN}_{G=1}(x;\gamma_c,\beta_c) =\operatorname{LN}_{(C,S)}(x;\Gamma_{c,s},B_{c,s}) \quad\text{if}\quad \Gamma_{c,s}=\gamma_c,\ B_{c,s}=\beta_c

This also assumes the same ε and variance convention. GroupNorm has 2C affine parameters; a general LayerNorm over (C,S) has 2CS. Its unconstrained per-position parameters need not match the channel-shared transform. GroupNorm with G=C has per-sample, per-channel spatial normalization statistics, as in instance normalization, but state and affine options must still be matched when comparing APIs.

Expose the group statistics

The complete Python 3.12 / NumPy 1.26.4 example explicitly loops over samples and groups. It handles an N-by-C-by-S tensor, returns the group means and variances, and broadcasts affine parameters only along sample and spatial axes. S can represent a flattened image grid, but this program performs no convolution or image loading.

import numpy as np


def groupnorm(x, groups, gamma, beta, eps=1e-5):
    x=np.array(x,dtype=np.float64,copy=True)
    if x.ndim!=3 or not 0<x.size<=4096 or any(d==0 for d in x.shape):raise ValueError('bounded nonempty N,C,S tensor required')
    n,c,s=x.shape
    if type(groups) is not int or not 1<=groups<=c or c%groups:raise ValueError('group count must divide channels')
    gamma,beta=[np.array(v,dtype=np.float64,copy=True) for v in (gamma,beta)]
    if gamma.shape!=(c,) or beta.shape!=(c,):raise ValueError('one affine pair per channel required')
    if any(not np.isfinite(v).all() or np.any(np.abs(v)>1000) for v in (x,gamma,beta)):raise ValueError('finite bounded entries 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')
    width=c//groups;out=np.empty_like(x);means=np.empty((n,groups));variances=np.empty_like(means)
    for sample in range(n):
        for group in range(groups):
            start=group*width;stop=start+width
            block=x[sample,start:stop,:];mean=block.mean();var=((block-mean)**2).mean()
            out[sample,start:stop,:]=(block-mean)/np.sqrt(var+eps)
            means[sample,group]=mean;variances[sample,group]=var
    return out*gamma[None,:,None]+beta[None,:,None],means,variances


if __name__=='__main__':
    x=np.array([[[0,2],[4,6],[10,12],[14,16]]],dtype=float)
    for groups in (1,2,4):
        y,m,v=groupnorm(x,groups,[1,1,1,1],[0,0,0,0],eps=4)
        print('groups:',groups,'means:',m.tolist(),'variances:',v.tolist())
        print('output:',np.round(y,6).tolist())
    affine=groupnorm(x,2,[1,2,1,2],[0,1,0,1],eps=4)[0]
    print('per-channel affine output:',np.round(affine,6).tolist())

Actual output, rounded for display:

groups: 1 means: [[8.0]] variances: [[30.0]]
output: [[[-1.371989, -1.028992], [-0.685994, -0.342997], [0.342997, 0.685994], [1.028992, 1.371989]]]
groups: 2 means: [[3.0, 13.0]] variances: [[5.0, 5.0]]
output: [[[-1.0, -0.333333], [0.333333, 1.0], [-1.0, -0.333333], [0.333333, 1.0]]]
groups: 4 means: [[1.0, 5.0, 11.0, 15.0]] variances: [[1.0, 1.0, 1.0, 1.0]]
output: [[[-0.447214, 0.447214], [-0.447214, 0.447214], [-0.447214, 0.447214], [-0.447214, 0.447214]]]
per-channel affine output: [[[-1.0, -0.333333], [1.666667, 3.0], [-1.0, -0.333333], [1.666667, 3.0]]]

With two groups, setting γ=(1,2,1,2) and β=(0,1,0,1) changes channels 1 and 3 to (5/3,3), while channels 0 and 2 remain (−1,−1/3). The shared statistics did not force shared affine parameters.

Tests check the literal statistics for all three group counts, compare one-group results with a separately calculated full-slice normalization, and verify per-channel affine broadcasting. Changing another sample or a different group leaves the first group unchanged. Invalid divisibility, shapes, nonfinite values, zero ε and a constant one-element group are also covered. Work and output storage are O(NCS), group-statistic storage O(NG), and affine storage O(C).

Independent statistics do not imply identical training runs

Changing batch size alone does not alter this layer’s per-sample normalization. It can still change gradient estimates, update counts and other layers in the network. Therefore the same GroupNorm operation does not guarantee the same optimizer trajectory or model accuracy across batch sizes.

A large group pools more values but removes a broader shared offset. A small group centers each subset separately, removing differences between group means, and may have too few values for a useful normalization. With one value in a group, centering makes the normalized value zero and the output equals its channel bias. Our mathematical teaching implementation allows that case; a framework may impose additional input checks.

Spatial padding contributes to statistics here. If padding should be ignored, a separate masked definition is needed. The original paper’s reported small-batch results concern specific architectures, data and training conditions; this example does not reproduce those measurements or establish a universally best group count.

How many values contribute?

  1. With C=4, S=2 and G=2, how many values form each statistic?

Answer 1: Four: two channels times two positions, from one sample.

  1. What are the two group means in the example?

Answer 2: Three and thirteen.

  1. Does G=1 always equal an arbitrary LayerNorm(C,S) including affine parameters?

Answer 3: No. The LayerNorm affine parameters must be shared across spatial positions to match GroupNorm’s per-channel parameters.

  1. What happens when one group contains a single value?

Answer 4: Its centered value is zero, so output is the affine bias.

A normalization family can be compared by index sets

The original paper provides the group-index formulation and relates its extremes to earlier methods. The fixed API makes the affine and variance conventions concrete. The loop implementation, literal tensor and equivalence checks here are original; no paper figure, TensorFlow snippet or trained model was copied.

Compare layer normalization for trailing-axis choices and batch normalization for cross-sample statistics and running state. Always compare the selected values, divisor, ε, affine sharing and evaluation behavior together.

Make a prediction, then check

For C4,S2,G2, how many values contribute to each group statistic?

Choose one answer

Learning objectives

  • List the sample, channel and spatial values used by each group.
  • Check affine sharing before claiming normalization equivalence.

Prerequisites & connections

Explore related knowledge →

References

  1. Group Normalization
    Yuxin Wu; Kaiming He · 2018
  2. GroupNorm — PyTorch 2.8
    PyTorch contributors
  3. LayerNorm — PyTorch 2.8
    PyTorch contributors

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. Normalization axes and groups, matched residual fits and reverse graph paths are checked against literal references, analytic identities and finite differences. Two examples use NumPy1.26.4; two use the standard library.
  • 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:

  • Group Normalization · Section3 physicalpages5–6, Eqs1–7: NCHW index sets, contiguous channel groups, per-channel affine, group extremes; original NumPy loop rather than copied TensorFlow Figure3.
  • GroupNorm — PyTorch 2.8 · Fixed2.8 GroupNorm body: divisibility, per-channel affine, biased variance, current-input stats in both modes and shape(N,C,*).
  • LayerNorm — PyTorch 2.8 · Fixed2.8 LayerNorm normalized_shape and per-element affine: used to qualify one-group equivalence.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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