Skip to content
MAMasterAI Now
9 / 1116 Min. LesezeitNiveau: Advanced5 Karten

Instruction-Tuning (LoRA)

Ein Textvervollständiger wird Assistent, ohne das ganze Modell neu zu trainieren.

⚠ Diese Etappe ist zu 2% auf Deutsch übersetzt; die übrigen Karten erscheinen auf Englisch. Fehler entdeckt? Korrekturen an Übersetzungen sind willkommen.

Lesefortschritt0%
Card 1 — the mismatchKarte 1 von 5

A pre-trained model completes text, it does not help you

Ask a base model a question and it may write more questions.

A base language model was trained on one task: continue the text. Ask "What is the capital of France?" and a raw base model might respond with a list of more exam questions, because that is what tends to follow such a line on the internet. It has the knowledge; it lacks the format of helpfulness.

Analogy
A brilliant student with no brief

You hired a genius researcher but never told them what you want. They will happily produce whatever seems to follow from your note. Instruction tuning is the briefing: thousands of worked examples of "here is a request, here is what a good answer looks like".

Supervised fine-tuning (SFT) trains on datasets of instructions paired with ideal responses, often including a system prompt and multi-turn structure. Crucially, the loss is only computed on the response tokens, not the instructions — you do not want to teach the model to write your prompts back to you.

py
# Chat template with masked prompt tokens
messages = [
    {"role": "system", "content": "You are a concise ML tutor."},
    {"role": "user", "content": "Explain gradient descent in one sentence."},
    {"role": "assistant", "content": "Repeatedly step downhill on the loss surface ..."},
]

ids = tokenizer.apply_chat_template(messages, return_tensors="pt")

# labels = -100 on the prompt/system tokens -> zero loss contribution
labels = ids.masked_fill(prompt_mask, -100)
Ein kurzer Check vor der nächsten Karte

During instruction tuning, why are the prompt tokens masked out of the loss?

5 Wissenschecks

🔒

Playground gesperrt

Schließe alle 5 Karten und ihre Checks ab, um die Simulation freizuschalten.

Read the full stage transcript (all 5 cards, no JavaScript required)
Card 1 — the mismatch

1. A pre-trained model completes text, it does not help you

Ask a base model a question and it may write more questions.

A base language model was trained on one task: continue the text. Ask "What is the capital of France?" and a raw base model might respond with a list of more exam questions, because that is what tends to follow such a line on the internet. It has the knowledge; it lacks the format of helpfulness.

Analogy
A brilliant student with no brief

You hired a genius researcher but never told them what you want. They will happily produce whatever seems to follow from your note. Instruction tuning is the briefing: thousands of worked examples of "here is a request, here is what a good answer looks like".

Supervised fine-tuning (SFT) trains on datasets of instructions paired with ideal responses, often including a system prompt and multi-turn structure. Crucially, the loss is only computed on the response tokens, not the instructions — you do not want to teach the model to write your prompts back to you.

py
# Chat template with masked prompt tokens
messages = [
    {"role": "system", "content": "You are a concise ML tutor."},
    {"role": "user", "content": "Explain gradient descent in one sentence."},
    {"role": "assistant", "content": "Repeatedly step downhill on the loss surface ..."},
]

ids = tokenizer.apply_chat_template(messages, return_tensors="pt")

# labels = -100 on the prompt/system tokens -> zero loss contribution
labels = ids.masked_fill(prompt_mask, -100)

Knowledge check: During instruction tuning, why are the prompt tokens masked out of the loss?

  • a. So the model is optimised to produce good responses, not to reproduce your prompts← correct
  • b. Because prompts are shorter than responses
  • c. To save GPU memory

Masking with -100 tells the loss function to ignore those positions. It is a small implementation detail with a large behavioural effect.

Card 2 — the obstacle

2. Full fine-tuning is a hardware problem first

Fine-tuning a 7B model the classic way needs far more than a 7B-sized GPU.

ComponentMemory cost (7B model, fp16)Why
Weights~14 GB7B parameters × 2 bytes
Gradients~14 GBOne per parameter
AdamW optimiser state~56 GBTwo fp32 tensors per parameter
ActivationsSeveral GB, grows with batchCached for the backward pass
Total≈ 84 GB+Two 80 GB cards before you have any headroom

Worse, every fine-tune produces a full copy of the model. Serving ten customer-specific variants means ten 14 GB checkpoints. This is the practical wall that parameter-efficient fine-tuning (PEFT) was invented to break.

Analogy
Sticky notes on a hardback book

Full fine-tuning rewrites the entire textbook for each reader. LoRA leaves the book untouched and adds a small pad of sticky notes that adjust the meaning. The original knowledge stays intact, the customisation is tiny, and you can swap note-pads instantly.

Knowledge check: Why does AdamW make full fine-tuning so memory-hungry?

  • a. It stores two extra fp32 tensors per parameter as optimiser state← correct
  • b. It duplicates the activations
  • c. It requires a copy of the dataset in GPU memory

