Fine-Tune the Model on Your Data

A pretrained model already knows a great deal about language, but it knows nothing about your classes. Fine-tuning closes that gap: you keep training the model for a short while on a few labelled examples, so it learns your task. The Transformers library does this with the Trainer, a training loop you configure instead of writing it yourself. A few of its settings decide the result, the numbers it reports after each epoch show whether the model still improves, and a fixed seed makes a run come out the same twice.

Fine-tuning: training that starts from pretrained weights

A text classifier built on a pretrained checkpoint has two parts. The body is the stack of pretrained layers that turns a text into vectors; it learned how language fits together from a very large amount of text. The head is one small layer on top that turns the vector of a text into one score per class. When you load a checkpoint with a classification class, the head is new. The checkpoint holds no weights for your classes, so the head's weights start random. Loading prints a report that says so: it lists the weights of the old pretraining head as unexpected, and those of the new head as missing and newly initialized. Until it is trained, that head can only guess.

Fine-tuning means continuing the training of all these weights on a small labelled set for your one task. The training itself is the loop you know from PyTorch: forward pass, loss, backward pass, optimizer step. The only difference from training from scratch is the starting point. Because the body already produces useful vectors, the head quickly learns which directions in them separate your classes, while the body's weights move only a little to suit your texts.

  • Labelled text
  • Pretrained body adjusts slightly
  • New head learns the classes
  • One score per class
  • Labelled text to Pretrained body: token IDs
  • Pretrained body to New head: a vector
  • New head to One score per class

This is why fine-tuning needs so little. Training the same network from random weights would have to learn the language first, from millions of texts. Fine-tuning reuses that work, so a few hundred or a few thousand labelled examples and a short run are often enough, and a small model fine-tunes on an ordinary CPU. A GPU makes each step faster, but nothing about the method needs one.

True or false?

During fine-tuning only the new head is trained, while the pretrained body stays frozen.

False. By default every weight is trained. The head changes a lot because it starts from random values; the body changes only slightly because it already starts from good ones.

Fine-tuning uses the same kind of training loop as training from scratch; what differs is the starting weights.

True. Forward pass, loss, backward pass and optimizer step are the same. Starting from pretrained weights is what saves the data and the time.

The Trainer: a training loop you configure

In plain PyTorch you write the training loop yourself: split the data into batches, shuffle it every epoch, run the forward pass, compute the loss, call loss.backward(), step the optimizer, reset the gradients, and every so often run the model on validation data to see how it does. That code is almost the same for every classifier. The Trainer class of Transformers is that loop, written once and tested, which you configure instead of writing by hand.

  • Next batch shuffled, padded
  • Forward pass model(batch)
  • Loss from the labels
  • Backward pass loss.backward()
  • Optimizer step AdamW, then scheduler
  • Zero gradients
  • Next batch to Forward pass
  • Forward pass to Loss
  • Loss to Backward pass
  • Backward pass to Optimizer step
  • Optimizer step to Zero gradients
  • Zero gradients to Next batch

Each turn of this loop is one step: one batch in, one update of the weights out. You hand the Trainer the pieces and it does the rest:

  • the model, which computes its own loss when the batch holds a labels column, as Transformers classifiers do;
  • the training set and the validation set, already tokenized; columns the model does not accept are dropped for you;
  • the tokenizer, passed as processing_class: the Trainer then pads each batch to its own longest text and saves the tokenizer beside the model;
  • a TrainingArguments object that holds the settings, such as the learning rate and the number of epochs.

It creates the optimizer itself (AdamW by default, with a learning rate schedule), moves the model to the available device, and runs on the CPU when no GPU is present.

A Trainer for a text classifier
from transformers import Trainer, TrainingArguments

args = TrainingArguments(output_dir="out")

trainer = Trainer(
    model=model,                  # a classifier with a new head
    args=args,                    # the settings of the run
    train_dataset=train_set,      # tokenized, with a labels column
    eval_dataset=validation_set,  # scored during training
    processing_class=tokenizer,   # pads each batch, saved with the model
)
trainer.train()

trainer.train() runs every epoch and returns a small result with the number of steps taken and the average training loss. The Trainer accepts no tokenizer= argument in current versions of Transformers; older examples that use it fail with a TypeError.

True or false?

With processing_class=tokenizer and no data collator, the Trainer pads every batch to the length of its own longest text.

True. When the processing class is a tokenizer, the Trainer uses DataCollatorWithPadding by default, which pads each batch dynamically.

The Trainer needs a GPU to run.

False. It uses whatever device is available and falls back to the CPU. A GPU only makes each step faster.

The few settings that matter

TrainingArguments has many options, and the defaults are sensible for most of them. Three decide most of what you get and how long you wait: the learning rate, the number of epochs and the batch size.

Learning rate

The learning rate sets how far the optimizer moves the weights at each step. For fine-tuning it is kept small, typically between 1e-5 and 5e-5 (the default is 5e-5; the official text classification guide uses 2e-5). The reason is the body: its weights already hold what pretraining learned, and large steps would push them far from those values, overwriting that knowledge with noise from a few hundred examples. Too small a rate has the opposite problem: the head learns so slowly that the run ends before it has learned the classes.

The value you set is the peak. By default the rate then falls in a straight line to zero at the last step, so the late steps only make fine corrections.

The default schedule with learning_rate=2e-5

learning rate (x 1e-5) against share of the training steps done

  • learning rate

Epochs

One epoch is one pass over the whole training set. More epochs give the model more chances to learn, and the training time grows with each one. Fine-tuning usually needs only a few (the default is 3). After some point extra epochs stop helping: the model starts to memorise the training examples instead of learning what generalises, and its results on the validation set stop improving or get worse.

Batch size

