Efficient Adaptation

Fine-tuning all 175 billion weights of GPT-3 scored 73.8% on WikiSQL, a test that turns questions into database queries. LoRA froze those weights, trained 4.7 million new ones (0.0027% as many) and scored 73.4%. Each task’s file shrank from 350.5 GB to 9.4 MB.

Tap a method, then slide the number of tasks. See what each method trains, what the tasks cost to store, and what each method scores. Then we build every method from zero: prompts, chains of thought, soft prompts, adapters, LoRA and QLoRA.

You need a little Python, what a probability is, the Transformer of Lecture 5 and pretraining from Lecture 7. We build the rest from zero.

Lecture 9, “Efficient Adaptation (Prompting + PEFT)”, of Stanford CS224N, Natural Language Processing with Deep Learning (Winter 2026, Diyi Yang and Yejin Choi). Its readings are GPT-3 (Brown et al., 2020), chain-of-thought prompting (Wei et al., 2022), the lottery ticket hypothesis (Frankle and Carbin, 2019), LoRA (Hu et al., 2021) and adapters (Houlsby et al., 2019). Before: Lecture 8, Post-training. Next: Lecture 10, Agents, Tool Use, and RAG.

Adapt GPT-3 to a task

10 tasks

Scores and trained-weight counts: Table 4 of Hu et al. (2021), GPT-3 175B. WikiSQL varies by about ±0.5 points between runs. “Soft prompt” is the paper’s prefix-embedding tuning, “Prefix” its prefix-layer tuning, “Adapter” Houlsby’s design. Files assume 2 bytes per weight (16-bit), with one frozen base kept for all tasks. The layer stack is a picture of 12 of GPT-3’s 96 layers.

Chapter 0

Why Adapt Efficiently?

Price one full fine-tune, then multiply it by the number of tasks

You have a pretrained model, and your team wants it to do ten jobs: write SQL, summarise chats, tag support tickets and more. The direct route is full fine-tuning: start from the pretrained weights and train all of them on each job’s labelled data.

Two costs grow with the model. Training must hold far more than the weights. Lecture 7 counted 16 bytes per trained weight. That is 2 for the 16-bit weight, 2 for its gradient, 4 for a 32-bit master copy and 8 for Adam’s two running averages. Storage grows with the number of jobs, because each job ends with its own full copy.

Price a full fine-tune

The bar is the 16 bytes each trained weight needs. The squares are 80 GB GPUs. Pick a model, then add jobs and watch the copies pile up.

10 jobs

Weights and optimizer state only, at Lecture 7’s 16 bytes per weight; activations come on top. Each copy uses 16-bit, 2 bytes per weight. Weight counts: GPT-2 XL 1.56 billion, LLaMA 7B 6.74 billion, LLaMA 65B 65.3 billion, GPT-3 175.3 billion. GB means 109 bytes.

The worked number is GPT-3. Its training state is 16 × 175.3 billion = 2.80 TB. One 80 GB GPU holds 1/35 of that, so the state alone needs 36 GPUs, before any activations. Each saved copy is 2 × 175.3 billion bytes = 350.5 GB. Ten jobs make 3.5 TB of files, and a better base model means ten new runs.

The rest of the lecture removes both costs. Some methods change only the prompt and train nothing. Others freeze every pretrained weight and train a small add-on, kept as its own small file. The LoRA paper stored 100 adapted GPT-3 models in about 354 GB, against 35 TB as full copies.

Symptom: the training job runs out of memory before its first step.

Measure: 16 bytes × the trained weights, against the memory of your GPUs.

Fix: freeze the base and train a small add-on (Chapters 4 to 8).

The road

  1. Prompt: in-context learning adapts with examples and no training.
  2. Chain: worked steps in the prompt, and why only large models gain.
  3. Few directions: the lottery ticket and a task’s intrinsic dimension.
  4. Soft prompt: train the prompt as vectors, at the input or every layer.
  5. Adapters: a small bottleneck inside each layer.
  6. LoRA: a low-rank detour that merges away for free.
  7. Rank: where to put LoRA, and how much rank to spend.
  8. Memory: QLoRA keeps the frozen base in 4 bits.
  9. Showcase: plan an adaptation and price every method.
  10. Field guide: the equations, the numbers and the code.
