Sub topic 3
QLoRA: Fine-Tuning on a 4-Bit Base
This chapter assumes basic PyTorch, transformer inference, and matrix multiplication. QLoRA combines quantization, storing weights with fewer bits, and LoRA, training small adapter matrices while the base model stays frozen.
QLoRA on a 4-Bit Base
A 4-bit base model uses much less GPU memory than a full-precision model. The weights are stored in NormalFloat 4 (NF4), while calculations and trainable adapters use a higher-precision type such as bfloat16.
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
base_id = "Qwen/Qwen2.5-0.5B-Instruct"
quantization = 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(
base_id, quantization_config=quantization, device_map="auto"
)
model = prepare_model_for_kbit_training(model)
model = get_peft_model(
model,
LoraConfig(
r=16, lora_alpha=32, lora_dropout=0.05,
target_modules="all-linear", task_type="CAUSAL_LM"
),
)
model.print_trainable_parameters()QLoRA needs a supported CUDA setup and the bitsandbytes package. Quantization reduces memory, but it does not make poor training data or an unsuitable base model effective.
Evaluate Against the Base Model
Keep a held-out set that training never sees. Run identical prompts through the base model and the adapted model. Compare task accuracy, response quality, formatting, and unwanted behavior. A lower training loss alone does not prove improvement.
Save, Load, and Merge
An adapter checkpoint stores only the LoRA parameters. It requires the same compatible base model when loaded.
from transformers import AutoModelForCausalLM
from peft import PeftModel
base = AutoModelForCausalLM.from_pretrained(base_id)
adapted = PeftModel.from_pretrained(base, "lora-out/adapter")
merged = adapted.merge_and_unload()
merged.save_pretrained("merged-model")A merged model is simpler to deploy, but merging can increase storage and removes the convenience of switching adapters.
Serving Choices
Serve an adapter when several behaviors share one base model or when adapters must be updated independently. Serve a merged model when the runtime does not support PEFT or when one fixed behavior is needed. Always save the tokenizer with the deployed model.
> callout warning > Do not evaluate a merged model with a different tokenizer, base revision, or chat template.
Common Failures and Fixes
- Out-of-memory: lower sequence length or batch size, use gradient accumulation, or choose a smaller base model.
- No learning: verify that LoRA parameters have
requires_grad=Trueand that target module names match the model. - Bad responses: check the chat template and train only on the intended assistant responses.
- Overfitting: reduce epochs, increase data, or add LoRA dropout.
- Broken loading: record the exact base model revision and adapter configuration.
Exercise
Why does QLoRA use less memory than full fine-tuning?
Show answer
It freezes a 4-bit base model and trains only small, higher-precision LoRA adapters.