Learning path: End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing · Step 14 of 16
Ticket Routing, Part 2: Fine-Tuning a Small Encoder on a CPU, With a Run Log and Honest Ranges
Fine-tune a 22.7-million-weight encoder (all-MiniLM-L6-v2, Apache 2.0) to route synthetic tickets on a CPU in about 48 seconds. It scores 0.887 [0.831, 0.931] against TF-IDF's 0.669, the whole gap comes from tickets with new words (0.885 vs 0.436), and vague tickets stay stuck at 0.286.
What you will learn
- Check a pretrained encoder's size and licence before using it
- Fine-tune all-MiniLM-L6-v2 with a four-label head on a CPU
- Write a run log with config, commit and a data hash so a result can be repeated
- Compare the encoder with the baselines per slice, with bootstrap ranges and seeds
Before you start
- Ticket Routing, Part 1: A Safe Split, Keyword Rules and a TF-IDF Baseline
- Pretrained Models from Hugging Face: A Sentiment Pipeline and Sentence Embeddings on a CPU
- A PyTorch training loop
In Part 1 our ticket router got a score to beat: TF-IDF at 0.669, and only 0.436 on tickets that use new words. Now we try a small model. We'll pick a small encoder and check we're allowed to use it, fine-tune it on a plain CPU, write down exactly how we trained it, and compare it on tickets it never saw, one slice at a time.
Same synthetic tickets, same safe split: 941 for training, 157 for validation, 160 for test.
A new colleague
Think about a new colleague on their first day. You don't teach them to read; they spent years learning that, and it came with them. What you teach them is your filing system: this kind of letter goes in this drawer, that kind in that one. A few days of examples and they're sorting letters with words you never showed them, because they already know what those words mean. That's fine-tuning. Someone else paid for the reading. We only teach the filing.
What a small encoder brings
Our colleague is sentence-transformers/all-MiniLM-L6-v2. It was trained on lots of text by someone else, so package and parcel aren't strangers to it. The words go in, and it turns the whole ticket into a position in a space of meaning; tickets that mean similar things should land near each other. On top we add one new layer with four outputs, one per queue. That layer is the only part starting from scratch.
Before using any model, check two things. Size: about 22.7 million weights, which a CPU can handle. Licence: Apache 2.0 according to its Hugging Face model card, which allows commercial use. (Running pretrained models with no training is in Pretrained Models from Hugging Face.)
Fine-tuning on a CPU: encoder.py
"""Fine-tune a small encoder (22M weights) on CPU."""
import random
import numpy as np
import torch
from transformers import (AutoModelForSequenceClassification,
AutoTokenizer)
from data import QUEUES
NAME = "sentence-transformers/all-MiniLM-L6-v2"
def seed_all(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
def batches(rows, tok, size, shuffle, rng):
idx = list(range(len(rows)))
if shuffle:
rng.shuffle(idx)
for i in range(0, len(idx), size):
part = [rows[j] for j in idx[i:i + size]]
enc = tok([r["text"] for r in part], padding=True,
truncation=True, max_length=48,
return_tensors="pt")
y = torch.tensor([QUEUES.index(r["label"])
for r in part])
yield enc, y
def train_encoder(rows, seed=0, epochs=3, lr=5e-5):
seed_all(seed)
tok = AutoTokenizer.from_pretrained(NAME)
model = AutoModelForSequenceClassification.from_pretrained(
NAME, num_labels=len(QUEUES))
opt = torch.optim.AdamW(model.parameters(), lr=lr)
rng = random.Random(seed)
losses = []
model.train()
for ep in range(epochs):
total, n = 0.0, 0
for enc, y in batches(rows, tok, 32, True, rng):
out = model(**enc, labels=y)
out.loss.backward()
opt.step()
opt.zero_grad()
total += out.loss.item()
n += 1
losses.append(round(total / n, 4))
model.eval()
return model, tok, losses
We load the tokenizer and the model and ask for four labels. Then AdamW with a small learning rate, 5e-5, because these weights are already good and we only want to nudge them. The loop is the usual one: a batch of 32 tickets goes forward, we get a loss, it goes backward, the optimizer steps, and we clear the gradients. (The loop itself is taught in the PyTorch training loop article.)
train loss per epoch [1.0472, 0.4041, 0.2406]
The loss comes down over three epochs. That's training loss, so it proves nothing yet about new words. And it has a cost: the baselines took about 2 seconds; this took about 48 seconds.
Write down how you trained it: run_log.py
A score you can't repeat isn't worth much. So there's a tiny file that trains once and records everything:
"""Train once, and write down exactly how it was done."""
import hashlib
import json
import subprocess
from data import make_tickets, split_by
from encoder import NAME, encoder_predict, train_encoder
from report import accuracy
CONFIG = {"model": NAME, "license": "apache-2.0",
"seed": 0, "epochs": 3, "lr": 5e-5, "batch": 32}
def data_version(rows):
raw = json.dumps(rows, sort_keys=True).encode()
return hashlib.sha256(raw).hexdigest()[:12]
def commit():
out = subprocess.run(
["git", "rev-parse", "--short", "HEAD"],
capture_output=True, text=True)
return out.stdout.strip() or "none"
python run_log.py writes run_log.json and prints:
{
"model": "sentence-transformers/all-MiniLM-L6-v2",
"license": "apache-2.0",
"seed": 0,
"epochs": 3,
"lr": 5e-05,
"batch": 32,
"commit": "none",
"data": "8e4c7014012f",
"losses": [
1.0472,
0.4041,
0.2406
],
"acc": {
"val": 0.854,
"test": 0.887
}
}
same code, other data: 13dded0ca816
- Config: model name, licence, seed, epochs, learning rate and batch size.
- Commit ties the result to the code. It says
nonehere because the project folder isn't a git repository. In your project you'd want a hash there. - Data version: every ticket is hashed into a short code. Same tickets, same code. Change the data seed and the code changes (
13dded0ca816). - Results go in too.
Training again with this file gave the same losses, digit for digit, so the run can be repeated, on this machine at least. For a fuller version of this idea with a tracking server, see Experiment Tracking with MLflow.
One number needs an interval
On the test group the encoder gets 142 of 160 right, which prints as 0.887. But 160 isn't many. So interval in report.py redraws those hits and misses with replacement 1,000 times and keeps the middle 95%:
def interval(rows, preds, n_boot=1000, seed=0):
"""95 percent bootstrap interval of accuracy."""
rng = np.random.default_rng(seed)
hits = np.array([p == r["label"]
for r, p in zip(rows, preds)], float)
means = [rng.choice(hits, len(hits)).mean()
for _ in range(n_boot)]
return float(np.percentile(means, 2.5)), \
float(np.percentile(means, 97.5))
That gives [0.831, 0.931]. TF-IDF's range tops out at 0.738, so the encoder clears it. Validation came in at 0.854, lower than test. That's not a win or a worry; it's noise, inside the same range. And three training seeds gave:
seed 0 encoder acc=0.887
seed 1 encoder acc=0.869
seed 2 encoder acc=0.875
So quote the range, not the best seed, and do any picking on validation, never on test.
Slices show where it wins
python compare.py encoder:
train loss per epoch [1.0472, 0.4041, 0.2406]
encoder
all n= 160 acc=0.887 [0.831, 0.931]
email n= 75 acc=0.840 [0.760, 0.920]
chat n= 85 acc=0.929 [0.871, 0.976]
new words n= 78 acc=0.885 [0.808, 0.949]
vague n= 21 acc=0.286 [0.095, 0.476]
- Email vs chat: 0.840 against 0.929. Those ranges overlap, so I wouldn't read much into it.
- New words, 78 tickets: rules 0.231, TF-IDF 0.436, encoder 0.885. That's the whole gap, right there. "consignment and package": rules say technical, TF-IDF says billing, the encoder says shipping, which is right. The training tickets never had those words; the pretrained weights brought them.
The slice nobody wins
Vague tickets, only 21 of them. The encoder gets 0.286, exactly the same as TF-IDF; with four queues, that's about what guessing gets you. Here's why: "please look into this" appears once labelled billing and once labelled login. Same words, two right answers. And that's built into data.py: it picks the queue first, and the vague sentence has nothing to do with it. A bigger model won't fix this. The information just isn't there.
One more honest point. I wrote the new words as synonyms of the old ones, and that suits an encoder well. So believe the method, and measure the gap again on your own tickets. Before you fine-tune anything bigger, When NOT to Fine-Tune is worth a read.
Common mistakes
- Skipping the licence check. Read the model card before the model goes anywhere near a product.
- Trusting training loss. 0.2406 says nothing about tickets with new words.
- Quoting one test number. On 160 tickets, report the range and the seed spread.
- Picking the best seed on test. Choose on validation; test is for the final report.
- No run log. Without config, commit and data version, nobody can repeat the result.
Recap
| Model | All (160) | New words (78) | Vague (21) | Time |
|---|---|---|---|---|
| Rules | 0.550 | 0.231 | 0.048 | no training |
| TF-IDF | 0.669 | 0.436 | 0.286 | about 2 s |
| MiniLM fine-tuned | 0.887 [0.831, 0.931] | 0.885 | 0.286 | about 48 s |
Try it yourself: in run_log.py, set seed to 1 in CONFIG and run it again. Guess first which fields will change.
In Part 3, we shrink this encoder, put it behind FastAPI and measure the server.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Ticket Routing, Part 1: A Safe Split, Keyword Rules and a TF-IDF Baseline
Next →Ticket Routing, Part 3: Quantise to int8, Host Behind FastAPI and Measure the Server
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
The whole ML workflow on 205 cars: clean the brand out of CarName, split first, audition five regressors on the same folds, tune the random forest, test once (RMSE 2,195, R2 0.939), save it and serve prices with FastAPI.
Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
Before training a fraud model, write down what good means. On 6,000 synthetic validation transactions, a rule that never flags is 96.13% accurate and costs 23,200, flagging everyone costs 28,840, and a small contract.py fixes the rules first.
Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
Train the fraud model against its contract: a time split of 30,000 synthetic transactions, a card_n_1h feature that never looks ahead, XGBoost that pays 23,200 at 0.5, and a cost-picked threshold of 0.045 that brings validation to 14,955 and test to 16,765.
Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
A payment is waiting on the fraud score. Time each stage (the model takes 0.43 ms of a 3.3 ms request), then load test: p99 is 6.1 ms with one client and 163.3 ms with 32, against an example 50 ms budget. Then a Dockerfile, built and run once.