17/31
Part 4 of 6 · Merge, unmerge and freezeLearn and do

Fold the scaled update into the weight, once

W′=W+αrBAW' = W + \frac{\alpha}{r} BA

W′W' has the shape of WW, so the merged layer is an ordinary linear layer. It costs exactly what the base did, so merging adds no latency at inference.

To switch tasks, subtract the update to get WW back, then add a different pair's B′A′B'A'. The paper calls that a quick operation with very little memory overhead.

Once merged, forward has to skip the branch

The layer keeps a flag, merged, that says which of the two forms it is in:

MethodWhat it does
merge()adds αrBA\frac{\alpha}{r}BA to base.weight, then sets merged
forward(x)runs the base, and adds the branch only while merged is clear
unmerge()subtracts the same update, then clears merged

Walk one small layer through it, then break it:

One layer, merged and unmergedInteractive
base.weight W
10201-1
branchon: + [-2, 4]
output on x = [1, 2, 3][5, 3]
Unmerged: the frozen W gives [7, -1], and the branch adds (α / r) · x Aᵀ Bᵀ = [-2, 4]. Output [5, 3].

A second merge() or unmerge() in a row does nothing, because each one checks the flag first.

Four details carry it:

  • Merge the scaled update, the same α/r\alpha / r that the forward pass applies.
  • Once merged, skip the branch. The update lives in the weight now.
  • Run both under torch.no_grad().
  • Check the flag first, so a second merge() or unmerge() changes nothing.
Predict

You run merge() without torch.no_grad(). What happens?

Pick an answer above to see the rest