Module contents
Lesson 11 of 22Core 80 min

Minibatch training: gradient noise and batch size

Minibatches turn gradients into noisy estimates. Study epochs and shuffling, measure gradient noise during training, examine critical batch size and the steps-versus-examples frontier, and assess learning-rate scaling and large-batch generalization.

After this lesson you can

  • Implement a minibatch iterator with epoch shuffling and compare sampling without and with replacement.
  • Measure network gradient variance as batch size changes and check 1/B scaling.
  • Measure gradient noise during training and estimate a critical batch size for a specific problem.
  • Apply linear learning-rate scaling with warmup and recognize its limits.
  • Use controlled experiments to investigate batch size and update count in generalization gaps.

Before you start

An approximate direction

A full-gradient update uses every available example to estimate a direction. A minibatch uses only some: each update costs less and its direction fluctuates. That fluctuation is not always helpful or harmful; it can allow more updates for the same number of examples processed, but also limits step precision. Full batches remain useful, for example as a reference in a small test.

An epoch is one pass through the training set; a step is one update. With NN examples and nominal batch size BB, an epoch has ⌈N/B⌉\lceil N/B\rceil steps if the final incomplete batch is retained and ⌊N/B⌋\lfloor N/B\rfloor if discarded. Retaining it avoids omitting examples, but its mean uses its actual size. When averaging batch losses to obtain an epoch mean, weight by the number of examples in each batch rather than assigning the smaller final batch equal weight.

Shuffling a new permutation each epoch avoids a fixed order correlated with labels. At a fixed point, a uniform sample without replacement is unbiased; during a training epoch, the current parameter depends on examples already seen and the remaining ones are not generally an independent uniform sample conditional on that parameter. HaoChen and Sra study reshuffling benefits under specific convexity and regularity assumptions, not a guarantee of superiority for every nonconvex network.

How much does a gradient vary?

Fix parameters θ\theta and let gig_i denote the gradient of example ii. Define G=N−1∑igiG=N^{-1}\sum_i g_i and population covariance Σ=N−1∑i(gi−G)(gi−G)T\Sigma=N^{-1}\sum_i(g_i-G)(g_i-G)^\mathsf{T}. If BB indices are chosen independently and uniformly with replacement, E[G^B]=G\mathbb E[\hat G_B]=G and

Cov⁡(G^B)=ΣB,E∥G^B∥2=∥G∥2+tr⁡(Σ)B.\operatorname{Cov}(\hat G_B)=\frac{\Sigma}{B},\qquad \mathbb E\|\hat G_B\|^2=\|G\|^2+\frac{\operatorname{tr}(\Sigma)}{B}.

The first equality uses independence and the second separates variance and mean. Without replacement, with 1≤B≤N1\leq B\leq N and N>1N>1, correction (N−B)/(N−1)(N-B)/(N-1) appears; in particular the full batch from that population has zero variance. This formula uses the definition of Σ\Sigma with divisor NN. A different covariance convention changes the factor’s form. The exercise asks you to prove it, and the lab compares both sampling methods without updating parameters during measurement.

When ∥G∥>0\|G\|>0, the simple scale Bsimple=tr⁡(Σ)/∥G∥2B_{\mathrm{simple}}=\operatorname{tr}(\Sigma)/\|G\|^2 compares individual gradient variation with the squared mean gradient. It is undefined if G=0G=0. A decrease in ∥G∥\|G\| can make it grow, but neither loss nor this ratio must vary monotonically. The figure shows a real short Fashion-MNIST run: loss falls between checkpoints while noise estimates fluctuate.

InteractiveNoise scale during training

MLP 784 → 128 → 10 trained with SGD on 8192 Fashion-MNIST images. At each checkpoint the same 2048 training examples and 128 gradients of batches of 32 sampled with replacement are evaluated. The large point is the mean gradient of the full subset.

Vertical axis: projection onto a direction orthogonal to the full gradient
Preparing the projection…
Horizontal axis: projection onto the full-gradient direction
  • Batch of 32
  • Gradient of 2048 examples

Both directions are recalculated at each checkpoint: the first follows the full gradient and the second is an orthogonal random vector. Axes scale independently; the projection shows only two dimensions, while noise scale uses all parameters.

Noise scale during this training run
Vertical axis: estimated scale in examples · horizontal axis: SGD steps
Preparing the curve…
  • Sample variance / full gradient
  • Two-batch estimator

The first curve uses sample variance of 128 gradients of size 32 and the norm of the full gradient over those 2048 examples. The second estimates numerator and denominator from sizes 32 and 256; each large batch groups eight small ones, so there are only 16 large samples. Differences reflect sampling uncertainty. Loss falls in this run, but the scale fluctuates and need not grow monotonically or universally.

0
Subset loss2.3088
Scale, two batches64.3
Scale with full gradient61.6
Change checkpoint and observe the measured projections and two estimates. They come from one particular short run; the scale does not grow monotonically in it.

In the figure’s measurement, the reference gradient is calculated on a fixed training subset and each test batch is drawn with replacement from that subset. The cloud is a projection onto two directions, not the whole parameter space. The two-batch estimate uses finitely many samples and can be unstable. The local code producing these data appears below; arithmetic and hardware can introduce small differences on repetition.

From variance to a critical batch size

