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.
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.
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 torchfrom transformers import AutoTokenizer, AutoModelForCausalLMname = "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
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.
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.