LoRA forward pass and weight merge

MediumFine-tuningPro

LoRA's forward pass adds a low-rank update scaled by alpha / r:

y = x @ W.T + (alpha / r) * (x @ A.T) @ B.T

For deployment you can merge it into one matrix: W_merged = W + (alpha / r) * B @ A, and then y = x @ W_merged.T with no extra cost.

Write lora_forward(x, W, A, B, alpha) returning (y, W_merged). W is (d_out, d_in), A is (r, d_in), B is (d_out, r), x is (n, d_in).

Signaturedef lora_forward(x, W, A, B, alpha)

Understand the idea

LoRA adds a low-rank correction to a frozen weight. In the forward pass the input goes through the frozen W and, in parallel, through A then B, and the second path is scaled by alpha / r. For deployment you can fold the correction into one matrix, W_merged = W + (alpha / r) B A, which gives identical outputs with no extra cost. Worked example: W = [[1, 1]] (d_out 1, d_in 2), A = [[1, 0]] (r = 1), B = [[2]], alpha = 2, so scale = 2. Input x = [[3, 4]]. Base path: 3 + 4 = 7. LoRA path: x A^T = 3, times B^T = 6, times scale = 12. y = 19. Merged: B A = [[2, 0]], so W_merged = [[1, 1]] + 2 x [[2, 0]] = [[5, 1]], and x W_merged^T = 15 + 4 = 19, the same. Rule: y = x W^T + (alpha / r)(x A^T) B^T; W_merged has W's shape (d_out, d_in), so use B @ A, not A^T @ B^T. LoRA fine-tunes are often merged before serving.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: outputlora_forward(_x, _W, _A, _B, 16)[0]
  • Sample 2: merged weightlora_forward(_x, _W, _A, _B, 16)[1]