Skip to content

19.5 Parameter-efficient fine-tuning

This part of Choosing Training and Adaptation Methods develops the mechanisms below. Work the numerical examples or trace the code before checking the answer.

Concepts from other sections (13)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

Learning objectives

  • Explain the memory and computation saved by freezing weights.

Every post-training method above can be run on a full copy of the weights, but the 16-bytes-per-parameter rule makes that expensive. Parameter-efficient fine-tuning freezes the base and trains a small number of new parameters instead. The key papers are LoRA, QLoRA, and DoRA.

LoRA freezes a weight matrix W0∈Rd×kW_0 \in \mathbb{R}^{d \times k} and learns a low-rank update:

h=W0x+ΔWx=W0x+αrBAx,A∈Rr×k, B∈Rd×r, r≪min⁡(d,k)h = W_0 x + \Delta W x = W_0 x + \frac{\alpha}{r} B A x, \qquad A \in \mathbb{R}^{r \times k},\ B \in \mathbb{R}^{d \times r},\ r \ll \min(d, k)

AA is initialized Gaussian (or Kaiming) and BB is initialized to zero, so ΔW=0\Delta W = 0 and training starts exactly at the base model. Each adapted matrix has r(d+k)r(d + k) trainable parameters instead of dkdk.

The hypothesis behind LoRA is that the fine-tuning update has low intrinsic rank. That makes it best for teaching format, style, or a narrow skill, and worst for injecting large amounts of new knowledge. The α/r\alpha/r scaling keeps the update’s magnitude roughly constant as you change rr, so a learning rate transfers across ranks; rsLoRA uses α/r\alpha/\sqrt{r} instead (2312.03732) and does better at high rank.

Which modules to adapt matters more than the original paper suggested. Apply LoRA to all linear layers (q, k, v, o, gate, up, down), not just q and v. QLoRA showed this is needed to match full fine-tuning, and Thinking Machines’ LoRA Without Regret (free) found that LoRA on all layers matches full fine-tuning on small-to-medium datasets with about 10 times the full-FT learning rate, and is notably efficient for RL, where each episode carries few bits of information.

For zero-latency serving you can merge the adapter, W=W0+(α/r)BAW = W_0 + (\alpha/r)BA, or keep adapters separate for multi-LoRA serving. On forgetting, LoRA Learns Less and Forgets Less (free) found lower target-domain gains than full fine-tuning on code and math continued pretraining, but better retention of base capabilities. lora_from_scratch.py implements LoRA on a frozen two-layer MLP with a merge check and a finite-difference gradient check.

Frozen means “not updated”. It does not mean “skipped”. The backward pass still runs through the whole network, frozen layers included, because that is the only route for the error signal from the loss at the output to an adapter in an early block.

Frozen W0W_0Adapter AA, BB
The error signal passes through itYesYes
A gradient for its own values is computedNoYes
The optimizer updates itNoYes

The base weights never improve. The effective weight does, because the layer behaves as W0+(α/r)BAW_0 + (\alpha/r)BA. With g=∂L/∂hg = \partial L / \partial h at an adapted layer, the chain rule gives each matrix its direction:

∂L∂B=αr g (Ax)⊤,∂L∂A=αr B⊤g x⊤.\frac{\partial L}{\partial B} = \frac{\alpha}{r}\, g\,(Ax)^\top, \qquad \frac{\partial L}{\partial A} = \frac{\alpha}{r}\, B^\top g\, x^\top.

The second formula contains BB, which starts at zero. On the first step every AA receives a zero gradient and only BB moves. AA starts to learn on the second step.

The loss is one scalar at the output, as in any training: cross-entropy for supervised fine-tuning, and reward-weighted log probabilities for RL. The adapter mechanics are the same in both.

Whether a layer trains depends on whether it has an adapter:

  • A module without an adapter is not trained at all. LoRA is opt-in for each module. Untargeted projections, norms, embeddings, and the output head stay exactly as they are in the base model.
  • A module with an adapter always trains. Every AA and BB receives a gradient on every step after the first.

