Search

Search papers and lessons

QLoRA

Level 4 · 10 min read

QLoRA fine-tunes a large model whose frozen weights are stored in 4 bits, training only small LoRA adapters in 16-bit, so a 65B model fits on a single 48 GB GPU.

On this page

  • Colour = topic mix
  • Linear algebra
  • Calculus
  • Post-training
  • Probability
  • Efficiency
  • Neural network basics
  • Sign in to see your progress

TL;DR

QLoRA is a way to fine-tune a large language model when the model barely fits in memory. The pretrained weights are frozen and stored in a compressed 4-bit format. Gradients flow back through those 4-bit weights, but only a small set of LoRA adapters, kept in 16-bit precision, receives updates. Two extra tricks shave the memory of the quantization bookkeeping, and a paging scheme stops rare memory spikes from crashing training.

The result is that a 65-billion-parameter model can be fine-tuned on one 48 GB GPU, with accuracy matching 16-bit LoRA on the benchmarks the authors tested.

Where you'll see it: fine-tuning open-weight chat models on a single workstation or a single rented GPU.

Intuition

Keep the big thing small, train the little thing precisely

Fine-tuning has two memory costs. The first is the model's weights, which must be in memory to run it. The second is everything needed to compute updates: activations, gradients and optimizer state. For a large model the weights dominate the first cost, and the trainable part is tiny.

LoRA already solved most of the second cost. It freezes the weights and adds a small trainable correction to each layer, so only a fraction of a percent of parameters receive gradients. But the frozen weights still sit in 16-bit precision, and at 65 billion parameters that is about 130 GB before anything else.

QLoRA's observation is that the frozen weights do not need to be precise to be useful as a fixed base. If you store them in 4 bits, you save about four times the memory. Training then works like this: when a layer's computation needs the weights, the 4-bit values are expanded to 16-bit for that one multiplication, and the adapters are trained in 16-bit as usual. The adapters can compensate for the small errors the compression introduced, because they are learned from data after the compression.

flowchart LR
  W[Pretrained weights in 4-bit NF4] -->|dequantise to BF16 per layer| M[Matrix multiply]
  X[Input activations BF16] --> M
  L[LoRA adapters in BF16, trained] --> A[Add low-rank correction]
  X --> A
  M --> Y[Layer output]
  A --> Y

Why plain 4-bit quantization is not enough

Quantization of a trained model to 4 bits for inference loses accuracy. Earlier work showed that the loss is real even though the model still works. QLoRA's claim is that the loss can be recovered by training adapters after quantization, and that the choice of 4-bit number format matters a lot for how much is lost.

The math

Block-wise quantization

Quantize a tensor by scaling it so its largest magnitude maps to the top of the integer range. For a tensor X\mathbf{X}, with c=127absmax⁡(X)c = \dfrac{127}{\operatorname{absmax}(\mathbf{X})} for signed 8-bit,

XInt8=round⁡(c⋅X),dequant⁡(c,XInt8)=XInt8c.\mathbf{X}^{\text{Int8}} = \operatorname{round}(c \cdot \mathbf{X}), \qquad \operatorname{dequant}(c, \mathbf{X}^{\text{Int8}}) = \frac{\mathbf{X}^{\text{Int8}}}{c}.

Here cc is the quantization constant, the scale that must be stored to undo the mapping. A single large value, an outlier, sets absmax⁡\operatorname{absmax} and wastes most of the integer range on the rest of the tensor. The fix is to cut the tensor into blocks of size BB and give each block its own constant cic_i. QLoRA uses B=64B = 64 for the weights.

The NormalFloat data type

Pretrained weights are roughly zero-centred and normally distributed, with some standard deviation σ\sigma. If each block is scaled so that its values fall into [−1,1][-1, 1], the values follow a known shape. The paper builds a 4-bit code book from the quantiles of the standard normal, using

qi=12(QX ⁣(i2k+1)+QX ⁣(i+12k+1)),q_i = \frac{1}{2}\left(Q_X\!\left(\frac{i}{2^k+1}\right) + Q_X\!\left(\frac{i+1}{2^k+1}\right)\right),

where QXQ_X is the quantile function of N(0,1)\mathcal{N}(0,1) (see the Gaussian distribution). Each code value then covers an equal share of the probability mass. The paper also forces an exact zero into the code book, so padding and zero-valued entries quantize without error. The authors call the result 4-bit NormalFloat (NF4) and argue it is information-theoretically optimal for normally distributed data. The optimality claim applies to the stated assumption. The empirical question, which the paper answers, is whether it beats the alternatives.

Double quantization

Each block of 64 weights needs one 32-bit constant, which costs 32/64=0.532/64 = 0.5 bits per parameter. QLoRA quantizes those constants too, with 8-bit floats in blocks of 256, plus one 32-bit constant per 256 of them:

864+3264⋅256≈0.127 bits per parameter,\frac{8}{64} + \frac{32}{64 \cdot 256} \approx 0.127 \text{ bits per parameter},

so the bookkeeping drops from 0.5 to about 0.127 bits per parameter, a saving of about 0.373 bits. The paper reports this as roughly 3 GB for a 65B model.

The QLoRA forward pass

For one linear layer, with stored 4-bit weights WNF4\mathbf{W}^{\text{NF4}}, constants c1,c2c_1, c_2, and adapters L1,L2\mathbf{L}_1, \mathbf{L}_2:

YBF16=XBF16 doubleDequant⁡(c1,c2,WNF4)+XBF16L1L2.\mathbf{Y}^{\text{BF16}} = \mathbf{X}^{\text{BF16}}\,\operatorname{doubleDequant}(c_1, c_2, \mathbf{W}^{\text{NF4}}) + \mathbf{X}^{\text{BF16}}\mathbf{L}_1\mathbf{L}_2.

The first term expands the frozen weights to BFloat16 for the multiply. The second term is the LoRA correction, where L1∈Rh×r\mathbf{L}_1 \in \mathbb{R}^{h \times r} and L2∈Rr×o\mathbf{L}_2 \in \mathbb{R}^{r \times o}. Gradients are computed only for L1\mathbf{L}_1 and L2\mathbf{L}_2. The weights need no gradient, but the backward pass still passes through the dequantised weights to reach the adapters.

Paged optimizers

Optimizer state for the adapters is allocated in NVIDIA unified memory. When the GPU runs short during a long-sequence mini-batch, the state is paged to CPU RAM and brought back when the optimizer step needs it. The paper says this avoids the out-of-memory spikes that gradient checkpointing causes on long sequences, and reports that with batch size 16 on a 65B model it matched the speed of regular optimizers.

Worked examples

Example
Quantizing a small block by hand

Take one block of four weights, x=(0.8, −0.1, 0.05, −0.6)\mathbf{x} = (0.8,\ -0.1,\ 0.05,\ -0.6), and quantize to the signed 4-bit integer range [−7,7][-7, 7] with absmax scaling.

  1. Find the absmax: max⁡∣xi∣=0.8\max |x_i| = 0.8.
  2. Compute the constant: c=7/0.8=8.75c = 7 / 0.8 = 8.75.
  3. Scale and round each value:
    • 0.8⋅8.75=7.00.8 \cdot 8.75 = 7.0, rounds to 77.
    • −0.1⋅8.75=−0.875-0.1 \cdot 8.75 = -0.875, rounds to −1-1.
    • 0.05⋅8.75=0.43750.05 \cdot 8.75 = 0.4375, rounds to 00.
    • −0.6⋅8.75=−5.25-0.6 \cdot 8.75 = -5.25, rounds to −5-5.
  4. Dequantize by dividing by cc: (0.8, −0.1143, 0, −0.5714)(0.8,\ -0.1143,\ 0,\ -0.5714).
  5. Absolute errors: (0, 0.0143, 0.05, 0.0286)(0,\ 0.0143,\ 0.05,\ 0.0286).

Interpretation: the small value 0.050.05 is erased entirely, because it is less than half a step away from zero at this scale. A smaller block would give the outlier 0.80.8 less influence over its neighbours. This is why QLoRA uses blocks of 64 rather than one scale for the whole tensor.

Example
Memory for a 65B model

Count only the stored weights, in bytes per parameter, for P=65×109P = 65 \times 10^9 parameters.

  1. 16-bit weights: P⋅2 bytes=130 GBP \cdot 2 \text{ bytes} = 130 \text{ GB}.
  2. 4-bit weights: P⋅0.5 bytes=32.5 GBP \cdot 0.5 \text{ bytes} = 32.5 \text{ GB}.
  3. Quantization constants with double quantization: P⋅0.127 bits=P⋅0.0159 bytes≈1.0 GBP \cdot 0.127 \text{ bits} = P \cdot 0.0159 \text{ bytes} \approx 1.0 \text{ GB}.
  4. Total frozen-weight storage: 32.5+1.0≈33.5 GB32.5 + 1.0 \approx 33.5 \text{ GB}.
  5. Adapter, optimizer, and activation memory must fit in the remaining room on a 48 GB card, which is the paper's claim.

Interpretation: the weights alone drop from about 130 GB to about 33.5 GB. The paper's headline figure is that full 16-bit fine-tuning of a 65B model needs more than 780 GB once optimizer state and gradients are counted, and QLoRA gets this under 48 GB. The paper also points out that most training memory comes from activation gradients, not from the adapters, so the 4-bit weights are only part of the story.

Example
A LoRA adapter's size

