Hello! Welcome back to our module on Fine-Tuning Language Models.
Introduction
In our last lesson, we took a deep dive into Low-Rank Adaptation (LoRA). We learned how its clever low-rank decomposition allows us to efficiently adapt massive language models with minimal trainable parameters, all while avoiding any extra latency at inference time. You now understand the mechanism for fine-tuning.
Today, we shift our focus from the "how" to the "what." A fine-tuning process is only as good as the data it's trained on. This lesson is dedicated to the crucial task of preparing that data. Our learning outcome is to prepare and format an instruction-following dataset for fine-tuning. We'll cover the entire journey, from raw information to a precisely structured format that an LLM can learn from.
Specifically, we will cover:
- What an instruction-following dataset is and common formats like the Alpaca format.
- The data engineering process of acquiring and structuring this data.
- The critical technical steps of formatting the data for a causal language model, including tokenization, creating shifted labels, and, most importantly, masking.
This stage is a blend of data engineering and deep learning mechanics, and getting it right is fundamental to successful fine-tuning.

Part 1: Anatomy of an Instruction Dataset
Before we can format a dataset, we first need to understand its structure and where the data comes from.
Data Sources
As a software engineer, you can think of data acquisition as the first step in a data pipeline. For fine-tuning, the data generally comes from three places:
- Public Datasets: The AI community has created many open-source instruction datasets (e.g.,
databricks-dolly-15k,Open-Orca). These are excellent for learning and for building general-purpose assistants. The Hugging Face Hub is the main repository for these. - Internal Data: This is often the most valuable source for commercial applications. It includes proprietary company data like support tickets, internal documentation, or customer interaction logs. Fine-tuning on this data creates a model with specialized, private knowledge.
- Synthetic Data: When high-quality data is scarce, we can use a powerful "teacher" LLM (like GPT-4o) to generate new instruction-response pairs based on raw documents. This is a very common and effective strategy.
Dataset preparation for LLM post-training
To get a more detailed overview of these data sources, please read this section from the Anyscale documentation.
Read the section titled 'Sources of training data'. It provides context on when and why you would choose each type of data source.
The Alpaca Format
Regardless of the source, the data needs to be structured. For single-turn instruction following, the most common structure is the Alpaca format. It's a simple JSON format that represents a single instruction-response pair.
Each entry is a JSON object with a few key fields. The most important are instruction and output.
[
{
"instruction": "Provide a brief summary of the plot of 'Dune'.",
"input": "",
"output": "Dune is a sci-fi epic about Paul Atreides..."
},
{
"instruction": "Identify the correct spelling of the following word.",
"input": "accomodate",
"output": "accommodate"
}
]
instruction: The task you want the model to perform.input(optional): Additional context for the instruction. If provided, it's typically combined with theinstructionto form the full prompt.output: The ideal response you want the model to learn to generate.
This clean, simple format is the standard for many fine-tuning tasks. Let's see how it's used in practice.
How to Create Custom Instruction Datasets for LLM Fine ...
This article from Firecrawl provides another clear example and discusses how these datasets are used. The Anyscale documentation also provides a specific example for supervised fine-tuning.
Read the first two sections, 'What Are Instruction Datasets?' and 'What Formats Do Instruction Datasets Use?'. This will solidify your understanding of the basic structure and file formats (JSON/JSONL). You can skim the parts about metadata.
Part 2: The Data Engineering Pipeline
Getting your knowledge into the Alpaca JSON format is a significant data engineering task. It often involves a multi-step pipeline, especially when creating a dataset from scratch using internal or web-scraped documents.

