Code Lab / Challenge 14

LoRA Adapters: Zero Init, Merging, Multi-Adapter Serving

MediumLoRA forward, merge, and batched multi-adapter serving

The problem, as an interviewer would set it

Implement LoRA (Hu et al., 2021) for a single linear layer, plus the batched
dispatch that lets one copy of the base weights serve many fine-tunes at once.

    LoRALinear(W, r, alpha, seed)
        W       base weight of shape (d, k), frozen
        A       shape (d, r), drawn from N(0, 1/r): variance 1/r, scale 1/sqrt(r)
        B       shape (r, k), all zeros
        scaling alpha / r

    forward(x) -> x @ W + (alpha / r) * (x @ A) @ B
        Keep the two thin matmuls. Forming A @ B here materialises a d x k
        matrix on every step and throws away the whole point of the method.
    merge() -> a single (d, k) matrix, W + (alpha / r) * A @ B, leaving W alone.
    trainable_params() -> entries in A and B
    param_ratio()      -> trainable_params() / W.size

    apply_adapters(x, base_W, adapters, request_ids) -> (batch, k)
        Batched multi-adapter serving, the S-LoRA idea. x is (batch, d) and
        request_ids is a (batch,) array of indices into `adapters`, where -1
        means "base model, no adapter". Run the base projection ONCE for the
        whole batch, then add each adapter's low-rank delta to the rows that
        asked for it, gathered by adapter id. A per-request Python loop over
        the base matmul is the wrong answer.

Constraints: numpy and the standard library only, float64, seeded throughout.
What interviewers look for

Why B is zero-initialised, what alpha/r decouples, why merging costs you hot-swapping

A strong solution demonstrates:
- Why B starts at zero and A does not. At step 0 the delta is exactly zero, so
  the adapted layer reproduces the pretrained one bit for bit. But dL/dB is
  proportional to (x @ A) transposed, so zeroing A as well would leave B with
  no gradient forever. One side zero, one side random. The exact distribution
  of A matters far less: the paper says Gaussian, Hugging Face PEFT defaults to
  Kaiming-uniform, and N(0, 1/r) here is simply a fixed, testable choice.
- Why the update is scaled by alpha / r rather than alpha. The paper's aim is
  that, with Adam, changing r should not force a fresh learning-rate sweep, so
  it fixes alpha and tunes r. Practitioners often set alpha = 2r instead, which
  pins the scaling at 2. rsLoRA (Kalajdzievski, 2023) shows alpha / r shrinks
  the update too much at high rank and argues for alpha / sqrt(r); PEFT
  exposes it as use_rslora.
- The cost model: r(d + k) trainable entries against d*k frozen ones. At
  d = k = 4096 and r = 8 that is under 0.4 percent of the layer. Gradients and
  optimizer state shrink with it. In mixed-precision Adam fine-tuning each
  parameter costs ~16 bytes: 2 for the bf16 weight, 2 for its gradient and 12
  for the fp32 master copy and two moments, so LoRA drops ~14 of those 16 on
  every frozen weight. Activations do not shrink, so long sequences still need
  checkpointing.
- Merging is a deployment decision, not a correctness one. The merged matrix is
  one matmul of the original shape, so inference overhead is zero, but it now
  serves exactly one tenant. Left unmerged you pay two thin matmuls per token
  and buy hot-swapping: one base copy, many adapters batched together.
- Merging into a quantized base is lossy. The base sits on a discrete grid and
  the delta does not, so you dequantize, add, and requantize, and that rounding
  is not the rounding the adapter trained against (QLoRA trains the adapter
  against the quantized base). Keep it unmerged, or merge before quantizing.
Common mistakes: random B, which corrupts the model on step 0; scaling by alpha
alone or dropping the scaling; computing A @ B inside forward; leaving W
trainable; looping request by request in the serving path; expecting merged and
unmerged to agree bit for bit in fp16, or merging to be undone by subtraction.
Follow-ups: DoRA, which splits the update into magnitude and direction; QLoRA
with an NF4 base and higher-precision adapters; which projections to adapt and
how that trades against r; rank scheduling, as in AdaLoRA; stacking several
adapters and the interference that follows; paged adapter memory (S-LoRA) and
segmented gather kernels such as Punica's SGMV for the gathered low-rank matmul
in a real server, the approach behind multi-LoRA serving in vLLM and SGLang.

Write your own version first. The reference solution and its tests are one click away when you are ready.

Next challenge