Library/Transformers from scratch/Gradients and fine-tuning

LoRA from scratch

85 min6 partsCoreFast-moving topicChecked Dec 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Freeze the weight W and train a small change ΔW = BA, with the shape of every tensor on the way
  • Say why B starts at zero and A starts random, and what the other starts cost
  • Say what the alpha / r scale buys you when you change the rank
  • Count what LoRA trains, r(in + out) against in × out, on a real GPT-3 layer
  • Merge the change into the weight for serving without adding it twice, and keep the base frozen
  • Answer the follow-ups: which layers, QLoRA, LoRA against full fine-tuning, and many adapters on one base

LoRA from scratch

LoRA comes up in ML fundamentals screens as a quick "explain LoRA", and in interviews given over to fine-tuning. The strongest answer is one you can also write. As a coding question, it reads like this:

Write LoRALinear(base, r, alpha), a layer that wraps an existing nn.Linear, in four levels.

  1. Freeze the base layer. The only parts that train are A, which is r by in_features, and B, which is out_features by r. Right after wrapping, the layer gives exactly the base layer's output.
  2. forward(x) returns base(x) + (alpha / r) * x @ A.T @ B.T, and the layer learns a low-rank change.
  3. merge() folds the update into base.weight, so inference costs nothing extra, and unmerge() takes it back out. A merged layer must not add the update a second time.
  4. add_lora(model, r, alpha, targets) wraps every nn.Linear named in targets, anywhere in a model, and freezes everything else.

As you go, tell me why B starts at zero and not A, what alpha / r buys you, and how many numbers train.

Here is the finished class on a small layer, nn.Linear(16, 12), wrapped at r = 4 and alpha = 8:

CheckResult
numbers that train112: A holds 4 × 16, and B holds 12 × 4
numbers that stay frozen204: the base's 192 weights and 12 biases
torch.equal(lora(x), base(x)), right after wrappingTrue
the outputs after merge(), once training has moved Bthe same as before the merge
base.weight after unmerge()the pretrained weight again

The class is short. The interview is in the reason behind each line, and in the follow-ups: which layers to adapt, QLoRA, and serving many adapters on one model. The lesson starts with what LoRA trains and why that saves so much, then builds the class one piece at a time. At the end you write all four levels yourself, as the practice problem, in about 45 minutes.

Part 1 of 6about 16 min
What LoRA trains

Full fine-tuning trains every weight, and keeps a copy per task

Fine-tuning the usual way updates every weight of a pretrained model. It works, and it gets expensive fast.

  • Training keeps a gradient and optimizer state for every weight.
  • Every task you fine-tune for leaves you another full copy of the model.

The LoRA paper's example is GPT-3 175B. A separate fine-tuned copy of all 175B parameters for each task is, in its words, prohibitively expensive. Here is what 100 tasks cost to store:

Storing 100 fine-tuned GPT-3 models
100 full copies
35 TB
one base and 100 adapters
354 GB

The paper's own numbers: 35 TB as full copies, 354 GB as one shared base plus 100 small adapters, about 100 times less.

In the editor, copy_gb is one fine-tuned copy of GPT-3 175B, and adapter_mb is one LoRA adapter. Set full_tb: 100 full copies, in terabytes. Set lora_tb: one shared base plus 100 adapters, in terabytes.

LoRA trains two thin matrices, B and A, and leaves W alone

LoRA, short for low-rank adaptation (Hu et al., 2021), freezes each pretrained weight matrix WW. It learns the change to WW as the product of two thin matrices:

W+ΔW=W+BAW + \Delta W = W + BA

ΔW\Delta W is the change that fine-tuning makes. BB has rr columns and AA has rr rows, with rr small, like 8. Only AA and BB train. Drag the rank:

One frozen W, one small pair per taskInteractive
W, frozen
192
A and B, trained
112
GPT-3 Wq, full
150,994,944
GPT-3 Wq, LoRA
98,304, 0.065%
At r = 4, A and B hold r × (in + out) = 4 × (16 + 12) = 112 numbers, against 192 in W. On GPT-3's 12,288-wide query projection the same rank trains 98,304 numbers, 0.065% of its 150,994,944.