Why does full fine-tuning of GPT-3 for ten jobs cost so much?

Chapter 1

Adapt with the Prompt Alone

Put solved examples in the prompt, change no weight, and see how much a larger model gains

The cheapest change touches no weight at all. GPT-3 (Brown et al., 2020) showed that a large model can do a new task from its prompt alone. You write a short description, add a few solved examples, then the new question. The model continues the text, and the continuation is the answer.

This is in-context learning. Zero-shot gives only the description. One-shot adds one solved example, and few-shot adds as many as fit. GPT-3’s window held 2,048 tokens, which fits about 10 to 100 examples. The model computes no gradient. The examples steer the model through attention, and they are gone after the call.

Build a few-shot prompt

Yellow chips are what you write: a description and solved examples. The warm chip is the question. Pick how many examples and which model, and watch the window fill.

Accuracies: TriviaQA, Appendix H of Brown et al. (2020); few-shot uses 64 examples. Token counts are illustrative: 15 for the description, 25 per example, 15 for the question.

The worked number is TriviaQA, a test of trivia questions. GPT-3 175B answered 64.3% with no examples, 68.0% with one and 71.2% with 64. The smallest GPT-3, with 125 million weights, went from 4.15% to 6.96%. On SuperGLUE, few-shot GPT-3 scored 71.8 on the test set with 32 examples per task. BERT-Large, fine-tuned on 125,000 examples, scored 69.0.

The price moves to every call. The examples ride along each time, so 64 examples of about 25 tokens add 1,600 tokens to every question. The result also depends on which examples you pick and in what order.

Symptom: the same examples in a new order change the accuracy by many points.

Measure: run several orders and compare. Zhao et al. (2021) saw GPT-3 on SST-2 range from 54.3% to 93.4%, as quoted by Wei et al. (2022).

Fix: average over orders, pick examples close to the question, or train a small add-on (Chapter 4 onward).

What changes when you go from zero-shot to few-shot prompting?

Chapter 2

Let the Model Write Its Working

Show worked steps in the examples, and a large model writes its own steps before it answers

Some questions need several steps. “The cafeteria had 23 apples. If they used 20 to make lunch and bought 6 more, how many apples do they have?” Asked for the answer alone, the model must do the arithmetic while it writes the first answer token. In Wei et al. (2022), standard prompting answered 27.

Chain-of-thought prompting changes the examples, not the model. Each solved example shows its working before its answer. The model copies the pattern: 23 − 20 = 3, then 3 + 6 = 9, then “The answer is 9.” Each step it writes becomes context that the next token can read.

Ask for the working

Pick a prompt style and a model. The answer streams in token by token, and the bars show each model’s score on GSM8K both ways.

Scores: GSM8K, Table 2 of Wei et al. (2022), eight chain-of-thought examples. The question and the two answers of the large model are the paper’s Figure 1. Which model solves this one question is illustrative, as is the small model’s chain, written to show the paper’s finding that small models produce fluent but illogical steps.

The worked number is GSM8K, a set of grade-school word problems. With eight chain-of-thought examples, PaLM 540B rose from 17.9% to 56.9%. GPT-3 175B rose from 15.6% to 46.9%. PaLM 8B fell, from 4.9% to 4.1%. The paper found the gain appears only near 100 billion weights.

You do not always need written chains. Kojima et al. (2022) added one sentence to the question: “Let’s think step by step.” On GSM8K, InstructGPT rose from 10.4% to 40.7%. The cost is more output tokens per answer: chain of thought spends compute when the model runs, not when it trains.

Symptom: a small model writes confident steps and a wrong answer.

Measure: accuracy with and without the chain on problems the examples do not cover. PaLM 8B: 4.9% without, 4.1% with.

