AI Hints
Home›Fine-Tuning LLMs Tutorial›How Training Works
Fine-Tuning LLMs · Lesson 23 of 120

Gradients and Learning Rate

Which way, and how far.

⏱ 2 min read▶ Video at 37:14🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

We know the loss should go down. But a model has millions of weights. For each one, should it go up, or down? And by how much? Two ideas answer this. The gradient, and the learning rate.

  • Millions of weights
  • Up or down? How much?
  • Gradient and learning rate

Two ideas

The gradient tells us, for every weight, which direction makes the loss bigger. So we move each weight the opposite way. PyTorch works out all the gradients for us, with one call, named backward. The learning rate says how big each step is. This whole method is called gradient descent.

keyvalue
Gradientwhich way increases the loss
Sostep the opposite way
backward()computes every gradient
Learning ratethe size of each step

Gradient descent by hand

Here's the smallest possible example. Our data follows the rule, y equals three times x. The model has one weight, w, starting at zero. Each step, we measure the loss. Backward computes the gradient. Then we move w a small step, against the gradient, and reset the gradient. Run it. Watch w climb towards three, while the loss falls. That's training. A real model does exactly this, with millions of weights at once.

app.pypython
import torch

x = torch.tensor([1.0, 2.0, 3.0, 4.0])
y = torch.tensor([3.0, 6.0, 9.0, 12.0])       # the rule is y = 3 * x
w = torch.tensor(0.0, requires_grad=True)      # one weight, starts at 0
lr = 0.02

for step in range(1, 7):
    loss = ((w * x - y) ** 2).mean()           # how wrong are we?
    loss.backward()                            # gradient: which way to move w
    with torch.no_grad():
        w -= lr * w.grad                       # take a small step
        w.grad.zero_()
    print(f"step {step}: w = {w.item():.2f}  loss = {loss.item():.2f}")
Output
step 1: w = 0.90  loss = 67.50
step 2: w = 1.53  loss = 33.07
step 3: w = 1.97  loss = 16.21
step 4: w = 2.28  loss = 7.94
step 5: w = 2.50  loss = 3.89
step 6: w = 2.65  loss = 1.91

Choosing the learning rate

The learning rate matters a lot. Too small, and training takes forever. Too big, and the weights jump past the answer, and the loss explodes. For LoRA fine-tuning, a learning rate around two times ten to the minus four is a common start. For full fine-tuning, it's usually ten times smaller.

keyvalue
Too smallvery slow
Too bigloss jumps, or explodes
LoRA start2e-4
Full fine-tuning~2e-5

Summary

Let's recap. The gradient says which way each weight should move. Backward computes all the gradients. And the learning rate sets the step size. Together, that's gradient descent. Next, epochs, batches, and steps.

Key takeaways
  • Gradient = direction
  • backward()
  • Learning rate = step size
Next up: Epochs, Batches, Steps — how training is organised