Why can so few numbers be enough? The paper's hypothesis is that the change fine-tuning makes has a low intrinsic rank. A matrix's rank counts the independent directions it holds, and the change needs only a few. BABA can hold at most rr directions, which is why rr is called the rank.

The frozen WW is shared by every task. A task's whole fine-tune is the AA and BB of each layer you adapted.

The forward pass adds a small branch to the frozen layer

The input goes through the frozen WW as before. It also goes through AA and then BB, a small side path called the branch. Step through it:

One LoRA layerInteractive
xWAuB+h
forward, values backward, gradients
x goes through the frozen W as before.

The branch's output is added on, scaled by α/r\alpha / r:

h=Wx+αrBAxh = Wx + \frac{\alpha}{r} BAx

Here hh is the layer's output. α\alpha (alpha) is a number you choose, like rr, and neither one trains. In the editor, W is a frozen weight with 16 inputs and 12 outputs, A and B are a rank-4 pair, and scale is α/r\alpha / r. x holds 5 inputs, one per row, so the frozen layer computes x @ W.T. Set h: the frozen layer's output plus the scaled branch. Then set rank, the rank of B @ A, and same: whether h equals one plain layer with the weight W + scale * (B @ A). Compare those two with torch.allclose, because they add in a different order and round differently in the last digits.

Watch · 5 min

LoRA drawn out, from the frozen weight to the shapes of B and A to the parameter count for a 1,000 by 5,000 weight at ranks 1 and 5.

LoRA: Low-Rank Adaptation of Large Language Models - Explained visually + PyTorch code from scratch · Umar Jamil · Jul 2023YouTube

A squeezes the input to r numbers, and B expands it back

Here is the layer as a module, with the branch and the scale you just met, wrapped around a small nn.Linear(16, 12):

import math

import torch
from torch import nn


class LoRALinear(nn.Module):
    def __init__(self, base: nn.Linear, r: int, alpha: float) -> None:
        super().__init__()
        # W and b stay frozen
        self.base = base.requires_grad_(False)
        d_in, d_out = base.in_features, base.out_features
        self.A = nn.Parameter(torch.randn(r, d_in) / math.sqrt(d_in))
        self.B = nn.Parameter(torch.zeros(d_out, r))
        self.scale = alpha / r

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """x: (..., in). Returns (..., out)."""
        return self.base(x) + self.scale * (x @ self.A.T @ self.B.T)


torch.manual_seed(0)
lora = LoRALinear(nn.Linear(16, 12), r=4, alpha=8.0)
# 5 rows of input
x = torch.randn(5, 16)
print(tuple(lora.A.shape), tuple(lora.B.shape))
(4, 16) (12, 4)

Every shape, with ... for any leading axes such as batch and time:

TensorShapeWhat it is
x(..., in)the layer's input
base.weight(out, in)the pretrained WW, frozen
A(r, in)trainable, random at the start
B(out, r)trainable, zero at the start
x @ A.T(..., r)the input squeezed to rr numbers
x @ A.T @ B.T(..., out)the update's output, added to base(x)
B @ A(out, in)ΔW\Delta W itself, built only to merge

PyTorch stores the weight as (out, in). The paper calls it d×kd \times k, so dd is out and kk is in. BABA has the same shape as WW.

The paper works on a column vector xx. PyTorch works on rows, x @ W.T + b. On rows, the forward pass reads:

y=xW⊤+b+αr xA⊤B⊤y = xW^\top + b + \frac{\alpha}{r}\, xA^\top B^\top

In the editor is the LoRALinear from above, wrapped around a layer with 64 inputs and 48 outputs, at rank 8. x is a batch of 10 rows. Set squeezed: x after A alone. Set out: the wrapped layer's output for x, and trainable: how many numbers A and B hold together.

Multiply x by A first, and the big matrix is never built

The order of the two matmuls decides what the update costs.

