Chapter 01Shaving Milliseconds Off LoRA Inference for Diffusion Models
Most LoRA write-ups stop at training. The part nobody warns you about is swapping adapters at inference time: a user picks a different style, or your serving layer wants to batch requests that each need a different fine-tune.
The naive merge is slow#
The obvious move is to merge the LoRA into the base weights before every request:
def merge_lora(base_weight, lora_a, lora_b, alpha, rank):
# base_weight: [out, in], lora_a: [rank, in], lora_b: [out, rank]
delta = (lora_b @ lora_a) * (alpha / rank)
return base_weight + deltaFine for one adapter per process. But merging is an out x in matrix add on every adapted layer, and a UNet has a few hundred of them. I saw 40-60ms of pure merge overhead before the denoising loop started, on a workload where 20 diffusion steps were budgeted at ~800ms.
Keep the delta separate#
merge: W' = W + B·A [out x in] add, per layer, per request
└── 40-60 ms before step 1
separate: y = W·x + s · B·(A·x)
└─ x [in] → A → [r] → B → [out], r = 16
base W is never modifiedKeep the low-rank delta as two small matmuls and add the result at the activation level:
class LoRALinear(nn.Module):
def __init__(self, base: nn.Linear, rank: int, alpha: float):
super().__init__()
self.base = base
self.lora_a = nn.Parameter(torch.zeros(rank, base.in_features))
self.lora_b = nn.Parameter(torch.zeros(base.out_features, rank))
self.scale = alpha / rank
self.base.weight.requires_grad_(False)
def forward(self, x):
out = self.base(x)
# rank is small (4-64), so this is cheap relative to the base matmul
out = out + (x @ self.lora_a.T @ self.lora_b.T) * self.scale
return outTwo extra matmuls per layer looks slower, but with r=16 the first one collapses the feature dimension to 16 before the second expands it. The FLOPs are negligible next to the base layer, and you never touch the base weight tensor:
- Adapter swaps are pointer swaps on two small tensors, not a full-model mutation.
- Requests with different adapters can share one forward pass, using a per-sample adapter index.
- Base weights stay untouched in VRAM, so every adapter shares one resident UNet.
Batching across adapters#
What moved the needle in production was batching requests with different adapters together, instead of one queue per adapter.
queue style-a [req][req] ──▶ GPU 1, UNet copy 1 queue style-b [req] ──▶ GPU 2, UNet copy 2 queue style-c [req][req][req] ──▶ GPU 3, UNet copy 3
queue all [a][c][b][a][c] ──▶ GPU 1, one resident UNet
base matmul once for the batch,
per-adapter delta only on that adapter's rowsThe batched forward (code)
def batched_lora_forward(x, base_linear, adapters, adapter_ids):
# adapters: dict[str, (lora_a, lora_b, scale)]
# adapter_ids: LongTensor[batch] mapping each row to an adapter
out = base_linear(x)
for name, (lora_a, lora_b, scale) in adapters.items():
mask = adapter_ids == name_to_id[name]
if not mask.any():
continue
delta = (x[mask] @ lora_a.T @ lora_b.T) * scale
out[mask] += delta
return outNot elegant: a scatter/gather over a Python dict loop wins no style points.
That turns "one adapter per GPU worker" into "one worker serving N adapters", the difference between needing N GPUs and needing one. For a catalog of ~30 style adapters with uneven traffic, that's the whole ballgame.
The lesson that generalized: the fine-tuning technique and the serving strategy are separate design problems. LoRA's low-rank structure makes cheap mid-request swaps possible, but only if your serving code keeps the delta separate, batches across adapters, and never assumes one weight tensor per process.