QLoRA: Fine-Tuning a 65B Model on One 48 GB GPU by Quantizing the Base to 4 Bits
QLoRA (Dettmers et al., 2023) quantizes a frozen base model to 4-bit NormalFloat and trains LoRA adapters on top, so a 65B model fine-tunes on one 48 GB GPU. This breakdown explains NF4, double quantization and paged optimizers, rebuilds NF4 in code and tests 4-bit data types on Qwen2.5.
On this page
- Why This Paper Matters
- Background: What LoRA Saves and What It Does Not
- Method
- Block-wise quantization: one constant for each block of numbers
- NF4: place the bins at quantiles of the normal distribution
- Double quantization: quantize the constants too
- Paged optimizers: hand memory spikes to unified memory
- Putting it together in one linear layer
- Adapters belong on all linear layers
- Experiments and Findings
- 4-bit data types: NF4 beats FP4 and INT4
- A 4-bit base plus adapters matches 16 bits
- Guanaco and chat benchmarks
- Data quality beats quantity, and MMLU is almost orthogonal to chat quality
- Judges are not perfect
- Checking It in Code
- The script and its output
- NF4 values and the error of block-wise quantization
- Double quantization costs almost no accuracy
- Real models: the ordering matches the paper, but “weights are normal” deserves a discount
- How much the adapters win back
- The paper’s memory arithmetic and table arithmetic
- Limitations and Reading Notes
- What to Take Away from This Paper
- Further Reading
- FAQ
QLoRA, proposed by Dettmers et al. in May 2023, fine-tunes a pretrained model by freezing its weights and quantizing them to 4 bits, then training only the LoRA adapters attached to each linear layer. During the forward and backward passes the 4-bit weights are restored to BF16 layer by layer on the fly. Three design choices keep memory low: the 4-bit NormalFloat (NF4) data type, double quantization, and paged optimizers. Together they take fine-tuning a 65B model from more than 780 GB with ordinary 16-bit fine-tuning to under 48 GB, and the paper reports that quality on the tasks it tested stays level with 16-bit LoRA and full fine-tuning.
Why This Paper Matters
- It brings the entry price down to one GPU. The introduction says ordinary 16-bit fine-tuning of LLaMA 65B needs more than 780 GB of GPU memory and QLoRA brings the average requirement under 48 GB. A 33B model can be trained on one 24 GB consumer card in under 12 hours, and a 65B model on one 48 GB professional card in about 24 hours.
- It made large controlled studies affordable. The memory savings let the authors train more than 1,000 models (8 instruction datasets, two architecture families, LLaMA and T5, from 80M to 65B parameters), which is where findings such as “data quality matters more than quantity” and “MMLU and chat quality are nearly orthogonal” come from.
- Guanaco. Guanaco 65B, trained on a variant of OASST1, reaches 99.3% of ChatGPT on the Vicuna benchmark as scored by GPT-4, and the paper says it outperforms all previously released open models.
- The method moved into everyday tools. The authors released code and 4-bit CUDA kernels and integrated the method into Hugging Face transformers. Loading a model with
BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True)and attaching LoRA follows exactly this recipe. - It is also a lesson in evaluation. The paper points out that GPT-4 as a judge has an order bias and rates its own answers too highly, and that how good a benchmark is depends on how similar the fine-tuning data is to it. These findings are worth as much as the method, and they connect to this site’s LLM-as-a-Judge page.
Background: What LoRA Saves and What It Does Not
In full fine-tuning each parameter needs its weight (BF16, 2 bytes), its gradient (2 bytes) and two FP32 Adam moments (8 bytes), 12 bytes in all. 65B parameters times 12 bytes is about 783 GB, which agrees with the paper’s “more than 780 GB” (the accounting is mine; the paper does not break it down). LoRA freezes the base, so gradients and optimizer states shrink to the small adapter part, but the frozen weights still have to sit in memory: a 65B model in 16 bits is 130 GB by itself and cannot fit on a 48 GB card. QLoRA’s idea is straightforward: if the base is no longer updated, store it in 4 bits.
Section 2 of the paper makes an easily missed observation. For a 7B LLaMA at batch size 1, a typical LoRA configuration (about 0.2% of the base parameters) takes only 26 MB, while the gradients of the LoRA layer inputs take 567 MB, which gradient checkpointing reduces to 18 MB per sequence, and the 4-bit base takes 5,048 MB. The adapters themselves hardly use any memory; the base and the activations do. This is what makes adapters on all linear layers affordable: adding more of them barely changes the total.
Method
Block-wise quantization: one constant for each block of numbers
The simplest quantization scales a whole tensor by its maximum absolute value and rounds to integers. For FP32 to Int8:
Here is the quantization constant. The problem is that a single outlier inflates and squeezes most values into a few bins. The usual remedy is block-wise quantization: flatten the tensor, cut it into blocks of numbers, and give each block its own constant . Smaller blocks quantize more finely but need more constants. QLoRA uses for the weights.
NF4: place the bins at quantiles of the normal distribution
Pretrained weights are roughly zero-mean normal. If each of the 16 bins receives about the same number of weights, the 4 bits carry the most information, which is why the paper calls the data type “information-theoretically optimal”. It is built in three steps:
- take the quantiles of the standard normal to get values;
- normalize these values into ;
- when quantizing, divide a block of weights by its so that it falls into ; all blocks then share the same set of values.
The paper’s Eq. (4) takes the midpoint of two adjacent quantiles, with the quantile function of the standard normal:
A symmetric choice has no exact zero, but zeros such as padding should be representable without error, so the paper makes the data type asymmetric: quantiles for the negative half and for the positive half, and after merging and dropping the duplicate 0 there are exactly values. Appendix E lists the 16 values of NF4: −1, −0.696, −0.525, −0.395, −0.284, −0.185, −0.091, 0, 0.080, 0.161, 0.246, 0.338, 0.441, 0.563, 0.723, 1. The main text does not say where the outermost quantile sits, so the code below follows the 0.9677083 used in the bitsandbytes source and compares the result with Appendix E value by value.
Double quantization: quantize the constants too
With a block size of 64, every block carries one 32-bit constant, which adds bits per parameter, already sizable next to 4 bits. Double quantization treats the first-level constants as input and quantizes them again: subtract the mean to center them on zero, store them as 8-bit floats with a block size of 256, and keep the second-level FP32 constants . The average cost per parameter becomes
a saving of 0.373 bits per parameter, about 3 GB for a 65B model.
Paged optimizers: hand memory spikes to unified memory
Small batches of long sequences make memory jump briefly when gradient checkpointing runs, and the usual outcome is an out-of-memory error. Paged optimizers use NVIDIA unified memory: optimizer states are allocated in pageable memory, evicted automatically to CPU RAM when the GPU runs out, and brought back when the parameter update needs them. The paper gives no hard numbers for paging; it only says paging happens on long-sequence mini-batches, is rare, and that training a 65B model on a 48 GB card at batch size 16 runs at the same speed as with a regular optimizer.
Putting it together in one linear layer
A QLoRA linear layer has a storage data type (usually NF4) and a computation data type (BF16):
where first restores and then . The paper stores in NF4 and in FP8, with a block size of 64 for and 256 for . A parameter update needs only the adapter gradients, not gradients for the 4-bit weights; but computing the adapter gradients still means passing gradients back through to the input, so the backward pass also dequantizes to BF16.
Adapters belong on all linear layers
The paper finds that following the original LoRA recipe, with adapters only on the attention query and value projections, cannot reproduce full fine-tuning for larger base models. When fine-tuning LLaMA 7B on Alpaca, the most important LoRA hyperparameter is how many layers carry an adapter, and only adapters on all linear layers of the Transformer block match full fine-tuning; other hyperparameters such as the rank made no difference. They also found the default hyperparameters of full fine-tuning to be under-tuned, so they searched learning rates from 1e-6 to 5e-5 and batch sizes from 8 to 128 to make the baseline stronger. The final recipe is , , all linear layers, a constant learning rate, Adam with , gradient-norm clipping at 0.3, and LoRA dropout of 0.1 for 13B and below and 0.05 for 33B and 65B.
Experiments and Findings
4-bit data types: NF4 beats FP4 and INT4
The paper quantizes OPT, BLOOM, LLaMA and Pythia models from 125M to 13B and measures perplexity and zero-shot accuracy. Table 2 gives the mean perplexity on Pile Common Crawl (lower is better):
| Data type | Mean perplexity |
|---|---|
| Int4 | 34.34 |
| Float4 (E2M1) | 31.07 |
| Float4 (E3M0) | 29.48 |
| NF4 + double quantization | 27.41 |
The zero-shot accuracies in Figure 3 give the same ordering and show that double quantization brings only a “small gain” in accuracy; its main role is to let model sizes be fitted precisely into 24 GB and 48 GB of memory.
A 4-bit base plus adapters matches 16 bits
Table 3 compares 16-bit full fine-tuning, 16-bit LoRA and 4-bit QLoRA on GLUE (RoBERTa-large, accuracy) and Super-NaturalInstructions (T5, RougeL):
| Method | GLUE | 80M | 250M | 780M | 3B | 11B |
|---|---|---|---|---|---|---|
| BF16 full fine-tuning | 88.6 | 40.1 | 42.1 | 48.0 | 54.3 | 62.0 |
| BF16 full fine-tuning (replication) | 88.6 | 40.0 | 42.2 | 47.3 | 54.9 | - |
| LoRA BF16 | 88.8 | 40.5 | 42.6 | 47.1 | 55.4 | 60.7 |
| QLoRA Int8 | 88.8 | 40.4 | 42.9 | 45.4 | 56.5 | 60.7 |
| QLoRA FP4 | 88.6 | 40.3 | 42.4 | 47.5 | 55.6 | 60.9 |
| QLoRA NF4 + DQ | - | 40.4 | 42.7 | 47.7 | 55.3 | 60.9 |
The paper concludes that the performance lost to quantization can be fully recovered by adapter fine-tuning after quantization. Three things are worth noting when reading this table. First, the “BF16 full fine-tuning” and “replication” rows should be identical but differ by 0.7 at 780M and 0.6 at 3B, which is the paper’s own noise scale. Second, the QLoRA FP4 and NF4 + DQ entries are all within 0.6 of 16-bit LoRA, but the Int8 row is 1.7 below 16-bit LoRA at 780M and 1.1 above it at 3B, so individual cells can swing more. Third, at 11B all three QLoRA variants and 16-bit LoRA are 1.1 to 1.3 below full fine-tuning, and the text only says “replication” without discussing that cell.
Table 4 fine-tunes LLaMA 7B to 65B on Alpaca and FLAN v2 and measures 5-shot MMLU. The mean of the eight cells is 53.0 for BFloat16, 52.2 for Float4 and 53.1 for NF4 with double quantization. The paper concludes that NF4 with double quantization fully matches BFloat16 while FP4 “consistently lags by about one percentage point”. The code section below redoes this table as paired differences.
Guanaco and chat benchmarks
The chat evaluation uses two prompt sets: the Vicuna benchmark (80 prompts) and 953 user messages from the OASST1 validation set (the OA benchmark). GPT-4 scores the answers of the model under test and of ChatGPT on a 10-point scale, and the result is the model’s score as a percentage of ChatGPT’s. Because GPT-4 tends to favor the answer that appears first, the authors average over both orders. An excerpt of Table 6:
| Model | Precision | Memory | Relative to ChatGPT (95% CI) |
|---|---|---|---|
| GPT-4 | - | - | 114.5% (±2.6) |
| Guanaco 65B | 4-bit | 41 GB | 99.3% (±4.4) |
| Guanaco 33B | 4-bit | 21 GB | 97.8% (±4.4) |
| Vicuna 13B | 16-bit | 26 GB | 94.9% (±4.5) |
| Bard | - | - | 94.8% (±4.1) |
| Guanaco 7B | 4-bit | 5 GB | 87.0% (±5.4) |
| Alpaca 65B | 4-bit | 41 GB | 70.7% (±4.3) |
| FLAN v2 65B | 4-bit | 41 GB | 48.4% (±4.6) |
The confidence intervals are wide and many models overlap, so the authors prefer to convert pairwise comparisons by humans and GPT-4 into Elo ratings (Table 7). Take GPT-4 as the judge on the Vicuna benchmark: GPT-4 1348, Guanaco 65B 1022, Guanaco 33B 992, Vicuna 13B 974, ChatGPT 966, Guanaco 7B 879. With human judges, Guanaco 65B gets 1023 and ChatGPT 916; on the larger OA benchmark, ChatGPT’s 1015 is slightly above Guanaco 65B’s 1008. The paper explains that the Vicuna benchmark favors open models and the OA benchmark favors ChatGPT.
Data quality beats quantity, and MMLU is almost orthogonal to chat quality
Table 5 gives MMLU after fine-tuning on each dataset and Table 6 gives chat scores for the same models, and the two rankings are nearly opposite: FLAN v2 has the highest MMLU at 65B (63.9) but a chat score of only 48.4%, while Guanaco 65B, fine-tuned on OASST1, has an MMLU of 62.2 and a chat score of 99.3%. The paper concludes that how closely a dataset resembles the benchmark matters more than its size: 9,000 samples of OASST1 beat 450,000 samples subsampled from FLAN v2 on the chat benchmark. Table 11 in the appendix confirms this on MMLU: raising the data from 50,000 to 150,000 samples and the training from 1 to 3 epochs changes MMLU by only 0.0 to 0.5 points, while switching the dataset changes it by 1.5 to 8.0 points.
Judges are not perfect
The paper puts numbers on the evaluation itself. Agreement among human judges is Fleiss ; the sample-level agreement between GPT-4 and the human majority is only ; at the system level, the rankings of the two agree moderately, with Kendall and Spearman . GPT-4 also favors itself: the Elo that the GPT-4 judge gives GPT-4 is 1348 against 1176 from the human judges, which the authors estimate to be an additional 20% probability of winning. This is the basis for the paper’s statement that current chatbot benchmarks are not reliable.
Checking It in Code
Several claims in the paper can be recomputed on a laptop. The script below has three modes. data rebuilds NF4 and compares INT4, FP4, NF4 and double quantization, first on Gaussian data and then on the weights of two real models. lora trains adapters on a 4-bit base to see how much of the quantization loss they win back. paper recomputes the memory arithmetic, the Elo conversions and the arithmetic of two tables in the paper.
Environment and scope. Apple M2 Max (64 GB), Python 3.14.3, PyTorch 2.10.0 (MPS backend), transformers 5.3.0, SciPy 1.18.1. The models are Qwen2.5-0.5B and Qwen2.5-1.5B-Instruct (Apache-2.0). The evaluation set is the first 48 windows of 512 tokens from the WikiText-2 test split (wikitext-2-raw-v1), 24,576 tokens in all; the lora mode trains on the WikiText-2 training split. The dataset path in the script is the Hugging Face cache location on my machine, so change it for your environment, and run with HF_HUB_OFFLINE=1.
A few choices are mine, not the paper’s: INT4 uses 15 symmetric equally spaced values; FP4 is E2M1; the second level of double quantization uses FP8 (E4M3); and NF4’s outermost quantile is 0.9677083, taken from the bitsandbytes source. All quantization here is simulated: weights are stored as codes plus scaling constants and restored to FP32 for the matrix multiply, without the bitsandbytes CUDA kernels, so this measures numerical precision, not speed and not memory.
The script and its output
"""A small QLoRA study. Usage: python qlora.py data | lora | paper"""
import glob
import math
import sys
import time
from statistics import NormalDist
import pandas as pd
import torch
import torch.nn.functional as F
from scipy.stats import shapiro
from transformers import AutoModelForCausalLM, AutoTokenizer
dev = "mps"
Q = NormalDist().inv_cdf
PAPER_NF4 = [ # the 16 values given in the paper's Appendix E
-1.0, -0.6961928009986877, -0.5250730514526367, -0.39491748809814453,
-0.28444138169288635, -0.18477343022823334, -0.09105003625154495, 0.0,
0.07958029955625534, 0.16093020141124725, 0.24611230194568634,
0.33791524171829224, 0.44070982933044434, 0.5626170039176941,
0.7229568362236023, 1.0]
def nf4_levels(off=0.9677083):
# offset from bitsandbytes; 8 positive values, 7 negative, plus a 0
pos = [Q(off + (0.5 - off) * i / 8) for i in range(8)]
neg = [-Q(off + (0.5 - off) * i / 7) for i in range(7)]
v = sorted(neg + [0.0] + pos)
return [x / v[-1] for x in v]
def int4_levels():
return [k / 7 for k in range(-7, 8)] # 15 equally spaced values
def fp4_levels():
mag = [0, 0.5, 1, 1.5, 2, 3, 4, 6] # the non-negative values of E2M1
return sorted({s * m / 6 for m in mag for s in (-1, 1)})
LV = {"int4": torch.tensor(int4_levels()),
"fp4": torch.tensor(fp4_levels()),
"nf4": torch.tensor(nf4_levels())}
def quant(x, lv, bs):
"""Blocks of bs numbers: divide by the block absmax, take nearest code"""
b = x.reshape(-1, bs)
am = b.abs().amax(1, keepdim=True).clamp_min(1e-12)
mid = (lv[1:] + lv[:-1]) / 2
return torch.bucketize(b / am, mid), am.squeeze(1)
def dequant(code, am, lv):
return lv[code] * am[:, None]
def dq_consts(am, bs2=256):
"""Double quantization: subtract the mean, then FP8 (E4M3), blocks of 256"""
mu = am.mean()
c = am - mu
cp = torch.cat([c, c.new_zeros((-c.numel()) % bs2)]).reshape(-1, bs2)
s = cp.abs().amax(1, keepdim=True).clamp_min(1e-30) / 448
q = (cp / s).to(torch.float8_e4m3fn)
hat = (q.to(torch.float32) * s).reshape(-1)[: c.numel()] + mu
return hat, q, s
def entropy(code, n):
p = torch.bincount(code.reshape(-1), minlength=n).float()
p = p[p > 0] / p.sum()
return -(p * p.log2()).sum().item()
WIKI = glob.glob("/Users/wzy/.cache/huggingface/hub/datasets--Salesforce--"
"wikitext/snapshots/*/wikitext-2-raw-v1/")[0]
SEQ, NWIN = 512, 48 # eval: first 48 windows of 512 tokens
def wiki_ids(tok, split):
f = f"{WIKI}{split}-00000-of-00001.parquet"
text = "\n\n".join(pd.read_parquet(f)["text"])
return tok(text, return_tensors="pt").input_ids[0]
@torch.no_grad()
def window_nll(model, ids):
out = []
for i in range(0, len(ids), 4):
x = ids[i:i + 4].to(dev)
lg = model(x).logits[:, :-1].float()
nll = F.cross_entropy(lg.reshape(-1, lg.size(-1)),
x[:, 1:].reshape(-1), reduction="none")
out.append(nll.reshape(x.size(0), -1).mean(1).cpu())
return torch.cat(out) # mean NLL of each window
def paired(a, b):
d = a - b # paired difference on the same windows (nat)
return d.mean().item(), (d.std() / math.sqrt(len(d))).item()
def run_data():
nf = nf4_levels()
gap = max(abs(a - b) for a, b in zip(nf, PAPER_NF4))
print(f"NF4: {len(nf)} levels, max |diff| to Appendix E: {gap:.1e}")
print("levels:", " ".join(f"{v:.3f}" for v in nf))
# 1. Block quantization of Gaussian data (the idealized "weights")
x = torch.randn(1 << 20, generator=torch.Generator().manual_seed(0))
print("\nGaussian data, absmax blocks")
print("block type relMSE SQNR_dB H_bits")
for bs in (64, 256, 4096):
for k, lv in LV.items():
code, am = quant(x, lv, bs)
e = ((x - dequant(code, am, lv).reshape(-1)) ** 2).mean()
e = (e / (x ** 2).mean()).item()
print(f"{bs:<5} {k:<5} {e:.5f} {-10 * math.log10(e):7.2f}"
f" {entropy(code, len(lv)):7.3f}")
s = Q(0.9677083) # paper's ideal: normalize by sigma, not block absmax
for k, lv in LV.items():
code = torch.bucketize((x / s).clamp(-1, 1), (lv[1:] + lv[:-1]) / 2)
p = torch.bincount(code, minlength=len(lv)).float() / len(x)
print(f"sigma-scaled {k:<5} H_bits {entropy(code, len(lv)):.3f}"
f" p_min {p.min():.4f} p_max {p.max():.4f}")
# 2. Double quantization: storage cost and constants' reconstruction error
code, am = quant(x, LV["nf4"], 64)
hat, q8, s2 = dq_consts(am)
bits = (4 * code.numel() + 8 * q8.numel() + 32 * s2.numel()) / len(x)
rel = (hat - am).abs() / am
print(f"\nDQ storage {bits:.4f} bits/param; constants rel. error "
f"max {rel.max():.4f} mean {rel.mean():.5f}")
for lab, c2 in (("no DQ", am), ("DQ", hat)):
e = ((x - dequant(code, c2, LV["nf4"]).reshape(-1)) ** 2).mean()
print(f" NF4 B=64 {lab:<5} relMSE {(e / (x ** 2).mean()).item():.5f}")
# 3. Real models: weight error and WikiText-2 perplexity
for name in ("Qwen/Qwen2.5-0.5B", "Qwen/Qwen2.5-1.5B-Instruct"):
tok = AutoTokenizer.from_pretrained(name)
ids = wiki_ids(tok, "test")[: NWIN * SEQ].reshape(NWIN, SEQ)
model = AutoModelForCausalLM.from_pretrained(name, dtype=torch.float32)
model = model.to(dev).eval()
lins = [m for n, m in model.named_modules()
if isinstance(m, torch.nn.Linear) and ".layers." in n]
orig = [m.weight.detach().cpu().clone() for m in lins]
print(f"\n{name}: {len(lins)} matrices, "
f"{sum(w.numel() for w in orig) / 1e6:.0f}M weights, "
f"{ids.numel()} eval tokens")
ku = torch.cat([ # excess kurtosis of each row (one output neuron)
((w - w.mean(1, keepdim=True)) ** 4).mean(1)
/ w.var(1, unbiased=False) ** 2 - 3 for w in orig])
q = ku.quantile(torch.tensor([0.1, 0.5, 0.9]))
print(f"row excess kurtosis p10/p50/p90: "
f"{q[0]:.2f} / {q[1]:.2f} / {q[2]:.2f}")
if "0.5B" in name: # per-row Shapiro-Wilk, 100 rows per matrix
g = torch.Generator().manual_seed(0)
rej = tot = 0
for w in orig:
for i in torch.randperm(w.size(0), generator=g)[:100]:
rej += shapiro(w[i].numpy()).pvalue < 0.05
tot += 1
print(f"rows rejecting normality at 5%: {rej / tot:.1%} "
f"({tot} rows tested)")
got = {}
for kind, dq in [("fp32", 0), ("int4", 0), ("fp4", 0), ("nf4", 0),
("nf4", 1)]:
err = en = 0.0
with torch.no_grad():
for m, w0 in zip(lins, orig):
w = w0
if kind != "fp32":
code, am = quant(w0.reshape(-1), LV[kind], 64)
if dq:
am = dq_consts(am)[0]
w = dequant(code, am, LV[kind]).reshape(w0.shape)
err += ((w - w0) ** 2).sum().item()
en += (w0 ** 2).sum().item()
m.weight.copy_(w)
nll = got[(kind, dq)] = window_nll(model, ids)
d, se = paired(nll, got[("fp32", 0)])
rm = f"{err / en:.5f}" if en else "-"
print(f"{kind:<5} dq={dq} weight relMSE {rm:>8} "
f"ppl {nll.mean().exp():7.3f} d_nll {d:+.4f} +- {se:.4f}")
for a, b in ((("fp4", 0), ("nf4", 1)), (("int4", 0), ("fp4", 0))):
d, se = paired(got[a], got[b])
print(f"{a[0]} minus {b[0]}{'+DQ' * b[1]}: "
f"d_nll {d:+.4f} +- {se:.4f}")
del model
class QLinear(torch.nn.Module):
"""Frozen (de)quantized base weights + an optional LoRA adapter"""
def __init__(self, lin, kind, dq, r, alpha=16):
super().__init__()
w = lin.weight.detach().cpu()
self.kind, self.shape, self.r = kind, w.shape, r
if kind == "fp32":
self.register_buffer("w", w.to(dev))
else:
code, am = quant(w.reshape(-1), LV[kind], 64)
am = dq_consts(am)[0] if dq else am
self.register_buffer("code", code.to(torch.uint8).to(dev))
self.register_buffer("am", am.to(dev))
self.register_buffer("lv", LV[kind].to(dev))
b = lin.bias
self.register_buffer("b", None if b is None else b.detach())
if r:
self.scale = alpha / r
self.A = torch.nn.Parameter(torch.empty(r, w.shape[1]))
torch.nn.init.kaiming_uniform_(self.A, a=math.sqrt(5))
self.B = torch.nn.Parameter(torch.zeros(w.shape[0], r))
def forward(self, x):
w = self.w if self.kind == "fp32" else (
self.lv[self.code.long()] * self.am[:, None]).reshape(self.shape)
y = F.linear(x, w, self.b) # dequantize, then high-precision matmul
if self.r:
y = y + F.linear(F.linear(x, self.A), self.B) * self.scale
return y
NAME = "Qwen/Qwen2.5-0.5B"
STEPS, CKPT, TSEQ, TBSZ = 300, (0, 20, 60, 150, 300), 256, 4
def train(kind, dq, targets, seed, tok_train, ids_test):
torch.manual_seed(seed)
model = AutoModelForCausalLM.from_pretrained(NAME, dtype=torch.float32)
for p in model.parameters():
p.requires_grad_(False)
for n, m in list(model.named_modules()):
for cn, c in list(m.named_children()):
if isinstance(c, torch.nn.Linear) and ".layers." in f"{n}.{cn}":
setattr(m, cn, QLinear(c, kind, dq, 16 * (cn in targets)))
model = model.to(dev)
params = [p for p in model.parameters() if p.requires_grad]
opt = torch.optim.AdamW(params, lr=2e-4, weight_decay=0.0)
g = torch.Generator().manual_seed(1000 + seed)
res, t0 = {}, time.time()
for step in range(STEPS + 1):
if step in CKPT:
res[step] = window_nll(model, ids_test)
print(f" step {step:>3} ppl {res[step].mean().exp():7.3f}"
f" ({time.time() - t0:.0f}s)", flush=True)
if step == STEPS:
break
st = torch.randint(0, len(tok_train) - TSEQ, (TBSZ,), generator=g)
x = torch.stack([tok_train[i:i + TSEQ] for i in st]).to(dev)
lg = model(x).logits[:, :-1].float()
loss = F.cross_entropy(lg.reshape(-1, lg.size(-1)),
x[:, 1:].reshape(-1))
opt.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(params, 0.3)
opt.step()
return res, sum(p.numel() for p in params)
def run_lora():
tok = AutoTokenizer.from_pretrained(NAME)
ids_test = wiki_ids(tok, "test")[: NWIN * SEQ].reshape(NWIN, SEQ)
ids_train = wiki_ids(tok, "train")
ALL = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj",
"down_proj"]
runs = [("fp32", 0, ALL, 0), ("nf4", 1, ALL, 0), ("fp4", 0, ALL, 0),
("int4", 0, ALL, 0), ("fp32", 0, ALL, 1), ("nf4", 1, ALL, 1),
("nf4", 1, ["q_proj", "v_proj"], 0)]
out = {}
for kind, dq, tg, seed in runs:
key = (kind, dq, len(tg), seed)
print(f"{kind} dq={dq} lora_on={len(tg)} seed={seed}", flush=True)
out[key], n_ad = train(kind, dq, tg, seed, ids_train, ids_test)
print(f" adapter params {n_ad / 1e6:.2f}M")
torch.mps.empty_cache()
ref = out[("fp32", 0, 7, 0)]
print("\nppl on the 48 test windows (seed 0)")
print("base lora_on " + " ".join(f"{s:>7}" for s in CKPT))
for key, r in out.items():
if key[3] == 0:
print(f"{key[0] + '+DQ' * key[1]:<9} {key[2]:>7} " + " ".join(
f"{r[s].mean().exp():7.3f}" for s in CKPT))
print("\nnll gap to fp32+LoRA (nat, paired se over windows), seed 0")
for key, r in out.items():
if key[3] == 0 and key[0] != "fp32":
cells = []
for s in CKPT:
d, se = paired(r[s], ref[s])
cells.append(f"{d:+.3f}+-{se:.3f}")
print(f"{key[0] + '+DQ' * key[1]:<9} {key[2]:>7} "
+ " ".join(cells))
print("\nseed 1 vs seed 0, all-linear LoRA, ppl at step 300")
for kind, dq in (("fp32", 0), ("nf4", 1)):
a, b = out[(kind, dq, 7, 0)][300], out[(kind, dq, 7, 1)][300]
print(f"{kind + '+DQ' * dq:<9} seed0 {a.mean().exp():.3f}"
f" seed1 {b.mean().exp():.3f}")
g0 = paired(out[("nf4", 1, 7, 0)][300], ref[300])[0]
g1 = paired(out[("nf4", 1, 7, 1)][300], out[("fp32", 0, 7, 1)][300])[0]
print(f"nf4+DQ gap at step 300: seed0 {g0:+.4f} nat, seed1 {g1:+.4f} nat")
def run_paper():
shapes = {"7B": (32, 4096, 11008), "13B": (40, 5120, 13824),
"33B": (60, 6656, 17920), "65B": (80, 8192, 22016)}
V, bpp, r = 32000, 4 + 8 / 64 + 32 / (64 * 256), 64
table6 = {"7B": 5, "13B": 10, "33B": 21, "65B": 41} # paper Table 6, GB
print("size body_B 16bit_GB NF4+DQ_GB lora_M Table6_GB")
for k, (L, D, FF) in shapes.items():
body, emb = L * (4 * D * D + 3 * D * FF), 2 * V * D
lora = L * (4 * r * 2 * D + 2 * r * (D + FF) + r * (FF + D))
w4 = (body * bpp / 8 + emb * 2) / 1e9 # 4-bit layers, 16-bit embeddings
print(f"{k:<5} {body / 1e9:6.2f} {(body + emb) * 2 / 1e9:9.1f} "
f"{w4:10.1f} {lora / 1e6:7.0f} {table6[k]:10d}")
L, D, FF = shapes["65B"]
body, emb = L * (4 * D * D + 3 * D * FF), 2 * V * D
tot = body + emb
print(f"\n65B: body {body / 1e9:.2f}B + embeddings {emb / 1e9:.3f}B "
f"= {tot / 1e9:.2f}B")
print(f"full finetune, 2+2+8 bytes/param: {tot * 12 / 1e9:.0f} GB")
save = 0.5 - (bpp - 4)
print(f"NF4+DQ {bpp:.4f} bits/param; DQ saves {save:.3f} bit "
f"= {save * tot / 8 / 1e9:.2f} GB at 65B")
lora = L * (4 * r * 2 * D + 2 * r * (D + FF) + r * (FF + D))
w4, e16, st = body * bpp / 8 / 1e9, emb * 2 / 1e9, lora * 12 / 1e9
print(f"LoRA r=64 on all linear layers: {lora / 1e6:.0f}M params "
f"({lora / tot:.2%} of base)")
print(f"16-bit LoRA 65B: weights {tot * 2 / 1e9:.1f} GB"
f" + adapters {st:.1f} GB = {tot * 2 / 1e9 + st:.1f} GB")
print(f"QLoRA 65B: weights {w4:.1f} GB + embeddings {e16:.2f} GB"
f" + adapters {st:.1f} GB")
print(f" total {w4 + e16 + st:.1f} GB")
def win(d):
return 1 / (1 + 10 ** (-d / 400))
print(f"\nElo 1100 vs 1000: {win(100):.3f}; "
f"10 points near 0: {(win(5) - win(-5)) * 100:.2f} pp")
print(f"Guanaco-65B vs GPT-4 (human Elo 1023 vs 1176): "
f"{win(1023 - 1176):.3f}; 33B (1009): {win(1009 - 1176):.3f}")
print(f"GPT-4 judge 1348 vs human 1176: {win(172):.3f} "
"against an equal opponent")
t6 = [(119.4, 110.1, 114.5), (93.2, 96.4, 94.8), (96.7, 101.9, 99.3),
(63.0, 77.9, 70.7), (37.0, 59.6, 48.4), (96.5, 99.2, 97.8),
(91.2, 98.7, 94.9), (67.2, 79.7, 73.6), (26.3, 49.7, 38.0),
(91.2, 98.7, 94.9), (87.3, 93.4, 90.4), (63.8, 76.7, 69.4),
(55.5, 69.1, 62.5), (50.6, 69.8, 60.5), (49.2, 69.3, 59.5),
(44.9, 62.0, 53.6), (38.0, 60.5, 49.1), (32.4, 61.2, 47.0),
(84.1, 89.8, 87.0), (57.3, 71.2, 64.4), (33.3, 56.1, 44.8)]
gap = [abs((a + b) / 2 - m) for a, b, m in t6]
print(f"\nTable 6: Mean != average of the two orders in "
f"{sum(g > 0.051 for g in gap)} of {len(t6)} rows "
f"(max gap {max(gap):.2f})")
t4 = {"BFloat16": [38.4, 45.6, 47.2, 50.6, 57.7, 60.5, 61.8, 62.5],
"Float4": [37.2, 44.0, 47.3, 50.0, 55.9, 58.5, 61.3, 63.3],
"NF4+DQ": [39.0, 44.5, 47.5, 50.7, 57.3, 59.2, 61.8, 63.9]}
rep = {"BFloat16": 53.0, "Float4": 52.2, "NF4+DQ": 53.1}
print()
for k, v in t4.items():
print(f"Table 4 {k:<8} mean of 8 cells {sum(v) / 8:.2f}, "
f"reported {rep[k]}")
for a, b in (("Float4", "BFloat16"), ("NF4+DQ", "BFloat16"),
("NF4+DQ", "Float4")):
d = torch.tensor([x - y for x, y in zip(t4[a], t4[b])])
print(f"{a} - {b}: mean {d.mean():+.2f}, "
f"paired se {d.std() / math.sqrt(len(d)):.2f}")
if __name__ == "__main__":
{"data": run_data, "lora": run_lora, "paper": run_paper}[sys.argv[1]]()
The output of one complete run of each mode. data:
NF4: 16 levels, max |diff| to Appendix E: 1.1e-07
levels: -1.000 -0.696 -0.525 -0.395 -0.284 -0.185 -0.091 0.000 0.080 0.161 0.246 0.338 0.441 0.563 0.723 1.000
Gaussian data, absmax blocks
block type relMSE SQNR_dB H_bits
64 int4 0.01160 19.36 3.500
64 fp4 0.01117 19.52 3.818
64 nf4 0.00846 20.73 3.884
256 int4 0.01599 17.96 3.278
256 fp4 0.01239 19.07 3.707
256 nf4 0.00977 20.10 3.750
4096 int4 0.02481 16.05 2.952
4096 fp4 0.01417 18.49 3.513
4096 nf4 0.01214 19.16 3.517
sigma-scaled int4 H_bits 3.794 p_min 0.0301 p_max 0.1055
sigma-scaled fp4 H_bits 3.893 p_min 0.0550 p_max 0.0803
sigma-scaled nf4 H_bits 3.996 p_min 0.0555 p_max 0.0709
DQ storage 4.1270 bits/param; constants rel. error max 0.0347 mean 0.00286
NF4 B=64 no DQ relMSE 0.00846
NF4 B=64 DQ relMSE 0.00848
Qwen/Qwen2.5-0.5B: 168 matrices, 358M weights, 24576 eval tokens
row excess kurtosis p10/p50/p90: -0.07 / 0.22 / 1.24
rows rejecting normality at 5%: 54.5% (16800 rows tested)
fp32 dq=0 weight relMSE - ppl 16.452 d_nll +0.0000 +- 0.0000
int4 dq=0 weight relMSE 0.01342 ppl 20.383 d_nll +0.2142 +- 0.0059
fp4 dq=0 weight relMSE 0.01143 ppl 19.007 d_nll +0.1443 +- 0.0043
nf4 dq=0 weight relMSE 0.00892 ppl 18.584 d_nll +0.1219 +- 0.0042
nf4 dq=1 weight relMSE 0.00898 ppl 18.597 d_nll +0.1225 +- 0.0042
fp4 minus nf4+DQ: d_nll +0.0218 +- 0.0049
int4 minus fp4: d_nll +0.0699 +- 0.0071
Qwen/Qwen2.5-1.5B-Instruct: 196 matrices, 1310M weights, 24576 eval tokens
row excess kurtosis p10/p50/p90: -0.07 / 0.15 / 0.72
fp32 dq=0 weight relMSE - ppl 11.941 d_nll +0.0000 +- 0.0000
int4 dq=0 weight relMSE 0.01277 ppl 13.855 d_nll +0.1487 +- 0.0048
fp4 dq=0 weight relMSE 0.01132 ppl 13.184 d_nll +0.0990 +- 0.0047
nf4 dq=0 weight relMSE 0.00874 ppl 13.047 d_nll +0.0886 +- 0.0045
nf4 dq=1 weight relMSE 0.00878 ppl 13.044 d_nll +0.0884 +- 0.0046
fp4 minus nf4+DQ: d_nll +0.0106 +- 0.0045
int4 minus fp4: d_nll +0.0497 +- 0.0057
lora: the first table is perplexity on the 48 test windows; the second is the log-loss gap to FP32 + LoRA, written as gap+-standard error, with the standard error paired over the 48 windows. The last row, with lora_on=2, puts adapters only on the q and v projections:
fp32 dq=0 lora_on=7 seed=0
step 0 ppl 16.452 (5s)
step 20 ppl 14.203 (22s)
step 60 ppl 13.066 (50s)
step 150 ppl 12.563 (106s)
step 300 ppl 12.339 (198s)
adapter params 8.80M
nf4 dq=1 lora_on=7 seed=0
step 0 ppl 18.597 (7s)
step 20 ppl 15.629 (28s)
step 60 ppl 14.131 (62s)
step 150 ppl 13.452 (127s)
step 300 ppl 13.131 (228s)
adapter params 8.80M
fp4 dq=0 lora_on=7 seed=0
step 0 ppl 19.007 (7s)
step 20 ppl 15.759 (26s)
step 60 ppl 14.291 (58s)
step 150 ppl 13.639 (120s)
step 300 ppl 13.327 (217s)
adapter params 8.80M
int4 dq=0 lora_on=7 seed=0
step 0 ppl 20.383 (7s)
step 20 ppl 16.542 (26s)
step 60 ppl 14.714 (58s)
step 150 ppl 14.004 (120s)
step 300 ppl 13.589 (221s)
adapter params 8.80M
fp32 dq=0 lora_on=7 seed=1
step 0 ppl 16.452 (6s)
step 20 ppl 14.067 (23s)
step 60 ppl 13.074 (51s)
step 150 ppl 12.525 (106s)
step 300 ppl 12.365 (194s)
adapter params 8.80M
nf4 dq=1 lora_on=7 seed=1
step 0 ppl 18.597 (7s)
step 20 ppl 15.487 (26s)
step 60 ppl 14.170 (58s)
step 150 ppl 13.421 (120s)
step 300 ppl 13.182 (223s)
adapter params 8.80M
nf4 dq=1 lora_on=2 seed=0
step 0 ppl 18.597 (7s)
step 20 ppl 17.393 (25s)
step 60 ppl 16.069 (53s)
step 150 ppl 15.040 (113s)
step 300 ppl 14.435 (205s)
adapter params 1.08M
ppl on the 48 test windows (seed 0)
base lora_on 0 20 60 150 300
fp32 7 16.452 14.203 13.066 12.563 12.339
nf4+DQ 7 18.597 15.629 14.131 13.452 13.131
fp4 7 19.007 15.759 14.291 13.639 13.327
int4 7 20.383 16.542 14.714 14.004 13.589
nf4+DQ 2 18.597 17.393 16.069 15.040 14.435
nll gap to fp32+LoRA (nat, paired se over windows), seed 0
nf4+DQ 7 +0.123+-0.004 +0.096+-0.003 +0.078+-0.003 +0.068+-0.003 +0.062+-0.003
fp4 7 +0.144+-0.004 +0.104+-0.004 +0.090+-0.004 +0.082+-0.004 +0.077+-0.003
int4 7 +0.214+-0.006 +0.152+-0.004 +0.119+-0.004 +0.109+-0.004 +0.096+-0.004
nf4+DQ 2 +0.123+-0.004 +0.203+-0.005 +0.207+-0.007 +0.180+-0.006 +0.157+-0.005
seed 1 vs seed 0, all-linear LoRA, ppl at step 300
fp32 seed0 12.339 seed1 12.365
nf4+DQ seed0 13.131 seed1 13.182
nf4+DQ gap at step 300: seed0 +0.0622 nat, seed1 +0.0640 nat
paper:
size body_B 16bit_GB NF4+DQ_GB lora_M Table6_GB
7B 6.48 13.5 3.9 160 5
13B 12.69 26.0 7.2 250 10
33B 32.10 65.1 17.4 488 21
65B 64.76 130.6 34.5 800 41
65B: body 64.76B + embeddings 0.524B = 65.28B
full finetune, 2+2+8 bytes/param: 783 GB
NF4+DQ 4.1270 bits/param; DQ saves 0.373 bit = 3.04 GB at 65B
LoRA r=64 on all linear layers: 800M params (1.22% of base)
16-bit LoRA 65B: weights 130.6 GB + adapters 9.6 GB = 140.2 GB
QLoRA 65B: weights 33.4 GB + embeddings 1.05 GB + adapters 9.6 GB
total 44.1 GB
Elo 1100 vs 1000: 0.640; 10 points near 0: 1.44 pp
Guanaco-65B vs GPT-4 (human Elo 1023 vs 1176): 0.293; 33B (1009): 0.277
GPT-4 judge 1348 vs human 1176: 0.729 against an equal opponent
Table 6: Mean != average of the two orders in 13 of 21 rows (max gap 0.85)
Table 4 BFloat16 mean of 8 cells 53.04, reported 53.0
Table 4 Float4 mean of 8 cells 52.19, reported 52.2
Table 4 NF4+DQ mean of 8 cells 52.99, reported 53.1
Float4 - BFloat16: mean -0.85, paired se 0.35
NF4+DQ - BFloat16: mean -0.05, paired se 0.31
NF4+DQ - Float4: mean +0.80, paired se 0.19
NF4 values and the error of block-wise quantization
The first line shows that the asymmetric construction, with 8 positive values, 7 negative values and a 0, and an offset of 0.9677083, gives 16 values whose largest deviation from Appendix E of the paper is only 1.1×10⁻⁷, which is float32 rounding. So this is how the paper’s NF4 comes about, and no further magic constant is needed.
On standard normal samples, scaled by the in-block absmax and then quantized, the results are as follows (a smaller relative MSE is better; the code entropy is at most 4 bits, and a higher value means the 16 bins are used more evenly):
| Block | Type | Rel. MSE | SQNR (dB) | Code entropy (bits) |
|---|---|---|---|---|
| 64 | INT4 | 0.01160 | 19.36 | 3.500 |
| 64 | FP4 | 0.01117 | 19.52 | 3.818 |
| 64 | NF4 | 0.00846 | 20.73 | 3.884 |
| 256 | INT4 | 0.01599 | 17.96 | 3.278 |
| 256 | FP4 | 0.01239 | 19.07 | 3.707 |
| 256 | NF4 | 0.00977 | 20.10 | 3.750 |
| 4096 | INT4 | 0.02481 | 16.05 | 2.952 |
| 4096 | FP4 | 0.01417 | 18.49 | 3.513 |
| 4096 | NF4 | 0.01214 | 19.16 | 3.517 |
Three observations. First, at block size 64 NF4 has the smallest error (0.00846), about 27% below INT4 and about 24% below FP4; at block size 4096 the INT4 error rises to 0.02481, 2.1 times its value at block size 64, while NF4 rises by only 43%, so the larger the block the more INT4 suffers, which fits the paper’s choice of cutting weights into blocks of 64. Second, NF4 also has the highest code entropy: 3.884 bits at block size 64 against 3.500 for INT4. Third, the paper’s “information-theoretically optimal” means that every bin receives the same probability. I also computed that ideal setting (the three sigma-scaled lines in the output; instead of the in-block absmax, the data is scaled by the standard deviation so that ±1 corresponds to the outermost quantile): NF4’s code entropy is 3.996 bits and its bin shares lie between 5.55% and 7.09%, close to the uniform 6.25%; INT4 ranges from 3.01% to 10.55% and FP4 from 5.50% to 8.03%. Note that this “optimal” refers to bin utilization, not to the smallest mean squared error, although NF4 also has the smallest mean squared error in this experiment.
Double quantization costs almost no accuracy
NF4 with a block size of 64 and double quantization stores 4.1270 bits per parameter, in line with above. After the scaling constants are quantized to FP8 their relative error is at most 3.47% and 0.286% on average, and the effect on the weight reconstruction error is a relative MSE going from 0.00846 to 0.00848. Real models behave the same way: on Qwen2.5-0.5B the relative weight error is 0.00892 for NF4 and 0.00898 with double quantization, with perplexities of 18.584 and 18.597. The 0.373 bits saved are close to free.
Real models: the ordering matches the paper, but “weights are normal” deserves a discount
| Base | 0.5B weight err. | 0.5B ppl | 0.5B Δ | 1.5B ppl | 1.5B Δ |
|---|---|---|---|---|---|
| FP32 | - | 16.452 | 0 | 11.941 | 0 |
| INT4 | 0.01342 | 20.383 | +0.2142±0.0059 | 13.855 | +0.1487±0.0048 |
| FP4 | 0.01143 | 19.007 | +0.1443±0.0043 | 13.184 | +0.0990±0.0047 |
| NF4 | 0.00892 | 18.584 | +0.1219±0.0042 | 13.047 | +0.0886±0.0045 |
| NF4+DQ | 0.00898 | 18.597 | +0.1225±0.0042 | 13.044 | +0.0884±0.0046 |
Δ is the difference in mean log-loss relative to FP32 (in nat; ± is the paired standard error over the 48 windows). On both models INT4 is worst and NF4 is best, and double quantization makes no distinguishable difference, the same ordering as the paper’s Table 2. The size of the gaps depends on the scale: on Qwen2.5-0.5B NF4 with double quantization beats FP4 by 0.0218 nat (about 4.4 standard errors), on Qwen2.5-1.5B only by 0.0106 nat (about 2.4 standard errors), while INT4 falls behind FP4 by more (0.0699 and 0.0497). The larger model also loses less to quantization: the Δ of NF4 with double quantization falls from 0.1225 at 0.5B to 0.0884 at 1.5B.
The premise that “pretrained weights are roughly zero-mean normal” needs a discount on this model. I ran a Shapiro-Wilk test on 16,800 rows of Qwen2.5-0.5B weights (100 rows per matrix), and 54.5% of the rows reject normality at the 5% level; Appendix F of the paper runs the same per-neuron test on LLaMA 7B and reports 7.5%. The two numbers cannot be compared directly: the models differ, I take one neuron to be one row of the nn.Linear weight and I am not sure this matches the paper’s procedure, and the paper itself says the Shapiro-Wilk p-value is inaccurate for large samples. At the same time, the median excess kurtosis of the rows is only 0.22 (10th and 90th percentiles −0.07 and 1.24), so most rows deviate mildly, and the relative error of NF4 on real weights (0.00892) is only 5% higher than on Gaussian data (0.00846). Read together: “roughly normal” is not strictly true, but it is good enough for NF4.
How much the adapters win back
| Adapter base | Step 0 | Step 20 | Step 60 | Step 150 | Step 300 |
|---|---|---|---|---|---|
| FP32 + LoRA | 16.452 | 14.203 | 13.066 | 12.563 | 12.339 |
| NF4+DQ + LoRA | 18.597 | 15.629 | 14.131 | 13.452 | 13.131 |
| FP4 + LoRA | 19.007 | 15.759 | 14.291 | 13.639 | 13.327 |
| INT4 + LoRA | 20.383 | 16.542 | 14.714 | 14.004 | 13.589 |
| NF4+DQ + LoRA (q, v only) | 18.597 | 17.393 | 16.069 | 15.040 | 14.435 |
The training puts LoRA on all linear layers of Qwen2.5-0.5B (, , AdamW, learning rate 2e-4, batches of 4×256 tokens, gradient-norm clipping at 0.3, 300 steps, about 300,000 tokens), and the base is FP32, NF4 with double quantization, FP4 or INT4. Much of the large drop in perplexity (16.452 to 12.339) is probably the adapters adapting to the style of WikiText, and the test split comes from the same corpus; what we care about is the gap between the quantized bases and the FP32 base, and how it changes with training steps:
| Base | Step 0 | Step 20 | Step 60 | Step 150 | Step 300 |
|---|---|---|---|---|---|
| NF4+DQ | +0.123±0.004 | +0.096±0.003 | +0.078±0.003 | +0.068±0.003 | +0.062±0.003 |
| FP4 | +0.144±0.004 | +0.104±0.004 | +0.090±0.004 | +0.082±0.004 | +0.077±0.003 |
| INT4 | +0.214±0.006 | +0.152±0.004 | +0.119±0.004 | +0.109±0.004 | +0.096±0.004 |
(The row with adapters only on q and v is left out of this table: its reference is still the FP32 adapter on all linear layers, which would mix “which layers” with “quantization”.)
How to read it. First, before training NF4 with double quantization is 0.123 nat worse than FP32; after 300 steps the gap shrinks to 0.062, about half remains. The shrinkage is slowing down (0.123, 0.096, 0.078, 0.068, 0.062), so 300 steps do not close it, and this run cannot tell whether longer training would: the paper’s conclusion comes from larger models, longer training and downstream task metrics, so this small experiment agrees in direction but is more conservative in size. Second, the ordering of the data types (NF4 with double quantization better than FP4, FP4 better than INT4) holds at all five checkpoints, with gaps of 0.062, 0.077 and 0.096 at step 300. Third, with another random seed FP32 gets perplexities of 12.339 and 12.365 and NF4 with double quantization 13.131 and 13.182, and the gaps at step 300 are 0.0622 and 0.0640, so seed noise is about 0.002 nat, much smaller than the 0.015 between data types; but each base was repeated with only two seeds, so this noise estimate is itself rough. Fourth, with adapters only on q and v, NF4 with double quantization reaches a perplexity of 14.435 after 300 steps, 1.3 above the same base with adapters on all linear layers (13.131), with 1.08M adapter parameters against 8.80M, 8 times fewer. The direction agrees with the paper’s “adapters belong on all linear layers”, but this comparison mixes “which layers” with “how many adapter parameters”, and cannot separate them.
The paper’s memory arithmetic and table arithmetic
Using the LLaMA structure (vocabulary 32,000, input and output embeddings not tied) to compute parameter counts from the number of layers, the hidden width and the FFN width, and then weight sizes at 4.127 bits per parameter for NF4 with double quantization:
| Model | Body (B) | 16-bit (GB) | NF4+DQ (GB) | LoRA (M) | Table 6 (GB) |
|---|---|---|---|---|---|
| 7B | 6.48 | 13.5 | 3.9 | 160 | 5 |
| 13B | 12.69 | 26.0 | 7.2 | 250 | 10 |
| 33B | 32.10 | 65.1 | 17.4 | 488 | 21 |
| 65B | 64.76 | 130.6 | 34.5 | 800 | 41 |
The 16-bit sizes (13.5, 26.0, 65.1 and 130.6 GB) agree with the 16-bit models in the paper’s Table 6, for example 26 GB for Vicuna 13B. For 4-bit models my weight sizes are 3.9, 7.2, 17.4 and 34.5 GB, while the memory column of the paper’s Table 6 says 5, 10, 21 and 41 GB, which is 1.1 to 6.5 GB more. The difference may be activations, the CUDA context and adapters; the paper does not break it down and I cannot tell.
The 65B accounting is as follows. Full fine-tuning at 2+2+8 bytes per parameter (weights, gradients, Adam states) is 783 GB. QLoRA has 33.4 GB of 4-bit weights, plus 1.05 GB for the embeddings kept in 16 bits, plus 9.6 GB for the adapters with on all linear layers (800 million parameters, 1.22% of the base) together with their gradients and Adam states, 44.1 GB in all. That is compatible with the paper’s “under 48 GB”, but it leaves less than 4 GB for activations, checkpoints and framework overhead, a thin margin where a slightly higher peak means an out-of-memory error, which is exactly the situation paged optimizers are for. Double quantization saves 3.04 GB at 65B, in line with the “about 3 GB” above. By contrast, 16-bit LoRA needs 140.2 GB.
Elo conversions: 1100 against 1000 is a win probability of 0.640, and near a zero difference every 10 Elo points are worth about 1.44 percentage points. With the human judges’ Elo, Guanaco 65B (1023) against GPT-4 (1176) wins with probability 0.293 and Guanaco 33B (1009) with 0.277, so GPT-4 wins about 71% to 72% of the time. The Elo that the GPT-4 judge gives itself (1348) is 172 points above the one from the human judges (1176), which converts into a win probability of 0.729 against an equal opponent, about 23 percentage points above even, in line with the paper’s “additional 20% probability of winning”.
Finally, the paper’s two tables. In Table 6 the “Mean” column does not equal the plain average of the two orders in 13 of 21 rows, with a maximum gap of 0.85. The paper does not say how it aggregates, so I do not call it an error, but do not use that column to back out the scores of the two orders. In Table 4 the means of the eight cells are 53.04, 52.19 and 52.99 for BFloat16, Float4 and NF4 with double quantization, while the paper writes 53.0, 52.2 and 53.1; the last one is 0.11 away from 52.99, which rounding does not explain. Treating the eight cells as paired samples (they are 4 sizes times 2 datasets and not independent, so the standard errors are only a rough guide), Float4 is 0.85 (±0.35) below BFloat16, NF4 with double quantization differs from BFloat16 by only −0.05 (±0.31), and NF4 with double quantization is 0.80 (±0.19) above Float4. This fits the paper’s “NF4 matches BFloat16 and FP4 lags by about a point”, but the statistical evidence is not strong, and it rests on eight cells.
Limitations and Reading Notes
- No direct comparison with 16-bit full fine-tuning at 33B and 65B. In its limitations section the paper admits it did not establish that QLoRA matches 16-bit full fine-tuning at 33B and 65B: full fine-tuning at 11B and above needs more than one high-memory server, and 33B and 65B were compared only against 16-bit LoRA on MMLU. “Matches full fine-tuning” is not directly verified at the largest scales.
- MMLU comes without error bars. Tables 4 and 5 both contain NF4 with double quantization on Alpaca and FLAN v2, and of the eight cells four are identical and four differ by 0.2 to 0.7 (13B on FLAN v2 is 50.7 against 51.4, 65B on Alpaca is 61.8 against 62.5). The paper does not say whether the two sets come from the same run, but at least it suggests that MMLU is not stable at this level, so differences within 0.5 points should not be interpreted.
- Discount the chat results. The Vicuna benchmark has only 80 prompts, Guanaco 65B’s 99.3% carries a ±4.4 confidence interval, GPT-4 has order bias and self-preference, and the authors admit that they often disagreed among themselves when comparing Guanaco and ChatGPT answer by answer. 99.3% reads as “hard to tell apart on this benchmark”.
- Limited evaluation scope. The paper admits it did not evaluate on BigBench, RAFT or HELM, did only a very limited bias evaluation for responsible AI (CrowS), and did not evaluate 3-bit bases or adapter methods other than LoRA.
- No speed comparison. The introduction says the method does not slow down running, but there is no throughput table for 4-bit dequantization, and the paged optimizer gets only a one-line “same speed” statement.
- Supervised fine-tuning only. Guanaco uses the cross-entropy loss and no RLHF; the paper leaves “the trade-off between simple cross-entropy and RLHF” to future work.
- A few numbers in the paper do not line up. Table 1 lists Guanaco 7B at 6 GB while Table 6 and the text say 5 GB; the NF4 with double quantization mean in Table 4 is written as 53.1 while the mean of the eight cells is 52.99; and the “Mean” column of Table 6 does not equal the plain average of the two orders in 13 of 21 rows. None of this changes the conclusions, but check the original tables when quoting specific numbers.
What to Take Away from This Paper
- QLoRA separates “storage” from “computation”. Weights are stored in 4 bits and computed in BF16, and adapters are trained in BF16. It saves the memory of the frozen base, not that of the adapters and not that of the activations.
- NF4 puts the same number of weights in every bin. That holds only when the weights are roughly normal and the data type is used with in-block absmax scaling; it beats INT4 and FP4, but by how much depends on the model and the block size.
- Double quantization is a detail optimization. It cuts the overhead from 0.5 to 0.127 bits, about 3 GB for 65B, and what matters is that it lets a model fit into 24 GB or 48 GB.
- Where the adapters go matters more than their rank. LoRA on the query and value projections alone does not catch up with full fine-tuning; it has to cover all linear layers.
- The second half of the paper is a lesson in evaluation. Data quality, the match between benchmark and data, and judge bias are all still relevant today.
Further Reading
- Dettmers et al., QLoRA: Efficient Finetuning of Quantized LLMs (2023): the NF4 values are in Appendix E, the memory breakdown in Figure 6, and the Elo and human evaluation in Section 5 and Appendices C and D.
- Hu et al., LoRA: Low-Rank Adaptation of Large Language Models (2021), with this site’s paper breakdown.
- Dettmers and Zettlemoyer, The case for 4-bit precision: k-bit Inference Scaling Laws (2022): the evaluation setup the paper follows for comparing zero-shot accuracy and perplexity across data types.
- Touvron et al., LLaMA: Open and Efficient Foundation Language Models (2023), with this site’s paper breakdown.
- Related pages on this site: LoRA and parameter-efficient fine-tuning, Quantization, Compute and memory, LLM-as-a-Judge, SFT data.
FAQ
- What is the difference between QLoRA and LoRA?
- LoRA freezes the base weights and trains low-rank adapters, but the base still sits in memory in 16 bits. QLoRA also quantizes the frozen base to 4 bits (NF4), dequantizes each layer to BF16 on the fly for the forward and backward passes, and trains 16-bit adapters as usual. What it saves is mainly the memory of the base weights: the paper reports that fine-tuning a 65B model drops from more than 780 GB to under 48 GB.
- Why is NF4 better than INT4 and FP4?
- NF4 places its 16 values at quantiles of the standard normal distribution, so each quantization bin catches roughly the same number of weights, and pretrained weights are close to zero-mean normal. The same 4 bits therefore keep more information. In the paper's Table 2 the mean Pile Common Crawl perplexity is 34.34 for INT4, 31.07 for FP4 (E2M1) and 27.41 for NF4 with double quantization. On Qwen2.5-0.5B this page reproduces the ordering: relative to FP32 the mean log-loss is higher by 0.214 nat for INT4, 0.144 for FP4 and 0.122 for NF4.
- How much memory does double quantization save?
- With a block size of 64 and 32-bit constants, every parameter carries an extra 32/64 = 0.5 bits. Double quantization quantizes those constants again to 8-bit floats in blocks of 256, which brings the overhead down to 8/64 + 32/(64x256), about 0.127 bits, a saving of 0.373 bits per parameter. For a 65B model that is about 3 GB, roughly 8% of the 4.5 bits per parameter that block-wise quantization alone would need.
- Is a QLoRA-tuned model really as good as a 16-bit one?
- On GLUE, Super-NaturalInstructions and MMLU for LLaMA 7B to 65B, the paper finds QLoRA roughly level with 16-bit LoRA and full fine-tuning, but it reports no error bars for MMLU and admits it did not compare against 16-bit full fine-tuning at 33B and 65B. In the small experiment on this page (Qwen2.5-0.5B), after 300 training steps the NF4 base was still 0.062 nat behind the FP32 base, about half of the 0.123 nat gap before training.
- What does Guanaco reaching 99.3% of ChatGPT mean?
- GPT-4 scored the 80 prompts of the Vicuna benchmark, and Guanaco 65B's score was divided by ChatGPT's score and averaged over both answer orders. The paper itself gives a 95% confidence interval of +-4.4 points and notes a strong order bias in GPT-4, so the figure says Guanaco and ChatGPT are hard to tell apart on this benchmark, not that Guanaco reaches 99.3% of ChatGPT on everything.