# GPT-3 175B's query projection, at rank 8
d, r = 12_288, 8
# x @ A.T @ B.T, for one input row
print(f"{r * (d + d):,}")
# the frozen layer, for one input row
print(f"{d * d:,}")
# building B @ A
print(f"{d * r * d:,}")
Predict

GPT-3's query projection is 12,288 by 12,288. At rank 8, how does the branch's work for one input row compare with the frozen layer's?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 1 done
Part 2 of 6about 14 min
How A and B start

With B at zero, the wrapped layer equals the base layer

Right after wrapping, the model should behave exactly as before.

base = nn.Linear(16, 12)
lora = LoRALinear(base, r=4, alpha=8.0)
print(torch.equal(lora(x), base(x)))
True

torch.equal is True only when every number matches exactly.

At creation the branch adds exactly zero
B (2, 1)
00
A, random (1, 3)
10-1
B @ A (2, 3)
000000

With B at zero, B @ A is all zeros, so lora(x) = base(x) + (α / r) · 0 = base(x). These are the sizes of the worked example in Part 5: out = 2, r = 1, in = 3.

That needs BA=0BA = 0, so one of the two factors starts at zero. The paper's choice is a random Gaussian AA and a zero BB.

In the editor, lora wraps a fresh base layer at rank 4, and x holds 5 inputs. Set same_at_start: whether lora(x) equals base(x) exactly. The next line moves B, as one training step would. Then set moved: whether the two outputs differ now.

If both started at zero, neither would ever move

Why start only B at zero, and not both?

def grad_sizes(A: torch.Tensor, B: torch.Tensor) -> tuple[float, float]:
    """A: (r, in), B: (out, r). Returns each one's largest first gradient."""
    A, B = A.clone().requires_grad_(), B.clone().requires_grad_()
    (x @ A.T @ B.T).sum().backward()
    return A.grad.abs().max().item(), B.grad.abs().max().item()


torch.manual_seed(0)
rand_A, rand_B = torch.randn(4, 16), torch.randn(12, 4)
zero_A, zero_B = torch.zeros(4, 16), torch.zeros(12, 4)
starts = [("B zero", rand_A, zero_B), ("A zero", zero_A, rand_B),
          ("both zero", zero_A, zero_B)]
for name, A, B in starts:
    dA, dB = grad_sizes(A, B)
    print(f"{name:<10} A gets {dA:5.2f}   B gets {dB:5.2f}")
Predict

Three starts: B zero, A zero, or both zero. Which one gives both factors a zero gradient?

Pick one to see what it prints.
Pick an answer above to see the rest

Divide A by sqrt(in), and the signal keeps its size

A starts random, and the scale of that randomness matters.

torch.manual_seed(0)
# inputs of typical size 1
xs = torch.randn(1000, 400)
plain = torch.randn(8, 400)
scaled = torch.randn(8, 400) / math.sqrt(400)
print(round((xs @ plain.T).std().item(), 1))
print(round((xs @ scaled.T).std().item(), 1))
19.7
1.0
The typical size of one entry, with in = 400
x
about 1
x @ A.T, A = randn
about 20
x @ A.T, A = randn / 20
about 1

The paper only says Gaussian. Dividing by in\sqrt{\text{in}} is a sensible scale: the bottleneck then neither blows up the signal nor shrinks it.

In the editor, xs holds 1,000 inputs of typical size 1, each with d_in = 1600 numbers. Set plain: the spread, .std(), of xs @ A.T for an A of 8 rows from torch.randn. Set scaled: the same spread, with A divided by math.sqrt(d_in).

The other way round also trains

What about a zero A and a random B instead?

Predict

A at zero with B random also gives B @ A = 0, and it trains too. Hayou et al. (2024) compared the two starts. Which did better on average?

Pick an answer above to see the rest
Part 2 done
Part 3 of 6about 17 min
Scale, count and placement

The alpha / r scale keeps one learning rate good at every rank

The last piece of the layer is the scale in front of the branch.

The scale multiplies the branch

# 2.0 for r = 4, alpha = 8
self.scale = alpha / r
y = self.base(x) + self.scale * (x @ self.A.T @ self.B.T)