The steps-versus-examples frontier asks how many updates and examples are needed to reach a goal. Increasing BB can initially reduce steps, but each step consumes more examples. In a local quadratic approximation with positive semidefinite Hessian HH, mean gradient GG, covariance Σ\Sigma, GTHG>0G^\mathsf{T}HG>0 and finite traces, using an iid minibatch with replacement at that fixed point, the approximate expected loss change in one step is

−η∥G∥2+η22(GTHG+tr⁡(HΣ)B).-\eta\|G\|^2+\frac{\eta^2}{2}\left(G^\mathsf{T}HG+ \frac{\operatorname{tr}(H\Sigma)}{B}\right).

Minimizing this expression with respect to η\eta gives ηopt(B)=ηmax⁡/(1+BH/B)\eta_{\rm opt}(B)=\eta_{\max}/(1+B_H/B), where ηmax⁡=∥G∥2/(GTHG)\eta_{\max}=\|G\|^2/(G^\mathsf{T}HG) and BH=tr⁡(HΣ)/(GTHG)B_H=\operatorname{tr}(H\Sigma)/(G^\mathsf{T}HG). The simple scale replaces curvature weighting and is a proxy, not generally identical to BHB_H. If H=hIH=hI with h>0h>0, the two coincide. McCandlish and colleagues study this relationship and an empirical frontier; it does not turn a noisy measurement into an exact law for every training run.

InteractiveSteps versus examples
The function is L(θ) = θ²/2, with θ₀ = 1 and estimated gradient θ + ξ. Noise is independent between steps, centered, and has variance 16/B. The target is E[L] ≤ 0.01; the vertical line marks the selected batch.
Steps to target expected loss
Examples processed to target
Batches whose floor exceeds the target do not appear on the curves. If the floor equals the target, they do not reach it in finite time either, unless η = 1: then the recurrence reaches the floor in one step. Nearly equal values are treated as equal to avoid rounding errors.
For qₜ = E[θₜ²], the exact recurrence is qₜ₊₁ = (1 − η)²qₜ + η²·16/B and E[Lₜ] = qₜ/2. We compute the first integer step with E[Lₜ] ≤ 0.01, not the average first crossing step of a random trajectory. The calculation assumes independent samples with replacement and constant η during each run.
In scaled mode, η = factor · B/(B + 800). The 800 is 16/target q, this model’s noise scale at the target; with factor 1 the formula minimizes qₜ₊₁ if qₜ exactly equals target q. The rate remains fixed for each individual curve: this is neither a universal network guarantee nor a measured estimate.
Learning rate
256
1.00
Effective rate η0.24242
Expected loss floor0.00431
Steps to target9
Examples to target2304
Explore a quadratic with explicit noise. The target is an expected loss; cases that do not reach it are shown separately.

In that one-dimensional model, L(θ)=θ2/2L(\theta)=\theta^2/2 and noise has variance σ2/B\sigma^2/B. For θt+1=(1−η)θt−ηξt\theta_{t+1}=(1-\eta)\theta_t-\eta\xi_t, with centered noise independent of state and variance σ2/B\sigma^2/B,

E[θt+12]=(1−η)2E[θt2]+η2σ2/B.\mathbb E[\theta_{t+1}^2]=(1-\eta)^2\mathbb E[\theta_t^2]+\eta^2\sigma^2/B.

The graph counts the first step when expected loss crosses the target. This is not the expected first crossing time of a trajectory. For 0<η<20<\eta<2, the recurrence has a stationary floor; if it lies above the target, no arrival time is invented. The number of examples is BB times the number of steps and excludes validation costs and hardware effects.

Measure a scale instead of guessing it

The equality for E∥G^B∥2\mathbb E\|\hat G_B\|^2 yields two estimators. For Bp<BgB_p<B_g, sample means qpq_p and qgq_g of squared norms, and iid batches at a fixed point,

∥G∥2^=Bgqg−BpqpBg−Bp,tr⁡Σ^=qp−qg1/Bp−1/Bg.\widehat{\|G\|^2}=\frac{B_gq_g-B_pq_p}{B_g-B_p},\qquad \widehat{\operatorname{tr}\Sigma}=\frac{q_p-q_g}{1/B_p-1/B_g}.

Each component is unbiased under that sampling; their ratio need not be. With finite samples either can be negative and a denominator near zero makes the ratio unstable. Average quantities before dividing, show the sample count, and do not hide a nonpositive denominator. The formulas require the gradient to remain fixed while batches are drawn.

The first cell reproduces the tensor engine from the previous lesson. The following cells train a small MLP on a fixed load_digits subset, compute per-example gradients, and compare the empirical trace with 1/B1/B and the finite-population correction. The reserved test split is not used here: the purpose is to check an identity on the chosen set, not estimate generalization.

[ ]Tensor engine from the previous lessonBrowser
import numpy as np
from copy import deepcopy

def unbroadcast(grad, shape):
    grad = np.asarray(grad)
    while grad.ndim > len(shape):
        grad = grad.sum(axis=0)
    for axis, size in enumerate(shape):
        if size == 1 and grad.shape[axis] != 1:
            grad = grad.sum(axis=axis, keepdims=True)
    if grad.shape != tuple(shape):
        raise ValueError('formas incompatibles')
    return grad

