Swap one merged LoRA adapter for another

Why it matters Multi-tenant serving and quick task switching rely on merging and unmerging adapters in place.

A merged LoRA adapter is baked into the weight. To switch tasks without reloading the base model, unmerge the old adapter and merge the new one.

Write swap_adapter(W_merged, A_old, B_old, A_new, B_new, scale). W_merged is (d_out, d_in) and equals W_base + scale * B_old @ A_old. A matrices are (r, d_in), B matrices are (d_out, r). Return (W_base, W_new) where W_new = W_base + scale * B_new @ A_new.

Signaturedef swap_adapter(W_merged, A_old, B_old, A_new, B_new, scale)

Example

W_merged = [[3, 2], [0, 1]], A_old = [[1, 0]], B_old = [[1], [0]], A_new = [[0, 1]], B_new = [[0], [1]], scale = 2 gives W_base = [[1, 2], [0, 1]] and W_new = [[1, 2], [0, 3]].

Understand the idea

LoRA learns a small update B @ A instead of a full weight change. For fast inference you can merge it into the weight once: W = W_base + scale * B A. Because addition is reversible, you can also take it back out, like removing a sticker you placed on a page.

Example: W_base = [[1, 2], [0, 1]], old adapter B A = [[1, 0], [0, 0]] with scale 2. Merged weight = [[3, 2], [0, 1]]. To switch, subtract 2 * [[1, 0], [0, 0]] to get W_base back, then add the new adapter 2 * [[0, 0], [0, 1]] to get [[1, 2], [0, 3]].

Rule: W_base = W_merged - s * B_old A_old; W_new = W_base + s * B_new A_new, with s = alpha / r.

In float16 the round trip is not perfectly exact, so long-running servers often keep a clean copy of the base weight or apply adapters unmerged instead.

Shapes and data flow

W (d_out, d_in); B (d_out, r) @ A (r, d_in) -> (d_out, d_in)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleswap_adapter([[3, 2], [0, 1]], [[1, 0]], [[1], [0]], [[0, 1]], [[0], [1]], 2)
  • Sample 2: random rank 2swap_adapter(WM, A1, B1, A2, B2, 0.5)
  • Test 3: same adapter round tripnp.allclose(swap_adapter(WM, A1, B1, A1, B1, 0.5)[1], WM)