🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

LoRA and PEFT: Low-Rank Fine-Tuning Explained

đŸŸĸ Free Lesson

LoRA and PEFT: Low-Rank Fine-Tuning Explained

LoRA ArchitectureStandard LayerWeight Matrix Wd x d parametersFrozen during trainingParameters: 100%LoRA LayerW (frozen)+A (rxd)B (dxr)Low-rank decompositionParameters: 0.1-1%BenefitsMemory efficientFast trainingMultiple adaptersEasy deployment

Why full fine-tuning gets expensive so fast

When a 7-billion-parameter chat model needs to learn your support-ticket triage rules, the obvious move is to keep training it on your labelled data. The cost of that obvious move is rarely obvious. Weights in 16-bit precision occupy about 14 GB, but Adam also keeps a first-moment and a second-moment buffer for every single parameter, and mixed-precision training retains a 32-bit master copy. The working set climbs to roughly 16 bytes per parameter, which is around 112 GB before you store a single gradient. A single A100 has 80 GB, so a team that planned "one GPU, one afternoon" is suddenly sharding checkpoints across a multi-GPU job.

LoRA exists because almost none of those bytes are doing useful work. The model already speaks the language; what it lacks is a narrow correction toward your domain. Training only that correction changes the economics of adaptation by two orders of magnitude, and it changes what a two-person team can realistically ship.

The low-rank hypothesis

The original LoRA paper asked an empirical question: when a pretrained transformer adapts to a new task, how large is the change really? The authors fine-tuned GPT-3 175B on downstream tasks and measured the rank of the resulting weight deltas. Despite the matrices having 12,288 rows and columns, the updates clustered around a few dozen meaningful directions. Most of the matrix was being reused, not rewritten.

That observation gives the method its name. Rather than learning a full d × d update, LoRA learns two thin matrices: A with shape r × d and B with shape d × r, where r is a small rank such as 8 or 16. The forward pass becomes the frozen weight output plus the product B(A(x)) scaled by alpha divided by r. The parameter arithmetic is brutal in your favour.

Layer width dFull matrixRank-8 adapterRank-16 adapter
10241,048,57616,384 (1.6%)32,768 (3.1%)
409616,777,21665,536 (0.4%)131,072 (0.8%)
819267,108,864131,072 (0.2%)262,144 (0.4%)

Writing the adapter layer yourself

The mechanism is small enough to hold in your head, and implementing it once makes every library call afterwards less magical. The frozen weight stays exactly where it was; the adapter is an additive branch that starts near zero, so an untrained LoRA layer initially reproduces the original model.

python
import torch
import torch.nn as nn

class LoRALinear(nn.Module):
    def __init__(self, base: nn.Linear, rank: int = 8, alpha: float = 16.0):
        super().__init__()
        self.base = base
        self.rank = rank
        self.scale = alpha / rank

        # A is initialised so that B @ A starts at zero
        self.lora_a = nn.Linear(base.in_features, rank, bias=False)
        self.lora_b = nn.Linear(rank, base.out_features, bias=False)
        nn.init.kaiming_uniform_(self.lora_a.weight, a=5 ** 0.5)
        nn.init.zeros_(self.lora_b.weight)

        for param in self.base.parameters():
            param.requires_grad = False

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        frozen = self.base(x)
        adapter = self.lora_b(self.lora_a(x)) * self.scale
        return frozen + adapter

    @torch.no_grad()
    def merge(self) -> nn.Linear:
        """Fold the adapter into the base weight for zero-cost inference."""
        self.base.weight += (self.lora_b.weight @ self.lora_a.weight) * self.scale
        return self.base

Zero-initialising B matters more than it looks. If both matrices carried random values at step zero, the model would start producing garbage and spend its first epochs unlearning itself. Starting from zero means training begins from the exact pretrained behaviour and only drifts as the loss demands it.

Wrapping a real checkpoint with PEFT

Hand-rolling the layer teaches the concept; the peft library is what you use in production, because it handles which modules get replaced, how adapters are saved, and how multiple adapters are swapped at inference time.

python
from peft import LoraConfig, PeftModel, get_peft_model, TaskType
from transformers import AutoModelForCausalLM

def attach_adapter(model_name: str, rank: int = 16, alpha: int = 32):
    base = AutoModelForCausalLM.from_pretrained(
        model_name, torch_dtype="auto", device_map="auto"
    )
    config = LoraConfig(
        task_type=TaskType.CAUSAL_LM,
        r=rank,
        lora_alpha=alpha,
        lora_dropout=0.05,
        target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
        bias="none",
    )
    model = get_peft_model(base, config)
    model.print_trainable_parameters()
    # trainable params: 8,388,608 || all params: 6,742,609,920 || trainable%: 0.12
    return model

def reload_later(base_name: str, adapter_dir: str):
    base = AutoModelForCausalLM.from_pretrained(base_name, device_map="auto")
    return PeftModel.from_pretrained(base, adapter_dir)

Roughly 0.1 percent of the weights move during training. That single number explains why adapter fine-tuning fits on one card, why checkpoints are measured in megabytes instead of gigabytes, and why one base model can carry a shelf of task-specific adapters.

Choosing rank, alpha and target modules

There is no universally correct configuration, but the trade-offs are well understood. Rank controls capacity: rank 4 to 8 handles style and tone shifts, while factual or domain-knowledge injection usually wants 16 to 64. Beyond about rank 128 the returns flatten and you are paying full fine-tuning prices for a method that is supposed to be cheap. Alpha controls how strongly the adapter's output is scaled relative to the frozen path; keeping alpha equal to rank is a sane default, and doubling alpha while holding rank fixed roughly doubles the adapter's initial influence.

