Stochastic Gradient Descent
Imagine training a model on a billion-example dataset. A single pass over the data to compute one exact gradient would take hours. Waiting hours between each parameter update is impossibly slow. Yet the alternative — updating on tiny slices of data — seems reckless. Each slice gives only a noisy hint about where to move. Stochastic gradient descent (SGD) resolves this tension by embracing the noise. It trades a perfectly accurate gradient for a cheap, unbiased estimate of it. It takes many more, smaller steps instead of a few large, expensive ones. This tradeoff is the computational backbone of modern machine learning. Every large neural network — from image classifiers to large language models — is trained with some variant of SGD. Full-batch Gradient Descent is simply infeasible at scale. Recomputing a gradient over millions or billions of examples for every single update would make training take years. SGD converts an intractable per-step cost into a tractable one. The price is a noisier trajectory. This article explains precisely why that trade is worthwhile. The big picture is this: optimization in machine learning is not really about finding the minimum of a fixed, known function. It is about finding the minimum of an expected loss using only a stream of noisy samples from it. SGD is the algorithm born from taking this statistical view seriously. At every step, it replaces the true gradient of the expected loss with an unbiased estimate. This estimate is computed from one example or a small mini-batch. It relies on the Learning Rates and Convergence machinery to guarantee something important. Despite the noise, the average behavior still converges. This article builds SGD from first principles. It covers the exact algorithm and its mini-batch generalization. It gives a precise accounting of its time and space complexity versus full-batch gradient descent. It offers a convergence argument that explains why noisy updates still work. It includes a worked numerical trace showing the noise in action. It also covers the common pitfalls that trip up practitioners. It closes by pointing toward Momentum Methods, the natural next refinement.
- SGD replaces the exact gradient of the full dataset with a cheap, unbiased estimate from one example or a mini-batch.
- Each step is far cheaper than full-batch gradient descent, so far more steps can be taken per unit of wall-clock time.
- The per-step estimate is noisy but unbiased in expectation, which is what makes convergence provable despite randomness.
- Convergence requires a shrinking or well-tuned learning rate schedule to tame the variance of the noise.
- Mini-batching (rather than pure single-example SGD) balances gradient noise against hardware parallelism.
- SGD's noise is not purely a cost — it can help escape saddle points and sharp minima, aiding generalization.
SGD trades the exact but expensive gradient of the whole dataset for a cheap, unbiased, noisy estimate, taking many more steps per second than full-batch descent.
The idea
Suppose the goal is to minimize an empirical risk defined as an average loss over a training set of examples, ``` L(θ) = (1/n) Σ_{i=1}^{n} ℓ(θ; x_i, y_i) ``` Full-batch gradient descent computes the exact gradient at every step, which requires touching all examples. Stochastic gradient descent instead draws one example (or a small random subset) at iteration , and updates using only that example's gradient, ``` θ_{t+1} = θ_t − η_t ∇ℓ(θ_t; x_{i_t}, y_{i_t}) ``` This single-example gradient is a random variable whose expectation, over the random choice of , equals the true gradient — it is an unbiased estimator. That single algebraic fact is the entire justification for the method: on average, the noisy step points in the same direction as the expensive exact step, so accumulating many noisy steps behaves like accumulating many exact steps, provided the noise is controlled.
Mini-batch SGD generalizes this by averaging the gradient over a small batch of size (commonly 32–4096) rather than a single example, ``` θ_{t+1} = θ_t − η_t · (1/b) Σ_{i ∈ B_t} ∇ℓ(θ_t; x_i, y_i) ``` This is still an unbiased estimator of , but its variance is reduced by a factor of roughly compared to single-example SGD (for i.i.d. sampling with replacement), since averaging independent noisy estimates shrinks variance linearly in . Mini-batching is the practical default because it exploits vectorized hardware (GPUs/TPUs) that computes a batch of gradients almost as fast as a single one, while still updating far more frequently than full-batch descent. The key conceptual shift from plain gradient descent is this: SGD does not treat as a fixed deterministic function to be minimized exactly at every step. It treats optimization as a stochastic approximation problem — estimating the root of from a stream of noisy gradient observations — a framework formalized by the Robbins–Monro algorithm long before it became the default training method for neural networks.
How it works
The mechanics of SGD are simple, but the two design choices that matter most are (1) how batches are sampled and (2) how the learning rate is scheduled over time. A well-posed implementation shuffles the dataset once per epoch and processes it in sequential mini-batches — this approximates i.i.d. sampling without the overhead of true random sampling with replacement. ``` PSEUDOCODE: Mini-batch Stochastic Gradient Descent Input: dataset D = {(x_1,y_1), ..., (x_n,y_n)} initial parameters θ_0 learning rate schedule η_t batch size b number of epochs E loss function ℓ(θ; x, y) Output: trained parameters θ θ ← θ_0 t ← 0 for epoch = 1 to E: shuffle D uniformly at random # fresh random order each epoch partition D into batches B_1, ..., B_m of size b # m = ceil(n / b) for each batch B_k in the shuffled partition: g ← (1 / |B_k|) Σ_{(x_i,y_i) in B_k} ∇_θ ℓ(θ; x_i, y_i) # mini-batch gradient θ ← θ − η_t g # parameter update t ← t + 1 end for end for return θ ``` Two invariants are worth naming explicitly: 1. Unbiasedness invariant: at every step, , where the expectation is over the randomness of the batch draw. This holds because each example is drawn from (an approximation of) the uniform distribution over the dataset, and the average of per-example gradients is itself the empirical-risk gradient. 2. Diminishing-influence invariant: as training progresses, the learning rate is chosen (or decayed) so that the cumulative noise injected into the trajectory does not prevent convergence, while still allowing enough movement to make progress. This is formalized by the Robbins–Monro step-size conditions discussed below. The diagram below shows the full pipeline: how a large dataset is sliced into batches, how each batch produces a noisy gradient estimate, and how that estimate perturbs the parameter update relative to the true full-batch direction.
The lower half of the figure captures the qualitative difference from full-batch descent: the green path is smooth because it always follows the exact gradient, while the red path zig-zags because each step follows a noisy estimate — yet both paths reach the same neighborhood of the minimum, because the noise averages out over many steps.
Complexity & correctness
Per-step time complexity. If computing the gradient of a single example costs (where is the number of parameters, as in a linear model or the backward pass of a network with weights), then:
- Full-batch gradient descent costs per update, since it touches all examples.
- Mini-batch SGD with batch size costs per update.
- Single-example SGD () costs per update.
This is the entire computational argument for SGD's scalability: to complete one epoch (one full pass over the data), full-batch GD performs a single update costing , while mini-batch SGD performs updates each costing , for the same total work per epoch — but it makes parameter updates instead of just one. Since progress toward the minimum is roughly proportional to the number of updates (not the amount of data examined per update, up to noise), SGD converges in far less wall-clock time even though the total floating-point operations per epoch are comparable.
Space complexity. Full-batch GD needs or at least auxiliary memory if gradients across the whole dataset must be aggregated per step (or streamed with working memory if implemented carefully), whereas mini-batch SGD only ever needs memory for the current batch's activations and gradients. Since typically, SGD has a dramatically smaller memory footprint, which is often the deciding factor for training on GPUs with limited memory.
Correctness — why noisy steps still converge. The classical convergence guarantee for SGD on a convex, -smooth objective with bounded gradient variance rests on the Robbins–Monro conditions on the learning rate schedule: ``` Σ_t η_t = ∞ (steps must be large enough, cumulatively, to reach any point) Σ_t η_t^2 < ∞ (steps must shrink fast enough to damp the noise) ``` A schedule like or satisfies these. The proof sketch is a stochastic Lyapunov / supermartingale argument: define , the expected squared distance to a minimizer . Using the update rule and unbiasedness, ``` D_{t+1} = D_t − 2η_t E[(θ_t − θ)ᵀ ∇L(θ_t)] + η_t² E‖g_t‖² ``` Convexity gives , and bounded variance/gradient norm gives for constants . So: ``` D_{t+1} ≤ D_t − 2η_t (L(θ_t) − L(θ)) + η_t² (σ² + G²) ``` Summing over and using bounds the accumulated noise term, while ensures the negative (progress) term can drive to zero along a subsequence. Formally this yields convergence in expectation of the running average of iterates, for convex, non-smooth objectives with a suitably tuned schedule — slower than the rate of full-batch gradient descent on the same class of problems, but each SGD step is times cheaper, so it reaches a given accuracy in less total work whenever is large.
The honest tradeoff. SGD's per-iteration convergence rate is worse than full-batch GD's — noisy gradients simply cannot drive the error down as fast, iteration for iteration, as exact gradients can. What makes SGD win in practice is that each of its iterations is vastly cheaper, so more iterations fit in the same wall-clock budget; the crossover point favors SGD whenever is large, which is essentially always true in modern machine learning. A second, more subtle correctness point: mini-batch SGD does not converge to the exact minimizer with a constant learning rate — it converges to a stationary distribution of iterates fluctuating in a neighborhood of size around , unless the rate is decayed to zero. Practitioners often accept this residual noise floor deliberately, since it also has a regularizing effect that improves generalization.
Worked example
Consider a toy 1-D least-squares problem to make the noise concrete. Suppose the true model is , and the training set has points:
| true label from | ||
|---|---|---|
| 1 | 2.1 | ~2 |
| 2 | 3.8 | ~4 |
| 3 | 6.3 | ~6 |
| 4 | 7.7 | ~8 |
The model is , and the per-example squared loss is , with per-example gradient . The full-batch gradient at is the average over all four points: ``` ∇L(θ) = (1/4) Σ_i 2 x_i (θ x_i − y_i) ``` Start at , learning rate (constant, for clarity of the trace).
Full-batch step at : compute each per-example gradient.
| 1 | 1 | 2.1 | ||
| 2 | 2 | 3.8 | ||
| 3 | 3 | 6.3 | ||
| 4 | 4 | 7.7 |
Full-batch gradient: . Full-batch update: .
Single-example SGD, same starting point , drawing examples in order (one epoch, mimicking a shuffle):
| step | example | gradient | update | new |
|---|---|---|---|---|
| 1 | 2 | (computed at , matches table above) | ||
| 2 | 4 | |||
| 3 | 1 | |||
| 4 | 3 |
After one epoch, single-example SGD lands at , compared to the full-batch method's single step to — SGD made four updates in the time full-batch made one, and moved further toward the true value despite each individual step being noisier and based on incomplete information. This illustrates the core tradeoff numerically: each SGD step is a worse estimate of the true gradient direction than the full-batch gradient, but because four cheap steps fit in the budget of one expensive step, SGD's net progress per unit of computation is larger. Continuing for more epochs with a decaying learning rate would let settle near , while the noise from single-example estimates would keep it oscillating slightly if the rate stayed constant — exactly the noise-floor phenomenon predicted by the convergence analysis above.
Common pitfalls & traps
| Pitfall | Why it happens | Consequence |
|---|---|---|
| Using a constant, too-large learning rate | Ignoring the requirement for exact convergence | Loss oscillates or diverges instead of settling near the minimum |
| Not shuffling data (or shuffling only once, ever) | Treating a fixed order as if it were i.i.d. sampling | Correlated batches bias early gradient estimates, slowing/misleading convergence |
| Batch size too small on parallel hardware | Believing smaller batches are always "more stochastic and better" | Underutilizes GPU parallelism; wall-clock time per epoch increases despite lower FLOPs |
| Batch size too large without adjusting learning rate | Assuming batch size only affects speed, not the effective step size | Loss plateaus or generalizes worse; large-batch training needs learning-rate scaling |
| Comparing SGD to GD only in "iterations," not wall-clock/epochs | Confusing convergence rate per step with convergence rate per unit compute | Wrongly concluding full-batch GD is "just better" because it needs fewer steps |
| Forgetting the noise floor with constant learning rate | Assuming SGD converges to the exact minimizer like GD does | Parameters fluctuate near indefinitely instead of settling exactly |
Pioneers & history
The theoretical seed of SGD lies in statistics and stochastic approximation, decades before its widespread use in deep learning. Herbert Robbins and Sutton Monro formalized the general problem of finding a root of a function known only through noisy observations, giving the first rigorous convergence proof for a Robbins–Monro-type recursive stochastic algorithm — the mathematical ancestor of every modern SGD convergence proof.
Origins · 1 minHerbert Robbins and how this was discovered
The Widrow–Hoff least-mean-squares (LMS) rule of 1960 is arguably the first widely used single-example stochastic gradient method in engineering practice, applied to adaptive signal filters long before "machine learning" was a common phrase. When backpropagation was popularized in the 1980s, mini-batch and online (single-example) updates were the natural computational fit for the hardware of the era, since full-batch computation over large datasets was infeasible. The 2012 AlexNet result cemented mini-batch SGD (with added momentum, foreshadowing Momentum Methods) as the default training procedure for deep networks, a status it has retained even as more sophisticated adaptive-rate variants have emerged.
Where this matters
Mini-batch SGD (and its refinements) is the training engine behind essentially every large-scale machine learning system in production. Deep learning frameworks such as PyTorch and TensorFlow implement SGD as a first-class optimizer primitive, and virtually every large neural network — convolutional networks for vision, transformers for language, recommendation systems at web scale — is trained by some descendant of the mini-batch SGD loop. Search-ranking and ad-click prediction models, trained on data streams too large to ever fit in memory, use online variants of SGD that treat the entire training process as one continuous stochastic optimization. Federated learning systems, which train models across many devices without centralizing data, are built on local mini-batch SGD updates aggregated across a network, since the fundamentally cheap, streaming nature of SGD makes it well suited to decentralized and privacy-sensitive settings. Understanding SGD's cost-noise tradeoff is also the prerequisite for understanding why practitioners add momentum, adaptive learning rates (as in Adam or RMSProp), and learning rate warmup/decay schedules — all of these techniques exist specifically to manage the noise that plain SGD introduces, which is exactly the direction that Momentum Methods develops further.
Ask the tutor: How does adding momentum change the noisy zig-zag trajectory of SGD, and why does it accelerate convergence in directions of consistent gradient sign?
Is SGD guaranteed to converge to the global minimum?
Only under strong assumptions. For convex objectives (like linear or logistic regression with convex regularizers), SGD with an appropriately decaying learning rate provably converges in expectation to the global minimum, at a rate around for general convex losses. For non-convex objectives, like deep neural network losses, SGD is only guaranteed to converge to a stationary point (where the gradient is near zero), which could be a local minimum, saddle point, or in practice a "good enough" region of low loss. Empirically, SGD's noise often helps it escape sharp local minima and saddle points, which is one reason it works surprisingly well on non-convex deep learning objectives despite lacking global guarantees there.
How does mini-batch size interact with the learning rate?
Larger batches produce lower-variance gradient estimates, which mathematically permits a proportionally larger learning rate without destabilizing training — this is the basis of "linear scaling rules" used when scaling batch size for distributed training. If the learning rate is not increased alongside a larger batch size, training can become needlessly slow because each of the (now fewer) updates makes a smaller relative move. Conversely, increasing batch size without adjusting the learning rate can cause the effective per-epoch progress to stall, since gradient noise (which sometimes helps escape bad regions) is also reduced. Tuning batch size and learning rate jointly is one of the most consequential decisions in large-scale training.
What is the difference between an "epoch" and an "iteration" in SGD?
An iteration (or step) is a single parameter update using one mini-batch's gradient estimate. An epoch is one complete pass over the entire training dataset, consisting of iterations if the batch size is and the dataset has examples. Full-batch gradient descent performs exactly one update per epoch, whereas mini-batch SGD performs many updates per epoch — this is precisely the mechanism by which SGD achieves faster wall-clock convergence, since it updates parameters far more frequently for the same amount of data processed.
Does using a smaller batch size always make training faster?
Not necessarily in wall-clock time, even though it reduces the FLOPs per update. Modern GPUs and TPUs are throughput-oriented: computing a gradient over a batch of, say, 128 examples can take barely longer than computing it over 1 example, because the hardware parallelizes across the batch dimension. If the batch size is too small, hardware utilization drops and the wall-clock time per epoch can actually increase, even though the FLOP count per update went down. Choosing batch size is therefore a hardware-aware tradeoff, not purely a statistical one.
Why does SGD sometimes generalize better than full-batch gradient descent, despite being noisier?
Empirically, the noise injected by mini-batch sampling acts as an implicit regularizer, discouraging the optimizer from settling into sharp, narrow minima of the training loss that tend to generalize poorly to new data. Full-batch gradient descent, following the exact gradient at every step, has no such noise and can converge precisely into a sharp minimum that overfits the training set. This is not a formal guarantee — it is an empirical and partially theoretical observation, an active area of research — but it is a widely cited practical reason that SGD-family optimizers are preferred even when full-batch computation is feasible.
How does SGD relate to online learning?
Online learning processes one example at a time as it arrives, updating the model immediately, without ever assuming a fixed, finite dataset — this is structurally identical to single-example SGD. In fact, single-example SGD is often called "online SGD" precisely because of this correspondence: the same unbiased-gradient, noisy-update mechanism underlies both streaming/online training and standard offline SGD on a shuffled finite dataset. The theoretical guarantees developed for online convex optimization (regret bounds) and for stochastic approximation (Robbins–Monro convergence) are close cousins, both analyzing the same core algorithmic idea.
What comes after plain SGD if it has this much noise?
Plain SGD's noisy, zig-zagging trajectory motivated a family of refinements that smooth or adapt the update direction without abandoning the cheap stochastic-gradient framework. Momentum methods accumulate an exponentially weighted running average of past gradients, damping oscillations in high-curvature directions while accelerating progress in consistent directions — this is the natural next topic once plain SGD is understood. Adaptive methods like Adam or RMSProp further rescale each parameter's step size based on the historical magnitude of its gradients, addressing the fact that a single global learning rate is often ill-suited to all parameters simultaneously.