Skip to content
Skip to lesson
Back to Topics
LearnTraining, Fine-Tuning & AlignmentLoRA & Parameter-Efficient Tuning
HardFine-Tuning & Training12 min read

LoRA & Parameter-Efficient Tuning

Full fine-tuning stores gradients and Adam state for every weight. LoRA trains a low-rank update, and held-out task checks still decide whether that update is enough.

On this page

Your read-only SQL analytics assistant handles routine queries, yet a warehouse migration renames tables and changes join rules. You have 5,000 labeled question-to-SQL pairs and a single 48 GB GPU. Full fine-tuning requires storing and Adam state for every base weight, blowing past 48 GB before the first step finishes. Do you need to update all 70 billion weights independently to teach new SQL conventions?

LoRA (Low-Rank Adaptation) bets that downstream weight updates live in a low-dimensional subspace: freeze the pretrained weights and train compact low-rank factors inside selected linear layers. On GPT-3 175B, LoRA cut trainable parameters by ~10,000x and memory by ~3x versus full Adam fine-tuning.[1] (Rapidly changing table definitions still belong in retrieval; fine-tuning teaches query patterns.)

Why LoRA exists

Under a lean 12-byte/param mixed-precision recipe ( weights and gradients + two FP32 Adam moments), full fine-tuning a 70B model requires 840 GB before activations (140 GB weights + 140 GB gradients + 560 GB Adam moments), or 1.12 TB with an FP32 master copy (16 bytes/param, see distributed training).

Aghajanyan et al. showed pretrained LLMs can adapt inside a low intrinsic dimension,[2] inspiring Hu et al.'s intrinsic rank hypothesis: constrain weight updates to ΔW=BA\Delta W = BA of rank at most rr.[1] (Intrinsic dimension and matrix rank differ: ΔW=θI\Delta W = \theta I has one free scalar yet full matrix rank whenever θ≠0\theta \ne 0.)

What LoRA saves, and what it doesn't

Freezing the base eliminates gradients and for frozen weights while leaving the frozen weights themselves in VRAM.

A 65B comparison on one shared 0 to 800 GB scale: full fine-tuning states use 780 GB under a 12-byte-per-parameter recipe (weights 130, gradients 130, Adam moments 260 each), the frozen FP16 base uses 130 GB, and an ideal NF4 base plus nested scales uses 33.5 GB, inside a 48 GB device line. A second 0 to 48 GB scale splits the ideal quantized base into 32.5 GB of NF4 values and 1.0 GB of nested scales, leaving 14.5 GB for omitted allocations. Adapters, gradients, optimizer state, activations, and temporary buffers are excluded from the lower bars.
65B model-state memory on a shared scale. Under QLoRA on a 48 GB GPU, the remaining 14.5 GB must still hold adapters, activations, and buffers.

The math: from a 4096×4096 layer

A layer small enough to count

Full fine-tuning updates all 40962=16.78M4096^2 = 16.78\text{M} entries of W0W_0. Rank-rr LoRA (r=16r=16) freezes W0W_0 and learns two skinny factors: down-projection A∈R16×4096A \in \mathbb{R}^{16 \times 4096} and up-projection B∈R4096×16B \in \mathbb{R}^{4096 \times 16}, totaling 131,072131{,}072 parameters (0.78% of the layer, a 99.2% reduction):

h=W0x+αrB(Ax)h = W_0 x + \frac{\alpha}{r} B(Ax)

Parenthesizing B(Ax)B(Ax) executes two thin matvecs (~262K FLOPs/token vs 33.6M for W0xW_0 x, ~0.78% overhead) without ever materializing dense BABA.

Why the product is low rank

For W0∈Rdout×dinW_0 \in \mathbb{R}^{d_{\text{out}} \times d_{\text{in}}}, A∈Rr×dinA \in \mathbb{R}^{r \times d_{\text{in}}} projects into an rr-dimensional bottleneck and B∈Rdout×rB \in \mathbb{R}^{d_{\text{out}} \times r} expands back, giving rank⁡(BA)≤r\operatorname{rank}(BA) \le r and adding r(din+dout)r(d_{\text{in}} + d_{\text{out}}) parameters (2rd2rd when square; at 4096×40964096\times4096, r=8/16/64r=8/16/64 adds 65.5K / 131K / 524K parameters, or 0.39% / 0.78% / 3.12%).[1]

Input xx flows through frozen W0xW_0 x and low-rank A→BA \to B in parallel. With B=0B=0 at init, the adapter starts as an exact no-op on step 0.

Initialization and gradient symmetry

LoRA initializes AA randomly (Gaussian in the paper; Kaiming-uniform in PEFT) and B=0B = 0:[1][4]

  1. Step-zero identity: B=0  ⟹  αrB(Ax)=0B=0 \implies \frac{\alpha}{r}B(Ax)=0, preserving pretrained outputs exactly.
  2. Step-1 and step-2 gradients: For incoming gradient g=∇hLg = \nabla_h \mathcal{L}, ∇BL=αrg(Ax)T,∇AL=αrBTgxT\nabla_B \mathcal{L} = \frac{\alpha}{r} g (Ax)^T, \qquad \nabla_A \mathcal{L} = \frac{\alpha}{r} B^T g x^T On step 1, B=0B=0 gives ∇AL=0\nabla_A \mathcal{L}=0 while ∇BL≠0\nabla_B \mathcal{L} \ne 0 (unless Ax=0Ax=0). Once BB updates, AA receives gradients from step 2 onward. Initializing both to zero leaves both stuck at zero forever.
lora_initial_gradients.py
import torch

def make_factors(a, b):
    return (torch.tensor([a], dtype=torch.float64, requires_grad=True),
            torch.tensor([[b]], dtype=torch.float64, requires_grad=True))
Initial gradient behavior
usual (A!=0, B=0)      -> |grad A|=0.0, |grad B|=1.0
null_space (Ax=0)      -> |grad A|=0.0, |grad B|=0.0
both_zero (stuck)      -> |grad A|=0.0, |grad B|=0.0
reversed (A=0, B!=0)   -> |grad A|=1.0, |grad B|=0.0
step 1 usual          -> |grad A|=0.000, |grad B|=1.000
step 2 usual          -> |grad A|=0.090, |grad B|=0.900

Separate capacity from strength

Rank rr sets subspace capacity; α/r\alpha/r sets update strength.[1] Increasing rr while holding α\alpha fixed shrinks α/r\alpha/r and damps updates, so keep α/r\alpha/r constant (e.g., α=r\alpha = r or 2r2r) during rank sweeps. At high ranks (r≥64r \ge 64), rsLoRA replaces α/r\alpha/r with α/r\alpha/\sqrt{r} (use_rslora=True in PEFT) so updates stay well-scaled.[5][4]

Where to inject LoRA

The original paper adapted WQW_Q and WVW_V,[1] whereas QLoRA ablations found matching full fine-tuning required adapting all linear layers in every Transformer block, including MLP projections (gate_proj, up_proj, down_proj in SwiGLU blocks).[3]

StrategyTarget modulesCost per 7B block (r=16r=16)Role
Original LoRAWQ,WVW_Q, W_V262KLean baseline
All attentionWQ,WK,WV,WOW_Q, W_K, W_V, W_O524KRouting-only adaptation
All-linearAttention + MLP1.25M (~4.8x Q/V)Strongest default

Keep PEFT families distinct: prompt tuning / soft prompts[6] train virtual input , and prefix tuning[7] prepends learned key/value prefixes at each layer, whereas LoRA injects low-rank factors A,BA, B into linear projections.

Implementing LoRA with Hugging Face PEFT

Verify the adapter lifecycle on CPU

Verify step-0 identity, step-1 vs step-2 gradients, reload equivalence, and lossless merging on a tiny Qwen2 block before launching GPU training:

tiny-peft-check.py

model = get_peft_model(base, LoraConfig(
    r=2, lora_alpha=4, target_modules="all-linear",
    lora_dropout=0.0, bias="none", task_type="CAUSAL_LM",
)).eval()
Real PEFT wrapper lifecycle on CPU
adapted modules: ['q_proj', 'k_proj', 'v_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj']
trainable: 512 / 3,920 (13.1%)
step-0 max logit diff: 0.0e+00
step 1 grads -> |grad A|=0.0000, |grad B|=2.4652
step 2 grads -> |grad A|=0.2497, |grad B|=2.3136
reload max diff: 0.0e+00 | merge max diff: 3.0e-08

With grouped-query attention (2 query heads, 1 KV head), k_proj and v_proj are narrower than q_proj (48 adapter params each vs 64 for q_proj/o_proj and 96 per MLP projection, totaling 512).

A Qwen2 block diagram (hidden 16, MLP 32, 2 Q heads, 1 KV head, rank 2) maps LoRA adapter attachments across GQA attention projections (q_proj 64, k_proj 48, v_proj 48, o_proj 64) and SwiGLU MLP projections (gate_proj, up_proj, down_proj at 96 each), leaving lm_head excluded. Proportional bars compare total adapter parameters: 112 for Q/V, 224 for all-attention, and 512 for all-linear.
Wider target sets adapt more projections: 112 (Q/V), 224 (all-attention), and 512 (all-linear) while leaving `lm_head` untouched.

