28/31
Part 6 of 6 · What interviewers ask nextLearn and do

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).