The problem LoRA solves
Full fine-tuning updates every weight in the model. With mixed-precision Adam that costs about sixteen bytes per parameter: two for the weight, two for its gradient, four for the fp32 master copy and four each for the two moment estimates. For a 7B model that is roughly 112GB before a single activation is stored, which means a multi-GPU node for a task that might only need a few thousand examples. You also get a complete new copy of the model per task, which is expensive to store and impossible to switch between at request time.
LoRA starts from an observation about adaptation rather than pretraining: the change in weights needed to move a general model onto a specific task tends to have low intrinsic rank. You do not need to perturb all sixteen million entries of a projection matrix independently to change its behaviour; a much smaller subspace usually captures most of the effect. If that holds, the update can be represented as the product of two thin matrices, and only those need gradients and optimizer state.
The practical consequence is that the frozen base can be shared by many tasks. You keep one copy of the 7B weights and a handful of small adapter files, each a few tens of megabytes, and select between them per request. For a company running ten internal assistants on one base model, that is the difference between ten models in memory and one.
The mathematics
For a frozen weight matrix W0 of shape d by k, LoRA learns A of shape r by k and B of shape d by r, and uses W0 plus the scaled product B times A. The forward pass becomes the original projection plus a parallel branch, so the base computation is untouched. A is initialised with small random values and B with zeros, which makes the initial update exactly zero: training starts from the base model's behaviour rather than from noise.
The rank r is the only real capacity knob. The number of trainable parameters per adapted matrix is r times d plus k, so a 4096 by 4096 projection at rank 16 trains 131,072 parameters instead of 16.7 million, about 0.8 percent. Across the query, key, value, output and feed-forward projections of a 7B model, a rank-16 configuration typically lands somewhere between twenty and forty million trainable parameters, well under one percent of the model.
The scaling factor alpha divided by r multiplies the update. Its purpose is to keep the effective magnitude of the update roughly constant when you change rank, so you can sweep rank without re-tuning the learning rate from scratch. The common convention is alpha equal to twice the rank. A newer variant, rsLoRA, scales by the square root of r instead and behaves better at high ranks, where the standard scaling shrinks the update too aggressively.
Choosing rank, alpha and target modules
Rank 8 to 16 is enough for style, format and classification tasks. Rank 32 to 64 is more appropriate when you are teaching a genuinely new behaviour, such as a tool-call grammar or a domain-specific reasoning pattern, because the update has to represent more. Going above 64 rarely helps at 7B scale and mostly adds memory; if quality is still short at rank 64, the problem is usually data rather than capacity, and full fine-tuning is the honest next step.
Which modules to adapt matters as much as rank. Adapting only the attention projections is the cheapest and works for tone and format. Adapting every linear layer, including the gate, up and down projections in the feed-forward blocks, consistently performs better on knowledge-heavy and reasoning-heavy tasks because most parameters live there. A middle setting, attention plus the down projection, is a reasonable default when memory is tight.
- Start at rank 16 with alpha 32 on all linear layers; move to rank 8 only if you need to save memory or serve many adapters at once.
- Include the feed-forward layers if the task requires new vocabulary or domain reasoning, not just a new tone.
- Do not adapt norms, biases or the embedding table unless you have a specific reason; it adds parameters with little benefit.
- Try DoRA if plain LoRA underfits at low rank; it decomposes the update into magnitude and direction and often recovers quality at the same parameter count.
What QLoRA adds
QLoRA keeps the LoRA objective exactly as it is and changes how the frozen base is stored. The weights are quantised to 4-bit NormalFloat, a data type whose quantisation levels are placed at the quantiles of a normal distribution, which matches the roughly bell-shaped distribution of pretrained weights better than uniform 4-bit integers. Quantisation constants are themselves quantised, a trick called double quantisation, saving a further fraction of a bit per parameter. During the forward and backward pass, blocks are dequantised to bf16 to compute, so the adapters still train in high precision.
The memory effect is large. A 7B model in NF4 occupies about 3.5 to 4GB instead of 14GB, which leaves room on a 24GB card for activations, gradients for the adapters and a reasonable batch. The original QLoRA work fine-tuned a 65B model on a single 48GB GPU and reported quality comparable to 16-bit fine-tuning on its benchmarks, which is what made the method popular outside large labs.
Paged optimizers complete the picture. Optimizer state is kept in paged memory that can spill to CPU when a long sequence causes a transient spike, instead of triggering an out-of-memory crash mid-epoch. The trade-off is speed: 4-bit dequantisation makes each step measurably slower than bf16 LoRA, often by twenty to forty percent, and long-context batches still need gradient checkpointing to fit.
Training settings that actually matter
LoRA tolerates a much higher learning rate than full fine-tuning because it is training a small fresh subspace rather than perturbing a converged model. Somewhere between 1e-4 and 2e-4 is the usual range, an order of magnitude above typical full fine-tuning rates. Too low and the adapter barely moves; too high and you get repetition, degenerate formatting and a model that answers every prompt with the same opening phrase.
One to three epochs is typical. Beyond that, a small dataset gets memorised: training loss keeps falling while held-out quality drops and the model starts reproducing verbatim phrasings from the training set. Use a cosine schedule with a short warmup, a batch size as large as memory allows, and gradient accumulation to reach an effective batch of thirty-two to sixty-four examples. Enable gradient checkpointing for anything above a 2048-token sequence length.
Two details cause most of the disappointing results. First, mask the loss on prompt tokens so the model is trained on responses rather than on reproducing your instructions. Second, apply the exact chat template used at inference time, including the same special tokens, role names and separators; a mismatch here produces a model that appears to have learned nothing. Both are one-line settings that are easy to get wrong and hard to diagnose afterwards.
Why low rank is a reasonable bet
The low-rank assumption is empirical rather than mathematical. Work on intrinsic dimensionality showed that pretrained representations can be fine-tuned effectively within a much smaller subspace than the full parameter space: performance on downstream tasks often recovers most of the way with a few hundred free directions per layer. LoRA is a structured, hardware-friendly way to exploit that observation, not a proof that every useful update is low rank.
The distinction matters when you evaluate results. If a task requires genuinely new computation, such as learning a new language's morphology or a new formal grammar, the required update may not be low rank, and the adapter will underfit no matter how long you train. That is the signal to move to higher rank, full fine-tuning or continued pretraining rather than to keep adding epochs.
Data for adapter training
A few hundred to a few thousand examples is the normal range, and quality dominates. A thousand examples written by someone who understands the task, covering the range of inputs the product will actually see, routinely beats a hundred thousand scraped pairs with inconsistent formatting. The dataset is the specification: if the examples disagree about tone, length or what counts as a refusal, the adapter learns the disagreement.
Diversity is the part people skip. Cover different intents, different lengths, easy and hard cases, and the awkward inputs that currently fail. Include the negative cases, such as requests the model should decline or questions it should route elsewhere, because an adapter trained only on successful answers becomes confidently wrong at the edges. If you generate examples with a stronger model, keep the generator's outputs only after filtering, and keep a human-written core so the adapter does not inherit the generator's stylistic tics wholesale.
Formatting discipline pays for itself. Strip trailing whitespace, normalise the chat template, use one consistent refusal wording, and make sure every target ends with the end-of-sequence token so the model learns to stop. Cap example length to the context you will serve, and pack short examples into longer sequences rather than padding them, or a large share of your compute is spent on padding tokens that contribute nothing to the loss.
Serving the adapter
For a single task, the adapter can be merged into the base weights: the update is just a matrix addition, so merging is exact and inference incurs no extra latency or memory. Merging requires the base in the same precision you intend to serve, and merging into a 4-bit quantised base is lossy, so the usual path is to merge in bf16 and then quantise the result for deployment.
For many tasks, keep the adapters separate and let the server swap them per request. vLLM and several other serving stacks support multi-LoRA, batching requests that use different adapters against one shared set of base weights. The costs are a small per-token overhead and memory for each resident adapter, which is trivial at eighty megabytes per file. This is the pattern that makes one base model economically serve a dozen products.
Record which base revision each adapter was trained against and refuse to load it onto a different one. Adapters are tied to the exact tensor layout and tokenizer of their base, and a silent base upgrade produces either a load error or, worse, a model that runs and answers slightly wrong. Store the adapter with its training config, dataset hash and evaluation report, and treat the pair of base revision plus adapter as a single deployable artefact.
Limits and failure modes
- Adapters cannot add knowledge the base model never saw; facts that change often belong in retrieval, not in weights.
- Low rank can underfit a genuine behaviour change, which shows up as a model that learns the format but not the reasoning.
- 4-bit training introduces quantisation noise and can be sensitive to block size and hardware; validate against a bf16 LoRA run before trusting a result.
- Narrow datasets cause forgetting of general instruction following, especially at high learning rates.
- Evaluating on training prompts inflates results dramatically, because the adapter has seen those exact strings.
- A merged adapter is invisible in the weights, so provenance has to be recorded deliberately or nobody will know which tasks a deployed model contains.
A worked recipe
Take a 7B instruct base, 5,000 curated instruction-response pairs, and a single 24GB card. Load the base in NF4 with double quantisation and bf16 compute, attach rank-16 adapters with alpha 32 to every linear layer, enable gradient checkpointing, and train for two epochs at a learning rate of 2e-4 with an effective batch of 32 and a 2048-token limit. On a modern consumer card that is roughly four to eight hours and a few dollars of electricity.
Before training, hold out 300 examples and write a rubric: correctness, format compliance, refusal behaviour and a blind preference comparison against the base model. After training, evaluate on the held-out set and on fifty prompts that resemble real traffic rather than the training distribution. If the adapter wins on format but loses on general questions, lower the learning rate and add a small rehearsal set of general instructions. If it loses on domain questions, the data is too thin, not the rank.