LoRA and QLoRA for LLMs in Practice
LoRA from scratch showed the idea, a frozen weight plus a trainable low-rank update ; LoRA with PEFT applied it to BERT and wired it into GPT-2; QLoRA built 4-bit NF4 quantization and LoRA on a quantized network from scratch. This lesson is about the decisions you make when the model is a decoder-only LLM: which of its linear layers to adapt, how to choose the rank and , whether the run fits in your GPU's memory, and how adapters are stored, switched and merged. It is the usual way to do the SFT, instruction and preference tuning of the previous lessons on a single GPU.
Where LoRA goes in a Llama-style block
A Llama, Mistral or Qwen block has seven linear layers: the attention projections q_proj, k_proj, v_proj, o_proj, and the SwiGLU feed-forward layers gate_proj, up_proj (width to the MLP width) and down_proj (back to ). Each adapted layer of shape adds parameters. The options people use:
target_modules |
What it adapts | Notes |
|---|---|---|
["q_proj", "v_proj"] |
two attention projections | the setting the original LoRA paper used most (and PEFT's default for many models); fewest parameters |
["q_proj", "k_proj", "v_proj", "o_proj"] |
all of attention | |
"all-linear" |
all seven per block (PEFT excludes the LM head) | the QLoRA paper found adapting every linear layer was needed to match full fine-tuning; most recipes use it today |
The rank sets capacity and the scale of the update; PEFT multiplies by , so with fixed, a larger rank shrinks each direction's step (rsLoRA uses instead to keep it stable across ranks). Common choices are from 8 to 64 with or , learning rates around to for LLMs, and a rank large enough for the task: style and format need little, new knowledge or a new language more. Embeddings and the LM head are left frozen unless you add tokens (chat markers, a new language), in which case they go in modules_to_save or get their own adapter.
The memory budget of a 7B run
PEFT overview counted weights and optimiser state for a Llama-2-7B shape: about 108 GB for full fine-tuning against 14 GB for LoRA and 4 GB for QLoRA. Those numbers leave out the activations, which LoRA does not reduce: to send gradients to the adapters in early blocks, the backward pass needs the activations of every block, frozen or not. The code counts adapter sizes for the three target choices and adds a rough activation estimate: about bytes per token per block in 16-bit with a fused attention kernel (a rule of thumb from GPT-style blocks: Korthikanti et al. 2022 count bytes per block for sequence length , batch and heads, and a fused kernel such as FlashAttention removes the attention-score term; real numbers depend on the implementation), or, with gradient checkpointing, only each block's input ( bytes per token) plus one block's activations recomputed at a time. The logits in float32 and their gradient come on top.
# a Llama-2-7B-shaped model: 32 blocks, width 4096, MLP width 11008, vocabulary 32000
d, ffn, L, V = 4096, 11008, 32, 32000
shapes = {"q_proj": (d, d), "k_proj": (d, d), "v_proj": (d, d), "o_proj": (d, d),
"gate_proj": (d, ffn), "up_proj": (d, ffn), "down_proj": (ffn, d)}
P = L * (sum(i * o for i, o in shapes.values()) + 2 * d) + 2 * V * d + d # blocks + embeddings + LM head + final norm
def lora_params(targets, r):
return L * sum(r * (shapes[t][0] + shapes[t][1]) for t in targets)
choices = {"q, v": ["q_proj", "v_proj"], "q, k, v, o": ["q_proj", "k_proj", "v_proj", "o_proj"], "all-linear": list(shapes)}
print(f"base model: {P / 1e9:.2f} B parameters")
for name, t in choices.items():
print(f" LoRA on {name:10s}: " + " | ".join(f"r={r}: {lora_params(t, r) / 1e6:5.1f} M" for r in (8, 16, 64)))
GB = 1e9
def budget(weight_bits, lora, seq, batch, checkpointing):
weights = P * weight_bits / 8
train_state = 16 * lora # bf16 weight + bf16 grad + fp32 master + Adam m, v
tokens = seq * batch
if checkpointing: # keep each block's input, recompute the rest
acts = L * tokens * d * 2 + tokens * d * 34
else: # rule of thumb: ~34 bytes x width per token per block
acts = L * tokens * d * 34
logits = tokens * V * 4 * 2 # fp32 logits and their gradient
return weights / GB, train_state / GB, (acts + logits) / GB
n = lora_params(choices["all-linear"], 16)
print("\nLoRA r=16 all-linear, sequence 2048: weights | LoRA + Adam | activations | total (GB)")
for label, bits, b, ckpt in [("bf16 base, batch 1", 16, 1, False), ("bf16 base, batch 4", 16, 4, False),
("bf16 base, batch 4, checkpointing", 16, 4, True), ("4-bit base, batch 4, checkpointing", 4.127, 4, True)]:
w, s, a = budget(bits, n, 2048, b, ckpt)
print(f" {label:36s} {w:6.1f} | {s:11.2f} | {a:11.1f} | {w + s + a:6.1f}")base model: 6.74 B parameters
LoRA on q, v : r=8: 4.2 M | r=16: 8.4 M | r=64: 33.6 M
LoRA on q, k, v, o: r=8: 8.4 M | r=16: 16.8 M | r=64: 67.1 M
LoRA on all-linear: r=8: 20.0 M | r=16: 40.0 M | r=64: 159.9 M
LoRA r=16 all-linear, sequence 2048: weights | LoRA + Adam | activations | total (GB)
bf16 base, batch 1 13.5 | 0.64 | 9.7 | 23.8
bf16 base, batch 4 13.5 | 0.64 | 38.6 | 52.7
bf16 base, batch 4, checkpointing 13.5 | 0.64 | 5.4 | 19.5
4-bit base, batch 4, checkpointing 3.5 | 0.64 | 5.4 | 9.5
- Adapters are small whatever you choose. Even rank 64 on every linear layer is 159.9 M parameters, 2.4 % of the model, and its weights, gradients and Adam state take 0.64 GB at rank 16.
- Activations decide the batch size. At sequence length 2048, one sequence needs about 9.7 GB of activations and logits, four need 38.6 GB, more than the 13.5 GB of bf16 weights. Gradient checkpointing (
model.gradient_checkpointing_enable()) cuts that to 5.4 GB for the price of roughly one extra forward pass (about 30 % more compute). - QLoRA moves the weights from 13.5 to 3.5 GB. With checkpointing, a batch of four 2048-token sequences fits in about 10 GB, a 12 to 16 GB consumer GPU, which is what made 7B fine-tuning common. (Real QLoRA keeps embeddings and norms in 16 bits, so the weights are a little larger than the 4.127 bits per parameter used here.)
To reach the batch size you want without the memory, use gradient accumulation: several small micro-batches, one optimiser step.
A tiny Llama, pre-trained, then adapted with LoRA
To run the real API offline, the recorded example builds a LlamaForCausalLM from a config, 2 blocks of width 64 with the real module names, and "pretrains" it from random weights for 300 steps on one character-level task, copying a word (prompt "abc>", answer "abc."). That is the stand-in for a pretrained base: it is not a language model, but it has a skill that LoRA must change. LoRA with , then teaches it to reverse words instead, for 300 steps with the base frozen, once on q_proj and v_proj and once on all linear layers. Scores are exact match of greedy decoding on 200 test words, computed in one batched forward pass.
import random
import torch
from transformers import LlamaConfig, LlamaForCausalLM
from transformers.utils import logging
from peft import LoraConfig, get_peft_model
logging.set_verbosity_error()
VOCAB = "_abcdefghijklmnopqrstuvwxyz>."
stoi = {c: i for i, c in enumerate(VOCAB)}
rng = random.Random(0)
def word(): return "".join(rng.choice("abcdefghijklmnopqrstuvwxyz") for _ in range(rng.randint(3, 6)))
train_words, test_words = [word() for _ in range(2000)], [word() for _ in range(200)]
def batch(pairs): # (prompt word, response) -> input ids and labels, prompt masked
rows = [[stoi[c] for c in w + ">" + r + "."] for w, r in pairs]
T = max(map(len, rows))
x = torch.tensor([r + [0] * (T - len(r)) for r in rows])
y = torch.tensor([[-100] * (len(w) + 1) + r[len(w) + 1:] + [-100] * (T - len(r)) for (w, _), r in zip(pairs, rows)])
return x, y # Llama shifts the labels itself
def train(model, task, steps, lr, seed=1):
opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=lr)
g = random.Random(seed)
model.train()
for _ in range(steps):
x, y = batch([(w, task(w)) for w in g.sample(train_words, 64)])
loss = model(input_ids=x, labels=y).loss
opt.zero_grad(); loss.backward(); opt.step()
return loss.item()
@torch.no_grad()
def accuracy(model, task): # exact match of greedy decoding, in one batched forward pass:
model.eval() # greedy gives the answer iff the argmax is right at every answer step
x, y = batch([(w, task(w)) for w in test_words])
pred = model(input_ids=x).logits.argmax(-1)[:, :-1]
return ((pred == y[:, 1:]) | (y[:, 1:] == -100)).all(1).float().mean().item()
copy_, reverse = (lambda w: w), (lambda w: w[::-1])
cfg = LlamaConfig(vocab_size=len(VOCAB), hidden_size=64, intermediate_size=172, num_hidden_layers=2, num_attention_heads=4,
num_key_value_heads=4, max_position_embeddings=32, pad_token_id=0, bos_token_id=None, eos_token_id=stoi["."])
torch.manual_seed(0)
base = LlamaForCausalLM(cfg)
print("base parameters:", f"{base.num_parameters():,}", "| linear layers per block:", [n.split(".")[-1] for n, m in base.model.layers[0].named_modules() if isinstance(m, torch.nn.Linear)])
train(base, copy_, 300, 3e-3)
print(f"base after 'pretraining' on copying: copy {accuracy(base, copy_):.3f} | reverse {accuracy(base, reverse):.3f}")
state = {k: v.clone() for k, v in base.state_dict().items()}
for targets in [["q_proj", "v_proj"], "all-linear"]:
base.load_state_dict(state)
model = get_peft_model(base, LoraConfig(task_type="CAUSAL_LM", r=8, lora_alpha=16, target_modules=targets))
n = sum(p.numel() for p in model.parameters() if p.requires_grad)
torch.manual_seed(0)
train(model, reverse, 300, 3e-3)
print(f"LoRA r=8 on {str(targets):20s}: trainable {n:6,} | reverse {accuracy(model, reverse):.3f} | copy {accuracy(model, copy_):.3f}")
base = model.unload() # remove the LoRA layers, keep the base objectbase parameters: 102,848 | linear layers per block: ['q_proj', 'k_proj', 'v_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj']
base after 'pretraining' on copying: copy 0.975 | reverse 0.015
LoRA r=8 on ['q_proj', 'v_proj']: trainable 4,096 | reverse 0.805 | copy 0.015
LoRA r=8 on all-linear : trainable 19,520 | reverse 1.000 | copy 0.015
The base copies 0.975 of the test words and reverses almost none (0.015: palindromes and chance). LoRA on q_proj and v_proj (4,096 trainable numbers, per layer, 4 layers) teaches reversal to 0.805; on all linear layers (19,520 numbers) it reaches 1.000 in the same 300 steps. Reversing needs the attention pattern to change and the MLPs to map positions differently; with only q and v adapted, the frozen MLPs and output projections limit what the update can express. In both cases the copy skill is gone while the adapter is active (0.015): the adapter replaces the behaviour for this prompt format, which is what you want here and a warning about forgetting in general.
Several adapters on one base, and merging
One base model can carry many adapters and switch between them per request: one per customer, per task or per language. The second recorded example trains two adapters on the same frozen base, "reverse" and "sort" (sort the letters), switches between them, turns them off, and finally merges one into the weights:
import random
import torch
from transformers import LlamaConfig, LlamaForCausalLM
from transformers.utils import logging
from peft import LoraConfig, get_peft_model
logging.set_verbosity_error()
VOCAB = "_abcdefghijklmnopqrstuvwxyz>."
stoi = {c: i for i, c in enumerate(VOCAB)}
rng = random.Random(0)
def word(): return "".join(rng.choice("abcdefghijklmnopqrstuvwxyz") for _ in range(rng.randint(3, 6)))
train_words, test_words = [word() for _ in range(2000)], [word() for _ in range(200)]
def batch(pairs): # (prompt word, response) -> input ids and labels, prompt masked
rows = [[stoi[c] for c in w + ">" + r + "."] for w, r in pairs]
T = max(map(len, rows))
x = torch.tensor([r + [0] * (T - len(r)) for r in rows])
y = torch.tensor([[-100] * (len(w) + 1) + r[len(w) + 1:] + [-100] * (T - len(r)) for (w, _), r in zip(pairs, rows)])
return x, y # Llama shifts the labels itself
def train(model, task, steps, lr, seed=1):
opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=lr)
g = random.Random(seed)
model.train()
for _ in range(steps):
x, y = batch([(w, task(w)) for w in g.sample(train_words, 64)])
loss = model(input_ids=x, labels=y).loss
opt.zero_grad(); loss.backward(); opt.step()
return loss.item()
@torch.no_grad()
def accuracy(model, task): # exact match of greedy decoding, in one batched forward pass:
model.eval() # greedy gives the answer iff the argmax is right at every answer step
x, y = batch([(w, task(w)) for w in test_words])
pred = model(input_ids=x).logits.argmax(-1)[:, :-1]
return ((pred == y[:, 1:]) | (y[:, 1:] == -100)).all(1).float().mean().item()
copy_, reverse, sort = (lambda w: w), (lambda w: w[::-1]), (lambda w: "".join(sorted(w)))
cfg = LlamaConfig(vocab_size=len(VOCAB), hidden_size=64, intermediate_size=172, num_hidden_layers=2, num_attention_heads=4,
num_key_value_heads=4, max_position_embeddings=32, pad_token_id=0, bos_token_id=None, eos_token_id=stoi["."])
torch.manual_seed(0)
base = LlamaForCausalLM(cfg)
print("base parameters:", f"{base.num_parameters():,}", "| linear layers per block:", [n.split(".")[-1] for n, m in base.model.layers[0].named_modules() if isinstance(m, torch.nn.Linear)])
train(base, copy_, 300, 3e-3)
# two adapters on one base: "reverse" and "sort", each trained with only its own LoRA weights
cfg_lora = LoraConfig(task_type="CAUSAL_LM", r=8, lora_alpha=16, target_modules="all-linear")
model = get_peft_model(base, cfg_lora, adapter_name="reverse")
torch.manual_seed(0); train(model, reverse, 300, 3e-3)
model.add_adapter("sort", cfg_lora)
model.set_adapter("sort") # makes "sort" active and the only trainable adapter
torch.manual_seed(0); train(model, sort, 300, 3e-3)
for name in ["reverse", "sort"]:
model.set_adapter(name)
print(f"adapter {name:7s}: reverse {accuracy(model, reverse):.3f} | sort {accuracy(model, sort):.3f} | copy {accuracy(model, copy_):.3f}")
with model.disable_adapter():
print(f"adapters off : reverse {accuracy(model, reverse):.3f} | sort {accuracy(model, sort):.3f} | copy {accuracy(model, copy_):.3f}")
model.set_adapter("reverse")
x, _ = batch([(w, reverse(w)) for w in test_words])
with torch.no_grad():
before = model(input_ids=x).logits
merged = model.merge_and_unload(adapter_names=["reverse"]) # W0 + (alpha / r) B A folded into each weight
with torch.no_grad():
after = merged(input_ids=x).logits
print(type(merged).__name__, "| same logits up to 1e-4:", bool((after - before).abs().max() < 1e-4),
"| parameters:", f"{merged.num_parameters():,}", "| reverse:", f"{accuracy(merged, reverse):.3f}")base parameters: 102,848 | linear layers per block: ['q_proj', 'k_proj', 'v_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj']
adapter reverse: reverse 1.000 | sort 0.080 | copy 0.015
adapter sort : reverse 0.075 | sort 0.755 | copy 0.050
adapters off : reverse 0.015 | sort 0.050 | copy 0.975
LlamaForCausalLM | same logits up to 1e-4: True | parameters: 102,848 | reverse: 1.000
Each adapter does its own task (reverse 1.000 with "reverse", sort 0.755 with "sort"; sorting is harder for a model this small) and with the adapters disabled the base copies again (0.975), untouched by either training. Merging folds into every adapted weight and returns a plain LlamaForCausalLM with the base's parameter count (102,848), the same logits up to float32 rounding and the same accuracy. Merge for deployment when one adapter will be used everywhere (no extra latency, any inference engine can load it); keep adapters separate when you switch between them. Serving engines such as vLLM can batch requests for different LoRA adapters on one base model.
QLoRA with bitsandbytes (needs a CUDA GPU, not run here)
The full QLoRA recipe loads the frozen base in 4-bit NF4 with bitsandbytes, prepares it for training (freezes the base, casts the remaining 16-bit weights such as the norms to float32, enables gradient checkpointing and input gradients), and adds LoRA on all linear layers. bitsandbytes needs a CUDA GPU, so this is shown without running:
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True,
bnb_4bit_compute_dtype=torch.bfloat16) # store in NF4, compute in bf16
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", quantization_config=bnb, device_map="auto")
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=True)
model = get_peft_model(model, LoraConfig(task_type="CAUSAL_LM", r=16, lora_alpha=32, lora_dropout=0.05,
target_modules="all-linear"))
model.print_trainable_parameters() # about 40 M of 6.7 B (0.6 %)
# then SFT as in the earlier lessons, e.g. with TRL's SFTTrainer and optim="paged_adamw_8bit"Two practical consequences of 4-bit training: the adapter is trained against the quantized base, so for best quality serve it on the same quantized base, or merge into a 16-bit copy of the base and check the quality again; and you cannot merge directly into NF4 weights without re-quantizing, which adds rounding error.
Pitfalls
- Target names from the wrong architecture.
q_projis Llama's name; GPT-2 has a fusedc_attn, Falconquery_key_value. Print the modules before writing the config. - Too small a rank or too few targets. q and v at rank 8 can be too little for tasks that change what the model does (the example: 0.805 against 1.000). Try
"all-linear"before raising the rank. - Changing but not . The update is scaled by , so doubling at fixed halves the scale; retune the learning rate, or keep fixed.
- Counting only weights. Activations at long sequence lengths often exceed the weights; use gradient checkpointing, shorter sequences, packing and gradient accumulation.
- New tokens without trainable embeddings. Added special tokens start with random or mean embeddings; put
embed_tokensandlm_headinmodules_to_save(or the new rows will never be learned). - Adapter and base out of sync. An adapter only works with the exact base revision (and quantization) it was trained on; store both names in the adapter config and model card.
Practice
- How many parameters does LoRA with add to one
down_projof the 7B shape (11,008 to 4,096)? - You have a 24 GB GPU and want LoRA on a 7B model with sequence length 4096. Using the lesson's estimates, which settings would you try first?
- Why did adapting only
q_projandv_projreach 0.805 while all linear layers reached 1.000? - You serve 50 customers, each with its own adapter for the same base. Merge or not?
Answers
- , per block; 7.7 million over 32 blocks.
- bf16 weights (13.5 GB) leave about 10 GB; without checkpointing one 4096-token sequence needs about GB of activations and logits, too much. So: gradient checkpointing (then about 2.7 GB for one sequence: block inputs, one block's activations and the logits), batch 1 with gradient accumulation, and if that is still tight, QLoRA (3.5 GB of weights).
- With q and v adapted, attention can change where it looks and what it reads, but the MLPs and output projections stay exactly as trained for copying; the low-rank updates in two layers per block were not enough to re-route the computation in 300 steps. Adapting every layer gives more capacity in more places.
- Do not merge: keep one base in memory and load the 50 adapters (tens of MB each for a 7B model), choosing one per request; merging would need 50 full copies of the model.
Test yourself
Which modules does target_modules="all-linear" adapt in a Llama block?
- Only q_proj and v_proj
- The four attention projections and the three MLP projections (not the LM head)
- The embeddings and the LM head
- The layer norms
Why does LoRA not reduce activation memory much?
- Because the adapters are large
- Because the backward pass still needs the activations of every block to send gradients to the adapters in earlier blocks
- Because LoRA uses float32
- It does: activations shrink by the rank ratio
In the lesson's estimate for a 7B model at sequence length 2048 and batch 4, what changed the total most?
- The LoRA rank
- Gradient checkpointing (activations from 38.6 GB to 5.4 GB)
- The choice of target modules
- The Adam state
What does merge_and_unload() return for a LoRA-adapted Llama?
- The adapter weights only
- A plain LlamaForCausalLM with in each adapted weight and the base's parameter count
- A quantized model
- A model with both adapters active