class Tensor:
    def __init__(self, data, parents=(), backward=None):
        self.data = np.array(data, dtype=np.float64, copy=True)
        self.grad = np.zeros_like(self.data)
        self.parents = tuple(parents)
        self._backward = backward or (lambda: None)

    @staticmethod
    def wrap(x): return x if isinstance(x, Tensor) else Tensor(x)

    def __add__(self, other):
        other = Tensor.wrap(other)
        a_shape, b_shape = self.data.shape, other.data.shape
        out = Tensor(self.data + other.data, (self, other))
        def backward():
            self.grad += unbroadcast(out.grad, a_shape)
            other.grad += unbroadcast(out.grad, b_shape)
        out._backward = backward
        return out
    __radd__ = __add__

    def __mul__(self, other):
        other = Tensor.wrap(other)
        a, b = self.data.copy(), other.data.copy()
        out = Tensor(a*b, (self, other))
        def backward():
            self.grad += unbroadcast(out.grad*b, a.shape)
            other.grad += unbroadcast(out.grad*a, b.shape)
        out._backward = backward
        return out
    __rmul__ = __mul__
    def __neg__(self): return self * -1
    def __sub__(self, other): return self + (-Tensor.wrap(other))
    def __rsub__(self, other): return Tensor.wrap(other) - self

    def __matmul__(self, other):
        other = Tensor.wrap(other)
        a, b = self.data.copy(), other.data.copy()
        if a.ndim != 2 or b.ndim != 2:
            raise ValueError('matmul admite matrices 2D')
        out = Tensor(a @ b, (self, other))
        def backward():
            self.grad += out.grad @ b.T
            other.grad += a.T @ out.grad
        out._backward = backward
        return out

    def tanh(self):
        y = np.tanh(self.data)
        out = Tensor(y, (self,))
        out._backward = lambda: self._accumulate(out.grad*(1-y*y))
        return out
    def sigmoid(self):
        x = self.data
        y = np.exp(-np.logaddexp(0, -x))
        out = Tensor(y, (self,))
        out._backward = lambda: self._accumulate(out.grad*y*(1-y))
        return out
    def relu(self):
        mask = self.data > 0
        out = Tensor(np.maximum(self.data, 0), (self,))
        out._backward = lambda: self._accumulate(out.grad*mask)
        return out
    def exp(self):
        y = np.exp(self.data)
        out = Tensor(y, (self,))
        out._backward = lambda: self._accumulate(out.grad*y)
        return out
    def log(self):
        x = self.data.copy()
        if np.any(x <= 0): raise ValueError('log exige entrada positiva')
        out = Tensor(np.log(x), (self,))
        out._backward = lambda: self._accumulate(out.grad/x)
        return out
    def _accumulate(self, value): self.grad += value

    def sum(self, axis=None, keepdims=False):
        shape = self.data.shape
        axes = tuple(range(len(shape))) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
        axes = tuple(a % len(shape) for a in axes) if shape else ()
        out = Tensor(self.data.sum(axis=axis, keepdims=keepdims), (self,))
        def backward():
            g = out.grad
            if not keepdims:
                for a in sorted(axes): g = np.expand_dims(g, a)
            self.grad += np.broadcast_to(g, shape)
        out._backward = backward
        return out
    def mean(self, axis=None, keepdims=False):
        axes = tuple(range(self.data.ndim)) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
        count = int(np.prod([self.data.shape[a] for a in axes]))
        return self.sum(axis, keepdims) * (1.0/count)
    def max(self, axis=None, keepdims=False):
        shape = self.data.shape
        axes = tuple(range(len(shape))) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
        axes = tuple(a % len(shape) for a in axes) if shape else ()
        maxima = self.data.max(axis=axis, keepdims=True)
        mask = self.data == maxima
        counts = mask.sum(axis=axis, keepdims=True)
        out = Tensor(self.data.max(axis=axis, keepdims=keepdims), (self,))
        def backward():
            g = out.grad
            if not keepdims:
                for a in sorted(axes): g = np.expand_dims(g, a)
            self.grad += mask * (g/counts)
        out._backward = backward
        return out
    def reshape(self, *shape):
        original = self.data.shape
        out = Tensor(self.data.reshape(*shape), (self,))
        out._backward = lambda: self._accumulate(out.grad.reshape(original))
        return out
    def transpose(self, *axes):
        perm = (tuple(axes[0]) if len(axes) == 1 and isinstance(axes[0], (tuple, list))
                else tuple(axes) if axes else tuple(reversed(range(self.data.ndim))))
        transposed = self.data.transpose(perm)  # NumPy valida la permutación.
        normalized = tuple(a % self.data.ndim for a in perm) if self.data.ndim else ()
        inverse = np.argsort(normalized)
        out = Tensor(transposed, (self,))
        out._backward = lambda: self._accumulate(out.grad.transpose(inverse))
        return out
    def __getitem__(self, index):
        # También pueden mutarse listas o estructuras anidadas de índices.
        index = deepcopy(index)
        out = Tensor(self.data[index], (self,))
        def backward(): np.add.at(self.grad, index, out.grad)
        out._backward = backward
        return out
    @staticmethod
    def concat(tensors, axis=0):
        tensors = tuple(tensors)
        cuts = np.cumsum([t.data.shape[axis] for t in tensors])[:-1]
        out = Tensor(np.concatenate([t.data for t in tensors], axis=axis), tensors)
        def backward():
            for tensor, g in zip(tensors, np.split(out.grad, cuts, axis=axis)):
                tensor.grad += g
        out._backward = backward
        return out

    def backward(self, seed=None):
        if seed is None:
            if self.data.size != 1: raise ValueError('salida no escalar: proporciona semilla')
            seed = np.ones_like(self.data)
        seed = np.asarray(seed, dtype=float)
        if seed.shape != self.data.shape: raise ValueError('forma de semilla incorrecta')
        topo, seen, stack = [], set(), [(self, False)]
        while stack:
            node, done = stack.pop()
            if done: topo.append(node)
            elif node not in seen:
                seen.add(node)
                stack.append((node, True))
                stack.extend((p, False) for p in reversed(node.parents))
        for node in topo:
            if node.parents: node.grad.fill(0)
        self.grad += seed
        for node in reversed(topo): node._backward()
        return len(topo)

