Skip to content
ImagineWorld

Supervised Fine-Tuning

node_idnode-book_building-frontier-llm-from-scratch_chapter-22-supervised-fine-tuning
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num22
chapter_titleSupervised Fine-Tuning
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Part VI — Post-Training and Alignment

The base model that emerges from pretraining is a brilliant autocomplete and a poor assistant. Ask it a question and it is as likely to continue with three more questions as to answer, because it learned to continue text, not to follow instructions. Supervised fine-tuning (SFT) is the first and simplest alignment step: show the model thousands of examples of instructions paired with good responses, and train it — with the same next-token loss it already knows — to produce the response. This chapter covers SFT and the parameter-efficient methods (LoRA) that make it cheap enough to do on modest hardware.

The gap between a base model and an assistant is one of behavior, not knowledge. The base model already contains the information; it simply has no notion that a turn of conversation should end, that a question warrants an answer, or that it is playing the role of a helpful assistant. SFT instills these conventions by example. It does not teach the model much new factual content — that was pretraining’s job, or continued pretraining’s (Chapter 17) — it teaches the model how to deploy what it knows in a useful format.

SFT data is a collection of conversations: a user instruction (sometimes with a system prompt and prior turns) and an ideal assistant response. Each is rendered into a single token stream using the chat template of Chapter 5 — the exact special-token format, with role markers, that the model will see forever after. Quality matters far more than quantity here: a few tens of thousands of carefully written, diverse examples typically beat millions of mediocre ones, a lesson the open community learned repeatedly. The data may be human-written, distilled from a stronger model (Chapter 26), or a mix.

Mechanically, SFT is ordinary next-token training with one crucial change: the loss is computed only on the assistant’s response, not on the prompt. We do not want the model to learn to generate user instructions; we want it to learn the response given the instruction. This is done by masking the prompt tokens in the labels so the loss ignores them.

# input_ids: the full templated conversation (prompt + response)
labels = input_ids.clone()
labels[:prompt_len] = -100 # -100 is ignored by cross_entropy
logits = model(input_ids)
loss = F.cross_entropy(logits.view(-1, logits.size(-1)),
labels.view(-1), ignore_index=-100) # response tokens only

Python — sft.py: mask the prompt, train only on the response

The hyperparameters are gentle: a small learning rate (the model is already capable and easily damaged), only one to three epochs over the data (more causes overfitting and degradation), and the usual warmup and decay. The output is an instruct or chat model that follows instructions and holds a conversation — already dramatically more useful than the base model, and for many applications, enough. What SFT cannot easily teach is preference between two plausible responses, which is where Chapter 23 begins.

22.4 Parameter-Efficient Fine-Tuning: LoRA

Section titled “22.4 Parameter-Efficient Fine-Tuning: LoRA”

Full fine-tuning updates every weight, which for a large model means storing gradients and optimizer state for billions of parameters — often more memory than inference itself. LoRA (Low-Rank Adaptation) avoids this using the low-rank idea from Chapter 2. It freezes the pretrained weights entirely and learns a small low-rank update for each weight matrix: W+ABW + AB, where AA and BB are thin matrices of rank rr (often 8 or 16). Only AA and BB are trained — a tiny fraction of the parameters — and at inference the update can be merged back into the weights for free. The layer is short:

class LoRALinear(nn.Module):
def __init__(self, base, r=8, alpha=16):
super().__init__()
self.base = base
for p in self.base.parameters(): p.requires_grad = False
d_in, d_out = base.in_features, base.out_features
self.A = nn.Parameter(torch.randn(d_in, r) * 0.01)
self.B = nn.Parameter(torch.zeros(r, d_out)) # zero -> no change at start
self.scale = alpha / r
def forward(self, x):
return self.base(x) + (x @ self.A @ self.B) * self.scale

Python — lora.py: a low-rank adapter wrapping a frozen linear layer

Initializing B to zero means the adapter starts as a no-op, so training begins exactly at the pretrained model and departs smoothly. QLoRA pushes this further by keeping the frozen base weights in a quantized 4-bit form (Chapter 26) while training the LoRA adapters in higher precision — making it possible to fine-tune a very large model on a single GPU. Table 22.1 compares the options.

MethodTrained parametersBase weightsMemory
Full fine-tuningallupdatedhighest (grads + optimizer for all)
LoRAsmall low-rank adaptersfrozen (full precision)much lower
QLoRAsmall low-rank adaptersfrozen (4-bit quantized)lowest — one GPU for large models

Table 22.1 — Full fine-tuning versus parameter-efficient methods

Everything in this chapter — the prompt masking, the LoRA adapters, the 4-bit base — is, in practice, a few lines of configuration with Hugging Face’s peft and trl. Here is the complete, real recipe for QLoRA-fine-tuning an open base model, reproduced; it is what most practitioners actually run:

