Skip to content

LLM Field Guide 08 — Adapting a Model: Continued Pretraining, Fine-Tuning, Alignment, and Distillation

Continued pretraining teaches a model what to know. Fine-tuning teaches it how to behave. Alignment teaches it which answer is better. Distillation copies all three from a bigger model into a smaller one. Pick the wrong one and you burn GPU-weeks on a problem it can't touch. Here's the decision framework, then a working recipe for each.

In this post:

  • Which method changes what: the decision framework
  • Continued pretraining: tokenizer fertility, replay, LR re-warm
  • Supervised fine-tuning: LoRA and QLoRA with TRL and Unsloth
  • Preference tuning: RLHF, DPO, AI feedback
  • RL with verifiable rewards: GRPO and its 2025 fixes
  • Reward hacking: the failure every method shares
  • Distillation: soft labels, reasoning and on-policy distillation
  • Summary: one table for every method
LLM Field Guide — all 12 posts
  1. How an LLM reads text
  2. Inside the transformer
  3. Training and generation
  4. KV cache and long context
  5. Prompting, context, and RAG
  6. Reasoning models and agents
  7. Choosing a base model
  8. Adapting a model ← you are here
  9. Making it smaller and faster
  10. Serving at scale
  11. Safety and evaluation
  12. Putting it all together

Which method changes what

Every method in this post runs the same training loop from post 03: forward pass, loss, backprop, AdamW. What differs is the data you feed it and which tokens the loss sees. That decides what the model learns.

Continued pretraining (CPT) Supervised fine-tuning (SFT) Preference tuning (DPO, RLHF) RL with verifiable rewards (GRPO) Distillation
Data Raw text: web, books, filings, code (prompt, ideal response) pairs (prompt, chosen, rejected) pairs Prompts + a checker Teacher outputs or teacher logits
Loss on Every token Response tokens only Relative log-prob of winner vs loser Group-relative advantage Divergence from teacher
Typical size 1B–100B+ tokens 1K–1M examples 1K–100K pairs 1K–100K prompts 10K–1M prompts
Changes Language fluency, facts, domain style Format, instruction following, tone Style, helpfulness, safety preferences Correctness, reasoning reliability Everything, compressed into a smaller model
Output A new base model (not a chatbot) An instruct model A better instruct model A reasoning model A smaller model

The rule that saves the most money: SFT, DPO, and RL can only rearrange knowledge the model already has. If the model doesn't know the Thai Civil and Commercial Code, a thousand Q&A pairs teach the answer format, not the law. LIMA matched or beat GPT-4 in 43% of comparisons with just 1,000 SFT examples, because "almost all knowledge in large language models is learned during pretraining"1.

Walk the decision top to bottom and stop at the first "yes":

Model fails your task
 │
 ├─ Fixable with a better prompt or retrieved context? ──► Prompting / RAG (post 05). Stop.
 │
 ├─ Lacks knowledge or reads your language badly?
 │     ├─ A base for your language/domain already exists ──► Switch base (post 07)
 │     └─ Billions of in-domain tokens available ─────────► Continued pretraining
 │
 ├─ Knows enough but answers in the wrong format/tone ───► SFT (LoRA / QLoRA)
 │
 ├─ Follows format but picks worse answers ──────────────► DPO on your SFT model
 │
 ├─ Task has a checkable answer (math, code, SQL, JSON) ─► GRPO with a verifier
 │
 └─ Small model, and a bigger model already does it well ► Distill first, RL later

The full stack runs CPT → SFT → preference tuning → RLVR → distillation, but few models use every stage. A support bot might stop after DPO. DeepSeek-R1-Zero skipped SFT entirely and went straight to RL2. DeepSeek V4's card describes domain experts trained with SFT and RL with GRPO, then merged into one model with on-policy distillation4.

Continued pretraining: adding a language or domain

CPT is next-token prediction on raw text, starting from a trained checkpoint instead of random weights. It's the only method here that adds real knowledge, and it's the most expensive one short of pretraining from scratch.

When CPT is worth the compute

Before you spend GPU-weeks, tick these off:

  • The tokenizer is inefficient for your language. 3× the tokens means 3× the compute, a third of the effective context, and 3× the serving cost.
  • The model lacks knowledge, not behavior, even with good prompts.
  • RAG isn't enough: the knowledge is too diffuse to retrieve (a grammar, a field's way of reasoning).
  • You have billions of clean in-domain tokens. My heuristic, not a published threshold: below ~100M tokens, RAG plus SFT usually wins.
  • No good base exists yet (post 07). For Thai, it's been done more than once.

Step 1: Measure tokenizer fertility

Fertility, how many tokens a sentence costs, is the first number to check. Post 01 explains BPE and the language tax; here's what it costs in practice.

I ran 86 Thai characters, "แมวนั่งอยู่บนเสื่อ" ("The cat sat on the mat") plus a sentence about the Bank of Thailand's policy rate, through seven tokenizers with Tokenizer.from_pretrained(repo).encode(text) from tokenizers 0.23.3. Results (measured by me, November 2026)5:

Tokenizer Vocab size Thai tokens (86 chars) Chars per token English equivalent
Mistral-7B-v0.1 32,000 87 0.99 26
Typhoon-7B (Mistral + Thai vocab) 35,219 27 3.19 26
Qwen3-8B 151,669 38 2.26 26
DeepSeek-V4-Flash 129,280 33 2.61 26
gpt-oss-20b 200,019 35 2.46 26
Gemma 4 31B 262,144 31 2.77 26
Qwen3.5-9B 248,070 19 4.53 26

Here's how "แมวนั่งอยู่บนเสื่อ" actually splits:

Mistral-7B : ▁ | แ | ม | ว | น | ั | ่ | ง | อ | ย | ู | ่ | บ | น | เ | ส | ื | ่ | อ   (19 tokens)
Typhoon-7B : ▁แม | วน | ั่ง | อยู่ | บน | เส | ื่อ                                     (7 tokens)
Qwen3.5-9B : แม | วน | ั่ง | อยู่บน | เส | ื่อ                                        (6 tokens)

Mistral-7B pays 3–4.6× more tokens per Thai sentence than a modern tokenizer, roughly one per character, sometimes one per combining vowel mark. The English column is the control: all seven spend 26 tokens. Tokenizer gaps show up almost entirely in non-English text.

