TExcelTAD
Home › NLP, Transformers & LLM Fine-Tuning › Fine-Tuning BERT for Text Classification

Fine-Tuning BERT for Text Classification

Sentiment, topic, intent, spam, toxicity, "is this support ticket urgent": most NLP work in industry is sentence or document classification. A TF-IDF model with logistic regression is a strong, cheap baseline, but it sees words as unrelated columns and cannot tell "not bad" from "bad". A pretrained encoder such as BERT has already learned how words combine in context; fine-tuning adds a small classification layer on top and trains the whole network for a few epochs on your labels.

The general recipe (small learning rate, warm-up, early stopping, a learning-rate sweep) is in Fine-Tuning: Learning Rate, Warm-up and Early Stopping, and a LoRA version of the same task is in LoRA with PEFT. This lesson is about the text-specific parts: what the classification head computes, how sentences become batches without wasting compute on padding, and an honest comparison with the TF-IDF baseline on the same data.

The model: an encoder plus one layer

[CLS] not badat all . [SEP] BERT encoderT x 128 states h_0 poolertanh(W_p h_0) new layerz = W_c u + b softmax+ loss every weight trains, with a small learning rate pretrained pretrained random at start only position 0 ([CLS]) feeds the head

AutoModelForSequenceClassification loads the pretrained encoder and puts a head on the hidden state h0\mathbf{h}_0 of the first position, the [CLS] token (Inside a Pretrained BERT shows the encoder itself). For BERT the head is the pooler, a dense layer with tanh that was pretrained on next-sentence prediction, followed by a new linear layer with one output per class:

u=tanh⁡(Wph0+bp),z=Wcu+bc,L=−log⁡softmax⁡(z)y\mathbf{u} = \tanh(W_p \mathbf{h}_0 + \mathbf{b}_p), \qquad \mathbf{z} = W_c \mathbf{u} + \mathbf{b}_c, \qquad L = -\log \operatorname{softmax}(\mathbf{z})_y

The gradient of the loss with respect to the logits is the familiar ∂L/∂z=p−ey\partial L / \partial \mathbf{z} = \mathbf{p} - \mathbf{e}_y (derived here), and it flows back through the pooler into all the encoder layers. Because h0\mathbf{h}_0 attends to every token, the [CLS] vector becomes a summary of the sentence that is shaped by the task during fine-tuning. A common alternative, used by sentence-embedding models, is mean pooling over the real tokens, hˉ=∑tmtht/∑tmt\bar{\mathbf{h}} = \sum_t m_t \mathbf{h}_t / \sum_t m_t with the attention mask mtm_t.

From scratch: the head, its gradient and pooling

The head on made-up hidden states: 4 sentences, 6 positions, hidden size 8. The code computes the probabilities and the loss, checks one gradient entry against a finite difference, and shows why mean pooling must use the mask.

python · try it yourself
import numpy as np
rng = np.random.default_rng(0)

B, T, d, C = 4, 6, 8, 2                       # 4 sentences, 6 positions, hidden size 8, 2 classes
H = rng.normal(size=(B, T, d))                # stand-in for the encoder's last hidden states
mask = np.array([[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0], [1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 1, 0]])
y = np.array([1, 0, 0, 1])
Wp, bp = rng.normal(scale=0.3, size=(d, d)), np.zeros(d)     # BERT pooler: dense + tanh on [CLS]
Wc, bc = rng.normal(scale=0.3, size=(d, C)), np.zeros(C)     # new classification layer

def loss_and_grad(Wc):
    pooled = np.tanh(H[:, 0] @ Wp + bp)       # position 0 is [CLS]
    z = pooled @ Wc + bc                      # logits, shape (B, C)
    z = z - z.max(1, keepdims=True)
    p = np.exp(z) / np.exp(z).sum(1, keepdims=True)
    loss = -np.log(p[np.arange(B), y]).mean()
    dz = (p - np.eye(C)[y]) / B               # softmax + cross-entropy: dL/dz = p - onehot(y)
    return loss, pooled.T @ dz, p

loss, gWc, p = loss_and_grad(Wc)
print("P(class 1):", p[:, 1].round(3).tolist(), "| loss:", round(float(loss), 4))
E = np.zeros_like(Wc); E[3, 1] = 1e-6         # finite-difference check of one weight
num = (loss_and_grad(Wc + E)[0] - loss_and_grad(Wc - E)[0]) / 2e-6
print("dL/dWc[3,1] analytic:", round(float(gWc[3, 1]), 6), "| numeric:", round(float(num), 6))