from peft import LoraConfig
from trl import SFTTrainer, SFTConfig
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
# load the base model in 4-bit (the "Q" in QLoRA)
bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4")
model = AutoModelForCausalLM.from_pretrained("base-model",
quantization_config=bnb)
# attach LoRA adapters to the attention and FFN projections
lora = LoraConfig(r=16, lora_alpha=32, target_modules="all-linear")
trainer = SFTTrainer(
model=model,
train_dataset=dataset, # {"prompt": ..., "completion": ...}
peft_config=lora,
args=SFTConfig(num_train_epochs=2, learning_rate=2e-4),
)
trainer.train()
# masking + LoRA + 4-bit, handled

Python — huggingface/peft + trl: QLoRA SFT (reproduced, Apache 2.0)

Notice how the concepts map: BitsAndBytesConfig(load_in_4bit=...) is the quantized base of Section 22.4; LoraConfig is the adapter of the same section, with r and lora_alpha exactly the rank and scale from our LoRALinear; and SFTTrainer applies the prompt-masked cross-entropy of Section 22.3 automatically, training only the adapters. The from-scratch code earlier in the chapter is what these three classes do underneath; running them is the work of an afternoon on a single GPU, and is the fastest path from an open base model to a useful specialized assistant. The LoRA and QLoRA papers introduce the underlying methods, and peft implements many more parameter-efficient variants beyond LoRA.

SFT and LoRA produce a capable instruction-follower. But many qualities we want — being helpful without being sycophantic, refusing harmful requests, preferring the clearer of two correct answers — are easier to judge than to demonstrate. Teaching a model from judgments rather than demonstrations is the domain of reinforcement learning from human feedback, the subject of the next chapter.

Supervised fine-tuning trains on instruction-response pairs, but only the response should contribute to the loss — the model is not learning to generate the prompt. The mechanism is a label mask using the ignore index, so prompt positions are skipped entirely:

input_ids = tokenize(prompt + response)
labels = input_ids.clone()
labels[:len(tokenize(prompt))] = -100 # -100 is ignored by the loss
# in the training step (Section 17.6):
loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten(),
ignore_index=-100) # prompt tokens contribute 0
# only response tokens shape the gradient — the model learns to ANSWER

Python — SFT: mask the prompt, train only on the response

Instruction-tuning data is wildly uneven in length: a one-line question sits beside a multi-paragraph coding task. Padding every example to the longest in the batch wastes most of the GPU on empty positions. Sequence packing recovers it by concatenating several examples into one fixed-length block, separated by the end-of-sequence token, paired with a mask that forbids attention across the boundaries:

def pack(examples, max_len):
blocks, cur, cur_len = [], [], 0
for ex in examples:
if cur_len + len(ex) > max_len and cur:
blocks.append(cur); cur, cur_len = [], 0
cur.append(ex); cur_len += len(ex)
if cur:
blocks.append(cur)
return blocks

Python — sft/pack.py: greedy length packing

The mask is not optional. Without a block-diagonal attention mask, a packed sequence lets the model attend across the EOS that separates two unrelated examples, and it learns the false lesson that one example’s answer continues into the next example’s prompt. With the mask in place, packing routinely doubles throughput on short-instruction datasets at zero cost to quality — the same effective work, with the padding squeezed out.

22.7 Worked Example: A Chat Template, Tokenized

Section titled “22.7 Worked Example: A Chat Template, Tokenized”

Section 22.2 introduced chat templates and Section 22.5 the loss mask; here they meet. A multi-turn conversation is rendered into a single token stream with role markers, and the label mask is set so the loss is computed only on the assistant’s tokens:

msgs = [{"role": "system", "content": "You are concise."},
{"role": "user", "content": "Capital of France?"},
{"role": "assistant", "content": "Paris."}]
ids = tokenizer.apply_chat_template(msgs, tokenize=True)
labels = mask_non_assistant(ids, msgs) # -100 on system/user spans

Python — sft/template.py: conversation to masked labels

The template expands each turn into special tokens that the base model never saw in pretraining — something like a header marking the role, the content, and a turn terminator. The model learns these control tokens during SFT, which is precisely what lets a deployed assistant know where the user’s text ends and its own turn begins. Because the labels carry –100 (PyTorch’s ignore index) everywhere except the assistant span, the gradient flows only from “Paris.” — the model is taught to produce the answer, never to parrot the prompt that elicited it.

Template and mask are a pair The chat template defines the structure the model emits; the loss mask defines which part of that structure it is trained to generate. Get the mask wrong and the model learns to echo prompts; get the template wrong and inference will not match training. They must be derived from the same source of truth.

22.8 LoRA and Parameter-Efficient Fine-Tuning

Section titled “22.8 LoRA and Parameter-Efficient Fine-Tuning”

Full fine-tuning updates every parameter and therefore carries the full optimizer-state cost of Section 17.9 — often impractical for adapting a large model on modest hardware. Low-Rank Adaptation (LoRA) sidesteps this by freezing the pretrained weights and learning a small pair of low-rank matrices alongside them, training well under 1% of the parameters:

class LoRALinear(nn.Module):
def __init__(self, base, r=16, alpha=32):
self.base = base # frozen pretrained weight
self.A = nn.Parameter(torch.randn(r, base.in_features))
self.B = nn.Parameter(torch.zeros(base.out_features, r))
self.scale = alpha / r
def forward(self, x):
return self.base(x) + (x @ self.A.T @ self.B.T) * self.scale

Python — peft/lora.py: a low-rank adapter on a frozen layer

Two design choices make this work. The update is the product B A of two thin matrices of rank r << d, so it adds only r × (in + out) trainable parameters per layer instead of in × out; and B is initialized to zero so the adapter contributes nothing at the start and training begins exactly at the pretrained model. Because only A and B require gradients and optimizer state, the memory cost collapses — which is what makes fine-tuning a multi-billion-parameter model feasible on a single GPU. QLoRA pushes this further by quantizing the frozen base to 4 bits (Chapter 26), so the bulk of the model occupies a quarter of the memory while the small adapters train in full precision.

Freeze the giant, train a sliver LoRA leaves the pretrained weights untouched and learns a tiny low-rank update beside them. Under 1% of the parameters train, the optimizer-state cost nearly vanishes, and a model that needed a cluster to fine-tune now fits on one card.

A counterintuitive lesson of the post-training era is that for supervised fine-tuning, quality and diversity beat quantity, often by a wide margin. A small set of carefully curated, varied instruction-response pairs can produce a stronger instruction-follower than a far larger but noisier one — the influential observation behind the “less is more” line of work, where on the order of a thousand excellent examples sufficed to turn a capable base model into a polished assistant.

The reason connects back to what SFT actually does. Pretraining (Chapter 17) already taught the model language, reasoning, and world knowledge; SFT does not teach these so much as teach the model to surface them in the helpful, instruction-following format the chat template defines (Section 22.7). That is a matter of demonstrating the desired style and breadth of behavior, for which a few hundred clean, diverse examples spanning many task types convey more than thousands of repetitive or low-quality ones — which merely teach the model to imitate noise. The practical consequence is that the data-curation discipline of Chapter 6, quality filtering and deduplication included, matters at the SFT stage at least as much as at pretraining, and that effort spent curating instructions repays itself more than effort spent merely collecting them.

SFT reveals behavior; it does not install knowledge The base model already knows; fine-tuning teaches it to respond in the right format and range. A small, diverse, high-quality instruction set conveys that better than a large noisy one — curation beats collection.

A conversation is not raw text — it has structure: who is speaking, where each turn starts and ends. Turning that structure into a token sequence the model can learn from requires special tokens that mark roles and boundaries, arranged by a fixed chat template. Every turn is wrapped in tokens identifying its speaker, and the assistant’s turn is cued so the model knows when to begin:

text = ""
for msg in conversation:
text += f"<|{msg['role']}>|\n{msg['content']}\n<|end|>\n"
text += "<|assistant|>\n"
# cue the model to respond

Python — sft/template.py: formatting a conversation (illustrative)

The single most important rule about the chat template is that it must be identical between training and inference. The model learns, during SFT (Section 22.7), to respond in the exact format it was shown — these specific role markers, this exact arrangement — and at inference it must be prompted in that same format or it sees an unfamiliar structure and behaves erratically. A mismatch here is one of the most common and most frustrating bugs in deploying a fine-tuned model: nothing crashes, the format merely differs subtly, and the model’s quality silently degrades (a textbook silent failure, Section 21.9). The special tokens themselves are added to the vocabulary (Chapter 5) so the model can represent them as single, unambiguous units rather than inferring boundaries from ordinary text. Getting the template exactly right, and keeping it consistent across the entire pipeline, is unglamorous but essential plumbing.

Train and serve with the same template Special tokens mark roles and turn boundaries; the chat template arranges them. The format must match exactly between SFT and inference, or the model silently degrades — a common, quiet, and entirely avoidable bug.

Fine-tuning data is wildly variable in length — a one-line instruction here, a multi-paragraph dialogue there — and the naive way to batch it, padding every example to the length of the longest, wastes an enormous amount of compute processing meaningless padding tokens. Sequence packing eliminates that waste by concatenating multiple short examples into a single full-length sequence, so that nearly every token the model processes is real.

The subtlety is keeping the packed examples independent. If three short conversations are concatenated into one sequence, the model must not let the second attend back to the first — they are unrelated, and bleeding across the boundary would corrupt the training signal. The fix is the attention mask (Section 7.4): a packed sequence carries a mask that confines each example’s attention to its own span, so the examples share a sequence for efficiency while remaining causally isolated from one another. The payoff is substantial: on data with many short examples, packing can multiply training throughput several-fold by replacing padding with content, at the cost only of constructing the right mask. It is a humble but ubiquitous optimization in fine-tuning pipelines, and a good illustration of how much efficiency hides in the unglamorous mechanics of how data is fed to the model — the same theme as the data-loader and pre-tokenization concerns of Section 20.8.

Pack examples, mask the boundaries Padding short examples to the longest wastes compute on padding; packing concatenates them into full sequences and uses an attention mask to keep them independent. Real tokens replace padding, multiplying fine-tuning throughput for the cost of a mask.