Take one attention projection of size h=o=4096h = o = 4096 and LoRA rank r=8r = 8.

  1. Full matrix parameters: h⋅o=4096⋅4096=16 777 216h \cdot o = 4096 \cdot 4096 = 16\,777\,216.
  2. Adapter parameters: h⋅r+r⋅o=4096⋅8+8⋅4096=65 536h \cdot r + r \cdot o = 4096 \cdot 8 + 8 \cdot 4096 = 65\,536.
  3. Fraction trainable: 65 536/16 777 216≈0.003965\,536 / 16\,777\,216 \approx 0.0039, or 0.39%.

Interpretation: each adapter trains about 0.4% of the parameters of the matrix it augments. The paper finds that the total number of adapters matters more for matching full fine-tuning than the rank rr.

Tradeoffs and failure modes

SituationWhat goes wrongBetter choice
Model fits comfortably in 16-bitQuantization adds error and slows the forward pass for no memory gainStandard 16-bit [[low-rank-adaptation
Adapters only on the query and value projectionsThe paper finds this does not match full 16-bit fine-tuning on large modelsAdapters on all linear layers of each block
FP4 instead of NF4About one MMLU point behind 16-bit in the paper's experimentsNF4 with double quantization
Long sequences on a small GPUOptimizer memory spikes cause out-of-memory crashesPaged optimizers, as in the paper
Inference on the 4-bit modelDequantisation adds latency per layerMerge adapters and serve at a precision the hardware runs fast
Evaluating only on a single benchmarkBenchmark gaps can hide losses that appear in chat qualityEvaluate on several tasks, including human or model-judged chat

Two cautions from the paper itself. First, its result is that 4-bit QLoRA matches 16-bit on the benchmarks studied. It does not show where the precision-versus-size tradeoff ends, which the authors leave open. Second, the paper's chatbot evaluations use GPT-4 as a judge, and it notes that model-based judging has uncertainties and sometimes disagrees with human raters.

History

Dettmers, Pagnoni, Holtzman and Zettlemoyer published QLoRA in May 2023 (arXiv 2305.14314). It built on LoRA (Hu et al., 2021) and on Dettmers and Zettlemoyer's earlier work on low-bit quantization for inference. The paper's main contributions were NF4, double quantization and paged optimizers, and the claim that 4-bit fine-tuning reaches 16-bit quality. It also released the Guanaco family of chat models, trained with QLoRA on the OASST1 dataset. The paper reports that the smallest Guanaco, at 7B parameters, needs about 5 GB at deployment.

Its practical significance, as the paper frames it, is that fine-tuning the largest open models becomes possible on a single GPU. See the paper node for the full reading guide.

Check yourself

QuestionIn one sentence, what is stored in 4 bits in QLoRA, and what is trained in 16 bits?Show answer

The frozen pretrained weights are stored in 4-bit NormalFloat. The LoRA adapter matrices are trained in 16-bit BFloat. The forward pass expands the 4-bit weights to 16-bit for each multiplication.

QuestionA block of weights has absmax 2.0. Using signed 4-bit integers in [−7,7][-7, 7], what is the scale cc, and what integer does the value 0.30.3 become?Show answer

c=7/2.0=3.5c = 7 / 2.0 = 3.5. Then 0.3⋅3.5=1.050.3 \cdot 3.5 = 1.05, which rounds to 11. The value dequantises to 1/3.5≈0.2861 / 3.5 \approx 0.286, an error of about 0.0140.014.

QuestionWhy does double quantization save memory, and by how much per parameter for blocks of 64 with 8-bit constants in blocks of 256?Show answer

Without it, each block of 64 weights carries one 32-bit constant, which is 32/64=0.532/64 = 0.5 bits per parameter. With double quantization the constants are themselves quantized to 8 bits with a second-level constant per 256 of them, giving about 0.1270.127 bits per parameter. The saving is about 0.3730.373 bits per parameter.

QuestionA model has 7 billion parameters. How many gigabytes do the 4-bit weights take, ignoring constants? Compare with 16-bit.Show answer

At 0.5 bytes per parameter, 7×109⋅0.5=3.5×1097 \times 10^9 \cdot 0.5 = 3.5 \times 10^9 bytes, about 3.5 GB. At 2 bytes per parameter, the 16-bit weights take about 14 GB. The ratio is four to one.

QuestionApplied: a team fine-tunes a 13B model with LoRA on only the query and value projections and finds it underperforms full fine-tuning. Using the paper's findings, what would you change first, and why might it help?Show answer

Add LoRA adapters to all linear layers of each transformer block, not only the query and value projections. The paper finds that the number of adapted layers is the most critical LoRA hyperparameter for matching full fine-tuning, and that the rank rr matters less. The change costs little memory, because adapters are small, so it is a cheap experiment before trying anything heavier.

Sources