AI Wiki中文/EN

Gradient accumulation: one update from unequal microbatches

梯度累积

Match a weighted full-batch gradient exactly, expose incorrect averaging, and identify batch-dependent exceptions.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with the problem

Your intended batch has six rows, but memory fits only a few at a time. You can compute gradients on smaller microbatches while leaving the parameters fixed, accumulate the contributions, and make one optimizer update at the end. The point is to preserve the intended objective while reducing simultaneously stored activations.

The trap is the word “mean.” Averaging the mean gradient of a one-row microbatch with that of a three-row microbatch gives those groups equal influence. That is not a six-row mean. With sample weights, even row counts are insufficient: the relevant normalization is total weight. The PyTorch autograd notes explain gradient accumulation into leaf tensors; the mathematics below decides what should be accumulated.

Definitions and derivation

Let each example have nonnegative weight aᵢ and per-example loss ℓᵢ. The total weight A must be positive. Our objective also regularizes the slope, while leaving the intercept unpenalized:

L(θ)=∑iaiℓi(θ)A+λ2θ12,A=∑iai>0,ai≥0.L(\theta)=\frac{\sum_i a_i\ell_i(\theta)}{A}+\frac\lambda2\theta_1^2, \qquad A=\sum_i a_i>0,\quad a_i\ge0.

Partition rows into disjoint microbatches Bⱼ. If a group has positive weight Aⱼ, its weighted mean gradient is gⱼ. Linearity of differentiation gives:

Aj=∑i∈Bjai,gj=1Aj∑i∈Bjai∇ℓi(θ),∇L=∑j:Aj>0AjAgj+λ(θ1,0)⊤.A_j=\sum_{i\in B_j}a_i,\quad g_j=\frac1{A_j}\sum_{i\in B_j}a_i\nabla\ell_i(\theta),\qquad \nabla L=\sum_{j:A_j>0}\frac{A_j}{A}g_j+\lambda(\theta_1,0)^\top.

All gⱼ must be evaluated at the same θ. Multiplying each group mean by its mass, summing, then dividing by total mass recovers the intended gradient. A zero-mass group contributes nothing and must be skipped rather than divided by zero. Add the regularizer gradient once after data accumulation. Alternatively it can be distributed across groups with weights that sum to one; adding the full regularizer at every group overcounts it.

For our two-parameter linear model, each row xᵢ contains an input and an intercept feature equal to 1. The gradient and one update are:

ℓi=12(xi⊤θ−yi)2,∇L=X⊤diag⁡(a)(Xθ−y)A+λ(θ1,0)⊤,θ+=θ−η∇L.\ell_i=\tfrac12(x_i^\top\theta-y_i)^2,\qquad \nabla L=\frac{X^\top\operatorname{diag}(a)(X\theta-y)}{A}+\lambda(\theta_1,0)^\top, \qquad\theta^+=\theta-\eta\nabla L.

This is an algebraic equivalence for an additive loss with fixed parameters. Sequential floating-point additions can differ slightly from a large matrix reduction. Performing an optimizer step after each microbatch changes the point at which later gradients are evaluated, and also changes momentum or Adam state. That is a different training procedure.

Computed gradients for the same six weighted rows. Group masses are 1, 1 and 4; all methods include the regularizer once.
Computed gradients for the same six weighted rows. Group masses are 1, 1 and 4; all methods include the regularizer once.

Run the calculation

The complete Python 3.12 / NumPy 1.26.4 program uses six rows with weights (1,1,0,2,1,1). Microbatch sizes are (1,2,3), but their positive masses are (1,1,4). The penalty coefficient is 0.2. The program also computes the wrong equal average for comparison.

import numpy as np


def check(x, y, weights, theta):
    x, y, weights, theta = [np.asarray(a, dtype=float) for a in (x, y, weights, theta)]
    if x.ndim != 2 or not 1 <= len(x) <= 64 or x.shape[1] != 2 or y.shape != (len(x),) or weights.shape != y.shape or theta.shape != (2,):
        raise ValueError('Expected 1 to 64 rows, two features and matching vectors.')
    if not all(np.isfinite(a).all() for a in (x, y, weights, theta)) or np.any(weights < 0) or weights.sum() <= 0:
        raise ValueError('Use finite values and positive total nonnegative weight.')
    return x, y, weights, theta


def full(x, y, weights, theta):
    x, y, weights, theta = check(x, y, weights, theta)
    residual = x @ theta - y
    penalty = np.array([0.2 * theta[0], 0.0])
    value = (weights * residual ** 2).sum() / (2 * weights.sum()) + 0.1 * theta[0] ** 2
    grad = x.T @ (weights * residual) / weights.sum() + penalty
    return float(value), grad


