What is LoRA and parameter-efficient fine-tuning (PEFT)?

Learning path, stage 3 of 5: RAG and fine-tuning · question 9 of 10

LoRA (Low-Rank Adaptation) fine-tunes a model by freezing the original weights and training small low-rank matrices (A·B) added to selected layers. You train well under 1% of the parameters, use far less GPU memory, and ship a small adapter file instead of a full model copy. Quality is often close to full fine-tuning.

Why it works

The weight updates needed to adapt a model to a task tend to be low-rank, so W + ΔW ≈ W + B·A with rank r (for example 8–64) captures most of the change.

PEFT family

  • LoRA: adapters on the attention and MLP projections.
  • QLoRA: LoRA on top of a 4-bit quantised base model, so large models can be fine-tuned on a single GPU.
  • Prefix or prompt tuning: learn soft prompt vectors instead.

Practical benefits

  • Switch between several task adapters on one base model at serving time.
  • Cheap to experiment. Merge the adapter into the weights for zero added latency.

Interview caveats

  • Fine-tuning shapes behaviour and format, not reliable new facts (use RAG for those).
  • You need clean data and an eval set. Watch for catastrophic forgetting and overfitting.

Sources

Code example

tsx
1// The LoRA idea in numbers: a frozen W plus a trainable low-rank update B·A.
2const d = 4096, k = 4096, r = 16;
3
4const fullParams = d * k; // 16,777,216 trainable for one matrix
5const loraParams = r * (d + k); // 131,072 trainable (A: r×k, B: d×r)
6console.log(`LoRA trains ${((loraParams / fullParams) * 100).toFixed(2)}% of this layer`);
7
8// forward pass: h = W·x + (alpha / r) · B·(A·x)
9type M = number[][];
10const mv = (m: M, v: number[]) => m.map((row) => row.reduce((s, w, i) => s + w * v[i], 0));
11
12export function loraForward(W: M, A: M, B: M, x: number[], alpha = 32) {
13 const base = mv(W, x); // frozen
14 const delta = mv(B, mv(A, x)); // trainable, low rank
15 return base.map((v, i) => v + (alpha / r) * delta[i]);
16}

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod pg, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app