KatInterview

Matrix Cumulative Product with Autodifferentiation

Machine LearningModel answer
HardModel answerMachine Learningautomatic-differentiationbackpropagationmatrix-operations

Last updated

Implement forward and backward passes for cumulative matrix multiplication with correct gradient propagation in an autodiff system.

You have a sequence of $N$ square matrices $A[0], A[1], \ldots, A[N-1]$, each with dimensions $D \times D$. Your goal is to compute the cumulative matrix products:

$$Y[i] = A[0] \cdot A[1] \cdot \ldots \cdot A[i]$$

where $\cdot$ represents standard matrix multiplication. In other words, $Y[0] = A[0]$ and for $i > 0$, we have $Y[i] = Y[i-1] \cdot A[i]$.

Since matrix multiplication is associative but not commutative, the multiplication order must be strictly preserved throughout all computations.

Your task is to build this operation as it would appear in an automatic differentiation framework:

  1. In-place forward pass: Compute all prefix products while overwriting the input array, using only constant auxiliary space. Analyze time and space complexity.

  2. Autodiff incompatibility: Explain why the in-place approach fails when computing gradients in reverse-mode autodiff. What specific values does the backward pass require?

  3. Gradient-safe forward pass: Implement an out-of-place version that preserves all data needed for gradient computation. What must be saved, and what's the space cost?

  4. Backward pass: You receive upstream gradients $G[i] = \partial L / \partial Y[i]$ for every output (where $L$ is a scalar loss). Derive and implement the computation of $\partial L / \partial A[k]$ for all input matrices. Achieve $O(ND^3)$ total time, not $O(N^2D^3)$.

  5. Parallel scan formulation: Given a parallel prefix-scan primitive that accepts an associative binary operator, express both forward and backward passes using this primitive. Address the non-commutative nature of matrix multiplication.

Assumptions:

  • All matrices are dense $D \times D$; one matrix multiplication costs $O(D^3)$ time and produces $O(D^2)$ output
  • $N$ may be large (hundreds to thousands); $D$ is moderate (tens to low hundreds)
  • You receive gradients for all outputs $Y[i]$, not just the final one
  • Use standard reverse-mode autodiff conventions

Hints

Hint 1

For the backward pass, derive the gradient rules using the chain rule with matrix transposes—if C = A·B, then ∂L/∂A involves B^T and ∂L/∂B involves A^T

Hint 2

The in-place forward destroys exactly the values that backward needs: the original factors and previous prefixes

Hint 3

To avoid O(N²D³) backward time, maintain a running 'gradient accumulator' that sweeps right-to-left, similar to how the forward pass swept left-to-right