Fix: use a larger model, or sample several chains and take the most common answer (self-consistency).

Why does chain-of-thought prompting help a large model on word problems?

Chapter 3

A Task Needs Only a Few Directions

Prune most weights of a trained network, then fine-tune a big model inside a tiny random subspace

Prompts stop helping when the model itself must change. Before we train anything, ask how much needs to change. Two results say: little.

First, the lottery ticket hypothesis (Frankle and Carbin, 2019). Train a network, delete the 20% of weights with the smallest size, reset the rest to their starting values, and train again. Repeat. For a small network on MNIST, subnetworks with 3.6% of the weights still matched the full network. Give the same subnetwork fresh random starting values and it learns worse.

Second, intrinsic dimension (Aghajanyan et al., 2021). Freeze the pretrained weights. Train only a few numbers, and spread them over every weight through a fixed random matrix. How few numbers are enough?

Call the pretrained weights θ0, a list of D numbers. Call the trained numbers z, a list of only d. A fixed random matrix P, with D rows and d columns, spreads them out. The fine-tuned weights are θ:

Say it aloud

Theta equals theta-zero plus P times z.

θ
theta the fine-tuned weights: D numbers, the same size as the model.
θ0
theta-zero the pretrained weights, frozen.
P
P a random matrix with D rows and d columns, drawn once and never trained.
z
z the d numbers we train. Training starts at z = 0, so θ starts at θ0.
In plain words

Start from the pretrained weights theta-zero. Train only the d numbers in z. Multiply z by the fixed matrix P to get a change for every weight, and add that change.

With numbers

With made-up numbers, D = 4 and d = 1: θ0 = (1.0, 2.0, −1.0, 0.5), P = (0.5, −0.5, 0, 1) and z = 0.4. Then θ = (1.2, 1.8, −1.0, 0.9). One trained number moved three of the four weights.

Fine-tune in d random directions

The toy model has 64 weights, but its task cares about only a few directions. Each bar is the best result with d random directions. Slide d, then change how many directions the task needs.

d = 3
4

Illustrative toy, solved exactly in your browser. The task’s loss weighs its few directions by 1 and the other directions by 0.02; P is a fixed random 64 × d matrix. Each bar is the best z by least squares, as share of the improvement full fine-tuning would make.

The worked number: RoBERTa-Large has 355 million weights. Trained through d = 207 random directions, it reached 90% of full fine-tuning’s score on MRPC, a paraphrase test. That is 0.00006% of its weights. The change a task needs lives in a small space, and LoRA (Chapter 6) builds on that.

Symptom: a pruned or subspace model falls far below the full one.

Measure: the score against d, or against the share of weights kept; find where it reaches 90%.

Fix: raise d, or prune less per round and keep the original starting values.

What did Aghajanyan et al. measure, and what did they find for RoBERTa-Large on MRPC?

Chapter 4

Train the Prompt Instead of Writing It

Learn a few input vectors by gradient descent, and give every layer its own prefix

A written prompt is a list of words from the vocabulary. Prompt tuning (Lester et al., 2021) drops that limit. It puts p extra vectors in front of the input, trains only those vectors by gradient descent, and freezes the model. The vectors need not match any word, so they are called a soft prompt.

Prefix tuning (Li and Liang, 2021) goes deeper. It gives every layer its own p trained positions, as extra keys and values that the real tokens can attend to. More trained numbers sit closer to each layer’s computation.

Call the number of soft-prompt positions p and the width of the model, the numbers in each vector, d. The count of trained numbers is n:

Say it aloud

n equals p times d.

n
n the trained numbers of one task: all it stores.
p
p the prompt length: how many soft-prompt positions sit in front of the input.
×
times each position holds one full vector.
d
d the model width: the numbers in one token’s vector, 4,096 in T5-XXL.
In plain words

Each soft-prompt position is one vector of d numbers. Make p of them. Their count n is everything you train and store for the task.

With numbers

T5-XXL has d = 4,096 and 11 billion weights. With p = 5, n = 20,480, the count Lester et al. give. With p = 100, n = 409,600: 0.0037% of the model.

