7 Fine-tuning to follow instructions

Language Models · v1.0.3

2026-11-03 01:40:27

Where we are

Where this fits

Built so far

  • tokenization, attention, a GPT architecture from scratch
  • pretraining, then real GPT-2 weights
  • a spam classifier — one task, two labels

Added here

  • the language-modeling head is kept, not replaced
  • the targets become full text responses
  • the objective stays next-token cross-entropy

The architecture does not change; the data distribution does.

Outline of key topics

  1. Why a pretrained base model completes text rather than obeying it
  2. The instruction dataset and the fixed Alpaca prompt template
  3. Dynamic padding, shifted targets, and the -100 ignore index
  4. Fine-tuning GPT-2 Medium and reading the loss curves
  5. Evaluating open-ended responses with an LLM judge

From completion to instruction

Completion is not obedience

A base model continues a fragment instead of carrying out the request stated in it.
  • pretraining optimises one objective: predict the next token
  • the result is capable of text completion
  • nothing in that objective rewards obeying a request

Given “Fix the grammar in this text,” a base model continues the text rather than fixing it.

Instruction fine-tuning

Two siblings of fine-tuning: narrowing to a label set, or broadening to arbitrary requests.

Definition

Continued training of the same pretrained model on data where input–output pairs are explicitly provided, so the model learns to interpret a task description and emit an appropriate answer.

  • the loss term is unchanged
  • instruction following is a consequence of the data distribution

The three-stage pipeline

Dataset preparation, model setup and fine-tuning, then evaluation.

The instruction dataset

Prompt styles and the Alpaca template

Two public prompt styles; Alpaca is used throughout this unit.
  • 1,100 instruction–response records: instruction, optional input, reference output
  • split 935 / 55 / 110 — train, validation, test
  • a fixed preamble, then ### Instruction:, then ### Input: only when non-empty

### Response: is both what the model learns to answer after, and the marker sliced on later.

Applying the template

def format_input(e):
    t = PREAMBLE
    t += "### Instruction:\n"
    t += e["instruction"]
    if e["input"]:
        t += "\n\n### Input:\n"
        t += e["input"]
    return t
  • preamble, then instruction, always
  • the input section appears only when the field is non-empty
  • the reference response is appended separately, for training examples only

Batching instruction data

Dynamic padding

Each batch pads only to its own longest sequence.
  • a custom collate function replaces PyTorch’s default
  • padding uses token ID 50256, <|endoftext|>
  • no dataset-wide maximum length is imposed

Observed batch widths vary — 61, then 76, then 73 — direct evidence that padding is per batch.

Targets and the ignore index

Padding positions become -100; the first end-of-text token is retained.
  • targets are the inputs shifted by one position
  • -100 is PyTorch’s default ignore_index: such positions are skipped by the loss

\[\text{CE}(\cdot,\cdot;\ \texttt{ignore\_index}=-100)\]

  • one terminal end-of-text token stays unmasked, so completion is learnable

The collate function

def collate(ids, bmax, pad=50256):
    ids = ids + [pad]
    ids = pad_to(ids, batch_max, pad)
    inputs, targets = ids[:-1], ids[1:]
    mask_all_but_first(targets, pad,
                       replacement=-100)
    return inputs, targets
  • append one end-of-text token
  • pad to the batch’s longest sequence
  • shift by one to build targets
  • keep the first pad token, mask the rest

Batches are moved to the training device inside the collate function; sequences are truncated at 1024 tokens.

Fine-tuning GPT-2 Medium

Capacity and training setup

  • 124M parameters is too limited in capacity for satisfactory instruction following
  • the medium checkpoint is roughly 1.42 GB

Training

  • the pretraining loop is reused unchanged
  • AdamW, \(5\times10^{-5}\), weight decay \(0.1\), two epochs

Loss over two epochs

Training loss solid, validation loss dotted, across two epochs.
  • training loss falls sharply in epoch one, ending near \(0.30\)
  • validation loss flattens around \(0.66\)
  • the gap is the ordinary signature of a small dataset

Further training is not essential and risks overfitting.

Baseline: the prompt echoed back. After two epochs: “The meal is cooked every day by the chef.”

Evaluating open-ended responses

An LLM judge

  • loss alone does not measure response quality; the prompt is sliced off and the answer read back
  • human preference comparison does not scale
  • a local Llama 3 8B instruct model, served by Ollama, scores each of the 110 test responses from 0 to 100

Scores are a relative signal, not an absolute measure; the judge is not fully deterministic, so runs are repeated and averaged.

Summary

Summary

Mechanism

  • the loss never changes; only the data distribution does
  • a fixed template gives the response a learnable boundary
  • dynamic padding, shifted targets, -100 for padding
  • one terminal end-of-text token left unmasked

Practice and beyond

  • capacity is a design decision: 355M parameters, two epochs over 935 examples
  • evaluation means generating on a test set and scoring with another model
  • next: preference fine-tuning (DPO), parameter-efficient fine-tuning (LoRA)

The models will change; the mechanism will not.