For multi-GPU training, let accelerate, FSDP, or DeepSpeed manage sharding instead of device_map="auto" (an inference placement helper).[8] Also inspect adapter dtypes after wrapping: PEFT promotes BF16 LoRA weights to FP32 by default (autocast_adapter_dtype=True) so tiny updates survive, whereas False keeps them in BF16.[9][10]

Build a minimal PyTorch LoRA layer and merge it

Under the hood, LoRA is 15 lines of PyTorch: freeze base.weight, initialize B = 0, train only A and B, and fold αrBA\frac{\alpha}{r}BA into W0W_0 via merged_weight() (in PEFT, merge_and_unload(), always saving the standalone adapter first):[4]

pytorch-lora-layer.py
import torch
import torch.nn as nn

class LoRALinear(nn.Module):
    def __init__(self, base: nn.Linear, rank: int, alpha: float):
        super().__init__()
        self.base = base
        self.base.weight.requires_grad_(False)
        d_out, d_in = base.weight.shape
        self.A = nn.Parameter(torch.randn(rank, d_in) * 0.1)
        self.B = nn.Parameter(torch.zeros(d_out, rank))
        self.scaling = alpha / rank

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.base(x) + self.scaling * ((x @ self.A.T) @ self.B.T)

    @torch.no_grad()
    def merged_weight(self) -> torch.Tensor:
        return self.base.weight + self.scaling * (self.B @ self.A)
From-scratch PyTorch LoRA training and merge
step-0 diff from base: 0.0e+00
step  1 MSE=1.7893
step 20 MSE=1.1618
step 40 MSE=1.0832
merged vs unmerged max diff: 1.8e-07

Choose rank and diagnose from the failure shape

Start sweeps at r∈{8,16}r \in \{8, 16\} with α=r\alpha = r or 2r2r, all-linear, learning rate 1e-4 to 2e-4 (~10x full fine-tuning LR), fixed effective token batch, dropout 0.0 or 0.05, and gradient checkpointing when activation-bound. Gate every candidate on both a held-out task set and a general regression set (never let a high pooled average hide a regression miss).

Choose LoRA for multi-tenant serving, tight VRAM, and rapid iteration; choose full fine-tuning when large out-of-distribution corpora make low-rank updates underfit on held-out evaluations.

QLoRA: going further

QLoRA[3] compresses the frozen base to 4-bit storage and dequantizes on the fly into for matmuls, shrinking a 65B base from 130 GB to ~33.5 GB so it fits on one 48 GB GPU via three techniques:

  1. NormalFloat4 (NF4): Maps 64-weight blocks (scaled by block absmax into [−1,1][-1, 1]) to 16 nonuniform standard-normal quantile levels (7 negative, exact 0.0, 8 positive).[3][11]
  2. Double quantization: Quantizes the per-block FP32 scales to 8-bit (one FP32 second-level scale per 256 blocks), cutting scale overhead from 0.50.5 to 0.1270.127 bits/weight (~3 GB saved on 65B).[3][11]
  3. Paged optimizers: Evicts optimizer state to CPU RAM via CUDA unified memory during activation spikes.[3][12]
nf4_lookup.py
codebook = [
    -1.0, -0.696193, -0.525073, -0.394917, -0.284441, -0.184773, -0.091050,
    0.0, 0.079580, 0.160930, 0.246112, 0.337915, 0.440710, 0.562617, 0.722957, 1.0,
]
weights = [-0.2, 0.0, 0.2, 2.0]
scale = max(abs(w) for w in weights)
indices = [min(range(16), key=lambda i: abs(w / scale - codebook[i])) for w in weights]
print("4-bit indices:", indices, "| reconstructed:", [round(scale * codebook[i], 5) for i in indices])
NF4 lookup output
4-bit indices: [6, 7, 8, 15] | reconstructed: [-0.1821, 0.0, 0.15916, 2.0]

In PEFT/Transformers, pass BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16) and call prepare_model_for_kbit_training(model) before get_peft_model.[13][14] For export, reload the BF16 base, merge the adapter, optionally re-quantize, and re-run held-out evaluations.[15]

Keep the base shared when serving many adapters

Duplicating a 14 GB base across 50 merged tenants takes 700 GB; one shared 14 GB base plus fifty 128 MB adapters takes 20.4 GB (34.3x smaller).

