← Build a Large Language Model… Latent Shelf · Ch.7

Book Study Guide · Sebastian Raschka · Chapter 7 · Finale

Finetuning to Follow Instructions

Pretraining taught it language; classification taught it one label. Instruction finetuning teaches it to do what you ask — the step that turns a text completer into an assistant.

— the last mile

The capstone. It turns the pretrained GPT into an instruction-follower: formatting an instruction dataset with a prompt template, batching with a custom collate function and target masking, finetuning the model, and evaluating its responses — including using another LLM as an automated judge.

instruction datasetAlpaca prompttarget masking (−100)LLM-as-judge15 quiz questions
01Instruction finetuning

Teaching the model to follow instructions

A pretrained LLM can complete text, but it struggles with explicit instructions like "Fix the grammar in this text" or "Convert this to passive voice." Instruction finetuning (supervised instruction finetuning) trains the model on instruction–response pairs so it learns to produce the desired response for a given instruction — the technique behind chatbots and personal assistants.

Key concept · The instruction dataset

The book uses a purpose-built dataset of 1,100 instruction–response pairs in JSON. Each entry has three fields: an instruction ("Identify the correct spelling…"), an optional input (extra context, sometimes empty), and the output (the desired response). The data is split 85/10/5 into train / test / validation. Unlike classification, the "label" here is a full free-form text response, not a class — which shapes everything about how the data is prepared.

02Prompt format

Wrapping entries in a prompt template

Raw fields must be assembled into a consistent prompt style so the model learns a predictable input→output shape. The book uses the Alpaca template (one of the earliest and most popular).

Key concept · The Alpaca prompt style

Each entry is formatted as: a fixed preamble ("Below is an instruction that describes a task. Write a response that appropriately completes the request."), then ### Instruction: with the instruction, an optional ### Input: section (omitted when the input field is empty), and finally ### Response: with the desired output. This structured format gives the model clear delimiters to learn from. (An alternative shown is the Phi-3 style, which uses <|user|>/<|assistant|> tokens instead — a reminder that prompt formats vary across models.)

03Batching

A custom collate function

Instruction examples vary in length, so — as in Chapter 6 — they must be padded. But here the batching is more involved, needing a custom collate function plugged into the DataLoader.

Key concept · Per-batch padding and shifted targets

An InstructionDataset formats each entry with the prompt template and pre-tokenizes it. The custom collate function then: pads every example in a batch to the length of the longest example in that batch (using token 50256) — a smarter approach than Chapter 6's dataset-wide padding, since it minimizes unnecessary padding (different batches can have different lengths). It builds the target as the input shifted one position right, with an end-of-text token appended, so the model learns next-token prediction on the response — and learns to emit an end-of-text token to signal it's done.

04Target masking

Excluding padding from the loss

A subtle but important step: the target tokens are edited so the model isn't penalized (or rewarded) for predicting padding.

Key concept · The −100 placeholder

In each target sequence, all padding tokens except the first end-of-text token are replaced with the value −100. Why −100? PyTorch's cross_entropy has a default ignore_index of −100, so any target position set to −100 is excluded from the loss — the padding doesn't influence training. The first end-of-text token is kept (not masked) so the model still learns when to stop generating. (The book notes some implementations also mask the instruction/prompt portion of the target so the loss is computed only on the response; this book masks just the padding.) An optional allowed_max_length can truncate examples that exceed the model's 1,024-token context.

05Finetune & evaluate

Training the model — and judging its answers

With the data pipeline built, finetuning reuses the Chapter 5 training loop, and the chapter closes by evaluating the results.

Key concept · Finetuning and extracting responses

The base model is a larger GPT-2 (355M "medium") — a more capable starting point than the 124M model — loaded with OpenAI's pretrained weights. Instruction finetuning runs the familiar loop (epochs → batches → reset → cross-entropy loss → backward → AdamW update), and the training/validation loss falls as the model learns to follow instructions. To evaluate, the finetuned model generates responses to the held-out test instructions; because the output includes the formatted prompt, you extract just the response portion (the text after ### Response:) for scoring.

