AI
Learning Rate in Machine Learning: How to Set It
What the learning rate is, why too high or too low breaks training, typical values, warmup, decay and schedulers, a worked example and PyTorch code.
The learning rate is the hyperparameter that controls how big a step a model takes each time it updates its weights during training. After computing the gradient (the direction that reduces the error), the optimizer moves the weights by the gradient multiplied by the learning rate. Too high, and training overshoots, oscillates or diverges into NaN losses; too low, and it crawls or gets stuck. It's usually the single most important hyperparameter to tune, and modern training rarely keeps it fixed: it typically warms up at the start and decays over time.
This guide explains what learning rate is, how it affects training (with a worked example you can check by hand), typical values for common optimizers and real large language models, how to find a good one, learning rate warmup, learning rate decay, how to use a learning rate scheduler in PyTorch, and how to diagnose problems from the loss curve.
What Is Learning Rate?
What is learning rate, mathematically? In plain gradient descent, each training step updates every weight like this:
new_weight = old_weight - learning_rate * gradientThe gradient says which way is downhill on the loss surface and how steep it is; the learning rate (often written as η, eta, or lr) says how far to move in that direction. Picture walking down a foggy valley: the gradient is the slope you feel under your feet, and the learning rate is your stride length.
Adaptive optimizers such as Adam and AdamW scale each weight's step using running averages of past gradients, but they still multiply that step by a global learning rate. So even with Adam, the learning rate sets the overall size of updates.
The learning rate interacts with other settings, especially batch size and the number of epochs: larger batches give less noisy gradients and often tolerate larger learning rates. Our epoch vs batch size guide covers those relationships, including the linear scaling rule for adjusting the learning rate when you change batch size.
How Learning Rate Affects Training
| Learning rate | What happens | Typical symptom |
|---|---|---|
| Far too high | Steps overshoot the minimum and grow larger each time | Loss shoots up or becomes NaN within a few steps |
| Slightly too high | Steps bounce across the valley | Loss is noisy, plateaus at a poor value or spikes occasionally |
| About right | Steady progress toward a good minimum | Loss drops quickly at first, then smoothly levels off |
| Too low | Tiny steps | Loss falls very slowly; training takes far longer or stalls in a poor region |
A higher learning rate also adds useful noise that can help the model escape sharp, poor minima, which is one reason training often starts with a relatively large rate and shrinks it later.
Worked Example: Gradient Descent on a Simple Curve
You can see the effect of the learning rate exactly on the simplest loss function, f(w) = w², whose minimum is at w = 0. Its gradient is 2w, so each step does:
w_new = w - lr * 2w = (1 - 2 * lr) * wEach step multiplies w by (1 − 2 × lr). Starting from w = 10:
| Learning rate | Multiplier per step | w after 1 step | w after 10 steps | Behaviour |
|---|---|---|---|---|
| 0.01 | 0.98 | 9.8 | about 8.17 | Converges, but very slowly |
| 0.1 | 0.8 | 8.0 | about 1.07 | Converges steadily |
| 0.5 | 0 | 0 | 0 | Jumps straight to the minimum (only for this exact curve) |
| 1.0 | −1 | −10 | 10 | Oscillates forever between 10 and −10 |
| 1.1 | −1.2 | −12 | about 61.9 | Diverges: each step overshoots further |
Three lessons carry over to real networks. First, there's a threshold above which training diverges, and it depends on how sharply curved the loss surface is (here the curvature is 2, and anything above lr = 1 diverges). Second, just below that threshold, training oscillates instead of settling. Third, a learning rate ten times too small isn't "safe": it simply wastes most of your compute. Real loss surfaces have different curvature in different directions and in different phases of training, which is why schedules and adaptive optimizers help.
Typical Learning Rate Values
There's no universal best value, but these starting points are common:
| Setting | Typical learning rate | Notes |
|---|---|---|
| Adam or AdamW, general deep learning | 1e-3 (0.001) | PyTorch and Keras default for Adam; often lowered to 3e-4 or 1e-4 for transformers |
| SGD with momentum, image classification | 0.1 for batch size 256 | Common in ResNet-style training, with decay over time |
| Pretraining GPT-3 Small (125M parameters) | 6.0e-4 peak | From the GPT-3 paper's Table 2.1 |
| Pretraining GPT-3 (175B parameters) | 0.6e-4 peak | Larger models used smaller learning rates |
| Pretraining Llama 2 7B and 13B | 3.0e-4 peak | Llama 2 paper; 34B and 70B used 1.5e-4 |
| Full fine-tuning of an LLM | about 1e-5 to 5e-5 | Llama 2's supervised fine-tuning used 2e-5 |
| LoRA or QLoRA fine-tuning | about 1e-4 to 2e-4 | Adapters train few weights and tolerate higher rates |
| Gradient-boosted trees (XGBoost, LightGBM) | 0.01 to 0.3 | Called eta or shrinkage; lower values need more trees |
Notice the pattern in the GPT-3 table: as models grew from 125 million to 175 billion parameters, the peak learning rate fell tenfold, from 6.0e-4 to 0.6e-4. Larger networks are more sensitive to big updates. Fine-tuning uses much smaller rates than pretraining because the goal is to adjust, not overwrite, what the model already knows; our how to fine-tune an LLM guide covers the full set of fine-tuning settings.
How to Find a Good Learning Rate
- Start from a known default for your optimizer and model type (the table above, or the paper or library you're building on).
- Run a learning rate range test. Leslie Smith's method, from his work on cyclical learning rates: start with a tiny learning rate, increase it exponentially every batch over a short run, and plot loss against learning rate. Pick a value somewhat below the point where the loss is falling fastest, and well below where it starts to blow up. Libraries such as fastai have this built in as an "LR finder".
- Sweep on a log scale. Try values like 1e-4, 3e-4, 1e-3 and 3e-3 rather than evenly spaced ones; learning rates matter by orders of magnitude, not small increments.
- Compare on validation loss after a fixed short budget, not training loss alone.
- Re-tune when you change things like batch size, model size, optimizer or dataset.
The learning rate is usually the first hyperparameter to tune and the one with the biggest payoff. It also interacts with regularization: weight decay in AdamW is multiplied by the learning rate in PyTorch's implementation, so changing one changes the effective strength of the other. Our regularization in machine learning guide explains weight decay and its alternatives.
Learning Rate Warmup
Learning rate warmup means starting training with a very small learning rate and increasing it, usually linearly, to the target peak over the first few hundred or thousand steps.
Why it helps:
- Early gradients are unreliable. At initialization, weights are random and gradients can be large and erratic; a full-size step can push the model into a bad region it never recovers from.
- Adam's statistics need time. Adaptive optimizers estimate gradient variance from a running average, which is poorly estimated in the first steps.
- Large batches and transformers are fragile at the start. The original Transformer paper used 4,000 warmup steps, and Goyal and colleagues' large-minibatch ImageNet training used a gradual warmup over the first five epochs.
Typical warmup lengths are a few hundred to a few thousand steps, or roughly 1% to 5% of training. Llama 2 used 2,000 warmup steps.
Learning Rate Decay
Learning rate decay means reducing the learning rate as training progresses. Large steps make fast progress early; smaller steps later let the model settle into a minimum instead of bouncing around it. Common decay schedules:
| Schedule | How it works | Common use |
|---|---|---|
| Step decay | Multiply the rate by a factor (for example 0.1) at set epochs | Classic image classification with SGD |
| Exponential decay | Multiply by a constant slightly below 1 every step or epoch | Simple, smooth decay |
| Cosine decay | Follow half a cosine curve from the peak down to a minimum | Most LLM pretraining and many vision models |
| Linear decay | Fall in a straight line to zero or a floor | Common in fine-tuning (Hugging Face default) |
| Inverse square root | Fall in proportion to 1 / √step after warmup | The original Transformer schedule |
| Reduce on plateau | Cut the rate when validation loss stops improving | When you don't know the training length in advance |
| Warm restarts (SGDR) | Cosine decay that periodically jumps back up | Loshchilov and Hutter's SGDR; exploring several minima |
| One-cycle | Rise to a peak, then fall well below the start | Smith's 1cycle policy for fast training |
The most common recipe for large models today is warmup followed by cosine decay. Llama 2, for example, warmed up for 2,000 steps and then followed a cosine schedule down to 10% of the peak learning rate.
How to Use a Learning Rate Scheduler in PyTorch
A learning rate scheduler is an object that changes the optimizer's learning rate as training proceeds. In PyTorch, schedulers live in torch.optim.lr_scheduler. Here's warmup followed by cosine decay, built from two standard schedulers:
import torch
from torch.optim.lr_scheduler import LinearLR, CosineAnnealingLR, SequentialLR
model = torch.nn.Linear(512, 10) # stand-in for your model
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.01)
total_steps = 10_000
warmup_steps = 500
warmup = LinearLR(optimizer, start_factor=0.01, total_iters=warmup_steps) # ramp from 1% to 100%
cosine = CosineAnnealingLR(optimizer, T_max=total_steps - warmup_steps, eta_min=3e-5) # decay to 10% of peak
scheduler = SequentialLR(optimizer, schedulers=[warmup, cosine], milestones=[warmup_steps])
for step in range(total_steps):
# forward pass, loss.backward() ...
optimizer.step()
scheduler.step() # update the learning rate after each optimizer step
optimizer.zero_grad()For the one-cycle policy, PyTorch has a single scheduler:
from torch.optim.lr_scheduler import OneCycleLR
scheduler = OneCycleLR(optimizer, max_lr=1e-3, total_steps=10_000) # rises for 30% of steps, then annealsThree rules prevent the most common bugs: call scheduler.step() after optimizer.step(), decide whether your scheduler counts batches or epochs and step it accordingly, and log the learning rate (scheduler.get_last_lr()) so you can confirm the schedule does what you expect. In Hugging Face Transformers, the Trainer handles this through the learning_rate, warmup_steps (or warmup_ratio) and lr_scheduler_type arguments.
Diagnosing Learning Rate Problems
| Symptom | Likely cause | What to try |
|---|---|---|
| Loss becomes NaN or explodes early | Learning rate too high, or no warmup | Lower the peak by 3 to 10 times, add warmup, add gradient clipping |
| Loss falls, then suddenly spikes | Peak rate too high for this phase, or bad batches | Lower the peak, lengthen warmup, clip gradients |
| Loss decreases very slowly | Learning rate too low | Run a range test; try 3 to 10 times higher |
| Loss plateaus early at a poor value | Too low, or decayed too fast | Raise the rate or slow the decay |
| Training loss fine, validation loss rising | Overfitting rather than the learning rate | Add regularization or stop earlier; lower the rate for fine-tuning |
| Loss is very noisy | Rate too high for the batch size | Lower the rate or increase the batch size |
FAQ
What is a good learning rate to start with?
For Adam or AdamW, 1e-3 is the common default, and 3e-4 is a popular choice for transformers. For SGD with momentum, 0.01 to 0.1 is typical. Then tune on a log scale.
Should the learning rate change during training?
Usually yes. Most modern training uses learning rate warmup at the start and learning rate decay afterwards, such as cosine decay, because it trains faster and reaches better results than a fixed rate.
Does Adam need a learning rate?
Yes. Adam adapts the step size for each weight, but it still multiplies every update by a global learning rate, and results remain sensitive to it.
How does batch size affect the learning rate?
Larger batches produce less noisy gradients and often allow larger learning rates. A common heuristic scales the learning rate with batch size, combined with warmup, but it breaks down at very large batches.
What is the learning rate in gradient boosting?
In gradient-boosted trees, the learning rate (eta or shrinkage) scales how much each new tree contributes. Smaller values, such as 0.05, usually generalize better but need more trees.