LoRA & Parameter-Efficient Fine-Tuning
Design LoRA and QLoRA training and releases with adapter budgets, target modules, memory estimates, compatibility contracts, evaluation evidence, and rollback.
What is LoRA fine-tuning?
Low-Rank Adaptation (LoRA) is a parameter-efficient way to specialize a pretrained model. The base model stays frozen. Training learns two much smaller matrices inside selected linear layers, and their product becomes a task-specific weight update.
In plain language: a team keeps one large foundation model and trains compact adapters for stable behaviors such as a response format, classification policy, or domain style. This reduces the parameters that need gradients, optimizer state, and separate checkpoint storage.
The core invariant is: an adapter is a versioned delta against one exact base-model and input-format contract, not a portable model by itself.
Four ideas explain the mechanism
Shared capability
Frozen base
The pretrained matrix W0 still participates in every forward pass, but its parameters do not receive optimizer updates.
Trainable delta
Low-rank path
Two matrices, A and B, learn a constrained update delta W = B A through a bottleneck of rank r.
Adaptation surface
Target modules
The recipe chooses which projections receive adapters: selected attention projections, every attention projection, or a broader set of linear layers.
Update strength
Scaling
Original LoRA applies the update as (alpha / r) B A x. Rank and alpha are separate choices even when recipes keep their ratio constant.
At initialization, a common setup makes one factor random and the other zero. The adapter therefore begins as a no-op: B A = 0, so wrapping a model does not immediately change its output.
Trace one adapted linear layer
For a frozen matrix W0 with shape d_out x d_in, the two trainable factors have shapes:
A:r x d_inB:d_out x r- trainable parameters:
r(d_in + d_out) - adapted output:
h = W0 x + (alpha / r) B A x
The base path and adapter path meet before the layer output
Only A and B are optimized. W0 remains frozen, but it must still be loaded for the forward and backward passes.
Shared input
Input activation x
The same activation enters the frozen transformation and the low-rank branch.
Base path
Frozen W0 x
Preserves the pretrained transformation without gradients for the base weights.
Adapter path
A then B
Compresses into r directions, expands back to the output width, and applies the scaling factor.
Layer output
Add both paths
The downstream layer receives the base result plus the learned task delta.
Low rank limits the dimension of the update; it does not prove that a chosen rank can represent every task. Rank, target modules, data, and optimization must be evaluated together.
Size the adapter before allocating hardware
The exact trainable count comes from matrix shapes, not from a fixed percentage of the model. Choose a Llama-like teaching fixture, adaptation surface, rank, base precision, sequence length, and GPU budget. The lab recomputes adapter parameters and a transparent memory floor.
Expose the real adapter and memory budget
Loading model shapes and planning assumptions...
Loading adapter budget...
The memory result is a planning floor, not a profiler. It includes frozen weights, a declared per-adapter-parameter training-state allowance, and an illustrative activation term. CUDA kernels, temporary buffers, fragmentation, attention implementation, checkpointing, and distributed strategy can move the real peak.
Change one capacity decision at a time
Rank controls the bottleneck width
- Begin with a modest rank and compare held-out task and slice metrics.
- Increase rank only when the lower-rank run underfits and the data or target-module coverage is not the actual bottleneck.
- Do not interpret a larger adapter as automatically better; extra capacity can memorize noise or make optimization less stable.
Target modules control where change is allowed
q_projandv_projform a narrow attention baseline with low storage and optimizer cost.- All attention projections broaden how token interactions can change.
- All linear layers also adapt feed-forward transformations and can substantially increase the parameter budget.
Alpha controls update scale
Original LoRA uses alpha / r. If rank changes while alpha stays fixed, the scale changes too. Treat rank, alpha, initialization, learning rate, and target modules as a jointly versioned recipe.
Use QLoRA when frozen-base memory is the constraint
QLoRA keeps the LoRA adapter trainable while storing the frozen base model in 4-bit quantized form. The original QLoRA recipe combines:
- NF4, a 4-bit data type designed for normally distributed pretrained weights;
- double quantization, which also quantizes quantization constants;
- paged optimizers, which manage memory spikes with unified memory;
- higher-precision computation for the operations that consume quantized weights.
QLoRA mainly reduces the frozen-base storage burden. It does not make activation memory, long contexts, data loading, evaluation, or optimizer behavior disappear. A 4-bit checkpoint is also not evidence that the task quality matches a higher-precision baseline.
Simpler baseline
LoRA on BF16/FP16
Use when the frozen base fits comfortably and the team wants a straightforward numerical baseline.
Memory constrained
QLoRA with NF4
Use when base-weight storage blocks the run and the hardware and kernels support the intended quantized path.
Largest update surface
Full fine-tuning
Use only when controlled evidence shows that the constrained adapter cannot meet the capability or quality target.
Build a reproducible adapter artifact
1 Measure
Freeze the task contract
Version the prompt or chat template, output schema, evaluation rubric, holdout groups, critical slices, and baseline result.
2 Identify
Pin model lineage
Record the immutable base revision, architecture, tokenizer files, special tokens, and template identity.
3 Configure
Declare the recipe
Record target modules, rank, alpha, dropout, initialization, quantization, compute dtype, optimizer, seed, and data manifest.
4 Learn
Train and inspect
Track optimization, throughput, memory, task metrics, rare slices, safety, and regressions against the frozen base.
5 Release
Package the delta
Store adapter weights, configuration, evidence, dependency versions, compatibility contract, rollback target, and integrity digest together.
Training loss answers whether the optimizer fits the training records. It does not answer whether the adapter generalizes, preserves base behavior, remains safe, or can load on the production runtime.
Recognize failure behavior before release
The run fails to learn
- Confirm that adapter parameters have
requires_grad=Trueand nonzero gradients. - Verify target-module names against the actual model architecture.
- Check labels, loss masking, padding, truncation, special tokens, and chat-template boundaries.
- Compare update norms and held-out metrics before simply raising rank or learning rate.
Training improves while validation degrades
- Select an earlier checkpoint instead of assuming the final step is best.
- Audit near-duplicate leakage and imbalance across rare or consequential slices.
- Reduce optimization pressure, improve data coverage, and rerun multiple seeds.
- Compare against the frozen base and prompt-only baseline on the same cases.
The adapter works offline but fails in serving
- Reject a different base revision, tokenizer, template, or architecture even when dimensions appear similar.
- Confirm the runtime supports the adapter format, target modules, dtype, and selected deployment mode.
- Validate a merged artifact separately; merging changes packaging, not the need for lineage and release evidence.
- Preserve the previous immutable base-plus-adapter manifest for rollback.
Prove the artifact fits the serving runtime
Choose an adapter, serving target, and deployment mode. The lab applies explicit compatibility, evidence, integrity, and rollback gates so a small checkpoint cannot bypass the controls used for a full model.
Treat the adapter and runtime as one release contract
Loading adapter and runtime manifests...
Loading release contracts...
Dynamic loading and merged serving optimize different operational goals. Neither mode makes an adapter independent of its training lineage.
Choose the deployment boundary deliberately
Load one frozen base and activate a named adapter per request, tenant, or deployment.
- Reduces duplicated base-model storage across tasks.
- Makes adapter routing, cache residency, concurrency, and tenant isolation part of the serving design.
- Requires the runtime to load the exact compatible base and adapter format.
- Keeps adapter rollback and switching independent from the base artifact.
Materialize W0 + delta W into a new full checkpoint during a controlled build.
- Removes the runtime adapter branch and can simplify a single-purpose serving path.
- Produces a larger artifact that must be evaluated, signed, distributed, and rolled back as a complete model.
- Requires enough build memory and a verified merge against the exact base revision.
- Loses cheap adapter swapping for that deployed artifact.
Keep several adapters or create an explicitly combined artifact only when the serving stack supports the operation.
- Define whether requests select one adapter, compose adapters, or use a separately evaluated merge.
- Treat rank growth, conflicting updates, cache pressure, and cross-tenant isolation as measured risks.
- Never assume two individually good adapters remain good after combination.
Operate LoRA as a versioned learning system
Monitor the training system
- peak allocated and reserved accelerator memory;
- tokens per second, examples per second, and data-loader stalls;
- gradient norms, update norms, loss curves, and numerical overflows;
- task, slice, safety, calibration, and base-regression metrics by checkpoint.
Monitor the serving system
- base, adapter, tokenizer, template, and runtime version on every release;
- adapter load failures, cache hit rate, swap latency, and active-adapter cardinality;
- p50, p95, and p99 latency plus memory pressure by adapter and sequence bucket;
- quality, policy, refusal, and schema failures by protected slice.
Define recovery before exposure
- Keep the previous immutable manifest and artifact digests.
- Roll back the adapter, base, prompt/template, tokenizer, or serving runtime independently when the boundary permits it.
- Canary on representative traffic and stop on critical slice or compatibility failures.
- Re-run release evidence whenever data, base revision, tokenizer, template, merge recipe, quantization path, or runtime changes.
Primary sources and scope
- The LoRA paper defines the low-rank update, zero-effect initialization, original
alpha / rscaling, target-matrix experiments, and mergeable linear design. - The QLoRA paper introduces NF4, double quantization, and paged optimizers for 4-bit base-model fine-tuning.
- The Hugging Face PEFT LoRA reference documents current configuration fields and adapter initialization behavior.
The lab models use declared teaching fixtures and transparent arithmetic. They are not performance forecasts. Profile the exact architecture, kernels, context distribution, precision, optimizer, hardware, and distributed strategy that will run in production.