Prefix tuning repeats this at every layer, once for the keys and once for the values. With L layers:

nprefix = 2 × L × p × d. GPT-2 Medium, L = 24, d = 1,024, p = 10: 2 × 24 × 10 × 1,024 = 491,520, about 0.14% of its 355 million weights. The paper reports about 0.1%.

Place the trained vectors

Rows are layers, columns are positions. Solid purple cells hold trained numbers; the warm columns are the task’s own tokens. Switch method and model, then lengthen the prompt.

5 positions

The grid draws at most 12 layers and 16 prompt positions. Counts use the full sizes. T5-XXL is an encoder-decoder, so this page counts prompt tuning only for it; prefix counts are for decoder-only models. Context windows: GPT-2 1,024, T5 512 input tokens as trained, GPT-3 2,048.

Scale decides whether it works. Lester et al. found prompt tuning trails full model tuning on small T5 models and matches it at 11 billion weights. In the LoRA paper’s GPT-3 test, full fine-tuning scored 73.8% on WikiSQL. A 3.2 million soft prompt scored 63.1%, and a 20.2 million prefix 70.1%.

Both methods spend part of the context window. Every soft-prompt position is one fewer position for the task’s own text.

Symptom: accuracy goes up and down as you lengthen the prompt.

Measure: the score against p. Lester et al. saw lengths past 100 mildly hurt, and the LoRA paper found prefix tuning hard to optimise.

Fix: start the vectors from real word embeddings, such as the class-label words, and keep p modest.

What does prefix tuning train that prompt tuning does not?

Chapter 5

Insert a Small Bottleneck

Squeeze each layer’s output through m numbers and back, start as the identity, and train only that

Houlsby et al. (2019) trained new weights instead of new inputs. An adapter is a small module placed inside each Transformer layer, once after the attention block and once after the feed-forward block. Every pretrained weight stays frozen.

A bottleneck of m numbers, much smaller than the model width d, keeps each module cheap.

Call the layer’s output h, a vector of d numbers. The down matrix Wdown has m rows and d columns. The nonlinearity is f, and the up matrix Wup has d rows and m columns. The adapter’s output is h′:

Say it aloud

h-prime equals h plus W-up times f of W-down times h.

h′
h-prime the output that goes on to the next part of the layer.
h
h the frozen sublayer’s output, d numbers. It appears twice: once through the skip, once through the bottleneck.
Wdown
W-down a trained m × d matrix that squeezes d numbers to m.
f
f a nonlinearity applied to each of the m numbers, such as ReLU.
Wup
W-up a trained d × m matrix that expands back to d. It starts near zero, so h′ starts equal to h.
In plain words

Multiply h by W-down to get m numbers. Apply f to each. Multiply by W-up to get back to d numbers, and add h.

With numbers

With made-up numbers, d = 2 and m = 1: h = (1, 2) and Wdown = (0.5, 0.5) give 1.5. ReLU keeps 1.5. Wup = (0.2, −0.4) gives (0.3, −0.6), so h′ = (1.3, 1.4). At the start Wup ≈ 0, so h′ = h.

Each adapter holds two matrices and their biases: 2md + d + m weights.

BERT-Large, d = 1,024, m = 64: 2 × 64 × 1,024 + 1,024 + 64 = 132,160 per adapter. Two per layer, 24 layers: 48 × 132,160 = 6,343,680, or 1.92% of 330 million.

Squeeze through the bottleneck

The column on the left is h, the narrow column is the bottleneck, the right column is h′. Change m and the model, and switch between the adapter at the start and after training.

m = 64

Weight counts are exact for the sizes shown, biases included, layer norms left out. The vectors are illustrative, and the drawing shows 16 of the d numbers. Latency: Table 1 of Hu et al. (2021), GPT-2 Medium, batch size 1, 128 tokens.

