AI Hints
Home›Fine-Tuning LLMs Tutorial›Results, Loss and Hyperparameters
Fine-Tuning LLMs · Lesson 53 of 120

Reading the Loss

Is training working?.

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

While training runs, the loss is your main window into what's happening. Learning to read it will save you hours of wasted training. Let's look at a run that goes wrong.

  • The loss is your window
  • Read it, save hours
  • A run that goes wrong

A learning rate that is too small

Here's the same training, but with a learning rate one hundred times smaller. Everything else is unchanged. Run it. The loss stays flat, near one point eight seven, the whole time. Compare that with our good run, which fell to zero point zero four. Tiny steps mean the model barely changes. Two minutes of training, for nothing.

app.pypython
from sft import trainer

trainer.args.learning_rate = 2e-6          # 100 times smaller than before
trainer.train()
for log in trainer.state.log_history:
    if "loss" in log:
        print(f"step {log['step']:2}: train loss {log['loss']:.3f}")
Output
step 11: train loss 1.873
step 22: train loss 1.842
step 33: train loss 1.870
step 44: train loss 1.847
step 55: train loss 1.911
step 66: train loss 1.893
Also uses chat.py
import json
from datasets import load_dataset

SYSTEM = "Read the customer's message. Reply with JSON: the intent and the book."

def to_example(row):
    answer = json.dumps({"intent": row["intent"], "book": row["book"]})
    return {"prompt": [{"role": "system", "content": SYSTEM},
                       {"role": "user", "content": row["message"]}],
            "completion": [{"role": "assistant", "content": answer}]}

data = load_dataset("json", data_files={"train": "tickets_train.jsonl",
                                        "test": "tickets_test.jsonl"})
data = data.map(to_example, remove_columns=["message", "intent", "book"])
Also uses ask.py
from chat import SYSTEM

def ask(model, tok, message):
    model.eval()                       # switch off training-only behaviour
    messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": message}]
    ids = tok.apply_chat_template(messages, add_generation_prompt=True,
                                  return_dict=True, return_tensors="pt")
    out = model.generate(**ids, max_new_tokens=30, do_sample=False)
    return tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)
Also uses sft.py
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import LoraConfig
from trl import SFTTrainer, SFTConfig
from chat import data

NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(NAME)
model = AutoModelForCausalLM.from_pretrained(NAME)
lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
                  target_modules="all-linear", task_type="CAUSAL_LM")
args = SFTConfig(output_dir="ticket-lora", num_train_epochs=1, learning_rate=2e-4,
                 per_device_train_batch_size=8, logging_steps=11,
                 eval_strategy="steps", eval_steps=22,
                 save_strategy="no", report_to="none")
trainer = SFTTrainer(model=model, args=args, train_dataset=data["train"],
                     eval_dataset=data["test"], processing_class=tok, peft_config=lora)

What the loss tells you

Here's how to read a loss curve. Falling steadily, then flattening, is healthy. Flat from the start means the learning rate is too low, or the data is broken. Jumping up and down wildly, or becoming not a number, means the learning rate is too high. And training loss falling while eval loss rises means overfitting.

You seeIt means
falls, then flattenshealthy
flat from the startlearning rate too low, or bad data
wild jumps, or NaNlearning rate too high
train ↓, eval ↑overfitting

Summary

Let's recap. A healthy loss falls, then flattens. Flat means too little learning. Wild jumps mean too much. And a rising eval loss means overfitting. Next, the settings that matter most.

Key takeaways
  • Falls then flattens
  • Flat: lr too low
  • Train ↓ eval ↑: overfitting
Next up: Hyperparameters That Matter — what to tune first