AI State of the Art
SOTA/Efficient Fine-tuning (PEFT)/25 min
Section 103

QLoRA: 4-bit Fine-tuning

Listen as a podcast →

The Flaw in LoRA That QLoRA Fixes

LoRA (Low-Rank Adaptation) removes the cost of gradients and optimizer states, but it leaves the heaviest item untouched: the frozen model still has to be loaded whole into the graphics card's memory.

Do the arithmetic for a 65-billion-parameter model. In 16 bits, i.e. 2 bytes per parameter, its weights take 2×65×109=1302 \times 65 \times 10^9 = 130 GB. The most common datacentre cards cap at 80 GB: even with LoRA, you need two.

QLoRA's idea (Quantized LoRA): keep the frozen model in a heavily compressed format, 4 bits per parameter, i.e. half a byte, four times less, while holding the LoRA adapters at 16 bits so learning quality is not hurt.

Here is the split, worth keeping in mind for the rest of the page:

FormatStatus
Base modelNF4, 0.5 bytes per parameterfrozen, never updated
LoRA adapters (matrices A and B)BF16, 2 bytes per parameterlearned
Activations, gradients passing through the frozen layersBF16recomputed on every pass, nothing is kept

So the frozen weights are compressed; what you learn is not. And gradients do pass through the quantized layers (they simply do not stop there) on their way to updating the LoRA matrices only.

QLoRA: Efficient Finetuning of Quantized LLMs (Dettmers et al., 2023)

The Three Technical Innovations of QLoRA

1. NormalFloat on 4 bits (NF4)

NF4 is a 4-bit number format designed for neural network weights. Four bits means only 24=162^4 = 16 possible values: the whole art lies in picking which sixteen.

The observation behind it: pre-trained weights roughly follow a normal distribution, a bell curve centred on zero. Most weights sit near zero; extreme values are rare.

Quantiles Rather Than Even Ticks

In ordinary 4-bit quantization (INT4), the 16 levels are spread evenly across the value range, like the marks on a ruler. That wastes them: many land in the tails of the distribution, where there are almost no weights at all.

NF4 puts the 16 levels at the quantiles of the normal distribution: each level covers an equal share of the distribution, so the ticks bunch up near zero and spread out towards the ends. The paper calls this format "information theoretically optimal" for normally distributed weights.

The gain costs nothing in memory: NF4 occupies exactly what INT4 or FP4 would, half a byte per weight. Only the placement of the 16 ticks changes.

Three-level diagram. At the top, a blue bell curve representing the weight distribution, with about a dozen blue dots sitting on the horizontal axis, most of them clustered near the centre. In the middle, an axis labelled float4 whose tick marks are evenly spaced from -1 to 1. At the bottom, an axis labelled Nfloat4 whose tick marks are tightly packed near zero and increasingly spread out towards the ends. Arrows connect each weight to the nearest tick on each of the two axes.
Compare the tick spacing on the two lower axes. With float4, the 16 levels are spread evenly: many land in the tails of the distribution, where there are almost no weights at all. With NF4, the levels bunch up around zero, where the weights actually live, the same 4-bit budget is spent where it does some good.Source : Deep Learning for the GPU Poor, lecture notes by Harry Coppock

2. Double Quantization

Compressing to 4 bits is only possible block by block, with one scaling constant per block: a factor saying what to multiply the 16 ticks by to recover the real magnitude of that block's weights. Without it, there is no way back to the true values.

Work out the extra cost. A block holds 64 weights and its constant is stored in FP32, i.e. 4 bytes, i.e. 32 bits. Spread over the block's 64 weights:

32 bits64 weights=0.5 bits per weight\frac{32 \text{ bits}}{64 \text{ weights}} = 0.5 \text{ bits per weight}

Half a bit added to 4 bits is a 12.5% overhead. Far from negligible.

QLoRA's trick: quantize the constants themselves. They are grouped by 256 and stored on 8 bits instead of 32, keeping one second-level constant per group of 256. The count becomes:

864+3264×256=0.125+0.002=0.127 bits per weight\frac{8}{64} + \frac{32}{64 \times 256} = 0.125 + 0.002 = 0.127 \text{ bits per weight}

About 3.2% overhead instead of 12.5%. These are the paper's own figures. On a 65-billion-parameter model, the 0.373 bits per weight saved amount to 0.373×65×109/8≈30.373 \times 65 \times 10^9 / 8 \approx 3 GB.

Three-stage diagram. On the left, a large blue square labelled W and Weights, in FP32. An arrow labelled Quant leads to a column of small blue blocks g1, g2, g3 through gn, annotated block size 64 and INT4, alongside a column of constants c1 to cn annotated one constant per block and FP32. A second green arrow labelled Quant leads to a new column of constants c prime, annotated block size 256 and FP8, itself alongside a final column of second-level constants c double prime in FP32.
Quantization is applied twice. First pass: the weights are cut into blocks of 64 and compressed to 4 bits, each block leaving behind one FP32 constant. Second pass, the green arrow: those constants are themselves grouped by 256 and compressed to FP8, leaving only a tiny residue of second-level constants.Source : Di's Blog, Understanding QLoRA

3. Paged Optimizers

What this targets is not average memory, QLoRA's optimizer states are tiny, since only the LoRA matrices have any. It is the spikes: at certain moments in training, notably when a long sequence comes through, memory demand jumps and the card runs out. One spike is enough to kill a twenty-four-hour run.

So QLoRA uses paging between the graphics card and main memory: when space runs short, optimizer states are moved out to the computer's RAM and brought back when needed again. The paper's abstract puts it plainly: paged optimizers "to manage memory spikes".

Transparent Memory Management

The technique rests on unified memory in CUDA (Compute Unified Device Architecture, NVIDIA's computing platform), which moves data page by page between card and main memory automatically, much as an operating system pushes to disk the memory pages it does not need right now. Nothing to write in your code.

Concrete Impact on Memory

Take the 65-billion-parameter model again and count, method by method, in bytes per parameter.

MethodBreakdownTotalHardware needed
Full fine-tuning, 16-bit + AdamWweights 2 + gradients 2 + optimizer 8 = 12 bytes12×65×109=78012 \times 65 \times 10^9 = 780 GBa cluster of cards
LoRA, frozen model in 16 bitsweights 2 bytes, the rest negligible130 GB + adapterstwo 80 GB cards
QLoRA, frozen model in NF4weights 0.5 bytes33 GB of weights, 41 GB measured in total by the paperone 48 GB card
QLoRA on a 7-billion-parameter modelweights 0.5 bytes3.5 GB of weights, 5 GB measured by the paperone consumer card

The 780 GB and the 41 GB are the paper's own numbers; both fall out of the bytes-per-parameter count.

The point not to miss: LoRA alone does not reduce the memory needed to load the model. It removes the gradients and the optimizer states, which takes 780 GB down to 130, but the frozen model's 130 GB stay. It is 4-bit quantization that divides those by four.

Fine-Tuning Quality: The Surprise

What the Paper Actually Claims

The paper argues that QLoRA in NF4 matches the quality of 16-bit fine-tuning. We put no percentage on the gap: the figures in circulation do not correspond to any single measurement in the paper, which compares across several datasets and several model sizes.

To back the claim, the authors produced Guanaco, a family of models fine-tuned with QLoRA on the OASST1 dataset (Open Assistant version 1, a corpus of conversations annotated by volunteers).

Guanaco 65B reaches 99.3% of ChatGPT's level on the Vicuna benchmark, after twenty-four hours of fine-tuning on a single graphics card. That is the figure from the paper's abstract, and it is what convinced the community.

One qualification matters for reading that number: the evaluation is automatic. Both models' answers go to a judge model, GPT-4, which picks the better one. The paper also runs a human evaluation, and explicitly defends GPT-4 judging as a cheap approximation of it, an approximation, not an equivalent.

Table 6 from the QLoRA paper. For each model the table gives the parameter count, the weight precision, the memory used and the Vicuna benchmark score as a percentage of the ChatGPT score. GPT-4 scores 114.5 percent and Bard 94.8 percent. Guanaco 65B in 4 bits takes 41 GB and scores 99.3 percent, against 70.7 percent for Alpaca and 48.4 percent for FLAN v2 at the same size and precision. Guanaco 33B in 4 bits takes 21 GB and scores 97.8 percent, ahead of Open Assistant 33B in 16 bits which takes 66 GB for 94.9 percent. Guanaco 13B scores 90.4 percent for 10 GB and Guanaco 7B scores 87.0 percent for 5 GB.
The table that convinced the community. The Guanaco 65B row shows 99.3% of the ChatGPT score for 41 GB of memory. Look above all at the 33B comparison: Guanaco in 4 bits fits in 21 GB and beats Open Assistant in 16 bits, which needs 66. The memory column is the paper's central argument.Source : QLoRA paper (Dettmers et al., 2023), table 6, via Andrey Lukyanenko

Practical Implementation

QLoRA is perfectly integrated into the Hugging Face ecosystem via bitsandbytes and PEFT:

from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model

# 4-bit quantization configuration
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_use_double_quant=True,
)