On GLUE, adapters scored 80.0 against 80.4 for full fine-tuning of BERT-Large, training 3.6% of the weights per task. The best m changed per task: 256 for MNLI, 8 for the small RTE. All the GLUE tasks together needed 1.3 times the model’s size, against 9 times for full copies.

The catch is time. The adapter layers add steps that must run one after another. The LoRA paper timed GPT-2 Medium at batch size 1 and 128 tokens: 19.8 ms per forward pass, and 25.8 ms with Houlsby adapters, 30% more.

Symptom: serving latency rises after you add adapters.

Measure: time a forward pass with and without them. At batch 32 and 512 tokens the same test showed only 3.0% more.

Fix: batch requests, or use LoRA, which merges into the weights (Chapter 6).

Why does an adapter start with Wup near zero?

Chapter 6

Add a Low-Rank Detour

Freeze W0, train two thin matrices whose product is the update, then fold them in for free

Hu et al. (2021) took Chapter 3 one step further. A task’s change lives in a small space. So write the change to each weight matrix as the product of two thin matrices, and train only those.

Take one frozen weight matrix W0, with d rows and k columns. Full fine-tuning would learn an update ΔW of the same size. LoRA (low-rank adaptation) learns B, with d rows and r columns, and A, with r rows and k columns. Their product BA has the full size, but its rank, the number of independent directions in it, is at most r.

Call the layer’s input x and its output h. A fixed number α (alpha) sets the update’s scale:

Say it aloud

h equals W-zero x plus alpha over r times B A x.

h
h the layer’s output, d numbers.
W0
W-zero the pretrained d × k matrix, frozen.
x
x the layer’s input, k numbers. Both paths read the same x.
α/r
alpha over r a fixed scale. You set alpha once; dividing by r keeps the update’s size steady when you change r.
B
B a trained d × r matrix. It starts at zero.
A
A a trained r × k matrix. It starts random, so BA = 0 at the start but can grow.
In plain words

Run the input x through the frozen W-zero as before. Also send x through A, down to r numbers, then through B, back up to d numbers. Scale that detour by alpha over r and add it to the first result.

With numbers

With made-up numbers, d = k = 2, r = 1 and α/r = 1: W0 = [[0.5, 0], [0, 0.5]] and x = (1, 2) give W0x = (0.5, 1.0). A = (0.3, 0.1) gives Ax = 0.5, and B = (2, −1) gives BAx = (1.0, −0.5). So h = (1.5, 0.5).

Train a rank-r update

Left: the update a task wants, 24 × 24. Right: BA as it trains. Press Train, change r, then try starting both matrices at zero.

r = 3

Illustrative toy, trained live: the target is a rank-3 update plus a little noise, d = k = 24, plain gradient descent on the squared error for 300 steps. The dashed line is the best any rank-r matrix can do (truncated SVD). Purple cells are positive values, grey cells negative.

The worked number: one GPT-3 attention matrix is 12,288 × 12,288, 151 million weights. At r = 4, B and A hold 2 × 12,288 × 4 = 98,304 weights, 0.065% of it.

After training, merge: W = W0 + (α/r)BA. In the example, W = [[1.1, 0.2], [−0.3, 0.4]], and Wx = (1.5, 0.5), the same h. The served model has one matrix per layer, as before, so LoRA adds no latency. To switch tasks, subtract one BA and add another.

Symptom: the loss does not move at all.

Measure: the size of BA after a few steps. If it is exactly zero, B and A both started at zero: each one’s gradient is multiplied by the other, so both gradients are zero.

Fix: start A at random and B at zero. The device’s “Start both at zero” switch shows the stall.

Why does a merged LoRA model run exactly as fast as the base model?

Chapter 7

Where to Put LoRA, and How Much Rank

Count LoRA’s weights, then spread a fixed budget over matrices instead of spending it on rank

Each Transformer layer has four attention matrices: Wq for queries, Wk for keys, Wv for values and Wo for the output. It also has the feed-forward matrices. On GPT-3 the LoRA paper adapted only attention matrices and froze the rest.

Call the number of adapted matrices L̂ (L-hat), the model width dmodel and the rank r. The trained weights number |Θ|:

