Now we'll implement the process of fine-tuning an LLM to follow human instructions, as shown in Figure 7.1. Instruction fine-tuning is a key technique for developing LLMs used in chatbots, personal assistants, and other conversational tasks.

Figure 7.1 The three main stages of training an LLM.
Introduction
We now know that pretraining an LLM involves a training process in which it learns to generate one word at a time. The resulting pretrained LLM can perform text completion, meaning it can finish a sentence or write a paragraph of text given a snippet as input.
However, pretrained LLMs often struggle with specific instructions, such as “correct the grammar in this text” or “rewrite this text in the passive voice.” Later, we’ll look at a concrete example in which we load a pretrained LLM as the basis for instruction fine-tuning, also known as supervised instruction fine-tuning.
Here, we focus on improving an LLM’s ability to follow such instructions and generate the desired responses, as shown in Figure 7.2.

Figure 7.2 An example instruction processed by an LLM to generate the desired response.
Preparing the dataset is a critical part of instruction fine-tuning. We’ll then complete all the steps in the three stages of the instruction fine-tuning process, starting with dataset preparation, as shown in Figure 7.3.

Figure 7.3 The three-stage fine-tuning process for a large language model.
Preparing a Dataset for Supervised Instruction
Let’s download and format the instruction dataset used to instruction-fine-tune a pretrained LLM. The dataset contains 1,100 instruction–response pairs similar to the one in Figure 7.2.
The following code implements and runs a function to download this dataset, which is a relatively small file (only 204 KB) in JSON format. JSON, or JavaScript Object Notation, mirrors the structure of Python dictionaries and provides a simple data interchange format that is easy for humans to read and machines to process.
The data list loaded from the JSON file contains 1,100 entries from the instruction dataset. Let’s print one of the entries to see the structure of each entry:
As we can see, the example entry is a Python dictionary object containing “instruction,” “input,” and “output.” Let’s look at another example:
Depending on the entry, the “input” field may occasionally be empty.
Format input
Instruction fine-tuning involves training a model on a dataset in which input–output pairs are provided explicitly, as in the entries we extracted from the JSON file. There are various ways to format these entries for an LLM. Figure 7.4 illustrates two different example formats, commonly called prompt styles, used to train well-known LLMs such as Alpaca and Phi-3.

Figure 7.4 A comparison of prompt styles for instruction fine-tuning LLMs. The Alpaca style (left) uses a structured format with defined sections, including instruction, input, and response, while the Phi-3 style (right) uses a simpler format with designated <|user|> and <|answer|> tokens.
The rest of this chapter uses the Alpaca prompt style because it is one of the most popular styles, largely because it helped define the original fine-tuning approach.
Let’s define a format_input function that converts entries in the data list into the Alpaca-style input format.
This format_input function takes a dictionary entry as input and constructs a formatted string. Let’s test it on the dataset entry data[50], which we looked at earlier:
Note that if the “input” field is empty, formatinput skips the optional ### Input: section. We can test this by applying the formatinput function to the entry data[999], which we examined earlier:
The output shows that an entry with an empty “input” field does not include the ### Input: section in the formatted input.
Split dataset
Before we move on to setting up the PyTorch data loaders in the next section, let’s split the dataset into training, validation, and test sets, similar to what we did with the spam classification dataset in the previous chapter. The following listing shows how we calculate the proportions for each split.
Having successfully downloaded and split the dataset and gained a clear understanding of its prompt format, we’re now ready for the core implementation of the instruction fine-tuning process. Next, we focus on developing the methods for building training batches to fine-tune the LLM.
Organizing data into training batches
As we move into the implementation phase of the instruction fine-tuning process, the next step, shown in Figure 7.5, focuses on building training batches efficiently. This involves defining a method that ensures our model receives the formatted training data during fine-tuning.

Figure 7.5 The three-stage process for instruction fine-tuning an LLM. Next, we look at step 2 of stage 1: assembling training batches.
The batching process for instruction fine-tuning is a bit more involved and requires us to create our own custom collate function, which we’ll then plug into the data loader. We implement this custom collate function to handle the specific requirements and format of our instruction fine-tuning dataset.
Let’s work through the batching process in several steps, including coding a custom collate function, as shown in Figure 7.6. First, to implement steps 2.1 and 2.2, we code an InstructionDataset class that applies format_input to all inputs in the dataset and pretokenizes them.

