AI Logic

Model Compression

QLoRA

Updated:

How QLoRA works. The left side shows the computation of one linear layer: the weight W stored in NF4 is restored to BF16 by double dequantization to compute X Β· W, which is added to the trainable LoRA branch s Β· X Β· L₁ Β· Lβ‚‚. The upper right compares the 16 NF4 values placed to match a normal distribution with 16 evenly spaced values, and the lower right shows double quantization reducing the memory for constants from 0.5 bits to 0.127 bits.

Background and Overview

QLoRA is a fine-tuning method that adds small trainable matrices (LoRA) to a language model that has been quantized to 4 bits and frozen, and trains only those matrices. It was proposed in 2023 by Dettmers, Pagnoni, Holtzman, and Zettlemoyer.

Fine-tuning a large language model uses a great deal of GPU memory. According to the paper, regular 16-bit fine-tuning of LLaMA 65B requires more than 780GB of GPU memory. Earlier quantization methods worked for inference but not for training.

QLoRA greatly reduces memory while keeping the same accuracy as 16-bit training through the following techniques.

  • 4-bit NormalFloat (NF4): A 4-bit data type that exploits the fact that trained weights are close to normally distributed.
  • Double quantization: Quantizes the quantization constants themselves to reduce memory further.
  • Paged optimizers: Move optimizer states to CPU memory only when GPU memory runs out, preventing training from stopping due to out-of-memory errors.
  • LoRA: Leaves the original weights unchanged and trains only small low-rank matrices.

This makes it possible to fine-tune a 65B-parameter model on a single 48GB GPU. In the paper, Guanaco 65B, a chat model trained this way, reaches 99.3% of ChatGPT's performance on the Vicuna benchmark (24 hours of training on a single GPU).

Theory (4-bit Weights and LoRA)

LoRA adds a product of low-rank matrices to a linear layer Y=XWY = XW (X∈RbΓ—hX \in \mathbb{R}^{b \times h}, W∈RhΓ—oW \in \mathbb{R}^{h \times o}) (Eq. (3) in the paper).

Y=XW+s XL1L2Y = XW + s\, X L_1 L_2

Here L1∈RhΓ—rL_1 \in \mathbb{R}^{h \times r} and L2∈RrΓ—oL_2 \in \mathbb{R}^{r \times o}, where rr is much smaller than hh or oo, and ss is a scaling factor. Only L1L_1 and L2L_2 are trained.

QLoRA stores this WW in 4 bits. The computation of one linear layer becomes the following (Eqs. (5) and (6) in the paper).

YBF16=XBF16 doubleDequant ⁣(c1FP32,c2k-bit,WNF4)+XBF16L1BF16L2BF16Y^{\mathrm{BF16}} = X^{\mathrm{BF16}}\, \mathrm{doubleDequant}\!\left(c_1^{\mathrm{FP32}}, c_2^{\mathrm{k\text{-}bit}}, W^{\mathrm{NF4}}\right) + X^{\mathrm{BF16}} L_1^{\mathrm{BF16}} L_2^{\mathrm{BF16}}

The key point is separating the storage data type (NF4) from the computation data type (BF16). The procedure is as follows.

  1. Split the trained weights WW into blocks of 64, scale each block into [βˆ’1,1][-1, 1] by its absolute maximum, and round each value to the nearest of the 16 NF4 values.
  2. Group the per-block constants c2c_2 (FP32) into blocks of 256 and quantize them again to 8-bit floating point (FP8). The constants for this second step are c1c_1 (FP32) (double quantization).
  3. Freeze the quantized WW and prepare the LoRA matrices L1L_1 and L2L_2 in BF16.
  4. In the forward and backward passes, WW is restored to BF16 on the fly for computation.
  5. Gradients flow through WW to L1L_1 and L2L_2, but only L1L_1 and L2L_2 are updated.
  6. Optimizer states are placed in paged memory and automatically moved to CPU memory when GPU memory runs out.

Since the quantized weights are not updated during training, no gradients with respect to the 4-bit weights are needed. However, computing LoRA's gradients requires propagating the gradient with respect to the input XX through WW to earlier layers. For this reason, WW is restored to BF16 for every computation.

How NF4 and Double Quantization Work

NF4 is a data type based on quantile quantization, which places grid points so that each interval contains the same number of values. Because trained weights are close to a normal distribution centered at 0, the grid values can be fixed in advance from the quantiles of the standard normal distribution (Eq. (4) in the paper).

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)

