SGD: follow the sample, then take the expectation
随机梯度下降
Run sampled updates and exact short-path averages to separate unbiased gradients from residual noise.
sgdA noisy step can still target the right objective
Suppose a device repeatedly estimates a typical sensor value from individual observations. Reading the entire historical dataset before every update may be unnecessary. A randomly selected observation supplies a cheap direction, although it need not improve the full objective at that step.
D2L Section 12.4.1 defines uniform-sample gradients and their unbiasedness. The fixed PyTorch 2.8 SGD interface specifies parameter updates; selecting observations is the caller’s responsibility. An optimizer named SGD is not itself evidence that the training loop samples randomly.
Condition the expectation on the current iterate
For N differentiable per-example losses, let Iₜ be a fresh uniform index, independent of earlier draws given the current state:
The equality follows by averaging N gradients at the same θₜ. It does not say that every sampled gradient points downhill for F. An epoch that shuffles once and visits each example without replacement has a different conditional sampling distribution after some examples have been used; its analysis should not silently reuse the fresh-draw identity.
For the scalar loss ℓᵢ(θ)=(θ−yᵢ)²/2 and targets (−1,1,3), the target mean is one and variance σ²=8/3. Expanding the full objective and using a constant learning rate gives:
Yₜ is the target selected at step t; θ₀ is fixed. The mean iterate approaches the minimizer for a suitable rate, but a single trajectory continues to feel fresh noise. Independence of Yₜ and previous draws gives a variance recurrence: multiply the old variance by (1−η)² and add η²σ². Summing the geometric series yields, for a constant rate strictly between zero and two:
The second statement uses a different schedule: the first rate is one, and induction turns the iterate into the sample mean. Its variance is σ²/T for independent draws. Our implementation restricts its constant rate to at most one, a narrower safe teaching contract. At η=1/2 the limiting variance is 8/9 and limiting expected excess loss is 4/9. Approaching the optimum in expectation is not the same as vanishing mean-square error.
Biased sampling needs a matching correction
At θ=0 the three example gradients are (1,−1,−3). Uniform averaging gives −1. Sampling them with probabilities (1/2,1/4,1/4) instead gives −1/2. To keep the original uniform objective, divide the selected gradient by N times its positive sampling probability. The expectation then returns to −1, at a potentially different variance. Simply changing the sampler changes the objective unless the update accounts for it.
Replay one run and enumerate all short runs
The complete Python 3.12 standard-library program performs actual sampling with replacement and logs every sampled index. It uses exact fractions for the updates. A second calculation enumerates all 3⁵ five-step index sequences; equal weighting is justified by independent uniform draws, not by an approximation from one favorable seed.
from fractions import Fraction as F
from itertools import product
from random import Random
def objective(theta,targets):
if not targets:raise ValueError('targets required')
return sum((theta-F(y))**2 for y in targets)/(2*len(targets))
def replay(targets,indices,theta=F(0),rate=F(1,2),schedule='constant'):
y=tuple(F(v) for v in targets);theta=F(theta);rate=F(rate)
if not 1<=len(y)<=16 or any(abs(v)>100 for v in y):raise ValueError('one to 16 bounded targets required')
if schedule not in ('constant','mean') or not 0<rate<=1:raise ValueError('supported schedule and rate in (0,1] required')
ids=tuple(indices)
if len(ids)>64 or any(type(i) is not int or not 0<=i<len(y) for i in ids):raise ValueError('up to 64 valid integer sample indices required')
history=[theta]
for t,i in enumerate(ids,1):
eta=rate if schedule=='constant' else F(1,t)
theta-=eta*(theta-y[i]);history.append(theta)
return history
def sampled(targets,steps,seed=7,schedule='constant'):
if type(steps) is not int or not 0<=steps<=64 or not targets:raise ValueError('bounded step count and nonempty targets required')
rng=Random(seed);ids=[rng.randrange(len(targets)) for _ in range(steps)]
return ids,replay(targets,ids,schedule=schedule)
if __name__=='__main__':
y=(-1,1,3);ids,history=sampled(y,8)
print('sample indices:',ids)
print('constant-rate parameters:',[str(v) for v in history])
print('full objective after each update:',[str(objective(v,y)) for v in history])
for schedule in ('constant','mean'):
endings=[replay(y,ids,schedule=schedule)[-1] for ids in product(range(3),repeat=5)]
mu=sum(endings)/len(endings);variance=sum((v-mu)**2 for v in endings)/len(endings)
print(schedule,'five-step exact mean / variance:',str(mu),str(variance))
Actual output:
sample indices: [1, 0, 1, 2, 0, 0, 2, 0]
constant-rate parameters: ['0', '1/2', '-1/4', '3/8', '27/16', '11/32', '-21/64', '171/128', '43/256']
full objective after each update: ['11/6', '35/24', '203/96', '587/384', '2411/1536', '9515/6144', '54443/24576', '136619/98304', '660395/393216']
constant five-step exact mean / variance: 31/32 341/384
mean five-step exact mean / variance: 1 8/15
The full objective sometimes rises even when the selected sample’s error falls. After five updates, the constant-rate mean is 31/32, whereas the decreasing-rate mean is one. Their variances differ, as predicted. The enumeration is a check on this small quadratic, not a neural-network benchmark.
For a model with d parameters and a dense per-example gradient, an update typically costs O(d) plus the example’s forward/backward computation. It avoids the factor N of a full pass; it is not constant cost in model size. Ordinary SGD keeps O(d) parameter/gradient state. Our stored history and exponential enumeration are optional teaching diagnostics.
A schedule needs assumptions, not a lucky seed
The sample-mean identity is special to this quadratic and the rate 1/(t+1). It is not a universal neural-network schedule. General convergence statements require conditions on smoothness, convexity or the stationarity criterion, gradient noise and step sizes. Nonconvex training does not inherit a global optimum guarantee from an unbiased gradient.
Drawing rare examples more often, sampling by class, weighting losses and averaging over batches are separate choices that should agree with the target objective. Keep the sampling log or seed, reduction convention and optimizer settings with an experiment. For exact continuation, also preserve the sampler’s state; storing only θ does not reproduce later random draws.
This chapter uses a fixed finite dataset and no momentum, regularization, clipping or adaptive scaling. Those additions change the recurrence. A zero gradient on one sampled example is not a stopping certificate for the full dataset, and one trajectory’s final loss is not an estimate of a method’s typical performance.
Follow the sampler and the expectation
- What is the full gradient at θ=0 for the three targets?
Answer 1: −1, the average of 1,−1,−3.
- Does η=1/2 make the limiting parameter variance zero?
Answer 2: No. It approaches 8/9 under the stated independent sampling model.
- What does the decreasing-rate iterate equal after T samples?
Answer 3: Their arithmetic mean, because the first rate is one and subsequent rates are reciprocals of the sample count.
- Does
optimizer.step()choose the next training example?
Answer 4: Not in the cited SGD API. The data-loading and loss computation code determines the samples.
Separate stochastic gradients from optimizer state
The cited teaching section supplies the finite-sum sampling definition; the fixed API supplies an implementation contract. Our exact noisy mean, biased-sampling correction and five-step enumeration are original. Continue with minibatches, momentum and Nesterov acceleration.
Make a prediction, then check
Does an unbiased sampled gradient guarantee that every update lowers the full loss?
Learning objectives
- State the conditional sampling assumption.
- Distinguish mean convergence from variance reduction.
Prerequisites & connections
Explore related knowledge →References
- Stochastic Gradient Descent — Dive into Deep Learning 1.0.3
D2L authors · 2023 - SGD — 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. Bidirectional alignment/Jacobians, injected network faults, exhaustive learning curves and stochastic paths, exact momentum trajectories, Nesterov reparameterization and a smooth accelerated bound instance are checked. Bidirectional RNN/debugging use NumPy1.26.4; the other four 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:
- Stochastic Gradient Descent — Dive into Deep Learning 1.0.3 · Section12.4.1 Eqs12.4.1–12.4.4: finite-sum objective, uniform sampled update and unbiased gradient.
- SGD — PyTorch 2.8 · SGD main algorithm and parameters: update consumes the computed gradient, optional momentum/decay; sampling is external.
Related topics