Optimisers — SGD, RMSProp & Adam
What Is an Optimiser?
Every time a neural network learns, an optimiser is doing the heavy lifting in the background — quietly nudging millions of weights, one tiny step at a time, towards a configuration that makes the model better.
An optimiser is the algorithm that updates a neural network’s parameters by following the gradient of the loss function — turning raw error signals into meaningful improvements in model behaviour.— utivra.com · AI Education Series
Training a neural network is essentially a giant search problem. Out of trillions of possible parameter combinations, the optimiser’s job is to find the one that produces the lowest error on the data. It does this by repeatedly computing the gradient (the direction of steepest improvement) and taking small steps downhill across the so-called loss landscape.
Imagine you’re blindfolded in a giant valley and trying to reach the lowest point. You feel the slope under your feet and take a small step in the downhill direction. Then you feel again, step again, and again. After thousands of careful steps, you reach the bottom. An optimiser does this exact thing — but in a mathematical landscape with millions of dimensions.
The Loss Landscape
Picture every possible combination of model weights as a point on a map. The “height” at each point is how badly the model performs on the training data. Training the network is exactly like rolling a ball downhill on this map — the optimiser steers from a randomly chosen starting position toward a low valley where the error is small. Some valleys are deeper than others (global vs. local minima); some terrain is flat (saddle points); some is steep and narrow (ravines). The optimiser’s design determines how well it copes with each.
Gradient Descent: The Core Idea
All three optimisers in this guide are descendants of one foundational technique: gradient descent. The word “gradient” simply means “slope.” When you stand on a hill and want to walk downhill, you naturally move in the direction that goes down most steeply. Gradient descent does exactly this — but in a mathematical space with potentially millions of dimensions.
At every training step, the algorithm measures the steepness of the error surface at the current position and takes a small step in the downhill direction. The size of that step is controlled by a setting called the learning rate. Too large a learning rate and you overshoot the valley; too small and it takes forever to arrive.
In its simplest form: new_weight = old_weight − (learning_rate × gradient). The gradient tells us which direction is “uphill” for the loss, so subtracting it moves us downhill. This tiny operation, repeated billions of times across millions of parameters, is how all modern AI learns.
Three Flavours of Gradient Descent
Most modern deep learning uses mini-batch gradient descent, processing a small group of training samples (typically 32 to 512 examples) before each weight update. This balances computational speed with the accuracy of the gradient estimate.
SGD — Stochastic Gradient Descent
SGD is the grandfather of all modern optimisers. Deceptively simple on the surface, it has powered some of the most significant breakthroughs in deep learning — and with the right tuning, it can still outperform far more complex alternatives.
Imagine you’re blindfolded in the mountains and want to walk downhill. You feel with your foot which direction slopes down, and take one careful step that way. Then you feel again, take another step. SGD does this — checking the slope one small step at a time, never looking at the full picture all at once.
The “Stochastic” in SGD means “random.” Instead of computing the exact average gradient over all training data (which would be enormously expensive), SGD estimates it using a single example or a small random batch. This estimation is noisy — but that noise turns out to be surprisingly useful, as it helps the model escape shallow local minima it might otherwise get stuck in.
// θ = parameters (weights) η = learning rate ∇J = gradient of loss
Why It Works — and Where It Struggles
SGD’s core strength is its simplicity and speed. Each update is cheap to compute, which means the model can update thousands of times per second on modern hardware. The built-in noise from using small batches acts as a kind of regularisation, stopping the model from over-fitting to any one pattern in the data.
However, SGD has two well-known problems. First, it uses the same learning rate for every single parameter in the network, even though different parameters may need to move at very different speeds. Second, if the loss surface has very different curvatures in different directions — a problem called pathological curvature — SGD oscillates back and forth inefficiently rather than moving straight toward the minimum.
SGD + Momentum: Adding Memory
The fix for SGD’s oscillation problem came in the form of momentum. Borrowed from physics, momentum gives the optimiser a kind of “memory” of the direction it has been moving. Instead of only looking at the current gradient to decide which direction to step, it also considers where it has been moving recently.
Imagine rolling a ball down a hilly track. The ball doesn’t stop and change direction instantly — it keeps rolling with the speed it already has, and only gradually steers toward the lowest point. Momentum gives gradient descent this same rolling behaviour. The ball rolls faster and straighter than someone taking one cautious step at a time.
θ ← θ − η · vt
// v = velocity (running average of gradients) β = momentum coefficient (typically 0.9)
The parameter β (beta) controls how much of the historical direction is carried forward. A value of 0.9 means “remember 90% of where I was going, and only 10% of the current gradient.” This smooths out the noisy zigzagging and lets the optimiser accelerate in directions where gradients consistently point the same way.
✓ SGD Strengths
- Simple, well-understood, and easy to implement
- Low memory requirement — just one copy of parameters
- Built-in noise helps escape local minima
- Often generalises better than Adam on image tasks
- Momentum variant is state-of-the-art for computer vision
✗ SGD Weaknesses
- Sensitive to learning rate choice — needs careful tuning
- Uniform learning rate for all parameters is inefficient
- Slow to converge in narrow, elongated valleys
- Without momentum, oscillates on pathological curvature
- Typically needs learning rate schedules for best results
# SGD with Momentum in PyTorch import torch.optim as optim optimizer = optim.SGD( model.parameters(), lr=0.01, # learning rate momentum=0.9, # momentum coefficient β weight_decay=1e-4 # optional L2 regularisation )
RMSProp — Root Mean Square Propagation
RMSProp solved one of the biggest problems in neural network training — the fact that different parameters in a model should learn at different speeds. Proposed by Geoffrey Hinton in a 2012 lecture, it became an instant classic.
Imagine you’re learning two skills: riding a bike (which needs big changes to your balance every day) and writing your name (which only needs tiny tweaks once you have the basics). RMSProp gives you a custom training speed for each skill — big adjustments where you need big changes, tiny adjustments where only fine-tuning is needed. This way, nothing is over-corrected or under-corrected.
The key idea behind RMSProp is adaptive learning rates. Instead of using one global learning rate for every parameter, RMSProp tracks how large the recent gradients have been for each individual parameter. If a particular weight has been seeing large, consistent gradients, its effective learning rate is scaled down. If gradients have been small, the effective rate goes up. Each weight gets exactly the learning speed it needs.
How RMSProp Computes Its Adaptive Rates
RMSProp maintains a running estimate of the squared gradients for each parameter. This is computed as an exponential moving average, meaning recent gradients matter more than old ones (controlled by the decay rate ρ, typically 0.9). The step size for each parameter is then divided by the square root of this running average.
θ ← θ − η / (√E[g²]t + ε) · gt
// E[g²] = running average of squared gradients ρ = decay rate ≈ 0.9 ε = tiny constant (1e-8)
The tiny constant ε (epsilon) is added inside the square root purely as a safety measure — it prevents a division-by-zero error in the extremely unlikely case where the gradient estimate becomes exactly zero.
Where RMSProp Shines
RMSProp was specifically designed to handle non-stationary objectives — problems where the gradient landscape keeps changing during training. Recurrent neural networks (RNNs) and reinforcement learning tasks are classic examples, because the data distribution or reward signal constantly shifts. In these settings, methods that accumulate gradient information over the entire training history (like Adagrad) deteriorate over time, while RMSProp’s rolling window keeps it relevant.
Natural Language Processing
Word embeddings and early LSTM-based language models benefited from RMSProp’s ability to handle the sparse gradient patterns that arise when only a fraction of vocabulary words appear in each training batch.
Reinforcement Learning
DeepMind’s original Deep Q-Network (DQN) — the model that learned to play Atari games at superhuman level — used RMSProp as its optimiser, establishing it as the go-to choice for RL.
Time Series & Finance
Non-stationary financial data, where the statistical properties of markets shift over time, aligns perfectly with RMSProp’s design philosophy of tracking recent behaviour rather than full history.
Audio & Speech Models
Recurrent architectures for speech recognition trained effectively with RMSProp, which handled the variable-length sequence gradients better than fixed-rate methods.
✓ RMSProp Strengths
- Adapts learning rate individually per parameter
- Excellent for non-stationary and shifting data
- Works well for RNNs and recurrent sequence models
- Resolves Adagrad’s learning-rate decay problem
- Simple to implement, minimal hyperparameter tuning
✗ RMSProp Weaknesses
- No published, peer-reviewed paper — originated from a lecture
- Still requires a manual learning rate to start
- Does not incorporate momentum by default
- Can be sensitive to the choice of decay rate ρ
- Generally outperformed by Adam in many modern benchmarks
# RMSProp in PyTorch optimizer = optim.RMSprop( model.parameters(), lr=0.001, # learning rate η alpha=0.9, # decay rate ρ for running average eps=1e-8, # ε for numerical stability momentum=0.0 # optional momentum term )
Adam — Adaptive Moment Estimation
Adam is arguably the most important optimiser in modern deep learning. It elegantly combines the best ideas from momentum and RMSProp into a single algorithm, and has become the default starting point for training almost every neural network today.
Adam is to optimisers what the smartphone was to electronics — it didn’t invent any new component, but it combined existing innovations so well that everything before it suddenly seemed unnecessarily complicated.— Intuition on Adam’s Design Philosophy
Remember how Momentum helps by tracking where you’ve been heading (like a rolling ball)? And RMSProp helps by slowing you down in directions where you’ve been running too fast, and speeding you up where you’ve been too slow? Adam does both at the same time, for every single parameter independently. It’s like having a wise navigator AND a smart speedometer built into one device.
Proposed by Diederik Kingma and Jimmy Ba in 2014, Adam stands for Adaptive Moment Estimation. The name refers to the two statistical moments it tracks for each parameter: the first moment (mean of gradients — like Momentum) and the second moment (uncentred variance of gradients — like RMSProp).
The Three Steps of Adam
- Track the first moment (m): Maintain a running exponential average of the gradients themselves. This captures direction and average magnitude — essentially a smoothed version of the gradient, similar to momentum.
- Track the second moment (v): Maintain a running exponential average of the squared gradients. This captures how much the gradient varies — allowing per-parameter learning rate scaling like RMSProp.
- Apply bias correction: Because both running averages start at zero, they are biased toward zero at the beginning of training. Adam corrects for this by dividing by (1 − β^t), making the early updates accurate rather than artificially small.
vt ← β₂ · vt-1 + (1 − β₂) · gt²
m̂t ← mt / (1 − β₁t) ← bias-corrected 1st moment
v̂t ← vt / (1 − β₂t) ← bias-corrected 2nd moment
θ ← θ − η · m̂t / (√v̂t + ε)
// Defaults: β₁ = 0.9, β₂ = 0.999, ε = 1e-8, η = 0.001
Understanding the Default Parameters
Adam’s original paper proposed default values that have proven remarkably robust across an enormous range of tasks. These are not magic numbers — each has a careful justification.
Weights recent gradients at 10% per step, carrying 90% of the previous momentum. Results in a smoothed average that looks roughly 10 steps back in history.
A much slower decay for the gradient-variance tracker. This looks ~1000 steps into the past, providing a very stable estimate of each parameter’s typical gradient magnitude.
A tiny floor value added to the denominator. Prevents catastrophic division-by-zero if the gradient variance estimate becomes extremely small for any parameter.
AdamW — The Improved Variant
Standard Adam has a subtle bug: when weight decay (L2 regularisation) is applied, it interacts incorrectly with the adaptive learning rate scaling. The result is that heavily updated parameters receive less weight penalty than they should. AdamW, proposed by Loshchilov and Hutter in 2017, decouples weight decay from the gradient-based update, fixing this issue.
In modern large language models (GPT, BERT, LLaMA) and vision transformers (ViT), AdamW has almost entirely replaced plain Adam. The improved regularisation behaviour leads to better generalisation, especially in models with billions of parameters where correct weight decay is critical for preventing overfitting.
✓ Adam Strengths
- Combines momentum and adaptive rates in one algorithm
- Bias correction ensures stability from step one
- Robust default hyperparameters — often needs no tuning
- Fast convergence, especially early in training
- Works well across images, text, audio, and tabular data
- AdamW variant is state-of-the-art for transformers
✗ Adam Weaknesses
- Uses more memory (stores m and v for every parameter)
- Can generalise worse than SGD on some vision benchmarks
- Weight decay is broken in standard Adam (use AdamW)
- May not converge to the optimum in some convex settings
- More computationally expensive per step than plain SGD
# Adam in PyTorch optimizer = optim.Adam( model.parameters(), lr=1e-3, # learning rate η (default: 0.001) betas=(0.9, 0.999), # (β₁, β₂) eps=1e-8 # ε for numerical stability ) # AdamW in PyTorch (preferred for transformers) optimizer = optim.AdamW( model.parameters(), lr=1e-4, weight_decay=0.01 # proper decoupled weight decay )
Hyperparameters — The Tuning Dials
Choosing an optimiser is only the first step. Getting great results means understanding the control knobs — the hyperparameters — that determine how aggressively each algorithm searches the loss landscape.
Learning Rate — The Most Important Setting
The learning rate determines how large a step the optimiser takes in the downhill direction after computing each gradient. It is almost universally the most impactful hyperparameter in training. A learning rate that is too high causes the model to overshoot and bounce chaotically. One that is too low causes glacially slow convergence — or getting stuck in a shallow local minimum.
Learning Rate Schedules
In practice, using a fixed learning rate throughout training is rarely optimal. A common strategy is to start with a higher learning rate (to take large steps through the broad landscape) and gradually decrease it as training progresses (to make fine adjustments near the minimum). Several scheduling strategies are widely used.
Multiply the learning rate by a fixed factor (e.g., 0.1) every N epochs. Simple and effective for many tasks.
ClassicThe learning rate follows a cosine curve — smoothly decaying from high to low each cycle. Extremely popular for vision and NLP transformers.
ModernStart with a tiny learning rate, ramp it up for the first few hundred steps (warmup), then decay. Standard for large language model training.
LLM StandardOscillate the learning rate between a minimum and maximum value in cycles. Helps escape saddle points and find better minima.
ResearchCommon Challenges in Optimisation
Training deep neural networks is treacherous terrain. The loss landscape is riddled with obstacles that can trap, slow, or mislead even the best optimisers. Understanding these challenges explains why more sophisticated algorithms were developed.
A saddle point is a location where the gradient is zero but it is neither a maximum nor a minimum — the terrain goes downhill in some directions and uphill in others. In high-dimensional networks, saddle points are far more common than true local minima. SGD without momentum often gets stuck here for thousands of steps.
In deep networks, gradients can shrink exponentially as they travel backward through many layers. By the time they reach early layers, the gradient is so small that those layers learn almost nothing. This is especially severe in RNNs and was a primary motivation for LSTM cells.
The opposite problem — gradients grow exponentially large through backpropagation, causing weight updates to be enormous and the model to diverge to useless, NaN-filled outputs. Gradient clipping (capping the gradient norm) is the standard remedy, applied in virtually every modern RNN and transformer pipeline.
Imagine you’re on a horse saddle. If you look left-right, you’re sitting at the bottom of a curve (like a valley). But if you look front-back, you’re at the top of a curve (like a hill). A saddle point in math is exactly this shape — and an optimiser sitting there sees zero slope in every direction, so it can’t figure out where to move!
Pathological Curvature — The Shape Problem
One of the trickiest challenges is when the loss landscape has very different curvatures in different directions — technically called a poor conditioning number. Imagine a very long, narrow valley running diagonally. The correct path is along the length of the valley, but the steepest direction is across the narrow width. Plain SGD keeps sliding across the valley from side to side (the “ravine” problem), making very slow progress along the actual path to the minimum. This is precisely the problem that momentum and adaptive learning rate methods solve.
Side-by-Side Comparison
A comprehensive reference comparing the three primary optimisers across every dimension that matters for practitioners.
| Property | SGD (+ Momentum) | RMSProp | Adam |
|---|---|---|---|
| Core Idea | Follow negative gradient; optionally accumulate past direction (momentum) | Scale each parameter’s learning rate by inverse of recent gradient magnitudes | Combine momentum (1st moment) and adaptive rates (2nd moment) with bias correction |
| Adaptive Learning Rates | No — same rate for all parameters | Yes — per-parameter adaptation | Yes — per-parameter with both moment estimates |
| Momentum | Optional (standard practice: yes) | Optional add-on | Built-in (1st moment) |
| Bias Correction | None | None | Yes — critical for early training stability |
| Key Hyperparams | lr, momentum (β), weight_decay | lr, ρ (decay), ε | lr, β₁, β₂, ε, weight_decay |
| Default lr | 0.01 – 0.1 | 0.001 | 0.001 |
| Memory Overhead | Low (just velocity if using momentum) | Medium (one extra state per parameter) | High (two states per parameter) |
| Convergence Speed | Slow initially, excellent final quality | Fast on non-stationary tasks | Fast overall, especially early on |
| Generalisation | Often best on vision/image tasks | Good for RL and RNNs | Excellent across most domains |
| Best For | CNNs, image classification, fine-tuning | RNNs, RL, non-stationary objectives | Transformers, NLP, general-purpose |
| Year Introduced | 1986 (+ Momentum 1999) | 2012 (Hinton lecture) | 2014 (Kingma & Ba) |
Which Optimiser Should You Choose?
There is no universal winner. The best optimiser depends on your task, your architecture, and what you care about — convergence speed, final accuracy, or training stability.
When in doubt, start with AdamW. If you’re training a CNN for images and care deeply about test accuracy, try switching to SGD with momentum and a cosine learning rate schedule once your architecture is stable.
Decision Framework by Task
Transformers & LLMs
Use AdamW — it is the standard across every major language model (GPT, BERT, T5, LLaMA). Pair with a warmup + cosine decay learning rate schedule. Typical settings: lr=1e-4, weight_decay=0.01.
Image Classification (CNNs)
Start with Adam to verify the architecture works. For maximising final test accuracy, switch to SGD + momentum + cosine annealing. ResNet and EfficientNet benchmarks typically show SGD wins here.
Reinforcement Learning
Use RMSProp for Q-learning and DQN-style agents (following DeepMind’s practice). For policy gradient methods (PPO, A3C), Adam is increasingly preferred.
RNNs & Sequence Models
Use RMSProp or Adam. RMSProp was Hinton’s recommendation for RNNs in his original lecture. Adam with gradient clipping (clip_norm=1.0) is equally effective.
New project? Use this stack: AdamW with lr=3e-4, β₁=0.9, β₂=0.999, weight_decay=0.01, and a linear warmup for 5% of total training steps followed by cosine decay. This configuration works surprisingly well as a first attempt across almost any architecture.
Real-World Usage Across Industries
Optimisers are not abstract mathematics — they are the invisible engines behind nearly every AI product in the world. Here is how the choice of optimiser has shaped real applications.
OpenAI’s language models are trained with AdamW with careful learning rate warmup and decay. The distributed training scale (thousands of GPUs) is only possible because Adam’s per-parameter adaptation reduces the sensitivity to hyperparameter tuning.
Deep neural network components in Google Search ranking use Adam variants internally. The ability to handle sparse feature updates efficiently (certain search signals appear rarely) makes adaptive optimisers ideal.
AdaptiveOpenAI’s Jukebox music generation model used Adam to train on millions of audio samples. The model’s transformers required stable gradient estimates across diverse musical styles.
CNNs for tumour detection and X-ray analysis often use SGD + momentum for its superior generalisation — critical when the cost of a false positive or false negative is extremely high.
High StakesWaymo, Tesla, and others train perception networks using Adam or AdamW for quick convergence during iterative development cycles, then validate with SGD-trained baselines for comparison.
Robot control policies trained via reinforcement learning (e.g., OpenAI’s robotic hand) used RMSProp and Adam depending on the specific policy gradient algorithm.
RLHistory of Optimisers
The story of deep learning optimisers spans nearly four decades of incremental insight, each new algorithm solving a weakness the previous one revealed.
French mathematician Augustin-Louis Cauchy first formalised the method of steepest descent for solving systems of equations. The core idea underlying all modern optimisers is nearly 180 years old.
Herbert Robbins and Sutton Monro published the first framework for stochastic approximation — the theoretical underpinning that allows using noisy (stochastic) gradient estimates rather than computing exact gradients.
The landmark paper on backpropagation made it practical to compute gradients through multi-layer networks, enabling SGD to train deep models for the first time and launching the modern neural network era.
Boris Polyak’s earlier work on heavy-ball methods was refined and popularised in neural network training, with Ilya Sutskever later demonstrating that momentum could dramatically accelerate convergence on deep networks.
Duchi, Hazan, and Singer introduced Adagrad, the first widely used adaptive learning rate method. It accumulated all squared gradients from the start of training — effective for sparse data but fatally prone to shrinking the learning rate to near-zero over time.
Geoffrey Hinton introduced RMSProp in Lecture 6e of his Coursera neural network course — notably never in a formal paper. By using an exponential moving average of squared gradients instead of a cumulative sum, it solved Adagrad’s vanishing learning rate problem.
Matthew Zeiler proposed Adadelta, which also used a windowed average of gradients and additionally scaled updates by a running average of weight changes — eliminating the need for a manual learning rate entirely.
Diederik Kingma and Jimmy Ba presented Adam at ICLR 2015. The paper has since accumulated over 200,000 citations, making it one of the most cited papers in all of computer science. Adam became the default optimiser for deep learning within months of publication.
Ilya Loshchilov and Frank Hutter fixed a subtle but important flaw in Adam’s interaction with weight decay regularisation, producing AdamW. It became the standard optimiser for transformer-based models and is now used to train virtually every major language model.
As models scaled to billions of parameters, new optimisers emerged: LAMB (Layer-wise Adaptive Moments) enables very large batch training; LION (EvoLved Sign Momentum) from Google Brain reduces memory by using only sign information; Sophia uses curvature information for faster convergence on language models.
Sources & Further Reading
Comprehensive technical survey of all major gradient descent variants; arXiv paper with 4,000+ citations.
Practical tutorial covering pathological curvature and the motivation behind each algorithm.
Applied introduction to Adam with configuration guidance and practical tips.
Broad survey covering Adagrad, RMSProp, Adam, and their relatives with visual intuitions.
Focused deep-dive on RMSProp’s mechanics, history, and applications.
Technical implementation guide for Adam with pseudocode and PyTorch examples.
Hands-on implementation walkthrough of SGD, Momentum, RMSProp and Adam in raw NumPy.
Notebook with visual animations and side-by-side training comparisons.
Ground-up implementation guide explaining each algorithm’s code with minimal abstractions.
Quick-reference covering optimiser selection criteria and typical use case mapping.
Comprehensive guide covering types, intuitions, and comparative analysis.
Survey including newer optimisers like LAMB and historical context for the field.