Chapter 6 · Post-training and Alignment 6.2
LoRA Fine-Tuning in Practice
Over fifty training runs of Qwen2.5-0.5B on banking77: the formula, the parameter count and a from-scratch implementation, then learning rate, rank, target modules, epochs, full fine-tuning and QLoRA compared, and the pitfalls of merging and deployment, with code and numbers behind every claim.
After this page you will be able to
- Write down the LoRA forward pass, compute the number of trainable parameters for any configuration, and explain why B=0 at initialization and why A gets exactly zero gradient at the first step.
- Run the full loop "data, training, evaluation, merge" with
pefton a real model, and read what each step does. - Decide which knob to turn first in a LoRA run: learning rate, rank, α, target modules or number of epochs. Know how much each one matters and what it costs.
- Measure both the gain on the target task and the loss of general ability, and choose a configuration by both, not by training loss.
- State the trade-offs between LoRA, full fine-tuning and QLoRA, and know the precision and template traps that come with merging weights.
On this page
- The Short Version
- What LoRA Does
- The forward pass and the parameter count
- Try it: how many parameters does LoRA add, and how much memory does it save?
- From scratch: a LoRALinear
- The Setup: How to Measure a LoRA Run
- A Minimal Training Script
- Baseline: could a better prompt do the job without fine-tuning?
- Tuning the Knobs: A Set of Measurements
- Learning rate: the most sensitive knob
- Rank and α: the capacity knob, and also the forgetting knob
- Target modules: where matters more than how many parameters
- α and the learning rate are not the same knob
- Epochs and dropout
- LoRA vs. Full Fine-Tuning: Accuracy, the Structure of the Update, and Cost
- With the same data, how far can full fine-tuning go?
- Is the update of full fine-tuning low-rank?
- Memory and speed: where LoRA saves
- Merging, Deployment and QLoRA
- Merging the adapter: at what precision
- QLoRA: store the frozen base in 4 bits
- What 4 bits cost a small model: a simulation
- Troubleshooting
- Summary and Exercises
- Quick self-test
- Further Reading
- FAQ
Every conclusion on this page comes from one set of experiments: Qwen2.5-0.5B fine-tuned on banking77 (77 customer-service intents) with 20 examples per class, over fifty training runs. The numbers are only responsible for this setting. A different model or task may show the same trends but will not have the same best values, and each section says which findings look robust and which are just observations from this setup. For the paper itself, see the LoRA paper breakdown.
The Short Version
- The default configuration works, but it is not the best. , , learning rate 2e-4, all 7 linear layers and 3 epochs give 85.8% on banking77 (three seeds: 85.8%, 85.9%, 86.1%); with the same prompt, the untuned base model gets none right (0.0%).
- The learning rate is the most sensitive knob, and it has a cliff. From 2e-5 to 5e-4 accuracy climbs from 47.6% to 86.9% and perplexity from 17.66 to 21.28; at 1e-3 the target task still scores 87.3%, but ARC-Easy multiple choice is down to 23.8%, and at 2e-3 perplexity passes two million.
- The role of rank is confounded by how is set. With fixed, ranks from 1 to 128 all land between 85.2% and 86.4%, so rank itself does little; with , accuracy rises with rank (rank 1: 72.9%, rank 64: 87.8%) and so does perplexity, because in that setup a larger rank acts like a larger learning rate.
- Where matters more than how many parameters. Adapting only the three MLP matrices reaches 85.5%, nearly matching all 7 matrices at 85.8%; adapting only q and v in attention reaches 52.0%.
- The longer you train, the more is learned and the more is forgotten. 1 epoch gives 69.8%, 3 epochs 85.8%, 10 epochs 87.5% (training loss down to 0.0003), and perplexity goes from 19.10 to 19.98.
- The target-task metric alone will fool you. LoRA and full fine-tuning each have a learning rate at which banking77 accuracy is still above 85% while multiple-choice accuracy is back at chance (1e-3 for LoRA, 5e-5 for full fine-tuning). Every fine-tune should also measure something outside the target.
- Full fine-tuning is not the weaker control. At a learning rate of 1e-5 (one twentieth of LoRA’s default) it scores 87.9% with perplexity 17.58 and multiple choice 72.8%; the nine LoRA settings with accuracy of 86.5% or more bottom out at a perplexity of 18.90. LoRA saves memory (3.5 GiB against 7.5 GiB at batch size 4), time and size (a 35 MB adapter against 1.98 GB for the whole model), not accuracy, and it did not save forgetting.
- Deployment has traps. Merge into the original 16-bit or 32-bit weights; merging the adapter into weights that are already quantized and quantizing again rounds the update away (only 1.6% to 1.8% survives); training on a 4-bit base (QLoRA) leaves general ability a notch below 16-bit LoRA (perplexity 21.64 against 19.10).
These conclusions answer for one model, one task and one training run per setting. Each section says which ones are fairly robust and which are only observations.
What LoRA Does
The forward pass and the parameter count
For a linear layer with , LoRA freezes and adds a low-rank branch in parallel:
is the rank and is a scaling constant, so the branch is multiplied by . is initialized randomly (a Gaussian in the paper, Kaiming uniform by default in peft) and is all zeros, so the branch outputs exactly 0 at the start and the model equals the base model. Every adapted matrix adds parameters.
Qwen2.5-0.5B has a hidden size of 896 and 7 linear layers per block. The following code recomputes the trainable-parameter count that peft reports, from the model config alone ():
from transformers import AutoConfig
cfg = AutoConfig.from_pretrained("Qwen/Qwen2.5-0.5B")
h, ff, L = cfg.hidden_size, cfg.intermediate_size, cfg.num_hidden_layers
kv = cfg.num_key_value_heads * (h // cfg.num_attention_heads)
shapes = {"q_proj": (h, h), "k_proj": (h, kv), "v_proj": (h, kv),
"o_proj": (h, h), "gate_proj": (h, ff), "up_proj": (h, ff),
"down_proj": (ff, h)}
r = 16
total = 0
for name, (d_in, d_out) in shapes.items():
n = r * (d_in + d_out)
total += n
print(f"{name:10s} {d_in:>5d} -> {d_out:<5d} LoRA params: {n:>7,d}")
print(f"per layer: {total:,d}; x {L} layers = {total * L:,d}")
Output:
q_proj 896 -> 896 LoRA params: 28,672
k_proj 896 -> 128 LoRA params: 16,384
v_proj 896 -> 128 LoRA params: 16,384
o_proj 896 -> 896 LoRA params: 28,672
gate_proj 896 -> 4864 LoRA params: 92,160
up_proj 896 -> 4864 LoRA params: 92,160
down_proj 4864 -> 896 LoRA params: 92,160
per layer: 366,592; x 24 layers = 8,798,208
The layer-by-layer sum matches the 8,798,208 that peft reports. Note that k_proj and v_proj only output 128 dimensions: this model uses grouped-query attention (GQA), so those two matrices are much smaller than q_proj, and LoRA adds fewer parameters to them.
Try it: how many parameters does LoRA add, and how much memory does it save?
For a weight, a rank- LoRA adds two small matrices with trainable parameters, far fewer than . Summing over all selected linear layers and all blocks gives the size of the adapter. The widget below does this arithmetic for published model architectures:
Start with Llama 2 7B, rank 8, “q, v”: the added parameters are exactly 4,194,304 ( layers matrices ), about 0.06% of the base model. Then watch what changes:
- Coverage matters more than rank for the parameter count. Switching “q, v” to “all linear layers” raises the count by about 4.8× (the three FFN matrices are far larger than the attention projections), while doubling the rank from 8 to 16 only doubles it.
- The memory saving is in gradients and optimizer state. Full fine-tuning stores weights, gradients and AdamW’s two moments for every parameter, about 16 bytes each; LoRA pays that price only for the small adapter, and the base model stores just its weights. A 4-bit base model is the idea behind QLoRA.
- Adapter files are small. For Llama 2 7B at rank 16 on all linear layers, a BF16 adapter is only about 76 MiB (the base model is about 12.6 GiB). That is why “one base model, many task adapters” works.
From scratch: a LoRALinear
The core of peft fits in under thirty lines. The implementation below wraps an nn.Linear: it freezes the original weight, adds the two small matrices and in parallel, and provides a merged() method that returns the merged weight.
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class LoRALinear(nn.Module):
def __init__(self, base: nn.Linear, r: int, alpha: float):
super().__init__()
self.base = base
for p in self.base.parameters():
p.requires_grad_(False)
self.scale = alpha / r
self.A = nn.Parameter(torch.empty(r, base.in_features))
self.B = nn.Parameter(torch.zeros(base.out_features, r))
nn.init.kaiming_uniform_(self.A, a=math.sqrt(5))
def forward(self, x):
return self.base(x) + (x @ self.A.T @ self.B.T) * self.scale
@torch.no_grad()
def merged(self):
return self.base.weight + self.scale * (self.B @ self.A)
Now check four things on two real matrices from layer 0 of Qwen2.5-0.5B (q_proj and up_proj, with random input x): zero initialization, gradients, whether merging is exact, and the parameter count.
from transformers import AutoModelForCausalLM
torch.manual_seed(0)
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B",
dtype=torch.float32)
layer = model.model.layers[0]
for name in ("self_attn.q_proj", "mlp.up_proj"):
base = layer.get_submodule(name)
lora = LoRALinear(base, r=16, alpha=32)
x = torch.randn(4, 10, base.in_features)
print(f"--- {name}: {base.in_features} -> {base.out_features},"
f" bias={base.bias is not None}")
# 1. zero init: the adapter changes nothing at step 0
print("max |lora(x) - base(x)| at init:",
(lora(x) - base(x)).abs().max().item())
# 2. only A and B get gradients; A's gradient is exactly 0 at step 0
lora(x).pow(2).sum().backward()
print("base.weight.grad:", base.weight.grad)
print("|B.grad| =", round(lora.B.grad.norm().item(), 3),
" |A.grad| =", lora.A.grad.norm().item())
# 3. merge: W' = W + (alpha/r) B A (use a trained-looking B)
with torch.no_grad():
lora.B.normal_(0, 0.02)
y = lora(x)
y_merged = F.linear(x, lora.merged(), base.bias)
print("max |unmerged - merged|:", (y - y_merged).abs().max().item(),
" (|y| max:", round(y.abs().max().item(), 2), ")")
# 4. parameter count
n = sum(p.numel() for p in lora.parameters() if p.requires_grad)
print("trainable:", n, "= r*(d_in + d_out) =",
16 * (base.in_features + base.out_features),
"; base weight:", base.weight.numel(),
f"({n / base.weight.numel():.1%})")
Output:
--- self_attn.q_proj: 896 -> 896, bias=True
max |lora(x) - base(x)| at init: 0.0
base.weight.grad: None
|B.grad| = 11702.57 |A.grad| = 0.0
max |unmerged - merged|: 0.00017547607421875 (|y| max: 81.12 )
trainable: 28672 = r*(d_in + d_out) = 28672 ; base weight: 802816 (3.6%)
--- mlp.up_proj: 896 -> 4864, bias=False
max |lora(x) - base(x)| at init: 0.0
base.weight.grad: None
|B.grad| = 2333.319 |A.grad| = 0.0
max |unmerged - merged|: 4.291534423828125e-06 (|y| max: 2.64 )
trainable: 92160 = r*(d_in + d_out) = 92160 ; base weight: 4358144 (2.1%)
Reading the output line by line:
- Zero initialization holds. At initialization the largest difference between the LoRA output and the base output is exactly 0.0, so training starts from the base model’s behavior.
- Only moves at the first step. The frozen
base.weight.gradisNone; has a large gradient norm, and ‘s gradient is exactly 0.0. The reason is that passes through , and . After the first update is no longer zero and starts receiving gradient, so the two matrices do not begin learning together: moves first and follows. If both were initialized to zero, both gradients would be 0 and training would stay at the origin forever; the paper’s convention is random, zero. - Merging is exact. After adding to , the output differs from the unmerged one by to , which is fp32 rounding error (the
q_projoutput reaches 81, so its absolute error is larger; the relative error is about in both cases). After merging, inference has no extra computation, which is LoRA’s selling point over Adapters. - Parameter share.
q_projgains 28,672 parameters, 3.6% of that matrix;up_projgains 92,160, 2.1%.
The Setup: How to Measure a LoRA Run
All numbers below come from one setup, so here it is in full:
| Item | Setting |
|---|---|
| Base model | Qwen2.5-0.5B (base, not instruct; Apache-2.0 license), 494,032,768 parameters, trained in fp32 |
| Task | banking77: 77 banking customer-service intents (Casanueva et al., 2020), CC-BY-4.0, 10,003 training and 3,080 test examples |
| Training data | 20 random examples per class, 1,540 in total (15% of the training set); the same subset in every run |
| Prompt | Classify the customer message into one banking intent.\nMessage: {text}\nIntent:; the answer is the class name plus the end-of-sequence token, and only the answer tokens contribute to the loss |
| Training | AdamW (weight decay 0), batch size 16, 3 epochs = 291 steps, learning rate warmed up linearly over 5% of the steps then decayed linearly to 0, gradient clipping 1.0 |
| Default LoRA | , , dropout 0.05, learning rate , all 7 linear layers adapted |
| Target-task metric | Greedy decoding on the full test set; an answer counts only if it is identical to the class name. The “valid-label rate” is the share of outputs that are one of the 77 class names |
| Forgetting probes | (1) WikiText-2 (raw v1, CC BY-SA 3.0) test perplexity (first 80 segments of 512 tokens, lower is better); (2) 2,365 ARC-Easy (CC BY-SA 4.0) test questions as four-way multiple choice (compare the logits of the letters A to D; random guessing is 25%) |
| Repeats | The default configuration ran with 3 random seeds; every other configuration ran once |
| Environment | Apple M2 Max (64 GiB unified memory), PyTorch’s MPS backend; Python 3.14.3, PyTorch 2.15.0, transformers 5.22.2, peft 0.21.2. Re-running the same code on this machine gives a bit-identical adapter; on other hardware or library versions individual numbers will differ slightly |
Some notes to keep in mind when reading the numbers:
- Why two forgetting probes. Accuracy on the target task only says whether the model learned. Perplexity measures whether language modeling was damaged, and the multiple-choice score measures whether “answering a question as instructed” was damaged. Neither is an authoritative general-ability benchmark, but both are enough to catch a clear regression.
- How big the noise is. The default configuration with 3 seeds scored 85.8%, 85.9% and 86.1%, a standard deviation of about 0.2 percentage points; the 3,080 test examples alone contribute about 0.6 points of sampling error. Do not read differences below 0.5 points; the conclusions below rely on larger gaps.
- Baselines. The untuned base model with the same prompt scores 0.0%: it does not answer with a class name, and none of the 3,080 outputs is a valid label (it improvises, for example writing
Payment). Its WikiText-2 perplexity is 16.83; the ARC-Easy baseline is given below. Putting the list of classes in the prompt and answering zero-shot is measured in the “Baseline: could a better prompt do the job” section below. - Only 1,540 examples. This is deliberate: small data amplifies the effect of hyperparameters, and a run takes only minutes, which is what makes this many comparisons possible. How the amount of data matters is covered in SFT Data Construction and Quality Control.
A Minimal Training Script
Here is the complete runnable script (peft plus plain PyTorch), in three parts: data and encoding, the model and LoRA config, and the training loop plus evaluation. The device is mps (Apple silicon); cuda or cpu also work.
import math, random
import torch
import torch.nn.functional as F
from datasets import load_dataset
from peft import LoraConfig, get_peft_model
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL, DEV = "Qwen/Qwen2.5-0.5B", "mps" # "cuda" or "cpu" also work
PROMPT = ("Classify the customer message into one banking intent.\n"
"Message: {}\nIntent:")
data = load_dataset("PolyAI/banking77")
names = data["train"].features["label"].names # the 77 intent names
tok = AutoTokenizer.from_pretrained(MODEL)
def pick(per_class=20, seed=0):
"""A stratified subset: `per_class` random messages per intent."""
rng, by_label = random.Random(seed), {}
for row in data["train"]:
by_label.setdefault(row["label"], []).append(row)
rows = []
for c in sorted(by_label):
rng.shuffle(by_label[c])
rows += by_label[c][:per_class]
rng.shuffle(rows)
return rows
def encode(row):
"""Token ids and labels; only the answer is supervised (-100 = skip)."""
prompt = tok(PROMPT.format(row["text"]))["input_ids"]
answer = tok(" " + names[row["label"]])["input_ids"]
answer += [tok.eos_token_id]
return prompt + answer, [-100] * len(prompt) + answer
model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32)
model = model.to(DEV)
torch.manual_seed(0)
model = get_peft_model(model, LoraConfig(
r=16, lora_alpha=32, lora_dropout=0.05, task_type="CAUSAL_LM",
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"]))
model.print_trainable_parameters()
def collate(examples):
"""Right-pad a list of (ids, labels) to the longest one."""
n = max(len(ids) for ids, _ in examples)
ids = torch.full((len(examples), n), tok.eos_token_id)
lab = torch.full((len(examples), n), -100)
att = torch.zeros((len(examples), n), dtype=torch.long)
for k, (x, y) in enumerate(examples):
ids[k, :len(x)], lab[k, :len(y)], att[k, :len(x)] = (
torch.tensor(x), torch.tensor(y), 1)
return ids.to(DEV), lab.to(DEV), att.to(DEV)
def response_loss(model, ids, lab, att):
"""Cross-entropy on the supervised positions only. The LM head maps
hidden states to 151,936 logits, so applying it only where a label
exists avoids a [batch, length, vocab] tensor."""
inner = model.base_model.model
h = inner.model(input_ids=ids, attention_mask=att).last_hidden_state
target = lab[:, 1:]
keep = target != -100
logits = inner.lm_head(h[:, :-1][keep])
return F.cross_entropy(logits.float(), target[keep])
There is no Trainer in the loop because the whole procedure is a few lines: set the learning rate by formula, forward for the loss, backward, clip the gradient, update.
examples = [encode(r) for r in pick()] # 77 x 20 = 1,540
epochs, bs, peak_lr = 3, 16, 2e-4
steps = epochs * math.ceil(len(examples) / bs) # 291 optimizer steps
warmup = int(0.05 * steps)
params = [p for p in model.parameters() if p.requires_grad]
opt = torch.optim.AdamW(params, lr=peak_lr, weight_decay=0.0)
rng, step = random.Random(0), 0
model.train()
for _ in range(epochs):
order = list(range(len(examples)))
rng.shuffle(order)
for s in range(0, len(order), bs):
lr = (peak_lr * (step + 1) / warmup if step < warmup
else peak_lr * (steps - step) / (steps - warmup))
for g in opt.param_groups:
g["lr"] = lr
ids, lab, att = collate([examples[i] for i in order[s:s + bs]])
loss = response_loss(model, ids, lab, att)
loss.backward()
torch.nn.utils.clip_grad_norm_(params, 1.0)
opt.step()
opt.zero_grad(set_to_none=True)
step += 1
if step % 50 == 0:
print(f"step {step}/{steps} loss {loss.item():.4f}")
@torch.no_grad()
def predict(model, rows, bs=64):
"""Greedy decoding; keep the first line of each generated answer."""
model.eval()
tok.padding_side = "left"
answers = []
for s in range(0, len(rows), bs):
enc = tok([PROMPT.format(r["text"]) for r in rows[s:s + bs]],
return_tensors="pt", padding=True).to(DEV)
out = model.generate(**enc, max_new_tokens=12, do_sample=False,
pad_token_id=tok.eos_token_id)
texts = tok.batch_decode(out[:, enc["input_ids"].shape[1]:],
skip_special_tokens=True)
answers += [t.strip().split("\n")[0].strip() for t in texts]
return answers
def accuracy(model, rows):
"""Exact match against the intent name."""
hits = [a == names[r["label"]] for a, r in zip(predict(model, rows), rows)]
return sum(hits) / len(rows)
print("test accuracy:", accuracy(model, list(data["test"])))
model.save_pretrained("banking-lora") # only the adapter (~35 MB)
Output:
trainable params: 8,798,208 || all params: 502,830,976 || trainable%: 1.7497
step 50/291 loss 0.7310
step 100/291 loss 0.2523
step 150/291 loss 0.0734
step 200/291 loss 0.0779
step 250/291 loss 0.0401
test accuracy: 0.8577922077922078
Reading the output line by line:
- 8,798,208 trainable parameters, 1.75% of the 502,830,976 total, matching the layer-by-layer sum above.
- The loss falls from 0.73 at step 50 to 0.04 at step 250. Each printed loss comes from the last batch of 16 examples only, so it is a single-step value rather than an average and it fluctuates: step 200 (0.0779) is slightly above step 150 (0.0734) for that reason.
- Accuracy on the full test set is 85.8%. With the same prompt the untuned base model scores 0.0%: it does not answer with a class name, so the 85.8% contains both the output format and the class mapping. On an Apple M2 Max the 291 training steps take about 100 seconds and evaluating the 3,080 test examples about 40 seconds.
- The adapter is about 35 MB (8,798,208 parameters at 4 bytes each in fp32); the base weights are untouched.
This is the baseline configuration for every experiment below. Each section changes one or two of its settings and watches what happens to the target task and to general ability.
Baseline: could a better prompt do the job without fine-tuning?
Before fine-tuning, ask what an untuned model can do with prompting alone. The table below runs three untuned setups under the same scoring rule as everything else (greedy decoding, at most 12 new tokens, the first line must equal a label name exactly). The first row uses the prompt this page trains with, which has no list of classes; the other two put the 77 label names in the prompt (Classify the customer message into one of these banking intents:, followed by the 77 label names, then Message: ... and Intent:) and hand it to the base model and to the 1.5B Instruct model (with its chat template).
| Setting | Accuracy | Valid-label rate |
|---|---|---|
| Qwen2.5-0.5B base, this page’s prompt (no label list) | 0.0% | 0.0% |
| Qwen2.5-0.5B base, 77 labels listed in the prompt | 13.4% | 71.2% |
| Qwen2.5-1.5B-Instruct, same prompt | 11.6% | 27.9% |
| Qwen2.5-0.5B + LoRA (default) | 85.8% | 98.5% |
- Without a list of classes the base model gets none right. It does not know the answer has to be one of 77 label names and improvises (the sampled outputs are words like
Payment,Payment ConfirmationandTransaction). The first thing training has to teach is this format. - With the list in the prompt the base model reaches 13.4%. 71.2% of its outputs are exactly a label name, so it understood “pick one from the list”, but it picks the wrong one (the sampled outputs are near neighbours such as
card_arrivalandcard_acceptance). - The Instruct model scores lower, mostly because of format. Only 27.9% of its outputs are valid labels: the sampled outputs mostly start with a sentence like
The intent for the message ..., and 12 tokens run out before the label appears. That is a loss caused by the scoring setup, not proof that the model does not understand the intents. A longer generation budget, a search for the label inside the output, or a few examples would all score noticeably higher; this page did not measure them. - All we can say is this: under this rule, 291 steps of LoRA training (a few minutes) take accuracy to 85.8% and teach the output format at the same time. Prompting and fine-tuning are not either/or: build a prompted baseline first, because that is the only way to know how much fine-tuning adds, and if the baseline is already good enough you do not need to fine-tune.
Tuning the Knobs: A Set of Measurements
LoRA has few knobs: learning rate, rank , scaling factor , target modules, number of epochs and dropout. Below they are swept one at a time, with everything else at the default. Every table gives the accuracy on the target task together with the two forgetting probes, because looking at accuracy alone picks the wrong configuration. The WikiText-2 perplexity of the base model is 16.83 and its ARC-Easy multiple-choice score is 72.4%; a higher perplexity or a lower multiple-choice score means the base model’s existing abilities were overwritten.
Learning rate: the most sensitive knob
With and fixed, only the learning rate changes:
| Setting | Accuracy | Valid-label rate | WikiText-2 perplexity | ARC-Easy (multiple choice) |
|---|---|---|---|---|
| 2e-5 | 47.6% | 72.4% | 17.66 | 72.2% |
| 5e-5 | 77.8% | 97.1% | 18.25 | 72.3% |
| 1e-4 | 83.6% | 98.4% | 18.66 | 72.2% |
| 2e-4 (default) | 85.8% | 98.5% | 19.10 | 72.8% |
| 5e-4 | 86.9% | 99.0% | 21.28 | 68.8% |
| 1e-3 | 87.3% | 99.3% | 28.92 | 23.8% |
| 2e-3 | 72.2% | 99.2% | 2,115,413 | 25.2% |
- Too small and it does not learn. At 2e-5, 291 steps only reach 47.6% accuracy, and the valid-label rate is just 72.4%: nearly a third of the outputs have not even learned the format “the answer must be one of the class names”. starts from zero and needs a much larger learning rate than full fine-tuning (compared below).
- There is a plateau around the default. From 1e-4 to 5e-4 accuracy rises from 83.6% to 86.9%, only 3 points, while perplexity rises from 18.66 to 21.28 (base model: 16.83).
- Accuracy keeps rising after general ability has collapsed. The accuracy of 87.3% at 1e-3 is the highest in the table, but the ARC-Easy score is down to 23.8% (random guessing is 25%) and the perplexity is 28.92. If you only watch the target-task metric you would pick this configuration and ship a model that can no longer answer multiple-choice questions. At 2e-3 training simply diverges: perplexity reaches 2.1 million and accuracy falls back to 72.2%.
- The forgetting probes raise the alarm first. Going from 2e-4 to 5e-4 adds about 1 point of accuracy while perplexity rises 11% and the multiple-choice score drops 4 points; at 1e-3 accuracy is still rising and the probes have already failed completely. Accuracy alone will not tell you when to stop.
A practical procedure: get a working baseline at 2e-4, then step upward by a factor of 2 to 2.5, look at the forgetting probes every time, and stop before they start to worsen.
Rank and α: the capacity knob, and also the forgetting knob
The rank sets the capacity of the adapter, but sets the amplification of the branch, so a rank sweep has to say how moves. Two groups are measured:
- : the amplification stays at 2, and a larger rank means a stronger adapter (the default , belongs to this group).
- : is fixed, the amplification is , and a larger rank means a smaller amplification per direction.
| Setting | Trainable params | Accuracy | WikiText-2 perplexity | ARC-Easy (multiple choice) |
|---|---|---|---|---|
| r=1 | 549,888 | 72.9% | 17.40 | 72.6% |
| r=2 | 1,099,776 | 80.2% | 17.63 | 72.9% |
| r=4 | 2,199,552 | 82.8% | 17.89 | 72.9% |
| r=8 | 4,399,104 | 85.3% | 18.30 | 72.9% |
| r=16 | 8,798,208 | 85.8% | 19.10 | 72.8% |
| r=32 | 17,596,416 | 86.5% | 19.96 | 71.0% |
| r=64 | 35,192,832 | 87.8% | 21.36 | 66.3% |
| r=128 | 70,385,664 | 88.0% | 27.81 | 29.2% |
| Setting | Scale α/r | Accuracy | WikiText-2 perplexity | ARC-Easy (multiple choice) |
|---|---|---|---|---|
| r=1 | 32 | 86.4% | 21.24 | 69.1% |
| r=2 | 16 | 85.5% | 20.14 | 71.0% |
| r=4 | 8 | 85.2% | 19.61 | 71.2% |
| r=8 | 4 | 85.8% | 19.06 | 72.3% |
| r=16 | 2 | 85.8% | 19.10 | 72.8% |
| r=32 | 1 | 85.6% | 18.92 | 72.5% |
| r=64 | 0.5 | 85.9% | 18.89 | 72.5% |
| r=128 | 0.25 | 85.9% | 18.69 | 72.2% |
The two tables have to be read separately.
(amplification fixed at 2): a larger rank learns more and forgets more. From rank 1 to 128, accuracy climbs from 72.9% to 88.0%, perplexity rises from 17.40 to 27.81, and the ARC-Easy score falls to 66.3% at r=64 and to 29.2% at r=128, close to random. The r=128 row shows the same symptoms as the learning-rate 1e-3 row above (perplexity 27.81 against 28.92, multiple-choice 29.2% against 23.8%). From r=1 to r=8 accuracy gains more than 12 points while the forgetting probes barely move; beyond r=16 each doubling buys only 0.2 to 1.3 points, at a growing cost.
(amplification ): accuracy hardly depends on the rank. From r=1 to r=128, accuracy stays between 85.2% and 85.9%, except r=1 which is slightly higher (86.4%); there is no monotonic trend. A rank-1 adapter with only 549,888 trainable parameters is as good as a rank-128 adapter with about 70 million. What changes is the forgetting probes: at r=1 the perplexity is 21.24 and the multiple-choice score 69.1%; from r=8 on, perplexity settles between 18.7 and 19.1 and the multiple-choice score between 72.2% and 72.8%. The same size of change spread over more directions does less damage to the base model.
Why do the two groups differ so much? A plausible explanation: write as a sum of rank-one matrices . The update of each term depends on the learning rate and the initialization, not on . With the amplification is a constant 2, the terms simply add up, and the total change grows linearly with , which quietly multiplies the learning rate. With a fixed the amplification is , so the terms are effectively averaged, and the total change does not depend on . Thinking Machines’ LoRA Without Regret makes the same argument (for the first training step) to explain why the prefactor makes the optimal learning rate nearly independent of rank, and reports that learning curves of different ranks almost coincide early in training. This page only observed the pattern in the tables on one model and one task and did not test the mechanism separately.
Two practical conclusions follow:
- Do not treat the rank as the main knob. With fixed (say 32), changing the rank hardly requires retuning the learning rate; with , raising the rank is the same as raising the learning rate, so lower the learning rate at the same time.
- This task does not lack capacity. 77 classes and 1,540 examples are enough for rank 1. Settings that do need a high rank (huge datasets, or math and code tasks far from the pretraining distribution) were not measured here; see the comparison with full fine-tuning below and the study by Biderman et al. in the further reading.
Target modules: where matters more than how many parameters
The LoRA paper adapts only the attention matrices and . In this setup, several choices of location are compared, with everything else at the default (rank 16, ):
| Setting | Trainable params | Accuracy | WikiText-2 perplexity | ARC-Easy (multiple choice) | Peak memory (GiB) |
|---|---|---|---|---|---|
| q, v | 1,081,344 | 52.0% | 20.79 | 70.9% | 6.3 |
| q, k, v, o | 2,162,688 | 73.0% | 20.04 | 70.2% | 6.7 |
| gate, up, down | 6,635,520 | 85.5% | 18.57 | 72.3% | 7.2 |
| all 7 | 8,798,208 | 85.8% | 19.10 | 72.8% | 8.0 |
| q, v, r=128, α=256 | 8,650,752 | 77.9% | 30.14 | 66.0% | 6.4 |
| q, k, v, o, r=64, α=128 | 8,650,752 | 83.0% | 22.80 | 71.0% | 6.8 |
- Where matters more than how many parameters. Adapters on the three MLP matrices alone (6,635,520 parameters) reach 85.5%, almost matching all seven matrices at 85.8% (8,798,208 parameters). The four attention matrices (2,162,688 parameters) reach only 73.0%, and q and v alone (1,081,344 parameters) only 52.0%; nearly a quarter of that model’s outputs are not even a valid label (valid-label rate 76.7%).
- At equal parameter counts, wider coverage wins. The last two rows deliberately raise the parameter count to 8,650,752, close to the 8,798,208 of all seven matrices: q and v only with rank 128 gives 77.9%; q, k, v, o with rank 64 gives 83.0%; all seven matrices with rank 16 give 85.8%. A budget concentrated on a few matrix types cannot be rescued by a larger rank. Raising the rank of the q and v adapters from 16 to 128 multiplies their parameters by 8 and lifts accuracy from 52.0% to 77.9%, still far below the 85.5% of MLP-only.
- This agrees with the paper and goes one step further. On GPT-3 175B the LoRA paper fixed the parameter budget and found that adapting several attention matrix types with a small rank is no worse than adapting one type with a large rank (see the paper breakdown); it did not test the MLP. These numbers say that on this task the MLP is where most of the capacity sits, which is why today’s default of covering all linear layers makes sense.
- The large-rank q, v adapter is already in the forgetting regime. Its perplexity is 30.14 (base 16.83) and its multiple-choice score 66.0%. The last two rows use , and the previous section showed that with this setting a larger rank is the same as a larger learning rate; the symptoms here (mediocre accuracy, general ability breaking first) match.
- The price is peak memory. Adding adapters on the MLP raises peak memory from 6.3 GiB to 8.0 GiB (batch size 16). When memory is tight, adapting only the MLP (7.2 GiB) is a reasonable compromise; there is no good reason to adapt only q and v.
α and the learning rate are not the same knob
With rank 16 and learning rate 2e-4 fixed, only changes (that is, the amplification ). The last two rows move and the learning rate in opposite directions by a factor of two, so that the product stays constant:
| Setting | Accuracy | Valid-label rate | WikiText-2 perplexity | ARC-Easy (multiple choice) |
|---|---|---|---|---|
| α=8 | 83.1% | 98.0% | 18.04 | 72.9% |
| α=16 | 85.3% | 98.5% | 18.48 | 72.6% |
| α=32 (default) | 85.8% | 98.5% | 19.10 | 72.8% |
| α=64 | 87.0% | 99.0% | 20.26 | 72.0% |
| α=128 | 87.3% | 98.7% | 23.70 | 61.9% |
| α=16, lr=4e-4 | 86.9% | 98.8% | 18.90 | 72.6% |
| α=64, lr=1e-4 | 85.1% | 98.4% | 19.58 | 71.7% |
- is an amplification, and it acts in the same direction as the learning rate. Raising from 8 to 128 (amplification 0.5 to 8) lifts accuracy from 83.1% to 87.3%, raises perplexity from 18.04 to 23.70, and drops ARC-Easy from 72.9% to 61.9%. A different knob gives the same curve: “learn harder, forget more”.
- The same gives similar but not identical results. The last two rows and the default all have ; accuracy is 86.9% (, learning rate 4e-4), 85.8% and 85.1% (, learning rate 1e-4), a spread of nearly 2 points, larger than seed noise. A plausible explanation: with Adam, the per-step update of is roughly proportional to the learning rate, and the weight change is the amplification times that update, so equal products give equal contributions from . also changes in proportion to the learning rate but only affects the output through , so its contribution scales roughly with , and the side with the larger learning rate gains more. This was not verified separately. In practice, do not treat the two as free variables at the same time: fix and tune only the learning rate.
- Tuning does not replace watching the forgetting probes. At accuracy is highest, but perplexity and the multiple-choice score are already clearly worse, between the levels of learning rates 5e-4 and 1e-3.
Epochs and dropout
| Setting | Accuracy | Valid-label rate | Mean loss, last 10 steps | WikiText-2 perplexity | ARC-Easy (multiple choice) |
|---|---|---|---|---|---|
| 1 epoch | 69.8% | 95.2% | 0.2482 | 18.25 | 72.1% |
| 3 epochs (default) | 85.8% | 98.5% | 0.0136 | 19.10 | 72.8% |
| 10 epochs | 87.5% | 98.7% | 0.0003 | 19.98 | 71.9% |
| dropout=0 | 85.4% | 98.5% | 0.0119 | 19.15 | 72.7% |
- Too short and even the format is not learned. After 1 epoch (97 steps) accuracy is 69.8%, the valid-label rate 95.2%, and the mean loss over the last 10 steps is still 0.25.
- A training loss near zero did not hurt test accuracy. After 10 epochs the mean loss over the last 10 steps is 0.0003, yet test accuracy rose from 85.8% at 3 epochs to 87.5%; perplexity went up by only 0.9 and the multiple-choice score fell by 0.9 points. A training loss near zero is normally read as a sign of overfitting, but on this task test accuracy did not drop: the answers are 77 fixed labels, and even after memorizing the training set the model’s judgment on new sentences kept improving. Do not extrapolate this to generative tasks, where overfitting usually shows up as repetitive answers rather than lower accuracy. It holds only for clean labels: with noisy labels, memorizing them has a price, see the 10-epoch comparison in SFT Data: Construction and Quality Control.
- Dropout showed no benefit here.
lora_dropout=0scores 85.4%, 0.4 points from the default 0.05 (85.8%), within seed noise. Its cost is memory: every adapter keeps an extra copy of its input for dropout, and peak training memory rises from 6.1 GiB to 8.0 GiB (batch size 16; a separate comparison follows below).
LoRA vs. Full Fine-Tuning: Accuracy, the Structure of the Update, and Cost
With the same data, how far can full fine-tuning go?
Everything above compared LoRA settings with each other. To see how much accuracy the adapter’s savings cost, we need a control without an adapter: hand all 494,032,768 parameters to the same AdamW, keep everything else fixed (1,540 examples, 3 epochs, batch size 16, warmup then linear decay, gradient clipping 1.0) and change only the learning rate. The last row is the default LoRA from above.
| Full fine-tuning lr | Accuracy | Valid-label rate | WikiText-2 perplexity | ARC-Easy (multiple choice) |
|---|---|---|---|---|
| 5e-6 | 84.2% | 97.9% | 17.37 | 73.3% |
| 1e-5 | 87.9% | 98.9% | 17.58 | 72.8% |
| 1.5e-5 | 88.2% | 99.0% | 17.85 | 72.0% |
| 2e-5 | 88.3% | 99.1% | 18.48 | 67.7% |
| 3e-5 | 88.8% | 99.2% | 20.56 | 30.1% |
| 5e-5 | 87.1% | 99.4% | 29.43 | 24.3% |
| 1e-4 | 85.7% | 99.5% | 380.07 | 24.7% |
| LoRA (default) | 85.8% | 98.5% | 19.10 | 72.8% |
- Full fine-tuning needs a much smaller learning rate. 5e-6 to 2e-5 keeps the general ability; from 3e-5 on, multiple-choice accuracy collapses. LoRA’s default is 2e-4, ten times the upper limit of what full fine-tuning tolerates here. That agrees with earlier reports: Thinking Machines’ LoRA Without Regret found across several models and datasets that LoRA’s optimal learning rate is about 10 times that of full fine-tuning, and Biderman et al. report a similar ratio. When you switch from LoRA to full fine-tuning, the learning rate does not carry over.
- Between 1e-5 and 3e-5, accuracy barely rises while forgetting accelerates. The four runs reach 87.9%, 88.2%, 88.3% and 88.8%, less than one point of total gain (the standard error of one run is about 0.6 points); perplexity is 17.58, 17.85, 18.48 and 20.56, and multiple-choice accuracy 72.8%, 72.0%, 67.7% and 30.1%. Where accuracy has already plateaued, pick the smallest learning rate.
- The cliff exists on both sides, and the target-task metric cannot see it. At 5e-5, full fine-tuning still scores 87.1% on banking77, yet perplexity has risen to 29.43 and multiple-choice accuracy is 24.3% (chance on a four-way question is 25%); at 1e-4, perplexity is 380.07. LoRA at a learning rate of 1e-3 does the same: 87.3%, perplexity 28.92, multiple choice 23.8%. Choosing a configuration by target-task accuracy alone would pick a model that has already lost its general ability. And the perplexity at 3e-5 (20.56) is only a little above the default LoRA’s 19.10 while multiple-choice accuracy has already fallen to 30.1%, so general ability needs more than one metric too. That is why every table on this page reports both perplexity and multiple-choice accuracy.
- In this setup, full fine-tuning did not forget more than LoRA. The blue dots in the figure are all LoRA configurations from above. Nine of them reach 86.5% accuracy or more; the lowest perplexity among them is 18.90 and the highest multiple-choice accuracy is 72.6%. Full fine-tuning at 1e-5 and 1.5e-5 scores higher (87.9% and 88.2%), has lower perplexity (17.58 and 17.85), and keeps multiple-choice accuracy at the level of the base model (72.4%).
- “LoRA learns less and forgets less”: here the learning gap is within noise and the forgetting gap points the other way. Biderman et al. (2024) compared the two methods on Llama-2-7B for code and math, with about 100K instruction examples and up to 20B tokens of continued pretraining, and found that LoRA learns less and also forgets less (see Further reading). In this small experiment the learning gap is tiny: the best LoRA accuracy is 88.0% against 88.8% for full fine-tuning, with both peaks already down at 29.2% and 30.1% on multiple choice, and among configurations with multiple-choice accuracy of at least 71%, LoRA’s best is 87.5% against 88.2%, a difference of the size of the noise (3,080 test examples, so the standard error of one run is about 0.6 points). The direction of forgetting is the opposite of the paper’s, as the previous point says. This does not refute the paper: here the model is 0.5B, the task is classification, the data is 1,540 examples, every setting was trained once, the forgetting metrics differ (the paper averages HellaSwag, ARC-Challenge and Winogrande; this page uses WikiText-2 perplexity and ARC-Easy), and a LoRA with a lower learning rate and more epochs was not tested. It only shows that this conclusion should not be carried over to your own task without checking.
- Two early runs ended in NaN. On the first attempt at learning rate 1e-5 the loss turned to NaN between steps 270 and 279, after behaving normally until then; on the first attempt at 1e-4 it happened between steps 20 and 29. Both settings finished normally when rerun unchanged, and the table uses the reruns. The 10-step average loss of the reruns already differs from the first attempt in the second group (1.436 against 1.461 at 1e-5, 1.206 against 1.240 at 1e-4), so full fine-tuning on this GPU is not bit-for-bit reproducible. The cause was not found: it may be an occasional fault of the MPS backend or of a machine short on memory at the time, or a real numerical instability, and this page cannot tell which. If you hit NaN yourself, first rerun with another seed, then check gradient clipping and learning-rate warmup, and only then suspect the hardware.
- Size and cost show up elsewhere. The saved adapter file is 35 MB and the fp32 weights of the whole model are 1.98 GB, about 56 times larger; the next section compares memory and speed.
Is the update of full fine-tuning low-rank?
LoRA assumes that the weight change produced by fine-tuning is itself close to low-rank. The weights of the full fine-tuning run at learning rate 2e-5 were saved (the largest learning rate tried that had not yet broken general ability), so the assumption can be tested directly. For the four kinds of matrices in layers 0, 12 and 23, take the singular value decomposition of and measure how much of the “energy” (share of the squared Frobenius norm) the top singular directions hold, averaged over the three layers. There are two references: the update of this page’s default LoRA (), and a Gaussian random matrix of the same shape as the weight.
import torch
from safetensors.torch import load_file
from transformers import AutoModelForCausalLM
RANKS = (1, 4, 16, 64)
MODULES = {"q": "self_attn.q_proj", "v": "self_attn.v_proj",
"up": "mlp.up_proj", "down": "mlp.down_proj"}
LAYERS = (0, 12, 23)
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B",
dtype=torch.float32)
base = model.state_dict()
tuned = torch.load("full_2e-5.pt", weights_only=True) # full fine-tuning
lora = load_file("banking-lora/adapter_model.safetensors")
scale = 32 / 16 # alpha / r
def energy(delta):
"""Share of the squared Frobenius norm in the top-r singular directions."""
s2 = torch.linalg.svdvals(delta) ** 2
cum = s2.cumsum(0) / s2.sum()
return [cum[r - 1].item() for r in RANKS]
def update(kind, name):
w0 = base[name + ".weight"]
if kind == "full fine-tuning":
return tuned[name + ".weight"] - w0
if kind == "LoRA r=16":
prefix = "base_model.model." + name
a = lora[prefix + ".lora_A.weight"]
b = lora[prefix + ".lora_B.weight"]
return scale * (b @ a)
return torch.randn_like(w0) # same shape, noise
torch.manual_seed(0)
print(f"{'update':18s}{'module':8s}" + "".join(f"r={r:<6d}" for r in RANKS))
for kind in ("full fine-tuning", "LoRA r=16", "random matrix"):
for key, mod in MODULES.items():
rows = [energy(update(kind, f"model.layers.{i}.{mod}"))
for i in LAYERS]
mean = [sum(col) / len(rows) for col in zip(*rows)]
print(f"{kind:18s}{key:8s}" + "".join(f"{x:<8.3f}" for x in mean))
Output:
update module r=1 r=4 r=16 r=64
full fine-tuning q 0.180 0.374 0.657 0.895
full fine-tuning v 0.140 0.319 0.604 0.916
full fine-tuning up 0.116 0.246 0.447 0.720
full fine-tuning down 0.085 0.208 0.414 0.709
LoRA r=16 q 0.379 0.741 1.000 1.000
LoRA r=16 v 0.471 0.774 1.000 1.000
LoRA r=16 up 0.448 0.731 1.000 1.000
LoRA r=16 down 0.451 0.772 1.000 1.000
random matrix q 0.004 0.017 0.067 0.236
random matrix v 0.015 0.057 0.209 0.661
random matrix up 0.002 0.009 0.035 0.132
random matrix down 0.002 0.009 0.035 0.132
- The update of full fine-tuning has low-rank structure but is not low-rank. The top 16 directions hold 41% to 66% of the energy across the four kinds of matrices and the top 64 hold 71% to 92%; a random matrix of the same shape holds only 3.5% to 21% at rank 16. The update concentrates in a few directions, but roughly half of it is spread over many more.
- The LoRA update has rank at most 16 by construction, so the column is 1.000; that row is a reference, not a finding. The column is worth a look: LoRA’s first direction alone holds 38% to 47%, far more concentrated than full fine-tuning.
- A gap is not a loss. This full fine-tuning run reaches 88.3% and default LoRA 85.8%; the data only say that a rank-16 update cannot hold everything full fine-tuning learned, not whether the part that does not fit is useful signal or noise. AdamW normalizes every parameter separately, so its updates carry a lot of near-random components, which is one possible reason; this page did not test it.
- This is one run, three layers and four kinds of matrices. Biderman et al. also found, on code and math tasks, that the weight perturbation of full fine-tuning has a rank 10 to 100 times higher than typical LoRA configurations (see Further reading). That points the same way as the data here, but the task and the scale are different.
Memory and speed: where LoRA saves
By parameter count, this model has 494,032,768 parameters, and each fp32 copy takes 1.84 GiB. Full fine-tuning stores the weights, the gradients and AdamW’s two moments, four copies in all, 7.36 GiB before any activations. LoRA stores those four copies only for the 8,798,208 adapter parameters (0.13 GiB) and needs just one copy of the frozen weights, 1.97 GiB in total, so the static part differs by 5.39 GiB. The measurement trains each configuration for 60 steps (Apple silicon, MPS backend, fp32): peak memory is the maximum of torch.mps.current_allocated_memory() read after the forward and backward pass of each step, and the time is the average per step after dropping the first 5 steps.
| Setting | Peak memory (GiB) | Seconds per step |
|---|---|---|
| LoRA, batch 4 | 3.5 | 0.15 |
| Full fine-tuning, batch 4 | 7.5 | 0.26 |
| LoRA, batch 16 | 8.0 | 0.37 |
| Full fine-tuning, batch 16 | 10.0 | 0.50 |
| LoRA, batch 16, dropout=0 | 6.1 | 0.37 |
- At batch size 4, LoRA uses 4.0 GiB less and each step is about 43% faster. 3.5 against 7.5 GiB agrees in direction with the static estimate, but the gap is smaller than 5.39 GiB because activations also take memory (this page does not break them down).
- At batch size 16 the gap shrinks to 2.0 GiB and each step is about 25% faster. Activations grow linearly with the batch size and become the bulk of the memory, which dilutes the savings in gradients and optimizer state. LoRA’s dropout also keeps a copy of each adapter’s dropped-out input for the backward pass: with
lora_dropoutset to 0, the batch-16 peak falls from 8.0 GiB to 6.1 GiB, and the time per step does not change. - LoRA does not simply “halve” the memory. How much it saves depends on the batch size, the sequence length and which layers are adapted. When memory is tight, look at activations first (smaller batch, shorter sequences, gradient checkpointing), then at optimizer state.
- Use this table for trends only: the readings come from the MPS allocator’s statistics, and CUDA or bf16 mixed precision will give different numbers. Measure again when you change machines.
Merging, Deployment and QLoRA
Merging the adapter: at what precision
A trained adapter can be used in two ways: keep it attached and compute the low-rank branch at inference time, or merge it into the base weights, , which costs nothing at inference and produces a standalone model. peft’s merge_and_unload() does the latter. The code below takes the adapter trained in the previous section and compares three ways of loading it against the “fp32, unmerged” reference. It continues the data and eval blocks above and reuses their MODEL, DEV, PROMPT, tok, data and predict:
from peft import PeftModel
def load(dtype):
"""Base model plus the saved adapter, still unmerged."""
base = AutoModelForCausalLM.from_pretrained(MODEL, dtype=dtype).to(DEV)
return PeftModel.from_pretrained(base, "banking-lora").eval()
@torch.no_grad()
def last_logits(model, rows):
"""Next-token logits at the end of each prompt."""
tok.padding_side = "left"
enc = tok([PROMPT.format(r["text"]) for r in rows],
return_tensors="pt", padding=True).to(DEV)
return model(**enc).logits[:, -1].float().cpu()
test = list(data["test"])
ref = load(torch.float32) # unmerged, fp32: the reference
ref_pred, ref_logits = predict(ref, test), last_logits(ref, test[:256])
variants = {"fp32 merged": (torch.float32, True),
"bf16 merged": (torch.bfloat16, True),
"bf16 unmerged": (torch.bfloat16, False)}
for name, (dtype, merge) in variants.items():
model = load(dtype)
if merge:
model = model.merge_and_unload().eval() # W + (alpha / r) B A
pred = predict(model, test)
diff = (last_logits(model, test[:256]) - ref_logits).abs().max().item()
flips = sum(a != b for a, b in zip(pred, ref_pred))
print(f"{name:14s} max logit diff {diff:.1e}, "
f"changed predictions {flips}/{len(test)}")
Output:
fp32 merged max logit diff 1.0e-04, changed predictions 0/3080
bf16 merged max logit diff 4.3e-01, changed predictions 18/3080
bf16 unmerged max logit diff 4.8e-01, changed predictions 17/3080
Each line reports two numbers: the largest difference in the logits at the end of the prompt over the first 256 test examples, and the number of the 3,080 test examples whose greedy answer differs from the reference.
- Merging in fp32 is exact. The maximum logit difference is and not one of the 3,080 answers changed, which agrees with the
LoRALinearcheck earlier on this page. - In bf16 the difference comes mostly from bf16 itself, not from merging. The maximum logit difference is 0.43 for the merged model and 0.48 for the unmerged one, and 18 and 17 answers (0.6%) differ from the reference. bf16 keeps 8 significant bits (relative precision about 0.4%), so the base weights are already rounded; the extra rounding that merging adds left no visible additional cost in this test.
- This is one adapter and one test. The difference between 18 and 17 means nothing, and the logit difference is a maximum over 256 examples, which a few extreme examples can dominate. Before shipping, compare outputs before and after merging on your own evaluation set.
- Merging is one-way. The merged weights no longer show the adapter, so rolling back means reloading the base model and the adapter. When one base model serves many tasks, do not merge: keep the adapters attached and let the inference engine pick one per request. vLLM and similar engines support this, and S-LoRA (Sheng et al., 2023) studies memory management and batching for serving thousands of adapters on one GPU.
- The prompt template must match training. Merging does not change that, and the most common deployment failure is not merging but the template: the SFT data page measured that the same adapter drops from 85.8% to 79.4% accuracy when the prompt is reworded.
QLoRA: store the frozen base in 4 bits
QLoRA (Dettmers et al., 2023) adds one thing on top of LoRA: the frozen base weights are stored in 4 bits and restored to 16 bits only for the layer being computed, in the forward and backward pass, while the gradients flow only into the 16-bit LoRA adapters. The paper splits the memory savings into three parts:
| Component | What it does | Where it saves |
|---|---|---|
| 4-bit NormalFloat (NF4) | 16 values taken from the quantiles of a standard normal distribution, rescaled to and including an exact 0; every 64 weights share one scale (the largest absolute value in the block) | Weights go from 16 bits to 4, plus one 32-bit scale per 64 weights, 4.5 bits on average |
| Double quantization | Quantizes those scales again to 8 bits, with one 32-bit constant per 256 scales | The overhead per parameter falls from 0.5 bit to about 0.127 bit, 4.127 bits on average |
| Paged optimizers | Use NVIDIA unified memory to move optimizer state to CPU memory when the GPU runs out and back when it is needed | A rare memory spike no longer causes an out-of-memory failure |
The paper’s abstract says this makes it possible to fine-tune a 65B-parameter model on a single 48 GB GPU while preserving the task performance of 16-bit full fine-tuning. The calculation below uses the architecture of Llama 2 7B. Full fine-tuning is estimated at 16 bytes per parameter (fp32 weights, gradients and the two AdamW moments); the QLoRA base is stored in NF4 with double quantization, the embeddings and lm_head stay in bf16, and the adapter uses on all linear layers, again at 16 bytes per parameter:
GIB = 2**30
d, ff, layers, vocab = 4096, 11008, 32, 32000 # Llama 2 7B
linear = layers * (4 * d * d + 3 * d * ff) # q,k,v,o + gate,up,down
other = 2 * vocab * d + (2 * layers + 1) * d # embeddings, head, norms
print(f"linear weights {linear:,}, embeddings and norms {other:,}")
# NF4: 4 bits per weight + one fp32 scale per block of 64 weights
plain = 4 + 32 / 64 # bits per weight
# double quantization: the scales themselves are quantized to 8 bits
# with one fp32 constant per 256 scales
dq = 4 + 8 / 64 + 32 / (64 * 256)
print(f"bits per weight: bf16 16, NF4 {plain:.3f}, NF4 + double quant {dq:.3f}")
bf16 = (linear + other) * 2 / GIB
qlora = (linear * dq / 8 + other * 2) / GIB # embeddings stay bf16
print(f"base model: bf16 {bf16:.2f} GiB -> NF4 + DQ {qlora:.2f} GiB")
r = 16
per_layer = 4 * r * (d + d) + 3 * r * (d + ff)
adapter = layers * per_layer
print(f"LoRA r={r}, all linear layers: {adapter:,} parameters")
# fp32 adapter + fp32 gradient + two AdamW moments = 16 bytes per parameter
state = adapter * 16 / GIB
print(f"adapter + gradient + Adam states: {state:.2f} GiB")
full = (linear + other) * 16 / GIB
print(f"full fine-tuning, same accounting (16 B/param): {full:.1f} GiB")
Output:
linear weights 6,476,005,376, embeddings and norms 262,410,240
bits per weight: bf16 16, NF4 4.500, NF4 + double quant 4.127
base model: bf16 12.55 GiB -> NF4 + DQ 3.60 GiB
LoRA r=16, all linear layers: 39,976,960 parameters
adapter + gradient + Adam states: 0.60 GiB
full fine-tuning, same accounting (16 B/param): 100.4 GiB
- The base model is the big item, and it is what QLoRA saves. The base weights shrink from 12.55 GiB in bf16 to 3.60 GiB, while the adapter, its gradients and optimizer state total only 0.60 GiB. The static part comes to about 4.2 GiB, against 100.4 GiB for full fine-tuning under the same accounting.
- That is only the static part. Activations are extra; they grow with batch size and sequence length, and gradient checkpointing can trade part of them away. Paged optimizers deal with the peaks.
What 4 bits cost a small model: a simulation
The machine used for this page is an Apple-silicon laptop and does not run bitsandbytes’ 4-bit kernels, so the experiment does a “quantize, then restore” round trip instead. It passes the weights of every linear layer inside the decoder blocks through NF4 (block size 64, each block scaled by its largest absolute value). The resulting fp32 weights are what the model “sees” in each computation under QLoRA; the embeddings and lm_head stay in fp32, and so do the scales (double quantization is not simulated). Numerically this matches QLoRA’s forward computation, but it saves no memory, so this page does not measure QLoRA’s memory or speed.
import torch
from transformers import AutoModelForCausalLM
# The 16 NF4 levels (QLoRA paper, appendix E): quantiles of a normal
# distribution, rescaled to [-1, 1], with an exact zero.
NF4 = [-1.0, -0.6961928009986877, -0.5250730514526367, -0.39491748809814453,
-0.28444138169288635, -0.18477343022823334, -0.09105003625154495, 0.0,
0.07958029955625534, 0.16093020141124725, 0.24611230194568634,
0.33791524171829224, 0.44070982933044434, 0.5626170039176941,
0.7229568362236023, 1.0]
@torch.no_grad()
def nf4_roundtrip(w, block=64):
"""Quantize to NF4 (one absmax scale per block of 64 weights), then
dequantize: the weights the model sees after QLoRA's storage step."""
book = torch.tensor(NF4)
flat = w.float().reshape(-1, block)
scale = flat.abs().amax(dim=1, keepdim=True).clamp_min(1e-12)
idx = ((flat / scale).unsqueeze(-1) - book).abs().argmin(dim=-1)
return (book[idx] * scale).reshape(w.shape)
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B",
dtype=torch.float32)
for name in ("self_attn.q_proj", "mlp.up_proj", "mlp.down_proj"):
w = model.model.layers[0].get_submodule(name).weight.data
q = nf4_roundtrip(w)
rel = ((w - q).norm() / w.norm()).item()
print(f"{name:17s} {str(tuple(w.shape)):12s} relative error {rel:.3f}")
Output:
self_attn.q_proj (896, 896) relative error 0.097
mlp.up_proj (4864, 896) relative error 0.093
mlp.down_proj (896, 4864) relative error 0.095
The relative error is between 9.3% and 9.7% for the three matrices. Doing this to the whole model, then training and deploying in different ways, gives the table below. In the “Base during training” column, fp32 is this page’s default LoRA and NF4 is QLoRA trained on the quantized base; every adapter was trained for 291 steps with all other settings unchanged.
| # | Base during training | At inference | Accuracy | Valid-label rate | WikiText-2 perplexity | ARC-Easy (multiple choice) |
|---|---|---|---|---|---|---|
| 1 | none | No adapter, fp32 base | 0.0% | 0.0% | 16.83 | 72.4% |
| 2 | none | No adapter, NF4 base | 0.0% | 0.0% | 19.00 | 69.9% |
| 3 | fp32 base (default LoRA) | Attached to the fp32 base | 85.8% | 98.5% | 19.10 | 72.8% |
| 4 | fp32 base (default LoRA) | Attached to the NF4 base | 84.3% | 98.0% | 21.91 | 68.8% |
| 5 | fp32 base (default LoRA) | Merged into the fp32 base, then quantized to NF4 | 83.6% | 98.0% | 21.64 | 68.2% |
| 6 | fp32 base (default LoRA) | Merged into the NF4 base, then quantized again | 0.0% | 0.0% | 19.08 | 69.7% |
| 7 | NF4 base (QLoRA) | Attached to the fp32 base | 84.1% | 97.7% | 18.83 | 72.2% |
| 8 | NF4 base (QLoRA) | Attached to the NF4 base | 85.5% | 98.6% | 21.64 | 68.1% |
| 9 | NF4 base (QLoRA) | Merged into the fp32 base, then quantized to NF4 | 84.0% | 98.0% | 21.47 | 67.8% |
| 10 | NF4 base (QLoRA) | Merged into the NF4 base, then quantized again | 0.0% | 0.0% | 19.08 | 69.8% |
- 4 bits already cost something. With no adapter, the NF4 base has a perplexity of 19.00 against 16.83 (up 13%), and the multiple-choice score falls from 72.4% to 69.9% (rows 1 and 2). The paper’s abstract says QLoRA preserves the task performance of 16-bit fine-tuning; a 0.5B model has little redundancy to spare, so quantization noise is more visible, which is one possible reason, but this page did not test it.
- Training on the 4-bit base costs the target task nothing but costs general ability. Row 8 (QLoRA, NF4 base for training and inference) reaches 85.5% accuracy, only 0.3 points below the 85.8% of row 3 and within noise; but its perplexity is 21.64 (19.10 in row 3) and its multiple-choice score 68.1% (72.8%). The adapter did not repair the damage done by quantization: the training data contain no general text, and the adapter was only asked to get the banking intents right.
- Train the adapter on the base it will serve on. The adapter trained on fp32 loses accuracy when attached to the NF4 base, from 85.8% to 84.3% (row 4). The adapter trained on NF4 scores 85.5% on the NF4 base and 84.1% when attached back to the fp32 base (row 7), where the general-ability probes return to the neighbourhood of the base model (perplexity 18.83, multiple choice 72.2%). Both directions lose about 1.5 points, far more than the seed noise (standard deviation about 0.2 points).
- Quantizing after merging costs part of the gain; merging into already-quantized weights and quantizing again costs all of it. Merging into the fp32 base and then quantizing the whole model to NF4 gives 83.6% and 84.0% (rows 5 and 9), 0.7 to 1.5 points below the unmerged adapter. Merging into weights that are already NF4 and quantizing again the same way gives 0.0%, identical to no adapter at all (rows 6 and 10), and perplexity and the multiple-choice score return to the level of the NF4 base.
The last point deserves a closer look. The code below computes, for the three matrices of layer 0, how much of each path keeps. It continues the previous code and reuses its nf4_roundtrip and model; the adapter is the one trained earlier on this page:
from safetensors.torch import load_file
adapter = load_file("banking-lora/adapter_model.safetensors")
for name in ("self_attn.q_proj", "mlp.up_proj", "mlp.down_proj"):
w = model.model.layers[0].get_submodule(name).weight.data
key = "base_model.model.model.layers.0." + name
a, b = adapter[key + ".lora_A.weight"], adapter[key + ".lora_B.weight"]
dw = 2.0 * (b @ a) # (alpha / r) * B A, here 32 / 16
on_grid = nf4_roundtrip(w) # the 4-bit base weights
into_nf4 = nf4_roundtrip(on_grid + dw) - on_grid # merge, quantize again
into_fp32 = nf4_roundtrip(w + dw) - on_grid # merge first, quantize
def kept(change):
"""Share of dW that survives: projection of the change on dW."""
return ((change * dw).sum() / (dw * dw).sum()).item()
print(f"{name}: mean |dW| {dw.abs().mean():.1e}, "
f"mean NF4 error {(w - on_grid).abs().mean():.1e}")
print(f" share of dW kept: merged into NF4 {kept(into_nf4):.3f}, "
f"merged into fp32 {kept(into_fp32):.3f}")
Output:
self_attn.q_proj: mean |dW| 2.0e-04, mean NF4 error 4.2e-03
share of dW kept: merged into NF4 0.018, merged into fp32 0.998
mlp.up_proj: mean |dW| 2.6e-04, mean NF4 error 1.4e-03
share of dW kept: merged into NF4 0.016, merged into fp32 0.996
mlp.down_proj: mean |dW| 1.0e-04, mean NF4 error 1.4e-03
share of dW kept: merged into NF4 0.016, merged into fp32 0.996
The “share kept” is the coefficient of the projection of the change in the quantized weights onto : 1 means is kept in full, 0 means it is wiped out. Already-quantized weights sit exactly on NF4 grid points, and the adapter’s update (about per element on average) is an order of magnitude smaller than the quantization error (about ), so rounding sends every weight back to its old grid point and only 1.6% to 1.8% is left. Starting from the fp32 weights is different: they do not sit on grid points, and adding a small pushes some of them across a boundary to the neighbouring grid point, so on average the update survives (99.6% to 99.8%) at the price of quantization noise, which is the 2.2 points that row 5 loses against row 3.
For deployment there are three ways: keep the adapter attached to the quantized base; merge into the original 16-bit weights and quantize the result once (rows 5 and 9); or restore the quantized base to 16 bits, merge the adapter, and serve in 16 bits without quantizing again. The one thing to avoid is merging the adapter into already-quantized weights and quantizing the same way once more (rows 6 and 10).
Troubleshooting
| Symptom | Common cause | What to do first |
|---|---|---|
| Training loss barely moves, accuracy stays near the baseline | The learning rate is too small (on this page 2e-5 reaches only 47.6% in 291 steps); target_modules matched no layer; gradient checkpointing is on but the input embeddings do not require gradients | Print model.print_trainable_parameters() to confirm that something is training; start from a learning rate of 2e-4; with gradient checkpointing call model.enable_input_require_grads() |
| Outputs are not valid class names, or generation does not stop | The label of the training examples has no end-of-sequence token; the inference prompt differs from the training prompt | Check that the encoded label ends with the end-of-sequence token and that its labels entry is not -100; use the training template at inference (on this page a reworded prompt drops accuracy from 85.8% to 79.4%) |
| The target metric rises while other abilities fall | The learning rate, , the rank or the number of epochs is too large | Run the forgetting probes with every evaluation; lower the learning rate or , or stop earlier (on this page a learning rate of 1e-3 gives 87.3% accuracy and 23.8% on the multiple-choice probe) |
| A larger rank does not catch up | Too few places are adapted (q and v only reaches 52.0%, and rank 128 only 77.9%) | Adapt all linear layers rather than compensating with rank |
| NaN appears | A batch whose labels are all -100 (the mean loss is 0/0); overflow in low precision; a learning rate that is too large | Check that every batch has at least one supervised token; fp16 overflows easily, so use bf16 or fp32; lower the learning rate |
| Results change after merging | Merging in bf16 or fp16 adds a rounding step; the merged model is quantized again afterwards | Merge in fp32 and convert to the deployment precision afterwards; compare the outputs before and after on your own evaluation set |
| Memory savings are smaller than expected | Activations dominate, and LoRA only saves gradients and optimizer state | Reduce the batch size, shorten the sequences, turn on gradient checkpointing; lora_dropout=0 saves one copy of the input per adapter |
| Production behaves worse than the offline evaluation | The evaluation set does not match production traffic; training and evaluation sets share examples | Deduplicate first, then draw a new evaluation set that resembles production traffic, as described in LLM evaluation methodology |
Summary and Exercises
Key points:
- LoRA writes the update as : starts training from the base model, a random lets move first (in the first step the gradient of is exactly 0), merging costs nothing at inference, and every adapted matrix gains parameters.
- Evaluate the target task and the forgetting probes together. A learning rate of 1e-3 has the highest accuracy in the whole learning-rate table (87.3%), yet its ARC-Easy multiple-choice score is only 23.8%, no better than guessing; looking at accuracy alone would pick it.
- The most sensitive knob is the learning rate, followed by the target modules. With fixed, the rank hardly matters between 1 and 128; with a larger rank amounts to a larger learning rate, so what it gains and what it forgets are two sides of one knob.
- Adapt all linear layers: q and v only reach 52.0%, rank 128 on them only 77.9%, while the three MLP matrices alone reach 85.5%.
- Full fine-tuning needs a learning rate 10 times or more below LoRA’s. Between 1e-5 and 3e-5 its accuracy barely moves (87.9% to 88.8%) while forgetting accelerates (multiple choice 72.8% falling to 30.1%). In this small experiment full fine-tuning lost to LoRA on neither accuracy nor forgetting; LoRA’s value is in memory, speed and size (a 35 MB adapter against 1.98 GB for the whole model), not in accuracy.
- LoRA saves gradients and optimizer state, not activations: at batch size 16 the peak memory is 8.0 GiB against 10.0 GiB for full fine-tuning, far less than the ratio of parameter counts.
- QLoRA stores the base in 4 bits. It saves base-model memory at the price of general ability: the NF4 base has a perplexity 13% higher than fp32. Merging into already-quantized weights and quantizing the same way again rounds the adapter away.
- Merge in fp32 before deployment and compare the outputs before and after merging on your own evaluation set; keep the prompt template identical to training (on this page a reworded prompt drops accuracy from 85.8% to 79.4%).
Quick self-test
1. In the first training step, what is the gradient of the matrix in LoRA?
- The same order of magnitude as the gradient of , so both matrices start learning together
- Exactly 0, because passes through and is initialized to 0
- Infinite, which is why gradient clipping is mandatory
- It depends on , and is nonzero once is large enough
In the
LoRALinearcheck on this page,|B.grad|is 11702.57 and|A.grad|is 0.0. After the first update is no longer 0 and starts receiving gradient. If both matrices were initialized to 0, both gradients would be 0 and training would stay at the origin forever; the paper’s convention is random and zero .
2. Raising the learning rate from 2e-4 to 1e-3 lifts target-task accuracy from 85.8% to 87.3%. Should you choose that configuration?
- Yes, it has the highest accuracy in the whole table
- No: the ARC-Easy score is only 23.8%, below the 25% of random guessing, and perplexity has risen to 28.92, so general ability has been destroyed
- Yes, the forgetting probes are not the target task, so ignore them
- It cannot be judged without rerunning the same configuration
The extra 1.5 points of accuracy were bought with general ability. That is why every evaluation should carry the forgetting probes: they fail while accuracy is still rising.
3. With fixed, raising the rank from 1 to 128 hardly changes accuracy; with , accuracy rises from 72.9% to 88.0% and perplexity from 17.40 to 27.81. What is the more plausible explanation?
- High-rank adapters learn new knowledge, so they are more accurate and also forget more easily
- With the amplification is always 2, the rank-one components simply add up, and the total change grows with the rank, quietly raising the learning rate; with fixed the amplification is and the total change is roughly independent of the rank
- A rank-1 adapter is exactly as expressive as a rank-128 one
- It is noise from the random seed
The standard deviation across seeds is only about 0.2 points, which cannot explain a gap of more than ten points. The mechanism is a reasonable guess; this page saw the effect on one model and one task and did not test the mechanism separately.
4. With a comparable number of trainable parameters (8.65 to 8.80 million), which configuration does best in this page’s experiments?
- q and v only, rank 128
- q, k, v, o, rank 64
- All 7 linear layers, rank 16
- There is no clear difference
Their accuracies are 77.9%, 83.0% and 85.8%. Concentrating the budget on a few kinds of matrices cannot be repaired by raising the rank; on this task the MLP is where most of the capacity sits.
5. At batch size 16 LoRA’s peak memory is 8.0 GiB, only 2.0 GiB below full fine-tuning’s 10.0 GiB. What is the main reason?
- The adapter has more parameters than expected
- Activations grow linearly with batch size and become the biggest item, which dilutes the savings in gradients and optimizer state
- LoRA has to keep a second copy of the base model
- It is an artifact of the MPS backend’s statistics
At batch size 4 the numbers are 3.5 against 7.5 GiB, a gap of 4.0 GiB; at batch size 16 the gap shrinks to 2.0 GiB. Setting
lora_dropoutto 0 lowers the peak at batch size 16 further, from 8.0 to 6.1 GiB, because dropout keeps a copy of the dropped-out input for every adapter.
6. What happens if you merge the adapter into base weights that are already quantized to NF4 and quantize the result the same way again?
- The result is almost the same as merging into fp32 weights and then quantizing
- Most of the adapter’s update is rounded away, accuracy returns to 0.0%, the same as with no adapter
- Accuracy improves slightly because quantization acts as a regularizer
- The model cannot be loaded
Weights that are already quantized sit exactly on NF4 grid points, and the adapter’s update is an order of magnitude smaller than the grid spacing, so rounding sends every weight back to its old grid point; the check on this page kept only 1.6% to 1.8% of it. Merging from the fp32 weights and then quantizing keeps the update (accuracy 83.6%).
Exercises:
- For Llama 2 7B (hidden size 4096, FFN size 11008, 32 layers, multi-head rather than grouped-query attention) with on all 7 linear layers, how many parameters does the adapter have? How large is it stored in fp32 and in bf16?
- You fine-tuned a customer-service model with LoRA; the target metric rose by 3 points, but general question answering got worse. Name three knobs to try first, with the direction and the cost of each and the metric you would use to see whether it helped.
- Let with and . Write the gradients of and in the first step, and explain why and cannot both be initialized to 0.
Reference answers
- The four attention matrices q, k, v and o are all , each adding parameters, 524,288 in total. The three MLP matrices gate, up and down map between 4096 and 11008, each adding parameters, 724,992 in total. That is 1,249,280 per layer and 39,976,960 for 32 layers. At 4 bytes per parameter fp32 takes about 160 MB (152.5 MiB); at 2 bytes bf16 takes about 80 MB (76.3 MiB).
- Three knobs to try first: lower the learning rate (watch accuracy and the probes: accuracy drops a little and forgetting eases noticeably); lower , or lower the rank when (equivalent to a smaller amplification, judged by the same metrics); train for fewer epochs or stop earlier (choose the stopping point with the probes on a validation set). Another remedy is mixing in general data (see SFT data construction and quality control). Change one knob at a time and keep the evaluation unchanged, otherwise you cannot tell which one helped.
- and . With the second gradient is exactly 0, while the first is nonzero as long as , so moves first and starts receiving gradient only after the first update. If both matrices were 0, both gradients would be 0, the parameters would never change, and training would stay at the origin.
Further Reading
- The paper: Hu et al., LoRA: Low-Rank Adaptation of Large Language Models; this site’s paper breakdown goes through the paper section by section and ends with the reproduction experiments from this page.
- QLoRA: Dettmers et al., QLoRA: Efficient Finetuning of Quantized LLMs, with a paper breakdown that rebuilds NF4 and reproduces the gaps between 4-bit data types on Qwen2.5; this site’s model quantization page covers other 4-bit schemes.
- LoRA against full fine-tuning: Biderman et al., LoRA Learns Less and Forgets Less (code and math tasks); Thinking Machines’ LoRA Without Regret (compares LoRA and full fine-tuning across dataset sizes, ranks and learning rates).
- The scaling factor: Kalajdzievski, A Rank Stabilization Scaling Factor for Fine-Tuning with LoRA (rsLoRA).
- Serving many adapters: Sheng et al., S-LoRA: Serving Thousands of Concurrent LoRA Adapters; the wider context is in LLM serving.
- Data and evaluation: SFT data construction and quality control, LLM evaluation methodology, Statistics for evaluation; the memory and compute accounting is in Compute and Memory.
- Tooling: Hugging Face’s PEFT documentation. Datasets used on this page: banking77 (Casanueva et al., Efficient Intent Detection with Dual Sentence Encoders), WikiText-2 and ARC-Easy.
- LoRA on a vision-language-action model (rank 32, about 1.4% of the parameters, success rate indistinguishable from full fine-tuning over 33 trials): the OpenVLA breakdown.
FAQ
- Which LoRA hyperparameter should I tune first?
- The learning rate. On Qwen2.5-0.5B with everything else fixed, raising it from 2e-5 to 5e-4 lifts banking77 accuracy from 47.6% to 86.9%. At 1e-3 accuracy on the target task is still 87.3%, but ARC-Easy multiple-choice accuracy falls to 23.8%, no better than guessing. Rank matters far less: with alpha fixed at 32, ranks from 1 to 128 all land between 85.2% and 86.4%.
- How should I set r, lora_alpha and target_modules?
- Start from the common defaults: r=16, lora_alpha=32, all linear layers, learning rate 2e-4 (measured here at 85.8%, with three seeds about 0.4 points apart). Coverage matters more than rank: adapting only q and v reaches 52.0%, while the three MLP matrices alone reach 85.5%. The ratio of lora_alpha to r sets the effective step size, so with alpha=2r a larger rank acts like a larger learning rate, and what you gain in accuracy and lose in general ability are two sides of the same knob.
- How much worse is LoRA than full fine-tuning?
- In this small experiment, not worse on accuracy: full fine-tuning (learning rate 1e-5) scores 87.9% and the best LoRA 88.0%, a gap of the size of the noise. LoRA did not forget less either: full fine-tuning at 1e-5 has a perplexity of 17.58, while the nine LoRA settings with accuracy of 86.5% or more bottom out at 18.90. LoRA wins on resources: 3.5 GiB against 7.5 GiB peak memory at batch size 4, a 35 MB adapter against 1.98 GB for the whole model. This is one 0.5B model, one classification task and one run per setting.
- How do I evaluate a LoRA fine-tune so I am not fooled?
- Measure the target task and one or two general-ability metrics, and compare with the untuned base model. Example from this page: LoRA at a learning rate of 1e-3 has the highest accuracy in the whole learning-rate table (87.3%), yet its perplexity went from the base model's 16.83 to 28.92 and its multiple-choice accuracy to 23.8%. Looking only at the target metric would pick this broken model. The prompt template must also match training: a different wording lowers accuracy noticeably.
- What goes wrong when I merge LoRA weights and quantize for deployment?
- Merge into the original 16-bit or 32-bit weights and quantize once. If you merge the adapter into weights that are already quantized and quantize again, the update is an order of magnitude smaller than the quantization grid and rounding erases it: accuracy fell back to 0.0% here, with only 1.6% to 1.8% of the update kept. QLoRA, which trains on a 4-bit base, costs the target task almost nothing (85.5%) but hurts general ability (perplexity 21.64 against 19.10 for default LoRA).