Backward pass of a LoRA layer with adapter dropout

In LoRA the frozen weight W gets a low-rank update: y = x W^T + s * dropout(x) A^T B^T with s = alpha / r. Only A and B train, but you still need the gradient with respect to x to keep backpropagating into earlier layers. Deriving these by hand is a good check that you understand where the scale and the dropout enter.

Write lora_backward(x, W, A, B, alpha, dY, mask, p). Shapes: x (n, d_in), W (d_out, d_in), A (r, d_in), B (d_out, r), dY (n, d_out) is the upstream gradient dL/dy, mask (n, d_in) is the 0/1 dropout mask used in the forward pass, p is the dropout rate (inverted dropout, so kept values are divided by 1 - p). r = A.shape[0].
Forward: xd = x * mask / (1 - p), h = xd @ A.T, y = x @ W.T + s * h @ B.T.
Return (dA, dB, dx) with shapes (r, d_in), (d_out, r), (n, d_in). W is frozen, so no dW.
Check: when B is all zeros (the usual init), dA is all zeros.

Signaturedef lora_backward(x, W, A, B, alpha, dY, mask, p)

Understand the idea

LoRA adds a small trainable path next to a frozen weight: y = x W^T + s * dropout(x) A^T B^T, with s = alpha / r. Only A and B learn, but dx is still needed; the adapter saw dropout(x), not x. Scalar example: x = 1, W = 2, A = 3, B = 0.5, s = alpha / r = 2, p = 0.5, mask = 1, so xd = 2. Forward: h = 2 * 3 = 6, y = 2 + 2 * 6 * 0.5 = 8. With dY = 1: dB = s * dY * h = 12. dh = s * dY * B = 1. dA = dh * xd = 2. dx = dY * W + (dh * A) * mask / (1 - p) = 2 + 3 * 2 = 8. Rule in matrix form: dh = s * dY B; dB = s * dY^T h; dA = dh^T xd; dx = dY W + (dh A) * mask / (1 - p). With B = 0, dA is zero. LoRA is the standard cheap way to fine-tune LLMs.

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

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

  • Sample 1: dropout 0.25lora_backward(_x, _W, _A, _B, 16, _dY, _m, 0.25)
  • Sample 2: no dropoutlora_backward(_x, _W, _A, _B, 8, _dY, _one, 0.0)