Parameter-efficient fine-tuning: LoRA and QLoRA¶
To fine-tune a model you do not have to move all of its weights. LoRA freezes the pre-trained matrices and learns a small low-rank correction beside each one, cutting trainable parameters by a factor of hundreds to thousands; QLoRA also stores the frozen weights in 4 bits, so an 8B model can be adapted on one consumer GPU. The idea to keep: the change fine-tuning makes is far simpler than the model it changes.
10,000 ft
Every post-training method on this track — instruction tuning, DPO, RLHF, RL with verifiable rewards — is a way of choosing a weight update. Full fine-tuning lets that update touch every parameter, which means holding gradients and optimiser state for all of them: roughly 16 bytes per parameter, or about 128 GB for an 8B model before a single activation is stored. Parameter-efficient fine-tuning (PEFT) restricts the update to a tiny subspace. The method that won, LoRA (Hu et al., 2021), writes the update to each weight matrix as the product of two thin matrices; QLoRA (Dettmers et al., 2023) adds 4-bit storage of the frozen base. Together they made fine-tuning something individuals and small companies do, made "one base model, a thousand adapters" a serving pattern, and turned out to be enough even for frontier-style RL. The limits are just as instructive: LoRA learns less than full fine-tuning when the data carries a lot of information, and it forgets less for the same reason.
2,000 ft
A LoRA layer computes \(h = W_0 x + \tfrac{\alpha}{r} B A x\). \(W_0\) (\(d \times k\)) is frozen; \(A\) (\(r \times k\)) and \(B\) (\(d \times r\)) are trained, with \(r\) usually 8–64 against \(d, k\) in the thousands.
- Freeze every pre-trained weight.
- Attach an adapter pair \((A, B)\) to each chosen linear layer — today, usually all of them.
- Initialise \(A\) randomly and \(B\) to zero, so the model starts exactly at the pre-trained function.
- Train only \(A\) and \(B\) with the ordinary loss (SFT, DPO, RL — LoRA does not care).
- Deploy either by merging, \(W = W_0 + \tfrac{\alpha}{r}BA\) (zero extra latency), or by keeping adapters separate and hot-swapping them per request.
- QLoRA variant: store \(W_0\) in 4-bit NormalFloat, dequantise each block to bf16 on the fly for the matmul, and keep the adapters in bf16.
Ground level¶
The memory bill of full fine-tuning¶
Start with the arithmetic, because it is the whole reason the field exists. Standard mixed-precision training with AdamW keeps, for every parameter:
| Item | Bytes per parameter |
|---|---|
| bf16 weights used in the forward and backward pass | 2 |
| bf16 gradients | 2 |
| fp32 master copy of the weights | 4 |
| Adam first moment \(m\) (fp32) | 4 |
| Adam second moment \(v\) (fp32) | 4 |
| Total, before activations | 16 |
For Llama 3.1 8B (8.03B parameters) that is 128 GB — more than one 80 GB H100 — and activation memory comes on top, growing with batch size and sequence length. The distributed training page shows how FSDP/ZeRO shards these 16 bytes over many GPUs; PEFT attacks the same bill from the other side, by making almost every parameter not need gradients or optimiser state at all.
There is a second, quieter cost: storage and serving. A fully fine-tuned 8B model is a new 16 GB checkpoint per task or per customer. The LoRA paper's motivating example was GPT-3 175B, where each fine-tuned copy is 350 GB; with LoRA at \(r = 4\) on two attention matrices the task-specific checkpoint was 35 MB, "roughly 10,000×" smaller, and training VRAM fell from 1.2 TB to 350 GB (Hu et al., 2021, §4.2).
The PEFT family¶
LoRA was not the first idea, and the alternatives are worth knowing because each one fails in an instructive way.
| Family | Example | What is trained | Inference cost | Weakness |
|---|---|---|---|---|
| Additive adapters | Houlsby et al., 2019 | Small bottleneck MLPs inserted after attention and FFN sub-layers | Extra layers in series: added latency at small batch | Cannot be folded into the base weights |
| Soft prompts | Prefix-tuning, prompt tuning | Learned "virtual token" vectors prepended to the input or to every layer's keys and values | Uses up context length | Hard to optimise; competitive mainly at large scale |
| Selective | BitFit | Only the bias terms | None | Very limited capacity |
| Reparameterisation | LoRA and descendants | A low-rank factorisation of each weight's update | None once merged | Rank caps how much it can learn |
| Scaling vectors | (IA)³ | Per-channel multipliers on keys, values and FFN activations | None once folded | Even smaller capacity than LoRA |
Houlsby adapters reached within 0.4% of full fine-tuning on GLUE while adding about 3.6% extra parameters per task, and proved the premise of the whole field: a frozen pre-trained network plus a small task-specific module is enough. LoRA's two advantages over adapters were practical: it adds nothing to the forward pass once merged, and the update lives in the same space as the weights, so it can be added, subtracted, scaled and swapped — the basis for model merging.
LoRA, exactly¶
Take any linear layer \(h = W_0 x\) with \(W_0 \in \mathbb{R}^{d \times k}\). Full fine-tuning learns \(W_0 + \Delta W\) with \(\Delta W\) unconstrained (\(dk\) numbers). LoRA constrains the update to rank at most \(r\):
Three design decisions are packed into that line.
The parameter count drops from \(dk\) to \(r(d + k)\). For a \(4096 \times 4096\) attention projection at \(r = 16\) that is 131,072 trainable numbers instead of 16,777,216: 0.78%. For a whole model the saving is larger in absolute terms. Llama 3.1 8B has 32 blocks, each with four attention projections (\(q\) and \(o\) are \(4096 \times 4096\); \(k\) and \(v\) are \(4096 \times 1024\) because of grouped-query attention) and three MLP projections (\(4096 \times 14336\) twice, \(14336 \times 4096\) once). Adapters on all seven at \(r = 16\) come to 41.9M trainable parameters, 0.52% of the model; on \(q\) and \(v\) only, as in the original paper, 6.8M.
Initialisation makes training start exactly at the pre-trained model. \(A\) is random (Gaussian in the paper, Kaiming-uniform in the reference code), \(B\) is zero, so \(BA = 0\) at step 0. If both were zero, every gradient would be zero and nothing would ever move (see the maths); if both were random, the model would start somewhere else, and the first hundred steps would be spent undoing the damage.
The scale \(\alpha/r\) decouples the step size from the rank. The paper's own advice was modest: "we simply set \(\alpha\) to the first \(r\) we try and do not tune it." The common rule of thumb today is \(\alpha = 2r\), and rank-stabilised LoRA argues that the divisor should be \(\sqrt r\), not \(r\).
Merging and serving¶
At inference the adapter path can be folded away: \(W = W_0 + \frac{\alpha}{r} BA\) is an ordinary \(d \times k\) matrix, and the merged model is architecturally identical to the base. That is LoRA's headline advantage over adapters: zero added latency. The reverse is also cheap — keep one copy of the base in GPU memory and many adapters beside it, each a few tens of megabytes.
The two choices conflict. Once merged, a batch can only serve one adapter; unmerged, every request in a batch can use a different adapter, at the cost of an extra pair of small matmuls per layer. The LoRA paper flagged this ("it is not straightforward to batch inputs to different tasks with different A and B in a single forward pass"), and systems work solved it: Punica wrote a batched kernel for gathering different adapters per row, and S-LoRA pages adapter weights through a unified memory pool to serve thousands of adapters concurrently. Multi-LoRA serving is now standard in vLLM and similar engines (see serving LLMs), and it is how hosted fine-tuning products can give every customer their own model for roughly the price of one.
Which layers, which rank¶
The 2021 paper adapted only the attention projections and found, on GPT-3 with a fixed budget of 18M parameters, that adapting both \(W_q\) and \(W_v\) beat spending the budget on one of them at a higher rank, and that "a rank as small as one suffices for adapting both \(W_q\) and \(W_v\)" on those datasets — with the caveat that small \(r\) would not work for every task. Practice since has moved in one clear direction: put adapters on every linear layer, especially the MLPs.
- QLoRA found that LoRA on "all linear transformer block layers" was required to match 16-bit full fine-tuning, and that the number of adapted matrices mattered far more than \(r\) (Dettmers et al., 2023).
- Sebastian Raschka's ablations on a 7B model found the same: enabling LoRA on all layers raised trainable parameters from 4.2M to 20.3M and improved results, for 2.4 GB more memory (Practical tips, 2023).
- Thinking Machines' systematic study (Schulman et al., 2025) found attention-only LoRA "significantly underperforms" MLP-only LoRA even at matched parameter counts, and adding attention adapters on top of MLP adapters gave no further gain.
Rank is a capacity knob. Too low and the adapter cannot absorb the dataset; beyond that point, rank barely matters. How low is "too low" depends on how many bits of information the training signal carries — the subject of the next section.
Does LoRA match full fine-tuning?¶
The honest answer changed between 2021 and 2025, and the change is the most useful thing on this page.
Where it falls short. Biderman et al. (2024), "LoRA Learns Less and Forgets Less" compared LoRA with full fine-tuning on code and maths, in two regimes: instruction tuning (about 100K pairs) and continued pre-training (20B tokens). In standard low-rank settings LoRA "substantially underperforms" full fine-tuning — especially for continued pre-training — but keeps more of the base model's out-of-domain ability, more than weight decay or dropout do. Their diagnosis: full fine-tuning learns weight perturbations with a rank "10–100× greater than typical LoRA configurations".
Where it is the same. Schulman et al. (2025) ran LoRA and full fine-tuning across Llama 3 and Qwen3 models, with learning rates swept for both. For small-to-medium instruction and reasoning datasets, LoRA with enough rank matched full fine-tuning; it fell behind only when the dataset exceeded its capacity, and then by learning more slowly rather than hitting a hard floor. For reinforcement learning on maths, LoRA matched full fine-tuning "even with small ranks", down to \(r = 1\).
Why both are true: count the bits. A supervised example provides on the order of one training signal per token; a policy-gradient episode provides on the order of one number, its advantage. Schulman et al. give the arithmetic: about 10,000 MATH problems × 32 samples is roughly 320,000 bits of reward information, while a rank-1 LoRA on Llama-3.1-8B has about 3M parameters; even DeepSeek-R1-Zero's roughly 5.3M episodes carry less information than a low-rank adapter can hold. Continued pre-training on 20B tokens is at the opposite extreme. LoRA is a low-capacity channel; whether that matters depends on how much you are trying to push through it.
The update is also different, not just smaller. Shuttleworth et al. (2024) compared the singular value decompositions of LoRA-tuned and fully tuned weights. LoRA introduces new high-ranking singular vectors nearly orthogonal to the pre-trained ones — "intruder dimensions" — that full fine-tuning does not, and scaling them down after training recovers much of the forgotten pre-training behaviour at little cost to the task. Two models with equal benchmark scores can therefore have learned the task in structurally different ways, which matters when you continue to fine-tune or merge them.
Use a higher learning rate for LoRA than for full fine-tuning
The single most common LoRA mistake is copying the full fine-tuning learning rate. Schulman et al. measured the optimal LoRA learning rate at about 10× the optimal full fine-tuning rate, consistently across supervised and RL settings (closer to 15× for very short runs). Many "LoRA is worse" results in the literature are under-tuned learning rates.
QLoRA: fine-tuning on top of a 4-bit model¶
LoRA removed the optimiser state for the frozen weights but still held them in bf16: 16 GB for an 8B model, 130 GB for 65B. QLoRA (Dettmers et al., 2023) noticed that frozen weights are only ever read, so they can be stored in whatever compressed form you like as long as you can reconstruct a good-enough bf16 version at matmul time. Three pieces made that work without losing quality:
- 4-bit NormalFloat (NF4). Pre-trained weights are approximately normally distributed. A uniform 4-bit grid wastes levels in the tails where few weights live. NF4 places its 16 levels at quantiles of a standard normal, so each level is used about equally often — the paper calls it "information theoretically optimal" for normal data — and uses an asymmetric construction so that zero is represented exactly. Weights are scaled per block of 64 by the block's absolute maximum before rounding.
- Double quantisation. Each block of 64 needs a scale constant. In fp32 that is \(32/64 = 0.5\) extra bits per parameter. QLoRA quantises the constants themselves to 8 bits, in blocks of 256 with one fp32 constant each: \(8/64 + 32/(64 \cdot 256) = 0.127\) bits, a saving of 0.373 bits per parameter, or about 3 GB on a 65B model.
- Paged optimisers. Long sequences cause memory spikes in the backward pass. Optimiser states are allocated in NVIDIA unified memory and evicted page by page to CPU RAM when the GPU runs out, instead of crashing the run.
The compute still happens in bf16: storage is 4-bit, arithmetic is not. Gradients flow through the dequantised \(W_0\) (they must, to reach the adapters in earlier layers) but are never accumulated into it. The result: a 65B model fine-tuned on one 48 GB GPU, down from more than 780 GB, while matching 16-bit full fine-tuning on the paper's benchmarks; their Guanaco model reached 99.3% of ChatGPT's score on the Vicuna benchmark after 24 hours on one GPU (a benchmark the same paper warns is not very trustworthy). The price is speed: dequantising every block on every forward and backward pass costs time — about 39% longer training for 33% less memory in Raschka's 7B measurements.
Variants worth knowing¶
The LoRA literature has hundreds of variants. These five change something real:
- rsLoRA (Kalajdzievski, 2023) proves that the adapter
should be scaled by \(\alpha/\sqrt r\), not \(\alpha/r\); with \(\alpha/r\), higher ranks learn more
slowly, which is part of why early practice found rank "did not matter". In Hugging Face PEFT
it is one flag (
use_rslora=True). - LoRA+ (Hayou et al., 2024) gives \(B\) a larger learning rate than \(A\); width-scaling arguments show a single shared rate is suboptimal for wide models. Reported: 1–2% better and up to about 2× faster.
- DoRA (Liu et al., 2024) splits each weight into a per-column magnitude and a direction, \(W = m \cdot \frac{W_0 + BA}{\lVert W_0 + BA \rVert_c}\), trains \(m\) directly and the direction with LoRA. It mimics a pattern the authors observed in full fine-tuning (magnitude and direction changing somewhat independently) and still merges to an ordinary matrix.
- PiSSA (Meng et al., 2024) initialises \(A\) and \(B\) from the top singular vectors of \(W_0\) and freezes the residual, so the adapter starts on the directions that matter most instead of on random ones.
- GaLore (Zhao et al., 2024) is the inverse idea: train all weights, but project the gradient (and so the optimiser state) onto a low-rank subspace that is refreshed periodically. It saves memory like LoRA without constraining the final update to be low-rank.
History¶
Low-rank structure in neural networks is an old observation — low-rank factorisation was used
to compress networks well before transformers — but the line that leads to LoRA starts
with transfer learning in NLP. In 2019 Neil Houlsby and colleagues at Google introduced adapters
for BERT, arguing that one frozen model plus small per-task modules made a "compact and
extensible" system. In 2020 Armen Aghajanyan, Luke Zettlemoyer and Sonal Gupta at Facebook
measured the intrinsic dimension of fine-tuning and found it tiny. In June
2021 Edward Hu, Yelong Shen, Phillip Wallis and colleagues at Microsoft, who needed to adapt
GPT-3 175B for many products, put the two ideas together: if the update has low intrinsic
dimension, parameterise it as a low-rank matrix directly. Their GitHub package, loralib, was
followed by Hugging Face's peft library in early 2023, and LoRA became the default.
The second wave came with open weights. After LLaMA's release in February 2023, Stanford's Alpaca
showed a 7B model could be instruction-tuned for under USD 600, and a community formed around
fine-tuning on single GPUs. Tim Dettmers, who had already written the 8-bit bitsandbytes
kernels, released QLoRA in May 2023 with Artidoro Pagnoni, Ari Holtzman and Luke Zettlemoyer;
fine-tuning 65B models on one 48 GB card turned a datacentre activity into a hobbyist one. (The
image-generation community had meanwhile adopted LoRA files as the way to share a fine-tuned
style or character for Stable Diffusion.) 2024 brought
careful comparisons (LoRA learns less and forgets less), and 2025 a reassessment: with the right
learning rate and all layers adapted, LoRA matches full fine-tuning across much of post-training,
including RL.
First principles¶
Why should the update be low-rank at all?¶
Two facts, one empirical and one structural.
Empirically, fine-tuning has low intrinsic dimension. Li et al. (2018) defined the intrinsic dimension of a problem as the smallest \(D\) such that optimising only \(\theta = \theta_0 + P z\), with \(z \in \mathbb{R}^D\) and \(P\) a fixed random projection, reaches 90% of full performance. Aghajanyan et al. (2020) applied it to fine-tuning: optimising "only 200 trainable parameters randomly projected back into the full space" took RoBERTa to 90% of full fine-tuning performance on MRPC. They also found that pre-training lowers intrinsic dimension, and that larger models have lower intrinsic dimension — which explains why bigger models are easier, not harder, to adapt with few parameters. Pre-training has already built the features; fine-tuning only has to recombine a few of them.
Structurally, each gradient of a linear layer is already low-rank. For \(h = Wx\), the gradient from one token is an outer product \(\delta x^\top\) (where \(\delta = \partial L/\partial h\)): rank 1. A batch of \(n\) tokens gives a sum of \(n\) outer products, rank at most \(n\), and in practice the inputs \(x\) of a trained network occupy a much lower-dimensional subspace than \(k\). So each step of full fine-tuning already moves \(W\) in a structured, mostly low-dimensional way; LoRA forces the accumulated update to stay in an \(r\)-dimensional subspace.
What breaks if you change the design¶
- Make both factors zero: gradients for \(A\) depend on \(B\) and vice versa, so both stay zero forever. One factor must be non-zero to break the symmetry.
- Make both factors random: the model starts at \(W_0 + BA \neq W_0\), a random perturbation of a carefully trained network, and the first part of training is wasted repairing it.
- Drop the \(\alpha/r\) scale: changing \(r\) then changes the effective learning rate as well as capacity, and you can no longer compare ranks fairly. (\(\alpha/\sqrt r\) fixes this better.)
- Put adapters on attention only: most of a transformer's parameters, and much of what it "knows", sit in the MLPs; attention-only adapters cannot reach them.
- Quantise the adapters too: the adapter carries the entire learned update; its rounding error is not diluted by anything. QLoRA quantises only what is frozen.
The maths¶
Forward pass and gradients¶
Write \(s = \alpha/r\) and the effective weight \(W = W_0 + sBA\). Let \(G = \partial L/\partial W\) be the gradient full fine-tuning would use (a \(d \times k\) matrix, the sum over tokens of \(\delta_t x_t^\top\)). Since \(L\) depends on \(A\) and \(B\) only through \(W\), use the differential \(dL = \operatorname{tr}(G^\top dW)\):
You never form \(G\) in practice — autograd computes \(\partial L/\partial B = s\,\sum_t \delta_t (A x_t)^\top\) directly from the \(r\)-dimensional activations \(Ax_t\) — but writing it this way shows how LoRA relates to full fine-tuning.
The first step is a random projection of the full gradient¶
At step 0, \(B = 0\), so \(\partial L/\partial A = 0\) and only \(B\) moves. One SGD step with rate \(\eta\) gives \(\Delta B = -\eta s\, G A^\top\), and the change in the effective weight is
\(A^\top A\) is a \(k \times k\) matrix of rank \(r\): the first LoRA step is the full-gradient step with its input side squeezed through the \(r\) random directions that \(A\)'s rows span. With \(A_{ij} \sim \mathcal N(0, 1/k)\), \(\mathbb E[A^\top A] = \tfrac{r}{k} I\), so for a gradient with no special structure the LoRA step keeps a fraction about \(\sqrt{r/k}\) of the full step's direction (the code below measures cosine 0.124 against \(\sqrt{8/512} = 0.125\)). Real gradients are far from structureless, which is why LoRA works much better than that worst case: the gradient's energy lies in few directions, and training rotates \(A\) toward them.
To first order in \(\eta\), a general step changes the effective weight by
a full-gradient step preconditioned on the input side by \(A^\top A\) and on the output side by \(BB^\top\), both of rank at most \(r\). This is also why LoRA's dynamics are not simply "full fine-tuning restricted to a subspace": the subspace itself moves, and the product parameterisation is what makes LoRA sensitive to batch size and to the relative learning rates of \(A\) and \(B\) (LoRA+).
How rank and \(\alpha\) interact¶
Combine the first-step formula with \(s = \alpha/r\): the expected size of the first SGD step scales as \(s^2 \cdot r/k = \alpha^2/(rk)\). Hold \(\alpha\) fixed and double \(r\), and the step halves. Kalajdzievski's rsLoRA analysis carries this through training with Adam and shows that only \(s \propto 1/\sqrt r\) keeps both the adapter's output and its gradients stable as \(r\) grows; under \(s \propto 1/r\), large ranks are starved.
Compute¶
Per token, a \(d \times k\) layer costs about \(2dk\) FLOPs forward, and full fine-tuning's backward costs twice that (gradient with respect to the input and with respect to the weight): \(6dk\) in all. LoRA skips the weight-gradient matmul for \(W_0\) and adds small terms for the adapters. For a square layer of width \(N\), Schulman et al. count \(2N^2 + 6NR\) multiply–adds per token against \(3N^2\) for full fine-tuning, a ratio of
so about 0.674 for \(R = 16\), \(N = 4096\). LoRA saves roughly a third of the compute, not 99%: the expensive part, pushing activations and gradients through \(W_0\), remains.
NF4¶
Quantile quantisation picks the \(2^b\) levels so that each is equally likely under the data distribution. For a standard normal with quantile function \(Q\), the QLoRA paper writes the levels as
then normalises them to \([-1, 1]\). Because 16 levels symmetric around zero cannot include zero itself, NF4 builds the negative and positive halves separately (7 negative levels, zero, 8 positive) — the asymmetric construction in the reference code. A weight \(w\) in a block with absolute maximum \(c\) is stored as the index of the level nearest to \(w/c\) and reconstructed as \(c \cdot q_{\text{index}}\).
Memory per parameter is \(b + \text{(constant bits)}/\text{(block size)}\):
Build it¶
Two NumPy experiments (no PyTorch needed). The first trains LoRA by hand on a layer whose true update is rank 4, and checks it against the best possible rank-\(r\) answer from the SVD (Eckart–Young). The second verifies the first-step projection formula and builds NF4.
import numpy as np
rng = np.random.default_rng(0)
d, n = 64, 4096
W0 = rng.normal(0, 1/np.sqrt(d), (d, d)) # frozen "pre-trained" weight
U, _ = np.linalg.qr(rng.normal(size=(d, d)))
V, _ = np.linalg.qr(rng.normal(size=(d, d)))
s_true = np.array([3.0, 2.0, 1.0, 0.5]) # the task's update is rank 4 ...
dW_true = (U[:, :4] * s_true) @ V[:, :4].T
dW_true += 0.01 * rng.normal(size=(d, d)) # ... plus a little full-rank noise
X = rng.normal(size=(n, d))
Y = X @ (W0 + dW_true).T
def train_lora(r, alpha=16, steps=3000, lr=1e-2):
A = rng.normal(0, 1/np.sqrt(d), (r, d)) # A random, B zero: ΔW = 0 at step 0
B = np.zeros((d, r))
s = alpha / r
m = [np.zeros_like(A), np.zeros_like(B)]; v = [np.zeros_like(A), np.zeros_like(B)]
for t in range(1, steps + 1):
err = X @ (W0 + s * B @ A).T - Y # (n, d)
G = 2 * err.T @ X / n # dL/dW_eff, (d, d)
grads = [s * B.T @ G, s * G @ A.T] # dL/dA, dL/dB
for i, (p, g) in enumerate(zip([A, B], grads)): # Adam
m[i] = 0.9 * m[i] + 0.1 * g; v[i] = 0.999 * v[i] + 0.001 * g * g
p -= lr * (m[i] / (1 - 0.9**t)) / (np.sqrt(v[i] / (1 - 0.999**t)) + 1e-8)
return A, B, s, np.mean(np.sum(err**2, axis=1))
sv = np.linalg.svd(dW_true, compute_uv=False)
print("singular values of the true update:", np.round(sv[:6], 3))
for r in [1, 2, 4, 8]:
A, B, s, loss = train_lora(r)
best = np.sum(sv[r:]**2) # Eckart–Young: best rank-r residual
print(f"r={r}: trainable={r*2*d:5d} of {d*d} loss={loss:.4f} rank-r optimum={best:.4f}")
W_merged = W0 + s * B @ A # merge the r=8 adapter
x = rng.normal(size=d)
print("merged vs adapter path, max diff:", np.abs(W_merged @ x - (W0 @ x + s * B @ (A @ x))).max())
Output:
singular values of the true update: [3.002 2.006 1.016 0.522 0.142 0.138]
r=1: trainable= 128 of 4096 loss=5.6803 rank-r optimum=5.6833
r=2: trainable= 256 of 4096 loss=1.6811 rank-r optimum=1.6585
r=4: trainable= 512 of 4096 loss=0.3555 rank-r optimum=0.3529
r=8: trainable= 1024 of 4096 loss=0.2788 rank-r optimum=0.2774
merged vs adapter path, max diff: 1.1102230246251565e-15
Read it slowly. Each LoRA run lands on the Eckart–Young optimum for its rank (to within the sampling noise of a finite batch, which is why \(r = 1\) can land a hair under it): gradient descent on the factored form finds the best rank-\(r\) update. The loss falls steeply until \(r\) reaches the true rank of 4, then flattens, because the remaining error is full-rank noise that no low-rank adapter can fit. That is the capacity story of the whole page in four lines. And merging is exact to floating-point precision.
import numpy as np
from statistics import NormalDist
rng = np.random.default_rng(1)
# 1) LoRA's first step is the full gradient projected onto r random input directions.
d, r, eta, s = 512, 8, 1.0, 2.0
G = rng.normal(size=(d, d)) # a full-rank gradient dL/dW
A = rng.normal(0, 1/np.sqrt(d), (r, d)); B = np.zeros((d, r))
dB = -eta * s * G @ A.T # only B moves at step 1 (dL/dA = s·Bᵀ·G = 0)
dW = s * dB @ A # = -η s² G AᵀA
print("rank of first LoRA update:", np.linalg.matrix_rank(dW))
print("equals -η s² G AᵀA:", np.allclose(dW, -eta * s * s * G @ A.T @ A))
cos = np.sum(dW * -G) / (np.linalg.norm(dW) * np.linalg.norm(G))
print(f"cosine(first LoRA step, full gradient step) = {cos:.3f} sqrt(r/d) = {np.sqrt(r/d):.3f}")
# 2) NF4: 16 levels at quantiles of N(0,1) (QLoRA's construction), vs uniform INT4.
N, off = NormalDist(), 0.9677083
pos = [N.inv_cdf(p) for p in np.linspace(off, 0.5, 9)[:-1]]
neg = [-N.inv_cdf(p) for p in np.linspace(off, 0.5, 8)[:-1]]
nf4 = np.sort(np.array(pos + [0.0] + neg)); nf4 /= nf4.max()
int4 = np.arange(-7, 8) / 7 # symmetric absmax INT4 (15 levels)
print("NF4 levels:", np.round(nf4, 3))
w = rng.normal(0, 0.02, 64 * 4096).reshape(-1, 64) # Gaussian weights, blocks of 64
scale = np.abs(w).max(axis=1, keepdims=True) # absmax per block
for name, lv in [("INT4", int4), ("NF4 ", nf4)]:
q = lv[np.abs((w / scale)[..., None] - lv).argmin(-1)] * scale
print(f"{name}: RMS error / RMS weight = {np.sqrt(np.mean((q-w)**2))/w.std():.4f}")
bits = lambda c_bits, extra: 4 + c_bits / 64 + extra
print("bits/param, fp32 block constants:", bits(32, 0))
print("bits/param, double-quantised :", round(bits(8, 32 / (64 * 256)), 3))
Output:
rank of first LoRA update: 8
equals -η s² G AᵀA: True
cosine(first LoRA step, full gradient step) = 0.124 sqrt(r/d) = 0.125
NF4 levels: [-1. -0.696 -0.525 -0.395 -0.284 -0.185 -0.091 0. 0.08 0.161
0.246 0.338 0.441 0.563 0.723 1. ]
INT4: RMS error / RMS weight = 0.1080
NF4 : RMS error / RMS weight = 0.0920
bits/param, fp32 block constants: 4.5
bits/param, double-quantised : 4.127
The NF4 levels printed are the ones in the bitsandbytes NF4 table (−1, −0.696, …, 0.723, 1),
reconstructed from nothing but the normal quantile function. On Gaussian weights they cut the
quantisation error by about 15% relative to a uniform 4-bit grid at the same memory.
In real code you would not write any of this. The PyTorch version of a LoRA layer is a dozen lines (PyTorch, not run here):
import math, torch, torch.nn as nn
class LoRALinear(nn.Module):
def __init__(self, base: nn.Linear, r=16, alpha=32):
super().__init__()
self.base = base.requires_grad_(False) # frozen W0 (and bias)
self.A = nn.Parameter(torch.empty(r, base.in_features))
self.B = nn.Parameter(torch.zeros(base.out_features, r)) # zero: start at W0
nn.init.kaiming_uniform_(self.A, a=math.sqrt(5))
self.scale = alpha / r # alpha / math.sqrt(r) for rsLoRA
def forward(self, x):
return self.base(x) + self.scale * (x @ self.A.T) @ self.B.T
and with Hugging Face peft and bitsandbytes, QLoRA on a causal LM is a configuration:
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)
model = AutoModelForCausalLM.from_pretrained("<base-model-id>", quantization_config=bnb)
model = prepare_model_for_kbit_training(model)
model = get_peft_model(model, LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
target_modules="all-linear", task_type="CAUSAL_LM"))
model.print_trainable_parameters()
Things to try
- In the first script, switch to rsLoRA scaling (
s = alpha / np.sqrt(r)) and compare how fast each rank converges in the first 200 steps. - Initialise both
AandBto zero and confirm that nothing trains. Then initialise both randomly and watch the starting loss. - Replace the rank-4
dW_truewith a full-rank update whose singular values decay like \(1/i\) and plot loss against \(r\). Where is the knee? - Quantise
wwith NF4 using block sizes 32, 64, 256, 4096 and plot error against the bits spent on constants. Why did QLoRA choose 64? - Do the LoRA project: a real fine-tune of a small model, end to end.
In practice¶
| Setting | Sensible default (2026) | Why |
|---|---|---|
| Target modules | All linear layers ("all-linear") |
MLP adapters carry most of the benefit |
| Rank \(r\) | 16–64 for SFT; 1–32 is plenty for RL | Capacity must exceed the information in the data |
| \(\alpha\) | \(2r\) with \(\alpha/r\); or set use_rslora=True |
Keeps step size comparable across ranks |
| Learning rate | About 10× your full fine-tuning rate | Measured optimum ratio (Schulman et al., 2025) |
| Dropout on adapters | 0–0.05 | QLoRA found it useful at 7B–13B, not at 33B–65B |
| Epochs | 1–3; watch held-out loss | Multi-epoch runs on small data overfit fast |
| Batch size | Moderate | LoRA tolerates very large batches less well than full FT |
| Quantisation | QLoRA when memory-bound, bf16 LoRA when time-bound | QLoRA trades speed for memory |
Gotchas that cost people days:
- Merging into the wrong base. An adapter trained with QLoRA saw dequantised NF4 weights. Merge it into the bf16 original and evaluate the merged model; merging into a 4-bit model and re-quantising can round small updates away entirely.
- New tokens need trainable embeddings. If you add special tokens (a new chat template, tool
tags), the new embedding rows and the output head must be trained, which LoRA on linear
layers does not do. In PEFT, list them in
modules_to_save. - Chat templates. A LoRA trained on one template and served with another fails silently. This is an SFT problem, not a LoRA problem, but adapters make it easy to mix bases and templates.
- Evaluate forgetting. LoRA forgets less, not nothing. Keep a small general benchmark in your eval suite alongside the target task (see evals in practice).
- Know when to stop using it. Continued pre-training on billions of tokens, or teaching a model a new language, is beyond a low-rank adapter's capacity; use full fine-tuning, or a much higher rank, there.
Common misconceptions¶
“LoRA makes training 100× cheaper”
It makes memory for gradients and optimiser state 100× cheaper, and checkpoints 1,000× smaller. Compute per step falls only to about two-thirds of full fine-tuning, because the forward and backward passes through the frozen weights still happen. QLoRA is slower than LoRA per step.
“QLoRA trains a 4-bit model”
Only the frozen base is stored in 4 bits. Matmuls run in bf16, and the adapters are bf16. The trained artefact is a bf16 adapter.
“Higher rank is always better”
Above the information content of your data, more rank buys nothing and costs memory. Under the original \(\alpha/r\) scaling, higher rank with fixed \(\alpha\) can even train worse, because it shrinks the step size.
Check yourself¶
Why is \(B\) initialised to zero and \(A\) randomly, rather than both to zero or both randomly?
\(\partial L/\partial A = sB^\top G\) and \(\partial L/\partial B = sGA^\top\). If both are zero, both gradients are zero forever. If both are random, \(W_0 + sBA \neq W_0\) at step 0, so the model starts at a randomly perturbed version of the pre-trained network. Zero \(B\) and random \(A\) gives an exact start at \(W_0\) and a non-zero gradient for \(B\) on the first step.
How many trainable parameters does a rank-16 adapter add to a 4096 → 14336 MLP up-projection? What fraction of the matrix is that?
\(r(d + k) = 16 \times (14336 + 4096) = 294{,}912\), against \(4096 \times 14336 = 58{,}720{,}256\): 0.50%.
Merging gives zero inference overhead. Why do multi-tenant services usually not merge?
A merged matrix serves one adapter. A batch mixing requests for different customers would need a separate merged copy of every layer per adapter. Keeping adapters unmerged costs two small extra matmuls per layer but lets each row of the batch use a different adapter (Punica, S-LoRA), with one shared base in memory.
With \(s = \alpha/r\) and \(\alpha\) fixed, what happens to the size of the first SGD step when you double \(r\)?
\(\Delta W = -\eta s^2 G A^\top A\) and \(\mathbb E[A^\top A] = (r/k) I\), so the step scales as \(\alpha^2/(rk)\): doubling \(r\) halves it. Higher rank silently means a smaller learning rate, which is the problem rsLoRA's \(\alpha/\sqrt r\) scaling addresses.
Why can rank-1 LoRA match full fine-tuning for RL on maths, but not for continued pre-training on 20B tokens?
Capacity has to exceed the information in the training signal. A policy-gradient episode carries about one number (its advantage), so even millions of episodes carry fewer bits than a rank-1 adapter on an 8B model has parameters (about 3M). Continued pre-training provides a supervised signal for every one of 20B tokens; no low-rank adapter can absorb that, and Biderman et al. found full fine-tuning's learned update has 10–100× higher rank there.
Your QLoRA adapter evaluates well unmerged. After you merge it into the 4-bit model and re-quantise, quality drops. Why, and what should you do?
Re-quantisation rounds \(W_0 + sBA\) to the NF4 grid, block by block. The update is small relative to each block's absolute maximum, so much of it falls inside a single quantisation step and is rounded away or distorted. Merge into the bf16 base instead (and evaluate the merged model, since the adapter was trained against dequantised rather than original weights), or serve the adapter unmerged on top of the quantised base.
LoRA and full fine-tuning reach the same score on your task. Are the two models equivalent?
Not necessarily. Shuttleworth et al. found LoRA introduces "intruder dimensions": new high-magnitude singular vectors nearly orthogonal to the pre-trained ones, which full fine-tuning does not create and which are associated with forgetting. The two can differ on out-of-domain behaviour, on further fine-tuning and when merged with other models.
Hard: QLoRA's gradients flow through the 4-bit weights. Why is that not a precision problem?
The backward pass needs \(W_0^\top \delta\) to propagate gradients to earlier layers, and it uses the same dequantised bf16 \(W_0\) as the forward pass, so the computation is self-consistent: the adapters are trained to be correct for the quantised base they will run with. No gradient is ever accumulated into the 4-bit numbers, which is where low precision would hurt (tiny updates would round to zero). The residual risk is the quantisation error of \(W_0\) itself, which NF4 and small blocks keep small.
Go deeper¶
Papers
- LoRA: Low-Rank Adaptation of Large Language Models — Hu et al., 2021. Sections 4 and 7: the method, the which-matrices ablation, and the analysis of what \(\Delta W\) amplifies.
- QLoRA: Efficient Finetuning of Quantized LLMs — Dettmers et al., 2023. NF4, double quantisation, paged optimisers, and the "adapters on all layers" finding.
- Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning — Aghajanyan, Zettlemoyer, Gupta, 2020. The empirical foundation LoRA stands on.
- Measuring the Intrinsic Dimension of Objective Landscapes — Li et al., 2018. Where the random-subspace training trick comes from.
- Parameter-Efficient Transfer Learning for NLP — Houlsby et al., 2019. Adapters: the paper that started PEFT.
- LoRA Learns Less and Forgets Less — Biderman et al., 2024. The careful negative result: where LoRA underperforms, and why it still protects the base model.
- LoRA vs Full Fine-tuning: An Illusion of Equivalence — Shuttleworth et al., 2024. Intruder dimensions: equal scores, different solutions.
- A Rank Stabilization Scaling Factor for Fine-Tuning with LoRA — Kalajdzievski, 2023. Why \(\alpha/\sqrt r\).
- DoRA: Weight-Decomposed Low-Rank Adaptation — Liu et al., 2024. Magnitude and direction trained separately.
- S-LoRA: Serving Thousands of Concurrent LoRA Adapters — Sheng et al., 2023. The systems side: one base, many adapters.
Articles and blog posts
- LoRA Without Regret — John Schulman and Thinking Machines, 2025. The best modern study: when LoRA equals full fine-tuning, the 10× learning-rate rule, and the bits-per-episode argument for RL.
- Practical Tips for Finetuning LLMs Using LoRA — Sebastian Raschka, 2023. Hundreds of ablations on one GPU: rank, alpha, layers, QLoRA's speed cost.
- Making LLMs even more accessible with bitsandbytes, 4-bit quantization and QLoRA — Hugging Face, 2023. The practical QLoRA walkthrough by the library authors.
Videos and lectures
- What is Low-Rank Adaptation (LoRA), explained by the inventor — Edward Hu. Why the team built it and what they expected.
- LoRA explained visually + PyTorch code from scratch — Umar Jamil. Derivation and implementation in one sitting.
- QLoRA: Efficient Finetuning of Quantized LLMs — Tim Dettmers, AMLD. The first author on NF4 and what makes 4-bit fine-tuning work.
Code
- microsoft/LoRA — The original
loralib, short enough to read in full. - huggingface/peft — The standard library: LoRA, DoRA, rsLoRA, prompt tuning, IA³ and adapter merging.
- artidoro/qlora — The QLoRA reference implementation and Guanaco training scripts.
- unslothai/unsloth — Hand-written kernels that make single-GPU LoRA and QLoRA much faster.
Where this leads¶
- Project: fine-tune a model with LoRA — do it for real on your own data.
- Quantisation: INT8, INT4, GPTQ, AWQ — the inference-side counterpart of NF4, and why post-training quantisation is harder than storage-only quantisation.
- Model merging and continual learning — LoRA updates are task vectors; add, subtract and combine them.
- Distillation and synthetic data — where the data for most LoRA fine-tunes now comes from.
- Serving LLMs — multi-adapter batching inside a real inference engine.