AI Hints
Home›Fine-Tuning LLMs Tutorial›Training with the Trainer
Fine-Tuning LLMs · Lesson 32 of 120

Train It

Our first fine-tuning run.

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

Everything is ready. Model, data, settings. Let's run our first fine-tuning, and watch the model learn.

  • Everything is ready
  • Our first run
  • Watch it learn

Fine-tune!

We import the trainer from train dot p y. Calling train runs the whole loop. Afterwards, the log history holds what happened. We print the test results, after each epoch. Run it. After one epoch, the model already gets almost ninety five percent of unseen messages right. After two, it gets all of them. And training took only seconds.

app.pypython
from train import trainer

trainer.train()
for log in trainer.state.log_history:
    if "eval_accuracy" in log:
        print(f"epoch {log['epoch']:.0f}: eval loss {log['eval_loss']:.3f}, "
              f"accuracy {log['eval_accuracy']:.1%}")
Output
epoch 1: eval loss 0.546, accuracy 94.8%
epoch 2: eval loss 0.217, accuracy 100.0%
Also uses prep.py
from datasets import load_dataset
from transformers import AutoTokenizer

INTENTS = ["order_status", "return", "price", "stock", "complaint"]
label2id = {name: i for i, name in enumerate(INTENTS)}
id2label = {i: name for i, name in enumerate(INTENTS)}
MODEL = "distilbert/distilbert-base-uncased"
tok = AutoTokenizer.from_pretrained(MODEL)

def prepare(row):
    enc = tok(row["message"], truncation=True, max_length=32)
    enc["label"] = label2id[row["intent"]]
    return enc

data = load_dataset("json", data_files={"train": "tickets_train.jsonl",
                                        "test": "tickets_test.jsonl"})
data = data.map(prepare, remove_columns=["message", "intent", "book"])
Also uses train.py
import numpy as np
from transformers import (AutoModelForSequenceClassification, DataCollatorWithPadding,
                          Trainer, TrainingArguments)
from prep import tok, data, MODEL, label2id, id2label

model = AutoModelForSequenceClassification.from_pretrained(
    MODEL, num_labels=5, id2label=id2label, label2id=label2id)
args = TrainingArguments(output_dir="intent-model", num_train_epochs=2,
                         per_device_train_batch_size=16, learning_rate=5e-5,
                         eval_strategy="epoch", logging_strategy="epoch",
                         save_strategy="no", report_to="none")

def accuracy(pred):
    return {"accuracy": (np.argmax(pred.predictions, -1) == pred.label_ids).mean()}

trainer = Trainer(model=model, args=args, train_dataset=data["train"],
                  eval_dataset=data["test"], data_collator=DataCollatorWithPadding(tok),
                  compute_metrics=accuracy)

Why so fast, and so good?

Why did it learn so quickly? Because Distil BERT already understands English. It learned that during pretraining. We only taught it how to map meaning, to our five intents. That's the power of fine-tuning. A little data, on top of a lot of knowledge.

keyvalue
Pretrainingalready knows English
Fine-tuningmaps meaning to intents
Neededa little data
Resultfast and accurate

Summary

Let's recap. Trainer dot train runs the whole training loop. The log history records the loss, and accuracy. And with a pretrained model, a few hundred examples are enough. Next, testing the model more carefully.

Key takeaways
  • trainer.train()
  • log_history
  • Little data, big results
Next up: Evaluate It — beyond one number