Merge several LoRA adapters into one weight with weights

MediumFine-tuningPro

Why it matters Adapter merging lets one deployment combine a style adapter with a domain adapter without extra inference cost.

You can combine skills by adding several LoRA updates into one base weight, each with its own strength. The products must be added, not the factors.

Write merge_adapters(W, adapters, weights). W is (d_out, d_in). adapters is a list of (A, B, scale) with A (r_i, d_in), B (d_out, r_i); ranks may differ. weights is a list of floats of the same length. Return W + sum_i weights[i] * scale_i * B_i @ A_i. With no adapters return W as a float array.

Signaturedef merge_adapters(W, adapters, weights)

Example

W = [[0, 0], [0, 0]], adapters = [([[1, 0]], [[1], [0]], 1.0), ([[0, 1]], [[0], [1]], 2.0)], weights = [0.5, 1.0] gives [[0.5, 0], [0, 2]].

Understand the idea

Each LoRA adapter is a low-rank update B A that you add to a weight. Two adapters can be combined by adding both updates, with knobs for how strong each one is, like mixing two paint colours by adding measured amounts of each.

Example: adapter 1 updates [[1, 0], [0, 0]] with scale 1, adapter 2 updates [[0, 0], [0, 1]] with scale 2. With user weights 0.5 and 1.0 the merged weight change is 0.5 * [[1, 0], [0, 0]] + 2 * [[0, 0], [0, 1]] = [[0.5, 0], [0, 2]].

Rule: W' = W + sum_i w_i * s_i * B_i A_i.

A tempting shortcut is to average the A matrices and the B matrices and multiply once. That is wrong: (B_1 + B_2)(A_1 + A_2) contains cross terms B_1 A_2 that neither adapter learned. Adapter-merging tools add the products, then may apply extra steps such as pruning or sign resolution.

Shapes and data flow

W (d_out, d_in); each B_i (d_out, r_i) @ A_i (r_i, d_in) -> (d_out, d_in)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplemerge_adapters([[0, 0], [0, 0]], [([[1, 0]], [[1], [0]], 1.0), ([[0, 1]], [[0], [1]], 2.0)], [0.5, 1.0])
  • Sample 2: mixed ranksmerge_adapters(Wm, [(Am1, Bm1, 0.5), (Am2, Bm2, 2.0)], [1.0, 0.3])