def accumulate(x, y, weights, theta, sizes):
    x, y, weights, theta = check(x, y, weights, theta)
    if not sizes or any(type(s) is not int or s < 1 for s in sizes) or sum(sizes) != len(x):
        raise ValueError('Positive integer microbatch sizes must partition all rows.')
    numerator = np.zeros(2)
    means, begin = [], 0
    for size in sizes:
        end = begin + size
        mass = weights[begin:end].sum()
        if mass > 0:
            g = x[begin:end].T @ (weights[begin:end] * (x[begin:end] @ theta - y[begin:end])) / mass
            numerator += mass * g
            means.append(g)
        begin = end
    penalty = np.array([0.2 * theta[0], 0.0])
    return numerator / weights.sum() + penalty, np.mean(means, axis=0) + penalty


def data():
    return np.column_stack(([-2, -1, 0, 1, 2, 3], np.ones(6))), np.array([1, 0, 2, 1, 3, 5]), np.array([1, 1, 0, 2, 1, 1]), np.array([0.3, -0.2])


def normalize(values):
    values = np.asarray(values, dtype=float)
    return (values - values.mean()) / np.sqrt(values.var() + 1)


if __name__ == '__main__':
    x, y, weights, theta = data()
    value, reference = full(x, y, weights, theta)
    actual, wrong = accumulate(x, y, weights, theta, [1, 2, 3])
    print('loss', round(value, 9), 'full gradient', reference.round(9).tolist())
    print('weighted accumulation', actual.round(9).tolist(), 'wrong equal means', wrong.round(9).tolist())
    print('one update', (theta - 0.1 * actual).round(9).tolist())
    print('normalization whole', normalize([0, 2, 4, 6]).round(6).tolist())
    print('normalization split', np.concatenate((normalize([0, 2]), normalize([4, 6]))).round(6).tolist())

Actual output:

loss 2.539 full gradient [-2.573333333, -1.833333333]
weighted accumulation [-2.573333333, -1.833333333] wrong equal means [-0.231666667, -1.491666667]
one update [0.557333333, -0.016666667]
normalization whole [-1.224745, -0.408248, 0.408248, 1.224745]
normalization split [-0.707107, 0.707107, -0.707107, 0.707107]

The correct slope gradient is −2.573333333; equal averaging gives −0.231666667, a material change in direction magnitude. One rate-0.1 update produces (0.557333333,−0.016666667). A finite-difference check of the full weighted objective independently verifies both gradient coordinates.

For n rows and d parameters in this linear example, data work is O(nd), with an O(d) accumulator. A real neural network can release each microbatch graph after backward; it still keeps parameters, optimizer state and accumulated gradients. Accumulation does not remove those persistent memory costs.

When the method fails

The equivalence fails if splitting changes the forward function. The printed normalization counterexample uses batch mean and variance: normalizing (0,2,4,6) together differs from normalizing (0,2) and (4,6) separately. Thus ordinary training-mode batch normalization does not automatically behave like a larger batch under accumulation. Matching dropout randomness also requires a stated policy; fresh masks need not reproduce a particular full-batch realization.

With mixed precision, the AMP accumulation recipe keeps gradients scaled by one constant factor throughout the effective batch. Unscale and clip after all contributions, then step, update the scale and clear accumulated gradients. Handle the last incomplete group using its actual mass. A fixed divisor equal to the nominal number of microbatches is valid only when the reduction and group weights justify it.

Exercises with answers

  1. Two microbatches have masses 1 and 3 and mean gradients 2 and 6. What is the combined mean?

Answer 1: (1×2+3×6)/4=5, not the unweighted mean 4.

  1. What should happen to a microbatch whose sample weights are all zero?

Answer 2: Skip its data-gradient contribution. Reject the entire effective batch only if total weight is zero.

  1. Why not call the optimizer after each microbatch?

Answer 3: Later gradients would use changed parameters and the optimizer would advance more often, breaking the one-update equivalence.

  1. Does accumulation make batch-normalization statistics use all effective-batch rows?

Answer 4: No. Without an explicit alternative computation, each forward pass uses its own microbatch statistics.

Sources and next steps

The framework sources establish gradient-buffer behavior and AMP ordering. The weighted decomposition, unequal-group counterexample, regularizer treatment and normalization numbers are original derivations and CPU calculations. Compare activation checkpointing, which reduces retained activations through recomputation rather than changing the batch partition.

Make a prediction, then check

Which factor combines microbatch mean gradients correctly?

Choose one answer

Learning objectives

  • Derive mass-weighted accumulation with one regularizer contribution.
  • Identify forward-state conditions required for full-batch equivalence.

Prerequisites & connections

Explore related knowledge →

References

  1. Automatic Mixed Precision examples — PyTorch 2.8
    PyTorch contributors
  2. Autograd mechanics — PyTorch 2.8
    PyTorch contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.

  • Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
  • Four focused CPython 3.12.4 tests passed per chapter, including independent derivatives, integrals, normal equations or exact/literal trajectory references as appropriate. NumPy 1.26.4 is used in six programs; PBT and curriculum use standard-library exact fractions. CPU teaching calculations, not framework or GPU benchmarks.
  • 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.
  • Bilingual SVG charts generated by Matplotlib 3.9.1 from executed chapter functions. Actual weighted gradients, logical activation/call counts and fixed-target excess losses are distinguished from hardware measurements. Both locale figures and sample data are hash-bound.

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.