def cross_entropy(logits, labels):
    z = logits.data.copy()
    labels = np.asarray(labels)
    if (z.ndim != 2 or z.shape[0] == 0 or z.shape[1] == 0 or
            labels.ndim != 1 or labels.shape[0] != z.shape[0] or
            not np.issubdtype(labels.dtype, np.integer) or
            np.any(labels < 0) or np.any(labels >= z.shape[1])):
        raise ValueError('formas o etiquetas incorrectas')
    shifted = z - np.max(z, axis=1, keepdims=True)
    exp = np.exp(shifted)
    probabilities = exp/exp.sum(axis=1, keepdims=True)
    loss = np.mean(np.log(exp.sum(axis=1))-shifted[np.arange(len(labels)), labels])
    delta = probabilities.copy()
    delta[np.arange(len(labels)), labels] -= 1
    delta /= len(labels)
    out = Tensor(loss, (logits,))
    out._backward = lambda: logits._accumulate(out.grad*delta)
    return out
[ ]Data, network, and measurement at a fixed pointBrowser
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

features, labels = load_digits(return_X_y=True)
features = features/16
train_index, heldout = train_test_split(np.arange(len(labels)), test_size=0.2,
                                        stratify=labels, random_state=42)
chosen = np.random.default_rng(17).choice(train_index, 128, replace=False)
X, y = features[chosen], labels[chosen]
init = np.random.default_rng(31)
params = [Tensor(init.normal(0, np.sqrt(2/64), (64, 16))), Tensor(np.zeros(16)),
          Tensor(init.normal(0, np.sqrt(2/16), (16, 10))), Tensor(np.zeros(10))]
shuffle = np.random.default_rng(77)

def logits(x): return (Tensor(x) @ params[0] + params[1]).relu() @ params[2] + params[3]

def train_epochs(n):
    for _ in range(n):
        for ids in np.array_split(shuffle.permutation(len(y)), 4):
            for p in params: p.grad.fill(0)
            loss = cross_entropy(logits(X[ids]), y[ids])
            loss.backward()
            for p in params: p.data -= 0.1*p.grad

def measure(label):
    # En un punto fijo: no se cambia ningún parámetro durante este bucle.
    per_example = []
    for i in range(len(y)):
        for p in params: p.grad.fill(0)
        out = cross_entropy(logits(X[i:i+1]), y[i:i+1])
        out.backward()
        per_example.append(np.concatenate([p.grad.ravel().copy() for p in params]))
    matrix = np.array(per_example)
    G = matrix.mean(axis=0)
    sigma_trace = np.mean(np.sum((matrix-G)**2, axis=1))
    g2 = G@G
    full_loss = float(cross_entropy(logits(X), y).data)
    print(label, 'pérdida', full_loss, 'traza Sigma', sigma_trace,
          'norma media al cuadrado', g2, 'escala simple', sigma_trace/g2 if g2 > 0 else float('nan'))
    draws = np.random.default_rng(102)
    for batch in (1, 4, 16, 64):
        variance = 0.
        for _ in range(200):
            ids = draws.integers(0, len(y), size=batch)
            delta = matrix[ids].mean(axis=0)-G
            variance += delta@delta
        print('B, traza empírica, predicción con reemplazo', batch, variance/200, sigma_trace/batch)
    for batch in (16, 64, len(y)):
        variance = 0.
        for _ in range(200):
            ids = draws.choice(len(y), size=batch, replace=False)
            delta = matrix[ids].mean(axis=0)-G
            variance += delta@delta
        predicted = (sigma_trace/batch)*(len(y)-batch)/(len(y)-1)
        print('B, traza empírica, predicción sin reemplazo', batch, variance/200, predicted)
    small, big = 8, 64
    gs, gb = [], []
    for _ in range(100):
        a = matrix[draws.integers(0, len(y), size=small)].mean(axis=0)
        b = matrix[draws.integers(0, len(y), size=big)].mean(axis=0)
        gs.append(a@a); gb.append(b@b)
    es, eb = np.mean(gs), np.mean(gb)
    estimate_g2 = (big*eb-small*es)/(big-small)
    estimate_s = (es-eb)/(1/small-1/big)
    print('estimador dos lotes G², traza, cociente:', estimate_g2, estimate_s,
          estimate_s/estimate_g2 if estimate_g2 > 0 else float('nan'))
[ ]Before trainingBrowser
measure('inicial')
[ ]After three epochsBrowser
train_epochs(3)
measure('tras 3 épocas')
[ ]After twelve epochsBrowser
train_epochs(9)
measure('tras 12 épocas')

