Sub topic 10
QLoRA: fine-tuning on a 4-bit base
This chapter assumes you know how LoRA adapters work, how to attach one with PEFT, and what a 16-bit versus a 4-bit weight means at a basic level. QLoRA applies LoRA on top of a base model whose frozen weights are stored in 4 bits. You use it when the base model does not fit in GPU memory at 16-bit precision.
What QLoRA changes
LoRA already removes optimizer state and gradients for the base weights. The base weights themselves still take memory: about 2 bytes per parameter in bf16. QLoRA shrinks that part by storing the frozen weights in 4-bit NF4 format, which is about 0.5 bytes per parameter. A 7B model drops from roughly 14 GB of weights to roughly 4 GB.
The adapter matrices A and B stay in higher precision (16-bit or 32-bit), and they are the only trainable parameters. During the forward pass, each 4-bit weight block is dequantized to the compute dtype, used in the matrix multiplication, and discarded. Gradients flow through the dequantized values to the adapter. The base weights never change.
The three quantization settings
QLoRA relies on three techniques, each controlled by a field in BitsAndBytesConfig.
| Setting | Value | What it does |
|---|---|---|
| `bnb_4bit_quant_type` | `"nf4"` | NormalFloat4 places its 16 levels to match the roughly normal distribution of pretrained weights. It usually loses less accuracy than plain 4-bit floats. |
| `bnb_4bit_use_double_quant` | `True` | Quantizes the per-block scaling constants too, saving a small amount more memory. |
| `bnb_4bit_compute_dtype` | `torch.bfloat16` | The precision used for the matrix math after dequantization. |
Loading and attaching the adapter
import torch
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",
bnb_4bit_use_double_quant=True,
bnb_4bit_compute_dtype=torch.bfloat16,
)
model = AutoModelForCausalLM.from_pretrained(
"Qwen/Qwen2.5-0.5B-Instruct",
quantization_config=bnb_config,
device_map="auto",
)
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"),
)
model.print_trainable_parameters()Three details matter here:
bitsandbytesneeds a CUDA GPU, so this code will not run on a CPU-only machine.prepare_model_for_kbit_trainingcasts some non-quantized layers (such as layer norms) to float32 and enables input gradients so that gradient checkpointing works.target_modules="all-linear"attaches adapters to every linear layer except the output head. The QLoRA authors found that adapting all linear layers recovers quality that attention-only adapters miss at 4 bits.
From here, training works as in the previous chapter: pass the quantized model, or the same model name with a BitsAndBytesConfig in model_init_kwargs, to SFTTrainer.
Trade-offs and common errors
QLoRA saves memory but costs time. Dequantizing on every forward pass makes training slower than LoRA on a 16-bit base, often by 20 to 40 percent.
Quality is usually close to 16-bit LoRA but not identical, because the adapter learns to compensate for quantization error in the 4-bit base.
Common problems:
- Merging into a 4-bit model. Merging adds the update to quantized weights and rounds them again. To merge cleanly, reload the base model in bf16, load the adapter on it, then call
merge_and_unload(). - Mismatch at inference. An adapter trained on a 4-bit base works best when served on the same 4-bit base. Evaluate the exact configuration you plan to deploy.
- Out-of-memory despite 4-bit. Activations and the optimizer state for the adapter still use memory. Lower the batch size, shorten the sequence length, or enable gradient checkpointing.
- No bitsandbytes CUDA support. Import errors usually mean a version mismatch between
bitsandbytes, PyTorch, and the CUDA driver.
Exercise
A 7B-parameter base model takes about 14 GB in bf16. Roughly how much memory do its weights take in 4-bit NF4, and why is it still wrong to say QLoRA training needs only that much GPU memory?
Show answer
About 3.5 to 4 GB for the weights (0.5 bytes per parameter plus quantization constants). Training also needs memory for activations, the adapter's weights, gradients and optimizer state, and the dequantization buffers, so total usage is higher than the weights alone.
Exercise
You trained an adapter on a 4-bit base and want a standalone model for deployment. What is the recommended way to merge it?
Show answer
Reload the base model in bf16 (not 4-bit), load the adapter with PeftModel.frompretrained, call mergeand_unload(), and save the result. Then evaluate the merged model, since its outputs differ slightly from the 4-bit version you trained against.