Key concept · Evaluating with an LLM judge

Scoring free-form responses by hand doesn't scale, so the book uses another LLM as an automated judge: it runs Llama 3 (8B) locally via Ollama and prompts it to score each generated response against the correct answer on a 0–100 scale. Averaging those scores gives a single quality number for the finetuned model — the same "AI-as-a-judge" idea used across the industry. The finetuned model produces coherent, on-instruction answers, completing the journey: you've now built, pretrained, and finetuned a GPT entirely from scratch. Natural next steps the book points to include preference finetuning (e.g. DPO) to further align the model's tone and helpfulness.

★Test yourself

Chapter 7 quiz

Fifteen questions on instruction finetuning, prompt formatting, batching, masking, and evaluation. Answer first, then expand Show answer.

Part A · Multiple choice

Q1

Instruction finetuning trains a model on:

  • A Instruction–response pairs
  • B Class labels only
  • C Raw unlabeled text only
  • D Images
Show answer

A. So it learns to produce the desired response for a given instruction.

Q2

Each dataset entry has which three fields?

  • A instruction, input (optional), output
  • B question, answer, score
  • C prompt, model, logits
  • D text, label, id
Show answer

A. The input field is sometimes empty.

Q3

The Alpaca prompt style uses sections labeled:

  • A ### Instruction, ### Input (optional), ### Response
  • B <|user|> / <|assistant|>
  • C Q: / A:
  • D BEGIN / END
Show answer

A. The Phi-3 style instead uses <|user|>/<|assistant|> tokens.

Q4

When the input field is empty, the formatted prompt:

  • A Omits the ### Input: section
  • B Leaves it blank but present
  • C Errors out
  • D Duplicates the instruction
Show answer

A.

Q5

The custom collate function pads each example to:

  • A The longest example in its batch (padding varies by batch)
  • B The longest example in the whole dataset
  • C Exactly 1024 tokens always
  • D No padding
Show answer

A. This minimizes unnecessary padding vs. dataset-wide padding.

Q6

How is the target sequence built from the input?

  • A The input shifted one position right, with an end-of-text token appended
  • B The input reversed
  • C Identical to the input
  • D A single class label
Show answer

A. Next-token prediction, as in pretraining.

Q7

Padding tokens in the target are replaced with −100 because:

  • A PyTorch's cross_entropy ignores index −100, excluding them from the loss
  • B −100 is a valid token
  • C It makes training faster only
  • D It's the padding token ID
Show answer

A. So padding doesn't influence weight updates.

Q8

Why keep the first end-of-text token unmasked in the target?

  • A So the model learns when to stop generating
  • B To pad more
  • C It's a bug
  • D To increase the loss
Show answer

A. Only the subsequent padding tokens are set to −100.

Part B · True or false

Q9

A pretrained (but not instruction-finetuned) LLM reliably follows explicit instructions.

Show answer

False. It can complete text but struggles with instructions — the motivation for this chapter.

Q10

The chapter uses a larger GPT-2 (355M "medium") as the base model.

Show answer

True. A more capable starting point than the 124M model.

Q11

The instruction-finetuning loss is the same cross-entropy next-token loss used in pretraining.

Show answer

True. With padding masked out via −100.

Q12

The book evaluates responses by hand only, with no automation.

Show answer

False. It uses another LLM (Llama 3 via Ollama) to score responses 0–100 automatically.

Part C · Short answer

Q13

Why extract just the response portion of the model's output before scoring?

Show answer

Because the generated output includes the formatted prompt; only the text after "### Response:" is the model's actual answer to evaluate.

Q14

How does per-batch padding improve on Chapter 6's approach?

Show answer

It pads only to the longest example in each batch (not the whole dataset), so different batches can have different lengths and unnecessary padding is minimized.

Q15

Summarize the full journey of building an LLM across the book.

Show answer

Prepare text data and embeddings → code attention → build the GPT architecture → pretrain (or load pretrained weights) → finetune for classification, then finetune to follow instructions — a complete GPT built and adapted from scratch.