Say it aloud

The size of Theta equals two times L-hat times d-model times r.

|Θ|
the size of Theta the count of trained weights for one task.
2
two each adapted matrix gets two thin matrices, B and A.
L̂
L-hat how many weight matrices get LoRA: 192 for Wq and Wv in all 96 GPT-3 layers.
dmodel
d-model the width of a square attention matrix: 12,288 in GPT-3.
r
r the rank: the columns of B and the rows of A.
In plain words

B and A each hold d-model times r numbers, so one adapted matrix costs 2 times d-model times r. Multiply by L-hat, the number of adapted matrices.

With numbers

GPT-3 with Wq and Wv adapted: L̂ = 192, dmodel = 12,288 and r = 4 give 2 × 192 × 12,288 × 4 = 18,874,368, about 18.9 million. In 16-bit that is 37.7 MB, which the paper calls roughly 35 MB, against 350.5 GB for a full copy.

Spend LoRA’s budget

Each cell is one measured setting. Ringed cells all cost the same 18 million weights. Pick matrices and a rank, or tap a cell; switch the score between WikiSQL and MNLI.

Matrices
Rank r

Scores: Table 6 of Hu et al. (2021), GPT-3 175B validation accuracy; WikiSQL varies by about ±0.5 and MNLI by ±0.1 between runs. Full fine-tuning: 73.8 and 89.5 (Table 4). Weight counts from the equation above.

Table 5 of the paper held the budget at 18 million and moved it around. All of it on Wq (r = 8) scored 70.4% on WikiSQL. Split over Wq and Wv (r = 4), it scored 73.7%. Over all four (r = 2), also 73.7%, with the best MNLI, 91.7%. A small rank on more matrices beat a large rank on one.

Rank itself mattered little. With Wq and Wv, r = 1 scored 73.4% and r = 64 scored 73.5%. The paper warns this need not hold for every task: a task in a new language may need far more. QLoRA (Chapter 8) found the same lesson on LLaMA. LoRA on Wq and Wv alone did not match full fine-tuning; LoRA on every linear layer did.

Symptom: LoRA trails full fine-tuning at every r you try.

Measure: the score as you change which matrices get LoRA, with r fixed.

Fix: adapt more matrices, all of attention and then the feed-forward ones, before you raise r.

With a fixed budget of 18 million LoRA weights on GPT-3, which choice scored best on WikiSQL?

Chapter 8

QLoRA: Keep the Frozen Base in Four Bits

Add up training memory, then shrink the frozen part to 4 bits and keep the trained part in 16

LoRA drops the gradients and optimizer state of the frozen weights, but the frozen weights still sit in GPU memory.

Call the number of trained weights Nt and the bytes each one needs during training bt. Call the number of frozen weights Nf and the bytes each one takes to store bf. Training memory is M:

Say it aloud

M equals b-t times N-t plus b-f times N-f.

M
M training memory for weights and optimizer state, in bytes. Activations come on top.
bt
b-t bytes per trained weight: 16 (16-bit weight and gradient, 32-bit master copy, two Adam averages).
Nt
N-t the number of trained weights: all of them in full fine-tuning, a few million with LoRA.
bf
b-f bytes per frozen weight: 2 in 16-bit, about 0.52 in QLoRA’s 4-bit format with its scales.
Nf
N-f the number of frozen weights.
In plain words

Multiply the trained weights N-t by 16 bytes each. Multiply the frozen weights N-f by the bytes each one takes to store. Add the two.

With numbers

GPT-3 with LoRA at r = 4: 16 × 18.9 million = 0.30 GB, plus 2 × 175.3 billion = 350.5 GB, so M = 350.8 GB. The LoRA paper measured 350 GB, down from 1.2 TB for full fine-tuning.

QLoRA (Dettmers et al., 2023) shrinks bf. It stores the frozen weights in 4-bit NormalFloat (NF4): 16 levels spaced to suit weights that follow a bell curve. Each block of 64 weights shares one scale. Storing those scales in 8 bits, called double quantization, costs 0.127 bits per weight instead of 0.5.

