Fine-Tuning Methods: LoRA, Adapters, and Prompt Tuning
What You'll Learn
- 1Count the trainable parameters and optimizer memory of full fine-tuning
- 2Derive the low rank decomposition used by LoRA and its trainable parameter formula
- 3Explain adapter bottlenecks and soft prompt conditioning
- 4Choose a method from model size, data size, and latency budget
Full fine-tuning updates every weight in a model and stores two optimizer moments for each of them, which for a 7 billion parameter model means more than 100 GB of state before a single gradient is kept. This lesson derives the arithmetic behind that cost, the low rank update that LoRA learns instead, the adapter and prompt tuning alternatives, and the memory numbers that decide which method a given GPU can run.
The Cost of Full Fine-Tuning
A gradient descent step on the full parameter vector updates every entry, and Adam additionally keeps a first and second moment per parameter:
With float32 parameters, gradients, and two moments, training needs 16 bytes per parameter, so 7 billion parameters cost 112 GB of optimizer state alone. Storing checkpoints of both the base model and a task specific copy multiplies that by the number of tasks, which is the problem parameter-efficient methods attack.
LoRA: Low Rank Adaptation
Hu et al. (2021) observed that the weight update produced by fine-tuning has small intrinsic rank, so can be written as a product of two thin matrices:
Only those factors receive gradients, and the trainable count collapses from a full outer product to a sum:
At and that is parameters instead of 16,777,216, which is 0.39 percent of the matrix. Because starts at zero, the model output at step zero is identical to the frozen base, and after training the factors merge into for inference with no added latency.
Adapters (Houlsby et al., 2019) keep the same idea in activation space by inserting a bottleneck block after the attention and feed forward sublayers:
with projecting down to a width such as 64 and projecting back, so each block learns a residual correction while the original weights stay frozen.
| Method | Trainable parameters for a 7B model | Optimizer state at 16 bytes each | Added inference cost |
|---|---|---|---|
| Full fine-tuning | 7,000 million | 112 GB | none |
| LoRA at , 32 matrices | 2.1 million | 33.6 MB | none after merge |
| Adapters at width 64, 2 per layer | 33.6 million | 538 MB | one small block per layer |
| Prompt tuning, 50 prompts | 0.2 million | 3.3 MB | longer sequence |
Prompt Tuning and Soft Prompts
Prompt tuning (Lester, Al-Rfou, and Constant, 2021) replaces the discrete input tokens with a block of trainable embedding vectors prepended to every example:
The language model stays frozen and only numbers move, so 50 prompts of width 4096 train 204,800 parameters no matter how large the model gets. Above roughly 10 billion parameters the soft prompt matches full fine-tuning on many benchmarks, while smaller models still prefer supervised updates.
Worked Examples
Worked Code
import torch
import torch.nn as nn
import torch.nn.functional as F
class LoRALinear(nn.Module):
def __init__(self, base, rank=8, alpha=16):
super().__init__()
self.base = base
self.scaling = alpha / rank
d_in, d_out = base.in_features, base.out_features
self.lora_A = nn.Parameter(torch.zeros(rank, d_in))
self.lora_B = nn.Parameter(torch.zeros(d_out, rank))
nn.init.kaiming_uniform_(self.lora_A, a=5 ** 0.5)
for p in self.base.parameters():
p.requires_grad = False
def forward(self, x):
base_out = F.linear(x, self.base.weight, self.base.bias)
low_rank = (x @ self.lora_A.T) @ self.lora_B.T
return base_out + self.scaling * low_rank
def merge(self):
self.base.weight.data += self.scaling * (self.lora_B @ self.lora_A)
layer = LoRALinear(nn.Linear(4096, 4096), rank=8, alpha=16)
trainable = sum(p.numel() for p in layer.parameters() if p.requires_grad)
frozen = sum(p.numel() for p in layer.base.parameters())
print("trainable:", trainable, "frozen:", frozen)
print("share:", round(trainable / (trainable + frozen), 6))
layer.merge()
import torch
import torch.nn as nn
torch.manual_seed(0)
d_model, vocab, prompt_len, seq_len = 128, 1000, 20, 32
embed = nn.Embedding(vocab, d_model)
encoder = nn.TransformerEncoder(
nn.TransformerEncoderLayer(d_model=d_model, nhead=4, batch_first=True),
num_layers=2)
head = nn.Linear(d_model, vocab)
for module in (embed, encoder):
for p in module.parameters():
p.requires_grad = False
prompt = nn.Parameter(torch.randn(prompt_len, d_model) * 0.02)
optimizer = torch.optim.AdamW([prompt], lr=1e-2)
def forward(ids):
prefix = prompt.unsqueeze(0).expand(ids.size(0), -1, -1)
hidden = encoder(torch.cat([prefix, embed(ids)], dim=1))
return head(hidden[:, prompt_len:])
for step in range(200):
ids = torch.randint(0, vocab, (8, seq_len))
logits = forward(ids)
loss = nn.functional.cross_entropy(
logits[:, :-1].reshape(-1, vocab), ids[:, 1:].reshape(-1))
optimizer.zero_grad()
loss.backward()
optimizer.step()
if step % 50 == 0:
frozen = sum(p.numel() for p in encoder.parameters())
print("step", step, "loss", round(loss.item(), 3),
"trainable", prompt.numel(), "frozen", frozen)
Real-World Applications
- Multi-task serving: one base checkpoint plus a small LoRA file per customer replaces a full model copy per tenant, which is how hosted adapters are shipped today.
- On-device personalization: a few hundred soft prompts or an adapter fit in kilobytes, so personalization ships as data rather than as weights.
- Continual learning: adapters give each task its own block, which limits forgetting because the shared trunk never moves.
đĄLoRA merges cleanly into the base model
Common Mistakes
Leaving the base weights trainable
Fix: Set requires_grad to false on the frozen module, otherwise the optimizer silently updates everything.
Initializing B to random values
Fix: Start B at zero so the adapted model begins identical to the pretrained checkpoint.
Using prompt tuning on a 500 million parameter model
Fix: Below roughly 10 billion parameters soft prompts lag supervised updates, so prefer LoRA or adapters.
Best Practices
- Target the query and value projections first, since they carry most of the task signal
- Keep alpha divided by rank fixed when you change rank so update scale stays comparable
- Evaluate merged and unmerged weights once to confirm the arithmetic before deployment
Key Takeaways
- Float32 Adam training costs 16 bytes per parameter, so 7 billion parameters need 112 GB
- LoRA trains r times (d_in plus d_out) parameters, 65,536 at d = 4096 and r = 8
- Adapters add a bottleneck residual per sublayer while every original weight stays frozen
- Prompt tuning trains only l times d embedding numbers, about 204,800 for 50 prompts of width 4096
Frequently Asked Questions
Does LoRA add latency at inference?
No. The product can be folded into the frozen weight matrix after training, so the deployed model has the same shapes, kernels, and latency as the original checkpoint.
Why does rank 8 usually suffice?
Fine-tuning moves weights along a low dimensional subspace, and empirical ranks from 1 to 64 change downstream accuracy by only a fraction of a point while parameter count scales linearly with rank, so small ranks win on cost.
When should you still fine-tune everything?
Full updates help when the labeled set is large and the domain differs sharply from pre-training, such as legal or biomedical text with millions of examples, or when the model must be trained rather than adapted.
Interview Questions
Q1: Why does LoRA work as well as full fine-tuning at 0.39 percent of the parameters?
Because the task specific change to a weight matrix has low intrinsic rank, two thin factors can express the same direction of change that the full outer product stores redundantly.
Q2: How many trainable parameters does LoRA add per matrix at d = 4096 and r = 8?
r times (d_in plus d_out) equals 8 times 8192, which is 65,536 parameters, compared with 16,777,216 for the full matrix.