QLoRA: 4-Bit Quantization plus LoRA
LoRA shrinks the trained part of a model to almost nothing, but the frozen base still has to sit in GPU memory: 13.5 GB for a 7-billion-parameter model in 16-bit. QLoRA (Dettmers et al., 2023) stores that frozen base in 4 bits per weight, about 3.5 GB, and trains LoRA adapters in 16-bit on top. The base is dequantized on the fly, block by block, for each forward and backward pass; gradients flow through it to the adapters but never change it. That is what made fine-tuning a 65-billion-parameter model possible on a single 48 GB GPU.
This lesson builds the quantization itself in NumPy: a 4-bit code, block-wise scaling, the NF4 data type and double quantization, and then LoRA on a 4-bit network. The real thing uses the bitsandbytes library, which needs a CUDA GPU, so its configuration is shown at the end as code that is not run here.
Quantization in one formula
To store a block of weights in bits, pick a code book of values in , a scale per block, and keep only the index of the nearest code value:
Storage is bits per weight for , plus the scale (32 bits) shared by the block. The error depends on two choices:
- The block size. One scale for a whole matrix is ruined by a single outlier: becomes large and every ordinary weight lands on the few code values near 0. Blocks of 64 weights keep an outlier's damage local. Their scales cost extra bits per weight.
- The code book. A uniform code (
int4: divided by 7) spaces its values evenly. Trained weights are roughly normally distributed: many near zero, few in the tails. A code with more values where the weights are dense wastes fewer of its 16 levels.
NF4: a code book for normal weights
NormalFloat 4 (NF4) puts its 16 values at quantiles of the standard normal distribution, so that each value is used by about the same share of normally distributed weights. It is built asymmetrically so that 0 is represented exactly (zero weights and padding stay zero): 8 positive values from the quantiles between 0.5 and 0.9677 of , 7 negative ones from the same construction with 8 points, and 0, all divided by the largest so they span .
import numpy as np
from scipy.stats import norm
offset = 0.9677083 # the outermost quantile used by QLoRA
positive = norm.ppf(np.linspace(offset, 0.5, 9)[:-1]) # 8 values
negative = -norm.ppf(np.linspace(offset, 0.5, 8)[:-1]) # 7 values
nf4 = np.sort(np.concatenate([positive, [0.0], negative]))
nf4 = nf4 / nf4.max()
int4 = np.arange(-7, 8) / 7 # uniform symmetric 4-bit code: 15 values
print("NF4 :", np.round(nf4, 4))
print("int4:", np.round(int4, 4))
w = np.random.default_rng(0).normal(size=(2000, 64)) # normally distributed "weights", blocks of 64
w = w / np.abs(w).max(1, keepdims=True) # absmax scale per block, as QLoRA does
for name, code in [("int4", int4), ("NF4", nf4)]:
idx = np.abs(w.ravel()[:, None] - code[None, :]).argmin(1) # nearest code value
used = np.bincount(idx, minlength=len(code)) / w.size
entropy = -(used[used > 0] * np.log2(used[used > 0])).sum()
rmse = np.sqrt(np.mean((w.ravel() - code[idx]) ** 2))
print(f"{name:4s} busiest code value holds {used.max():.1%} of the weights | information used {entropy:.2f} of 4 bits | RMS error {rmse:.4f}")NF4 : [-1. -0.6962 -0.5251 -0.3949 -0.2844 -0.1848 -0.091 0. 0.0796
0.1609 0.2461 0.3379 0.4407 0.5626 0.723 1. ]
int4: [-1. -0.8571 -0.7143 -0.5714 -0.4286 -0.2857 -0.1429 0. 0.1429
0.2857 0.4286 0.5714 0.7143 0.8571 1. ]
int4 busiest code value holds 14.7% of the weights | information used 3.50 of 4 bits | RMS error 0.0410
NF4 busiest code value holds 9.3% of the weights | information used 3.88 of 4 bits | RMS error 0.0359
The NF4 values are those of the QLoRA paper and of bitsandbytes (to within 0.0001 after rounding): closely spaced near 0 (steps of about 0.08 to 0.09) and wide in the tails (from 0.723 to 1). The uniform code has 15 values, one less, because a symmetric code with 0 must have an odd count; NF4's asymmetric construction uses all 16.
On normal weights scaled per block of 64, the uniform code's busiest value (the 0 in the middle) takes 14.7 % of all weights while its outer values are almost empty; it uses 3.50 bits of information out of the 4 it stores. NF4 spreads the weights more evenly (busiest value 9.3 %, 3.88 bits) and its RMS error is smaller, 0.0359 against 0.0410 (in units of the block's largest weight). It is not exactly uniform, because the absmax scale of a block of 64 is set by its largest value, which varies from block to block.
Block-wise quantization and its cost
Now a real-sized weight matrix: 256 x 256 values from , the scale of a trained layer, with a few large outliers (0.1 % of the weights at about ten times the usual size, which trained transformers do have). Five schemes, each with its storage in bits per weight and its error relative to the weights' own size, :
import numpy as np
from scipy.stats import norm
positive = norm.ppf(np.linspace(0.9677083, 0.5, 9)[:-1])
negative = -norm.ppf(np.linspace(0.9677083, 0.5, 8)[:-1])
nf4 = np.sort(np.concatenate([positive, [0.0], negative])); nf4 /= nf4.max()
int4 = np.arange(-7, 8) / 7
int8 = np.arange(-127, 128) / 127
rng = np.random.default_rng(0)
W = rng.normal(0, 0.05, (256, 256))
outliers = rng.choice(W.size, W.size // 1000, replace=False)
W.flat[outliers] = rng.choice([-1, 1], len(outliers)) * 0.5 # 0.1 % large weights
def quantize(W, code, block):
"""Absmax scale per block, nearest code value; returns codes, scales and the dequantized matrix."""
blocks = W.reshape(-1, block)
scale = np.abs(blocks).max(1, keepdims=True)
mid = (code[1:] + code[:-1]) / 2 # nearest code value = count of midpoints below
k = np.searchsorted(mid, blocks / scale) # 4- or 8-bit indices
return k, scale, (code[k] * scale).reshape(W.shape)
def report(name, What, bits):
print(f"{name:28s} {bits:6.3f} bits/weight relative error {np.linalg.norm(W - What) / np.linalg.norm(W):.4f}")
report("float16 (reference)", W.astype(np.float16).astype(float), 16)
report("int8, block 64", quantize(W, int8, 64)[2], 8 + 32 / 64)
report("int4, one scale per matrix", quantize(W, int4, W.size)[2], 4 + 32 / W.size)
report("int4, block 64", quantize(W, int4, 64)[2], 4 + 32 / 64)
k, scale, W_nf4 = quantize(W, nf4, 64)
report("NF4, block 64", W_nf4, 4 + 32 / 64)
# double quantization: store the 1024 block scales themselves in 8 bits, in groups of 256
s = scale.ravel()
mean = s.mean()
_, _, s_hat = quantize((s - mean).reshape(-1, 256), int8, 256) # centred, then absmax int8
W_dq = (nf4[k] * (s_hat.reshape(-1, 1) + mean)).reshape(W.shape)
report("NF4, block 64, double quant", W_dq, 4 + 8 / 64 + 32 / (64 * 256))
print(f"memory for this matrix: float16 {W.size * 2 / 1024:.0f} KiB, NF4 + double quant {W.size * 4.127 / 8 / 1024:.1f} KiB")float16 (reference) 16.000 bits/weight relative error 0.0002
int8, block 64 8.500 bits/weight relative error 0.0077
int4, one scale per matrix 4.000 bits/weight relative error 0.3942
int4, block 64 4.500 bits/weight relative error 0.1403
NF4, block 64 4.500 bits/weight relative error 0.1036
NF4, block 64, double quant 4.127 bits/weight relative error 0.1038
memory for this matrix: float16 128 KiB, NF4 + double quant 33.0 KiB
Read the rows top to bottom:
- float16 keeps the weights almost exactly (relative error 0.0002) at 16 bits.
- int8 with blocks is nearly lossless too (0.0077) at 8.5 bits: the standard for 8-bit inference.
- int4 with one scale for the matrix is useless: the outliers at 0.5 set the scale, the ordinary weights (standard deviation 0.05) fall between the code values and , and the error is 0.3942.
- int4 with blocks of 64 cuts that to 0.1403 for half a bit more. The outliers now only spoil their own blocks.
- NF4 with blocks of 64 cuts it again to 0.1036, with the same storage: the better code book alone removes a quarter of the error.
- Double quantization stores the 1,024 block scales in 8 bits instead of 32 (centred on their mean, absmax-scaled in groups of 256). The error barely changes (0.1038) and the storage drops from 4.5 to 4.127 bits per weight.
The matrix shrinks from 128 KiB in float16 to 33.0 KiB, a factor of 3.9. An error of 10 % per weight sounds large, but it is noise in many weights that average out in each dot product, as the next example shows.
QLoRA from scratch: LoRA on a 4-bit network
The digit network of the LoRA lesson: a 64-unit MLP pretrained on one half of the digits, adapted to the other half shifted by one pixel, with 300 labelled images and 599 for testing (3 draws). Its first-layer weight matrix is stored in NF4 with blocks of 64 and frozen; a rank-8 LoRA update and a new head train on top, in full precision. Every forward pass uses the dequantized weights , exactly as QLoRA's kernels do:
import numpy as np
from scipy.stats import norm
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
positive = norm.ppf(np.linspace(0.9677083, 0.5, 9)[:-1])
negative = -norm.ppf(np.linspace(0.9677083, 0.5, 8)[:-1])
nf4 = np.sort(np.concatenate([positive, [0.0], negative])); nf4 /= nf4.max()
def nf4_roundtrip(W, block=64):
blocks = W.reshape(-1, block)
scale = np.abs(blocks).max(1, keepdims=True)
k = np.searchsorted((nf4[1:] + nf4[:-1]) / 2, blocks / scale) # index of the nearest NF4 value
return (nf4[k] * scale).reshape(W.shape)
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_src, X_tgt, y_src, y_tgt = train_test_split(X, y, test_size=0.5, random_state=0, stratify=y)
source = MLPClassifier(hidden_layer_sizes=(64,), max_iter=500, random_state=0).fit(X_src, y_src)
W_fp, b0 = source.coefs_[0], source.intercepts_[0]
W_q = nf4_roundtrip(W_fp)
print(f"first layer: relative quantization error {np.linalg.norm(W_fp - W_q) / np.linalg.norm(W_fp):.4f}")
for name, W in [("float", W_fp), ("NF4", W_q)]: # does the 4-bit model still work on its own task?
h = np.maximum(0, X_tgt @ W + b0)
z = h @ source.coefs_[1] + source.intercepts_[1]
print(f"pretrained model with {name:5s} first layer, unshifted digits: {(z.argmax(1) == y_tgt).mean():.3f}")
X_new = np.roll(X_tgt.reshape(-1, 8, 8), 1, axis=2).reshape(-1, 64)
def lora_train(W0, Xl, yl, rng, r=8, alpha=8, lr=0.003, steps=300):
s = alpha / r
P = {"V": rng.normal(0, 0.1, (64, 10)), "c": np.zeros(10),
"A": rng.normal(0, 1 / np.sqrt(64), (64, r)), "B": np.zeros((r, 64))}
m = {k: 0 for k in P}; v = {k: 0 for k in P}
for t in range(1, steps + 1):
pre = Xl @ (W0 + s * P["A"] @ P["B"]) + b0 # W0 is the frozen (dequantized) base
h = np.maximum(0, pre); z = h @ P["V"] + P["c"]
p = np.exp(z - z.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
g = p.copy(); g[np.arange(len(yl)), yl] -= 1; g /= len(yl)
GW = Xl.T @ ((g @ P["V"].T) * (pre > 0)) # flows through W0, never applied to it
G = {"V": h.T @ g, "c": g.sum(0), "A": s * GW @ P["B"].T, "B": s * P["A"].T @ GW}
for k in P:
m[k] = 0.9 * m[k] + 0.1 * G[k]; v[k] = 0.999 * v[k] + 0.001 * G[k] ** 2
P[k] = P[k] - lr * (m[k] / (1 - 0.9 ** t)) / (np.sqrt(v[k] / (1 - 0.999 ** t)) + 1e-8)
return lambda A: (np.maximum(0, A @ (W0 + s * P["A"] @ P["B"]) + b0) @ P["V"] + P["c"]).argmax(1)
for name, W in [("LoRA on the float base", W_fp), ("QLoRA: LoRA on the NF4 base", W_q)]:
accs = []
for seed in range(3):
rng = np.random.default_rng(seed)
lab = np.concatenate([rng.choice(np.where(y_tgt == c)[0], 30, replace=False) for c in range(10)])
test = np.setdiff1d(np.arange(len(y_tgt)), lab)
predict = lora_train(W, X_new[lab], y_tgt[lab], rng)
accs.append((predict(X_new[test]) == y_tgt[test]).mean())
print(f"{name:28s} shifted digits, test accuracy {np.mean(accs):.3f} (599 images, 3 draws)")first layer: relative quantization error 0.0903
pretrained model with float first layer, unshifted digits: 0.971
pretrained model with NF4 first layer, unshifted digits: 0.967
LoRA on the float base shifted digits, test accuracy 0.935 (599 images, 3 draws)
QLoRA: LoRA on the NF4 base shifted digits, test accuracy 0.937 (599 images, 3 draws)
Rounding the first layer to NF4 changes its weights by 9 % of their size, yet the pretrained model still reads the unshifted digits almost as before: 0.967 against 0.971 in float, 3 or 4 of the 899 images. LoRA trained on top of the 4-bit base reaches 0.937 on the shifted digits, the same as on the float base (0.935, the same numbers as in the LoRA lesson); the difference is one image. This is QLoRA's central finding at a tiny scale: the adapter learns around the quantization error, and fine-tuning quality matches 16-bit LoRA while the base takes a quarter of the memory.
QLoRA in practice (needs a CUDA GPU, not run here)
With Transformers, bitsandbytes and PEFT the whole recipe is a configuration. The block below is the standard QLoRA setup; it is not run in this course (bitsandbytes' 4-bit kernels need an NVIDIA GPU, and this course runs everything on CPUs), so it has no output. "your-org/your-7b-model" stands for any causal LM checkpoint.
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
bnb = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4", # the code book built above
bnb_4bit_use_double_quant=True, # quantize the block scales too
bnb_4bit_compute_dtype=torch.bfloat16, # dequantize to bf16 for each matrix multiplication
)
model = AutoModelForCausalLM.from_pretrained("your-org/your-7b-model", quantization_config=bnb, device_map="auto")
model = prepare_model_for_kbit_training(model) # gradient checkpointing, norms in float32
model = get_peft_model(model, LoraConfig(task_type="CAUSAL_LM", r=16, lora_alpha=32, lora_dropout=0.05,
target_modules="all-linear"))
model.print_trainable_parameters()
# train as usual; optionally with optim="paged_adamw_8bit" in TrainingArgumentsThe pieces, mapped to this lesson: nf4 is the code book of the first example, block size 64 is the default, use_double_quant is the last row of the second example, and compute_dtype is the precision of during the matrix products. QLoRA adds paged optimizers, which move optimiser state to CPU memory when a long sequence causes a memory spike, instead of crashing.
Pitfalls
- Merging LoRA into the 4-bit base. must be quantized again to stay in 4 bits, which adds new rounding error. Merge into a 16-bit copy of the base, or keep the adapter separate.
- Quantizing with one scale per matrix. One outlier sets the scale for everything; use blocks (the second example's third row).
- Expecting a faster model. 4-bit storage saves memory; each matrix product still dequantizes and computes in 16-bit, so steps are often slower than 16-bit LoRA.
- Quantizing everything. Embeddings, the output layer and normalisation layers are usually kept in 16-bit; QLoRA quantizes the large linear layers.
- Evaluating only after fine-tuning. Measure the quantized base before training too (as in the third example), so that a quantization loss is not blamed on the adapter.
Practice
- How many bits per weight does NF4 with block size 128 and no double quantization use? With double quantization (8-bit scales in groups of 256)?
- Why is NF4 built with an exact 0?
- A 70-billion-parameter model: estimate the memory of its frozen weights in bf16, and in NF4 with double quantization.
Answers
- bits; with double quantization bits.
- Zero weights (and zero padding) must stay exactly zero after a round trip; a symmetric code with an even number of values has no 0 and would turn every 0 into a small nonzero number.
- bf16: bytes GB. NF4 with double quantization: GB.
Test yourself
In QLoRA, which parameters are stored in 4 bits?
- The LoRA matrices A and B
- The frozen pretrained weights of the large linear layers
- The optimiser state only
- The activations
Why does NF4 put its 16 values at quantiles of a normal distribution?
- Because it is faster on GPUs
- Trained weights are roughly normal, so quantile-spaced values are each used by a similar share of weights and waste fewer levels
- To make the code symmetric
- Because 4 bits can only store normal numbers
What does block-wise quantization (one scale per 64 weights) protect against?
- Underflow in the gradients
- A single outlier forcing a huge scale on the whole matrix and flattening all ordinary weights to a few code values
- Overfitting
- Loss of the LoRA adapter