# Load the quantized model
model = AutoModelForCausalLM.from_pretrained(
    "mistralai/Mistral-7B-v0.1",
    quantization_config=bnb_config,
    device_map="auto",
)

# Apply LoRA
lora_config = LoraConfig(r=16, lora_alpha=32, target_modules="all-linear")
model = get_peft_model(model, lora_config)

Four settings, one per innovation: load_in_4bit turns on compression, nf4 picks the NormalFloat format over an evenly-spaced one, bfloat16 fixes the format the arithmetic is done in (weights are decompressed on the fly for each multiplication), and double_quant enables double quantization. Those four lines divide the base model's memory by four, not total memory, which also holds the activations.

Practical Tips

The Compute Format

Weights are stored in 4 bits, but every multiplication happens in a wider format, after decompression on the fly. That compute format is what you choose here. Both candidates occupy 2 bytes, but they spend their bits differently:

  • BF16 (brain floating point on 16 bits): fewer significant digits, but a range of representable values as wide as FP32's. This is the recommended choice, because a tiny or enormous gradient never collapses to zero or blows up to infinity. Needs an Ampere-generation card or newer.
  • FP16: more significant digits, narrower range, so more prone to overflow. Reserve it for older cards with no BF16 support.

The Adapter's Rank

With QLoRA you can afford a higher rank than with plain LoRA. The reason is purely arithmetic: the adapter weighs a few dozen megabytes where the frozen model weighs dozens of gigabytes. Going from r = 16 to r = 64 quadruples an already negligible item. Take the room.

What 4-bit Compression Costs

Rounding a weight to one of 16 values loses information, and the loss is irreversible: the base model will never recover its exact values. The adapter can learn to compensate for part of it during fine-tuning, but not to undo it.

For tasks where numerical precision matters a lot, 8-bit or 16-bit fine-tuning may do better. Measure on your own task before concluding.

Impact on the Ecosystem

QLoRA was the trigger for the democratization of fine-tuning. Before it, adapting a multi-billion-parameter model demanded professional hardware. After it, one consumer card handles a 7-billion-parameter model, and a single 48 GB card handles a 65-billion one.

The consequence: thousands of practitioners with no access to a cluster started fine-tuning models. QLoRA became the default entry point.

The next step is DoRA, which attacks quality rather than memory: LoRA's correction blends a change in the weights' magnitude with a change in their direction, and DoRA separates the two.

Check your understanding0 / 5

1. Which specific weakness of LoRA does QLoRA's quantization fix?

2. Why does NF4 place its 16 levels at the quantiles of the normal distribution rather than at regular intervals?

3. In QLoRA, what exactly gets compressed to 4 bits?

4. What is QLoRA's double quantization?

5. 4-bit compression loses information about the original weights. Can the adapter get it back?