Trained does not mean changed much. Where a layer matters for the task, BABA grows into a real correction. Where it does not, the gradient is small, BB stays near zero, and the layer behaves almost like the base. AdaLoRA uses this unevenness: it scores the adapters and moves rank from the idle ones to the useful ones.

No formal standard defines an adapter. The Hugging Face PEFT format is the de facto one: an adapter_config.json that holds the definition and an adapter_model.safetensors that holds only the AA and BB tensors. Downloads, loaders, and sharding covers the files and how a server loads them.

The config is a pattern, and the weight file is the definition for each layer. "target_modules": ["q_proj"] matches by name suffix, so it selects the q_proj in every block. A 32-block model gets 32 adapters from that one entry. Each has its own AA and BB, and nothing is shared between them:

layers.0.self_attn.q_proj.lora_A.weight shape (r, in_features)
layers.0.self_attn.q_proj.lora_B.weight shape (out_features, r)
layers.1.self_attn.q_proj.lora_A.weight
...
layers.31.self_attn.q_proj.lora_B.weight

The default is uniform: the same rank and the same α\alpha on every match. The PEFT LoraConfig has finer controls:

FieldEffect
layers_to_transformAdapt only the listed block indices
target_modules as one stringTreat the string as a regular expression over the full module path
rank_patternOverride the rank for matching layers
alpha_patternOverride α\alpha for matching layers
exclude_modulesRemove matches from the selection

An adapter fits only the exact base model it was trained on. The architecture and the base weights must both match, or the correction is meaningless.

QLoRA stores the base weights in 4 bits, keeps the adapters in BF16, and lets gradients flow through the dequantized base. Its 4-bit format, NF4, places 16 levels at the quantiles of N(0,1)\mathcal{N}(0,1), which is information-theoretically optimal for normally distributed weights. Blocks of 64 weights each carry an FP32 absmax scale, an overhead of 0.5 bits per parameter. Double quantization then quantizes those absmax constants to FP8 in blocks of 256, cutting the overhead to 8/64+32/(64⋅256)≈0.1278/64 + 32/(64 \cdot 256) \approx 0.127 bits per parameter, for a total of about 4.127 bits, or 0.516 bytes, per parameter. Paged optimizers keep optimizer states in NVIDIA unified memory and page them to CPU during memory spikes from long sequences.

The compute dtype is still BF16, so QLoRA saves memory, not FLOPs, and runs slower than LoRA because of the dequantization. The paper’s headline result was a 65B fine-tune on one 48 GB GPU. The quantization details are in Quantization.

DoRA decomposes each weight into a magnitude vector and a column-normalized direction, W=m⋅V/∥V∥cW = m \cdot V/\|V\|_c. It trains mm directly and updates the direction with LoRA:

W′=m⋅W0+BA∥W0+BA∥cW' = m \cdot \frac{W_0 + BA}{\|W_0 + BA\|_c}

This brings learning dynamics closer to full fine-tuning at small rank, for a small compute overhead, and it merges just like LoRA.

Now the payoff. The table below comes from memory_calc.py for Llama 3 shapes, rank 16 on all linear layers, sequence length 4096, micro-batch 1, with activation checkpointing:

ModelMethodTrainableStates+ activationsMin H100-80GB
8Bfull FT (16 B/param)8.03B128.5 GB132 GB2 (FSDP), 8 in practice for throughput
8BLoRA (2 B/param base)41.9M (0.5%)16.7 GB20.5 GB1 (fits a 24 GB card)
8BQLoRA (0.516 B/param)41.9M4.8 GB8.6 GB1
70Bfull FT70.6B1,129 GB1,138 GB18, i.e. 3 nodes
70BLoRA207M (0.3%)144.4 GB153 GB3 (shard the frozen base)
70BQLoRA207M39.7 GB48.3 GB1

