9.3 Parameter-Efficient Fine-Tuning (PEFT)
A transformer projection with 4,096 inputs and 1,024 outputs contains 4,194,304 weights. You can adapt it by training just 81,920 values at rank 16 while keeping the original matrix frozen. Where do those values go? Change the projection and rank, then try merging the learned update into an inference weight. Parameter-efficient fine-tuning (PEFT) lets several tasks share a base model while keeping a separate adapter for each task.
Start with a Memory Budget
For full fine-tuning, account separately for model weights, master weights if used, gradients, optimizer moments, activations, temporary kernels, communication buffers, and checkpoints. A statement such as “70B needs multiple terabytes” is only meaningful after specifying precision, optimizer, sharding, sequence length, microbatch, and activation recomputation.
LoRA removes optimizer states and gradients for frozen base weights, but forward activations still scale with batch and sequence length. Gradient checkpointing trades extra compute for activation memory. FSDP or ZeRO shards model-related states across devices; tensor/context parallelism addresses layers or sequences that do not fit locally. Choose from a measured memory worksheet rather than by model size alone.
LoRA: A Low-Rank Update
Let be the number of input features and the number of output features. PyTorch stores a linear layer’s weight as . LoRA freezes this weight and learns two smaller factors. The input first passes through (), then through (). The rank sets the width of the intermediate representation and bounds the rank of the update. With B initialized to zero, the update starts at rank zero. The scalar sets its scale. [1] [4]
With , and , A holds values and B holds . Together they train 81,920 parameters, about 1.95% of the 4,194,304 weights. If you adapt another projection, count its input and output widths separately. These counts exclude bias.
How many parameters does one projection train?
Keep the input width at 4,096 and narrow the output to 1,024. Which factor gets smaller?
- Full weight W
- 4,096 × 4,09616,777,216
- Input factor A
- 16 × 4,09665,536
- Output factor B
- 4,096 × 1665,536
A and B train 131,072 parameters, or 0.78% of the count for training W.
Counts cover one weight matrix. The frozen bias and the activations kept for training are excluded.
Set the widths to 12 and 8. At rank 4 the factors hold 80 values for 96 base weights. At rank 8 they hold 160. Factorization saves parameters only while . For a training run, sweep rank alongside the target modules, , learning rate, dropout, supervised tokens per update and total token budget. Training only query and value projections is one baseline. Adapting every linear layer increases both the number of trainable parameters and checkpoint size. Record whether embeddings and output weights are tied before deciding to train either.
Educational Merge Semantics
Scope of the example. Run the next two blocks together with CPU PyTorch. They wrap a single dense floating-point nn.Linear, with the bias frozen and shared across both paths. A separate inference buffer temporarily costs one more weight matrix. Unmerge before loading, casting or editing parameters. The example omits dropout, tied weights, distributed training, quantization and concurrent updates.
import math
import torch
from torch import nn
from torch.nn import functional as F
class LoRAWrapper(nn.Module):
def __init__(self, base: nn.Linear, rank: int, alpha: float):
super().__init__()
if not 1 <= rank <= min(base.in_features, base.out_features):
raise ValueError("rank must fit both feature dimensions")
self.base = base.requires_grad_(False)
self.A = nn.Parameter(base.weight.new_empty(rank, base.in_features))
self.B = nn.Parameter(base.weight.new_zeros(base.out_features, rank))
nn.init.kaiming_uniform_(self.A, a=math.sqrt(5))
self.scale = alpha / rank
self.register_buffer("merged_weight", None, persistent=False)
def forward(self, x):
if self.merged_weight is not None:
return F.linear(x, self.merged_weight, self.base.bias)
return self.base(x) + F.linear(F.linear(x, self.A), self.B) * self.scale
@torch.no_grad()
def merge(self):
if self.training:
raise RuntimeError("switch to eval mode before merging")
if self.merged_weight is None:
self.merged_weight = self.base.weight + (self.B @ self.A) * self.scale
def unmerge(self):
self.merged_weight = None
def train(self, mode=True):
if mode:
self.unmerge()
return super().train(mode)
A starts with random values and B starts at zero, so the first prediction must match the supplied base layer. Fit one synthetic batch of two three-position sequences to a zero target with one SGD step. The resulting nonzero update makes the merge test meaningful. Each inference merge computes a fresh weight from the original and caches it; calling merge() again leaves it alone (an idempotent operation). Unmerging drops the cache. This avoids subtracting a rounded update from a rounded sum, which can change the original bits. The fused and separate matrix products can still round differently.
for dtype in (torch.float32, torch.float64):
torch.manual_seed(7)
base = nn.Linear(12, 8, bias=True, dtype=dtype)
layer = LoRAWrapper(base, rank=4, alpha=8)
x = torch.randn(2, 3, 12, dtype=dtype)
target = torch.zeros(2, 3, 8, dtype=dtype)
original = base.weight.detach().clone()
assert sum(p.numel() for p in layer.parameters() if p.requires_grad) == 80
assert torch.equal(layer(x), base(x))
optimizer = torch.optim.SGD([layer.A, layer.B], lr=0.1)
F.mse_loss(layer(x), target).backward()
optimizer.step()
layer.eval()
with torch.no_grad():
expected = layer(x)
assert not torch.equal(expected, base(x))
for _ in range(3):
layer.merge()
layer.merge()
torch.testing.assert_close(layer(x), expected)
layer.unmerge()
assert torch.equal(base.weight, original)
assert torch.equal(layer(x), expected)
print(dtype, expected.shape)
Both dtypes produce a tensor of shape [2, 3, 8]. The test compares outputs with PyTorch’s dtype-specific tolerance and checks the original weight for exact equality after each cycle.
QLoRA: Quantized Storage, Floating-Point Updates
QLoRA stores frozen base weights in 4-bit NF4, optionally uses double quantization for quantization constants, and computes through dequantized values while LoRA parameters remain trainable [2]. The compute dtype—usually BF16 on supported hardware, otherwise carefully tested FP16—is distinct from the storage dtype.
Configuration sketch for one CUDA device. Supply a verified local base checkpoint and compatible quantization backend. This block configures the adapter; the training loop, data, evaluation and distributed placement are omitted. [3]
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
model_id = "your-pinned-base-checkpoint"
quant = 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(
model_id, quantization_config=quant, device_map={"": 0}
)
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=True)
model = get_peft_model(model, LoraConfig(
r=16,
lora_alpha=32,
target_modules="all-linear",
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM",
))
This configuration is a starting point, not a universal recipe. Verify kernel/backend support, normalization and output-head dtypes, peak memory, trainable parameter names, and that gradient checkpointing interacts correctly with caches. Quantization error can change the best learning rate and rank.
Choosing and Shipping an Adapter
Compare at least a cheap LoRA baseline, a higher-capacity target-module/rank setting, and full fine-tuning only when the budget permits. Keep data order, token budget, evaluation, and tuning effort equal. DoRA, prompt tuning, and other variants can be useful, but evidence from one architecture or vision benchmark does not establish a universal LLM ranking.
Version the deployment as one artifact bundle:
- base checkpoint revision and hash;
- tokenizer files, chat template, special-token map, and generation config;
- adapter method/config/weights and library versions;
- precision and quantization configuration;
- dataset manifest, code/config/container, and evaluation report.
Loading the right adapter on the wrong base can produce plausible but invalid output. Add an explicit compatibility guard. For merged deployment, merge into an explicitly selected floating-point dtype, save a new immutable checkpoint, and compare logits/generations against unmerged inference. Do not assume merging directly into 4-bit weights is lossless or reversible. Retain the original base and adapter for rollback.
Run and Release Gates
For a chat task, pin the base and tokenizer, apply the serving chat template, and train only on the intended assistant tokens. Preserve EOS on retained responses, mask padding and prompt tokens, and check that packed examples cannot attend across boundaries. The SFT example spells out these checks. Evaluate on held-out conversations from different source groups. The regression above instead uses an unpadded synthetic tensor and mean squared error.
Track training and validation loss per supervised token, domain and length slices, adapter gradient and activation norms, nonfinite or overflow counts, peak memory, tokens per second and data wait. For distributed runs, include model FLOP utilization and collective waits. Record batch IDs so a bad update can be replayed. A resumable checkpoint includes the adapter and pinned base identity, optimizer, scheduler, scaler, token counter, RNG, sampler and data cursor, with dataset and configuration hashes.
Stop if a frozen base parameter acquires a gradient, a target layer was missed, repeated overflow persists, or memory exceeds the agreed headroom. Before a rollout, set tolerances for domain quality, retention, safety, formatting and tool use, latency, cost and errors. Compare the candidate and current adapter on the same held-out cases with uncertainty by slice. If a critical slice fails its limit, keep the prior bundle in service. Rehearse restoring that bundle and running its probes before the next release.
Quizzes
Quiz 1: Why can a LoRA run still run out of memory even though less than one percent of parameters are trainable?
LoRA greatly reduces trainable gradients and optimizer states, but the frozen weights, activations, temporary kernels, communication buffers, and evaluation still consume memory. Long sequences and microbatch size can dominate activation memory.
Quiz 2: What is the difference between QLoRA’s storage dtype and compute dtype?
Frozen base weights are stored in 4-bit NF4, while matrix operations use dequantized floating-point values such as BF16. Adapter weights and optimizer state are also trained in floating-point representations.
Quiz 3: Why must merge be idempotent?
A second merge must not add the same delta again. Explicit merged state plus tested unmerge behavior prevents silent weight corruption and makes deployment rollback auditable.
Quiz 4: Which files identify a deployable adapter?
At minimum: exact base revision, tokenizer and chat template, special-token and generation configuration, adapter config and weights, precision/quantization settings, code/library versions, and the evaluation report.
Quiz 5: For 12 input features and 8 output features, what is the largest integer rank that still trains fewer parameters than the original weight?
The weight has 96 values and the two factors train 20r. To stay below 96, r must be at most 4. Rank 5 already trains 100 values.
References
- Hu, E. J., et al. (2021). LoRA: Low-Rank Adaptation of Large Language Models. arXiv:2106.09685.
- Dettmers, T., et al. (2023). QLoRA: Efficient Finetuning of Quantized LLMs. arXiv:2305.14314.
- Hugging Face. PEFT documentation. Documentation.
- PyTorch.
torch.nn.Linear: weight and input shapes.