πŸ€– AI/ML

QLoRA

Quantized LoRA

A memory-efficient fine-tuning technique that combines quantization and LoRA.

πŸ“– Detailed Explanation

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.

πŸ’» Code Example

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")

πŸ—£οΈ Say It Like This in Practice

πŸ’Ό In a Meeting

"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."

πŸ‘” In an Interview

"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%."

πŸ”§ In a Technical Discussion

"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

⚠️ Common Mistakes & Cautions

❌
Setting the rank too low: A low rank such as r=8 is sufficient for simple tasks, but learning complex domain knowledge requires r=32~64 or higher. If the rank is low, the learning capacity is insufficient, resulting in underfitting.
❌
bitsandbytes version mismatch: If the CUDA version and the bitsandbytes version do not match, 4-bit quantization fails. Use CUDA 11.8 or higher and the latest bitsandbytes (0.41+), and update with pip install bitsandbytes --upgrade.
βœ…
Best Practice: Including MLP layers (gate_proj, up_proj, down_proj) in target_modules in addition to the attention layers (q_proj, k_proj, v_proj, o_proj) improves performance. You can also save additional memory with gradient_checkpointing=True.

πŸ”— Related Terms

πŸ“š Learn More