Figure 7.6 The five substeps for implementing the batching process: (2.1) apply the prompt template, (2.2) use the tokenization from previous chapters, (2.3) add padding tokens, (2.4) create target token IDs, and (2.5) replace the -100 placeholder tokens to mask padding tokens in the loss function.
This two-step process, detailed in Figure 7.7, is implemented in the init constructor of InstructionDataset.

Figure 7.7 The first two steps of implementing the batching process. Entries are first formatted using a specific prompt template (2.1) and then tokenized (2.2), producing token ID sequences the model can process.
Alignment Input
Similar to the approach used in classification fine-tuning, we want to speed up training by collecting multiple training examples in a batch, which requires padding all inputs to a similar length. As in classification fine-tuning, we use the <|endoftext|> token as the padding token.
We can add the token ID corresponding to <|endoftext|> directly to the pretokenized input instead of appending the <|endoftext|> token to the text input. We can use the tokenizer’s .encode method on the <|endoftext|> token to confirm which token ID we should use:
Moving on to step 2.3 of the process (see Figure 7.6), we take a more sophisticated approach and develop a custom collate function so that we can pass it to the data loader.
This custom collate function pads the training examples in each batch to the same length while allowing different batches to have different lengths, as shown in Figure 7.8. This approach minimizes unnecessary padding by extending sequences only to match the longest sequence in each batch, rather than the longest sequence in the entire dataset.

Figure 7.8 Padding training examples with token ID 50256 to ensure uniform length within each batch. Each batch may have a different length, as shown in the first and second batches.
We can implement the padding process with a custom collate function.
Our customcollatedraft_1 implementation is designed to integrate with the PyTorch DataLoader, but it can also be used as a standalone utility. Here, we use it on its own to test and verify that it works as expected. Let’s try it with three different inputs that we want to assemble into a batch, with each example padded to the same length:
This output shows that all inputs have been padded to the length of the longest input list, inputs_1, which contains five token IDs.
Alignment Target
We’ve just implemented our first custom collate function for creating batches from lists of inputs. However, as we learned earlier, we also need to create target token IDs corresponding to the batch of input IDs.

Figure 7.9 The five substeps involved in implementing the batching process. We now focus on step 2.4, creating the target token IDs. This step is crucial because it enables the model to learn and predict the tokens it needs to generate.
As Figure 7.9 shows, these target IDs are essential because they represent what we want the model to generate and what we need to compute the loss used for weight updates during training. That is, we modify the custom collate function to return target token IDs in addition to input token IDs.
Similar to the process we used to pretrain the LLM, the target token IDs match the input token IDs but are shifted one position to the right. As Figure 7.10 shows, this setup enables the LLM to learn how to predict the next token in a sequence.

Figure 7.10 Input and target token alignment used during instruction fine-tuning of an LLM. For each input sequence, the corresponding target sequence is created by shifting the token IDs one position to the right, ignoring the first token of the input, and appending an end-of-text token.
The updated collate function below generates target token IDs from the input token IDs:
In the next step, we assign all padding tokens the placeholder value -100, as shown in Figure 7.11.

Figure 7.11 The five substeps for implementing the batching process. After creating the target sequences by shifting the token IDs one position to the right and appending an end-of-text token, in step 2.5 we replace the end-of-text padding tokens with the placeholder value (-100).
This special value lets us exclude these padding tokens from the training loss calculation, ensuring that only meaningful data affects what the model learns. We’ll discuss this process in more detail after implementing this modification. (When we did classification fine-tuning, we didn’t have to worry about this because we trained the model only on the final output token.)
However, note that we keep one end-of-text token, ID 50256, in the target list, as shown in Figure 7.12.

