Project 13: Fine-Tuned Language Model
TAD Reviews, a fictional film site, shows a one-line reader review under every film and wants a label next to it: positive, negative, or "unsure" when the text is ambiguous. The label also sorts reviews, so its probability must mean what it says. The team already runs a TF-IDF model. Your job is to decide whether a fine-tuned transformer should replace it, and if so, to hand over a package that the serving team can load, call and document. Level: advanced. Main skills: a fixed evaluation protocol, fine-tuning on CPU, candidate selection on validation, one test, error analysis by linguistic phenomenon, calibration, packaging and a model card.
The course has fine-tuned this model on this data before. Fine-Tuning BERT for Text Classification showed how the head and the batches work and found a small win over TF-IDF on one subset; the training-strategies mini project compared scratch, feature extraction and LoRA across label budgets. This project does not re-teach either. It treats fine-tuning as one step of a delivery: every choice is made on validation by a rule written down first, the test set is opened once, and the output is a package plus a document, not a table of scores. The answer turns out less flattering for BERT than the earlier lessons suggest, which is exactly why the protocol matters.
Goal and success criteria
Fixed before any model was trained:
| Criterion | Target | Measured on |
|---|---|---|
| Accuracy of the shipped model | at least the TF-IDF baseline's, with the paired 95 % bootstrap interval of the difference reported | the 1,066 test sentences, once |
| Calibration: expected calibration error (10 bins) | at most 0.05 | test, after calibration fitted on validation |
| "Unsure" band | the narrowest band that leaves at least 80 % accuracy on answered reviews; report coverage | band chosen on validation, coverage on test |
| Latency | p95 below 50 ms per review, one review per call, CPU | 200 single calls |
| Package size | at most 50 MB | files on disk |
| Phenomena (negation, contrast, long) | reported, no target | validation |
Choices allowed on validation only: the TF-IDF regularisation , the learning rate, the epoch, and one of four pre-declared candidates (BERT alone, or a blend of BERT and TF-IDF probabilities with BERT weight ).
The data
rotten_tomatoes (the sentence-polarity data of Pang and Lee, 2005, cached in the course image): 8,530 training, 1,066 validation and 1,066 test sentences, lower-cased with spaces around punctuation, balanced labels. The project's labelling budget is 3,000 training sentences (a fixed shuffle with seed 1, a different sample from the earlier lessons), the full validation set for every choice, the full test set once. Its licence on the Hugging Face Hub is listed as "unknown", so treat it as research data. For TAD Reviews the real data would be its own readers' reviews: covered by the site's terms of use, checked for personal data (reviewers name actors, but also friends), and labelled by annotators with written guidelines on sarcasm and mixed reviews (privacy, consent and licensing, labels and ground truth). All steps are recorded examples (they need Transformers) except steps 4 and 6, which run in your browser.
Step 1: data, phenomena and the baseline
Before training anything, tag the phenomena the error analysis will look at, with rules fixed now so they cannot be tuned to the results: negation (not, no, never, n't, ...), contrast (but, yet, although, ...) and long sentences (more than 30 words). Then fit the baseline from text classification: TF-IDF of words and word pairs, vocabulary from the training sentences only, logistic regression with chosen on validation.
import re
import numpy as np
from datasets import load_dataset
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
train = ds["train"].shuffle(seed=1).select(range(3000)) # the labelling budget: 3,000 of 8,530 sentences
val, test = ds["validation"], ds["test"] # all 1,066 each; test is opened once, in step 3
print(f"train {len(train)} | val {len(val)} | test {len(test)} | positive share "
f"{np.mean(train['label']):.3f} / {np.mean(val['label']):.3f} / {np.mean(test['label']):.3f}")
TAGS = {"negation": r"\b(not|no|never|nothing|nobody|neither|nor|without|n't)\b",
"contrast": r"\b(but|yet|although|though|however)\b"}
def tags(text): # phenomena for the error analysis, fixed now
out = [t for t, rx in TAGS.items() if re.search(rx, text)]
return out + (["long"] if len(text.split()) > 30 else [])
for name, d in [("train", train), ("val", val)]:
tagged = [tags(x) for x in d["text"]]
print(f"{name:5}", " | ".join(f"{t} {sum(t in g for g in tagged)}" for t in ["negation", "contrast", "long"]))
vec = TfidfVectorizer(ngram_range=(1, 2), min_df=2, sublinear_tf=True)
Xtr, Xva = vec.fit_transform(train["text"]), vec.transform(val["text"]) # vocabulary from train only
for C in [1, 2, 4, 8, 16]:
acc = LogisticRegression(C=C, max_iter=2000).fit(Xtr, train["label"]).score(Xva, val["label"])
print(f"TF-IDF + LR C={C:<3} val accuracy {acc:.3f}")train 3000 | val 1066 | test 1066 | positive share 0.506 / 0.500 / 0.500
train negation 474 | contrast 537 | long 499
val negation 174 | contrast 190 | long 165
TF-IDF + LR C=1 val accuracy 0.711
TF-IDF + LR C=2 val accuracy 0.720
TF-IDF + LR C=4 val accuracy 0.709
TF-IDF + LR C=8 val accuracy 0.708
TF-IDF + LR C=16 val accuracy 0.706
Each phenomenon covers about one sentence in six, so each validation slice has 165 to 190 sentences: enough to see large effects, too few for small ones (step 4 puts a number on that). The baseline peaks at with 0.720 on validation; that is the bar, and is now frozen.
Step 2: the learning rate, on validation
The model is google/bert_uncased_L-2_H-128_A-2, 4.4 million parameters, small enough to fine-tune on a CPU in seconds. The recipe is the one from the fine-tuning recipe: AdamW with weight decay 0.01, 10 % linear warm-up then linear decay, gradient clipping at norm 1, batches of 32 with dynamic padding. Three learning rates are tried for 2 epochs. To keep the sweep under half a minute it runs on half the budget (1,500 sentences), a common shortcut: the ranking of learning rates usually transfers to the full set, the best epoch count does not. The selection rule, declared before the run, is the lowest validation loss, because loss reacts to confidence and accuracy only to which side of 0.5 a prediction falls (grid and random search).
import torch
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForSequenceClassification, DataCollatorWithPadding, get_linear_schedule_with_warmup
from transformers.utils import logging
logging.set_verbosity_error() # hide the "classifier newly initialised" report
NAME = "google/bert_uncased_L-2_H-128_A-2"
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
train = ds["train"].shuffle(seed=1).select(range(3000))
tok = AutoTokenizer.from_pretrained(NAME)
collate = DataCollatorWithPadding(tok) # pads each batch to its longest sentence
def feats(d):
ids = tok(list(d["text"]), truncation=True, max_length=64)["input_ids"]
return [dict(input_ids=i, labels=y) for i, y in zip(ids, d["label"])]
tr, va = feats(train)[:1500], feats(ds["validation"]) # the sweep uses half the budget, to fit in seconds
def val_loss_acc(model):
model.eval(); loss = correct = 0.0
with torch.no_grad():
for i in range(0, len(va), 200):
b = collate(va[i:i + 200]); out = model(**b)
loss += out.loss.item() * len(b["labels"]); correct += (out.logits.argmax(1) == b["labels"]).sum().item()
return loss / len(va), correct / len(va)
EPOCHS, BS = 2, 32
for lr in [1e-4, 3e-4, 1e-3]:
torch.manual_seed(0)
model = AutoModelForSequenceClassification.from_pretrained(NAME, num_labels=2)
steps = EPOCHS * -(-len(tr) // BS)
opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.01)
sched = get_linear_schedule_with_warmup(opt, int(0.1 * steps), steps)
g = torch.Generator().manual_seed(0)
for epoch in range(1, EPOCHS + 1):
model.train()
for idx in torch.randperm(len(tr), generator=g).split(BS):
loss = model(**collate([tr[i] for i in idx])).loss
opt.zero_grad(); loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step(); sched.step()
vl, acc = val_loss_acc(model)
print(f"lr {lr:.0e} epoch {epoch}: val loss {vl:.3f} val accuracy {acc:.3f}")lr 1e-04 epoch 1: val loss 0.672 val accuracy 0.634
lr 1e-04 epoch 2: val loss 0.661 val accuracy 0.646
lr 3e-04 epoch 1: val loss 0.650 val accuracy 0.649
lr 3e-04 epoch 2: val loss 0.595 val accuracy 0.687
lr 1e-03 epoch 1: val loss 0.611 val accuracy 0.671
lr 1e-03 epoch 2: val loss 0.641 val accuracy 0.695
The rule picks (validation loss 0.595). Accuracy alone would have picked (0.695), but at that rate the validation loss already rises in epoch 2 (0.611 to 0.641): the model becomes confidently wrong on more sentences, a sign of overfitting that accuracy hides. With 1,066 validation sentences, 0.687 against 0.695 is a difference of 9 sentences, well inside noise, so the loss is the better tie-breaker too.
Step 3: train, choose a candidate on validation, test once
The final run trains on all 3,000 sentences for up to 3 epochs and keeps the epoch with the lowest validation loss (early stopping with a checkpoint). Then the four pre-declared candidates are compared on validation, the best one is chosen, and only then are the chosen candidate and the baseline scored on the test set. The comparison is paired (same sentences), so the bootstrap resamples sentences and recomputes the difference (comparing models). Finally the error analysis breaks validation accuracy down by the phenomena of step 1.
import copy, re
import numpy as np
import torch
from datasets import load_dataset
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from transformers import AutoTokenizer, AutoModelForSequenceClassification, DataCollatorWithPadding, get_linear_schedule_with_warmup
from transformers.utils import logging
logging.set_verbosity_error()
NAME, LR, EPOCHS, BS = "google/bert_uncased_L-2_H-128_A-2", 3e-4, 3, 32 # learning rate chosen in step 2
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
train, val, test = ds["train"].shuffle(seed=1).select(range(3000)), ds["validation"], ds["test"]
tok = AutoTokenizer.from_pretrained(NAME)
collate = DataCollatorWithPadding(tok)
def feats(d):
ids = tok(list(d["text"]), truncation=True, max_length=64)["input_ids"]
return [dict(input_ids=i, labels=y) for i, y in zip(ids, d["label"])]
tr, va, te = feats(train), feats(val), feats(test)
y_va, y_te = np.array(val["label"]), np.array(test["label"])
def logits_of(model, data):
model.eval(); out = []
with torch.no_grad():
for i in range(0, len(data), 200):
out.append(model(**collate(data[i:i + 200])).logits)
return torch.cat(out)
torch.manual_seed(0)
model = AutoModelForSequenceClassification.from_pretrained(NAME, num_labels=2)
steps = EPOCHS * -(-len(tr) // BS)
opt = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=0.01)
sched = get_linear_schedule_with_warmup(opt, int(0.1 * steps), steps)
g, best = torch.Generator().manual_seed(0), (float("inf"), 0, None)
for epoch in range(1, EPOCHS + 1):
model.train()
for idx in torch.randperm(len(tr), generator=g).split(BS):
loss = model(**collate([tr[i] for i in idx])).loss
opt.zero_grad(); loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step(); sched.step()
vl = torch.nn.functional.cross_entropy(logits_of(model, va), torch.tensor(y_va)).item()
print(f"epoch {epoch}: val loss {vl:.3f}")
if vl < best[0]:
best = (vl, epoch, copy.deepcopy(model.state_dict()))
model.load_state_dict(best[2]) # early stopping: keep the best epoch
vec = TfidfVectorizer(ngram_range=(1, 2), min_df=2, sublinear_tf=True)
base = LogisticRegression(C=2, max_iter=2000).fit(vec.fit_transform(train["text"]), train["label"]) # C from step 1
p_tfidf = {"val": base.predict_proba(vec.transform(val["text"]))[:, 1], "test": base.predict_proba(vec.transform(test["text"]))[:, 1]}
p_bert = {"val": logits_of(model, va).softmax(1)[:, 1].numpy(), "test": logits_of(model, te).softmax(1)[:, 1].numpy()}
# the candidates, all compared on VALIDATION only: BERT alone, and blends w * BERT + (1 - w) * TF-IDF
cands = {f"blend w={w}": w for w in [0.3, 0.5, 0.7]} | {"bert": 1.0}
acc = lambda p, y: float(np.mean((p > 0.5) == y))
print(f"kept epoch {best[1]} | val accuracy: tfidf {acc(p_tfidf['val'], y_va):.3f}", end="")
for c, w in cands.items():
print(f" | {c} {acc(w * p_bert['val'] + (1 - w) * p_tfidf['val'], y_va):.3f}", end="")
choice = max(cands, key=lambda c: acc(cands[c] * p_bert["val"] + (1 - cands[c]) * p_tfidf["val"], y_va))
w = cands[choice]
print(f"\nchosen on validation: {choice}")
# the test set, once: the chosen candidate against the baseline, with a paired bootstrap of the difference
right_c = ((w * p_bert["test"] + (1 - w) * p_tfidf["test"]) > 0.5) == y_te
right_b = (p_tfidf["test"] > 0.5) == y_te
rng = np.random.default_rng(0)
diffs = [np.mean(right_c[i]) - np.mean(right_b[i]) for i in rng.integers(0, len(y_te), (2000, len(y_te)))]
lo, hi = np.percentile(diffs, [2.5, 97.5])
print(f"TEST (1,066): baseline {right_b.mean():.3f} | {choice} {right_c.mean():.3f} | difference {right_c.mean() - right_b.mean():+.3f}"
f" (95% bootstrap CI {lo:+.3f} to {hi:+.3f}) | only one right: candidate {np.sum(right_c & ~right_b)}, baseline {np.sum(right_b & ~right_c)}")
TAGS = {"negation": r"\b(not|no|never|nothing|nobody|neither|nor|without|n't)\b",
"contrast": r"\b(but|yet|although|though|however)\b"}
def tags(text):
out = [t for t, rx in TAGS.items() if re.search(rx, text)]
return out + (["long"] if len(text.split()) > 30 else [])
vt = [tags(x) for x in val["text"]]
pc_va = w * p_bert["val"] + (1 - w) * p_tfidf["val"]
print("error analysis on VALIDATION, accuracy by phenomenon:")
for t in ["negation", "contrast", "long", "none"]:
m = np.array([(t in tg) if t != "none" else not tg for tg in vt])
print(f" {t:9} n={m.sum():4} | tfidf {acc(p_tfidf['val'][m], y_va[m]):.3f} | bert {acc(p_bert['val'][m], y_va[m]):.3f}"
f" | {choice} {acc(pc_va[m], y_va[m]):.3f}")
wrong = [x for x, tg, p, t in zip(val["text"], vt, pc_va, y_va) if "negation" in tg and (p > 0.5) != t and len(x) < 70]
for x in wrong[:3]:
print(" wrong:", x)epoch 1: val loss 0.560
epoch 2: val loss 0.533
epoch 3: val loss 0.556
kept epoch 2 | val accuracy: tfidf 0.720 | blend w=0.3 0.755 | blend w=0.5 0.750 | blend w=0.7 0.741 | bert 0.740
chosen on validation: blend w=0.3
TEST (1,066): baseline 0.752 | blend w=0.3 0.763 | difference +0.010 (95% bootstrap CI -0.011 to +0.032) | only one right: candidate 75, baseline 64
error analysis on VALIDATION, accuracy by phenomenon:
negation n= 174 | tfidf 0.661 | bert 0.621 | blend w=0.3 0.661
contrast n= 190 | tfidf 0.668 | bert 0.658 | blend w=0.3 0.695
long n= 165 | tfidf 0.721 | bert 0.691 | blend w=0.3 0.727
none n= 676 | tfidf 0.741 | bert 0.781 | blend w=0.3 0.786
wrong: overall , interesting as a documentary -- but not very imaxy .
wrong: it may be a no-brainer , but at least it's a funny no-brainer .
wrong: buy popcorn . take nothing seriously and enjoy the ride .
Read it in order, the way the protocol does:
- Training. Validation loss is lowest after epoch 2 (0.533) and rises in epoch 3, so epoch 2 is kept.
- Selection. On validation, BERT alone (0.740) beats the baseline (0.720) by 0.020, and the blend with is best (0.755). The two models make different mistakes, so averaging their probabilities helps, even with most of the weight on the weaker one.
- The one test. The blend scores 0.763 against the baseline's 0.752 on test: , and the paired interval runs from to . The blend is right on 75 sentences where the baseline is wrong and wrong on 64 where it is right. The first criterion (not worse than the baseline) is met; a claim that the blend is better is not supported by 1,066 sentences.
- Validation was optimistic. The blend led by 0.035 on validation and by 0.010 on test. That is the cost of choosing a learning rate, an epoch and a candidate on the same 1,066 sentences: the winner is partly the one that was lucky on them. Only the untouched test set can show this, which is why it was kept for last.
- Phenomena. BERT is worse than TF-IDF on negation (0.621 against 0.661) and better only on untagged sentences (0.781 against 0.741). This tiny 2-layer encoder has not learned what "never" or "nothing" does to the words around it; the blend rescues contrast sentences but not negation. Two of the three blend failures quoted ("a funny no-brainer", "take nothing seriously and enjoy the ride") are positive reviews built from negative words, the hardest case for both models; the third ("interesting as a documentary -- but not very imaxy") turns on a made-up word.
The decision: ship the blend, because it meets the criterion and its probabilities can be calibrated (step 5); record in the model card that it is not proven better than the baseline. A team that needed a proven gain would go back with more labels or a larger encoder and, for its next claim, a new test set.
Step 4: how much can a slice tell you?
Is BERT's negation gap (0.621 against 0.661 on 174 sentences) real? The Wilson interval for an accuracy measured on items, with for 95 %, is
and the number of items needed for a half-width is about . The counts below are the validation results of step 3 (0.621 of 174 is 108 sentences).
import math
def wilson(k, n, z=1.96):
p = k / n
centre = (p + z * z / (2 * n)) / (1 + z * z / n)
half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
return centre - half, centre + half
slices = {"negation": (174, {"tfidf": 115, "bert": 108, "blend": 115}),
"contrast": (190, {"tfidf": 127, "bert": 125, "blend": 132}),
"none": (676, {"tfidf": 501, "bert": 528, "blend": 531})}
for name, (n, right) in slices.items():
cells = [f"{m} {k / n:.3f} [{wilson(k, n)[0]:.3f}, {wilson(k, n)[1]:.3f}]" for m, k in right.items()]
print(f"{name:8} n={n:3} | " + " | ".join(cells))
for h in [0.05, 0.03, 0.02]:
print(f"sentences needed for +-{h} at accuracy 0.66: {math.ceil(1.96 ** 2 * 0.66 * 0.34 / h ** 2)}")negation n=174 | tfidf 0.661 [0.588, 0.727] | bert 0.621 [0.547, 0.689] | blend 0.661 [0.588, 0.727]
contrast n=190 | tfidf 0.668 [0.599, 0.731] | bert 0.658 [0.588, 0.722] | blend 0.695 [0.626, 0.756]
none n=676 | tfidf 0.741 [0.707, 0.773] | bert 0.781 [0.748, 0.811] | blend 0.786 [0.753, 0.815]
sentences needed for +-0.05 at accuracy 0.66: 345
sentences needed for +-0.03 at accuracy 0.66: 958
sentences needed for +-0.02 at accuracy 0.66: 2156
Every interval on the 174 negation sentences is about $\pm 0.07$ wide, and BERT's interval (0.547 to 0.689) overlaps the baseline's (0.588 to 0.727) almost completely. So "BERT is worse on negation" is a hypothesis from 7 sentences, not a finding. To measure a negation accuracy to $\pm 0.03$ you need about 960 negated sentences, far more than the validation set has. This is why teams build a dedicated **behavioural test suite** for the phenomena they care about: a few hundred short, hand-written sentences per phenomenon ("not bad", "not good", "never boring"), with labels checked by two people ([robustness testing](/ml-training-evaluation/robustness-testing/)). Only the untagged slice (676 sentences) shows a gap that the intervals separate a little: BERT and the blend near 0.78, TF-IDF 0.741.
## Step 5: calibrate, package and serve
The blend averages two probabilities, which pulls them towards 0.5. **Temperature scaling** ([calibration](/ml-training-evaluation/calibration/)) fixes this with one number $T$ fitted on validation: with the blend's probability $p$ and its log-odds $z = \ln \frac{p}{1 - p}$, the calibrated probability is $\sigma(z / T)$, and $T$ minimises the validation log-loss. It never changes which side of 0.5 a review falls on, so accuracy stays the same. The expected calibration error over 10 equal-width confidence bins $B_b$ is
```math
\operatorname{ECE} = \sum_{b=1}^{10} \frac{\lvert B_b \rvert}{n} \, \bigl\lvert \operatorname{acc}(B_b) - \operatorname{conf}(B_b) \bigr\rvertThen the package: the fine-tuned BERT and its tokenizer with save_pretrained (safetensors), the TF-IDF pipeline with joblib (a pickle: load it only from your own registry, see saving models), and a small JSON config with , and the unsure band. A loader function reads the three and returns a predict function, which is what the serving code calls (model artifacts and signatures).
import json, os, tempfile, time
import joblib
import numpy as np
import torch
from datasets import load_dataset
from scipy.optimize import minimize_scalar
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from transformers import AutoTokenizer, AutoModelForSequenceClassification, DataCollatorWithPadding, get_linear_schedule_with_warmup
from transformers.utils import logging
logging.set_verbosity_error()
NAME, LR, EPOCHS, KEEP, BS, W = "google/bert_uncased_L-2_H-128_A-2", 3e-4, 3, 2, 32, 0.3 # from steps 2 and 3
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
train, val, test = ds["train"].shuffle(seed=1).select(range(3000)), ds["validation"], ds["test"]
tok = AutoTokenizer.from_pretrained(NAME)
collate = DataCollatorWithPadding(tok)
feats = lambda d: [dict(input_ids=i, labels=y) for i, y in zip(tok(list(d["text"]), truncation=True, max_length=64)["input_ids"], d["label"])]
tr = feats(train)
torch.manual_seed(0) # the same run as step 3, stopped after epoch 2
model = AutoModelForSequenceClassification.from_pretrained(NAME, num_labels=2)
steps = EPOCHS * -(-len(tr) // BS)
opt = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=0.01)
sched = get_linear_schedule_with_warmup(opt, int(0.1 * steps), steps)
g = torch.Generator().manual_seed(0)
for epoch in range(1, KEEP + 1):
model.train()
for idx in torch.randperm(len(tr), generator=g).split(BS):
loss = model(**collate([tr[i] for i in idx])).loss
opt.zero_grad(); loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step(); sched.step()
model.eval()
tfidf = make_pipeline(TfidfVectorizer(ngram_range=(1, 2), min_df=2, sublinear_tf=True),
LogisticRegression(C=2, max_iter=2000)).fit(train["text"], train["label"])
def raw_prob(texts, model=model, tfidf=tfidf, tok=tok): # the blend, before calibration
with torch.no_grad():
enc = tok(list(texts), padding=True, truncation=True, max_length=64, return_tensors="pt")
pb = model(**enc).logits.softmax(1)[:, 1].numpy()
return W * pb + (1 - W) * tfidf.predict_proba(list(texts))[:, 1]
# calibration: one temperature on the blend's log-odds, fitted on validation
logit = lambda p: np.log(np.clip(p, 1e-6, 1 - 1e-6) / np.clip(1 - p, 1e-6, 1))
sig = lambda z: 1 / (1 + np.exp(-z))
p_va, y_va = raw_prob(val["text"]), np.array(val["label"])
p_te, y_te = raw_prob(test["text"]), np.array(test["label"])
nll = lambda T: -np.mean(y_va * np.log(sig(logit(p_va) / T)) + (1 - y_va) * np.log(1 - sig(logit(p_va) / T)))
T = minimize_scalar(nll, bounds=(0.05, 10), method="bounded").x
def ece(p, y, bins=10): # on the confidence of the predicted class
conf, right = np.maximum(p, 1 - p), (p > 0.5) == y
idx = np.minimum(((conf - 0.5) / 0.5 * bins).astype(int), bins - 1)
return sum(np.mean(idx == b) * abs(right[idx == b].mean() - conf[idx == b].mean()) for b in range(bins) if np.any(idx == b))
print(f"temperature T = {T:.2f} | ECE on test: before {ece(p_te, y_te):.3f}, after {ece(sig(logit(p_te) / T), y_te):.3f}")
# the 'unsure' band: the narrowest |p - 0.5| < d that gives 80 % accuracy on the answered validation reviews
pc_va, pc_te = sig(logit(p_va) / T), sig(logit(p_te) / T)
d = next(d for d in np.arange(0, 0.5, 0.01) if np.mean(((pc_va > 0.5) == y_va)[abs(pc_va - 0.5) >= d]) >= 0.80)
ans = abs(pc_te - 0.5) >= d
print(f"unsure band |p - 0.5| < {d:.2f}: test coverage {ans.mean():.3f}, accuracy on answered {np.mean(((pc_te > 0.5) == y_te)[ans]):.3f}")
# package: BERT + tokenizer (safetensors), the TF-IDF pipeline (joblib), and a config with W, T and the band
out = tempfile.mkdtemp()
model.save_pretrained(f"{out}/bert"); tok.save_pretrained(f"{out}/bert")
joblib.dump(tfidf, f"{out}/tfidf.joblib")
json.dump({"bert_weight": W, "temperature": round(T, 4), "unsure_band": round(d, 2), "labels": ["negative", "positive"]},
open(f"{out}/config.json", "w"))
size = sum(os.path.getsize(os.path.join(r, f)) for r, _, fs in os.walk(out) for f in fs)
print(f"package: {sorted(os.listdir(out))}, {size / 1e6:.1f} MB")
def load_predictor(path): # what the serving code does at start-up
cfg = json.load(open(f"{path}/config.json"))
m = AutoModelForSequenceClassification.from_pretrained(f"{path}/bert").eval()
t, tf = AutoTokenizer.from_pretrained(f"{path}/bert"), joblib.load(f"{path}/tfidf.joblib")
def predict(texts):
p = sig(logit(raw_prob(texts, m, tf, t)) / cfg["temperature"])
return [{"label": "unsure" if abs(q - 0.5) < cfg["unsure_band"] else cfg["labels"][int(q > 0.5)],
"p_positive": round(float(q), 2)} for q in p]
return predict
predict = load_predictor(out)
ref = sig(logit(raw_prob(test["text"][:200])) / T)
got = [r["p_positive"] for r in predict(test["text"][:200])]
print("reloaded package agrees with the in-memory model on 200 test reviews:", bool(np.allclose(ref, got, atol=0.005)))
for s in ["a warm , funny and surprisingly moving film .", "not bad at all .", "the plot is thin , but the cast is a joy ."]:
print(predict([s])[0], "|", s)
lat = []
for s in test["text"][:200]:
t0 = time.perf_counter(); predict([s]); lat.append(time.perf_counter() - t0)
print("p95 latency per review under 50 ms (one review per call):", bool(np.percentile(lat, 95) < 0.050))temperature T = 0.58 | ECE on test: before 0.100, after 0.025
unsure band |p - 0.5| < 0.12: test coverage 0.802, accuracy on answered 0.823
package: ['bert', 'config.json', 'tfidf.joblib'], 18.5 MB
reloaded package agrees with the in-memory model on 200 test reviews: True
{'label': 'positive', 'p_positive': 0.99} | a warm , funny and surprisingly moving film .
{'label': 'negative', 'p_positive': 0.02} | not bad at all .
{'label': 'negative', 'p_positive': 0.1} | the plot is thin , but the cast is a joy .
p95 latency per review under 50 ms (one review per call): True
- Calibration. is below 1, so the blend was under-confident, as expected from averaging; dividing the log-odds by 0.58 stretches them, and the test ECE drops from 0.100 to 0.025, inside the target of 0.05.
- The unsure band. On validation, answering only when reaches 80 % accuracy; on test that band answers 80.2 % of reviews with 0.823 accuracy. The site shows "unsure" for the other fifth.
- The package is 18.5 MB, almost all of it BERT's weights, and the reloaded copy gives the same probabilities. The latency check prints only a yes or no, because timings vary from machine to machine; one review takes a few milliseconds on a laptop CPU. For heavier traffic, batch the calls (latency and batching) or quantize the encoder.
- Two failures to write down. "not bad at all ." is called negative with 0.02, and the contrast review "the plot is thin, but the cast is a joy" negative with 0.10. Both are confident and wrong: calibration fixes the average, not individual cases. They go into the model card as known limitations and into the behavioural test suite.
To put the predictor behind an HTTP endpoint, wrap predict in a FastAPI route as in FastAPI basics, load the package once at start-up, and log the package version with every answer.
Step 6: the acceptance check and the model card
The last step turns the measured numbers into a decision and a document. It runs in your browser: the numbers are copied from the outputs of steps 3 and 5, as a CI job would read them from a metrics file (CI/CD for ML). The model card follows the usual sections (intended use, data, evaluation, limitations, ethics) of governance.
results = { # from steps 3 and 5 (test set, 1,066 sentences, scored once)
"test_acc": 0.763, "baseline_test_acc": 0.752, "diff_ci": (-0.011, 0.032),
"ece_after": 0.025, "coverage": 0.802, "answered_acc": 0.823,
"p95_under_50ms": True, "size_mb": 18.5,
}
checks = [
("accuracy >= baseline (test)", results["test_acc"] >= results["baseline_test_acc"]),
("ECE <= 0.05 (test, calibrated)", results["ece_after"] <= 0.05),
("answered accuracy >= 0.80 (test)", results["answered_acc"] >= 0.80),
("p95 latency < 50 ms", results["p95_under_50ms"]),
("package <= 50 MB", results["size_mb"] <= 50),
]
for name, ok in checks:
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
decision = "ship" if all(ok for _, ok in checks) else "do not ship"
lo, hi = results["diff_ci"]
print(f"decision: {decision}\n")
card = f"""# Model card: review-sentiment blend v1
Intended use: label one-line English film reviews as positive / negative / unsure on TAD Reviews.
Not for: other domains, other languages, decisions about people (e.g. moderating reviewers).
Model: 0.3 x fine-tuned google/bert_uncased_L-2_H-128_A-2 + 0.7 x TF-IDF logistic regression,
temperature-calibrated (T = 0.58), unsure band |p - 0.5| < 0.12.
Data: rotten_tomatoes, 3,000 training sentences (seed 1); all choices on the 1,066 validation sentences.
Evaluation (test, 1,066 sentences, once): accuracy {results['test_acc']:.3f} vs baseline {results['baseline_test_acc']:.3f},
difference 95% CI {lo:+.3f} to {hi:+.3f}: not proven better than the baseline.
ECE {results['ece_after']:.3f}; answers {results['coverage']:.0%} of reviews at {results['answered_acc']:.1%} accuracy.
Known limitations: negation and contrast ('not bad at all', 'thin plot, but a joy') are often
wrong with high confidence; validation slices of ~180 sentences are too small to measure them.
Ethics: reviews may contain names; the model stores no text; labels can be appealed by the reviewer."""
print(card)[PASS] accuracy >= baseline (test)
[PASS] ECE <= 0.05 (test, calibrated)
[PASS] answered accuracy >= 0.80 (test)
[PASS] p95 latency < 50 ms
[PASS] package <= 50 MB
decision: ship
# Model card: review-sentiment blend v1
Intended use: label one-line English film reviews as positive / negative / unsure on TAD Reviews.
Not for: other domains, other languages, decisions about people (e.g. moderating reviewers).
Model: 0.3 x fine-tuned google/bert_uncased_L-2_H-128_A-2 + 0.7 x TF-IDF logistic regression,
temperature-calibrated (T = 0.58), unsure band |p - 0.5| < 0.12.
Data: rotten_tomatoes, 3,000 training sentences (seed 1); all choices on the 1,066 validation sentences.
Evaluation (test, 1,066 sentences, once): accuracy 0.763 vs baseline 0.752,
difference 95% CI -0.011 to +0.032: not proven better than the baseline.
ECE 0.025; answers 80% of reviews at 82.3% accuracy.
Known limitations: negation and contrast ('not bad at all', 'thin plot, but a joy') are often
wrong with high confidence; validation slices of ~180 sentences are too small to measure them.
Ethics: reviews may contain names; the model stores no text; labels can be appealed by the reviewer.
Extensions
- More labels or a bigger encoder. Train on all 8,530 sentences, or try a LoRA adapter; record the gain on validation, and keep in mind that this test set has now been used once.
- A behavioural test suite of 200 hand-written negation and contrast sentences (robustness testing), run as a CI check on every new model.
- Seeds. Repeat steps 3 and 5 with 3 to 5 seeds and report the spread of the test difference (fine-tuning recipe).
- Distillation. Train the TF-IDF model, or a smaller student, on the blend's calibrated probabilities (distillation).
- ONNX export of the encoder and a latency comparison (ONNX export).
- Monitoring. Log the share of "unsure" answers per day: a rise is an early sign of new vocabulary or a new kind of film (data drift).
Write-up template
Problem and user: who sees the label, what a wrong label costs
Criteria (fixed first): metric, target, measured on ... (copy the table)
Data: source, licence, sizes, how the split was made, what is kept back
Choices on validation: C = ..., learning rate = ..., epoch = ..., candidate = ...
Test (once): model ... vs baseline ..., difference ... (95% CI ... to ...)
Calibration and band: T = ..., ECE before/after ..., coverage ..., answered accuracy ...
Error analysis: phenomena, slice sizes and intervals, 3 typical failures
Package: files, size, loader, latency check
Decision and next step: ship / do not ship, and what would change the decisionPractice
- Step 2 picked by validation loss, while validation accuracy preferred . Give one argument for each rule.
- After step 3 a colleague suggests trying "because 0.3 won". May you test it on the test set? What would you do instead?
- Temperature scaling did not change the accuracy of 0.763. Why not, and what did it change?
- The unsure band was chosen on validation for 80 % answered accuracy. On test the answered accuracy is 0.823. Is that a sign of overfitting the band?
Answer
- Loss rewards confident correct answers and punishes confident wrong ones, so it saw that was starting to overfit (loss up in epoch 2). Accuracy is what the product reports, but 0.687 against 0.695 is 9 of 1,066 sentences, within noise; when the two disagree on a tiny gap, the smoother criterion is the safer tie-breaker. Either rule is acceptable if it is written down before the run.
- No: choosing by test accuracy would turn the test set into a second validation set, and its 0.763 would no longer be an unbiased estimate. Add to the candidates, choose on validation (or by cross-validation on the training data), and use a fresh test set for any new claim.
- Dividing the log-odds by keeps the sign of each log-odds, so every review stays on the same side of 0.5. It changed the probabilities themselves: ECE from 0.100 to 0.025, which makes the unsure band and any sorting by probability meaningful.
- No: 0.823 is above the 0.80 target, the opposite direction from overfitting. The band was the narrowest meeting 0.80 on validation; on test it happens to do a little better, within the noise of about 850 answered reviews (half-width about 0.026).
Test yourself
In step 3 the blend led the baseline by 0.035 on validation but by 0.010 on test. What is the most likely reason?
- The test set is harder
- The learning rate, the epoch and the candidate were all chosen on the validation set, so its score is optimistic
- BERT forgot what it learned
- Temperature scaling lowered the accuracy
The paired 95% bootstrap interval of the test difference was to . What may the model card claim?
- The blend is 1 point better than the baseline
- The blend is not worse than the baseline on this test set, but a gain is not proven
- The blend is worse
- Nothing, because bootstrap intervals are not valid for accuracy
The fitted temperature was . What does say about the blend's raw probabilities?
- They were over-confident
- They were under-confident, too close to 0.5, as averaging two models tends to make them
- They were perfectly calibrated
- The model is biased towards positive reviews
BERT had 0.621 accuracy on 174 negation sentences, TF-IDF 0.661. About how wide is each 95% interval, and what follows?
- About : BERT is clearly worse on negation
- About : the intervals overlap, so the gap is a hypothesis for a dedicated test suite
- About : slices are useless
- Intervals cannot be computed for slices