Sub topic 10
QLoRA: fine-tuning on a 4-bit base
This chapter assumes you can attach a LoRA adapter with PEFT and run a training loop with SFTTrainer. It also assumes you know what a data type such as float16 or bfloat16 means for memory. QLoRA changes how the frozen base weights are stored. It does not change what LoRA trains.
What QLoRA changes
LoRA freezes the base weights and trains small adapter matrices. The frozen weights still take memory, though. A 7-billion-parameter model in 16-bit precision needs about 14 GB just for weights, before activations, gradients for the adapters, and optimizer state.
QLoRA (Quantized LoRA) stores the frozen base weights in 4 bits and keeps the adapters in higher precision. The base weights are dequantized to a higher-precision compute type one layer at a time during the forward and backward passes. Gradients flow through the frozen 4-bit weights into the adapter matrices, and only the adapters are updated.
| Item | LoRA (16-bit base) | QLoRA (4-bit base) |
|---|---|---|
| Frozen base weights | 16 bits per parameter | about 4 bits per parameter, plus a small quantization overhead |
| Adapter weights | trainable, 16 or 32 bits | trainable, 16 or 32 bits |
| Optimizer state | adapters only | adapters only |
| Speed per step | baseline | slower, because of dequantization |
| Hardware | any GPU that fits the model | CUDA GPU with bitsandbytes |
For a 7B model, the weights drop from roughly 14 GB to roughly 4 to 5 GB. That is the difference between needing a data-center GPU and fitting on a consumer card with 16 to 24 GB.
The three ingredients of the 4-bit format
QLoRA, introduced by Dettmers et al. in 2023, combines three techniques. Each maps to a setting in BitsAndBytesConfig.
- NF4 (4-bit NormalFloat). Pretrained weights are roughly normally distributed. NF4 places its 16 representable values at quantiles of a normal distribution, so each value is used about equally often. This loses less information than evenly spaced 4-bit integers. Set it with
bnb_4bit_quant_type="nf4". The alternative is"fp4", which is rarely the better choice. - Double quantization. Weights are quantized in blocks (for example 64 values), and each block stores a scale factor. Those scale factors are themselves quantized. This saves roughly 0.4 bits per parameter. Set it with
bnb_4bit_use_double_quant=True. - Paged optimizers. Optimizer state can spike in memory when a batch has long sequences. Paged optimizers move that state between GPU and CPU memory on demand to avoid out-of-memory errors. You enable them by choosing an optimizer such as
paged_adamw_8bitin the training arguments.
Setting up the 4-bit model
This code needs a CUDA GPU and the bitsandbytes package. It does not run on CPU-only machines.
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()The pieces do the following.
load_in_4bit=Truereplaces eachnn.Linearlayer with a 4-bit linear layer. The weights are quantized as they are loaded, so the full 16-bit model never has to fit on the GPU.bnb_4bit_compute_dtypeis the precision used for the matrix multiplications after dequantization. It is not the storage precision. Usetorch.bfloat16on GPUs that support it (Ampere or newer). On older GPUs usetorch.float16. The default is float32, which is slower and uses more memory.device_map="auto"places the model on available devices.prepare_model_for_kbit_trainingcasts layers such as layer norms to float32 for stability and enables input gradients so gradient checkpointing works. Call it beforeget_peft_model.target_modules="all-linear"attaches adapters to every linear layer except the output head. The original QLoRA paper found that adapting all linear layers matched full 16-bit fine-tuning quality better than adapting only attention projections.
The printed count shows trainable parameters as a tiny fraction of the total. The model's total count may look smaller than you expect for a 4-bit model, because 4-bit weights are packed two per byte and the reported parameter count can reflect the packed storage.
Training with SFTTrainer
Training uses the same flow as the previous chapter. You pass the quantization setup through model_init_kwargs and the adapter through peft_config. The following configuration shows the settings that matter for QLoRA.
import torch
from datasets import Dataset
from peft import LoraConfig
from transformers import BitsAndBytesConfig
from trl import SFTConfig, SFTTrainer
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True,
bnb_4bit_compute_dtype=torch.bfloat16,
)
train_ds = Dataset.from_list([
{"messages": [
{"role": "user", "content": "Summarize: LoRA trains small low-rank matrices."},
{"role": "assistant", "content": "LoRA adapts a model by training only small low-rank matrices."},
]},
])
trainer = SFTTrainer(
model="Qwen/Qwen2.5-0.5B-Instruct",
train_dataset=train_ds,
args=SFTConfig(
output_dir="qlora-out",
num_train_epochs=1,
per_device_train_batch_size=1,
gradient_accumulation_steps=8,
gradient_checkpointing=True,
learning_rate=2e-4,
optim="paged_adamw_8bit",
bf16=True,
logging_steps=1,
model_init_kwargs={
"quantization_config": bnb_config,
"device_map": "auto",
},
),
peft_config=LoraConfig(r=16, lora_alpha=32, target_modules="all-linear", task_type="CAUSAL_LM"),
)
trainer.train()
trainer.save_model("qlora-out/adapter")Notes on these settings:
- When you pass a model name to
SFTTrainerwith apeft_configand a quantized model, the trainer prepares the model for k-bit training for you. If you load the model yourself, callprepare_model_for_kbit_trainingas shown earlier. gradient_checkpointing=Truerecomputes activations during the backward pass instead of storing them. It cuts activation memory sharply at the cost of roughly 20 to 30 percent more compute. With 4-bit bases, activations often dominate memory, so this setting usually matters.gradient_accumulation_steps=8gives an effective batch size of 8 while holding one example in memory at a time.bf16=Trueshould match the compute dtype. Mixing a float16 compute dtype withbf16=Trueis a common source of confusing dtype warnings.- The learning rate of 2e-4 is a typical LoRA and QLoRA value. It is much higher than full fine-tuning rates because only the small adapter learns.
- The saved directory contains only the adapter weights and config. The 4-bit base is not saved.
Memory budget
Memory use has four parts. Estimating them tells you whether a run will fit.
| Part | Depends on | Effect of QLoRA |
|---|---|---|
| Base weights | parameter count and bits per weight | cut by about 4x versus 16-bit |
| Adapter weights, gradients, optimizer state | rank and number of target modules | same as LoRA, small |
| Activations | batch size, sequence length, depth | unchanged, reduced by gradient checkpointing |
| Temporary dequantized layer | width of one layer | small, one layer at a time |
If a run still runs out of memory, reduce max_length or the per-device batch size first. Lowering the rank saves little, because adapter memory is already small compared with the base and the activations.
Merging and deployment caveats
The adapter you trained was fitted against 4-bit weights, which are slightly different from the original 16-bit weights. This creates a decision when you deploy.
- Keep the adapter separate and load it on a 4-bit base. This reproduces the training conditions exactly. It is the safest choice for evaluation.
- Merge into a 16-bit base. Load the original model in float16 or bfloat16, attach the adapter with
PeftModel.from_pretrained, and callmerge_and_unload(). This is the common route. It is not mathematically identical to what you trained against, because the base is no longer quantized. Quality is usually close, but you should re-evaluate the merged model rather than assume it. - Do not merge into the 4-bit weights directly. Merging adds a small update to quantized weights, which requires requantizing and loses precision. Dequantize first or merge into a full-precision copy.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Error about bitsandbytes needing a GPU, or "CUDA Setup failed" | No CUDA device, or an incompatible bitsandbytes install | Run on a CUDA GPU and reinstall bitsandbytes for your CUDA version |
| Warning that the input requires grad is not set, or loss does not change | Skipped `prepare_model_for_kbit_training` with gradient checkpointing on | Call it before `get_peft_model`, or let `SFTTrainer` do it |
| Dtype mismatch errors or NaN loss | Compute dtype and `bf16`/`fp16` flags disagree | Use bfloat16 for both, or float16 for both |
| Out of memory despite 4-bit base | Long sequences, large batch, no gradient checkpointing | Enable checkpointing, shorten `max_length`, accumulate gradients |
| Quality worse than expected after merging | Adapter trained on 4-bit weights, merged into 16-bit | Re-evaluate, or serve with the 4-bit base |
| Training much slower than LoRA | Dequantization on each forward pass and checkpointing | Expected. Use LoRA if memory allows |
When to choose QLoRA
QLoRA trades speed for memory. Pick it when the 16-bit model does not fit on your GPU with room for activations. If the model fits comfortably with plain LoRA, plain LoRA trains faster and avoids the quantization mismatch at merge time. Quantization error is small for most tasks, but evaluate on your own held-out data instead of relying on published results.
Exercise
You load a 7B model with load_in_4bit=True and bnb_4bit_compute_dtype=torch.bfloat16. Which parts of the model are stored in 4 bits, which are trained, and what is the role of the compute dtype?
Show answer
The frozen base weights are stored in 4-bit NF4 format. The LoRA adapter matrices A and B are separate parameters kept in higher precision, and only they are trained. The compute dtype is the precision used for matrix multiplications: each 4-bit weight block is dequantized to bfloat16 on the fly for the forward and backward passes, then discarded. It does not change how the weights are stored.
Exercise
You trained an adapter with QLoRA and now want a standalone model with no PEFT dependency. Describe a safe way to produce it, and name what you should do before shipping it.
Show answer
Load the original base model in bfloat16 or float16 (not 4-bit), attach the adapter with PeftModel.from_pretrained, call merge_and_unload(), and save the result along with the tokenizer. Because the adapter was trained against quantized weights, the merged model differs slightly from what you trained, so evaluate it on held-out data and compare it with the adapter on the 4-bit base before shipping.