Squares drawn to one scale of area. Static merging stores one dense 14 GB checkpoint for each task: fifty copies use 700 GB. With dynamic serving, each request selects an adapter or none while one 14 GB base is shared. Fifty assumed 128 MB adapters plus the base occupy 20.4 GB as artifacts. Merged inference computes the dense merged weights; dynamic inference adds a scaled low-rank term for the selected adapter.
Merging removes adapter branches for single-task serving; dynamic routing shares one base across many tasks (20.4 GB vs 700 GB for 50 adapters).

Two serving designs keep multi-adapter latency low: Punica uses Segmented Gather Matrix-Vector (SGMV) kernels to batch heterogeneous requests through one shared base GEMM (XW0TX W_0^T) before applying each request's adapter correction in parallel,[16] and S-LoRA introduces Unified Paging to store KV-cache blocks and adapters in one paged GPU pool without fragmentation.[17] Merge your top one or two hot adapters; route dynamically once traffic spans dozens of variants.

Deep dive: DoRA (Weight-Decomposed Low-Rank Adaptation) and detached norm gradients

DoRA[18] decouples each weight row's magnitude m∈Rdoutm \in \mathbb{R}^{d_{\text{out}}} (initialized to ∥W0∥row\|W_0\|_{\text{row}}) from its unit direction:

V=W0+αrBA,WDoRA=m⊙V∥V∥rowV = W_0 + \frac{\alpha}{r}BA, \qquad W_{\text{DoRA}} = m \odot \frac{V}{\|V\|_{\text{row}}}

Step-zero identity holds (B=0  ⟹  W(0)=W0B=0 \implies W^{(0)} = W_0), on square projections magnitude adds 1/(2r)1/(2r) parameters over LoRA (dout/[r(din+dout)]d_{\text{out}} / [r(d_{\text{in}} + d_{\text{out}})] in general), and PEFT enables it via use_dora=True.[19] To save memory, both DoRA and PEFT detach ∥V∥row\|V\|_{\text{row}} during backward: for V=(3,4),m=5,x=(1,0)V=(3, 4), m=5, x=(1, 0), full differentiation subtracts the projection along VV to give [0.64, -0.48], while PEFT's detached-norm backward gives [1.0, 0.0]:

dora-backward-check.py

output = model(torch.tensor([[1.0, 0.0]]))
output.sum().backward()
peft_grad = layer.lora_B["default"].weight.grad.flatten()

direction = torch.tensor([3.0, 4.0], requires_grad=True)
full_grad, = torch.autograd.grad(5 * direction[0] / direction.norm(), direction)
print(f"out={output.item():.1f} | full_grad={[round(v, 2) for v in full_grad.tolist()]} | detached_grad={[round(v, 2) for v in peft_grad.tolist()]}")
DoRA backward check
out=3.0 | full_grad=[0.64, -0.48] | detached_grad=[1.0, 0.0]

What to check before moving on

Verify five invariants before shipping: A/BA/B shapes match every target including narrower GQA K/V layers; step-0 identity, step-1 BB gradient, step-2 AA gradient, and frozen base weights all hold; reloaded and merged eval-mode logits match within float tolerance; peak VRAM is measured at target sequence length; and both held-out task and regression gates pass.

Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 10 answered
1.A bias-free layer has 12 outputs and 20 inputs. It receives ordinary LoRA with rank 3. How many trainable factor parameters are added, and what fraction of the 240 base weights is that?
2.A scalar LoRA adapter adds sB(Ax) to the base output. A = 2, B = 0, x = 3, and s = 0.5. The incoming loss gradient is g = −4. What are the loss gradients of A and B before any optimizer update?
3.An ordinary LoRA experiment changes rank from 6 to 24 while alpha stays 24. What happens to its explicit multiplier, and which new alpha would preserve the old multiplier at rank 24?
4.An attention block has output-by-input shapes Q = 12×12, K = 4×12, V = 4×12 and O = 12×12. At LoRA rank 3, how many trainable factor parameters does adapting Q and V add? How many does adapting all four projections add?
5.A model uses untied input embeddings and output weights. New tokenizer IDs are added, but only attention projections are wrapped with trainable LoRA factors. The new IDs have no useful learned input or output rows. What fixes both layers?
6.At its peak, a LoRA training run uses 18 GB for gathered frozen weights, 12 GB for activations, 4 GB for temporary buffers and 0.4 GB for adapter state. You halve the adapter state and keep the other allocations fixed. What is the revised peak, and how far above or below a 32 GB GPU’s capacity is it?
7.For a nonzero NF4 block scale of 4, one weight is 0.6. Its nearest candidate normalized levels are code 8: 0.079580, code 9: 0.160930 and code 10: 0.246112; other levels are farther away. Which chosen code and reconstructed weight follow nearest-level lookup?
8.A DoRA layer has a directional row V = [5, 12], a magnitude parameter m = 13 and an input x = [1, 0]. It computes y = m(V·x)/‖V‖ using the Euclidean norm. What is y? How does its gradient with respect to V compare when you differentiate the norm and when you hold it fixed during backward?
9.A supplied layer has W₀ = I₂, A = [1,2], B = [0.5,−1]ᵀ, rank 1 and alpha 3. With input x = [1,2]ᵀ, what output does the correctly merged ordinary LoRA layer produce?
10.You evaluate two candidate adapters on 50 task cases and 50 regression cases. Release requires at least 90% correct on each set. P gets 48 task cases and 43 regression cases correct. Q gets 45 correct on each set. Which adapters qualify for release?