The cell’s simulations use finitely many draws. Differences from the prediction reflect sampling error as well as rounding; they are not an exact proof of the identity. The two-batch ratio is an estimate, not the true value. Change the seed and number of draws and observe variation.

Scaling the learning rate is not a universal law

The linear rule proposes multiplying η\eta by the same factor as BB in an appropriate regime; warmup gradually increases the rate initially to avoid excessively large early steps. In Goyal and colleagues, ResNet-50 on ImageNet moved from B=256B=256, η=0.1\eta=0.1 to B=8192B=8192, η=3.2\eta=3.2, with gradual five-epoch warmup. Table 1 reports validation top-1 errors of 23.60%±0.1223.60\%\pm0.12 and 23.74%±0.0923.74\%\pm0.09, respectively, versus 24.84%±0.3724.84\%\pm0.37 without gradual warmup for the large batch; these are means and deviations over five runs under that protocol, not promises for another network.

The scaling rule depends on optimizer, stage, and task. For adaptive methods, square-root rules with additional hyperparameter adjustments have been proposed under stochastic-approximation assumptions; Malladi and colleagues do not establish that multiplying by the square root suffices for every use of AdamW. Check stability and validation across a range rather than treating a recipe as a guarantee.

What does temperature mean?

For a one-dimensional approximation with iid noise of variance σ2/B\sigma^2/B, an SGD discretization has noise amplitude ησ/B\eta\sigma/\sqrt B. If also approximated by a diffusion with time step η\eta and constant additive noise, its effective temperature is T=ησ2/(2B)T=\eta\sigma^2/(2B) and ideal stationary density is proportional to e−U/Te^{-U/T}. The relationship η/B\eta/B describes that model under its assumptions; it is not a universal temperature for a network with state-dependent noise. Smith and Le develop another scaling convention that includes dataset size.

InteractiveSGD temperature

Explicit potential U(x) = (x² − 1)²(1 + 0.7x + 0.49x²), with equal-height minima at −1 and 1. The left minimum is flatter: their curvatures are 6.32 and 17.52, respectively.

step 0 / 500
  • Potential U
  • Current particles
  • Division between wells
Empirical distribution of 96 particles

Equal intervals between -1.5 and 1.5; the tallest bar represents 48 particles. The scale adjusts each step.

-1.5position x1.5

Update: x ← reflection[x − ηU′(x) + η·5·ξ/√B], with independent standard normal ξ. Half start at each minimum and trajectories reflect at the endpoints. Seed 411 fixes the samples; moving a control restarts the simulation.

In the idealized continuous diffusion with this isotropic noise and reflection, T = η·5²/(2B) and the stationary density is proportional to exp(−U/T). The equilibrium readout integrates that density numerically on both sides of the barrier x ≈ 0.1856. Particles follow finite discrete steps: they may not have crossed the barrier or reached equilibrium, and large η introduces discretization error. In real networks noise can depend on position, be anisotropic and non-Gaussian; η/B does not define a universal temperature.

0.040
2
Step0
Particles in left well50.0 %
Ideal continuous equilibrium, left62.2 %
Model T0.2500
Mean particle loss0.0000
Adjust learning rate and batch size in an explicit potential. Compare discrete trajectories with the stationary distribution of an idealized diffusion without confusing them.

Generalization and budgets

The debate on large batches and generalization requires controlling more than one variable. Keskar and colleagues report test accuracy 80.04%±0.1280.04\%\pm0.12 with a small batch versus 77.26%±0.4277.26\%\pm0.42 with a large batch for their C1 network on CIFAR-10 and relate their observations to sharpness; this does not prove every gap is explained solely by fewer steps. Dinh and colleagues show that some sharpness measures change under function-preserving reparameterizations. Shallue and colleagues collect results from 168160 models and 35 workloads and study the roles of budgets and tuning. None of these results supports a universal rule that large batches always generalize worse.

At minimum, compare different seeds and rates tuned using validation. Matching epochs approximately fixes examples processed, but not steps; matching steps changes the number of examples and computation. On a memory-limited GPU, the largest batch that fits is not automatically best: compare memory, examples per second, and required steps. Equal-step and equal-example experiments answer different questions; neither alone establishes the cause of a gap.

Real Fashion-MNIST experiment

The first local cell reproduces the short measurement underlying the noise figure: an 784→128→10784\to128\to10 MLP, explicit subset and seeds, a reference gradient over a fixed subset, and projections of real batches. It writes JSON at the path given by ORYON_NOISE_OUTPUT, or in the current directory if unset. The scale fluctuates between checkpoints in this run; the synthetic control does not replace these data.

[ ]Measure the cloud and noise scale on Fashion-MNISTLocal GPU
"""Medición breve: Fashion-MNIST real, dos tamaños de lote y gradiente completo de un subconjunto."""
import json
import math
import os
from pathlib import Path

import torch
from torch import nn
from torchvision.datasets import FashionMNIST

