def grad_sizes(A: torch.Tensor, B: torch.Tensor) -> tuple[float, float]: """A: (r, in), B: (out, r). Returns each one's largest first gradient.""" A, B = A.clone().requires_grad_(), B.clone().requires_grad_() (x @ A.T @ B.T).sum().backward() return A.grad.abs().max().item(), B.grad.abs().max().item()torch.manual_seed(0)rand_A, rand_B = torch.randn(4, 16), torch.randn(12, 4)zero_A, zero_B = torch.zeros(4, 16), torch.zeros(12, 4)starts = [("B zero", rand_A, zero_B), ("A zero", zero_A, rand_B), ("both zero", zero_A, zero_B)]for name, A, B in starts: dA, dB = grad_sizes(A, B) print(f"{name:<10} A gets {dA:5.2f} B gets {dB:5.2f}")
Predict
Three starts: B zero, A zero, or both zero. Which one gives both factors a zero gradient?
Pick one to see what it prints.
That's the first gradient each start gets. The loss here is just the sum of the branch's outputs, which is enough to see who gets a gradient.
Here is that first backward pass, with B at zero:
The first backward pass, with B at zeroInteractive
forward, values backward, gradients
G arrives at h. B's gradient pairs G with u, and u isn't zero while A is random, so B moves on the first step.
In symbols: call the bottleneck u=xA⊤, and G the gradient arriving at the layer's output. The matmul backward rule gives:
∂B∂L=rαG⊤u,∂A∂L=rα(GB)⊤x
B's gradient pairs G with u, and u isn't zero while A is random. A's gradient has to come back through B first, so it is zero while B is zero.
B zero, A random: the first step moves B. From the second step on, both move.
Both zero: both gradients are zero on every step, so the adapter never moves.
In the editor, first_grads(A, B) runs one backward pass on the branch alone, with the loss (x @ A.T @ B.T).sum(). Finish it, so that A.grad and B.grad fill in. Then set stuck: True if both gradients are zero when zero_A and zero_B go in.
Pick an answer above to see the rest
Instructions
1
In first_grads, run the loss backward, so that A.grad and B.grad fill in.
2
Set stuck: True if both factors get a zero gradient when both start at zero.