Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  The Fine-Tuning Handbook
Handbook~15 min readIntermediate
Deep Dive

Fine-tuning,
and the low-rank shortcut.

Fine-tuning has a reputation for being expensive and mysterious — and often the wrong tool. Here's when it beats RAG and prompting, how LoRA made it cheap enough for a single GPU, and the part everyone underestimates: the data.

01

Three ways to adapt a model

Before reaching for fine-tuning, know your options. There are three ways to make an LLM do what you want, in increasing order of cost and commitment.

Prompt

Instructions + examples

Change behavior via the prompt and few-shot examples. Instant, free, reversible. Try this first, always.

RAG

Give it knowledge

Retrieve relevant docs at query time. Best for facts, private or changing data. The model stays fixed.

Fine-tune

Change the weights

Train on examples so the model itself changes. Best for behavior, style, format, and domain patterns.

→ The rule of thumb

RAG for what the model should know; fine-tuning for how it should behave. Reach for prompting first, RAG for knowledge, and fine-tuning only when you need consistent behavior prompting can't buy.

02

What fine-tuning actually changes

Fine-tuning continues training a pretrained model on your own examples, updating its weights so the behavior is baked in — no prompt or retrieval needed at inference. It's how you get a model to reliably adopt a style or persona, always produce a specific format (strict JSON, a house tone), follow a task pattern consistently, or specialize in a narrow domain's language.

The common mistake is fine-tuning to add knowledge. That works poorly: facts crammed into weights are lossy, hard to update, and easy to hallucinate around — exactly what RAG does better and more cheaply. Fine-tuning teaches how to respond, not what is true. If your problem is "the model doesn't know X," use RAG; if it's "the model doesn't respond the way I need," consider fine-tuning.

03

Full fine-tuning vs PEFT

Full fine-tuning updates all the model's weights. It's powerful but brutally expensive: you need enough GPU memory to hold the model, its gradients, and optimizer state — for a large model, many high-end GPUs — and you end up with a full copy of the model per task. For most teams that's a non-starter.

Parameter-efficient fine-tuning (PEFT) solves this by freezing the base model and training only a tiny number of new parameters. You get most of the quality for a fraction of the memory, compute, and storage — and you can keep the base model shared and swap small task-specific pieces. LoRA is the dominant PEFT method.

Full fine-tuningPEFT (LoRA)
Weights updatedAll of themSmall adapters (<1%)
GPU memoryVery high (model + grads + optimizer)Low — base frozen
Output per taskA full model copyA few MB of adapter weights
Catastrophic forgettingHigher riskLower (base untouched)
Best whenDeep domain shift, resources plentifulAlmost always — the default
04

How LoRA works

The idea that made fine-tuning cheap: don't change the weights — add a small, low-rank correction beside them.

LoRA (Low-Rank Adaptation) freezes the original weight matrices and, next to each, injects two small matrices whose product is a low-rank update. During training, only these little adapter matrices learn; the huge base weights never move. At inference, the adapter's contribution is added to the frozen weight, so the effective weight is W + BA — the original plus a small learned correction.

The insight is that the change a task requires has low intrinsic rank — it can be captured by matrices far smaller than the full weight. So instead of training millions of parameters, you train thousands, using a fraction of the memory. QLoRA pushes this further: load the frozen base model in 4-bit quantized precision to slash its memory footprint, then train LoRA adapters on top — letting you fine-tune a very large model on a single GPU that couldn't otherwise hold it, with little quality loss.

LoRA

  • Freeze base weights
  • Train tiny low-rank adapters
  • Effective weight = W + BA
  • Adapters are a few MB, swappable

QLoRA

  • Base loaded in 4-bit (quantized)
  • + LoRA adapters on top
  • Fine-tune huge models on one GPU
  • Minimal quality loss

Just how small is "low-rank"? Count it.

Take one attention projection — a 4096 × 4096 weight, about 16.8M numbers. LoRA replaces its update with two skinny matrices, B (4096 × r) and A (r × 4096). At rank r = 8 that's:

