AI Hints
Home›Fine-Tuning LLMs Tutorial›Quantization and QLoRA
Fine-Tuning LLMs · Lesson 60 of 120

QLoRA

4-bit model + LoRA.

⏱ 2 min read▶ Video at 1:33:37🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

QLoRA is one of the most important ideas in fine-tuning. It combines two tricks. Load the frozen model in four bits. And train LoRA adapters on top, in sixteen bits. Suddenly, big models fit on one GPU.

  • One of the most important ideas
  • 4-bit frozen model
  • 16-bit LoRA on top

How QLoRA works

Here's how it works. First, the base model is loaded in NF4, using a quarter of the memory. It stays frozen. LoRA adapters are added, in b float sixteen. During each step, the needed weights are briefly turned back into sixteen bits, for the maths. Only the adapters are updated.

  1. Loadbase model in NF4
  2. Freezethe 4-bit weights
  3. AddLoRA in bfloat16
  4. Computedequantize on the fly
  5. Updateonly the adapters

QLoRA in code

Here's what QLoRA looks like in code. It needs an NVIDIA GPU, and the bits and bytes library, so we show it, rather than run it on our laptop. Bits and bytes config asks for four bit NF4, computing in b float sixteen. Double quant also shrinks the scales. We load an eight billion model with that config. Prepare model for k bit training gets it ready. And the rest is exactly the same as our LoRA code.

qlora.pypython
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from peft import LoraConfig, prepare_model_for_kbit_training
from trl import SFTTrainer, SFTConfig
from chat import data

bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
                         bnb_4bit_compute_dtype=torch.bfloat16,
                         bnb_4bit_use_double_quant=True)
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B-Instruct",
                                             quantization_config=bnb, device_map="auto")
model = prepare_model_for_kbit_training(model)
lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
                  target_modules="all-linear", task_type="CAUSAL_LM")
trainer = SFTTrainer(model=model, train_dataset=data["train"], peft_config=lora,
                     args=SFTConfig(output_dir="llama-tickets", bf16=True))
trainer.train()

Summary

Let's recap. QLoRA loads the frozen model in four bits, and trains sixteen bit LoRA adapters. It needs an NVIDIA GPU, and bits and bytes. And it lets an eight billion model train on one card. Next, planning GPU memory.

Key takeaways
  • 4-bit base + LoRA
  • BitsAndBytesConfig
  • 8B on one GPU
Next up: GPU Memory Budget — will it fit?