AI Hints
Home›Fine-Tuning LLMs Tutorial›Classification Fine-Tuning
Fine-Tuning LLMs · Lesson 30 of 120

A Classification Model

DistilBERT with a new head.

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

Let's load our model, and see what it does before any training. This 'before' picture will make the 'after' picture much more impressive.

  • Load the model
  • Before any training
  • A picture to compare with

Before training

Auto model for sequence classification loads Distil BERT, and adds a new head, for five labels. We also give it our label names. Then we print the head. And we ask the untrained model to classify one message. Run it. The head is one linear layer, seven hundred and sixty eight numbers in, five scores out. Its weights are random. So the model spreads its guesses almost evenly. It has no idea yet.

app.pypython
import torch
from transformers import AutoModelForSequenceClassification
from prep import tok, MODEL, id2label, label2id

model = AutoModelForSequenceClassification.from_pretrained(
    MODEL, num_labels=5, id2label=id2label, label2id=label2id)
print(model.classifier)
inputs = tok("Where is my copy of Dune?", return_tensors="pt")
with torch.no_grad():
    probs = torch.softmax(model(**inputs).logits, dim=-1)[0]
for i, p in enumerate(probs):
    print(f"{id2label[i]:13} {p:.0%}")
Output
Linear(in_features=768, out_features=5, bias=True)
order_status  19%
return        19%
price         23%
stock         23%
complaint     17%
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)

Full fine-tuning

For this small model, we'll train every weight. The reading part, and the new head. That's called full fine-tuning. It works well here, because Distil BERT only has sixty six million parameters. For big language models, full fine-tuning gets too expensive. That's where LoRA comes in, later.

keyvalue
Full fine-tuningtrain every weight
DistilBERT66 million parameters
Herecheap and easy
Big LLMsuse LoRA instead

Summary

Let's recap. Auto model for sequence classification adds a new head. Before training, the head is random, so the guesses are even. And we'll fully fine-tune this small model. Next, the Trainer, which does the training for us.

Key takeaways
  • AutoModelForSequenceClassification
  • Random head at first
  • Full fine-tuning
Next up: Trainer and TrainingArguments — the training loop, done for you