The mechanism is simple. Frozen parameters need no gradient, no master copy, and no Adam moments, so 14 of their 16 bytes vanish, and QLoRA removes most of the remaining 2. Compute drops too: with no weight gradients for frozen matrices, the backward pass costs about 2N2N instead of 4N4N, so LoRA training costs about 4ND4ND instead of 6ND6ND. Training compute for a typical customer job is single-digit GPU-hours at most. The real cost is data and evaluation.

Adapters are megabytes, so one base model can serve hundreds of fine-tunes. The server batches requests for different adapters together and applies each adapter’s BABA with segmented gather matmul kernels (Punica, S-LoRA). vLLM (--enable-lora), SGLang, and LoRAX implement it, and it is the economic basis of per-customer fine-tunes at inference clouds: a LoRA deployment is billed like the base model.

The merged and unmerged paths are not numerically identical. W0x+(α/r)BAxW_0x + (\alpha/r)BAx computed in two parts does not round the same way as (W0+(α/r)BA)x(W_0 + (\alpha/r)BA)x computed once. If RL rollouts come from one path and the trainer scores tokens on the other, that difference is one more source of trainer and inference engine drift. The serving side is covered in Serving and Load.

All of these are free on arXiv.

TopicPaperRead it for
The methodHu et al., LoRA, 2021The low-rank update, the zero start, and which modules to adapt
Why low rank worksAghajanyan et al., Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning, 2020The evidence that a fine-tune needs few free directions
Rank allocationZhang et al., AdaLoRA, 2023Moving rank from idle adapters to useful ones
InitializationMeng et al., PiSSA, 2024Starting the adapter from the top singular directions of the weight
Learning ratesHayou et al., LoRA+, 2024Separate learning rates for AA and BB
Fewer parametersKopiczko et al., VeRA, 2023Shared random matrices with small trained scaling vectors
Capacity and forgettingBiderman et al., LoRA Learns Less and Forgets Less, 2024Measured gaps to full fine-tuning and retention of base ability
Multi-LoRA servingChen et al., Punica, 2023Batching requests for different adapters on one base model
Multi-LoRA serving costSheng et al., S-LoRA, 2023Adapter memory management and the throughput cost of serving thousands of adapters
The engine underneathKwon et al., PagedAttention, 2023The cache and batching design that multi-adapter servers build on

Explain the memory and computation saved by freezing weights. State the assumptions before applying the result to a different workload.

  1. Does freezing the base remove its forward and backward compute?

    Answer

    The forward still runs and gradients must usually propagate through frozen layers to adapters. Only base weight-gradient computation and associated optimizer state disappear.

  2. The base weights are frozen. How does the model’s behavior improve?

    Answer

    The layer computes with the effective weight W0+(α/r)BAW_0 + (\alpha/r)BA. Backpropagation gives gradients for AA and BB, the optimizer moves them, and the product grows into a learned correction on top of an unchanged W0W_0.

  3. On the first training step, which adapter matrices change, and why?

    Answer

    Only BB. The gradient for AA is proportional to B⊤B^\top, and BB starts at zero, so every AA receives a zero gradient until BB has moved.

  4. A config sets "target_modules": ["q_proj", "v_proj"] on a 32-block model. How many adapters exist, and do they share weights?

    Answer

    Sixty-four: one for each matching module in each block. Each adapter has its own AA and BB. The config is a pattern, and the keys in the weight file identify each layer’s tensors.

  5. Are any layers left untrained in a LoRA fine-tune?

    Answer

    Yes. Every module without an adapter keeps its base values. Modules with an adapter all receive gradients, but those that matter little for the task stay close to a zero correction.

  6. Why can a merged adapter and an unmerged adapter give different logits for the same input?

    Answer

    The two paths group the floating-point operations differently, so they round differently. The functions are equal in exact arithmetic and only close in finite precision.

Chapter contents · Next: Evaluation and fine-tune scope