LoRA params = r·(d + k) = 8·(4096 + 4096) = 65,536   vs   d·k = 4096·4096 = 16,777,216   →   0.39% (256× fewer)

One matrix. The adapter trains 256× fewer numbers than the weight it corrects.

The adapter is applied with a fixed scale α/r, so the effective weight is W + (α/r)·BA. That's why α and r are tuned together — raise r for more capacity, and α/r keeps the update's magnitude sane. But the parameter count isn't even the memory that matters. Optimizers do. Adam keeps two fp32 moments per trainable parameter (8 bytes), so full fine-tuning a 7B model needs ~52 GB just for Adam state — before activations. LoRA trains ~4M params instead of 7B, cutting that to ~32 MB. That — not the disk size of the adapter — is what lets a fine-tune fit on one GPU.

The knobs that matter (LoRA/QLoRA)

HyperparameterTypicalWhat it does / how to move it
rank r8–64Adapter capacity. Higher = more expressive + more params. Start 8–16; raise only if underfitting.
lora_alpha16–32Scale of the update (applied as α/r). Common rule of thumb: α = 2·r. Tune with r, not alone.
learning rate1e-4 – 3e-4Higher than full FT (you train fewer params). Too high → instability/forgetting.
epochs1–3Few. More epochs on a small set = memorization. Watch held-out loss, stop when it turns up.
target modulesq,v (or all-linear)Which matrices get adapters. q_proj+v_proj is the cheap classic; all-linear is stronger, costlier.
lora_dropout0.05–0.1Regularizes the adapter on small datasets to fight overfitting.
base precision4-bit (QLoRA)Quantize the frozen base to shrink its footprint 4× (fp16 → nf4). Adapters stay higher precision.
05

The data is the job

Here's the part teams underestimate: fine-tuning is 90% data work. The method (LoRA and friends) is nearly commoditized; the differentiator is a clean, well-formatted, high-quality dataset of the exact behavior you want. Garbage in, garbage baked into the weights.

Format your data as the model expects (prompt–response pairs, chat turns, an instruction template). Prize quality over quantity — a few hundred to a few thousand excellent, consistent examples usually beat tens of thousands of noisy ones, because fine-tuning imitates whatever you show it, mistakes included. Ensure examples are consistent (contradictory examples teach nothing) and representative of real inputs. Hold out a clean test set from the start.

→ The uncomfortable truth

Most failed fine-tunes fail on data, not method. If the model learned the wrong thing, look at your examples — it faithfully imitated them. Curation, consistency, and quality beat any clever hyperparameter.

06

Catastrophic forgetting & overfitting

Fine-tuning has a dark side. Catastrophic forgetting: training hard on a narrow task can overwrite the model's general abilities — your specialized model gets great at the new thing and worse at everything else. And overfitting: with a small dataset, the model can memorize your examples rather than learn the pattern, producing brittle, parroting behavior.

Mitigations: PEFT methods like LoRA reduce forgetting by leaving the base weights frozen; keep learning rates modest and don't over-train (few epochs); optionally mix in general-purpose data so the model retains breadth; and — crucially — evaluate for regressions, not just improvements. A fine-tune that nails your task but tanks the model's reasoning or safety is a net loss you'll only catch if you measure the general abilities too.

07

Evaluate & decide

Judge a fine-tune on a held-out set the model never trained on — otherwise you're measuring memorization. Compare against the honest baselines: the base model with good prompting, and a RAG setup. Fine-tuning only wins if it clearly beats those on your real metric, and doesn't regress general ability. Measure both the target behavior and a broad capability check.

Then weigh the ongoing costs: fine-tuning adds a training and data pipeline, model/adapter versioning, and re-tuning as needs change. It's worth it when you need consistent behavior/format/style at scale, want to shrink prompts (bake the instructions in) for latency and cost, or must specialize a smaller cheaper model to match a bigger one on your task. It's the wrong tool for knowledge (use RAG), for one-offs (use prompting), or when you can't produce quality data.

Fine-tunefor behavior — consistent style, format, tone, task pattern, domain voice.
Fine-tunefor efficiency — bake in instructions to shrink prompts; specialize a small cheap model.
Don'tfor knowledge — facts belong in RAG, which is cheaper and updatable.
Don'twithout data — no quality dataset, no good fine-tune. Full stop.
RUN IT YOURSELF

Size a LoRA fine-tune yourself

The reason LoRA fits on one GPU isn't the adapter's disk size — it's optimizer memory. Run the numbers for a 7B model: how few parameters you actually train, and how the Adam state collapses from tens of GB to tens of MB. Then see QLoRA quarter the frozen base. Change r, the target modules, or the model size and watch the budget move.

CPython · WebAssembly
The picture

The picture: one LoRA layer, frozen path and trainable path

frozen path (never updated) trainable path, rank r = 8 input x4096 dims W (frozen)4096 × 4096 = 16.8M A: 8 × 4096trains B: 4096 × 8trains × α/r16/8 = 2 addWx + 2·BAx h trainable: 8·(4096 + 4096) = 65,536 = 0.39% of W
The input goes through the frozen weight exactly as before, and also through two skinny matrices that start out adding nothing (B is initialised to zero, so the first step is the base model unchanged). Gradients flow only into A and B. After training you can keep the adapter separate and swap it per task, or fold 2·BA into W once, and the layer costs nothing extra at inference.
Trade-offs

Cost and trade-offs: from prompting to full fine-tuning

For the page’s 7B model. Time is the effort to make or change the adaptation. Space is the memory or storage it needs. GiB figures are computed from the page’s byte counts and exclude activations.

CaseTimeSpaceWhy
PromptingMinutes; edit the text and rerunNo training memory; every request pays for the instructions in tokensCheapest to change. A long prompt is a cost you pay on every call.
RAGBuild an index and a retrieval stepAn index beside the model; the weights are untouchedFacts can be updated by re-indexing, not retraining.
LoRA (r = 8, q + v)A training run plus a data pipelineBase 13.0 GiB in fp16; Adam state 32 MiB; adapter file 8 MiB4.19M trainable params. Many adapters can share one base.
QLoRASame run, slower per step (the base is dequantised on the fly)Base 3.3 GiB in 4-bit; adapters unchangedWhat makes a 7B fine-tune fit a single 24 GB card with room for activations.
Full fine-tuneA multi-GPU training jobWeights 13.0 + gradients 13.0 + Adam 52.2 ≈ 78 GiB, before activationsEvery weight moves, so it adapts deepest and forgets most. One full model copy per task.

Read the table top to bottom as a ladder: each rung costs more to build and to change, so climb only when the rung below has been measured and found short. The jump that matters is from LoRA to full fine-tuning. It is not 2×; the optimizer state alone grows from 32 MiB to 52 GiB, which is the difference between one GPU and a cluster.

Watch for

Common mistakes

  • Training and serving with different chat templates

    The model learns the exact tokens around each turn: role markers, separators, end-of-turn token. Train with one template and serve with another and the tuned behaviour half-appears, or the model never stops generating. Render training examples with the same apply_chat_template call you will use in production.

  • Computing loss on the prompt too

    If the loss covers every token, a large share of training goes into predicting your system prompt and the user’s question, which you never need the model to generate. Mask the prompt tokens so only the response is learned. With long shared prompts this can be most of the tokens.

  • Leaking the test set

    Splitting rows at random after you have generated paraphrases or near-duplicates puts copies of test items in training. The held-out score then measures memory, not skill. De-duplicate first, and split by source document or customer, not by row.

  • Changing r without changing α

    The update is scaled by α/r. Double r from 8 to 16 with α fixed at 16 and the scale halves from 2 to 1, so the adapter’s effect shrinks just as you gave it more capacity. Move them together (the page’s α = 2·r) or you are tuning two things at once.

  • Loading an adapter on the wrong base

    An adapter is a correction to one exact set of weights. Applied to a newer release, a different fine-tune or a differently quantised copy of “the same” model, it loads without error and quietly produces worse output. Record the base model’s exact name and revision with every adapter.

