506. LoRA forward pass and weight merge
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).
def lora_forward(x, W, A, B, alpha)Example 1
Input: lora_forward(np.array([[1.0, 1.0]]), np.array([[1.0, 0.0]]), np.array([[1.0, 0.0]]), np.array([[0.5]]), 2.0)
Output: ([[2.0]], [[2.0, 0.0]])
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
r = A.shape[0].
Hint 2
Compute the scale once and use it in both places.
Common mistakes
- A.T @ B.T is its transpose
(d_in, d_out), which is the bug in the buggy version and only works by accident for square shapes.
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.
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.
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.
Topics
Companies1
- Netflix the topic appears in interview reports Netflix Machine Learning Engineer Interview Process
From public interview reports and guides. Not affiliated with or endorsed by these companies.