QXQ_X is the quantile function of the standard normal distribution (the inverse of the cumulative distribution function), and kk is the number of bits. The resulting values are scaled into [βˆ’1,1][-1, 1]. As is, however, there would be no value that represents 0 exactly, so the negative side is built from 2kβˆ’12^{k-1} quantiles and the positive side from 2kβˆ’1+12^{k-1} + 1 quantiles, and the overlapping 0 is merged into one. This yields 16 values that include 0 (upper right of the top figure).

The grid is placed densely near 0, where values concentrate, and sparsely at the tails, where values are rare, so the error is smaller than with an evenly spaced grid at the same 4 bits. It is like putting up more signposts where more people pass by.

Double quantization reduces the memory for quantization constants. Keeping accuracy at 4 bits requires small blocks, but storing a 32-bit constant per block of 64 costs an extra 32/64=0.532/64 = 0.5 bits per weight. Quantizing the constants again to FP8 (in blocks of 256) reduces this as follows.

864+3264β‹…256β‰ˆ0.127Β bits\frac{8}{64} + \frac{32}{64 \cdot 256} \approx 0.127 \text{ bits}

The paper states that this saves about 0.373 bits per weight, equivalent to about 3GB for a 65B model.

Experimental Results

Table 2 of the paper compares, by data type, the mean perplexity (lower is better) on Pile Common Crawl when OPT, BLOOM, LLaMA, and Pythia (125M to 13B) are quantized to 4 bits.

Data typeMean perplexity
Int434.34
Float4 (E2M1)31.07
Float4 (E3M0)29.48
NF4 + double quantization27.41

Table 4 fine-tunes LLaMA on Alpaca and FLAN v2 and compares MMLU (5-shot) accuracy.

Base data type for LoRA7B (Alpaca)13B (Alpaca)33B (Alpaca)65B (Alpaca)Overall mean
BF1638.447.257.761.853.0
Float437.247.355.961.352.2
NF4 + double quantization39.047.557.361.853.1
  • NF4 + double quantization matched the accuracy of 16-bit LoRA. Float4, by contrast, was about 1 point lower.
  • Smaller models were also compared against 16-bit training of all weights. For RoBERTa-large (GLUE) and T5 (Super-NaturalInstructions), 4-bit QLoRA reached the same level as 16-bit full fine-tuning (Table 3).
  • LoRA must be applied to every linear layer. The common setup of applying LoRA only to the attention query and value fell short of 16-bit full fine-tuning. With LoRA on every linear layer, the rank rr had almost no effect on the results.

Practical Considerations

  • Apply LoRA to every linear layer, not just attention. In the paper's experiments, the factor that mattered most for accuracy was the number of layers with LoRA.
  • Combine it with gradient checkpointing. According to the paper, most of the memory in LoRA training is taken not by the LoRA parameters but by activation gradients. Gradient checkpointing reduces this substantially.
  • Computation runs in BF16. Although storage is 4-bit, weights are restored to 16 bits for every computation, so it is not faster than a 16-bit model.
  • Evaluate on data close to the intended use. The paper notes that benchmark results depend heavily on how similar the fine-tuning data is to the benchmark.

The paper verified matching accuracy with 16-bit full fine-tuning only for models up to about 3B parameters. For 33B and 65B, it confirmed matching accuracy with 16-bit LoRA, but the paper itself states that, due to cost, it did not check whether it matches full fine-tuning.

Comparison with Other Methods

The following table compares methods for handling LLMs with less memory by what they are used for.

MethodPurposeWeight bit widthWhat is trained
Full fine-tuningTraining16 bitsAll weights
LoRATraining16 bits (frozen)Only low-rank matrices
QLoRATraining4 bits (NF4, frozen)Only low-rank matrices
LLM.int8()Inference8 bitsNothing
GPTQ, AWQInference3 to 4 bitsNothing (post-training quantization)

QLoRA is implemented in the same bitsandbytes library as LLM.int8(). GPTQ and AWQ are quantization methods for inference that spend computation on reducing quantization error. QLoRA's idea is instead to compensate for quantization error through LoRA training. The paper also notes that fine-tuning after quantization appears to recover much of the performance lost to quantization.

  • QLoRA is well suited to adapting a large model to your own data on limited GPUs.
  • If GPU memory is plentiful and you want training to be even slightly faster, choose 16-bit LoRA.
  • If you only want lighter inference without training, use inference-oriented quantization such as GPTQ, AWQ, or LLM.int8().

PyTorch example

Show code
python
import torch
import torch.nn as nn

# One QLoRA linear layer written as in Eq. (5) of the paper (for illustration; double quantization omitted)

