Lab: Fine-Tune a Pretrained Encoder for Classification
Fine-tune a small pretrained BERT encoder from the Hugging Face Hub to classify support tickets, with its own tokenizer, a pinned revision, a checked licence, a warm-up schedule and a small learning rate; compare it on the same splits with a TF-IDF plus logistic regression baseline and with the same network trained from scratch, over several seeds, on normal and newly worded tickets, and weigh the gain against the cost per prediction.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Generate the tickets
- Step 2: The baseline first
- Step 3: Check the model card, tokenizer and model
- Step 4: Fine-tune
- Step 5: Seeds and a from-scratch control
- Step 6: The cost per prediction
- Check your understanding
- Apply it
- Review prompt
Lessons of Transformer Architecture
- Attention as Soft Lookup: Queries, Keys and Values Concept · 20 min
- Lab: Build Multi-Head Causal Self-Attention from Scratch Lab · 30 min
- Anatomy of a Transformer Block and the Three Model Families Concept · 25 min
- Tokens In, Tokens Out: Tokenizers, Decoding Controls and the KV Cache Concept · 25 min
- Lab: Fine-Tune a Pretrained Encoder for Classification Lab · 30 min
- Check: Inside the Transformer Knowledge check · 8 questions
What you will learn
- Fine-tune a pretrained encoder (for example a BERT-family model) for text classification with Hugging Face Transformers and compare it with a classical baseline.
Prerequisites: Deep Learning Fundamentals
01. Goal and setup
Fine-tuning takes a model that was pretrained on a large amount of text, here with masked-token prediction as described in the lesson on model families, adds a small task-specific layer, and trains everything briefly on your labelled data. The pretrained weights already encode a lot about words and how they combine, so the model needs few examples and can cope with wording it has not seen in training. Whether that is worth its cost is a measurement, not a belief, so this lab measures it against two references: a classical baseline and the same network trained from random weights.
The task is routing support tickets into four categories. The tickets are generated with a seed, so everyone gets the same data, and they come in two test sets: one worded like the training data, and a paraphrase set that describes the same problems with words the training data never uses ("debited two times" instead of "charged twice"). That second set imitates what happens after deployment, when users write in their own words.
You need: Python 3.12, PyTorch 2 (CPU build), Transformers 5 and scikit-learn 1.9, about 150 MB of disk and an internet connection for the first download of the model, google/bert_uncased_L-4_H-256_A-4 (BERT-mini, 11 million parameters; the download is under 100 MB). Results are seeded; on other versions or CPUs the third decimal may differ. Each fine-tuning run takes about a minute on a laptop CPU.
finetune-lab/
├── tickets.py step 1: writes train, val, test and paraphrase CSV files
├── baseline.py step 2: TF-IDF + logistic regression
├── settings.py step 3: model name and pinned revision
├── inspect_model.py step 3: licence, tokenizer, model parts
├── finetune.py step 4: fine-tuning loop (also --scratch)
└── latency.py step 6: time per predictionmkdir finetune-lab && cd finetune-lab
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install "torch==2.15.*" \
--index-url https://download.pytorch.org/whl/cpu
python -m pip install "transformers==5.23.*" "scikit-learn==1.9.*"02. Step 1: Generate the tickets
"""Seeded support tickets in four categories, plus a test set worded differently."""
import csv
import random
LABELS = ["billing", "delivery", "account", "technical"]
# Phrases used for training and the normal test set ...
SEEN = {
"billing": ["I was charged twice", "the invoice amount is wrong", "I want a refund",
"my payment failed", "there is an extra fee on my bill"],
"delivery": ["my parcel has not arrived", "the courier lost my package",
"the order is late", "the tracking number does not work",
"the box came damaged"],
"account": ["I cannot log in", "I forgot my password", "my account is locked",
"I want to change my email address", "the login code never comes"],
"technical": ["the app crashes on start", "the page shows an error",
"the screen freezes", "the upload button does nothing",
"the website is very slow"],
}
# ... and different wording for the same problems, used only in the paraphrase test
UNSEEN = {
"billing": ["the same purchase was debited two times", "I would like my money back",
"the receipt shows the wrong total", "my card was declined",
"an unexpected surcharge appeared"],
"delivery": ["the shipment never showed up", "the postman left nothing",
"my goods are overdue", "the shipping status is stuck",
"the item was broken in transit"],
"account": ["I am unable to sign in", "I do not remember my passcode",
"my profile has been suspended", "I need to update my e-mail",
"the verification text is missing"],
"technical": ["the program quits immediately", "the site displays a fault",
"everything hangs", "attaching a file fails silently",
"loading takes forever"],
}
OPENERS = ["Hello,", "Hi team,", "Good morning,", "Help!", "Dear support,", ""]
CLOSERS = ["Please help.", "Thanks.", "What should I do?", "This is urgent.", ""]
def make(phrases, n, rng):
rows = []
for _ in range(n):
label = rng.choice(LABELS)
parts = (rng.choice(OPENERS), rng.choice(phrases[label]) + ".",
rng.choice(CLOSERS))
text = " ".join(p for p in parts if p) # skip empty opener or closer
rows.append((text, label))
return rows
if __name__ == "__main__":
rng = random.Random(0)
splits = {"train": make(SEEN, 400, rng), "val": make(SEEN, 100, rng),
"test": make(SEEN, 200, rng), "paraphrase": make(UNSEEN, 200, rng)}
for name, rows in splits.items():
with open(f"{name}.csv", "w", newline="") as f:
csv.writer(f).writerows([("text", "label"), *rows])
print(f"{name:10} {len(rows)} tickets, e.g. {rows[0][0]!r}")python tickets.pytrain 400 tickets, e.g. 'Help! the app crashes on start. What should I do?'
val 100 tickets, e.g. 'Hi team, the page shows an error. What should I do?'
test 200 tickets, e.g. 'Help! the page shows an error. Thanks.'
paraphrase 200 tickets, e.g. 'Dear support, I need to update my e-mail. Thanks.'Training, validation and the normal test set use the SEEN phrases; the paraphrase set uses only UNSEEN ones. Real tickets are messier than these templates, so treat the numbers below as a controlled experiment, not as a forecast for your data.
03. Step 2: The baseline first
TF-IDF turns each text into a vector with one entry per word or word pair, weighted by how often it appears in this text and how rare it is in the collection; logistic regression then learns one weight per entry and class. It is fast, cheap and often strong for text classification, which makes it the reference any bigger model must beat. Macro-F1 averages the F1 score of each class, so every category counts equally.
"""TF-IDF features and logistic regression: the classical baseline."""
import csv
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
from sklearn.pipeline import make_pipeline
def read(name):
with open(f"{name}.csv") as f:
rows = list(csv.DictReader(f))
return [r["text"] for r in rows], [r["label"] for r in rows]
if __name__ == "__main__":
model = make_pipeline(TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True),
LogisticRegression(max_iter=1000, C=10))
model.fit(*read("train"))
for split in ("test", "paraphrase"):
texts, labels = read(split)
f1 = f1_score(labels, model.predict(texts), average="macro")
print(f"TF-IDF + logistic regression, {split:10} macro-F1 {f1:.3f}")python baseline.pyTF-IDF + logistic regression, test macro-F1 1.000
TF-IDF + logistic regression, paraphrase macro-F1 0.318On tickets worded like the training data, the baseline is perfect. On the paraphrases it falls to 0.318, not far above the 0.25 of guessing: almost every informative word in a paraphrase is a word it never saw, and an unseen word has no weight.
04. Step 3: Check the model card, tokenizer and model
Before using a model from the Hugging Face Hub, read its model card: what it was trained on, its intended uses and limits, and its licence, which decides whether you may use it commercially. Pin the revision, the commit hash of the files, so that a later update to the repository cannot silently change your results; settings.py holds both, and every later script imports them. Always load the tokenizer from the same checkpoint as the model: token ids are row numbers in the model's embedding table, so a different vocabulary would feed it the wrong vectors.
"""The model to fine-tune, pinned to one commit of its Hub repository."""
MODEL = "google/bert_uncased_L-4_H-256_A-4"
REVISION = "387825ce42dbb39b87911cdf8e383ee3b25184f8" # pin the exact files"""Read the model card metadata, then look at the tokenizer and the model."""
from huggingface_hub import model_info
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from settings import MODEL, REVISION
info = model_info(MODEL, revision=REVISION)
print("licence on the model card:", info.card_data.license)
tokenizer = AutoTokenizer.from_pretrained(MODEL, revision=REVISION)
enc = tokenizer("Help! the courier lost my package.")
print("tokens:", tokenizer.convert_ids_to_tokens(enc["input_ids"]))
print("vocabulary size:", tokenizer.vocab_size)
model = AutoModelForSequenceClassification.from_pretrained(MODEL, revision=REVISION,
num_labels=4)
body = sum(p.numel() for p in model.bert.parameters())
head = sum(p.numel() for p in model.classifier.parameters())
print(f"pretrained encoder {body:,} parameters, new classification head {head:,}")python inspect_model.pylicence on the model card: apache-2.0
tokens: ['[CLS]', 'help', '!', 'the', 'courier', 'lost', 'my', 'package', '.', '[SEP]']
vocabulary size: 30522
pretrained encoder 11,170,560 parameters, new classification head 1,028The licence is Apache 2.0, which allows commercial use with attribution. The tokenizer is WordPiece with a 30,522-token vocabulary; it lowercases text and adds the special tokens [CLS] at the start and [SEP] at the end. AutoModelForSequenceClassification puts a new classification layer of 1,028 parameters (256 × 4 weights plus 4 biases) on the pooled [CLS] representation of the 11-million-parameter encoder. That layer is randomly initialised, so Transformers prints a load report listing it as MISSING (newly initialised) and the checkpoint's unused pretraining heads as UNEXPECTED. This is expected when you fine-tune.
05. Step 4: Fine-tune
The loop is the ordinary PyTorch loop from earlier lessons, with three details specific to fine-tuning. DataCollatorWithPadding pads each batch to its own longest ticket and builds the attention mask that tells the encoder which positions are padding. Passing labels makes the model compute the cross-entropy loss itself. And the optimizer uses a small learning rate, 5e-5, with a linear warm-up over the first 10% of steps and a linear decay after it. Pretrained weights are already good; large updates, especially in the first steps when the new head is still random and its gradients are noisy, can overwrite what pretraining learned. The BERT authors fine-tuned with rates between 2e-5 and 5e-5, a useful starting range. --scratch builds the same architecture from its configuration with random weights, for step 5.
"""Fine-tune a small pretrained BERT encoder for ticket classification."""
import argparse
import torch
from sklearn.metrics import f1_score
from torch.utils.data import DataLoader
from transformers import (AutoConfig, AutoModelForSequenceClassification,
AutoTokenizer, DataCollatorWithPadding,
get_linear_schedule_with_warmup)
from baseline import read
from settings import MODEL, REVISION
from tickets import LABELS
def encode(tokenizer, split):
texts, labels = read(split)
enc = tokenizer(texts, truncation=True, max_length=64)
return [{"input_ids": i, "attention_mask": m, "labels": LABELS.index(y)}
for i, m, y in zip(enc["input_ids"], enc["attention_mask"], labels)]
def evaluate(model, loader):
model.eval()
preds, gold = [], []
with torch.no_grad():
for batch in loader:
labels = batch.pop("labels")
preds += model(**batch).logits.argmax(-1).tolist()
gold += labels.tolist()
return f1_score(gold, preds, average="macro")
def main(args):
torch.manual_seed(args.seed)
tokenizer = AutoTokenizer.from_pretrained(MODEL, revision=REVISION)
if args.scratch: # same architecture, random weights: what does pretraining add?
config = AutoConfig.from_pretrained(MODEL, revision=REVISION,
num_labels=len(LABELS))
model = AutoModelForSequenceClassification.from_config(config)
else:
model = AutoModelForSequenceClassification.from_pretrained(
MODEL, revision=REVISION, num_labels=len(LABELS))
collate = DataCollatorWithPadding(tokenizer) # pads each batch to its longest
g = torch.Generator().manual_seed(args.seed)
train = DataLoader(encode(tokenizer, "train"), batch_size=16, shuffle=True,
collate_fn=collate, generator=g)
evals = {s: DataLoader(encode(tokenizer, s), batch_size=64, collate_fn=collate)
for s in ("val", "test", "paraphrase")}
opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=0.01)
steps = args.epochs * len(train)
sched = get_linear_schedule_with_warmup(opt, int(0.1 * steps), steps)
for epoch in range(1, args.epochs + 1):
model.train()
for batch in train:
loss = model(**batch).loss # cross-entropy computed inside the model
opt.zero_grad()
loss.backward()
opt.step()
sched.step()
if not args.quiet:
print(f"seed {args.seed} epoch {epoch}: last batch loss {loss.item():.3f}, "
f"val macro-F1 {evaluate(model, evals['val']):.3f}")
name = "from scratch" if args.scratch else "pretrained"
for split in ("test", "paraphrase"):
print(f"seed {args.seed} {name}, {split:10} macro-F1 "
f"{evaluate(model, evals[split]):.3f}")
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("--lr", type=float, default=5e-5)
p.add_argument("--epochs", type=int, default=6)
p.add_argument("--scratch", action="store_true")
p.add_argument("--quiet", action="store_true")
p.add_argument("--seed", type=int, default=0)
main(p.parse_args())python finetune.pyseed 0 epoch 1: last batch loss 1.237, val macro-F1 0.480
seed 0 epoch 2: last batch loss 0.887, val macro-F1 0.900
seed 0 epoch 3: last batch loss 0.662, val macro-F1 0.989
seed 0 epoch 4: last batch loss 0.420, val macro-F1 1.000
seed 0 epoch 5: last batch loss 0.349, val macro-F1 1.000
seed 0 epoch 6: last batch loss 0.341, val macro-F1 1.000
seed 0 pretrained, test macro-F1 1.000
seed 0 pretrained, paraphrase macro-F1 0.632Validation macro-F1 reaches 1.000 by epoch 4, and the test set is also perfect, so on familiar wording the encoder only ties with the baseline. On the paraphrases it scores 0.632, twice the baseline. The words are new to the classifier, but not to the encoder: during pretraining it met words such as "debited" and "charged" or "shipment" and "parcel" in similar contexts, so their representations are already related, and fine-tuning only has to connect them to the right labels.
06. Step 5: Seeds and a from-scratch control
One run is one sample. Fine-tuning results change with the random seed, which sets the new head's initial weights, the dropout masks and the batch order. Two more seeds show the spread. Three runs from scratch then answer a different question: is the gain due to pretraining, or would any transformer do? A randomly initialised network needs a larger learning rate to learn anything in six epochs, so it gets 1e-3.
for s in 1 2; do python finetune.py --seed $s --quiet; done
for s in 0 1 2; do python finetune.py --scratch --lr 1e-3 --seed $s --quiet; doneseed 1 pretrained, test macro-F1 1.000
seed 1 pretrained, paraphrase macro-F1 0.507
seed 2 pretrained, test macro-F1 1.000
seed 2 pretrained, paraphrase macro-F1 0.579
seed 0 from scratch, test macro-F1 1.000
seed 0 from scratch, paraphrase macro-F1 0.457
seed 1 from scratch, test macro-F1 1.000
seed 1 from scratch, paraphrase macro-F1 0.249
seed 2 from scratch, test macro-F1 1.000
seed 2 from scratch, paraphrase macro-F1 0.282Over three seeds, the pretrained encoder scores 0.507 to 0.632 on paraphrases, a mean of about 0.57. The same network from scratch learns the training wording just as well (1.000 on the normal test) but scores 0.249 to 0.457 on paraphrases, a mean of about 0.33, close to the baseline. So the gain on new wording comes from pretraining, not from the architecture. The spread between seeds is large: comparing single runs, the gap could look as large as 0.38 (0.632 against 0.249) or as small as 0.05 (0.507 against 0.457). Always report several seeds, ideally with the mean and the range.
07. Step 6: The cost per prediction
"""Time per ticket for the baseline and the encoder, one ticket at a time on a CPU."""
import time
import torch
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from baseline import read
from settings import MODEL, REVISION
texts, labels = read("train")
tests = read("test")[0][:100]
baseline = make_pipeline(TfidfVectorizer(ngram_range=(1, 2)), LogisticRegression())
baseline.fit(texts, labels)
tokenizer = AutoTokenizer.from_pretrained(MODEL, revision=REVISION)
model = AutoModelForSequenceClassification.from_pretrained(
MODEL, revision=REVISION, num_labels=4).eval()
def per_item(fn):
fn(tests[0]) # warm-up
start = time.perf_counter()
for t in tests:
fn(t)
return (time.perf_counter() - start) / len(tests) * 1000
with torch.no_grad():
enc_ms = per_item(lambda t: model(**tokenizer(t, return_tensors="pt")).logits)
base_ms = per_item(lambda t: baseline.predict([t]))
print(f"TF-IDF + logistic regression: {base_ms:.2f} ms per ticket")
print(f"encoder (11M parameters): {enc_ms:.2f} ms per ticket "
f"({enc_ms / base_ms:.0f}x)")python latency.pyTF-IDF + logistic regression: 1.18 ms per ticket
encoder (11M parameters): 13.36 ms per ticket (11x)Your times will differ, but on a CPU the encoder is typically an order of magnitude slower per ticket than the baseline, and larger encoders cost more still. Now the decision has numbers. If tickets in production look like the training data, the baseline is as accurate and much cheaper. If users phrase things in many ways, the encoder wins clearly on the paraphrase slice, and the question becomes whether milliseconds per ticket on a CPU, or a GPU for high volume, are worth it. Check this on real, labelled production tickets before you decide: synthetic paraphrases are only a proxy.
08. Check your understanding
09. Apply it
For the second part of the practice project:
- Replace the generated tickets with a labelled text dataset of your own, split it once, and save the split.
- Run the baseline and three seeds of fine-tuning, and report the mean and range of macro-F1 for each, overall and on one slice that matters to you (for example short texts or a rare class).
- Measure latency per prediction for both, and write a short recommendation that weighs the gap against the cost.
10. Review prompt
Without looking back, explain what fine-tuning changes in a pretrained encoder and what the new head is; why the tokenizer must match the checkpoint; why fine-tuning uses small learning rates with warm-up; what to read on a model card and why to pin a revision; what the baseline, the seeds and the from-scratch control each tell you; and how you would decide whether the encoder is worth its cost.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.