torch.set_num_threads(1)
torch.manual_seed(71)
torch.cuda.manual_seed_all(71)
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
torch.use_deterministic_algorithms(True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# Mismo contenido oficial y MD5 definidos por torchvision; el mirror original S3 usa HTTP.
FashionMNIST.mirrors = ['https://raw.githubusercontent.com/zalandoresearch/fashion-mnist/master/data/fashion/']
root = Path.home() / '.cache' / 'atlas-data'
dataset = FashionMNIST(root, train=True, download=True)
generator = torch.Generator().manual_seed(72)
train_ids = torch.randperm(len(dataset), generator=generator)[:8192]
images = dataset.data[train_ids].to(device=device, dtype=torch.float32).reshape(-1, 784) / 255
labels = dataset.targets[train_ids].to(device=device)
probe_n = 2048
probe_x, probe_y = images[:probe_n], labels[:probe_n]
model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10)).to(device)
parameters = tuple(model.parameters())
optimizer = torch.optim.SGD(parameters, lr=0.1)
train_rng = torch.Generator().manual_seed(73)
probe_rng = torch.Generator().manual_seed(74)
projection_rng = torch.Generator().manual_seed(75)
batch_small, batch_large, samples = 32, 256, 128
group = batch_large // batch_small

def gradient(x, y):
    loss = nn.functional.cross_entropy(model(x), y)
    pieces = torch.autograd.grad(loss, parameters)
    return loss.detach(), torch.cat([part.detach().reshape(-1) for part in pieces])

def measure(step):
    full_loss, full_grad = gradient(probe_x, probe_y)
    draws = torch.randint(probe_n, (samples, batch_small), generator=probe_rng)
    small = []
    for indexes in draws:
        _, g = gradient(probe_x[indexes.to(device)], probe_y[indexes.to(device)])
        small.append(g)
    gradients = torch.stack(small)
    groups = gradients.reshape(samples // group, group, -1).mean(dim=1)
    small_norm2 = gradients.square().sum(dim=1).mean()
    large_norm2 = groups.square().sum(dim=1).mean()
    trace_two = (small_norm2-large_norm2) / (1/batch_small - 1/batch_large)
    norm_two = (batch_large*large_norm2 - batch_small*small_norm2) / (batch_large-batch_small)
    full_norm2 = full_grad.square().sum()
    # Estima la traza de Σ a partir de la varianza muestral de los 128 gradientes de B=32.
    trace_sample = batch_small * (gradients-gradients.mean(dim=0)).square().sum() / (samples-1)
    axis1 = full_grad / full_grad.norm()
    axis2 = torch.randn(full_grad.shape, generator=projection_rng).to(device)
    axis2 -= (axis2 @ axis1) * axis1
    axis2 /= axis2.norm()
    cloud = torch.stack((gradients @ axis1, gradients @ axis2), dim=1).cpu().tolist()
    result = {
        'step': step, 'loss': float(full_loss), 'full_grad_norm2': float(full_norm2),
        'small_mean_norm2': float(small_norm2), 'large_mean_norm2': float(large_norm2),
        'trace_two_batch': float(trace_two), 'norm2_two_batch': float(norm_two),
        'noise_two_batch': float(trace_two / norm_two) if norm_two > 0 else None,
        'trace_sample': float(trace_sample), 'noise_full_reference': float(trace_sample / full_norm2),
        'full_projection': [float(full_grad @ axis1), float(full_grad @ axis2)], 'cloud': cloud,
    }
    print('paso', step, 'pérdida', result['loss'], 'B ruido 2 lotes', result['noise_two_batch'],
          'B ruido con gradiente completo', result['noise_full_reference'], flush=True)
    return result

checkpoints = {0, 50, 200, 600}
history = [measure(0)]
order = torch.randperm(len(images), generator=train_rng)
cursor = 0
for step in range(1, max(checkpoints)+1):
    if cursor+64 > len(order):
        order = torch.randperm(len(images), generator=train_rng)
        cursor = 0
    batch = order[cursor:cursor+64].to(device)
    cursor += 64
    optimizer.zero_grad(set_to_none=True)
    loss = nn.functional.cross_entropy(model(images[batch]), labels[batch])
    loss.backward()
    optimizer.step()
    if step in checkpoints: history.append(measure(step))

output = {
    'dataset': 'Fashion-MNIST train oficial; subconjunto de 8192 sin reemplazo',
    'source': 'https://github.com/zalandoresearch/fashion-mnist',
    'device': str(device), 'seed_model': 71, 'seed_subset': 72, 'seed_training': 73,
    'seed_probes': 74, 'seed_projection': 75, 'probe_population': probe_n,
    'architecture': [784, 128, 10], 'activation': 'ReLU', 'loss': 'entropía cruzada media',
    'training_batch': 64, 'optimizer': 'SGD sin momentum', 'learning_rate': 0.1,
    'small_batch': batch_small, 'large_batch': batch_large, 'small_samples': samples,
    'sampling': 'con reemplazo dentro de cada lote y entre lotes; lotes grandes agrupan ocho lotes pequeños independientes',
    'projection': 'eje 1: gradiente completo normalizado; eje 2: nuevo vector normal reproducible ortogonalizado en cada checkpoint',
    'history': history,
}
target = Path(os.environ.get('ORYON_NOISE_OUTPUT', 'fashion-noise.json'))
target.write_text(json.dumps(output, ensure_ascii=False, indent=2), encoding='utf-8')
print('resultado:', target, 'dispositivo:', device, flush=True)
del model, images, labels, parameters, optimizer, probe_x, probe_y, loss, batch
if device.type == 'cuda': torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The second cell compares batch sizes from 32 to 4096 with fixed rate and linear scaling with epoch-stepped warmup. It separates validation from training and records the first end-of-epoch evaluation to reach the target; it does not know the exact first crossing step. Duration includes complete training and validations, not time to target. The official test set is evaluated at the end of each nondivergent run; do not use it to select hyperparameters. A run that does not reach the target is marked accordingly, even if a batch processed more examples or loss became non-finite.

The additional equal-step comparison samples with replacement for both batches, while the epoch sweep uses permutations without replacement. Comparing the two protocols also changes sampling, so no single cause is isolated. The result is saved as JSON with policies, seeds, steps, examples, accuracy, and time. The full run includes several seeds; the small test uses one and does not settle inference about generalization. By default the full sweep runs; ORYON_VERIFY_SHORT=1 selects the small test used to verify the lesson.

[ ]Fashion-MNIST batch sweepLocal GPU
import json
import math
import os
import time
from pathlib import Path
import torch
from torch import nn
from torchvision.datasets import FashionMNIST

if not torch.cuda.is_available():
    raise RuntimeError('se necesita CUDA')
torch.set_num_threads(1)
torch.backends.cuda.matmul.allow_tf32 = False
device = torch.device('cuda')
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
FashionMNIST.mirrors = ['https://raw.githubusercontent.com/zalandoresearch/fashion-mnist/master/data/fashion/']
dataset = FashionMNIST(Path.home()/'.cache'/'atlas-data', train=True, download=True)
test_dataset = FashionMNIST(Path.home()/'.cache'/'atlas-data', train=False, download=True)
split_rng = torch.Generator().manual_seed(101)
indices = torch.randperm(len(dataset), generator=split_rng)
n_train, n_validation = (2048, 1024) if short else (50000, 10000)
train_ids = indices[:n_train]
validation_ids = indices[n_train:n_train+n_validation]
X_train = dataset.data[train_ids].to(device=device, dtype=torch.float32).reshape(-1, 784)/255
y_train = dataset.targets[train_ids].to(device=device)
X_val = dataset.data[validation_ids].to(device=device, dtype=torch.float32).reshape(-1, 784)/255
y_val = dataset.targets[validation_ids].to(device=device)
test_count = 1024 if short else len(test_dataset)
X_test = test_dataset.data[:test_count].to(device=device, dtype=torch.float32).reshape(-1, 784)/255
y_test = test_dataset.targets[:test_count].to(device=device)
batches = [32, 128, 512] if short else [32, 64, 128, 256, 512, 1024, 2048, 4096]
seeds = [7] if short else [7, 11]
epochs = 3 if short else 12
target = 0.70 if short else 0.85

def accuracy(model, inputs, targets):
    model.eval()
    correct = 0
    with torch.no_grad():
        for x, y in zip(inputs.split(512), targets.split(512)):
            correct += int((model(x).argmax(dim=1)==y).sum())
    return correct/len(targets)

def make_model(seed):
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    return nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10)).to(device)