# The 16 NF4 values from Appendix E of the paper
NF4 = torch.tensor([
    -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 quantize_nf4(w, block_size=64):
    """Scale each block into [-1, 1] by absmax and map to the index (0-15) of the nearest NF4 value"""
    flat = w.flatten().reshape(-1, block_size)
    absmax = flat.abs().amax(dim=1, keepdim=True).clamp(min=1e-8)   # per-block constant
    idx = (flat / absmax).unsqueeze(-1).sub(NF4).abs().argmin(dim=-1)  # 4-bit index
    return idx.to(torch.uint8), absmax


def dequantize_nf4(idx, absmax, shape):
    return (NF4[idx.long()] * absmax).reshape(shape)


class QLoRALinear(nn.Module):
    def __init__(self, base: nn.Linear, r=16, lora_alpha=32, dropout=0.05):
        super().__init__()
        # 1. Store the original weights in NF4 and do not train them (keep as buffers)
        idx, absmax = quantize_nf4(base.weight.data)
        self.register_buffer("w_idx", idx)
        self.register_buffer("w_absmax", absmax)
        self.shape = base.weight.shape                      # (out, in)
        self.register_buffer("bias", base.bias.data.clone() if base.bias is not None else None)
        # 2. Only the two LoRA matrices are trained
        out_f, in_f = self.shape
        self.lora_A = nn.Parameter(torch.randn(r, in_f) * 0.01)   # corresponds to L1
        self.lora_B = nn.Parameter(torch.zeros(out_f, r))          # corresponds to L2 (starts at 0)
        self.scale = lora_alpha / r                                # scaling factor s
        self.dropout = nn.Dropout(dropout)                         # behaves differently under model.train() / eval()

    def forward(self, x):
        # 3. Restore to 16 bits for every computation (float32 used here instead)
        w = dequantize_nf4(self.w_idx, self.w_absmax, self.shape)
        y = nn.functional.linear(x, w, self.bias)
        # 4. Add the LoRA branch: s Β· X Β· L1 Β· L2
        return y + self.scale * (self.dropout(x) @ self.lora_A.T @ self.lora_B.T)


torch.manual_seed(0)
layer = QLoRALinear(nn.Linear(128, 64))
print("Trainable parameters:", [n for n, p in layer.named_parameters() if p.requires_grad])

layer.train()
loss = layer(torch.randn(8, 128)).pow(2).mean()
loss.backward()                          # gradients pass through the NF4 weights and reach only LoRA
print(layer.lora_A.grad.shape, layer.lora_B.grad.shape)


# For real use (requires a GPU, bitsandbytes, and peft)
# from transformers import AutoModelForCausalLM, BitsAndBytesConfig
# from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
# bnb_config = BitsAndBytesConfig(
#     load_in_4bit=True,
#     bnb_4bit_quant_type="nf4",              # NF4
#     bnb_4bit_use_double_quant=True,         # double quantization
#     bnb_4bit_compute_dtype=torch.bfloat16,  # compute in BF16
# )
# model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=bnb_config)
# model = prepare_model_for_kbit_training(model)
# model = get_peft_model(model, LoraConfig(r=16, lora_alpha=32, target_modules="all-linear", task_type="CAUSAL_LM"))

FAQ

Q. What is the difference between QLoRA and LoRA?
A.

Both freeze the original weights and train only small low-rank matrices. The difference is how the frozen weights are stored: LoRA keeps them at 16 bits, while QLoRA quantizes them to 4 bits (NF4). As a result, QLoRA needs far less memory; in the paper, a 65B model could be trained on a single 48GB GPU. In the paper's experiments, accuracy was the same as 16-bit LoRA.

Q. How does NF4 differ from an ordinary 4-bit integer (INT4)?
A.

INT4 divides the value range into 16 evenly spaced levels, whereas NF4 determines 16 values from the quantiles of the normal distribution and places the grid densely near 0, where values concentrate. Because trained weights are close to a normal distribution centered at 0, the error is smaller at the same 4 bits. In the paper's comparison, the mean perplexity of 4-bit models was 34.34 with Int4 versus 27.41 with NF4 (with double quantization).

Q. How should the model be used after training?
A.

The 4-bit base model can be combined with the trained LoRA matrices for inference. Since the LoRA matrices are small, separate ones can be stored for each use case and swapped. The paper's Guanaco 7B is about 5GB with 4-bit weights, small enough to fit on a smartphone.

References

  1. T. Dettmers, A. Pagnoni, A. Holtzman, and L. Zettlemoyer, "QLoRA: Efficient Finetuning of Quantized LLMs," arXiv:2305.14314, 2023.
  2. E. J. Hu, Y. Shen, P. Wallis, Z. Allen-Zhu, Y. Li, S. Wang, L. Wang, and W. Chen, "LoRA: Low-Rank Adaptation of Large Language Models," arXiv:2106.09685, 2021.
  3. Hugging Face Transformers Documentation, "Bitsandbytes."