Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Supervised Fine-Tuning: Model Training

In the previous chapter, we built the SFT training data: 512 (prompt, response) pairs. In this chapter, we will use this data to perform supervised fine-tuning on the pre-trained model.

Supervised fine-tuning

The core idea of supervised fine-tuning: compute the loss only on the response part.

During pre-training, the model computes a loss at every position, because every position is learning to predict the next token. But in supervised fine-tuning, we only care whether the model has learned to generate suitable answers, and we do not need it to learn how to generate prompts.

Mask

The solution is to add a mask to every sample:

  • Prompt part: the mask is 0 and no loss is computed;

  • Response part: the mask is 1 and the loss is computed as usual.

This way, the prompt part produces no loss, and the model learns only from the response part.

Strategy

  • Learning rate: supervised fine-tuning usually uses a learning rate one order of magnitude smaller than pre-training. The model is already trained, and we only want to adjust the direction in which it generates text, not relearn language knowledge;

  • Epochs: SFT data is small and training for too long easily overfits, so the number of epochs is usually small. This chapter trains for only 1 epoch.

Dataset

SFT dataset

The SFT dataset SFTDataset differs from the pre-training dataset: it processes (prompt, response) pairs:

  • Concatenation: join the prompt and the response into one token sequence;

  • Truncation: if the sequence exceeds the context size, truncate from the head of the prompt and keep the complete response;

  • Masking: give the prompt part a mask of 0 and the response part a mask of 1. The result is returned as (features, labels, mask).

In addition, the samples have different lengths, so the batch size is fixed at 1 and no padding is needed.

Loss function

SFT cross-entropy loss function

The SFT loss function SFTLoss is a cross-entropy loss function with a mask:

  • compute the cross-entropy at all positions;

  • multiply by the mask, keeping only the loss of the response part;

  • divide by the length of the response part (the number of 1s in the mask) to take the average over the valid values.

During backpropagation, the gradient at the prompt positions is likewise 0.

Trainer

SFT trainer

The SFT trainer SFTTrainer inherits from the GPT trainer GPTTrainer. The main differences are:

  • train (training function): receives the mask from the dataset and passes it to the loss function as an argument;

  • test (test function): no testing is needed in supervised fine-tuning, so it returns None directly.

SFT trains for only 1 epoch and saves the model parameters right after.

Hyperparameters

Learning rate

Supervised fine-tuning uses a smaller learning rate to avoid disturbing the pre-training result too much.

Model parameters

The other model parameters must stay the same as in the pre-training stage.

Modeling

Loading the model

The pre-training dataset CharDataset is used here only to provide the vocabulary and the conversion between text and tokens.

Loading the SFT data

The SFT samples are split 9:1 into a training set and a test set. The training set has 460 samples and the batch size is 1, so one epoch has 460 steps. The 52 samples of the test set are not used in this chapter.

Training

Use a warmup-cosine learning rate scheduler: warm up linearly to LEARNING_RATE over the first 50 steps, then decay along a cosine curve to LEARNING_RATE / 10.

epoch 1 step 100/460 loss 1.5225 lr 0.000097
epoch 1 step 200/460 loss 1.4181 lr 0.000074
epoch 1 step 300/460 loss 1.3249 lr 0.000040
epoch 1 step 400/460 loss 1.3159 lr 0.000015
epoch 1 saved SFT model to ../../../../data/tinyshakespeare-sft.npz

Inference

Let the fine-tuned model generate, starting from the prompt ROMEO:.

ROMEO:
He theople, that low with many thrieve weak:
While crampudged you I know the valous in your blood,
I must my patience, and my Edward's life!

TRANIO:

ANORTEN:

POLIXENES:
I know not mine a deep a shado, your whom

PETRUCHIO:
You say you know! but know re

In this chapter, we performed supervised fine-tuning on the pre-trained model with the SFT dataset: only the loss of the response part is computed, so that the model learns the (prompt, response) conversation format. From the generated result we can see that the model keeps the “speaker: speech” turn-taking format, but the content is still incoherent.

But SFT has its own limitation: it only tells the model how to answer a question, not what a better answer is. For example, two answers may both be correct, but one is concise and clear while the other is wordy. SFT cannot tell the model which one is better.

In the next chapter, we will introduce Direct Preference Optimization (DPO), so that the model learns to pick the better one among several answers.

Exercises

Try raising the SFT learning rate, for example to the same value as in pre-training, and observe the training result. Think about why fine-tuning needs a smaller learning rate.