10 questions remaining.

References

LoRA: Low-Rank Adaptation of Large Language Models.

Hu, E. J., et al. · 2021 · ICLR

https://arxiv.org/abs/2106.09685

Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning.

Aghajanyan, A., Zettlemoyer, L., & Gupta, S. · 2020 · ACL 2021

https://arxiv.org/abs/2012.13255

QLoRA: Efficient Finetuning of Quantized LLMs

Dettmers, T., et al. · 2023 · NeurIPS

https://arxiv.org/abs/2305.14314

PEFT Documentation: LoRA Developer Guide.

Hugging Face · 2026

https://huggingface.co/docs/peft/main/developer_guides/lora

A Rank Stabilization Scaling Factor for Fine-Tuning with LoRA.

Kalajdzievski, D. · 2023 · arXiv preprint

https://arxiv.org/abs/2312.03732

The Power of Scale for Parameter-Efficient Prompt Tuning.

Lester, Al-Rfou & Constant · 2021

https://arxiv.org/abs/2104.08691

Prefix-Tuning: Optimizing Continuous Prompts for Generation.

Li, X. L. & Liang, P. · 2021 · ACL 2021

https://arxiv.org/abs/2101.00190

Accelerate Documentation: Big Model Inference.

Hugging Face · 2026

https://huggingface.co/docs/accelerate/usage_guides/big_modeling

PEFT Troubleshooting: Adapter Dtypes

Hugging Face · 2026

https://huggingface.co/docs/peft/developer_guides/troubleshooting

TRL 1.17.1: SFT Trainer Implementation

Hugging Face TRL Contributors · 2026

https://github.com/huggingface/trl/blob/v1.17.1/trl/trainer/sft_trainer.py

bitsandbytes: NF4 Codebook and Nested Scale Quantization (8336490)

bitsandbytes Contributors · 2026

https://github.com/bitsandbytes-foundation/bitsandbytes/blob/833649043474794b8fe7a4136e0c40faf077b2e0/bitsandbytes/functional.py

bitsandbytes Optimizers: Paged Optimizers

Hugging Face and bitsandbytes Contributors · 2026

https://huggingface.co/docs/bitsandbytes/explanations/optimizers

PEFT 0.20.0: prepare_model_for_kbit_training

Hugging Face PEFT Contributors · 2026

https://github.com/huggingface/peft/blob/a5526d27a9d47d1e8264d5e1b1f96c0fdc79464e/src/peft/utils/other.py

bitsandbytes 0.50.2: Four-Bit Matrix Autograd

bitsandbytes Contributors · 2026

https://github.com/bitsandbytes-foundation/bitsandbytes/blob/0.50.2/bitsandbytes/autograd/_functions.py

PEFT Documentation: Quantization.

Hugging Face · 2026

https://huggingface.co/docs/peft/main/developer_guides/quantization

Punica: Multi-Tenant LoRA Serving

Chen, L., Ye, Z., Wu, Y., Zhuo, D., Ceze, L., & Krishnamurthy, A. · 2023

https://arxiv.org/abs/2310.18547

S-LoRA: Serving Thousands of Concurrent LoRA Adapters.

Sheng, Y., et al. · 2023 · arXiv preprint

https://arxiv.org/abs/2311.03285

DoRA: Weight-Decomposed Low-Rank Adaptation.

Liu, S., et al. · 2024 · ICML 2024

https://arxiv.org/abs/2402.09353

PEFT DoRA implementation

Hugging Face PEFT Contributors · 2026

https://github.com/huggingface/peft/blob/a5526d27a9d47d1e8264d5e1b1f96c0fdc79464e/src/peft/tuners/lora/dora.py

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.