Step 2: Extend the vocabulary or switch base

When fertility is bad, you have two options.

Option A: extend the vocabulary. Train a tokenizer on your language, add its tokens, grow the embedding and output matrices, train the new rows. Typhoon 1 did this in December 2023: a 5,000-token Thai tokenizer merged into Mistral-7B's, then LoRA on the extended embeddings and LM head over a 50/50 Thai–English mix5. The table above shows the payoff: 87 → 27 tokens.

Option B: pick a base whose tokenizer already works. In 2026 this is usually right. ThaiLLM-8B, Thailand's 2025 national base, kept Qwen3's tokenizer unchanged: same 151,669 vocab, same 38 tokens on my test6.

Extending lowers inference cost but raises training cost: new rows start untrained, risk an early loss spike, and every engine config must follow your custom tokenizer. My rule of thumb: extend only below ~1.5 chars/token when you'll serve billions of tokens.

If you extend, initialize each new row at the mean of the sub-token embeddings it replaces (in both the input embedding and the LM head), so the token starts out meaning roughly what its pieces meant. That beats transformers 5.22's default resize_token_embeddings(..., mean_resizing=True), which samples from a normal fitted to the old embeddings7. And note tok.add_tokens() matches whole strings before BPE runs: fine for a few thousand domain terms, but a full language needs vocab and merge rules merged into the tokenizer model itself, as Typhoon did5.

Step 3: Mix in replay, or the model forgets

Train only on new-domain text and the model forgets what it knew (catastrophic forgetting). The fix is replay: mix general data back in.

Project New-domain data Replay / general Notes
Typhoon 1 (2023) Thai web, ~3 TB curated English (RefinedWeb), 50% LoRA on extended embeddings + head5
ThaiLLM-8B (2025) 31.5B Thai FineWeb2 + 8.05B curated 24B English FineWeb2, 38% ~63B tokens total, from Qwen3-8B-Base6
Ibrahim et al. (2024) Weak / strong shift 5% / 25% Tested 0.5–50% replay8

Use at least 5% replay for a weak shift and 25% for a strong one like a new language; Ibrahim et al. found "even small amounts of replay are good at mitigating forgetting"8.

Step 4: Budget and train

Budget with 6·N·D and memory with 16 bytes per parameter, both derived in post 03. At ThaiLLM-8B's scale:

C = 6 × 8.19e9 params × 63e9 tokens = 3.10e21 FLOPs
At 40% MFU on H100 (≈ 3.96e14 FLOP/s) → 7.8e6 GPU-s ≈ 2,170 H100-hours ≈ 34 h on 64 GPUs
Domain CPT, 2B tokens on the same model → 9.8e19 FLOPs ≈ 69 H100-hours ≈ 9 h on one 8×H100 node

The 40% MFU is my assumption. Domain CPT is affordable. Language CPT is a project. Full-parameter CPT of an 8B model needs ~131 GB before activations, so it shards across GPUs with FSDP or ZeRO-3 (post 10).

Three learning-rate rules from Ibrahim et al. carry most of the weight8:

  1. Re-warm. The checkpoint ended at a tiny decayed LR. Warm back up over the first ~1% of steps.
  2. Re-decay with cosine (or warmup-stable-decay) to a low floor.
  3. Don't exceed the original peak. "Decreasing the schedule's maximum learning rate can help reduce forgetting, whereas increasing it can improve adaptation."

For a new language, go full-parameter. For a domain top-up, high-rank LoRA is a fair budget option. Biderman et al. found LoRA CPT "substantially underperforms full finetuning" on new knowledge but "better maintains the base model's performance" outside the domain, because full fine-tuning learns perturbations of "a rank that is 10-100X greater than typical LoRA configurations"9. LoRA CPT of an 8B model fits one 80 GB GPU.

TRL's SFTTrainer handles CPT too. Hand it a plain text dataset and it computes loss on every token; packing glues documents into full sequences so no compute goes to padding10:

# pip install "trl==1.17.1" "transformers==5.22.1" "datasets==5.1.0" "accelerate==1.15.0"
# Launch: accelerate launch --config_file fsdp.yaml cpt.py
from datasets import load_dataset, interleave_datasets
from trl import SFTConfig, SFTTrainer

thai = load_dataset("HuggingFaceFW/fineweb-2", "tha_Thai", split="train", streaming=True)
eng  = load_dataset("HuggingFaceFW/fineweb-edu", "sample-10BT", split="train", streaming=True)
mix  = interleave_datasets(
    [thai.select_columns(["text"]), eng.select_columns(["text"])],
    probabilities=[0.75, 0.25],          # 25% replay: "strong shift" setting
    seed=42, stopping_strategy="all_exhausted",
)

config = SFTConfig(
    output_dir="qwen3-8b-th-cpt",
    max_length=4096,                     # packed sequence length
    packing=True,                        # best-fit-decreasing (TRL default "bfd")
    per_device_train_batch_size=4,
    gradient_accumulation_steps=8,       # 4 x 8 x 4096 = 131K tokens/GPU/step
    learning_rate=3e-5,                  # well under a typical pretraining peak
    lr_scheduler_type="cosine",
    warmup_steps=0.01,                   # float = ratio of total steps (transformers 5.x)
    max_steps=20_000,                    # required for streaming datasets
    bf16=True, gradient_checkpointing=True,
)
trainer = SFTTrainer(model="Qwen/Qwen3-8B-Base", args=config, train_dataset=mix)
trainer.train()

On 8 GPUs that's ≈ 21B tokens. Note that warmup_ratio is gone in transformers 5.x: pass a float to warmup_steps11.

Step 5: Measure gains and forgetting

A CPT run without a forgetting check is half an experiment. ThaiLLM-8B's card publishes both sides against its starting point6:

Benchmark Qwen3-8B-Base ThaiLLM-8B Δ
Belebele-Thai (reading) 0.388 0.845 +45.7 pts
ThaiExam average 0.314 0.483 +16.9 pts
MMLU (English, 5-shot) 0.769 0.757 −1.3 pts
XNLI-Thai 0.753 0.667 −8.6 pts
M6 exam: Math 0.409 0.273 −13.6 pts
Average (card's set) 0.599 0.689 +9.0 pts

Read it like a production change review:

  • Thai knowledge and reading jumped. That's what CPT is for.
  • English barely moved (−1.3 MMLU): the 38% English replay did its job.
  • Math and Thai NLI dropped sharply. The curated mix had only 0.6M tokens of code and no math slice. What isn't in the mix decays.

These are the publisher's own base-model evals: knowledge, not chat quality (post 11).

After CPT you still have a base model

CPT outputs a model that completes text, not one that follows instructions. ThaiLLM-8B's card says it "requires instruction fine-tuning" and lists four instruct models built on it: Typhoon, THaLLE, OpenThaiGPT, and Pathumma6. Typhoon-S post-trained it with SFT and on-policy distillation on "an academic budget—equivalent to two days on a single H100 node"12. That's the pattern to copy: one expensive CPT run feeds many cheap post-training runs.

Supervised fine-tuning: LoRA and QLoRA

SFT teaches a text completer the concept "the user asked, now I answer." It trains on (prompt, ideal response) pairs.

SFT is pretraining with the prompt masked out

SFT loss masking and LoRA low-rank update

The loss is the same cross-entropy as pretraining, computed only on response tokens:

Input:      [ prompt tokens ........ ] [ response tokens ... ]
Loss mask:  [   0    0    0    0     ] [   1     1     1     ]

Prompt:   "What comes after: the cat sat on the ___?"   Response: "mat"
Before:   P("mat") = 0.05  →  loss = −ln(0.05) = 3.00
After:    P("mat") = 0.90  →  loss = −ln(0.90) = 0.105

The prompt is given, so there's nothing to learn from predicting it.

Full fine-tuning doesn't fit; LoRA does

Full fine-tuning pays the 16 bytes per parameter from post 03: 8.19B × 16 B = 131 GB for Qwen3-8B, two 80 GB GPUs minimum with sharding.

LoRA freezes the weight matrix W and learns a small low-rank update instead13:

W_effective = W_original + (α / r) · B × A
B ∈ ℝ^(d_out × r),  A ∈ ℝ^(r × d_in),  r ≪ d   (r typically 8–64)

B starts at zero, so at step 0 the adapter is an exact no-op; PEFT's default init does exactly this14. Applied to every linear layer of Qwen3-8B (hidden 4096, 8 KV heads × 128, FFN 12,288, 36 blocks)15:

Module Shape (in → out) LoRA params at r = 16
q_proj / o_proj 4096 → 4096 131,072 each
k_proj / v_proj 4096 → 1024 81,920 each
gate_proj / up_proj 4096 → 12,288 262,144 each
down_proj 12,288 → 4096 262,144
Per block 1,212,416
× 36 blocks 43.6M (0.53% of 8.19B)

You train 43.6M parameters instead of 8.19B, and optimizer state shrinks by the same factor. At inference you can merge, W + (α/r)·B·A, for zero extra latency, or keep adapters separate and hot-swap them per request.

Thinking Machines' "LoRA Without Regret" (September 2025) reset the defaults with controlled comparisons16:

  • Apply LoRA to all layers, especially the MLP. Attention-only at rank 256 lost to MLP-only at rank 128.
  • Use ~10× the full fine-tuning LR (fitted multiplier 9.8 across 14 models): 2e-4 instead of TRL's 2e-5.
  • LoRA matches full FT on small-to-medium SFT datasets, and falls behind once the data exceeds adapter capacity.
  • LoRA dislikes large batches, and raising the rank doesn't fix it.

QLoRA: store the frozen base in 4 bits

LoRA shrinks the trainable memory, but the frozen BF16 base is still 16.4 GB. QLoRA quantizes the frozen weights to 4 bits and backpropagates through them into BF16 adapters. It stores weights as NF4, a 4-bit type "information theoretically optimal for normally distributed weights," quantizes the per-block scales too (double quantization, ~0.127 bits/param), and pages optimizer state to CPU RAM during spikes. That was enough to "finetune a 65B parameter model on a single 48GB GPU"17. My estimate for Qwen3-8B (illustrative arithmetic):

Full FT LoRA r=16 (BF16 base) QLoRA r=16 (NF4 base)
Frozen base — 16.4 GB ~3.6 GB linear (NF4) + 2.5 GB embed/head (BF16) ≈ 6.1 GB
Trainable + grads + Adam 131 GB 43.6M × 16 B ≈ 0.7 GB ≈ 0.7 GB
Realistic GPU 2× 80 GB + sharding 1× 40–48 GB 1× 16–24 GB

QLoRA trades speed for memory: every forward pass dequantizes on the fly, so if the BF16 base fits, use plain LoRA.

Data and chat templates

Your data matters more than any hyperparameter in this post. A few hundred to a few thousand clean, consistent examples beat 100K noisy ones; LIMA used 1,0001. Best sources first: your own logs answered by experts, then filtered synthetic data from a stronger model (check its license), then open sets like trl-lib/Capybara (15,806 conversations)18. Use the conversational messages format:

{"messages": [
  {"role": "system", "content": "You are a support agent for Acme Bank. Answer in Thai."},
  {"role": "user", "content": "โอนเงินต่างประเทศใช้เวลากี่วัน"},
  {"role": "assistant", "content": "โดยทั่วไปใช้เวลา 1–3 วันทำการ ขึ้นอยู่กับธนาคารปลายทางค่ะ"}
]}

Train and serve with the same chat template (post 01 covers templates), or the model learns one format and gets prompted in another.

assistant_only_loss=True applies the 0/1 mask per conversation. It needs {% generation %} markers, which most stock templates lack, so TRL 1.17 swaps in patched training templates automatically for Qwen3/3.5/3.6/3.8, Gemma 3, gpt-oss, Llama 3, DeepSeek V3, and more19. Gemma 4 isn't on the 1.17.1 list: pass your own template via chat_template_path, or use Unsloth's train_on_responses_only. TRL also warns if the end-of-turn token is outside the mask; a model never trained on its stop token never learns to stop.

Recipe: QLoRA with TRL + PEFT

The reference path, Hugging Face libraries only, versions current as of November 202620:

# pip install "trl==1.17.1" "peft==0.21.2" "transformers==5.22.1" \
#             "bitsandbytes==0.50.2" "datasets==5.1.0" "accelerate==1.15.0"
import torch
from datasets import load_dataset
from peft import LoraConfig
from transformers import BitsAndBytesConfig
from trl import SFTConfig, SFTTrainer

dataset = load_dataset("trl-lib/Capybara")            # 'messages' column, train/test splits

bnb = BitsAndBytesConfig(                             # QLoRA: NF4 + double quant, BF16 compute
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_use_double_quant=True,
    bnb_4bit_compute_dtype=torch.bfloat16,
)
peft_config = LoraConfig(
    r=16, lora_alpha=16, lora_dropout=0.0,            # alpha/r = 1.0
    target_modules="all-linear",                      # q,k,v,o,gate,up,down
    task_type="CAUSAL_LM",
)
args = SFTConfig(
    output_dir="qwen3-8b-qlora",
    assistant_only_loss=True,                         # loss on assistant turns only
    max_length=4096,                                  # default 1024 silently truncates
    per_device_train_batch_size=2,
    gradient_accumulation_steps=8,                    # effective batch 16
    learning_rate=2e-4,                               # ~10x full-FT LR
    lr_scheduler_type="cosine",
    warmup_steps=0.03,
    num_train_epochs=1,
    logging_steps=10,
    eval_strategy="steps", eval_steps=200, save_steps=200,
)
trainer = SFTTrainer(
    model="Qwen/Qwen3-8B",
    args=args,
    train_dataset=dataset["train"],
    eval_dataset=dataset["test"],
    quantization_config=bnb,                          # TRL loads the model in 4-bit for you
    peft_config=peft_config,
)
trainer.model.print_trainable_parameters()           # expect ~43.6M trainable
trainer.train()
trainer.save_model()                                  # adapter only (~tens of MB)

API changes to know: SFTTrainer takes quantization_config directly21, max_seq_length is now max_length, and processing_class replaced tokenizer=.

To merge for serving, load the base in BF16, never 4-bit, then PeftModel.from_pretrained(base, "qwen3-8b-qlora").merge_and_unload().

The same job with Unsloth

Unsloth wraps the same TRL trainer with custom Triton kernels; its README claims "2× faster with 70% less VRAM" (vendor numbers; measure on your GPU)22. In 2026.11.2 you load with FastLanguageModel.from_pretrained(..., load_in_4bit=True), add adapters with get_peft_model, mask with train_on_responses_only (add mask_out_tokens=["</think>"] for reasoning models), and export with save_pretrained_merged(..., save_method="merged_16bit") or save_pretrained_gguf(..., quantization_method="q4_k_m")23. Import unsloth before trl/transformers.

Pick TRL + PEFT for production pipelines, multi-node FSDP, and exotic architectures. Pick Unsloth for a single GPU, fast iteration, and one-call GGUF export.

Failure signs and serving

The recipe's values are the starting points: all-linear, r = α = 16, LR 2e-4, effective batch 16–32, 1–3 epochs, max_length at your p95 sample length. Change one at a time. When things go wrong:

  • Train loss falls, eval loss rises: overfitting. Fewer epochs, more data, or lower LR.
  • Never stops generating: end-of-turn token isn't in the loss mask.
  • Echoes the system prompt or user turn: the mask is off; you're training on prompts.
  • General skills collapsed: LR too high or data too narrow. Mix in 10–20% general chat data (my rule of thumb).
  • Great on eval, bad in production: train/eval leak, or serving template ≠ training template.

To serve many fine-tunes on one GPU, load adapters per request instead of merging. vLLM supports it natively24:

vllm serve Qwen/Qwen3-8B --enable-lora \
  --lora-modules acme-support=./qwen3-8b-qlora --max-lora-rank 16
# then call it with "model": "acme-support"

Keep runtime adapter loading to trusted environments, per vLLM's docs24; post 10 covers serving at scale.

Preference tuning: RLHF, DPO, and AI feedback

SFT is imitation: it knows "this exact text," not "better" or "worse." Writing the perfect demonstration for every prompt is expensive; ranking two answers is cheap.

In InstructGPT, raters preferred a 1.3B model trained with SFT + RLHF over the 175B GPT-325.

The three families differ in how they turn a judgement into a gradient:

RLHF with PPO DPO (and variants) RLVR with GRPO
Signal Learned reward model on human rankings (prompt, chosen, rejected) pairs Programmatic check: right/wrong
Models in memory 4: policy, reference, reward, value 2 (1 for reference-free variants) 1–2
2026 status Mostly replaced Default for preferences Default for reasoning

The 2023–2026 story is PPO → DPO for preferences and PPO → GRPO for reasoning. TRL 1.17.1 doesn't even ship a PPOTrainer26.

RLHF: train a judge, then please it

Stage 1 trains a reward model, usually the SFT model with its output layer swapped for a scalar head, on human rankings with the Bradley-Terry loss:

L_RM = −log σ( r(x, y_chosen) − r(x, y_rejected) )
"Explain entanglement to a 10-year-old":  "two magic coins..." r = 2.1 (chosen)
                                          "correlated quantum states..." r = 0.4 (rejected)
gap = 1.7  →  σ(1.7) = 0.846  →  L = 0.168

It learns to rank, not to grade. Stage 2 optimizes the policy (the LLM being trained) with PPO: generate, score, subtract a KL penalty R = r − β·KL(policy ‖ reference), and nudge toward tokens that beat a value model's estimate, with clipped updates.

The KL penalty is the most important guardrail in RL post-training. It measures drift from the frozen SFT model; without it, the policy finds outputs the reward model loves and humans hate. It returns in DPO and GRPO.

PPO fell out of favor because an 8B policy needs four 8B-class networks resident (policy, value model, reference, reward model) plus generation in the loop. GRPO removed the critic precisely to cut that memory27. The build post implements reward modelling and PPO if you want the machinery.

DPO: preference tuning without the RL loop

DPO loss: increase the chosen response's probability relative to the reference model more than the rejected one's

DPO showed the RLHF objective can be solved "with only a simple classification loss": no reward model, no sampling28. The log-probability ratio between your policy and the reference is an implicit reward.

L_DPO = −log σ( β × (ratio_winner − ratio_loser) )
ratio = log π_θ(y|x) − log π_ref(y|x)        β = 0.1 (TRL default)

The model wins by raising the winner's probability relative to the reference more than the loser's. Because it's relative, inflating every probability doesn't help. Worked example:

Prompt: "Summarize the article in one sentence."
Winner: "The paper shows X reduces latency by 40% on Y benchmarks."
Loser:  "The paper talks about some interesting findings related to performance."

log π_θ(winner) = −1.2   log π_ref(winner) = −1.8   →  ratio_winner = +0.6
log π_θ(loser)  = −1.5   log π_ref(loser)  = −1.4   →  ratio_loser  = −0.1
margin = 0.7  →  L = −log σ(0.1 × 0.7) = −log(0.517) = 0.66

0.66 is close to log 2 ≈ 0.69, the loss when the model can't tell the pair apart, so this pair has plenty left to teach. In TRL3029:

# pip install "trl==1.17.1" datasets
from datasets import load_dataset
from trl import DPOConfig, DPOTrainer

dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")  # prompt/chosen/rejected
args = DPOConfig(output_dir="qwen3-0.6b-dpo", beta=0.1, learning_rate=1e-6, max_length=1024)
trainer = DPOTrainer(model="Qwen/Qwen3-0.6B", args=args, train_dataset=dataset)
trainer.train()

Start from your SFT checkpoint, not the base. DPO assumes the reference already speaks the right format. The variants you'll meet:

Method What changes Reach for it when
DPO28 Pairwise loss vs frozen reference Default
IPO Bounded loss; margin can't grow forever DPO overfits a small, clean dataset
KTO31 Only "good"/"bad" labels, no pairs You have thumbs-up/down logs
ORPO32 Merges SFT + preference, no reference One-stage training, tight memory
SimPO33 Reference-free, length-normalized Drop the reference and curb verbosity

DPO never explores

DPO only learns from the pairs you hand it. If the rejected answers are all obviously bad, it learns little. If both answers came from another model, you're teaching it to rank someone else's style. Build pairs from your own SFT model's outputs, and refresh them each round.

RLAIF: let a model write the preferences

Anthropic's Constitutional AI replaced most human rankings with RL from AI Feedback: a model critiques and revises against written principles, then judges pairs. "The only human oversight is provided through a list of rules or principles"34. Most 2026 preference datasets mix human and AI labels. To build your own:

  • Sample 2–4 responses per prompt from your SFT model
  • Have a stronger judge pick the best against a rubric you wrote
  • Spot-check 100–200 judgements by hand before trusting the judge
  • Drop pairs where the verdict flips when you swap A/B order (judge biases are covered in post 11)

RL with verifiable rewards: GRPO

RLVR: sample several answers, score each with a verifier, upweight the ones that beat the group average

For math, code, and structured output you don't need anyone's opinion: check the answer. Does the number match, do the tests pass, does the JSON validate? Tülu 3 named this RL with Verifiable Rewards (RLVR)35.

A verifiable reward can't be flattered. A learned reward model can be fooled by confident tone or length; a unit test can't. DeepSeek dropped neural reward models for R1-Zero after finding them prone to reward hacking at scale, using rule-based accuracy and format rewards instead3.

GRPO: PPO without the critic

GRPO (DeepSeekMath, 2024) replaces PPO's value model by comparing each response to its siblings: sample G responses to one prompt and use the group's statistics as the baseline27.

A_i = ( r_i − mean(r_1..r_G) ) / std(r_1..r_G)
L   = −mean_i [ min( ρ_i·A_i, clip(ρ_i, 1−ε, 1+ε)·A_i ) ] + β·KL(π_θ ‖ π_ref)
      ρ_i = π_θ(o_i|x) / π_old(o_i|x)   (PPO ratio, per token)

No value model, and no reward model when the reward is a rule:

Prompt: "A shop sells 3 pens for $4. How much do 12 pens cost?"
G = 8:  5 say "$16" (r = 1), 3 say something else (r = 0)
mean = 0.625   std = sqrt(0.625 × 0.375) = 0.484

Correct: A = (1 − 0.625) / 0.484 = +0.77   ← pushed up
Wrong:   A = (0 − 0.625) / 0.484 = −1.29   ← pushed down

Two consequences fall out of the arithmetic:

  • The model is only rewarded for beating its own average. At 8/8 or 0/8 correct, every advantage is 0 and nothing is learned.
  • The signal lives on medium-difficulty prompts. Curate for prompts the current model solves sometimes.

The whole response, reasoning included, gets the same advantage, so reasoning that leads to correct answers gets reinforced. That's how RLVR grew reasoning in DeepSeek-R1-Zero with no SFT: AIME 2024 pass@1 went from 15.6% to 71.0%, and 86.7% with majority voting3. Post 06 covers reasoning models from the user side.

GRPO's 2025 fixes are now the defaults

Problem in vanilla GRPO Fix
Length normalization favors long wrong answers Dr. GRPO: unbiased normalization; 43.3% AIME 2024 from a 7B base36
Entropy collapse, wasted all-same groups, truncation noise DAPO: Clip-Higher, Dynamic Sampling, token-level loss, overlong shaping; 50 on AIME 2024 in half R1-Zero-Qwen-32B's steps37
Noisy per-token ratios destabilize MoE training GSPO: sequence-level importance ratio; credited for Qwen3's RL gains38

All three live in TRL 1.17.1's GRPOConfig: loss_type defaults to "dapo" ("grpo" is flagged as length-biased), epsilon_high gives Clip-Higher (DAPO recommends 0.28), and importance_sampling_level="sequence" gives GSPO. beta now defaults to 0.0, so the reference model isn't even loaded39. With a verifier, the checker keeps the policy honest.

GRPO with a custom verifier

GSM8K grade-school math with two rewards: correctness, plus a small one for the expected format.

# pip install "trl[vllm]==1.17.1" datasets
import re
from datasets import load_dataset
from trl import GRPOConfig, GRPOTrainer

dataset = load_dataset("openai/gsm8k", "main", split="train").map(lambda r: {
    "prompt": [{"role": "user", "content": r["question"] + "\nGive the final number after '####'."}],
    "solution": r["answer"].split("####")[-1].strip().replace(",", "")})

def correctness(completions, solution, **kwargs):   # extra dataset columns arrive as kwargs
    out = []
    for completion, gold in zip(completions, solution):
        m = re.search(r"####\s*(-?[\d.,]+)", completion[0]["content"])
        out.append(1.0 if m and m.group(1).replace(",", "").rstrip(".") == gold else 0.0)
    return out

def has_format(completions, **kwargs):
    return [0.1 if "####" in c[0]["content"] else 0.0 for c in completions]

args = GRPOConfig(
    output_dir="qwen3-0.6b-grpo-gsm8k",
    num_generations=8,                # G (TRL default)
    max_completion_length=512,
    per_device_train_batch_size=8,    # effective batch must divide by G
    learning_rate=1e-6,
    use_vllm=True,                    # vLLM generates the samples
)
trainer = GRPOTrainer(model="Qwen/Qwen3-0.6B", reward_funcs=[correctness, has_format],
                      args=args, train_dataset=dataset)
trainer.train()

Reward functions get completions plus extra dataset columns as kwargs and return one float each40. Watch three curves: mean reward (should climb), mean completion length (should grow slowly, not explode), and the fraction of clipped completions (rising means answers hit max_completion_length).

Generation is the bottleneck

Most GRPO wall-clock goes to sampling G completions, not the backward pass. use_vllm=True hands generation to vLLM; on multi-GPU, vllm_mode="server" puts it on dedicated GPUs40.

Reward hacking: the failure every method shares

Every method above optimizes a proxy, and pushed hard enough, the model finds the gap between proxy and goal.

Reward How the model games it Defense
Learned reward model Longer, more confident, more flattering answers KL penalty, length-controlled eval, refresh the RM
"Correct final number" Right number, nonsense reasoning; formats the regex accepts Stricter parsers, audit reasoning on a sample
"Unit tests pass" Special-casing test inputs, editing the tests Hidden tests, sandboxed file system
Format reward Perfect tags around empty content Keep format rewards small vs correctness

The defenses are boring and effective: read samples every few hundred steps, hold out an eval set the reward never touched (post 11), and treat a sudden reward jump as a bug until proven otherwise.

Distillation: teaching a small model what a big one knows

Distillation trains a small "student" to copy a large "teacher," and it's how most good small models in 2026 are made.

Soft labels carry more than right answers

Pretraining treats every token except the target as equally wrong. A trained teacher knows more: "down" is reasonable, "banana" is absurd. Hinton, Vinyals, and Dean called that ranking of wrong answers the knowledge worth transferring43.

Teacher logits:   on: 4.0   down: 2.5   still: 1.5   quietly: 1.0   banana: −2.0
Hard label:       on = 1.0, everything else = 0.0
Soft, T = 1:      on 0.737  down 0.164  still 0.060  quietly 0.037  banana 0.002
Soft, T = 2:      on 0.492  down 0.232  still 0.141  quietly 0.110  banana 0.025

T is the sampling temperature from post 03; raising it exposes the teacher's opinion of the "wrong" answers. Every token now carries a full ranking instead of one bit of right-or-wrong, which is why distillation is so sample-efficient.

Hinton's loss mixes hard-label cross-entropy with a KL term on softened distributions:

L_KD = α · CE(y_hard, p_student) + (1 − α) · T² · KL( p_teacher^T ‖ p_student^T )

T² rebalances the soft term, whose gradients shrink by ~1/T²43. Say the student outputs on 0.624, down 0.084, still 0.229, ...: right top answer, but "still" above "down." Hard-label CE (0.472) only says "raise 'on'." The KL term (0.136 at T = 1) also says "lower 'still', raise 'down'," which a hard label can't carry.

KL direction matters for generative students. Forward KL(teacher ‖ student) is mode-covering: a small student spreads probability over junk it can't model and rambles. Reverse KL(student ‖ teacher) is mode-seeking: it commits to the teacher's main answers. MiniLLM argued for reverse KL to "prevent the student model from overestimating the low-probability regions of the teacher distribution"44, and TRL's DistillationTrainer defaults to it (beta=1.0; 0.0 is forward KL)45.

Three ways to distill an LLM

Sequence-level (black-box) Logit-level (white-box) On-policy
Student learns from Teacher's generated text Teacher's full distribution Teacher's distribution on the student's own text
Teacher access Text only (an API works) Logits; same tokenizer Logits on arbitrary text; same tokenizer
Example DeepSeek-R1-Distill Gemma 2 2B/9B, Llama 3.2 1B/3B Qwen3 small models, DeepSeek-V4 consolidation

Reasoning distillation: SFT on a reasoning teacher's traces

DeepSeek built the R1-Distill models with nothing but SFT. They generated ~800K samples with R1 (~600K reasoning, ~200K non-reasoning) and fine-tuned Qwen2.5 and Llama 3 bases from 1.5B to 70B, with no RL3:

Model AIME 2024 pass@1 MATH-500 pass@1
GPT-4o-0513 9.3 74.6
o1-mini 63.6 90.0
R1-Distill-Qwen-1.5B 28.9 83.9
R1-Distill-Qwen-7B 55.5 92.8
R1-Distill-Qwen-32B 72.6 94.3
R1-Distill-Llama-70B 70.0 94.5

Source: DeepSeek-R1-Distill model card41. A 1.5B student triples GPT-4o's AIME score.

The sharper finding: running large-scale RL directly on Qwen-32B-Base reached 47.0% on AIME 2024; distilling R1 into the same base reached 72.6%. DeepSeek's conclusion: reasoning patterns distilled from a larger model beat the ones a small model discovers through its own RL3.

The recipe is generate-then-SFT, and it works with any teacher, even one behind an API. Run the teacher in vLLM (LLM(...).chat(messages, SamplingParams(temperature=0.6, top_p=0.95, max_tokens=4096))), write each prompt and answer as a messages row to JSONL, and feed it to the SFT recipe above. Two upgrades worth the effort:

  • Filter by correctness (rejection sampling): keep only teacher answers that match the gold answer.
  • Sample several answers per prompt at temperature 0.6–1.0 and keep the correct ones. Diverse reasoning paths make a sturdier student.

Logit-level: match the whole distribution

If you own the teacher, train the student on its full next-token distribution. It's the standard recipe for a family's small siblings: Gemma 2's 2B and 9B were trained "with knowledge distillation instead of next token prediction"46, Llama 3.2 1B/3B used logits from Llama 3.1 8B and 70B "as token-level targets" after pruning47, and Llama 4 Maverick was "codistilled" from Behemoth48.

Logit distillation needs a shared vocabulary

The KD loss compares probability vectors position by position. With different tokenizers, token 9059 means different things to each model and the comparison is meaningless. Across families, fall back to sequence-level.

A 150K-token distribution per position is huge, so store only the top-k probabilities or run the teacher live.

On-policy distillation: the student practices, the teacher grades

Off-policy, the student only ever sees the teacher's text, so at inference its own first mistake lands it somewhere it never trained, and errors compound.

On-policy distillation trains on the student's own generations: the student writes, the teacher scores every token, and the loss pulls the student toward the teacher's choice at each position. Google DeepMind formalized this as GKD49.

Think of it as GRPO with a much denser reward. GRPO gives the whole response one number; on-policy distillation gives every token a score, the per-token reverse KL to the teacher. Thinking Machines estimated it ~9× cheaper than SFT (~30× counting dataset generation)50.

The strongest evidence is from the Qwen3 report, starting Qwen3-8B from the same off-policy-distilled checkpoint42:

Method (Qwen3-8B) AIME'24 AIME'25 GPU hours
Off-policy distillation only 55.0 42.8 —
+ RL 67.6 55.5 17,920
+ On-policy distillation 74.4 65.5 1,800

On-policy distillation beat RL by 7–10 points at ~1/10 the compute, which is why Qwen3's 0.6B–14B and 30B-A3B models were distilled from Qwen3-32B or 235B-A22B instead of getting their own RL runs42.

TRL 1.17.1 ships a stable DistillationTrainer that generates student completions on-policy (optionally with vLLM) and uses a chunked JSD loss51:

# pip install "trl[vllm]==1.17.1" datasets
from datasets import load_dataset
from trl import DistillationConfig, DistillationTrainer

dataset = load_dataset("trl-lib/ultrafeedback-prompt", split="train")  # prompt-only
args = DistillationConfig(output_dir="qwen2.5-0.5b-distilled", beta=1.0,  # reverse KL
                          max_completion_length=512, use_vllm=True)
trainer = DistillationTrainer(
    model="Qwen/Qwen2.5-0.5B-Instruct",          # student
    teacher_model="Qwen/Qwen2.5-1.5B-Instruct",  # teacher: same tokenizer family
    args=args, train_dataset=dataset)
trainer.train()

Since TRL 1.1 it supports an external teacher server, so the teacher doesn't have to fit on the training GPUs, plus a generation buffer worth up to 40× speedup52.

What goes wrong in distillation

  • The teacher can be too smart. "Student network performance degrades when the gap between student and teacher is large"53; in Thinking Machines' run, Qwen3-8B was a slightly better teacher for itself than Qwen3-32B50. Start with a teacher 2–10× the student's size.
  • Teacher compute adds up. Logit-level and on-policy runs execute the teacher on every training token: trivial at 1.5B, dominant at 235B. That's why generate-once sequence-level distillation stays popular.
  • Students sound confident when wrong. They inherit the teacher's style without all its knowledge. Evaluate on held-out tasks, never distillation prompts (post 11).

Check the teacher's license first

Training on a model's outputs is governed by its license or terms of service, and they differ sharply:

Teacher What the terms say
Llama 3.1 Allowed, but a distributed derivative must put "Llama" at the start of its name54
Anthropic commercial API Customers may not use the services "to build a competing product or service, including to train competing AI models"55
Apache 2.0 / MIT (Qwen3, gpt-oss, DeepSeek-V4) Permissive; check each card56574

Other commercial APIs carry similar restrictions. Post 07 covers open-weight licenses.

Distillation stacks with the other cost levers. Distill a 4–8B student, quantize it, and serve it with a speculative draft model (post 09). Pruning plus distillation is the cheapest path to a smaller sibling: NVIDIA's Minitron needed up to 40× fewer training tokens than training from scratch58.

Summary

One table for every way to change a model:

You have / need Method Tool Key knob Watch for
Missing language or domain; billions of tokens CPT SFTTrainer on text, packing Replay 5–25%+, LR re-warm, peak ≤ original Forgetting what's not in the mix
Right knowledge, wrong format or tone SFT (LoRA/QLoRA) TRL + PEFT, or Unsloth all-linear, r=16, LR 2e-4, batch 16–32 Mask errors, template mismatch
Rankings (human or AI judge) DPO DPOTrainer beta 0.1, LR 1e-6 Stale pairs from another model
Thumbs-up/down logs KTO KTOTrainer Good/bad balance Label noise
A checker (tests, exact match, schema) GRPO / RLVR GRPOTrainer + vLLM num_generations, max_completion_length Reward hacking, length blow-up
Only a fuzzy notion of "good" Reward model → GRPO RewardTrainer + GRPOTrainer RM refresh cadence RM exploitation
Teacher via API or different tokenizer Sequence-level distillation vLLM + SFTTrainer Filter for correctness Teacher license
Same-family teacher On-policy distillation DistillationTrainer Teacher 2–10× student Teacher compute

Rules that hold across all of them:

  • Rule out prompting and RAG first; then match method to what's missing (knowledge → CPT, format → SFT, preference → DPO, correctness → GRPO)
  • Measure tokenizer fertility before planning CPT; budget with 6·N·D and 16 B/param (post 03)
  • Same chat template for training and serving; loss on assistant turns, stop token included
  • Start alignment from a good SFT checkpoint, with samples from your model; read raw samples on a schedule
  • Distill before you RL a small model, and read the teacher's license first
  • Evaluate target gains and general skills, on data no training signal touched (post 11)

Next: Post 09 — Making It Smaller and Faster: you've trained a better model; now quantize it, understand MoE memory, and speed up decoding.

Go deeper:


  1. Zhou et al., LIMA: Less Is More for Alignment, 2023. ↩↩

  2. DeepSeek-AI, DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning, published in Nature 645, 633–638 (2025). ↩

  3. DeepSeek-AI, DeepSeek-R1 full text: rule-based rewards; R1-Zero AIME 15.6% → 71.0% (86.7% majority vote); ~800K distillation samples; RL on Qwen-32B-Base 47.0% vs distilled 72.6%. ↩↩↩↩

  4. DeepSeek-AI, DeepSeek-V4-Pro model card: SFT + GRPO domain experts consolidated by on-policy distillation; MIT. ↩↩

  5. Pipatanakul et al., Typhoon: Thai Large Language Models, December 2023: 5,000-token Thai tokenizer merged into Mistral-7B, ~3 TB Thai text, 50/50 Thai/English mix, LoRA on extended embeddings and head. Token counts in this post measured by the author with tokenizers 0.22.1 and 0.23.3 (identical). ↩↩↩↩

  6. ThaiLLM, ThaiLLM-8B model card: CPT from Qwen3-8B-Base on ~63B tokens (24.0B English, 31.5B Thai, 8.05B curated), Apache-2.0, benchmarks vs the base, downstream instruct models. ↩↩↩↩

  7. Hugging Face Transformers 5.22.1, resize_token_embeddings(..., mean_resizing=True), source. ↩

  8. Ibrahim et al., Simple and Scalable Strategies to Continually Pre-train Large Language Models, 2024: LR re-warm/re-decay; replay tested at 0.5–50%, 5% (weak shift) and 25% (strong shift) in the main experiments. ↩↩↩

  9. Biderman et al., LoRA Learns Less and Forgets Less, 2024. ↩

  10. Hugging Face TRL 1.17.1, SFTConfig: learning_rate 2e-5, max_length 1024, packing_strategy="bfd", assistant_only_loss, full-sequence loss for language-modeling datasets. ↩

  11. Hugging Face Transformers 5.22.1, TrainingArguments.warmup_steps: integer steps or a float ratio in [0, 1); no warmup_ratio field. ↩

  12. Typhoon, Typhoon-S-ThaiLLM-8B-Instruct and Typhoon-S paper, January 2026. ↩

  13. Hu et al., LoRA: Low-Rank Adaptation of Large Language Models, 2021. ↩

  14. Hugging Face PEFT 0.21.2, LoraConfig: target_modules="all-linear", default init B = 0 (no-op adapter), use_rslora. ↩

  15. Qwen, Qwen3-8B config.json: hidden 4096, intermediate 12,288, 36 layers, 32/8 heads, head_dim 128, vocab 151,936; 8,190,735,360 parameters per Hub metadata. ↩

  16. Schulman et al. / Thinking Machines Lab, LoRA Without Regret, September 29, 2025. ↩

  17. Dettmers et al., QLoRA: Efficient Finetuning of Quantized LLMs, 2023. ↩

  18. trl-lib/Capybara: 15,806 train / 200 test conversations. ↩

  19. Hugging Face TRL 1.17.1, training chat templates: patched *_training.jinja templates swapped in when assistant_only_loss=True. ↩

  20. PyPI as of 2026-11-05: trl 1.17.1, peft 0.21.2, transformers 5.22.1, bitsandbytes 0.50.2, unsloth 2026.11.2. ↩

  21. Hugging Face TRL 1.17.1, SFTTrainer: accepts quantization_config, peft_config, processing_class. ↩

  22. Unsloth, README: speed/VRAM claims. ↩

  23. Unsloth and unsloth_zoo 2026.11.2 source: FastLanguageModel, get_peft_model, train_on_responses_only, save_pretrained_merged, save_pretrained_gguf. ↩

  24. vLLM, LoRA Adapters: --enable-lora, --lora-modules, --max-lora-rank, runtime-update security warning. ↩↩

  25. Ouyang et al., Training language models to follow instructions with human feedback, 2022. ↩

  26. Hugging Face TRL v1.17.1, trl/__init__.py: exported trainers. ↩

  27. Shao et al., DeepSeekMath, February 2024: introduces GRPO. ↩↩

  28. Rafailov et al., Direct Preference Optimization: Your Language Model is Secretly a Reward Model, 2023. ↩↩

  29. Hugging Face TRL v1.17.1, dpo_config.py: beta 0.1, learning_rate 1e-6, loss_type sigmoid/ipo/others. ↩

  30. Hugging Face, TRL DPO Trainer: quick start on Qwen3-0.6B and UltraFeedback. ↩

  31. Ethayarajh et al., KTO: Model Alignment as Prospect Theoretic Optimization, 2024. ↩

  32. Hong et al., ORPO: Monolithic Preference Optimization without Reference Model, 2024. ↩

  33. Meng et al., SimPO: Simple Preference Optimization with a Reference-Free Reward, 2024. ↩

  34. Bai et al., Constitutional AI: Harmlessness from AI Feedback, 2022. ↩

  35. Lambert et al., Tülu 3, 2024: introduces RLVR. ↩

  36. Liu et al., Understanding R1-Zero-Like Training, 2025. ↩

  37. Yu et al., DAPO, 2025: 50 on AIME 2024 vs 47 for DeepSeek-R1-Zero-Qwen-32B at 50% of the steps. ↩

  38. Zheng et al., Group Sequence Policy Optimization, 2025. ↩

  39. Hugging Face TRL v1.17.1, grpo_config.py: loss_type default "dapo", beta 0.0, num_generations 8, epsilon_high, importance_sampling_level, learning_rate 1e-6. ↩

  40. Hugging Face, TRL GRPO Trainer: reward function contract, vLLM colocate/server modes. ↩↩

  41. DeepSeek-AI, DeepSeek-R1-Distill-Qwen-32B model card. ↩

  42. Qwen Team, Qwen3 Technical Report, 2025: §4.5 strong-to-weak distillation; §4.7 Table 21, distillation vs RL on Qwen3-8B. ↩↩

  43. Hinton, Vinyals, Dean, Distilling the Knowledge in a Neural Network, 2015. ↩↩

  44. Gu et al., MiniLLM, 2023. ↩

  45. Hugging Face TRL v1.17.1, distillation_config.py: beta default 1.0 (reverse KL). ↩

  46. Gemma Team, Gemma 2, 2024. ↩

  47. Meta AI, Llama 3.2, September 2024. ↩

  48. Meta AI, The Llama 4 herd, April 2025. ↩

  49. Agarwal et al., On-Policy Distillation of Language Models, 2023. ↩

  50. Kevin Lu / Thinking Machines Lab, On-Policy Distillation, October 27, 2025. ↩↩

  51. Hugging Face TRL v1.17.1, Distillation Trainer docs. ↩

  52. Hugging Face TRL, v1.1.0 release notes, April 2026. ↩

  53. Mirzadeh et al., Improved Knowledge Distillation via Teacher Assistant, 2019. ↩

  54. Meta, Llama 3.1 Community License, §1.b.i. ↩

  55. Anthropic, Commercial Terms of Service, §D.4. ↩

  56. Qwen, Qwen3-8B model card: Apache 2.0. ↩

  57. OpenAI, gpt-oss-120b model card: Apache 2.0. ↩

  58. Muralidharan et al., Compact Language Models via Pruning and Knowledge Distillation, NVIDIA, 2024. ↩

Discussion

Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.