QLoRA
Quantized LoRA
A memory-efficient fine-tuning technique that combines quantization and LoRA.
Quantized LoRA
A memory-efficient fine-tuning technique that combines quantization and LoRA.
QLoRA (Quantized Low-Rank Adaptation) is an innovative fine-tuning technique published in 2023 by Tim Dettmers' team at the University of Washington. It makes it possible to fine-tune a 65B-parameter large language model on a single 48GB GPU, making LLM customization, which previously required hundreds of GB of memory, accessible to ordinary developers. The core idea is to quantize the base model to 4-bit and keep only the trainable LoRA adapters in 16-bit.
QLoRA has three key innovations. First, NF4 (NormalFloat 4-bit) quantization. Unlike ordinary INT4, it is a data type optimized for the normal distribution, minimizing information loss by matching the distribution characteristics of neural network weights. Second, Double Quantization also quantizes the quantization constants (scale factors) themselves, further saving memory. Third, Paged Optimizers automatically swap to CPU RAM when GPU memory runs short, preventing OOM (Out of Memory) errors.
QLoRA's performance is remarkable. In the original paper, the Guanaco-65B model achieved 99.3% of ChatGPT's performance with only 24 hours of fine-tuning. Memory usage is reduced by about 75% compared to Full Fine-tuning, while the quality degradation is minimal. This is because the knowledge of the base model is preserved in quantized form, while the LoRA adapters learn the task-specific knowledge. However, because the quantized base model is also used during inference, there may be a slight performance degradation.
In practice, QLoRA can be easily used through Hugging Face's PEFT and bitsandbytes libraries. Most major open-source LLMs such as Llama, Mistral, and Qwen support QLoRA fine-tuning. It is widely used especially for developing domain-specific chatbots and custom assistants, and you can fine-tune 7Bβ13B models on a personal PC (RTX 3090/4090) and 70B-class models on an A100 80GB. It is supported by default in fine-tuning frameworks such as Axolotl and LLaMA-Factory.
Here is a QLoRA fine-tuning example using Hugging Face PEFT and bitsandbytes:
import torch
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
BitsAndBytesConfig,
TrainingArguments
)
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from trl import SFTTrainer
from datasets import load_dataset
# 1. 4-bit μμν μ€μ (QLoRA ν΅μ¬)
bnb_config = BitsAndBytesConfig(
load_in_4bit=True, # 4-bit μμν νμ±ν
bnb_4bit_quant_type="nf4", # NormalFloat4 (QLoRA κΆμ₯)
bnb_4bit_compute_dtype=torch.bfloat16, # μ°μ°μ bfloat16μΌλ‘
bnb_4bit_use_double_quant=True # Double Quantization
)
# 2. μμνλ λͺ¨λΈ λ‘λ
model_name = "mistralai/Mistral-7B-v0.1"
model = AutoModelForCausalLM.from_pretrained(
model_name,
quantization_config=bnb_config,
device_map="auto",
trust_remote_code=True
)
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenizer.pad_token = tokenizer.eos_token
# 3. LoRA μ€μ
lora_config = LoraConfig(
r=64, # LoRA rank (λμμλ‘ ννλ ₯ μ¦κ°)
lora_alpha=16, # μ€μΌμΌλ§ κ³μ
target_modules=[ # μ΄λν° μ μ© λ μ΄μ΄
"q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"
],
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM"
)
# 4. λͺ¨λΈμ LoRA μ μ©
model = prepare_model_for_kbit_training(model)
model = get_peft_model(model, lora_config)
# νμ΅ κ°λ₯ν νλΌλ―Έν° νμΈ
model.print_trainable_parameters()
# μΆλ ₯: trainable params: 83,886,080 || all params: 7,242,M || 1.16%
# 5. λ°μ΄ν°μ
μ€λΉ (μ: Alpaca νμ)
dataset = load_dataset("tatsu-lab/alpaca", split="train[:1000]")
def format_prompt(example):
return f"""### Instruction:
{example['instruction']}
### Input:
{example['input']}
### Response:
{example['output']}"""
# 6. νμ΅ μ€μ
training_args = TrainingArguments(
output_dir="./qlora-output",
num_train_epochs=3,
per_device_train_batch_size=4,
gradient_accumulation_steps=4,
learning_rate=2e-4,
fp16=True,
logging_steps=10,
save_strategy="epoch",
optim="paged_adamw_8bit" # Paged Optimizer (OOM λ°©μ§)
)
# 7. SFTTrainerλ‘ νμ΅
trainer = SFTTrainer(
model=model,
train_dataset=dataset,
formatting_func=format_prompt,
max_seq_length=512,
tokenizer=tokenizer,
args=training_args
)
trainer.train()
# 8. LoRA μ΄λν° μ μ₯ (μ©λ λ§€μ° μμ: ~100-500MB)
model.save_pretrained("./qlora-adapter")
# 9. μΆλ‘ : μ΄λν° λ‘λνμ¬ μ¬μ©
from peft import PeftModel
base_model = AutoModelForCausalLM.from_pretrained(
model_name, quantization_config=bnb_config, device_map="auto"
)
model = PeftModel.from_pretrained(base_model, "./qlora-adapter")
"Multiple A100s are beyond our budget, but with a single RTX 4090 we can build a domain-specific chatbot by fine-tuning Mistral 7B with QLoRA. Training time is estimated at about 6-8 hours."
"The core of QLoRA is NF4 quantization. Unlike ordinary INT4, it is optimized for the normal distribution, so it minimizes information loss by matching the distribution characteristics of neural network weights. It saves 75% of memory while the performance degradation is around 1-2%."
"When deploying a model fine-tuned with QLoRA, you have two options. You can serve the quantized base plus the LoRA adapter as is, or merge the adapter to create a full-weight model. The latter has faster inference speed."
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free