def run(batch, policy, seed):
    model = make_model(seed)
    optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
    generator = torch.Generator().manual_seed(seed+100)
    steps, seen, first_hit, history = 0, 0, None, []
    torch.cuda.synchronize(device)
    start = time.perf_counter()
    for epoch in range(epochs):
        order = torch.randperm(n_train, generator=generator)
        model.train()
        for ids in order.split(batch):
            ids = ids.to(device)
            # El calentamiento es lineal durante cinco épocas, incluida la primera.
            lr = 0.1 if policy == 'fijo' else 0.1*(batch/32)*min(1, (epoch+1)/5)
            for group in optimizer.param_groups: group['lr'] = lr
            optimizer.zero_grad(set_to_none=True)
            loss = nn.functional.cross_entropy(model(X_train[ids]), y_train[ids])
            if not bool(torch.isfinite(loss)):
                print('pérdida no finita; entrenamiento interrumpido', batch, policy, seed, flush=True)
                return {'batch':batch, 'policy':policy, 'seed':seed, 'hit':first_hit, 'diverged':True, 'history':history}
            loss.backward()
            optimizer.step()
            steps += 1
            seen += len(ids)
        val_accuracy = accuracy(model, X_val, y_val)
        history.append({'epoch':epoch+1, 'steps':steps, 'examples':seen, 'accuracy':val_accuracy})
        if first_hit is None and val_accuracy >= target:
            first_hit = {'steps':steps, 'examples':seen, 'epoch':epoch+1}
    torch.cuda.synchronize(device)
    elapsed = time.perf_counter()-start
    test_accuracy = accuracy(model, X_test, y_test)
    result = {'batch':batch, 'policy':policy, 'seed':seed, 'hit':first_hit,
              'diverged':False, 'history':history, 'seconds':elapsed, 'final_test_accuracy':test_accuracy}
    print(json.dumps(result, ensure_ascii=False), flush=True)
    del model, optimizer, loss
    torch.cuda.empty_cache()
    return result

results = [run(batch, policy, seed) for seed in seeds
           for batch in batches for policy in ('fijo', 'lineal_warmup')]

