Mathematical foundations
Stochastic Gradients and Noisy Optimization
Understand gradient estimators, batch variance, sampling policies, update clocks, and the assumptions behind stochastic optimization claims.
By the end you can
- Interpret a mini-batch gradient as an estimator of a declared objective
- Compare sampling schemes and their effects on bias and variance
- Separate example, update, epoch, and compute clocks
- Audit clipping, weighting, accumulation, and distributed staleness as changes to the gradient estimator
Comparison
Uniform, stratified, weighted, and without-replacement sampling
The sampling rule changes both the estimand and the variance of the gradient estimate. Uniform sampling with replacement draws each example independently from the empirical distribution. The expectation analysis is then simple, it is natural for streaming, it allows repeated examples, and it may ignore rare strata. Shuffling without replacement — traversing a random permutation each epoch — is what most training loops actually do. The literature calls it random reshuffling, or RR. It often reduces duplicate draws. But it introduces dependence within an epoch, and the classical iid proofs do not apply directly to it.
That gap took decades to close, and the paper that closed it says so in its own abstract. Mishchenko and two co-authors, writing in 2020, set out the state of the literature they had inherited: “The convergence rate of RR has attracted substantial attention recently and, for strongly convex and smooth functions, it was shown to converge faster than SGD if 1) the stepsize is small, 2) the gradients are bounded, and 3) the number of epochs is large.” Their own analysis needs none of those three. It proves convergence without them, improves the condition-number dependence from κ² to κ in the strongly convex case, and shows that Random Reshuffling has a different type of variance from with-replacement SGD. They also give a result for Shuffle-Once, which shuffles the data only once at the start. The practical reading is blunt: the scheme in your data loader has its own theory, and it is not the with-replacement theory.
Stratified sampling controls representation from declared groups. It can reduce variance and it improves rare-group coverage. But it depends on the strata being correct, and it requires weighting if the intended objective is still the unstratified one.
Importance sampling goes further: sample from one distribution and reweight toward another. Katharopoulos and Fleuret open their 2018 abstract with the motivation — “Deep neural network training spends most of the computation on examples that are properly handled, and could be ignored.” Their scheme samples by an upper bound on the per-sample gradient norm. It also carries an estimator of how much variance the reweighting actually removes, so reweighted sampling is switched on only when it will pay. For a fixed wall-clock budget they measured training-loss reductions of up to an order of magnitude, and relative test-error improvements between 5% and 17%. The weights can still explode, support overlap is still required, and the effective sample size still changes. That is exactly why they measure the payoff before spending it.
Uniform with replacement
Each draw is independent from the empirical distribution.
- Simple expectation analysis
- Allows repeated examples
- Natural for streaming
- May ignore rare strata
Shuffle without replacement
Traverse a random permutation each epoch.
- Common in practice
- Introduces dependence within an epoch
- Often reduces duplicate draws
- Classical iid proofs do not apply directly
Stratified sampling
Control representation from declared groups.
- Can reduce variance
- Improves rare-group coverage
- Requires weighting for the intended objective
- Depends on correct strata
Importance sampling
Sample from one distribution and reweight toward another.
- Can target informative examples
- Weights may explode
- Requires support overlap
- Changes effective sample size
A mini-batch gradient is an estimate of a larger objective
Empirical risk is often a sum or average over many examples. Computing its exact gradient can be expensive. Training uses a random subset to estimate the direction. The estimate is noisy but can be unbiased under the sampling design. Its variance depends on batch size, data heterogeneity, weighting, and dependence among examples. Stochastic optimization therefore combines geometry with sampling theory. The update rule cannot be understood from the learning rate alone.
Everything this lesson claims about that estimator comes from a published run or a published paper. A 1951 result in the Annals of Mathematical Statistics. A lock-free training scheme from 2011. A differentially private optimizer whose authors state in their own text that their gradient estimate is not unbiased. A study of batch size across many workloads, in the Journal of Machine Learning Research. And a normalisation defect that shipped in a widely used trainer until October 2024.
Gradient noise is produced by a sampling scheme, not by magic.
Case
Robbins and Monro, 1951: solving an equation you can only sample
The framing is old. You want to find where an unknown function M crosses a level α — the value x = θ at which M(x) = α. Nothing in the setting permits an exact evaluation of M at any point. The only available act is to run an experiment at a level you choose and receive a noisy answer. That is the problem Robbins and Monro set in September 1951, in the Annals of Mathematical Statistics. Their method chooses the successive experiment levels so that the iterates xₙ tend to θ in probability.
That is the shape of a modern training loop, described in 1951 with no model, no dataset and no learning rate in it. An unknown function you may only sample. A sequence of levels you control. A convergence claim that holds in probability rather than pointwise. Every step-size schedule argued about since descends from that condition.
Analogy
Sample size buys precision, sample design buys the right population
Small polls estimate a population average. Each poll gives a noisy direction, and larger well-designed samples usually fluctuate less. A biased sample can be precise about the wrong population. Weighting may repair representation, but extreme weights can make the estimate unstable.
The polling profession has audited exactly this failure on itself, with numbers. Polling error in 2020 was the highest in 40 years for the national popular vote. Among polls conducted in the final two weeks, average error on the margin was 4.5 points nationally and 5.1 points at state level. Those figures come from the AAPOR task force on 2020 pre-election polling, chaired by Josh Clinton, which reported in July 2021 in a 106-page report.
The error also had a direction: “Among polls conducted in the last two weeks before the election, the average signed error on the vote margin was too favorable for Biden by 3.9 percentage points in the national polls and by 4.3 percentage points in statewide presidential polls.” The task force attributed at least part of that to nonresponse — a systematic difference between who did and did not answer. Not to sampling variance. A signed error of that size is not noise that averages away with more interviews. It is the wrong population, measured precisely.
A pollster measures a population that stays where it is. Model parameters move after every gradient estimate, so the target landscape is traversed rather than merely measured. The sampling lesson still applies. Who is in the batch decides which quantity the average is an estimate of, and no amount of B fixes a systematic exclusion.
A low-variance estimate of the wrong objective is still wrong.
Key idea
Gradient estimators can be biased on purpose
Clipping, truncated sequences, stale distributed gradients, adaptive sampling, and nonlinear reweighting can introduce bias. Bias is not automatically harmful. It can improve stability, or target a different objective on purpose.
The cleanest example is an optimizer whose authors state the bias in their own paper. DP-SGD clips every per-example gradient to a fixed L2 norm before averaging and adding noise. Martín Abadi and six co-authors published it in 2016. On MNIST they clipped each layer's gradient norm at 4 with lot size 600, and reported 90%, 95% and 97% test accuracy at (0.5, 10⁻⁵), (2, 10⁻⁵) and (8, 10⁻⁵)-differential privacy. The non-private baseline was 98.30%.
The paper does not hide what the clipping costs. Abadi and his co-authors write, in the section on tuning the clipping bound: “Limiting the gradient norm has two opposing effects: clipping destroys the unbiasedness of the gradient estimate, and if the clipping parameter is too small, the average clipped gradient may point in a very different direction from the true gradient.” The bias is bought deliberately, and its price is printed next to it: a little over eight points of accuracy at the strictest setting, a bit over one point at the loosest. NIST reached the same conclusion in March 2025. Special Publication 800-226 describes the mechanism as enforcing sensitivity rather than measuring it, and warns that the clipping parameters introduce bias.
Staleness is the same story at the systems layer. HOGWILD! runs stochastic gradient descent with no memory locking at all: processors write into shared parameters and may overwrite each other's updates. Its four authors said so in the 2011 abstract — “We present an update scheme called HOGWILD! which allows processors access to shared memory with the possibility of overwriting each other's work.” When the problem is sparse, that stale, raced scheme still attains a nearly optimal convergence rate, while outperforming lock-based schemes by an order of magnitude. The gradient actually applied is not the gradient any processor computed. The design is sound anyway, and it is still supported: PyTorch's multiprocessing guidance documents shared-memory tensor passing as the way to build asynchronous training of this kind.
The risk is unacknowledged bias. A team may believe it is optimizing the empirical risk while the pipeline actually follows a modified signal. Document the estimator implemented by the code, not only the ideal equation in the paper.
The executed gradient estimator is part of the objective definition.
Visual
Four clocks in a stochastic training run
Comparisons can become misleading when they use different notions of progress. The example clock counts how many training examples or tokens have been processed. The update clock counts how many optimizer steps have been applied. The compute clock counts wall time, energy, or accelerator work spent. The data-pass clock counts effective epochs completed. A run can be ahead on one and behind on the others, and a single headline number rarely says which.
The most consequential recent result in language modelling is a re-allocation between two of those clocks. Model size and training tokens should grow together, in step. Hoffmann and 21 co-authors established that in 2022, and their abstract carries the evidence in one sentence: “By training over 400 language models ranging from 70 million to over 16 billion parameters on 5 to 500 billion tokens, we find that for compute-optimal training, the model size and the number of training tokens should be scaled equally: for every doubling of model size the number of training tokens should also be doubled.”
Chinchilla is the demonstration. 70B parameters, four times more data, the same compute budget as the 280B-parameter Gopher — and a state-of-the-art 67.5% average on MMLU, more than a 7% improvement over Gopher. The compute clock was held fixed. The example clock was advanced and the parameter count cut by a factor of four, and the model got better. Anyone comparing those two runs by parameter count alone would have read the result backwards.
Example clock
How many training examples or tokens have been processed.
Update clock
How many optimizer steps have been applied.
Compute clock
How much wall time, energy, or accelerator work has been spent.
Data-pass clock
How many effective epochs have been completed.
Step-size conditions express a tradeoff
For classical stochastic approximation, decreasing step sizes balance carrying on exploring against eventually settling down. Foundational analyses state that balance as two conditions: a divergent sum of step sizes, and a convergent sum of squared step sizes. Those conditions descend from the choice Robbins and Monro made in 1951 — pick the successive experiment levels so the iterates tend to the root in probability. Modern deep learning often uses finite-horizon schedules that do not satisfy the asymptotic textbook conditions exactly. Their value is empirical and problem-dependent.
The correct conclusion is not that theory is irrelevant. It is that each guarantee belongs to a specific objective, noise model, and schedule. That is why Mishchenko and his co-authors had to name the small stepsize, the bounded gradients and the large number of epochs as assumptions before they could remove them.
Case
ImageNet in an hour, and the workload-by-workload limits measured after it
Two measured results bound the intuition, and both are quotable. The first is an hour on ImageNet in 2017. A Caffe2-based system, Goyal and eight co-authors reported, “trains ResNet-50 with a minibatch size of 8192 on 256 GPUs in one hour, while matching small minibatch accuracy”. The recipe was a linear scaling rule for the learning rate as a function of minibatch size, plus a warmup phase. They report “no loss of accuracy when training with large minibatch sizes up to 8192 images”. A minibatch of 8192 spread across 256 GPUs is 32 images per device. The sampling design, not the optimizer name, is what made the hour possible.
The second measured the same tradeoff systematically. How much does batch size change the number of steps needed to reach a goal out-of-sample error? Shallue and five co-authors answered that across many workloads, in the Journal of Machine Learning Research in 2019. Two findings from that abstract are worth carrying verbatim. They “find extremely large variation between workloads”. And they “find no evidence that larger batch sizes degrade out-of-sample performance”. Both matter, in opposite directions. The second removes a folk objection to large batches. The first says that a batch size which paid off on someone else's workload is not evidence about yours. One hour on ImageNet was a result about one model, one dataset and one tuned schedule. It is not a scaling law you inherit.
Steps
Audit a stochastic update
Two training runs can behave differently despite using the same optimizer name. Work through six things when they do. First, define the full objective: state the population or empirical quantity being estimated. Second, describe the sampling: record replacement, shuffling, grouping, and stratification. Third, record the weights, including class weights, importance ratios, and masks. Fourth, measure gradient statistics: norms, variance, outliers, and group differences. Fifth, align the clocks, comparing examples, updates, compute, and epochs separately. Sixth, test estimator changes by ablating clipping, accumulation, staleness, and sampling policy.
The sixth step is not hypothetical. The largest recent example was a normalisation bug in a mainstream trainer. In October 2024 Hugging Face confirmed that gradient accumulation in its Trainer was not mathematically equivalent to full-batch training for token-level tasks. The per-micro-batch cross-entropy losses were averaged, rather than summed and divided by the total non-padding tokens. The maintainers' own account opens with the symptom: “Gradient accumulation is supposed to be mathematically equivalent to full batch training; however, losses did not match between training runs where the setting was toggled on and off.”
The timeline is four days long. Benjamin Marie reported the issue first. Unsloth shared it on 15 October, the Hugging Face blog described it on 16 October, and transformers PR #34191, opened by ArthurZucker, was merged on 17 October. The fix changed reduction="mean" to reduction="sum" divided by the token count.
The size of the discrepancy is the reason step four exists. Marie measured loss gaps of roughly 0.2–0.3 between batch size 32 without accumulation and batch size 1 with 32 accumulation steps, at 2048-token sequences. With high sequence-length diversity the gap widened to 0.45–0.70. After the fix it fell to about 0.0004. Nobody had changed the objective on purpose. A configuration flag that was supposed to be a memory-management detail was quietly changing the quantity being minimised, and it took a comparison of two runs that should have matched to see it.
1. Define the full objective
State the population or empirical quantity being estimated.
2. Describe sampling
Record replacement, shuffling, grouping, and stratification.
3. Record weights
Include class weights, importance ratios, and masks.
4. Measure gradient statistics
Track norms, variance, outliers, and group differences.
5. Align clocks
Compare examples, updates, compute, and epochs separately.
6. Test estimator changes
Ablate clipping, accumulation, staleness, and sampling policy.
Example
Why doubling batch size does not halve every uncertainty
Suppose independent per-example gradients have variance σ² in one direction.
- Ideal average: A batch of B independent examples has variance σ²/B in that direction — and the halving is a consequence of independence, not of the batch size.
- Dependence: Similar or grouped examples reduce the effective number of independent contributions. A shuffled epoch is not a sequence of independent draws, which is why Mishchenko and his co-authors had to give Random Reshuffling its own analysis rather than borrow the with-replacement one.
- Heterogeneity: Rare high-magnitude gradients can dominate the average — the same asymmetry Katharopoulos and Fleuret exploit by sampling on an upper bound of the per-sample gradient norm.
- Weighting: Class or importance weights alter both expectation and variance, and clipping alters the expectation deliberately: DP-SGD's per-layer bound of 4 is chosen knowing that it destroys unbiasedness.
- System effect: A larger batch may permit fewer parameter updates under a fixed compute budget. Shallue and five co-authors measured that steps-to-goal-error relationship across many workloads and found extremely large variation between them.
Key takeaways
- Mini-batch gradients are random estimators defined by a sampling scheme; Robbins and Monro set the problem in September 1951 as finding x = θ of M(x) = α when M can only be observed through noisy experiments.
- Variance reduction depends on independence, weighting, and data heterogeneity. The σ²/B ideal assumes independent draws, and a shuffled epoch is not one — Mishchenko and his co-authors needed a separate analysis to drop the small-stepsize, bounded-gradient and many-epochs assumptions and move from κ² to κ.
- Stratification and importance sampling change both expectation and effective sample size. Katharopoulos and Fleuret gained relative test-error improvements between 5% and 17% only because their scheme estimates the variance reduction first and reweights sampling only when it pays.
- Epochs, updates, examples, and compute are different progress measures: at a fixed compute budget, Chinchilla's 70B parameters trained on four times more data beat the 280B-parameter Gopher, reaching 67.5% on MMLU.
- Practical stabilizers introduce deliberate bias. Abadi and his six co-authors state that clipping destroys the unbiasedness of the gradient estimate, and NIST Special Publication 800-226 warns of the same thing in March 2025.
- Document the gradient estimator the system actually executes: Hugging Face's Trainer averaged per-micro-batch losses instead of normalising by total non-padding tokens, and the 0.2–0.3 loss gap that caused survived until PR #34191 was merged on 17 October 2024.