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 gradients 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 GPU 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 (FP16 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 of rank at most .[1] (Intrinsic dimension and matrix rank differ: has one free scalar yet full matrix rank whenever .)
What LoRA saves, and what it doesn't
Freezing the base eliminates gradients and optimizer state for frozen weights while leaving the frozen weights themselves in VRAM.

The math: from a 4096×4096 layer
A layer small enough to count
Full fine-tuning updates all entries of . Rank- LoRA () freezes and learns two skinny factors: down-projection and up-projection , totaling parameters (0.78% of the layer, a 99.2% reduction):
Parenthesizing executes two thin matvecs (~262K FLOPs/token vs 33.6M for , ~0.78% overhead) without ever materializing dense .
Why the product is low rank
For , projects into an -dimensional bottleneck and expands back, giving and adding parameters ( when square; at , adds 65.5K / 131K / 524K parameters, or 0.39% / 0.78% / 3.12%).[1]
Initialization and gradient symmetry
LoRA initializes randomly (Gaussian in the paper; Kaiming-uniform in PEFT) and :[1][4]
- Step-zero identity: , preserving pretrained outputs exactly.
- Step-1 and step-2 gradients: For incoming gradient , On step 1, gives while (unless ). Once updates, receives gradients from step 2 onward. Initializing both to zero leaves both stuck at zero forever.
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))
for name, a, b, values in [
("usual (A!=0, B=0)", [1.0, -1.0], 0.0, [1.0, 0.0]),
("null_space (Ax=0)", [1.0, -1.0], 0.0, [1.0, 1.0]),
("both_zero (stuck)", [0.0, 0.0], 0.0, [1.0, 0.0]),
("reversed (A=0, B!=0)", [0.0, 0.0], 1.0, [1.0, 0.0]),
]:
A, B = make_factors(a, b)
x = torch.tensor(values, dtype=torch.float64)
(((B @ (A @ x)).squeeze() - 1).square() / 2).backward()
print(f"{name:22s} -> |grad A|={A.grad.abs().sum().item():.1f}, |grad B|={B.grad.abs().sum().item():.1f}")
A, B = make_factors([1.0, -1.0], 0.0)
opt, x = torch.optim.SGD([A, B], lr=0.1), torch.tensor([1.0, 0.0], dtype=torch.float64)
for step in (1, 2):
opt.zero_grad(set_to_none=True)
((B @ (A @ x) - 1).square() / 2).backward()
print(f"step {step} usual -> |grad A|={A.grad.abs().sum().item():.3f}, |grad B|={B.grad.abs().sum().item():.3f}")
opt.step()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.900Separate capacity from strength
Rank sets subspace capacity; sets update strength.[1] Increasing while holding fixed shrinks and damps updates, so keep constant (e.g., or ) during rank sweeps. At high ranks (), rsLoRA replaces with (use_rslora=True in PEFT) so updates stay well-scaled.[5][4]
Where to inject LoRA
The original paper adapted and ,[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]
| Strategy | Target modules | Cost per 7B block () | Role |
|---|---|---|---|
| Original LoRA | 262K | Lean baseline | |
| All attention | 524K | Routing-only adaptation | |
| All-linear | Attention + MLP | 1.25M (~4.8x Q/V) | Strongest default |
Keep PEFT families distinct: prompt tuning / soft prompts[6] train virtual input embeddings, and prefix tuning[7] prepends learned key/value prefixes at each layer, whereas LoRA injects low-rank factors 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:
import tempfile
import torch
from peft import LoraConfig, PeftModel, get_peft_model
from transformers import Qwen2Config, Qwen2ForCausalLM
torch.manual_seed(7)
config = Qwen2Config(
vocab_size=32, hidden_size=16, intermediate_size=32,
num_hidden_layers=1, num_attention_heads=2, num_key_value_heads=1,
max_position_embeddings=32, attention_dropout=0.0, tie_word_embeddings=False,
)
base = Qwen2ForCausalLM(config).eval()
ids = torch.tensor([[1, 2, 3, 4]])
base_logits = base(ids).logits.detach().clone()
base_state = {k: v.detach().clone() for k, v in base.state_dict().items()}
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()
targets = [n.rsplit(".", 1)[-1] for n, m in model.named_modules() if hasattr(m, "lora_A")]
trainable, total = model.get_nb_trainable_parameters()
print("adapted modules:", targets)
print(f"trainable: {trainable:,} / {total:,} ({trainable / total:.1%})")
print(f"step-0 max logit diff: {(model(ids).logits - base_logits).abs().max().item():.1e}")
model.train()
opt = torch.optim.SGD([p for p in model.parameters() if p.requires_grad], lr=0.1)
for step in (1, 2):
opt.zero_grad(set_to_none=True)
model(ids, labels=ids).loss.backward()
a_g = sum(p.grad.abs().sum().item() for n, p in model.named_parameters() if "lora_A" in n)
b_g = sum(p.grad.abs().sum().item() for n, p in model.named_parameters() if "lora_B" in n)
print(f"step {step} grads -> |grad A|={a_g:.4f}, |grad B|={b_g:.4f}")
opt.step()
model.eval()
adapted_logits = model(ids).logits.detach()
with tempfile.TemporaryDirectory() as tmpdir:
model.save_pretrained(tmpdir)
fresh = Qwen2ForCausalLM(config)
fresh.load_state_dict(base_state)
reloaded = PeftModel.from_pretrained(fresh, tmpdir).eval()
reload_diff = (reloaded(ids).logits - adapted_logits).abs().max().item()
merged = model.merge_and_unload(safe_merge=True).eval()
merge_diff = (merged(ids).logits - adapted_logits).abs().max().item()
print(f"reload max diff: {reload_diff:.1e} | merge max diff: {merge_diff:.1e}")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-08With 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).

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 into via merged_weight() (in PEFT, merge_and_unload(), always saving the standalone adapter first):[4]
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)
torch.manual_seed(0)
base, x, target = nn.Linear(4, 3, bias=False), torch.randn(8, 4), torch.randn(8, 3)
layer = LoRALinear(base, rank=2, alpha=4.0)
print(f"step-0 diff from base: {(layer(x) - base(x)).abs().max().item():.1e}")
opt = torch.optim.Adam([layer.A, layer.B], lr=0.05)
for step in range(1, 41):
opt.zero_grad()
loss = (layer(x) - target).pow(2).mean()
loss.backward()
opt.step()
if step in (1, 20, 40):
print(f"step {step:2d} MSE={loss.item():.4f}")
print(f"merged vs unmerged max diff: {(x @ layer.merged_weight().T - layer(x)).abs().max().item():.1e}")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-07Choose rank and diagnose from the failure shape
Start sweeps at with or , 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).
- Validation loss stalls: Verify formatting/gradients, widen Q/V to
all-linear,[3] or check that fixed did not shrink (useuse_rslora=Trueat high rank).[5] - Held-out worsens while train improves: Low rank does not prevent overfitting; tune epochs, data diversity, and dropout.
- OOM with a small adapter on sharded FSDP / ZeRO: Gathered frozen block weights, activations, and temp buffers dominate peak VRAM; halving adapter state barely moves peak memory.
- New special tokens never appear: Call
resize_token_embeddings(len(tokenizer))before wrapping, train the affected input embedding and untiedlm_headoutput rows, and verify both after reload.[4] - Unexpected latency: Merge single-task adapters with
merge_and_unload().
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 BF16 for matmuls, shrinking a 65B base from 130 GB to ~33.5 GB so it fits on one 48 GB GPU via three techniques:
- NormalFloat4 (NF4): Maps 64-weight blocks (scaled by block absmax into ) to 16 nonuniform standard-normal quantile levels (7 negative, exact
0.0, 8 positive).[3][11] - Double quantization: Quantizes the per-block FP32 scales to 8-bit (one FP32 second-level scale per 256 blocks), cutting scale overhead from to bits/weight (~3 GB saved on 65B).[3][11]
- Paged optimizers: Evicts optimizer state to CPU RAM via CUDA unified memory during activation spikes.[3][12]
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])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).

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 () 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 (initialized to ) from its unit direction:
Step-zero identity holds (), on square projections magnitude adds parameters over LoRA ( in general), and PEFT enables it via use_dora=True.[19] To save memory, both DoRA and PEFT detach during backward: for , full differentiation subtracts the projection along to give [0.64, -0.48], while PEFT's detached-norm backward gives [1.0, 0.0]:
import torch
from torch import nn
from peft import LoraConfig, get_peft_model
base = nn.Sequential(nn.Linear(2, 1, bias=False))
with torch.no_grad():
base[0].weight.copy_(torch.tensor([[3.0, 4.0]]))
model = get_peft_model(base, LoraConfig(r=2, lora_alpha=2, target_modules=["0"], use_dora=True))
layer = model.base_model.model[0]
with torch.no_grad():
layer.lora_A["default"].weight.copy_(torch.eye(2))
layer.lora_B["default"].weight.zero_()
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()]}")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: shapes match every target including narrower GQA K/V layers; step-0 identity, step-1 gradient, step-2 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.