The batch size is how many examples go through the model in one step (per_device_train_batch_size, default 8). It decides how many steps an epoch has: the training rows divided by the batch size, rounded up, so 1,000 rows in batches of 16 make 63 steps. Larger batches give a steadier estimate of the gradient and fewer updates per epoch, and each step needs more memory and takes longer. Smaller batches update more often with noisier steps. On a CPU, 8 or 16 is a common choice.

SettingHigherLower
learning_ratefaster learning; too high damages the pretrained bodysafer for the body; too low and the head learns too little
num_train_epochsmore learning, longer run; too many and it memorisesshorter run; too few and it stops while still improving
per_device_train_batch_sizefewer, steadier steps; more memory per stepmore, noisier updates; less memory

True or false?

A larger learning rate always makes fine-tuning finish with a better model, just sooner.

False. Large steps move the pretrained weights far from what they learned, so the model can end up worse. Fine-tuning keeps the rate small for that reason.

With 640 training rows and a batch size of 16, one epoch has 40 steps.

True. One step processes one batch, so an epoch has 640 / 16 = 40 steps.

Reading the run after every epoch

The training loss alone does not tell you whether the model is getting better at the task. It measures how well the model fits the examples it trains on, and it keeps falling even when the model is only memorising them. To see real progress you score the model on the validation set, data it never trains on, after each epoch.

By default the Trainer does not do this. It does not evaluate during training at all, and it logs the training loss only every 500 steps, which a short run may never reach. Two settings make it score the validation set and log the training loss at the end of each epoch:

Evaluate and log once per epoch
args = TrainingArguments(
    output_dir="out",
    learning_rate=2e-5,
    num_train_epochs=3,
    per_device_train_batch_size=16,
    per_device_eval_batch_size=16,
    eval_strategy="epoch",     # score the validation set after each epoch
    logging_strategy="epoch",  # log the training loss after each epoch
)

Evaluation then reports the validation loss, as eval_loss. For a number about the task itself, such as accuracy, you write a small function and pass it as compute_metrics. After the whole validation set has gone through the model, the Trainer calls it with an EvalPrediction: the raw logits of every example and the true labels, both as NumPy arrays. The function picks the highest-scoring class for each example and returns a dictionary of metrics.

Accuracy from the validation logits
import numpy as np

def compute_metrics(eval_pred):
    logits, labels = eval_pred
    predictions = np.argmax(logits, axis=1)
    return {"accuracy": float((predictions == labels).mean())}

trainer = Trainer(
    model=model,
    args=args,
    train_dataset=train_set,
    eval_dataset=validation_set,
    processing_class=tokenizer,
    compute_metrics=compute_metrics,
)

The Trainer adds the prefix eval_ to what the function returns, so after each epoch you read three numbers side by side: the training loss, eval_loss and eval_accuracy. Their directions together tell you where the run stands.

Training lossValidation lossValidation metricWhat it means
fallsfallsrisesstill learning what generalises; another epoch may help
fallsflatflatgains have stopped; more epochs mostly cost time
fallsrisesflat or fallsmemorising the training set; fewer epochs would do as well

The validation set guides these choices, so its score is no longer an unbiased estimate of new data. The final, honest result comes from a separate test set that no decision has touched.

True or false?

compute_metrics receives the predicted class of each validation example.

False. It receives the raw logits and the labels. The function itself takes the argmax to turn logits into predicted classes.

A training loss that keeps falling while the validation loss rises is a sign of overfitting.

True. The model fits the training examples ever better while getting worse on data it has not seen, so it is memorising rather than generalising.

Seeds: making a run repeat

Run the same fine-tuning twice and, unless you take care, the numbers differ a little each time. The cause is that a run makes several random choices:

  • the starting weights of the new head, drawn at random when the model is loaded;
  • the order of the examples, shuffled again at every epoch;
  • dropout, which switches off a random part of the network's values at each training step.

A computer draws these from a random number generator, and a generator started from the same seed produces the same sequence every time. Fix the seed and every random choice repeats, so the losses and the metrics do too.

  • Fixed seed set_seed(42)
  • Head starting weights
  • Order of examples
  • Dropout
  • Same losses and metrics
  • Fixed seed to Head starting weights
  • Fixed seed to Order of examples
  • Fixed seed to Dropout
  • Head starting weights to Same losses and metrics
  • Order of examples to Same losses and metrics
  • Dropout to Same losses and metrics

TrainingArguments has a seed (default 42) that the Trainer sets when it is created. That covers the shuffling and dropout, but it comes too late for the head: a model you pass in with model= was loaded earlier, and its head was already drawn. So set the seed yourself, before loading the model, with set_seed, which seeds Python's random, NumPy and PyTorch at once.

Seed before the head is created
from transformers import AutoModelForSequenceClassification, set_seed

set_seed(42)  # the new head is drawn from this seed
model = AutoModelForSequenceClassification.from_pretrained(
    checkpoint, num_labels=2, id2label=id2label, label2id=label2id
)

args = TrainingArguments(output_dir="out", seed=42, eval_strategy="epoch")

A fixed seed promises the same numbers on the same machine with the same library versions. PyTorch does not guarantee identical results across its releases, across platforms, or between a CPU and a GPU, because the order of floating-point operations can differ. A seed also does not make a result better: it makes it repeatable, so that when you change one setting, the difference you see comes from that setting and not from chance.

True or false?

Passing seed=42 to TrainingArguments is enough to make the new head start from the same weights on every run.

False. The Trainer sets that seed when it is built, after a model passed with model= has already drawn its head. Call set_seed before from_pretrained.

The same seed, script and library versions on the same machine give the same losses and metrics on every run.

True. Every random choice comes from the seeded generators, so it repeats. On a different machine or another PyTorch version the numbers may differ slightly.