Figure 7.12 Step 2.4 of the token replacement process for the target batch during training data preparation. We replace all but the first end-of-text token instance with the placeholder value -100 as padding while keeping the initial end-of-text token in each target sequence.
Keeping it allows the LLM to learn when to generate the end-of-text token based on an instruction, which we use as an indicator that the generated response is complete.
In the following listing, we modify the custom collate function to replace ID 50256 with -100 in the target list. In addition, we introduce an allowedmaxlength parameter to optionally limit the length of samples. This adjustment is useful if you plan to use a dataset that exceeds the 1,024-token context size supported by the GPT-2 model.
Why change placeholder token ID
The modified collate function works as expected, changing the target list by inserting token ID -100. What’s the logic behind this adjustment? Let’s explore the underlying purpose of this modification.
For demonstration purposes, consider the following simple, self-contained example, where each output logit corresponds to a potential token in the model’s vocabulary. The following shows how we calculate the cross-entropy loss when the model predicts a sequence of tokens, similar to what we did when pretraining the model and fine-tuning it for classification.
As we’d expect, adding an extra token ID affects the loss calculation:
So far, we’ve done a few more or less obvious example calculations with the cross-entropy loss function in PyTorch, which is also the same loss function we used in the training functions for pretraining and classification fine-tuning. Now let’s get to the interesting part and see what happens if we replace the third target token ID with -100:
The loss for these three training examples is exactly the same as the loss we calculated earlier from the two training examples. In other words, the cross-entropy loss function ignores the third entry (token ID) in the targets_3 vector, which corresponds to -100.
So what makes -100 special enough to be ignored by the cross-entropy loss?
The default setting for the cross-entropy function in PyTorch is crossentropy(..., ignoreindex=-100). This means it ignores targets labeled -100. We take advantage of this ignore_index to ignore the extra end-of-text (padding) tokens we use to pad training examples so that each batch has the same length. However, we want to keep one 50256 (end-of-text) token ID in the targets because it helps the LLM learn to generate the end-of-text token, which we can use as an indicator that the response is complete.
In addition to masking padding tokens, it’s also common to mask the target token IDs corresponding to the instruction, as shown in Figure 7.13.

Figure 7.13 Left: We tokenize the formatted input text and then provide it to the LLM during training. Right: The target text we prepare for the LLM, where we can optionally mask the instruction part, meaning we replace the corresponding token IDs with the -100 ignore_index value.
By masking the LLM target token IDs that correspond to the instruction, the cross-entropy loss is calculated only for the target IDs of the generated response. As a result, the model is trained to focus on generating accurate responses rather than memorizing the instruction, which helps reduce overfitting.
As of this writing, researchers disagree about whether masking instructions during instruction fine-tuning is generally beneficial. For example, the 2024 paper “Instruction Fine-Tuning and Instruction Loss” by Shi et al. (https://arxiv.org/abs/2405.14394) demonstrates the benefits of not masking instructions for LLM performance. Here, we won’t apply masking, leaving it as an optional exercise for interested readers.
Creating data loaders for an instruction dataset

Figure 7.14 The three-stage process for instruction fine-tuning an LLM.
We’ve completed several stages to implement the InstructionDataset class and the customcollatefn function for the instruction dataset. As shown in Figure 7.14, we’re ready to reap the rewards of our work by simply plugging two InstructionDataset objects and the customcollatefn function into PyTorch data loaders.
These loaders will automatically shuffle and organize batches for the LLM instruction fine-tuning process.
Previously, we moved data to the target device in the main training loop (for example, GPU memory when device="cuda"). Doing this as part of the collate function has the advantage of performing the device transfer as a background process outside the training loop, preventing it from blocking the GPU during model training.
Next, to reuse the selected device setting in customcollatefn when we plug it into the PyTorch DataLoader class, we use the partial function from Python’s functools standard library to create a new version of the function with the device parameter pre-filled. In addition, we set allowedmaxlength to 1024, which truncates the data to the maximum context length supported by the GPT-2 model we’ll fine-tune later:
from functools import partial
customized_collate_fn = partial(
custom_collate_fn,
device=device,
allowed_max_length=1024
)
Next, we can set up the data loaders as before, but this time we’ll use our custom collate function for the batching process.
Let’s check the dimensions of the input and target batches generated by the training loader:
This output shows that the first input and target batch has dimensions 8 × 61, where 8 is the batch size and 61 is the number of tokens for each training example in that batch. The second input and target batch has a different number of tokens, 76, for example. Thanks to our custom collate function, the data loader can create batches of different lengths.