Skip to content
ML to LLMs
Cheat sheets

Fine-tuning

Post-training stages, SFT data rules, memory math for full fine-tuning, LoRA, and QLoRA, and the DPO and GRPO formulas.

StageDataLossTeaches
Pretrainingtrillions of raw tokensnext-token cross-entropylanguage, knowledge
SFT(prompt, response) pairscross-entropy on response tokens onlyassistant format, task behavior
Preference tuning(prompt, chosen, rejected)DPO, or reward model + PPOpreferred style, helpfulness, refusals
RL with verifiable rewardsprompts + checker (tests, answers)GRPO / PPO on checker rewardmulti-step reasoning, correctness

Bytes per trained parameter (mixed-precision AdamW): weights 2 + grads 2 + fp32 master 4 + Adam mm 4 + Adam vv 4 = 16. Plus activations (≈34⋅s⋅d\approx 34 \cdot s \cdot d bytes per layer; gradient checkpointing keeps about 2⋅s⋅d2 \cdot s \cdot d per layer).

MethodBase weightsTrainedSynthetic 7B-style total
Full fine-tuning2 bytes/param, trainedall NN~108.6 GB
LoRA2 bytes/param, frozenr(din+dout)r(d_{\text{in}} + d_{\text{out}}) per matrix~14.9 GB
QLoRA~0.52 bytes/param (NF4), frozensame adapters~5.3 GB

LoRA: W=W0+αrBAW = W_0 + \frac{\alpha}{r}BA. AA random, B=0B = 0, so training starts at the base model. Target all 7 linear layers for best quality. Merge into a 16-bit base for zero-overhead inference. Rank barely affects memory; the frozen base dominates.

DPO: L=−log⁡σ(β[log⁡πθ(yw)πref(yw)−log⁡πθ(yl)πref(yl)])\mathcal{L} = -\log\sigma\big(\beta[\log\frac{\pi_\theta(y_w)}{\pi_{\text{ref}}(y_w)} - \log\frac{\pi_\theta(y_l)}{\pi_{\text{ref}}(y_l)}]\big). Loss starts at ln⁡2=0.693\ln 2 = 0.693.

GRPO: sample GG answers, advantage A^i=(ri−mean)/std\hat{A}_i = (r_i - \text{mean})/\text{std} within the group. All-pass or all-fail groups give no signal.

Watch out

Mask prompt tokens, include the EOS token, use the serving chat template, dedup and decontaminate, and run general-capability and safety regression evals before shipping.

Use something else when: facts change (RAG, tools), you have no eval set, a better prompt already works, or you need citations.

Lessons: Fine-tuning in practice · Adapting LLMs