The paper scales the update by α/r\alpha / r and gives its reason. With Adam, tuning α\alpha is roughly the same as tuning the learning rate, if you also scale the starting values of AA and BB to match. So the authors set α\alpha to the first rr they try and never tune it. The scale means less retuning when you change rr.

Without the scale, a bigger rank takes a bigger step

Predict

No scale, and Adam's first step. How does a rank-64 adapter's step compare with a rank-16 one's?

Pick an answer above to see the rest

Rank-stabilized LoRA divides by the square root of r instead

Not everyone agrees that rr is the right divisor.

Predict

Rank-stabilized LoRA divides by √r instead of r. At r = 256 and α = 16, what's its scale, against α / r = 0.0625?

Pick an answer above to see the rest

Count the numbers in A and B

A full update to one weight trains in × out numbers. LoRA trains AA and BB:

r×in⏟A+out×r⏟B=r (in+out)\underbrace{r \times \text{in}}_{A} + \underbrace{\text{out} \times r}_{B} = r\,(\text{in} + \text{out})

The paper treats each attention projection of GPT-3 175B as a 12,288 × 12,288 matrix. Below, WqW_q, WkW_k, WvW_v and WoW_o are the query, key, value and output projections.

ComputationTrainable numbers
one full WqW_q12,288 × 12,288150,994,944
LoRA, r=1r = 11 × (12,288 + 12,288)24,576
LoRA, r=4r = 44 × 24,57698,304, or 0.065% of WqW_q
LoRA, r=8r = 88 × 24,576196,608, or 0.13% of WqW_q
WqW_q and WvW_v at r=4r = 4, all 96 layers96 × 2 × 98,30418,874,368
# Wq and Wv at r = 4, 96 layers
total = 96 * 2 * 4 * (12_288 + 12_288)
print(f"{total:,}", total * 2 / 2**20, "MiB at 2 bytes a number")
print(f"{round(175e9 / total):,}", "times fewer than the full model")
18,874,368 36.0 MiB at 2 bytes a number
9,272 times fewer than the full model

That last row of the table is the paper's whole budget for its study of which layers to adapt.

  • At 2 bytes a number it's 36 MiB: the roughly 35MB checkpoint the paper reports, against 350GB for a full fine-tune.
  • The paper rounds the 9,272 to 10,000.
  • The paper's GPT-3 results table lists LoRA runs with 4.7M and 37.7M trainable parameters. Those are the same WqW_q and WvW_v count at r=1r = 1 and r=8r = 8.

In the editor, write lora_params(shapes, r): how many numbers train when LoRA at rank r adapts every weight in shapes, a list of (out, in) pairs. Each weight adds r(in+out)r(\text{in} + \text{out}).

CheckpointCount what LoRA trains

Write lora_params(shapes, r): how many numbers train when LoRA at rank r adapts every weight in shapes. shapes is a list of (out, in) pairs. The tests use the practice layer, and GPT-3's query and value projections in all 96 layers.

Training memory drops much less than that

Fewer trainable weights sounds like far less memory. Count what stays.

Predict

LoRA trains about 10,000 times fewer numbers on GPT-3 175B. By how much did the paper's training memory drop?

Pick an answer above to see the rest

The paper spread a fixed budget over more attention matrices

With a fixed budget of parameters, the next choice is where to spend them.

Where LoRA goesWqW_qWkW_kWvW_vWoW_oMLP upMLP down
LoRA paper, 2021yesnoyesnonono
QLoRA and lateryesyesyesyesyesyes

LoRA works on any weight matrix, so you choose where it goes. The paper chose narrowly. It adapted only the attention weights and froze the MLP, for simplicity and to save parameters.

Then it asked which attention matrices to adapt, under a fixed budget of 18M trainable parameters on GPT-3.

Predict

The same 18M budget, spent two ways. Which scored higher on WikiSQL: Wq alone at rank 8, or all four attention matrices at rank 2?

Pick an answer above to see the rest
Predict

The paper's rank study went further. What rank was enough on these datasets, with both Wq and Wv adapted?

Pick an answer above to see the rest
Predict

QLoRA tried adapting only the query and value projections on large models. Did that match full fine-tuning?

Pick an answer above to see the rest
Part 3 done
Part 4 of 6about 15 min
Merge, unmerge and freeze

Fold the scaled update into the weight, once

W′=W+αrBAW' = W + \frac{\alpha}{r} BA

W′W' has the shape of WW, so the merged layer is an ordinary linear layer. It costs exactly what the base did, so merging adds no latency at inference.

To switch tasks, subtract the update to get WW back, then add a different pair's B′A′B'A'. The paper calls that a quick operation with very little memory overhead.

Once merged, forward has to skip the branch

The layer keeps a flag, merged, that says which of the two forms it is in:

MethodWhat it does
merge()adds αrBA\frac{\alpha}{r}BA to base.weight, then sets merged
forward(x)runs the base, and adds the branch only while merged is clear
unmerge()subtracts the same update, then clears merged

Walk one small layer through it, then break it:

One layer, merged and unmergedInteractive
base.weight W
10201-1
branchon: + [-2, 4]
output on x = [1, 2, 3][5, 3]
Unmerged: the frozen W gives [7, -1], and the branch adds (α / r) · x Aᵀ Bᵀ = [-2, 4]. Output [5, 3].

A second merge() or unmerge() in a row does nothing, because each one checks the flag first.

Four details carry it:

  • Merge the scaled update, the same α/r\alpha / r that the forward pass applies.
  • Once merged, skip the branch. The update lives in the weight now.
  • Run both under torch.no_grad().
  • Check the flag first, so a second merge() or unmerge() changes nothing.
Predict

You run merge() without torch.no_grad(). What happens?

Pick an answer above to see the rest

Merge and unmerge are exact on paper, not in bf16

Merging is exact in theory, but real weights are stored with limited precision.

torch.manual_seed(0)
# weights of typical size 0.02
W = torch.randn(4096, 4096) * 0.02
# an update of typical size 0.001
dW = torch.randn(4096, 4096) * 0.001
for dtype in (torch.float32, torch.bfloat16):
    w, d = W.to(dtype), dW.to(dtype)
    # merge, then unmerge
    back = (w + d) - d
    print(dtype, f"{(back.float() - w.float()).abs().max().item():.1e}")
Predict

Merge and then unmerge an update of size 0.001 into weights of size 0.02. How far off is W afterward, in float32 and in bfloat16?

Pick one to see what it prints.
Pick an answer above to see the rest

requires_grad_(False) freezes the weight and the bias together

Freezing the base layer is one call, and it freezes more than the weight.

lora = LoRALinear(nn.Linear(16, 12), r=4, alpha=8.0)
names = [n for n, p in lora.named_parameters() if p.requires_grad]
print(names, sum(p.numel() for p in lora.parameters() if p.requires_grad))
['A', 'B'] 112

Run this check right after wrapping, every time.

ParameterShapeNumbersTrains?
base.weight12 × 16192frozen
base.bias1212frozen
A4 × 1664trains
B12 × 448trains
What trains112

Then hand only those to the optimizer:

opt = torch.optim.Adam([p for p in lora.parameters() if p.requires_grad], lr=lr)

The PyTorch docs name requires_grad as the main way to choose which parts of a model take part in the gradient computation, and freezing part of a pretrained model for fine-tuning is their example. A frozen weight gets no .grad and no optimizer state.

The method's name is not the point. A loop that sets p.requires_grad_(False) for each p in base.parameters() does the same, and the practice's worked solution does exactly that.

In the editor, this LoRALinear.__init__ freezes base.weight alone, so base.bias still trains. Fix it: freeze the whole base layer in one call, so that only A and B train.

A frozen weight still passes the gradient back

From the loss down, each LoRA layer does the same three things:

  1. Its AA and BB get gradients and train.
  2. Its frozen WW gets no gradient of its own.
  3. The gradient still goes back through WW to the layer below.
Predict

A frozen W gets no gradient of its own. Does the gradient still flow back through it to the layers below?

Pick an answer above to see the rest
Part 4 done
Part 5 of 6about 8 min
A worked example

A worked example: one layer by hand

Shrink it to something you can do by hand: in = 3, out = 2, r=1r = 1 and α=2\alpha = 2, so the scale is 2. The bias is zero and the input is x=[1,2,3]x = [1, 2, 3].

W=[10201−1],A=[10−1]W = \begin{bmatrix} 1 & 0 & 2 \\ 0 & 1 & -1 \end{bmatrix}, \qquad A = \begin{bmatrix} 1 & 0 & -1 \end{bmatrix}

To keep the arithmetic short, pretend training moved only BB, to B⊤=[0.5,−1]B^\top = [0.5, -1], and left AA where it started.

Before merge, merged, and unmerged: the same output

W = torch.tensor([[1., 0., 2.], [0., 1., -1.]])
A = torch.tensor([[1., 0., -1.]])
B = torch.tensor([[0.5], [-1.]])
x = torch.tensor([[1., 2., 3.]])
# base, bottleneck
print((x @ W.T).tolist(), (x @ A.T).tolist())
# trained
print((x @ W.T + 2 * (x @ A.T @ B.T)).tolist())
W_merged = W + 2 * (B @ A)
# merged
print(W_merged.tolist(), (x @ W_merged.T).tolist())
Predict

W gives [7, -1] for x, and the bottleneck x @ A.T is -2. With scale 2 and B = [0.5, -1], what does the trained layer give?

Pick one to see what it prints.
Pick an answer above to see the rest

Break it each way, and every answer looks fine

Start from the trained layer and put in one bug at a time:

BugWhat runsOutputCorrect
nonexW⊤+2 xA⊤B⊤xW^\top + 2\,xA^\top B^\top[5, 3][5, 3]
B starts at [0.1, -0.2]at creation, [7,−1]+2⋅(−2)⋅[0.1,−0.2][7, -1] + 2 \cdot (-2) \cdot [0.1, -0.2][6.6, -0.2][7, -1]
no α/r\alpha / r[7,−1]+[−1,2][7, -1] + [-1, 2][6, 1][5, 3]
merge without α/r\alpha / rx(W+BA)⊤x(W + BA)^\top[6, 1][5, 3]
branch still on after mergexW′⊤+[−2,4]xW'^{\top} + [-2, 4][3, 7][5, 3]
base not frozensame outputs13 trainable numbers5

The unscaled merge does more damage on the way out.

Predict

After an unscaled merge, unmerge() subtracts 2 B A and leaves W − B A. What does the base alone give now?

Pick an answer above to see the rest
Part 5 done
Part 6 of 6about 15 min
What interviewers ask next

QLoRA keeps the frozen weights in 4 bits

Once the layer works, the follow-ups move to memory, quality and serving. Have four answers ready.

Memory for 65 billion frozen weights
16-bit
130 GB
QLoRA
33.5 GB

LoRA drops the gradients and optimizer state for the frozen weights, but the weights themselves still sit in memory at 16 bits. QLoRA (Dettmers et al., 2023) stores them in 4 bits. It backpropagates through the frozen 4-bit model into the LoRA adapters. Three pieces make that work:

  • NF4, a 4-bit NormalFloat type built for weights that are normally distributed.
  • Double quantization, which quantizes the per-block scale constants too.
  • Paged optimizers, which move optimizer state to CPU memory when the GPU runs short.

The weights are stored in 4 bits and turned back into bf16 for each matmul, which is called dequantizing. Only the adapters get weight gradients, and they stay in 16-bit BrainFloat (bf16).

The memory math:

  • With blocks of 64 weights, a 32-bit scale per block adds 0.5 bits per weight.
  • Double quantization cuts that to 0.127 bits.
  • So 65 billion weights at 4.127 bits come to about 33.5 GB, against 130 GB in 16-bit.

That's how QLoRA fine-tunes a 65B parameter model on a single 48GB GPU. Regular 16-bit fine-tuning of it needs more than 780 GB of GPU memory. QLoRA also puts adapters on every linear layer, which is where the all-layers finding in Part 3 comes from.

Predict

A QLoRA adapter learned its correction on top of the dequantized 4-bit weights. Which weights do you merge it into?

Pick an answer above to see the rest

Merging makes serving cheap, but only for one adapter

Back to serving: merge the adapter, or keep it separate?

MergedUnmerged
Tasks per modelonemany, on one shared base
Extra work per adapted layernonetwo small matmuls

A merged model is a plain model: no extra matmuls, no extra kernel launches, nothing for the serving stack to know about. Unmerged, every adapted layer runs two more small matmuls on each forward pass. They're cheap in arithmetic, 0.13% of the layer at r=8r = 8 on GPT-3's projection, but they're extra steps on the path that sets latency.

Predict

You merged adapter 0 into the base. Can the same batch also serve a request for adapter 2?

Pick an answer above to see the rest
Predict

Biderman et al. (2024) trained on code and math, with about 100K instruction examples and 20B tokens of continued pretraining. How did LoRA do against full fine-tuning?

Pick an answer above to see the rest

Many adapters can share one base

One batch, where each row is a request with its own adapter:

RowShared base, one matmul for the batchIts own adapter
0x0 @ W.T+ scale · x0 @ A2.T @ B2.T
1x1 @ W.T+ scale · x1 @ A0.T @ B0.T
2x2 @ W.T+ scale · x2 @ A2.T @ B2.T

Keep the base unmerged and shared, and give each request its own adapter. Every request goes through the same WW, so the big matmul still runs once for the whole batch. Only the small low-rank part differs from row to row.

Two tools build that part. Indexing with a tensor of ids picks one adapter for each row:

torch.manual_seed(0)
K, r, d_in = 5, 4, 16
# K adapters
A_all = torch.randn(K, r, d_in)
# each row's adapter
ids = torch.tensor([2, 0, 2])
picked = A_all[ids]
print(tuple(picked.shape), torch.equal(picked[1], A_all[0]))
(3, 4, 16) True

And torch.bmm runs one matmul per row, pairing the matrices along the first axis:

P, Q = torch.randn(3, 4, 16), torch.randn(3, 16, 1)
out = torch.bmm(P, Q)
print(tuple(out.shape), torch.allclose(out[2], P[2] @ Q[2], atol=1e-6))
(3, 4, 1) True

The pieces, in the order you use them:

  • A_all[ids] gathers one adapter for each row, so A[i] belongs to request i. B_all[ids] does the same for B.
  • x.unsqueeze(-1) turns each row of x into an (in, 1) column, the shape torch.bmm wants on the right.
  • torch.bmm multiplies the matching pairs: (r, in) by (in, 1) for every request, then (out, r) by (r, 1).
  • squeeze(-1) drops the trailing axis of size 1 again.

In the editor are a frozen W, the K = 5 adapters in A_all and B_all, three requests in x, and ids, each row's adapter. Set A, B: each row's own pair, picked with ids. Set y: the shared base for every row, plus each row's own scaled branch, as (N, out).

Serving systems batch the adapters with their own kernels

The gather, A_all[ids], copies an adapter for every row of the batch, so serving systems write their own kernels for this step:

  • Punica has a CUDA kernel that batches GPU operations for different LoRA models. So one GPU holds a single copy of the base model while it serves many different LoRA models.
  • S-LoRA keeps all adapters in main memory and fetches the ones the running queries use to GPU memory. It pages adapter weights and the KV cache from one shared pool, and it reports serving thousands of adapters on one GPU or across several, with a small overhead.
  • By 2025 this was mainstream. The Thinking Machines post notes that vLLM and SGLang implement it.

The storage side is why it's worth it.

Predict

100 fine-tuned GPT-3 variants: one 350GB base plus 100 adapters of 35MB each. About how much is that in all?

Pick an answer above to see the rest

The practice problem, start to finish

That's every piece the practice problem needs. It asks for the four levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.

The round may open with the short version, before any code.

Check yourself
5 questions
  1. 1.You initialize B with torch.randn(out, r) * 0.01 instead of zeros. What happens?

  2. 2.You wrap nn.Linear(16, 12) with r = 4 and forget to freeze the base. How many parameters report requires_grad=True?

  3. 3.With alpha = 8 and r = 4, merge() runs W += B @ A and forgets the scale. What does the merged layer compute?

  4. 4.After merge(), your forward still adds the LoRA branch. What do you get?

  5. 5.Your layer multiplies the update by 1 instead of alpha / r. Which check catches it?

Where this shows up

The reports behind this lesson, each with its source.

A prep site lists a Netflix MLE technical screen (posted 2026-04-22) as a rapid-fire ML fundamentals screen (the question is titled 'Compare Losses and Explain LoRA').

Prep site·PracHub (prep site question bank)·2026-04-22Source

The Production Model Post-Training role (Zürich posting) names Constitutional AI and RLHF among the techniques involved.

“techniques like Constitutional AI, RLHF, and other alignment methodologies”
Company source·Anthropic job posting (Greenhouse)Source

Same mid-2026 DS report (ant-078): the next interview was about fine-tuning.

Candidate report·Aced, formerly Exponent (candidate report)Source

The ML engineering ladder runs up to Principal; the one open Principal role is in LLM fine-tuning.

“Principal Machine Learning Engineer- LLM Fine-tuning and Optimization”
Company source·Airbnb job board (Greenhouse API, boards-api.greenhouse.io/v1/boards/airbnb)Source

Practice

Sources (9)
  1. LoRA: Low-Rank Adaptation of Large Language Models · arXiv 2106.09685 · Jun 17, 2021
    “We propose Low-Rank Adaptation, or LoRA, which freezes the pre-trained model weights and injects trainable rank decomposition matrices into each layer of the Transformer architecture, greatly reducing the number of trainable parameters for downstream tasks.”
  2. QLoRA: Efficient Finetuning of Quantized LLMs · arXiv 2305.14314 · May 23, 2023
    “QLoRA backpropagates gradients through a frozen, 4-bit quantized pretrained language model into Low Rank Adapters (LoRA).”
  3. The Impact of Initialization on LoRA Finetuning Dynamics · arXiv 2406.08447 · Jun 12, 2024
    “We demonstrate that this is an incorrect intuition and that the first scheme (initializing B to zero and A to random) on average yields better performance compared to the other scheme.”
  4. A Rank Stabilization Scaling Factor for Fine-Tuning with LoRA · arXiv 2312.03732 · Nov 28, 2023
    “This scaling factor, which divides adapters by a factor of the rank, results in slowed learning and stunted performance for LoRA with higher-rank adapters.”
  5. Autograd mechanics · PyTorch 2.15 documentation · Aug 11, 2026
    “Setting requires_grad should be the main way you control which parts of the model are part of the gradient computation, for example, if you need to freeze parts of your pretrained model during model fine-tuning.”
  6. LoRA Without Regret · Thinking Machines Lab: Connectionism · Sep 29, 2025
    “Even in small data settings, LoRA performs better when applied to all weight matrices, especially MLP and MoE layers.”
  7. LoRA Learns Less and Forgets Less · arXiv 2405.09673 · May 15, 2024
    “Our results show that, in the standard low-rank settings, LoRA substantially underperforms full finetuning. Nevertheless, LoRA better maintains the base model's performance on tasks outside the target domain.”
  8. Punica: Multi-Tenant LoRA Serving · arXiv 2310.18547 · Oct 28, 2023
    “This allows a GPU to hold only a single copy of the underlying pre-trained model when serving multiple, different LoRA models, significantly enhancing GPU efficiency in terms of both memory and computation.”
  9. S-LoRA: Serving Thousands of Concurrent LoRA Adapters · arXiv 2311.03285 · Nov 6, 2023
    “S-LoRA stores all adapters in the main memory and fetches the adapters used by the currently running queries to the GPU memory.”