Optimiser state often exceeds the weight memory itself. This is exactly the cost LoRA avoids by training a tiny number of new parameters.

Card 3 — the trick

3. LoRA: learn a small correction instead of rewriting the weights

Freeze the model. Train two skinny matrices that nudge it.

LoRA (Low-Rank Adaptation) starts from an empirical observation: the change a fine-tune makes to a weight matrix has low intrinsic rank. So instead of updating a d×d weight matrix W directly, freeze W and learn a correction ΔW = B·A, where A is r×d and B is d×r with r as small as 8 or 16.

h = W₀x + (α/r)·B·A·x
W₀ is frozen. Only A and B receive gradients, scaled by alpha/r so rank changes do not change the effective magnitude.
Rank rTrainable params (per 4096×4096 layer)Typical use
4≈ 0.2% of the layerStyle and tone adjustment
16≈ 0.8% of the layerThe common default for instruction data
64≈ 3% of the layerNew domain or a genuinely new skill
Full rank100%That is just fine-tuning again
  • A is initialised randomly, B is initialised to zero, so ΔW starts at zero and the model begins as the original model.
  • Target modules matter: adapting all attention projections and the MLP is the standard recipe; attention-only is a cheaper subset.
  • Merging works because the correction is a plain matrix add: W₀ + BA folds LoRA away for zero inference overhead.
  • Multiple adapters can share one base model, and switching them costs only a load — the reason multi-tenant fine-tuned serving is practical.

Knowledge check: Why is the B matrix initialised to zeros in LoRA?

  • a. So the LoRA correction starts as zero and training begins from the original model behaviour← correct
  • b. To save memory
  • c. Because random initialisation is impossible for large matrices

Zero-init makes the adapted model identical to the base model at step 0, which is what makes LoRA training stable and safe to abort.

Card 4 — the recipe

4. QLoRA and a working fine-tune recipe

4-bit base weights, full-precision adapters, one consumer GPU.

QLoRA quantises the frozen base model to 4-bit and keeps LoRA adapters in higher precision. The base is never trained, so its quantisation error is a fixed cost, not something you must accumulate gradients through. This is how a 7B or even 13B model can be fine-tuned on a single 24 GB GPU.

py
from peft import LoraConfig, get_peft_model
from transformers import BitsAndBytesConfig

bnb = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype="bfloat16",
)

model = AutoModelForCausalLM.from_pretrained(base, quantization_config=bnb)

config = LoraConfig(
    r=16, lora_alpha=32, lora_dropout=0.05,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj"],
    task_type="CAUSAL_LM",
)
model = get_peft_model(model, config)   # ~0.5% of params now trainable
  • Quality over quantity in SFT data: a few thousand curated, consistent examples beat 100k noisy ones.
  • Consistent formatting matters more than raw volume — the model imitates your template exactly.
  • Learning rate: LoRA tolerates ~10–100× higher rates than full fine-tuning (1e-4 to 2e-4).
  • Watch for catastrophic forgetting: heavy fine-tuning on one narrow style degrades general ability. Mix in a little general data, or lower alpha.
Watch outThe classic mistake

Fine-tuning to inject facts is usually the wrong tool — retrieval does it better and keeps citations. Fine-tuning changes how the model behaves and formats; RAG changes what it knows.

Knowledge check: You need the model to answer questions about your company wiki, updated weekly. What is the better approach?

  • a. Fine-tune with LoRA every week
  • b. Retrieval-augmented generation, reserving fine-tuning for behaviour and format← correct
  • c. Pre-train a new base model

Facts change; behaviour is stable. RAG keeps knowledge fresh and traceable, while a style or format fine-tune can be reused unchanged.

Card 5 — the trade-offs

5. Choosing between prompting, RAG and fine-tuning

Three tools, three different problems. Most teams reach for the wrong one first.

You need to…Best toolCostEffort
Change tone, format or output schemaPromptingZeroMinutes
Add facts that change oftenRAGLow (embedding + storage)Days
Inject a stable new skill or domain styleLoRA / SFTLow (one GPU, hours)Days
Teach preferences, safety and refusal styleRLHF / DPOHigh (data + compute)Weeks
Change what the base model is capable ofPre-trainingVery highMonths
  • Always start with the cheapest option that could plausibly work: prompting, then RAG, then PEFT.
  • A fine-tune cannot add knowledge reliably, and retrieval cannot reliably change style. Use both when you need both.
  • Keep an evaluation set of 50–200 real cases. Without it you cannot tell whether any of this helped.
  • Version everything: base model, adapter, prompt template and evaluation set are one artefact.
Good to knowWhat you can now do

You know how to curate data, tokenize it, embed it, pretrain on it, tune it for instructions, and align it to preferences. The final stage covers what happens at request time — where latency, cost and memory all live.

Knowledge check: What is fine-tuning generally poor at, compared with retrieval?

  • a. Reliably adding facts that change over time← correct
  • b. Changing output formatting
  • c. Learning a consistent brand tone

Training data becomes diffuse and forgettable knowledge. Retrieval injects facts verbatim, with citations, and can be updated in seconds.