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

Loss

Measuring mistakes.

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

To improve at something, you need to know how wrong you are. A model is the same. The number that measures how wrong it is, is called the loss. Training is simply the search for a smaller loss.

  • How wrong are we?
  • That number is the loss
  • Training lowers the loss

Loss for language models

For a language model, the loss asks one question, at every token. How much probability did the model give to the token that really came next? If it gave high probability, the loss is small. If it gave low probability, the loss is big. This is called cross entropy loss.

keyvalue
At every tokenwas the real next token likely?
High probabilitysmall loss
Low probabilitybig loss
Namecross-entropy loss

Measure the loss

Let's measure it. We give the model two texts. A normal sentence, and the same words, shuffled. Passing labels makes the model compute the loss. The labels are the text itself, because the model must predict each next token. Run it. The normal sentence gets a loss of about four. The shuffled one gets over eight. The model is much more surprised by nonsense.

app.pypython
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

name = "HuggingFaceTB/SmolLM2-135M"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name)

for text in ["The cat sat on the mat.", "Mat the on sat cat the."]:
    inputs = tok(text, return_tensors="pt")
    with torch.no_grad():
        loss = model(**inputs, labels=inputs["input_ids"]).loss
    print(f"{text:25} loss = {loss.item():.2f}")
Output
The cat sat on the mat.   loss = 3.94
Mat the on sat cat the.   loss = 8.41

What fine-tuning does to the loss

Now we can say exactly what fine-tuning does. We take our examples, and measure the loss on them. At first, the loss is high, because the model doesn't know our task. Training changes the weights, a little at a time, to make that loss smaller. When the loss is low, the model predicts our answers well.

keyvalue
Starthigh loss on our examples
Trainingchange weights to lower it
Endlow loss
Meaningit predicts our answers

Summary

Let's recap. The loss measures how wrong the model is. For language models, it's cross entropy, at every token. Passing labels makes the model compute it. And training means making the loss smaller. Next, how the weights actually change.

Key takeaways
  • Loss = how wrong
  • Cross-entropy
  • Training lowers it
Next up: Gradients and Learning Rate — which way, and how far