The arithmetic stays in 16-bit. In each forward pass QLoRA turns the 4-bit weights back into 16-bit numbers, then multiplies. Gradients flow back through it into the LoRA weights.

Fit fine-tuning on one GPU

The bar stacks the frozen base, its scales and the trained weights with their state. The lines are 24, 48 and 80 GB GPUs. Pick a model and a method, then switch double quantization off.

Our estimate from the equation above: weights and optimizer state only, no activations. LoRA and QLoRA both use QLoRA’s setting, rank 64 on every linear layer. 4-bit costs 4 bits plus 0.127 bits of scales with double quantization, 0.5 without. LLaMA sizes from its published shapes; GB means 109 bytes.

The worked number is LLaMA 65B, with 65.3 billion weights. The 4-bit base costs 65.3 billion × 4.127/8 bytes = 33.7 GB. LoRA on every linear layer at r = 64 adds 0.80 billion trained weights: 12.8 GB at 16 bytes each. The total is 46.5 GB, under one 48 GB GPU. The paper reports a drop from more than 780 GB to under 48 GB; it counts 12 bytes per trained weight, where we count 16.

Symptom: QLoRA still runs out of memory on long sequences.

Measure: activations grow with batch size times length. In the paper’s 7B example, LoRA’s input gradients took 567 MB against 26 MB for the LoRA weights.

Fix: gradient checkpointing (18 MB per sequence in that example) and QLoRA’s paged optimizers, which move state to CPU memory during spikes.

What does QLoRA store in 4 bits?

Chapter 9

Plan an Adaptation

Pick a base model, your GPUs and the number of tasks, and price every method side by side

Every number in this planner comes from the last eight chapters. Training memory is M = btNt + bfNf. Each task’s file holds only its trained weights, in 16-bit. The last column says what each call pays beyond the base model.

Price every method

A tick means the method fits on your GPUs; a cross means it does not. Change the model, the GPU size and count, and the number of tasks.

1 GPU
10 tasks

Illustrative planner. Memory counts weights and optimizer state only; activations and the KV cache come on top, so a tight fit may still fail. Settings: few-shot with 64 examples of 25 tokens; soft prompt p = 100; Houlsby adapters with m = 64; LoRA on Wq and Wv at r = 8; QLoRA at r = 64 on every linear layer. Scores are not modelled here; Chapters 1 to 8 give the measured ones.

Three settings tell the story. LLaMA 7B on one 24 GB GPU: LoRA needs 13.5 GB and fits, while full fine-tuning needs 107.8 GB. LLaMA 65B on one 48 GB GPU: QLoRA, at 46.5 GB, is the only method that fits. Even running the 16-bit model for few-shot prompts needs 130.6 GB. GPT-3 with 100 tasks: full copies take 35 TB, while 100 LoRA files add 7.5 GB to the one base.

Symptom: the plan fits, but the score disappoints.

Measure: score each method on held-out examples from your task.

Fix: move one step up the ladder: few-shot, then a soft prompt, then LoRA on more matrices, then full fine-tuning.

You have LLaMA 65B and one 48 GB GPU. Which method can train?

Chapter 10

Field Guide

Keep the methods, the numbers and the code, and see where the course goes next

You can adapt a pretrained model without copying it. Prompts change only the input: examples for in-context learning, worked steps for chain of thought. When the model must change, the change is small. It fits in a few hundred random directions, a soft prompt, a bottleneck per layer, or a low-rank update per matrix. LoRA’s update merges away, and QLoRA keeps the frozen base in 4 bits.

MethodWhat it trainsTrained on GPT-3Extra cost per call
Few-shot promptnothing; examples in the prompt0the examples’ tokens
Chain of thoughtnothing; worked steps0the generated steps
Soft promptp input vectors3.2 millionp positions
Prefixkeys and values at every layer20.2 millionp positions per layer
Adaptera bottleneck per sublayer7.1 millionextra serial layers
LoRAB and A per adapted matrix4.7 millionnone once merged
QLoRALoRA on a 4-bit frozen basenot testednone once merged into 16-bit
Full fine-tuningevery weight175 billionnone
NumberValueWhere
GPT-3 full fine-tune: state and one copy2.80 TB and 350.5 GBChapter 0
TriviaQA, GPT-3 175B: zero-shot against 64 examples64.3% against 71.2%Chapter 1
GSM8K, PaLM 540B: standard against chain of thought17.9% against 56.9%Chapter 2
RoBERTa-Large, MRPC: directions for 90%207 of 355 millionChapter 3
Soft prompt, T5-XXL, p = 520,480 numbersChapter 4
Adapters on GLUE against full fine-tuning80.0 against 80.4, at 3.6% per taskChapter 5
Adapter latency, batch 119.8 ms to 25.8 msChapter 5
LoRA, one GPT-3 matrix at r = 498,304 of 151 millionChapter 6
Same 18 million budget: Wq only against Wq, Wv70.4% against 73.7%Chapter 7
LLaMA 65B with QLoRA46.5 GB (our estimate), under 48 GBChapter 8

The core as code: an adapter, a LoRA layer with its merge, and a soft prompt, in PyTorch.

python
import torch, torch.nn as nn

class Adapter(nn.Module):                        # h' = h + W_up f(W_down h)
    def __init__(self, d, m):
        super().__init__()
        self.down, self.up = nn.Linear(d, m), nn.Linear(m, d)
        nn.init.zeros_(self.up.weight); nn.init.zeros_(self.up.bias)   # start as the identity
    def forward(self, h):                            # h: [batch, seq, d]
        return h + self.up(torch.relu(self.down(h)))

class LoRALinear(nn.Module):                     # h = W0 x + (alpha/r) B A x
    def __init__(self, base: nn.Linear, r=8, alpha=16):
        super().__init__()
        self.base = base.requires_grad_(False)          # W0 frozen
        d, k = base.weight.shape                         # [out, in]
        self.A = nn.Parameter(torch.randn(r, k) * 0.01)  # random
        self.B = nn.Parameter(torch.zeros(d, r))         # zero, so BA = 0 at the start
        self.scale = alpha / r
    def forward(self, x):                            # x: [batch, seq, k]
        return self.base(x) + self.scale * (x @ self.A.T @ self.B.T)
    @torch.no_grad()
    def merge(self):                                 # one matrix again: no extra latency
        self.base.weight += self.scale * (self.B @ self.A)

class SoftPrompt(nn.Module):                     # n = p x d trained numbers
    def __init__(self, p, d):
        super().__init__()
        self.P = nn.Parameter(torch.randn(p, d) * 0.02)
    def forward(self, emb):                          # emb: [batch, seq, d] token embeddings
        return torch.cat([self.P.expand(emb.size(0), -1, -1), emb], dim=1)

def lora_count(L_hat, d_model, r): return 2 * L_hat * d_model * r       # |Theta|
def train_bytes(N_t, N_f, b_f=2.0): return 16 * N_t + b_f * N_f       # M, no activations

Where the course goes next. These methods adapt a model to one task at a time. Lecture 10 builds on prompting: agents that call tools and retrieve documents, and use chain of thought to plan. Lecture 18 returns to LoRA with a guest view of when it matches full fine-tuning.

Keep going

Read next

The habit. Before you fine-tune, write down three numbers: how many weights you will train, the bytes they and the frozen base need, and the size of one task’s file. Then try the cheapest method that can reach your score.
Which sentence best sums up the lecture?

Now teach it: press Present or Teach. Explain why few-shot examples change no weight, why LoRA’s B starts at zero, and why a merged LoRA model costs nothing extra to run. Then go back to the hero, tap Soft prompt and then LoRA, and say why one loses 10.7 points and the other 0.4.

Efficient Adaptation · Stanford CS224N, Lecture 9
Before: Post-training · Next: Agents, Tool Use, and RAG · Course site · Back to Gleams