Skip to main content
LearnMLAcademy
Advanced10 min read

Optimizers and Learning-Rate Scheduling

Compare adaptive optimizers including AdamW, momentum, and cosine schedulers, with tensor walkthroughs, gradient calculations, and PyTorch practice.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

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.

1

Forward pass

The network makes a prediction.

2

Loss

A number measures how wrong it was.

3

Backpropagation

Gradients show how each weight affected the loss.

4

Optimizer

A rule converts gradients into weight changes.

5

Updated network

The next prediction uses the new weights.

The optimizer does not make predictions and it does not calculate gradients. Its job begins after gradients exist.

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

wnew = wold − ηg
Read it aloud: the new weight equals the old weight minus the learning rate multiplied by the gradient. If g is positive, w decreases. If g is negative, subtracting it makes w increase.

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

wt = wt−1 − ηgt
The subscript t means the current training step. SGD uses gt, the current mini-batch gradient, and remembers no earlier gradient.

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.

LOW LOSSSTARThigher lossnarrow valley

Plain SGD

The current gradient repeatedly sends the update across the steep sides of the valley.

LOW LOSSSTARThigher lossnarrow valley

SGD + Momentum

Remembered direction damps side-to-side movement and builds speed along the valley.

LOW LOSSSTARThigher lossnarrow valley

Adam

Per-parameter scaling makes smaller moves along steep directions and relatively larger moves along flatter ones.

Conceptual illustration: these are explanatory paths, not measured results or a promise that one optimizer will always converge faster. Real paths depend on the model, data, batch order and hyperparameters.

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

v is velocity and β (beta) controls how much earlier velocity remains. With β = 0.9, 90% of the previous velocity is carried into the new calculation. Some books use an equivalent rescaled convention, so formulas can look slightly different.

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 + ε)

s remembers recent squared-gradient size; ρ controls that memory. Squaring removes the sign and makes large gradients stand out. The square root returns the scale to gradient units, while ε prevents division by zero.

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 + ε)

The hats mark bias-corrected values. Because m and v start at zero, their early averages are pulled toward zero. Dividing by 1 − βt corrects that startup effect.

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

wt = (1 − ηλ)wt−1 − η · m̂t / (√v̂t + ε)
λ (lambda) is the weight-decay coefficient. The first term shrinks the old weight; the second is the adaptive Adam update. Implementations can differ in ordering details, but the defining idea is that decay is not mixed into Adam’s moment estimates.

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.

MethodWhat it remembersExtra stateGood reason to try itImportant caution
Plain SGDCurrent gradientLowestTransparent baseline; constrained optimizer memoryMay zigzag and often needs careful scheduling
SGD + MomentumGradient plus velocityOne extra value per parameterLong, carefully tuned vision training; noisy narrow valleysLearning rate and momentum interact
RMSPropMoving average of squared gradientsOne extra value per parameterNon-stationary or recurrent problems; uneven gradient scalesCan need a different base rate from SGD
AdamFirst and second momentsTwo extra values per parameterFast baseline; sparse or differently scaled gradientsFast training loss is not proof of best validation quality
AdamWAdam moments plus decoupled decayTwo extra values per parameterModern Transformer and general deep-learning baselinesWeight 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.

training progress →learning rate

Constant

Keeps the same rate from beginning to end.

When it fits: A dependable baseline for short or already stable runs.

warmup endstraining progress →learning rate

Warmup → cosine

Rises gently, then follows a smooth cosine-shaped fall.

When it fits: Useful when a large model is unstable at the start.

training progress →learning rate

Step decay

Drops by a chosen factor at fixed milestones.

When it fits: Useful when the training recipe has known phase changes.

training progress →learning rate

Exponential decay

Multiplies the rate by a factor repeatedly.

When it fits: A simple, smooth reduction throughout training.

training progress →learning rate

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.

metric stallsstalls againtraining progress →learning rate

Reduce on plateau

Waits for a monitored metric to stop improving, then drops.

When it fits: Useful when you cannot predict the right milestone.

maximum ratetraining progress →learning rate

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.

linear warmup: ηt = ηmax × t / Twarmup, for t ≤ Twarmup

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?

ScheduleChoose it when…Check before trusting it
ConstantThe run is short and stable, or you need a clean baselineWatch whether progress stalls before the budget ends
Warmup + cosineThe start is fragile and the total number of steps is knownChoose both warmup duration and final rate
Step / multi-stepA proven recipe specifies milestone epochsFixed dates ignore what validation is actually doing
ExponentialYou want a steady proportional decreaseToo much decay can freeze learning early
Reduce on plateauYou want validation performance to trigger the dropNoisy metrics need suitable patience and threshold
One-cycleYou can tune a fixed-length run and maximum safe rateIt 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.

pytorch_optimizer_and_schedule.py
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])
metric_driven_alternative.py
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 loss

Where 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 observeLikely explanationsUseful next checks
Loss jumps wildly or becomes NaNLearning rate too high, exploding gradients, unstable input scale or invalid arithmeticLower the rate; inspect inputs and gradients; add clipping only after finding the cause
Loss falls, but extremely slowlyLearning rate too low, saturated activations, poor initialization or frozen parametersTry a modestly higher rate; inspect gradient norms and requires_grad settings
Training loss falls while validation worsensOverfitting—not automatically an optimizer failureUse regularization, more data or early stopping; compare models on validation
Progress stops immediately after a schedule changeDecay happened too early or the factor was too severePlot the actual rate; delay the milestone or use gentler decay
ReduceLROnPlateau drops constantlyNoisy metric, low patience or overly strict thresholdMonitor validation loss correctly; increase patience; verify mode='min'
A resumed run behaves differentlyOptimizer or scheduler state was not restoredCheckpoint 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.

Continue Learning

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Optimizers and Learning-Rate Scheduling"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What information does plain SGD use for its basic update?
Question 2 of 5conceptual
What does momentum add?
Question 3 of 5interpretation
Why does Adam keep a squared-gradient average?
Question 4 of 5debugging/diagnostic
What can happen when the learning rate is too large?
Question 5 of 5practical selection
What does ReduceLROnPlateau patience=3 mean?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What information does plain SGD use for its basic update?▼

Correct Answer: The current gradient and learning rate

The basic SGD step subtracts the learning-rate-scaled current gradient.

2What does momentum add?▼

Correct Answer: A running direction from recent gradients

Velocity carries recent direction, damping oscillation and building movement along persistent slopes.

3Why does Adam keep a squared-gradient average?▼

Correct Answer: To scale updates per parameter by typical gradient size

The second-moment estimate normalizes parameters with different gradient scales.

4What can happen when the learning rate is too large?▼

Correct Answer: Loss can oscillate or diverge

Oversized steps can repeatedly cross a good region or move into unstable values.

5What does ReduceLROnPlateau patience=3 mean?▼

Correct Answer: Wait for three monitored non-improving epochs before reducing the rate

Patience counts consecutive monitored epochs without sufficient improvement before the scheduler reacts.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next