SettingConservativeBalancedAggressive
Rank r4–816–3264–128
Alphaequal to r2 × r2 × r
Dropout0.05–0.10.050.0
Targetsattention onlyattention + MLPevery linear layer
Learning rate1e-42e-45e-4

Target modules deserve their own thought. Attaching adapters to query and value projections alone is the classic recipe and the cheapest. Adding the output projection and the feed-forward blocks roughly quadruples trainable parameters but gives the model room to change what it retrieves from its own representation, which is what you want for a new vocabulary such as internal product names or ICD codes.

Serving: keep adapters apart or fold them in

Adapters give you a deployment choice that full fine-tuning never did. You can host one base model and swap adapters per tenant in milliseconds, or you can merge the adapter into the base weights and serve it as an ordinary checkpoint with no added latency. Merging is a single in-place addition, but it is irreversible, so keep the adapter files in version control even after you ship the merged model.

python
import torch

def benchmark(model, prompt, steps=50):
    input_ids = tokenizer(prompt, return_tensors="pt").input_ids.cuda()
    torch.cuda.synchronize()
    start = torch.cuda.Event(enable_timing=True)
    end = torch.cuda.Event(enable_timing=True)
    start.record()
    with torch.no_grad():
        model.generate(input_ids, max_new_tokens=64, do_sample=False)
    end.record()
    torch.cuda.synchronize()
    return start.elapsed_time(end) / steps

# A merged adapter generates at exactly base-model speed:
merged = peft_model.merge_and_unload()
merged.save_pretrained("./support-bot-merged")

Because the merged weights are mathematically identical to base-plus-adapter, quality never differs between the two paths. Only operational flexibility does: merged checkpoints are simpler to serve, unmerged adapters let you run A/B tests or multi-tenant routing from a single loaded model.

Which variant fits your situation

The original paper spawned a family of refinements, and each one fixes a specific complaint.

VariantCore changeReaches for it when
QLoRABase weights in 4-bit NF4, adapters in 16-bitYou have one 24 GB card and a 30B+ model
AdaLoRARank is allocated per layer and pruned during trainingSome layers clearly matter more than others
DoRASplits each weight into magnitude and directionYou want full fine-tuning quality at adapter cost
LoRA+Different learning rates for A and BYou are chasing the last few points of accuracy
rsLoRARescales gradients as rank growsYou are experimenting with rank 64 and above

QLoRA is the one most teams actually deploy: it lets a 65B model fine-tune inside 48 GB of VRAM with modest quality loss, which collapsed the hardware requirement for adaptation from a cluster to a single workstation.

Where the approach breaks down

LoRA is not free magic. It underperforms full fine-tuning when the task requires genuinely new knowledge rather than a re-weighting of what the model already knows — training a model on a large corpus of facts it has never seen is one of the few cases where updating every parameter still wins. It also struggles when you need the model to forget something, because a low-rank correction is structurally poor at cancelling a high-rank behaviour. And adapter quality is sensitive to data order and learning rate: with only a fraction of a percent of parameters moving, a bad schedule shows up quickly and there is no large model to absorb the mistake.

Treat LoRA as the default first attempt and full fine-tuning as the escalation path you take with evidence, not as a starting point you graduate from.

Common Mistakes

Setting rank to 256 hoping for more capacity

Fix: Start at 16 and double only while validation loss is still falling; beyond 128 the cost curve stops making sense.

Applying adapters to every linear layer by default

Fix: Begin with q_proj and v_proj, then widen targets only if the model clearly cannot express the new behaviour.

Training with a learning rate borrowed from full fine-tuning

Fix: Adapters need 1e-4 to 5e-4; 2e-5, which is standard for full runs, will barely move them.

Merging adapters before verifying evaluation results

Fix: Validate the unmerged model first, keep the adapter file, and merge only once metrics pass.

Best Practices

  • Keep one base checkpoint and many small adapter directories so tenants can be served from a single loaded model.
  • Log trainable parameter counts at start-up; a percentage above 1 percent usually means the targets are too broad.
  • Pair every adapter with the base model revision it was trained against, because merging against the wrong revision silently corrupts weights.
  • Use dropout between 0.05 and 0.1 on small datasets and 0 on large ones.

Interview Questions

Q1: Why does LoRA initialise one of its two matrices to zero?

It guarantees the adapter contributes nothing at step zero, so training starts from the exact pretrained behaviour instead of degrading the model first.

Q2: What do r and lora_alpha control?

r is the bottleneck rank that sets adapter capacity and parameter count; alpha scales the adapter output by alpha divided by r, controlling how strongly it influences the frozen pathway.

Q3: When would you pick full fine-tuning over LoRA?

When injecting substantial new factual knowledge, when the model must unlearn behaviour, or when adapter experiments have already shown a persistent quality gap you can attribute to capacity.

Key Takeaways

  • LoRA freezes the pretrained weight and trains two rank-sized matrices, cutting trainable parameters to roughly 0.1–1 percent of the model.
  • The method works because fine-tuning updates are empirically low-rank; the adapter mirrors the structure of the change the task actually needs.
  • Zero-initialising the B matrix lets training begin from the untouched pretrained model.
  • Alpha divided by r scales the adapter, and target modules decide how much of the network can move.
  • Adapters can be swapped per tenant at runtime or merged into the base weights for identical quality at zero added latency.
  • QLoRA extends the same idea to 4-bit base weights, which is what makes single-GPU adaptation of 30B-plus models practical.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement