After this chapter you will be able to
compute the memory of full fine-tuning and of LoRA, and say where the saving comes from;
quantise a row of weights by hand, and show how one outlier ruins a shared scale;
say why prefill is compute-bound and decoding is memory-bound;
size the KV cache and say what shrinks it;
name two effects that appear only after a model is deployed.
This chapter builds on Chapters 19 and 17, which supply the model and the cost of attention.
Most of this book has followed capability, through larger models, longer contexts and better scores. There is a second axis, and outside research it is usually the binding one, because a model that cannot run within your budget, memory or latency is not available to you at any quality.
This chapter is about that axis, and it divides cleanly into three questions. How do I adapt a model without paying for full fine-tuning, how do I make the model smaller, and how do I make it answer faster?
Full fine-tuning updates every weight, and the memory cost is worse than the parameter count suggests. For a billion parameter model in half precision (fp16, two bytes per number, where fp32 uses four):
| what must be held | memory |
|---|---|
| weights, fp16 | 14 GB |
| gradients, fp16 | 14 GB |
| Adam’s two moments, fp32 | 56 GB |
| total, before activations | 84 GB |
Adam is the standard optimiser, a refinement of gradient descent, and it keeps two running averages for every parameter, one of the gradient and one of its square. Each fp32 quantity is four bytes per parameter (Appendix A), so one moment over billion parameters is GB and two are . Mixed precision training usually keeps an fp32 master copy of the weights as well. This is another GB and takes the total past . The table leaves it out, so treat GB as the floor and not the figure. Either way it is several high-end accelerators to fine-tune a model that fits on one for inference, and the result is a whole new GB of weights per task.
Low-rank adaptation (Hu et al. 2022) rests on one observation, which is that the change a fine-tune makes to a weight matrix has low intrinsic rank even though the matrix does not. So do not learn the change directly but factor it:
Freeze entirely and train only and . The arithmetic is the argument, since a full matrix has parameters while the adapter has .
| rank | full matrix | adapter | share |
|---|---|---|---|
| 1 | 16,777,216 | 8,192 | 0.05% |
| 4 | 16,777,216 | 32,768 | 0.20% |
| 8 | 16,777,216 | 65,536 | 0.39% |
| 16 | 16,777,216 | 131,072 | 0.78% |
| 64 | 16,777,216 | 524,288 | 3.13% |
Those figures are for , a typical attention projection. At you train four tenths of one per cent of the weights, and the optimiser state shrinks in the same proportion, which is where most of the memory in the table above went.
Three practical consequences follow, and the third is the one people underrate. You can fine-tune a large model on one accelerator. An adapter is megabytes and not gigabytes, so you can keep hundreds of them. And because Equation (25.1) is an addition to a frozen , adapters can be swapped at serving time without reloading the base model, which gives one model in memory and many behaviours. QLoRA combines the idea with a quantised base model and puts fine-tuning a billion parameter model within reach of a single accelerator.
Weights are usually trained in bits and they rarely need bits to be used. The codes below are integers, so int8 means an 8-bit integer and int4 a 4-bit one.
| precision | bytes per parameter | a 7B model |
|---|---|---|
| fp32 | 4 | 28.0 GB |
| fp16 | 2 | 14.0 GB |
| int8 | 1 | 7.0 GB |
| int4 | 0.5 | 3.5 GB |
The int4 row is the interesting one, because a model that needed a data-centre card at fp16 now fits on a consumer GPU. Quality loss at int8 is usually indistinguishable in practice, and at int4 the loss is measurable but often acceptable, which is almost always a better trade than moving to a genuinely smaller model.
A quantised weight is an integer code and a scale shared across a group of weights. For a symmetric scheme the scale is set by the largest magnitude in the group,
where is for int8 and for int4. Take eight weights from one row of a hidden layer and put them through Equation (25.2) twice:
| int8, | int4, | ||||
|---|---|---|---|---|---|
| 2-3(l)5-6 | error | error | |||
| rms error | |||||
Halving the bit width multiplies the root mean square error by , because the step between neighbouring codes grows from to . The largest weight is exact in both columns, since it is what defines the scale.
Equation (25.2) has a weakness that matters enormously in practice. The scale is set by the largest magnitude, so a single extreme value drags it upward and every other weight in the group inherits a coarser step. Trained transformers reliably produce such outliers in a few coordinates.
Add one weight of to the same row and the int8 scale moves from to , which is times coarser. The outlier itself is then stored with no error at all, while the small weights that make up the rest of the row carry up to per cent error. There are far more of them, and they are the ones doing the work.
The repair is to stop sharing one scale across the whole row:
| scheme | scale | rms error over the row |
|---|---|---|
| one scale for the whole row | ||
| two scales, normal weights | ||
| two scales, the outlier |
Thirteen times less error, for a cost that is easy to miss. The scales now have to be stored too, and one fp16 scale for every group of weights adds two bytes per , which is a quarter of a bit per weight. So int4 with group scales costs bits, and every quantisation scheme in use is negotiating that same trade between the size of a group and the damage one outlier inside it can do.
Run it.
code/worked_examples/quantization.pyproduces every table in this section. Run--roundfor the two precisions,--outlierfor the damage one weight does and--channelfor the repair. Change the outlier from to and watch how much of the error disappears.
Distillation trains a small student to match a large teacher’s output distribution, and the teacher’s full distribution carries more information than a hard label does, because it says which wrong answers were nearly right. Pruning removes weights or whole structures that contribute little, where unstructured pruning gives better compression ratios while structured pruning gives speedups on real hardware, because it removes shapes, not scattered entries.
The general finding across all three techniques is the same. Models are substantially over-parameterised for inference, and most of that slack can be recovered without retraining from scratch.
Generation has two phases with completely different cost profiles, and conflating them causes most confusion about latency. Prefill processes the whole prompt in parallel, so it is compute-bound and fast per token. Decoding produces one token at a time, each depending on the last, so it is memory-bound, because every step reads the entire weight matrix to produce one token. The second phase therefore dominates wall-clock time on any answer of reasonable length, and it is the one worth optimising.
Each decoding step recomputes attention over the whole prefix, so caching the keys and values avoids that, and it is the standard first optimisation for inference. It also becomes the memory problem. For and layers in fp16, where one token costs bytes, or half a mebibyte:
| context length | KV cache |
|---|---|
| 2,048 | 1.07 GB |
| 32,768 | 17.18 GB |
At long context the cache can exceed the weights, since GB against the GB of fp16 weights is a cache larger than the model. This is why grouped-query attention exists, sharing key and value projections across heads, and it is one of the few architecture changes since the original transformer driven purely by serving cost.
Throughput comes from batching, because decoding is memory-bound and processing many sequences at once costs little more than one. Serving systems therefore batch aggressively and schedule continuously and do not wait for a batch to fill.
Underneath all of it sits the of Chapter 17, where quadrupling the context multiplies the attention cost sixteen-fold, and every long-context technique is an attempt to pay less than that. FlashAttention does not change the complexity but the memory traffic, computing attention in tiles that fit in fast on-chip memory, which is a large practical speedup for no change in the result.
Two effects only appear after shipping, and neither is a modelling problem. Drift is the first. The world changes and the training data does not, so a model’s accuracy on live traffic decays even though the model has not changed. The response is monitoring, not retraining on a schedule. Feedback loops are the second. A deployed model influences the data it will later be trained on, so a recommender changes what people read and a text model changes what people write. That loop is now measurable in web corpora.
The engineering discipline here is the empirical method of Chapter 15 applied to a system, not an experiment. State the metric, hold out the evaluation, log the failures, and look at them.
Summary
Efficiency is the other axis of progress. Full fine-tuning holds weights, gradients and two optimiser moments, so the memory is several times the model. LoRA freezes the weight and trains a low-rank update whose size is a fraction of one per cent of the matrix, so a large model fits on one accelerator and adapters can be swapped at serving time. Quantisation stores weights as integer codes with a shared scale, halving the bits multiplies the rounding error by about twenty on the worked row, and one outlier coarsens the scale for the whole group, so scales are shared over small groups. Distillation and pruning recover the slack of over-parameterised models. Prefill is compute-bound and decoding is memory-bound, the KV cache grows with context and can exceed the weights, and batching and FlashAttention reduce the cost. Deployed models drift and shape their own future data.
Key terms
LoRA. fine-tuning that freezes a weight and trains a low-rank additive update.
quantisation. storing weights as low-precision integer codes with a shared scale.
distillation. training a small student to match a large teacher’s output distribution.
prefill. processing the prompt in parallel before generation starts.
drift. decay of accuracy on live traffic because the world changes and the model does not.
Hu et al. (2022) introduce LoRA and its rank ablations are worth
reading for the intuition about intrinsic dimension. Dettmers et al.
(2023) combine it with quantisation. Dao et al. (2022) explain why
memory traffic, not arithmetic is the bottleneck. LoRA is
peft, quantised loading is bitsandbytes, and
vLLM is the serving stack that made paged attention and continuous
batching standard.
25.1 Count the adapter. For , compute the LoRA parameter count at and express each as a share of the full matrix. Then repeat for . Why is the share so much larger on the smaller matrix, and what does that imply about where LoRA pays best?
25.2 The memory budget. Work out the full fine-tuning memory for a billion parameter model in fp16 with Adam, then the same figure with LoRA at applied to attention projections only. State every assumption you made.
25.3 Choose a precision. A B model must run on a card with GB of memory, leaving GB for activations and the KV cache. Which precision can you use? Now the context must be tokens. Recompute and say what has to give.
25.4 Prefill against decode. Explain why the first phase is compute-bound and the second memory-bound. Then predict which phase dominates for a token prompt with a token answer, and for a token prompt with a token answer.
25.5 Size the cache. For , and fp16, compute the KV cache at and tokens. At which length does it exceed the weights of a B model? Name one architectural change that reduces it.
In practice
25.6 Pick the technique. For each constraint, choose one method from this chapter and justify it: (a) one accelerator, must serve forty customer- specific behaviours; (b) model must run on a phone; (c) latency is fine but throughput is a tenth of what is needed; (d) context must grow from 4k to 64k.
Build and measure
25.7 The exact weight is the useless one. In both columns of the quantisation table the weight has zero error, because it sets the scale. Explain why the most faithfully stored weight in a group is always the one you learn least from. Then quantise the same eight weights after deleting and report what happens to the other seven.
25.8 Price the outlier. With one scale for the row, the outlier costs the small weights up to per cent error. Compute the rms error for group sizes of , and weights, counting the stored scales each time at two bytes per group. Plot error against bits per weight and say where you would stop.
25.9 Where int4 stops paying. Halving the bit width multiplied the rms error by on this row. Work out what that factor would be for a row with no outlier and a flat spread of weights, and explain why real transformer rows behave worse than your calculation.
25.10 Make the library agree with your
count. Wrap a single
linear layer in a peft LoraConfig at
and call print_trainable_parameters. It reports
trainable weights, exactly the figure Problem 1 asks you to compute. It
also reports the fraction as
per cent where this chapter says
.
Neither is a rounding error. Find the difference in the two
denominators, and say which one you would quote to someone deciding
whether to fine-tune.
25.11 Predict the outlier. Before computing, predict whether adding one weight of to the row of this chapter hurts the int8 error more or less than the weight of did, and by roughly what factor. Then compute it.
25.12 A cost conversation. A team asks whether to quantise to int4 or to move to a smaller model. State the two measurements you would take first and what result would make you choose each.
Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.
quantization.pyWhat rounding a weight costs
The affine map, the error it leaves, and why one outlier ruins a whole row.
runs in your browser Run itFrom Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.