Models
From base model to your model
Instruction data, chat templates, fine-tuning, preferences and distillation
Pre-training ends with a base model: it continues text and does nothing else. Everything that makes a model answer questions, follow instructions, refuse some requests and stop at the end of its answer is taught afterwards, in post-training. This lesson covers that stage from the data up. It follows a support team that wants this site's model to answer GPU node tickets in its own format, and it uses the steps Qwen3-32B itself went through. The lesson shows how instruction data is laid out, how a chat template turns a conversation into tokens, which tokens carry the loss, what full fine-tuning costs and what it can break, how the result is measured, and how preference tuning and distillation work. The next lesson, A detour beside the weights, does the same fine-tuning with LoRA.
Chapter 1 of 10
A base model only continues text
Pre-training builds capability, post-training shapes its use
A base model has read trillions of tokens and learned one skill: given some text, predict what comes next. Give it an instruction and it treats the instruction as the start of a document. "Explain why a pod stays in Pending" may be followed by an explanation, or by "asked the instructor, and the class went quiet", or by three more questions from the same imagined quiz. From the model's point of view all of these are plausible continuations. It has no notion that someone is waiting for an answer.
Post-training is the broad name for all training after pre-training that shapes how the model behaves. Supervised fine-tuning shows it instructions paired with good responses. Preference tuning shows it which of two responses is better. Reinforcement learning rewards responses that pass a check, such as a maths answer that is correct. Distillation trains a smaller model to match a larger one. Pre-training builds the model's broad capabilities. Post-training decides how it uses them.
The effect is large and the cost is small. The InstructGPT paper reports that labelers preferred the outputs of a 1.3 billion weight model after post-training to those of the 175 billion weight GPT-3, a model more than 100 times larger. The 1.3 billion weight model was trained from the GPT-3 of its own size, so the comparison is with a separate, much larger model.
This site's model went through four stages of post-training, as the Qwen3 report describes for its flagship models Qwen3-235B-A22B and Qwen3-32B. The first two build reasoning: a cold start on long chains of thought, then reinforcement learning on reasoning tasks. The next two add a mode that answers without thinking and then general reinforcement learning across many tasks.
So Qwen3-32B as released is already a post-trained model. Its true base model, the checkpoint straight out of pre-training, is a different set of weights, which the Qwen3 report evaluates under the name Qwen3-32B-Base. The support team in this lesson starts from the released Qwen3-32B and tunes it further. Where the lesson compares the team's model with what it started from, it calls that the starting model. The next lesson uses base model in the narrower sense LoRA gives it: the frozen model an adapter sits beside.
Chapter 2 of 10
Instruction data
Examples of the behaviour you want, written as conversations
Supervised fine-tuning, SFT, is the next-token loop of pre-training run on a different text: conversations in which a user asks and an assistant answers the way you want. The model learns to produce answers of that kind when it sees a question of that kind. The data is the whole specification. If the answers are sloppy, the model learns to be sloppy.
TRL, the Hugging Face library for post-training, accepts two layouts. A conversational example is a list of messages, each with a role, such as system, user or assistant, and its content. A prompt-completion example splits the same thing into a prompt and the completion that should follow. Both end up as one sequence of tokens.
Take the support team. It wants tickets about GPU nodes answered in a fixed shape: a one-line diagnosis, the kubectl command to confirm it, and the fix. It has 5,000 past tickets with answers written by its best engineers. At about 600 tokens per ticket and answer, that is 3 million tokens, about a twelve-millionth of the 36 trillion tokens Qwen3's pre-training read. It holds back 500 tickets for testing and trains on 4,500.
Size matters less than quality and coverage here. InstructGPT's supervised stage used about 13 thousand prompts. What matters is that the examples cover the kinds of tickets that will arrive, that the answers are consistently good, and that no ticket used for testing also appears in training. Fine-tuning is the right tool for how the model should behave: a format, a tone, a narrow task. It is a poor tool for facts that change next week, which belong in the prompt.
Chapter 3 of 10
The chat template
How a list of messages becomes one sequence of tokens
The model reads one sequence of tokens. A conversation has roles, and the roles have to be written into that sequence in a way the model can recognise. The chat template does this. It is a small program, written in the Jinja template language, stored in the model's tokenizer_config.json, and applied by apply_chat_template in Transformers and by vLLM when it serves the model.
Qwen3's template wraps each message in two special tokens. <|im_start|>, number 151644, opens a message and is followed by the role and a line break. <|im_end|>, number 151645, closes it. Rendered, the support example is <|im_start|>system, the system text, <|im_end|>, then <|im_start|>user, the ticket, <|im_end|>, then <|im_start|>assistant and the answer, closed by <|im_end|>. For the last assistant turn Qwen3's template also inserts an empty thinking block, <think>, number 151667, two line breaks, and </think>, number 151668, which marks an answer given without reasoning.
The template does two jobs. At training time it renders the whole conversation, here 74 tokens. At serving time it renders the conversation so far and, with add_generation_prompt, ends with <|im_start|>assistant and a line break, here 42 tokens, so the model's next token is the first token of its answer. When the model writes <|im_end|> the server stops.
The two renderings must match. A model fine-tuned with one template and served with another sees role markers it was never trained on, and it may run past the end of its answer or answer in the wrong voice.
Chapter 4 of 10
Which tokens carry the loss
Train on the answer, mask the question
In pre-training every token is a target. In SFT that would be a mistake. The 74 tokens of the example include the system message and the ticket, and the model is not meant to learn to write tickets. It is meant to learn to answer them. So the loss is computed only on the assistant's tokens, and every other position is excluded.
The mechanism is a second array beside the token numbers, called the labels. It starts as a copy of the tokens, and every position that should not count is set to minus 100. PyTorch's cross-entropy loss has an ignore_index setting that defaults to minus 100, so those positions add nothing to the loss and nothing to the slopes. The model shifts the labels by one inside the loss, as in pre-training, so each position is still judged on the token that follows it.
For the example, the first 42 positions, up to and including the assistant header, are set to minus 100. The remaining 32 are trained: the empty thinking block, the 26 tokens of the answer, <|im_end|> and the final line break. Training on <|im_end|> matters. It is how the model learns to stop.
The mean is taken over the trained positions only. If the answer's tokens average a loss of 0.9 and the 42 prompt tokens were included at, say, 2.0, the mean would be 1.52 and most of the slope would come from text the model should not learn. TRL does the masking for you. Its SFTConfig has assistant_only_loss, which needs a template with {% generation %} markers, and TRL patches the template for known families such as Qwen3. For prompt-completion data, completion_only_loss does the same and is on by default.
Chapter 5 of 10
Full fine-tuning
Every weight moves, and the arithmetic is small while the memory is not
Full fine-tuning is pre-training continued: load the finished weights, run the examples through, compute the masked loss, work backwards and let AdamW move all 32.8 billion weights. The settings differ from pre-training in one important way. The model is already good, and large steps would damage what it knows, so the learning rate is much smaller. TRL's SFTConfig defaults to 2 × 10⁻⁵, well below a pre-training peak. The lesson Every weight moves a little used a peak of 1.5 × 10⁻⁴ for its illustrative run, the figure the LLaMA papers report for their larger models. A run usually passes over the data a few times, each pass called an epoch.
The rest of the training loop from that lesson carries over at a smaller scale. The rate still warms up from near zero over the first steps and then decays, often along a cosine curve, because the first steps on a new task bring large slopes even for a trained model. A batch here is a number of examples, and when the GPUs cannot hold enough examples at once, several micro-batches are run and their slopes added before one optimizer step, which is gradient accumulation. Examples of different lengths in one batch are padded to the same length, and the padding positions get the label -100 like the prompt, so they add nothing to the loss. When several short examples are packed into one sequence to avoid padding, the trainer has to keep each example's attention from reaching into its neighbours, or one ticket learns from the text of another. Check how the trainer in use handles packing before turning it on.
The compute is small. The team's 4,500 training tickets hold about 2.7 million tokens. Three epochs are 8.1 million tokens, and by the rule of 6 FLOPs per weight per token that is 6 × 32.8 billion × 8.1 million, about 1.6 × 10¹⁸ FLOPs. At 400 trillion FLOPs per second on each of 8 GPUs, that is about 500 seconds of arithmetic. Activation checkpointing, which SFTConfig turns on by default, runs each forward pass a second time during the backward pass. That brings the rule of thumb to about 8 FLOPs per weight per token, 2.1 × 10¹⁸ FLOPs and about 11 minutes. Either way it is minutes, at full speed and before any time lost to communication. Pre-training this model took several million times as much.
The memory is the same as for pre-training, because the optimizer still holds state for every weight: 16 bytes each, 524 GB, plus activations. That needs the sharding of the lesson A training run at scale. With ZeRO stage 3 or FSDP's FULL_SHARD over the 8 GPUs of two 4-GPU servers it is 65.5 GB per GPU before activations. The sizes in this lesson are in decimal gigabytes, 10⁹ bytes. An 80 GB H100 holds 80 GiB, 80 × 2³⁰ bytes, which is about 85.9 GB in the same units. That leaves about 20 GB per GPU for activations, the layers FSDP gathers in full while it computes them, and the CUDA context. It fits with activation checkpointing, without much room to spare.
And the result is a complete new model, 65.5 GB at 16 bits. A provider who fine-tunes for 100 customers stores 100 models and must load each one into its own GPUs to serve it. That cost is what the next lesson's method removes.
Chapter 6 of 10
What fine-tuning can break
Forgetting, overfitting, and the alignment tax
Fine-tuning moves weights that were set by trillions of tokens to fit a few million. Two kinds of damage follow if it is done carelessly.
The first is forgetting, often called catastrophic forgetting. The model gets better at tickets and worse at things the tickets never exercise: writing code, answering in other languages, following instructions of other shapes. Each step pushes the weights towards the new data, and nothing pulls them back towards the old. The InstructGPT team measured a version of this, which it called an alignment tax: after reinforcement learning from human feedback, the model got worse on some public benchmarks. Their remedy, a variant named PPO-ptx, mixed pre-training gradients back into the updates, and it greatly reduced the regressions without removing all of them. Mixing some general data into the fine-tuning set is the same idea at smaller scale.
The team's own data carries a risk of this kind. Every training answer is rendered with an empty thinking block, so every step rewards answering without reasoning. Qwen3-32B's thinking mode is exercised by none of the 4,500 examples, and by the same logic as any other forgetting it can wear away. If the tuned model will still be asked to think, mix in examples with full thinking blocks, for instance ones the starting model wrote itself, and test the thinking mode in the regression checks.
The second is overfitting. With 4,500 examples and three epochs, the model sees every ticket three times. The loss on the training tickets keeps falling, and at some point the loss on the 500 held-back tickets stops falling and starts to rise. From there the model is memorising the training answers word for word. The remedy is to watch the held-out loss and keep the checkpoint where it was lowest, use a lower learning rate or fewer epochs, or add data.
The method matters too. Biderman and colleagues compared full fine-tuning with LoRA, the method of the next lesson, on Llama-2-7B for code and mathematics. With common low-rank settings LoRA learned less of the new domain than full fine-tuning, and it kept more of the model's original abilities. Their title says it in six words: LoRA learns less and forgets less.
Chapter 7 of 10
Measuring the result
Held-out tickets, the format, and everything else
A fine-tuned model is a candidate until it is measured, and measuring it means comparing it with the model it started from on things it was not trained on. Three kinds of measurement are needed, because each catches a different failure.
The first is the loss on the 500 held-back tickets, computed the same way as in training, only on answer tokens. It is cheap and it shows whether the model has learned the patterns of the answers. It says nothing about whether the answers are right.
The second is a check of the task itself. For the support team that means generating an answer for each held-back ticket and checking it: does it have a one-line diagnosis, a kubectl command and a fix, in that order, and does the command name the right node? Some checks can be done by a script. Others need an engineer, or a stronger model as a judge with a written rubric, and then the judge's own agreement with engineers has to be measured on a sample.
The third is a regression check: the general tests the model was good at before, such as coding, instruction following and other languages. A tuned model that is better at tickets and worse at everything else may still be the right choice for a ticket queue, and the team should know the cost before it decides.
All three depend on the held-back data staying clean. If tickets in the test set are near copies of training tickets, every score is too high. The de-duplication from the lesson The text before training applies here at a small scale: compare every test ticket with the training set before training starts.
Chapter 8 of 10
Feedback on which answer is better
Reinforcement learning from human feedback
SFT needs someone to write the ideal answer. For many tasks it is far easier to compare two answers and say which is better. Reinforcement learning from human feedback, RLHF, is built on such comparisons. The InstructGPT paper describes the classic pipeline in three steps.
First, supervised fine-tuning on demonstrations, about 13 thousand prompts. Second, a reward model. For each prompt the model writes several answers, and labelers rank them. InstructGPT showed labelers between 4 and 9 answers at once, which gives between 6 and 36 pairwise comparisons per prompt, since K answers make K × (K - 1) ÷ 2 pairs. A separate language model with its output head replaced by a single number is trained to give the preferred answer of each pair a higher score. It need not be the size of the model being tuned. InstructGPT trained one reward model of 6 billion weights, started from a 6 billion weight GPT-3, and used it for the policies of every size, the 175 billion weight one included. This reward model was trained on 33 thousand prompts. Third, reinforcement learning with PPO, an algorithm that adjusts the model to raise the reward of the answers it generates, on 31 thousand prompts. The comparisons came from a team of about 40 contractors.
There is a trap in the third step. A model that chases a learned reward finds answers that score high without being good, because the reward model is only an approximation. InstructGPT adds a penalty for each token, based on how far the new model's probabilities have moved from the SFT model's, measured as a Kullback-Leibler divergence. The model may improve, but only so far from where it started.
The result was the paper's headline: a 1.3 billion weight model trained this way was preferred by labelers to the 175 billion weight GPT-3.
Chapter 9 of 10
DPO: preferences without a reward model
The same comparisons, turned into a loss you can compute directly
RLHF needs a separate reward model and a reinforcement learning loop that generates answers during training, which makes it expensive and fiddly. Direct Preference Optimization, DPO, by Rafailov and colleagues, gets to the same kind of result with a plain loss on the comparison data.
Each example is a prompt with a chosen answer and a rejected answer. Two models are involved: the one being trained, called the policy, and a frozen copy of where it started, called the reference. For each answer, the method takes the log-probability the policy gives it minus the log-probability the reference gives it. That difference says how much more likely training has made the answer. The loss pushes the chosen answer's difference up and the rejected answer's down. Written out, it is minus the log of the sigmoid of beta times the chosen difference minus the rejected difference. Beta, 0.1 by default in TRL, sets how strongly the policy is held near the reference, the role the KL penalty plays in RLHF.
Take one pair. The reference gives the chosen answer a log-probability of minus 12.5 and the rejected one minus 13.2. After some training the policy gives minus 12.0 and minus 14.0. The chosen answer's difference is plus 0.5 and the rejected one's is minus 0.8, so the margin is 1.3. Times beta it is 0.13, the sigmoid of 0.13 is 0.532, and the loss is minus the log of that, 0.630. At the very start the policy equals the reference, the margin is zero, and the loss is ln 2, 0.693. Training lowers it by widening the margin.
Chapter 10 of 10
Distillation: a large model teaches a small one
Soft targets carry more than the one right token
Distillation trains a smaller model, the student, to reproduce a larger one, the teacher. The Qwen3 report uses it for all its smaller models, from Qwen3-30B-A3B down to Qwen3-0.6B, and names this site's model as one of the two teachers. It calls the method strong-to-weak distillation and runs it in two phases.
In the off-policy phase the student is fine-tuned on answers the teachers wrote, in both thinking and non-thinking modes. That is SFT with a teacher as the author of the data. In the on-policy phase the student writes its own answers to sampled prompts, and is then trained so that its logits, its scores for every possible next token, match the teacher's at each position, by minimising the KL divergence between them. The student learns from its own mistakes, judged position by position by the teacher.
The reason it works so well is in the targets. SFT tells the model one right token per position. A teacher's distribution says much more. Go back to the four-token example of the lesson How wrong, and which way, where the student gave Pending 53.2, Running 32.3, Terminating 11.9 and purple 2.6 percent. Suppose the teacher gives 70, 20, 8 and 2. The KL divergence of the student from the teacher is the sum over tokens of the teacher's share times the log of the teacher's share over the student's, here 0.059. It says the student should raise Pending and lower Running, and also that Running is far more plausible than purple, which the one right token never said.
The Qwen3 report compares on-policy distillation with reinforcement learning for its 8B model, starting from the same checkpoint. Distillation scored higher on every benchmark listed and used 1,800 GPU hours against 17,920, about a tenth.
What to keep
Shaping a model that already knows
A base model continues text. Post-training teaches it to answer. Supervised fine-tuning runs the same next-token loop on conversations rendered by the model's chat template, with the loss masked to the assistant's tokens and the end-of-turn token trained so that the model stops. Full fine-tuning needs little compute and the full 16 bytes of memory per weight, and leaves a complete model per customer. It can make the model forget and can overfit a small set, so a tuned model is measured on held-out tickets, on the task itself and on what it could do before. Preferences teach what better means, through a reward model and PPO or directly through DPO. Distillation passes a large model's distributions to a small one, and Qwen3-32B is one of the teachers that did so.