def equal_steps(batch, seed, steps):
    model = make_model(seed)
    opt = torch.optim.SGD(model.parameters(), lr=0.1)
    generator = torch.Generator().manual_seed(seed+400)
    model.train()
    for _ in range(steps):
        ids = torch.randint(n_train, (batch,), generator=generator).to(device)
        opt.zero_grad(set_to_none=True)
        loss = nn.functional.cross_entropy(model(X_train[ids]), y_train[ids])
        loss.backward()
        opt.step()
    val_accuracy = accuracy(model, X_val, y_val)
    test_accuracy = accuracy(model, X_test, y_test)
    print('mismos pasos, muestreo con reemplazo:', batch, steps, batch*steps, val_accuracy, test_accuracy, flush=True)
    del model, opt, loss
    torch.cuda.empty_cache()
    return {'batch':batch, 'seed':seed, 'steps':steps, 'examples':batch*steps,
            'validation_accuracy':val_accuracy, 'final_test_accuracy':test_accuracy}

matched_steps = 16 if short else 2*math.ceil(n_train/128)
equal_results = [equal_steps(batch, seed, matched_steps) for seed in seeds
                 for batch in ((128, 512) if short else (128, 4096))]
output = {'dataset':'Fashion-MNIST oficial', 'train':n_train, 'validation':n_validation, 'test':test_count,
          'target':target, 'epochs':epochs, 'batch_sweep':results,
          'equal_steps_with_replacement':equal_results}
path = Path(os.environ.get('ORYON_BATCH_OUTPUT', 'fashion-batch-sweep.json'))
path.write_text(json.dumps(output, ensure_ascii=False, indent=2), encoding='utf-8')
print('salida guardada en', path, flush=True)
del X_train, y_train, X_val, y_val, X_test, y_test
torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Steps and examples to the observed targetLocal GPU
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 4))
shown = 0
for policy, marker in [('fijo', 'o'), ('lineal_warmup', 's')]:
    for row in results:
        hit = row['hit']
        if row['policy'] != policy or hit is None:
            continue
        ax.scatter(hit['examples'], hit['steps'], marker=marker, label=policy)
        ax.annotate('B='+str(row['batch']), (hit['examples'], hit['steps']), fontsize=7)
        shown += 1
if shown:
    handles, names = ax.get_legend_handles_labels()
    unique = dict(zip(names, handles))
    ax.legend(unique.values(), unique.keys())
    ax.set_xscale('log')
    ax.set_yscale('log')
else:
    ax.text(0.5, 0.5, 'Ningún caso alcanzó la meta', ha='center', va='center', transform=ax.transAxes)
ax.set_xlabel('Ejemplos procesados hasta el primer control que alcanza la meta')
ax.set_ylabel('Pasos hasta ese control')
ax.set_title('Solo se representan metas alcanzadas')
fig.tight_layout()
plt.show()
print('casos sin meta observada:', sum(row['hit'] is None for row in results), 'de', len(results))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofFinite-population correction
Prove: Prove the covariance of the mean gradient of a uniform sample without replacement.
0
Fix the parameters and N>1 gradients gᵢ. Define G as their mean and Σ as the population mean of (gᵢ−G)(gᵢ−G)ᵀ, with denominator N. Choose B distinct elements, with 1≤B≤N.

Step 1 of 3. If Iᵢ indicates that element i is in the batch, what is its expectation?

NumericSimple noise scale
At a fixed point tr(Σ)=120 and ||G||²=3 are measured. Calculate B_simple=tr(Σ)/||G||².
NumericOptimal step in a quadratic model
In a quadratic problem with H=hI, h>0, iid gradients and B_simple=40, use η_opt(B)/η_max=1/(1+B_simple/B). What is the ratio for B=40?
QuizChanging batch size and rate
You increase batch size from 64 to 1024, a factor of 16. What tuning plan is most defensible for SGD and AdamW?
CodeShuffle once per epoch
Implement minibatches(n, batch_size, epochs, seed, drop_last=False), a generator of index arrays. Assume n≥0, batch_size≥1, and epochs≥0. Create np.random.default_rng(seed) once, obtain a new permutation at the start of each epoch, and yield its blocks in order. Include the final incomplete block unless drop_last is True; do not repeat indices within an epoch.
import numpy as np

def minibatches(n, batch_size, epochs, seed, drop_last=False):
  pass
Shift+Enter to run
QuizWhere does the gap come from?
You compare B=128 and B=4096 for the same number of epochs at the same rate and observe worse test performance for B=4096. Which conclusion and next experiment are strongest?

The following cell checks the exercises’ numerical calculations and, for a small vector population, enumerates all samples of a given size to check the covariance formula. Enumeration is an independent check for that example, not a proof for every case.

[ ]Check scale and finite correctionBrowser
from itertools import combinations
population = np.array([[1., 2.], [2., -1.], [0., 3.], [-1., 0.]])
N, B = len(population), 2
G = population.mean(axis=0)
centered = population-G
Sigma = centered.T @ centered/N
means = np.array([population[list(ids)].mean(axis=0) for ids in combinations(range(N), B)])
observed = (means-G).T @ (means-G)/len(means)
predicted = Sigma/B*(N-B)/(N-1)
print('error máximo de covarianza:', np.max(np.abs(observed-predicted)))
simple = 120/3
print('escala simple y tasa relativa del ejemplo:', simple, 1/(1+simple/40))
Key idea

A minibatch estimates a direction at a fixed point; noise depends on sampling and batch size. The simple scale is useful but does not necessarily equal the curvature-weighted scale. To choose batch size and rate, measure steps, examples, time, memory, and validation under comparable protocols.