In the wild

Where this shows up in production and interviews

  • Many adapters, one base

    Serving engines such as vLLM can load several LoRA adapters over one copy of the base model and pick one per request. A product can give every customer or task its own 8 MiB adapter instead of its own 13 GiB model.

  • Hosted fine-tuning

    Model providers that offer fine-tuning take the same input the page describes: a file of chat-format examples, usually JSONL. You never see r or α there, but the data rules (consistency, a held-out set, no contradictions) apply unchanged.

  • Distilling a big model into a small one

    A common use of the “efficiency” case: collect a large model’s best answers for your task, filter them hard, and fine-tune a smaller model on them. The small one is cheaper and faster per call, and only has to be good at one thing.

  • The interview version

    “Would you fine-tune or use RAG?” Ask what is wrong first: missing knowledge (RAG) or wrong behaviour (fine-tune). Then cover the data plan, the baseline you must beat, and the regression check on general ability. Naming LoRA is the easy part; the evaluation plan is what is being tested.

Self-check

Check yourself

You raise r from 8 to 16, still on q_proj and v_proj across 32 layers of 4096 × 4096 projections. How many parameters train now?

8,388,608. Each projection trains r·(d + k) = 16·8,192 = 131,072, and there are 32 × 2 = 64 of them. Doubling r doubles the count, and the Adam state goes from 32 MiB to 64 MiB, which is still tiny next to the 13 GiB base.

Training loss keeps falling, but held-out loss bottoms out after epoch 2 and rises in epoch 3. What do you ship?

The epoch-2 checkpoint. Falling training loss with rising held-out loss is the overfitting the page warns about: the model is memorising your examples. More epochs make it worse. Keep the checkpoint where held-out loss was lowest, and if quality is still short, improve the data before adding capacity.

A support bot must answer from product docs that change every week, in a fixed house tone. Which tool for which part?

RAG for the docs; prompting first, then perhaps fine-tuning, for the tone. Weekly-changing facts baked into weights would mean retraining weekly, and the old facts would linger. Tone is behaviour, so fine-tune for it only if a good prompt cannot hold it consistently.

Why is QLoRA’s saving mostly about the base model, while LoRA’s is mostly about the optimizer?

LoRA keeps the base frozen, so it removes the gradients and Adam state for 7B weights (about 65 GiB) but leaves the 13 GiB fp16 base in memory. Once that is done, the base is the largest thing left, so QLoRA attacks it: 4-bit storage cuts it to 3.3 GiB. The adapters and their optimizer state were already only tens of MiB.

Frequently asked

Quick answers

Fine-tune vs RAG vs prompting?

Prompt first (free, instant). RAG to give the model knowledge — facts, private or changing data. Fine-tune to change behavior, style, format, or domain patterns. RAG for what it should know; fine-tuning for how it should behave.

What is LoRA?

A parameter-efficient method that freezes the base model and trains small low-rank adapter matrices injected into its layers. Only a tiny fraction of parameters update, so it's far cheaper than full fine-tuning at comparable quality.

What is QLoRA?

LoRA plus quantization: load the frozen base in 4-bit precision to save memory, then train LoRA adapters on top — letting you fine-tune very large models on a single GPU with minimal quality loss.

What is catastrophic forgetting?

When fine-tuning on a narrow task degrades the model's general abilities, because new weight updates overwrite prior knowledge. LoRA (frozen base), modest training, mixed data, and regression evals all reduce it.

Finished this one? 0 / 209 Handbooks done
NextLoRA vs Full Fine-Tuning Next on the “Training and adaptation” ladder · rung 2 of 7

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks