Compute a DoRA adapted weight

MediumFine-tuningPro

Why it matters DoRA is a drop-in LoRA upgrade in PEFT that often closes the gap to full fine-tuning.

DoRA splits a weight into magnitude and direction, applies LoRA to the direction and learns the magnitude separately.

Write dora_weight(W0, A, B, m, scaling). W0 is (out, in), B is (out, r), A is (r, in), m is (in,) column magnitudes. V = W0 + scaling * B @ A. Return W = m * V / ||V|| where the norm is the L2 norm of each column of V.

Signaturedef dora_weight(W0, A, B, m, scaling)

Example

W0 = [[3], [4]], B and A zero, m = [10] gives [[6], [8]].

Understand the idea

DoRA treats each column of a weight matrix as a length (magnitude) times a direction. LoRA's low-rank update B @ A changes the direction, and a separate learned vector m sets each column's length. Worked example: W0 = [[1, 0], [0, 2]], B = [[1], [0]], A = [[0, 1]], scaling 1, m = [2, 5]. B @ A = [[0, 1], [0, 0]], so V = [[1, 1], [0, 2]]. Column 0 is [1, 0] with norm 1. Column 1 is [1, 2] with norm sqrt(5) = 2.236. New column 0 = 2 * [1, 0] = [2, 0]. New column 1 = 5 * [1, 2] / 2.236 = [2.236, 4.472]. W = [[2, 2.236], [0, 4.472]]. Every column now has exactly the length given by m. Rule: V = W0 + scaling * (B @ A); norms = L2 norm of each column of V (over the out axis, giving shape (in,)); W = m * V / norms, broadcasting over columns. Normalising rows instead is the usual mistake, since m has one entry per input column. Used in: parameter-efficient fine-tuning of LLMs, as an option in PEFT libraries next to LoRA.

Shapes and data flow

B (out, r) @ A (r, in) -> (out, in)
V column norms (1, in)
W = m (1, in) * V / norms
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: exampledora_weight([[3], [4]], np.zeros((1, 1)), np.zeros((2, 1)), [10], 1.0)
  • Sample 2: randomdora_weight(_W, _A, _B, _m, 0.5)