Deep Learning · Beginner Tutorial
A neural network learns by changing its weights. Backpropagation tells us how the loss responds to each weight; an optimizer decides the actual change to make. This lesson follows one weight through SGD, Momentum, RMSProp, Adam and AdamW, then shows how a learning-rate schedule changes the size of those updates over time.
What Does an Optimizer Actually Do?
Imagine a network predicts that a used car is worth ₹7 lakh when the correct price is ₹8 lakh. The loss function converts that mistake into a number. Backpropagation then calculates a gradient for every weight: it estimates whether increasing or decreasing that weight would reduce the loss near the network’s current position.
That calculation does not change the network by itself. The optimizer receives the gradients and turns them into updates. A simple optimizer uses only the newest gradient. More advanced optimizers remember earlier gradients, track their typical size, or apply weight decay. The goal is the same in every case: move the parameters toward values that produce a lower loss.
Where the optimizer fits in one training step
Backpropagation calculates information; the optimizer uses it to change the model.
Forward pass
The network makes a prediction.
Loss
A number measures how wrong it was.
Backpropagation
Gradients show how each weight affected the loss.
Optimizer
A rule converts gradients into weight changes.
Updated network
The next prediction uses the new weights.
Backpropagation asks
“For this mini-batch, how did each weight influence the loss?” Its output is a collection of gradients.
The optimizer asks
“Given those gradients and anything I remember from earlier steps, how much should each weight change now?”
The Two Ingredients in the First Update Rule
We begin with one learned weight, written as w. Backpropagation gives its gradient, written as g. To reduce the loss, we move in the opposite direction from that gradient. The learning rate, written as the Greek letter η (eta), controls how large the move will be.
Plain gradient-descent update
Parameter (w)
A number learned by the network, such as a weight or bias.
Gradient (g)
The slope of the loss with respect to a parameter. Its sign gives a local direction; its size gives local steepness.
Learning rate (η)
A multiplier that controls how large the update is.
Optimizer state
Remembered values such as velocity or moving averages. Plain SGD has no extra state.
Step
One parameter update, usually after one mini-batch.
Epoch
One pass through the training dataset. An epoch normally contains many steps.
Weight decay (λ)
A separate force that gently shrinks weights during training.
Epsilon (ε)
A tiny positive number that prevents division by zero in adaptive methods.
The gradient is not the update.
A gradient of 1.5 does not mean “subtract 1.5.” With η = 0.1, plain SGD subtracts only 0.15. Optimizers and learning-rate schedules can change that conversion further.
First Method: Stochastic Gradient Descent (SGD)
In deep-learning code, SGD normally updates the model using the average gradient from one mini-batch, perhaps 32 or 128 examples. Because different mini-batches contain different examples, their gradients vary. That randomness can make the path noisy, which is why the method is called stochastic.
SGD
Worked numerical example
Start with w = 4.00, gradient g = 1.50 and learning rate η = 0.10.
These are deliberately simple teaching values. In a real run, w began from initialization and has already been changed by training, g is calculated by backpropagation from the current mini-batch, and η is a developer-chosen hyperparameter.
update = ηg = 0.10 × 1.50 = 0.15
wnew = 4.00 − 0.15 = 3.85
Interpretation: the positive gradient says the loss rises when w rises nearby, so the optimizer moves w downward. The learning rate limits the move to 0.15.
Why people still use SGD
It is easy to reason about, stores little optimizer state and can produce excellent models when momentum and a schedule are carefully tuned.
Where plain SGD struggles
A single base learning rate treats every parameter alike. In a narrow valley, updates may cross the steep direction repeatedly instead of moving smoothly along the valley.
Why SGD Can Zigzag
A neural network’s loss is a surface over millions of parameter directions. Consider a narrow valley: the walls are steep from side to side, but the floor slopes gently toward lower loss. The gradient is dominated by the steep wall. Plain SGD therefore makes a large sideways correction, lands near the opposite wall, and then receives a gradient pointing back. It can keep bouncing even while slowly moving forward.
How three optimizers may travel through a narrow loss valley
The centre represents lower loss. Each coloured path starts at the same point and illustrates a different update behaviour.
Plain SGD
The current gradient repeatedly sends the update across the steep sides of the valley.
SGD + Momentum
Remembered direction damps side-to-side movement and builds speed along the valley.
Adam
Per-parameter scaling makes smaller moves along steep directions and relatively larger moves along flatter ones.
Momentum and Adam are not alternative ways to calculate the loss. They are alternative ways to process gradients. Momentum remembers direction; RMSProp remembers gradient size; Adam remembers both.
Momentum: Remember the Recent Direction
A ball rolling downhill does not forget its movement at every centimetre. Momentum gives an optimizer a similar memory called velocity. Gradients that repeatedly point in the same direction build velocity. Gradients that alternate—left, right, left, right—partly cancel inside that memory, reducing sideways oscillation.
SGD with momentum
vt = βvt−1 + gt
wt = wt−1 − ηvt
Continue the same example for two steps
Velocity starts at v₀ = 0 because there is no earlier gradient. We choose β = 0.9 and η = 0.10; backpropagation supplies g₁ = 1.50 for the first batch and g₂ = 1.00 for the next batch.
Step 1
v₀ = 0, g₁ = 1.50
v₁ = 0.9(0) + 1.50 = 1.50
w₁ = 4.00 − 0.10(1.50) = 3.85
Step 2
g₂ = 1.00
v₂ = 0.9(1.50) + 1.00 = 2.35
w₂ = 3.85 − 0.10(2.35) = 3.615
What the memory changed: plain SGD would use only g₂ and move by 0.10 at step 2. Momentum sees that both gradients point in the same direction, so its stored velocity makes a larger 0.235 move. If the next gradient points the other way, part of it first cancels the velocity.
RMSProp: Adjust for Recent Gradient Size
Different weights can have gradients on very different scales. A single learning rate may be too aggressive for a parameter with repeatedly large gradients and too cautious for another with small gradients. RMSProp keeps an exponential moving average of each parameter’s squared gradients. It divides the current gradient by the root of that average, creating a different effective step scale for each parameter.
RMSProp
st = ρst−1 + (1 − ρ)gt2
wt = wt−1 − η · gt / (√st + ε)
Use w = 4.00 and g = 1.50 again
Suppose the optimizer's earlier squared-gradient calculations stored sprevious = 2.25. The developer chooses ρ = 0.9 and η = 0.1; backpropagation supplies g = 1.50. Frameworks add a tiny ε by default to prevent division by zero, but it is too small to affect these rounded values.
s = 0.9(2.25) + 0.1(1.50²) = 2.25
scaled gradient = 1.50 / √2.25 = 1.00
wnew = 4.00 − 0.10(1.00) = 3.90
How to interpret 3.90
The raw gradient was 1.50, but its recent root-mean-square size was also 1.50. RMSProp normalized it to 1.00 before applying η.
This does not mean RMSProp always makes smaller updates. A parameter with unusually small recent gradients can receive a relatively larger effective step.
Adam: Combine Direction Memory and Size Memory
Adam stands for Adaptive Moment Estimation. It keeps a first moving average, m, that summarizes gradient direction like momentum. It also keeps a second moving average, v, of squared gradients like RMSProp. The update uses m for direction and divides by √v to adapt the scale separately for every parameter.
Adam in four calculations
mt = β₁mt−1 + (1 − β₁)gt
vt = β₂vt−1 + (1 − β₂)gt2
m̂t = mt / (1 − β₁t), v̂t = vt / (1 − β₂t)
wt = wt−1 − η · m̂t / (√v̂t + ε)
Adam’s first update for the same w = 4.00 and g = 1.50
The optimizer initializes its memories m₀ and v₀ to zero because no gradients have arrived. We choose β₁ = 0.9, β₂ = 0.999 and η = 0.1 for this demonstration; PyTorch uses the same beta values as Adam defaults, while the learning rate here is deliberately larger so the arithmetic stays visible. We omit ε only in the rounded hand calculation.
m₁ = 0.9(0) + 0.1(1.50) = 0.15
v₁ = 0.999(0) + 0.001(1.50²) = 0.00225
m̂₁ = 0.15 / (1 − 0.9) = 1.50
v̂₁ = 0.00225 / (1 − 0.999) = 2.25
update = 0.10 × 1.50 / √2.25 = 0.10
w₁ = 4.00 − 0.10 = 3.90
What this number teaches: on the first idealized step, bias correction recovers the raw first and second moments, so the gradient magnitude largely cancels and the step is close to η. Later steps depend on the accumulated history. This example explains the mechanism; it is not a claim that Adam always moves every weight by exactly η.
AdamW: Keep Weight Decay Separate
Weight decay discourages weights from growing unnecessarily large. With adaptive optimizers, adding an L2 penalty to the loss and letting Adam process its gradient is not generally the same as shrinking the weights directly. AdamW decouples the two actions: it performs Adam’s gradient-based update and applies a separate weight-shrinking step.
Conceptual AdamW update
Add λ = 0.01 to Adam’s worked example
The old weight 4.00 and Adam update 0.10 come from the continuing example. The developer chooses weight-decay coefficient λ = 0.01; it is not inferred by Adam and should be compared on validation data.
Decay factor
1 − 0.10(0.01) = 0.999
Shrunk weight
0.999 × 4.00 = 3.996
Then Adam update
3.996 − 0.10 = 3.896
AdamW is a strong modern starting point, especially for Transformer-style models, but “W” does not make tuning automatic. A decay that is too strong can underfit, and parameters such as biases and normalization scales are often placed in a no-decay parameter group.
Choosing an Optimizer for a Real Project
There is no optimizer that wins every dataset, architecture and training budget. Begin with a sensible baseline, keep the model and split fixed, and compare validation quality, training time and memory—not just how quickly training loss falls.
| Method | What it remembers | Extra state | Good reason to try it | Important caution |
|---|---|---|---|---|
| Plain SGD | Current gradient | Lowest | Transparent baseline; constrained optimizer memory | May zigzag and often needs careful scheduling |
| SGD + Momentum | Gradient plus velocity | One extra value per parameter | Long, carefully tuned vision training; noisy narrow valleys | Learning rate and momentum interact |
| RMSProp | Moving average of squared gradients | One extra value per parameter | Non-stationary or recurrent problems; uneven gradient scales | Can need a different base rate from SGD |
| Adam | First and second moments | Two extra values per parameter | Fast baseline; sparse or differently scaled gradients | Fast training loss is not proof of best validation quality |
| AdamW | Adam moments plus decoupled decay | Two extra values per parameter | Modern Transformer and general deep-learning baselines | Weight decay and learning rate still require tuning |
You need a working baseline quickly
Start with AdamW or Adam. Verify that the loss falls, then tune the learning rate and compare alternatives if final quality justifies the work.
You are training a CNN for many epochs
Compare SGD with momentum and AdamW under a fair schedule. Momentum SGD can be strong when the recipe is carefully tuned.
Gradients are sparse or vary greatly by parameter
Try Adam or AdamW because their per-parameter moment estimates adapt update scales.
Optimizer memory is the bottleneck
Plain SGD stores the least extra state; Momentum adds one state value per parameter, while Adam-family methods normally add two.
Why Change the Learning Rate During Training?
The best step size near the start may be unsuitable near the end. Early in training, the weights are usually far from a useful solution, so larger updates can make rapid progress. Later, a smaller rate can refine the weights without repeatedly jumping across a low-loss region. A learning-rate scheduler changes η according to training time or a measured result.
Too high
Loss can oscillate, explode or become NaN because updates overshoot useful regions.
Too low
Loss changes very slowly, making a correct pipeline look broken and wasting the training budget.
Changed deliberately
Warmup stabilizes the start; decay makes later updates more precise; metric-driven schedules react to a plateau.
Seven Learning-Rate Patterns at a Glance
Read each graph from left to right. The horizontal axis is training progress; the vertical axis is the learning rate. The shapes are original illustrative curves shown on a common scale so their behaviour is easy to compare.
Constant
Keeps the same rate from beginning to end.
When it fits: A dependable baseline for short or already stable runs.
Warmup → cosine
Rises gently, then follows a smooth cosine-shaped fall.
When it fits: Useful when a large model is unstable at the start.
Step decay
Drops by a chosen factor at fixed milestones.
When it fits: Useful when the training recipe has known phase changes.
Exponential decay
Multiplies the rate by a factor repeatedly.
When it fits: A simple, smooth reduction throughout training.
Cosine decay
Falls slowly at first and near the end, faster in the middle.
When it fits: Common when the total training budget is known.
Reduce on plateau
Waits for a monitored metric to stop improving, then drops.
When it fits: Useful when you cannot predict the right milestone.
One-cycle
Rises to a peak and then falls to a very small rate.
When it fits: Useful for a deliberately tuned, fixed-length run.
Warmup, Decay and Metric-Driven Changes
Warmup protects the fragile beginning
Warmup starts below the intended peak rate and increases over the first set of steps. At the beginning, optimizer moments, normalization statistics and activations are not yet settled. A full-size update can be disruptive, especially with large batches or large Transformer-style models.
Where the values come from: t is the current step counted by the scheduler; Twarmup and ηmax are developer choices. Meaning: halfway through warmup, the rate is halfway to ηmax. Warmup is a short opening phase, not a replacement for the schedule that follows.
Decay changes from exploration to refinement
Step, exponential and cosine schedules all reduce the learning rate, but they answer “when?” differently. Step decay makes abrupt changes at milestones. Exponential decay shrinks by the same proportion repeatedly. Cosine decay uses the known training horizon to make a smooth transition toward a chosen minimum.
Step:
ηt = η₀γ⌊t/s⌋
Exponential:
ηt = η₀γt
Cosine:
ηt = ηmin + ½(ηmax−ηmin)(1+cos(πt/T))
Here γ is a multiplier below 1, s is the step interval, and T is the planned schedule length. Decaying too soon can stop learning before useful features form.
Reduce on plateau listens to validation performance
Instead of using fixed dates, this scheduler monitors a metric such as validation loss. It tracks checks that do not improve beyond the configured threshold. Once the allowed patience has been exceeded, it multiplies the learning rate by a reduction factor. It should receive the validation metric after validation finishes.
Patience
How many non-improving checks the scheduler tolerates before a later bad check triggers a reduction.
Threshold
How much change counts as real improvement.
Factor
How strongly to reduce the rate.
A noisy metric with patience set too low can cause premature drops. Smooth evidence and domain-appropriate patience matter more than reacting to one bad epoch.
One-cycle deliberately rises before it falls
One-cycle is a finite training policy rather than ordinary monotonic decay. It begins below the maximum rate, rises to that peak, then falls—often below the starting rate. The increasing phase allows larger exploratory updates; the long decreasing phase refines the solution. Because the maximum rate and total number of steps are central to the policy, it should be tuned as a complete recipe.
Which Schedule Fits Which Situation?
| Schedule | Choose it when… | Check before trusting it |
|---|---|---|
| Constant | The run is short and stable, or you need a clean baseline | Watch whether progress stalls before the budget ends |
| Warmup + cosine | The start is fragile and the total number of steps is known | Choose both warmup duration and final rate |
| Step / multi-step | A proven recipe specifies milestone epochs | Fixed dates ignore what validation is actually doing |
| Exponential | You want a steady proportional decrease | Too much decay can freeze learning early |
| Reduce on plateau | You want validation performance to trigger the drop | Noisy metrics need suitable patience and threshold |
| One-cycle | You can tune a fixed-length run and maximum safe rate | It is not a drop-in cure for an unstable pipeline |
A practical beginner decision
For a fixed-length run, AdamW with warmup followed by cosine decay is a reasonable modern baseline. For a small project with an uncertain stopping time, AdamW plus ReduceLROnPlateau is easier to relate to observed validation progress. These are starting experiments, not universal defaults.
Putting the Optimizer and Scheduler Into a Training Loop
The optimizer must update the parameters before most PyTorch schedulers advance. ReduceLROnPlateau is different: it steps after validation and receives the monitored metric.
import torch
# AdamW keeps gradient adaptation and weight decay separate.
optimizer = torch.optim.AdamW(
model.parameters(),
lr=3e-4,
betas=(0.9, 0.999),
weight_decay=1e-2,
)
# Warm up for 3 epochs, then decay through the remaining 27.
warmup = torch.optim.lr_scheduler.LinearLR(
optimizer, start_factor=0.1, end_factor=1.0, total_iters=3
)
cosine = torch.optim.lr_scheduler.CosineAnnealingLR(
optimizer, T_max=27, eta_min=1e-6
)
scheduler = torch.optim.lr_scheduler.SequentialLR(
optimizer, schedulers=[warmup, cosine], milestones=[3]
)
for epoch in range(30):
model.train()
for inputs, targets in train_loader:
optimizer.zero_grad() # remove gradients from the last batch
predictions = model(inputs) # forward pass
loss = loss_fn(predictions, targets)
loss.backward() # calculate current gradients
optimizer.step() # use gradients to update weights
validate(model, validation_loader)
scheduler.step() # advance after optimizer updates
print("learning rate:", scheduler.get_last_lr()[0])plateau = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer, mode="min", factor=0.2, patience=3
)
for epoch in range(30):
train_one_epoch(model, train_loader, optimizer)
validation_loss = validate(model, validation_loader)
plateau.step(validation_loss) # step AFTER measuring validation lossWhere the code's schedule values come from
This example plans 30 epochs: the developer assigns the first 3 to linear warmup and the remaining 27 to cosine decay. start_factor=0.1 begins at 10% of the base rate 3e−4, so the first scheduled rate is about 3e−5; end_factor=1.0 reaches the base rate. eta_min=1e-6 is the chosen final floor. In the alternative, factor=0.2 makes the rate one fifth as large once the allowed patience has been exceeded; patience=3 does not mean “reduce on exactly the third bad check.”
AdamW creates two moment buffers per trainable parameter and applies decay separately. SequentialLR switches schedulers at milestone 3. scheduler.step() advances the time-based schedule; plateau.step(validation_loss) instead needs the newly measured validation result before deciding whether to reduce the rate.
Why zero gradients?
PyTorch accumulates them by default. Without clearing, the optimizer may use unintended sums from earlier batches.
Why save optimizer state?
Momentum, RMSProp and Adam remember history. Restoring only model weights does not truly resume the same training run.
Why log the rate?
A wrong scheduler order or milestone becomes visible when you plot learning rate beside training and validation loss.
Diagnose the Symptom Before Switching Methods
| What you observe | Likely explanations | Useful next checks |
|---|---|---|
| Loss jumps wildly or becomes NaN | Learning rate too high, exploding gradients, unstable input scale or invalid arithmetic | Lower the rate; inspect inputs and gradients; add clipping only after finding the cause |
| Loss falls, but extremely slowly | Learning rate too low, saturated activations, poor initialization or frozen parameters | Try a modestly higher rate; inspect gradient norms and requires_grad settings |
| Training loss falls while validation worsens | Overfitting—not automatically an optimizer failure | Use regularization, more data or early stopping; compare models on validation |
| Progress stops immediately after a schedule change | Decay happened too early or the factor was too severe | Plot the actual rate; delay the milestone or use gentler decay |
| ReduceLROnPlateau drops constantly | Noisy metric, low patience or overly strict threshold | Monitor validation loss correctly; increase patience; verify mode='min' |
| A resumed run behaves differently | Optimizer or scheduler state was not restored | Checkpoint model, optimizer, scheduler, epoch and random-state information |
Fair comparisons require more than changing one class name.
SGD, RMSProp and Adam often need different learning-rate ranges. Compare them with the same data split, initialization policy, number of updates and validation metric, but give each a reasonable learning-rate search. Otherwise the experiment compares hyperparameter luck rather than optimizers.
What to Remember
- Backpropagation calculates gradients; the optimizer converts them into parameter updates.
- Plain SGD uses the current mini-batch gradient. Momentum remembers direction.
- RMSProp remembers squared-gradient size. Adam combines direction and size memories with early-step bias correction.
- AdamW applies weight decay separately from Adam’s adaptive moment calculation.
- The learning rate controls update scale; a schedule changes that scale across training.
- Warmup stabilizes the beginning, decay supports later refinement, and plateau scheduling reacts to validation progress.
- Choose by controlled validation experiments, runtime and memory—not by optimizer popularity alone.