A common modern workflow looks like this:
- Scrape/Load: Gather raw data (e.g., from documentation websites, PDFs, or databases).
- Clean & Chunk: Clean the text (e.g., remove HTML tags) and break it into smaller, meaningful chunks.
- Generate Instruction-Pairs: For each chunk of text, use a powerful "teacher" LLM to generate one or more relevant instruction/output pairs. For example, you might prompt GPT-4o: "Given the following text about our API, create a question a developer might ask and the corresponding answer based only on the text."
- Format & Validate: Assemble the generated pairs into the final Alpaca-style JSON file and perform quality checks.
The article from Firecrawl provides a fantastic, code-centric walkthrough of this entire process. While you don't need to read it all now, it's a valuable resource that shows how to implement this pipeline in Python.
How to Create Custom Instruction Datasets for LLM Fine ...
To understand the steps of this pipeline in more detail, please review the summary of the process from the Firecrawl article.
Read the section titled 'General Process For Creating Instruction Datasets'. It provides a concise, step-by-step checklist of the entire data preparation pipeline from a practical engineering standpoint.
Part 3: Formatting the Data for Model Training
Now for the most technical part. Once we have our clean JSON file, we can't just feed it to the model. We need to convert it into a format that aligns with how causal language models are trained: predicting the next token.
This involves several steps, which are often implemented in a PyTorch Dataset and DataLoader. Let's watch an expert walk through this process. Sebastian Raschka's video provides a from-scratch implementation that makes the underlying mechanics very clear.
Build an LLM from Scratch 7: Instruction Finetuning
This video from Sebastian Raschka breaks down the process of preparing a dataset for instruction fine-tuning. We'll focus on the key steps of formatting, tokenizing, and creating labels.
Please watch the following segments: Dataset Structure (05:05 - 08:34): See the example JSON dataset and how it's formatted into a single string using a prompt template (the Alpaca style). The 5-Step Process (15:28 - 21:36): Pay close attention as he outlines the five crucial steps: formatting, tokenizing, padding, creating target IDs, and masking padding tokens. This is the theoretical roadmap. Masking Padding Tokens (24:55 - 39:30): This is a long but critical segment. Skim the initial code setup and focus on the final implementation of the custom_collate function. Pay special attention to the explanation starting around 35:00 where he demonstrates why masking padding tokens with -100 works in PyTorch's CrossEntropyLoss.
Let's break down the two most critical concepts from that video and add a crucial third one.
1. Prompt Templating
The first step is to convert the instruction, input, and output fields into a single piece of text. This is done using a prompt template. Different models are trained with different templates, and using the correct one is important.
For example, the Alpaca template combines the fields like this:
Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
{instruction}
### Input:
{input}
### Response:
{output}
During training, the model sees this entire text.
2. Shifting for Causal Language Modeling
An LLM is trained to predict the next token. This means for a given sequence of tokens, the input to the model is the sequence up to a certain point, and the label (what it should predict) is the sequence shifted by one token.
- Input Tokens:
[token_1, token_2, token_3, ... token_n-1] - Target Labels:
[token_2, token_3, token_4, ... token_n]
The model's goal is to learn that when it sees token_1, it should predict token_2; when it sees the sequence up to token_2, it should predict token_3, and so on.
3. The Crucial Art of Masking
This is the most important and often misunderstood part of data preparation for fine-tuning. We do not want the model to learn from every token in our formatted text. We use a special value, -100, to "mask" certain tokens in our target labels. PyTorch's loss functions, by default, completely ignore tokens with the label -100 when calculating the loss.
We need to mask two things:
A. The Prompt Tokens: We only want the model to learn to generate the ### Response: {output} part. We don't want it to calculate loss on its predictions for the instruction part of the prompt. Therefore, we replace the labels corresponding to the prompt tokens with -100.
B. The Padding Tokens: When we create batches of data, examples will have different lengths. We pad shorter examples with a special padding token to make them all the same length. We don't want the model to learn to predict padding tokens, so we also replace the labels for these padding tokens with -100.
This video provides an excellent visual explanation of masking the prompt.
Finetune LLMs to teach them ANYTHING with Huggingface and Pytorch | Step-by-step tutorial
This video from Neural Breakdown gives a very clear explanation of why and how we mask the prompt tokens in the target labels.
Watch the segment from 20:42 to 26:08. Focus on how the full tokenized sequence is split into input_ids and target_ids, and how the target_ids corresponding to the prompt are replaced with -100 so that loss is only calculated on the answer.
Test your understanding!
Imagine your formatted and tokenized text for one training example is:
[PROMPT_TOKEN_1, PROMPT_TOKEN_2, ANSWER_TOKEN_1, ANSWER_TOKEN_2, EOS_TOKEN]
EOS_TOKEN is the "end-of-sequence" token that signals the end of the generation.
What would the input_ids and labels tensors look like for this single example before batching and padding? Use -100 for masked tokens.
Show answer
The goal is for the model to predict the answer and the end-of-sequence token, but not the prompt.
-
input_ids: This is the full sequence, as the model needs all prior context to make the next prediction.[PROMPT_TOKEN_1, PROMPT_TOKEN_2, ANSWER_TOKEN_1, ANSWER_TOKEN_2, EOS_TOKEN] -
labels: This is the shifted sequence, with the prompt tokens masked out.[-100, -100, ANSWER_TOKEN_2, EOS_TOKEN, -100 (or another token, often EOS)]Let's be more precise based on the common "shift-left" method:
The raw shifted labels would be:[PROMPT_TOKEN_2, ANSWER_TOKEN_1, ANSWER_TOKEN_2, EOS_TOKEN, padding/EOS]
After masking the prompt portion, the finallabelstensor becomes:labels:[-100, -100, ANSWER_TOKEN_2, EOS_TOKEN](assuming the sequence ends here for simplicity).
The key insight is that the loss will only be calculated where the labels are ANSWER_TOKEN_2 and EOS_TOKEN. The model's predictions for the first two prompt tokens are ignored.
Conclusion
You've now walked through the entire data preparation pipeline for instruction fine-tuning, from high-level data sourcing to the low-level mechanics of token masking. This is a critical skill that underpins your ability to customize LLMs for specific tasks.
Key Takeaways:
- Standard Format: Instruction-following datasets are typically structured as a list of JSON objects, with the Alpaca format (
instruction,input,output) being a common standard. - Data Pipeline: Creating a custom dataset is a data engineering task involving sourcing/scraping, cleaning, chunking, and often using a "teacher" LLM to generate high-quality instruction-response pairs.
- Prompt Templating: The structured JSON is converted into a single string using a model-specific prompt template.
- Shifted Labels: For causal language modeling, the target labels are the input tokens shifted one position to the left.
- Critical Masking: To ensure the model only learns to generate the desired response, we mask out the prompt tokens and any padding tokens from the loss calculation by setting their corresponding labels to
-100.
Next Up:
We have our efficient training method (LoRA) and we know how to prepare our data. In the next lesson, we will finally bring it all together. You will fine-tune an open-source LLM on a custom dataset using a PEFT method like LoRA, applying the concepts from this and the previous lesson in a hands-on coding exercise.