Train It
Our first fine-tuning run.
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.
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%}")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.
| key | value |
|---|---|
| Pretraining | already knows English |
| Fine-tuning | maps meaning to intents |
| Needed | a little data |
| Result | fast 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