m = mask[:, :, None]                          # the alternative: mean of the real (unpadded) tokens
mean_pool = (H * m).sum(1) / m.sum(1)
wrong = H.mean(1)                             # mean over all positions, padding included
print("mean pooling ignores padding:", np.allclose(mean_pool[0], wrong[0]), "(sentence 1, no padding) |",
      np.allclose(mean_pool[2], wrong[2]), "(sentence 3, 3 pads)")
P(class 1): [0.394, 0.63, 0.694, 0.359] | loss: 1.0333
dL/dWc[3,1] analytic: -0.021925 | numeric: -0.021925
mean pooling ignores padding: True (sentence 1, no padding) | False (sentence 3, 3 pads)

The random head gets every sentence wrong in this draw (probabilities on the wrong side of 0.5 for all four), so the loss, 1.0333, is above ln⁡2≈0.693\ln 2 \approx 0.693, the loss of a coin flip. The analytic and numeric gradients agree to six decimals. A plain mean over all positions is only correct for the sentence without padding: padded positions hold numbers too, and averaging them in changes the vector.

The data and the batches

The data is rotten_tomatoes: one-sentence movie reviews, lower-cased and split on spaces, labelled 1 = positive. To keep runs short, a fixed random 2,000 sentences from train and 500 from validation (later also 500 from test, used once). The first recorded example looks at the label balance and at the lengths in BERT tokens, then counts how many positions a model would process in one epoch with three ways of building batches of 32:

  • fixed padding to max_length=64 for every sentence,
  • dynamic padding: each batch padded to its own longest sentence (DataCollatorWithPadding),
  • length-grouped batches: sentences sorted by length first, so each batch holds similar lengths (Trainer's length-grouped sampler, train_sampling_strategy="group_by_length" in recent versions and group_by_length=True in older ones, does a randomised version of this).
python · try it yourself
import numpy as np
from datasets import load_dataset
from transformers import AutoTokenizer

ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
train = ds["train"].shuffle(seed=0).select(range(2000))
val = ds["validation"].shuffle(seed=0).select(range(500))
print("train labels:", np.bincount(train["label"]).tolist(), "| val labels:", np.bincount(val["label"]).tolist())

tok = AutoTokenizer.from_pretrained("google/bert_uncased_L-2_H-128_A-2")
lengths = np.array([len(ids) for ids in tok(list(train["text"]))["input_ids"]])
print("tokens per sentence (with [CLS], [SEP]): median", int(np.median(lengths)), "| 95th pct", int(np.percentile(lengths, 95)),
      "| max", int(lengths.max()), "| share above 64:", f"{(lengths > 64).mean():.3f}")

L = np.minimum(lengths, 64)                   # truncate at 64
batches = np.array_split(np.random.default_rng(0).permutation(len(L)), len(L) // 32)
fixed = 64 * len(L)
dynamic = sum(L[b].max() * len(b) for b in batches)
order = np.argsort(L, kind="stable")
grouped = sum(L[b].max() * len(b) for b in np.array_split(order, len(L) // 32))
print(f"padded positions per epoch: fixed 64 = {fixed:,} | dynamic = {dynamic:,} | length-grouped = {grouped:,} | real tokens = {L.sum():,}")
train labels: [1027, 973] | val labels: [253, 247]
tokens per sentence (with [CLS], [SEP]): median 26 | 95th pct 47 | max 78 | share above 64: 0.001
padded positions per epoch: fixed 64 = 128,000 | dynamic = 104,073 | length-grouped = 55,526 | real tokens = 54,529

The classes are balanced (1,027 against 973), so accuracy is a fair headline metric here. A median sentence has 26 tokens and only 0.1 % are longer than 64, so max_length=64 truncates almost nothing. Padding everything to 64 processes 128,000 positions per epoch for 54,529 real tokens: 57 % of the work is padding. Dynamic padding saves less than you might hope (104,073), because a random batch of 32 almost always contains one long sentence. Grouping by length gets within 2 % of the real token count. Since attention cost grows with the square of the length, the real saving in compute is larger than these counts suggest. The price of grouping is less random batches; Trainer keeps some randomness by sorting only inside large random chunks.

Fine-tuning, against the baseline

The recorded run below fits the TF-IDF baseline (word 1- and 2-grams, sublinear term frequency, logistic regression with C=4C = 4, a common setting not tuned here) and fine-tunes the 4.4-million-parameter google/bert_uncased_L-2_H-128_A-2 on the same 2,000 sentences: AdamW with weight decay 0.01, peak learning rate 5⋅10−45 \cdot 10^{-4} with 10 % linear warm-up and linear decay over 3 epochs of 63 batches, gradient clipping at norm 1 (why), dynamic padding. The peak rate is high for BERT because this model is tiny and trained for only 189 steps; the recipe lesson's sweep found 10−310^{-3} best on half the data. Both models are scored on the validation sentences and, once, on 500 test sentences.

python · try it yourself
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()                    # hide the "classifier newly initialised" load 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=0).select(range(2000))
val = ds["validation"].shuffle(seed=0).select(range(500))
test = ds["test"].shuffle(seed=0).select(range(500))

# baseline: TF-IDF on word 1- and 2-grams + logistic regression, fitted on the same 2,000 sentences
vec = TfidfVectorizer(ngram_range=(1, 2), min_df=2, sublinear_tf=True)
lr_clf = LogisticRegression(C=4.0, max_iter=1000).fit(vec.fit_transform(train["text"]), train["label"])
base_acc = {s: (lr_clf.predict(vec.transform(d["text"])) == d["label"]).mean() for s, d in [("val", val), ("test", test)]}

tok = AutoTokenizer.from_pretrained(name)
def feats(d):
    ids = tok(list(d["text"]), truncation=True, max_length=64)["input_ids"]   # no padding here
    return [dict(input_ids=i, labels=y) for i, y in zip(ids, d["label"])]
tr, va, te = feats(train), feats(val), feats(test)
collate = DataCollatorWithPadding(tok)           # pads each batch to its own longest sentence

def accuracy(model, data):
    model.eval(); correct = 0
    with torch.no_grad():
        for i in range(0, len(data), 100):
            batch = collate(data[i:i + 100])
            correct += (model(**batch).logits.argmax(1) == batch["labels"]).sum().item()
    return correct / len(data)

torch.manual_seed(0)
model = AutoModelForSequenceClassification.from_pretrained(name, num_labels=2)
epochs, bs, peak = 3, 32, 5e-4
steps = epochs * -(-len(tr) // bs)               # 63 batches per epoch, 189 steps
opt = torch.optim.AdamW(model.parameters(), lr=peak, 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()
    print(f"epoch {epoch}: last batch loss {loss.item():.3f} | val accuracy {accuracy(model, va):.3f}")

print(f"TF-IDF + LR : val {base_acc['val']:.3f} | test {base_acc['test']:.3f}")
print(f"BERT (4.4 M): val {accuracy(model, va):.3f} | test {accuracy(model, te):.3f}   (500 sentences each)")

new = ["a warm , funny and surprisingly moving film .", "two hours of my life i will never get back .",
       "not bad at all .", "the plot is not good , but the acting is not bad either ."]
with torch.no_grad():
    p = model(**tok(new, padding=True, return_tensors="pt")).logits.softmax(-1)[:, 1]
for s, pi in zip(new, p.tolist()):
    print(f"P(positive) = {pi:.2f} | {s}")
epoch 1: last batch loss 0.857 | val accuracy 0.642
epoch 2: last batch loss 0.460 | val accuracy 0.726
epoch 3: last batch loss 0.115 | val accuracy 0.732
TF-IDF + LR : val 0.702 | test 0.708
BERT (4.4 M): val 0.732 | test 0.754   (500 sentences each)
P(positive) = 0.95 | a warm , funny and surprisingly moving film .
P(positive) = 0.44 | two hours of my life i will never get back .
P(positive) = 0.05 | not bad at all .
P(positive) = 0.05 | the plot is not good , but the acting is not bad either .

Reading the result honestly:

  • BERT wins, by a little. 0.754 against 0.708 on the 500 test sentences, 23 sentences more. The standard error of an accuracy near 0.73 on 500 sentences is 0.73⋅0.27/500≈0.02\sqrt{0.73 \cdot 0.27 / 500} \approx 0.02, so the gap is about two standard errors: probably real, but one seed and one subset. Validation shows a smaller gap (0.732 against 0.702).
  • The model is small. Two layers and hidden size 128 are a fraction of BERT-base (12 layers, 768, 110 million parameters). Larger encoders reach about 0.85 to 0.90 on this data set with all 8,530 training sentences; the TF-IDF model would gain much less from more data. Fine-tuning pays off most with a strong pretrained model.
  • It starts to memorise in epoch 3. The last training batch loss falls to 0.115 while validation accuracy hardly moves (0.726 to 0.732). With more epochs, early stopping on the validation loss would be needed.
  • Negation is still hard for it. "not bad at all ." gets P(positive)=0.05P(\text{positive}) = 0.05: the small model has learned that "bad" is negative but not what "not ... at all" does to it. Collecting such failures is error analysis; the usual fixes are a larger pretrained model, more examples of the pattern, or targeted augmentation.

In practice: Trainer

The plain loop above makes every step visible. The Trainer class does the same with less code, plus evaluation, checkpointing, mixed precision and length grouping. It is shown here without running, because its logs include timings:

python
from transformers import Trainer, TrainingArguments

args = TrainingArguments(
    output_dir="out", num_train_epochs=3, per_device_train_batch_size=32, learning_rate=5e-4,
    weight_decay=0.01, warmup_steps=0.1, lr_scheduler_type="linear", max_grad_norm=1.0,
    eval_strategy="epoch", save_strategy="epoch", load_best_model_at_end=True,
    metric_for_best_model="eval_loss", train_sampling_strategy="group_by_length", seed=0,
)
trainer = Trainer(model=model, args=args, train_dataset=train_tok, eval_dataset=val_tok,
                  data_collator=DataCollatorWithPadding(tok), compute_metrics=compute_metrics)
trainer.train()

The argument names are those of recent Transformers versions: a float warmup_steps below 1 is a fraction of the total steps, and older versions spell these warmup_ratio=0.1 and group_by_length=True. train_tok and val_tok are the data sets after .map(tokenize, batched=True), and compute_metrics receives the logits and labels of the evaluation set. For several labels per text (a ticket can be both "billing" and "urgent"), pass problem_type="multi_label_classification": the head then uses a sigmoid per class with binary cross-entropy and float labels instead of softmax.

Pitfalls

  • No baseline. Without the TF-IDF number you cannot tell whether a fine-tuned model is good. On short, keyword-heavy texts the baseline is sometimes within a point of BERT, at a thousandth of the cost.
  • Padding to the longest sentence of the data set. One 500-token outlier makes every batch 500 wide. Truncate at a length that covers 95 to 99 % of the data and pad per batch.
  • Ignoring the attention mask. Pass attention_mask (the collator does) and pool with it; otherwise padding changes the predictions.
  • Different preprocessing at inference. This data set is lower-cased with spaces around punctuation; production text is not. Evaluate on text that looks like what the model will see, or normalise it the same way.
  • Tuning on the test set. Choose the learning rate and the epoch on validation; touch the test set once.
  • Reading one run as a ranking. Differences of a point or two on 500 sentences are within seed noise; repeat with 3 to 5 seeds before choosing.

Practice

  1. A batch holds sentences with 10, 12, 14 and 60 tokens. How many positions does dynamic padding process, and how many are real tokens?
  2. Why is the [CLS] vector a sensible input for the head after fine-tuning, even though it is a fixed token with no meaning of its own?
  3. You have 300 labelled support tickets and a laptop CPU. Which would you try first, and why?
  4. Your classes are 95 % "not urgent" and 5 % "urgent". What should the report contain instead of accuracy alone?
Answers
  1. 4⋅60=2404 \cdot 60 = 240 positions for 10+12+14+60=9610 + 12 + 14 + 60 = 96 real tokens; 60 % of the batch is padding. Grouping by length would put the 60-token sentence with other long ones.
  2. Through self-attention, position 0 combines information from every token in every layer, and fine-tuning trains the whole encoder so that this position carries what the head needs. Without fine-tuning (frozen encoder), mean pooling is often the better summary.
  3. The TF-IDF + logistic regression baseline (seconds, often good on short texts), then frozen sentence embeddings with a linear model (sentence embeddings), and only then fine-tuning, which with 300 examples needs several seeds and careful early stopping.
  4. Per-class precision, recall and F1 (or the PR curve) for "urgent", plus the confusion matrix; a model that always says "not urgent" has 0.95 accuracy (classification metrics).

Test yourself

In BertForSequenceClassification, which hidden state feeds the classification layer?

  1. The mean of all hidden states
  2. The [SEP] token's hidden state
  3. The [CLS] (position 0) hidden state after the tanh pooler
  4. The last token's hidden state

In the lesson's 2,000 training sentences, why did dynamic padding (104,073 positions) save much less than length-grouped batches (55,526)?

  1. Dynamic padding is buggy
  2. A random batch of 32 almost always contains one long sentence, which sets the width of the whole batch
  3. Grouping removes sentences
  4. Dynamic padding pads to 64

Fine-tuned BERT scored 0.754 and TF-IDF + LR 0.708 on 500 test sentences, one seed. What is a fair conclusion?

  1. BERT is 4.6 points better on every data set
  2. The gap is about two standard errors (about 0.02 each): probably real here, but check more seeds and subsets before relying on it
  3. The difference is pure noise
  4. TF-IDF is better because it is cheaper

Which setting turns a sequence-classification head into a multi-label head (several labels per text)?

  1. num_labels=1
  2. problem_type="multi_label_classification", with a sigmoid and binary cross-entropy per class
  3. A larger learning rate
  4. Grouping batches by length