Finetuning
When to change the weights, what it costs in memory, and the cheap way to do it.
Decide
- Facts → RAG. Form → finetune. Information failure (wrong, missing, stale facts) vs. behavior failure (right facts, wrong format, style or relevance).
- Order: eval pipeline → systematic prompting → 1–50 examples → simple retrieval (BM25) → advanced RAG or finetune, by failure type → both. Both failures? Start with RAG.
- Reasons to finetune: rare syntaxes and dialects, consistent format and style, a small cheap model for one task (distillation), bias mitigation.
- Reasons not to: data + ML skill + serving + maintenance costs; can degrade other tasks; new base models may overtake it (BloombergGPT vs GPT-4); prompt caching removed the “shorter prompts” argument.
Memory math
| Format | Bytes / value | 7B weights |
|---|---|---|
| FP32 | 4 | 28 GB |
| FP16 / BF16 | 2 | 14 GB |
| INT8 | 1 | 7 GB |
| INT4 / NF4 | ½ | 3.5 GB |
- Inference ≈ params × bytes × 1.2 (activations + KV cache; more for long context or big batches).
- Training = weights + activations + (trainable params × 3 × 2 bytes) for gradient + two Adam states. Activations can exceed the weights; gradient checkpointing trades time for memory.
- Full finetune of 7B in FP16: 14 + 42 = 56 GB before activations. Consumer GPUs: 12–24 GB.
- BF16 ≠ FP16: same bits, BF16 has more range, less precision. Load a model in its intended format.
Techniques
| Technique | Trainable | Note |
|---|---|---|
| Full finetuning | All | Best quality; most memory and data |
| Partial finetuning | Some layers | Parameter-inefficient (~25% needed to match full) |
| Adapters (Houlsby) | ~3% | Within 0.4% of full; adds inference latency |
| LoRA | ≪ 1% | W frozen; train A (n×r) and B (r×m); merge → no latency; r = 4–64 usually enough |
| QLoRA | ≪ 1% | 4-bit NF4 base + LoRA; 65B on one 48 GB GPU; slower training |
| Soft prompts | Prompt vectors | Trainable tokens, not human-readable; less common |
- Multi-LoRA serving: one base + many small adapters (per customer or per task); switch by loading an adapter.
- Model merging: combine finetuned models (summing, layer stacking, concatenation) for multi-task use or on-device; avoids catastrophic forgetting from sequential finetuning.
Tactics
- Start with LoRA; full finetune later. A few hundred examples → LoRA may match full.
- API (fast, limited) vs. framework (PEFT, Axolotl, unsloth, LLaMA-Factory, LitGPT).
- Learning rate: jumpy loss = too high; slow = too low; typical 1e-7 to 1e-3.
- Batch size: < 8 is unstable; gradient accumulation when memory-bound.
- Epochs: train ↓ and val ↑ = overfitting → fewer epochs. Millions of examples: 1–2; thousands: 4–10.
- Prompt loss weight: default ~10% (learn mostly from responses).