Matrix Cumulative Product with Autodifferentiation
Machine LearningModel answerLast 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:
-
In-place forward pass: Compute all prefix products while overwriting the input array, using only constant auxiliary space. Analyze time and space complexity.
-
Autodiff incompatibility: Explain why the in-place approach fails when computing gradients in reverse-mode autodiff. What specific values does the backward pass require?
-
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?
-
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)$.
-
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
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: In-Place Forward Pass
Implementation:
def cumulative_matmul_inplace(A):
"""
A: list/array of N matrices, each D×D
Overwrites A so A[i] becomes Y[i] = A[0]·...·A[i]
"""
for i in range(1, len(A)):
A[i] = A[i-1] @ A[i] # Y[i] = Y[i-1] · A[i]
# A[0] unchanged: Y[0] = A[0]
Complexity:
- Time: $O(ND^3)$ — we perform $N-1$ matrix multiplications, each costing $O(D^3)$
- Space: $O(1)$ auxiliary space beyond the input/output array (which is $O(ND^2)$ but provided). We use no extra storage proportional to $N$ or $D$.
This sequential sweep correctly computes all cumulative products by leveraging the recurrence $Y[i] = Y[i-1] \cdot A[i]$. However, it destroys the original input matrices—a critical issue for gradient computation.
Part 2: Why In-Place Breaks Autodiff
The backward pass for matrix multiplication requires access to both operands of each multiplication:
For $C = A \cdot B$, the gradient rules are:
- $\frac{\partial L}{\partial A} = \frac{\partial L}{\partial C} \cdot B^T$
- $\frac{\partial L}{\partial B} = A^T \cdot \frac{\partial L}{\partial C}$
In our cumulative product, computing $Y[i] = Y[i-1] \cdot A[i]$ means the backward pass needs:
- The original factor $A[i]$
- The previous prefix $Y[i-1]$
The in-place sweep overwrites both: slot $i$ originally held $A[i]$, but after iteration $i$ it holds $Y[i]$, destroying $A[i]$. By iteration $i+1$, we've also overwritten $Y[i-1]$ with $Y[i+1]$.
Autodiff engine mechanism: Modern frameworks track tensor versions. When you call tensor.backward(), the engine checks that saved tensors haven't been modified since the forward pass. If they have:
- Loud failure: PyTorch raises
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation - Silent failure: If checks are bypassed, you compute gradients using corrupted values, producing incorrect results with no warning
Part 3: Out-of-Place Forward Pass
Implementation:
def cumulative_matmul_safe(A):
"""
A: list of N matrices (D×D), left unchanged
Returns Y: list of N cumulative products
"""
N = len(A)
Y = [None] * N
Y[0] = A[0].copy() # or just A[0] if no mutation risk
for i in range(1, N):
Y[i] = Y[i-1] @ A[i]
return Y
What to save for backward:
- All original factors $A[0], \ldots, A[N-1]$
- All prefix products $Y[0], \ldots, Y[N-1]$ (or equivalently, the exclusive prefixes $Y[-1]=I, Y[0], \ldots, Y[N-2]$)
Complexity:
- Time: Still $O(ND^3)$ — same number of multiplications
- Space: $O(ND^2)$ auxiliary storage to hold the separate output array $Y$, plus the input $A$ remains intact
This is the standard trade-off in autodiff: we double the memory footprint to preserve gradient information.
Part 4: Backward Pass
Gradient rules: For $C = A \cdot B$, using the Frobenius inner product: $$\frac{\partial L}{\partial A} = \frac{\partial L}{\partial C} \cdot B^T, \quad \frac{\partial L}{\partial B} = A^T \cdot \frac{\partial L}{\partial C}$$
Naive approach (too slow): Each $A[k]$ contributes to all $Y[i]$ where $i \geq k$. Summing contributions: $$\frac{\partial L}{\partial A[k]} = \sum_{i=k}^{N-1} Y[k-1]^T \cdot G[i] \cdot (\text{suffix product } A[k+1] \cdots A[i])^T$$
This requires computing suffix products, leading to $O(N^2D^3)$ time.
Efficient approach: Maintain a running gradient accumulator $\bar{Y}[i]$ sweeping right-to-left:
def backward_pass(A, Y, G):
"""
A: original factors (N matrices, D×D)
Y: forward outputs (N matrices, D×D)
G: upstream gradients ∂L/∂Y[i] for all i
Returns: gradA[k] = ∂L/∂A[k] for all k
"""
N = len(A)
gradA = [None] * N
# Running accumulator: gradient flowing backward through prefixes
grad_accum = G[N-1].copy() # Start from the last output
# Sweep right-to-left
for k in range(N-1, -1, -1):
# Gradient w.r.t. A[k]: use Y[k-1] (or I if k=0)
Y_prev = Y[k-1] if k > 0 else np.eye(A[0].shape[0])
gradA[k] = Y_prev.T @ grad_accum @ A[k].T
# Accumulate gradient for next iteration (earlier positions)
if k > 0:
grad_accum = grad_accum @ A[k].T + G[k-1]
return gradA
Wait, let me reconsider. The correct formulation:
For $Y[i] = Y[i-1] \cdot A[i]$:
- $\frac{\partial L}{\partial Y[i-1]} += G[i] \cdot A[i]^T$
- $\frac{\partial L}{\partial A[i]} = Y[i-1]^T \cdot G[i]$
Corrected backward:
def backward_pass(A, Y, G):
N = len(A)
D = A[0].shape[0]
gradA = [None] * N
# Accumulate gradients flowing to prefixes
grad_Y = G[N-1].copy()
for i in range(N-1, 0, -1):
gradA[i] = Y[i-1].T @ grad_Y
grad_Y = grad_Y @ A[i].T + G[i-1]
# Base case: Y[-1] = I
gradA[0] = grad_Y
return gradA
Complexity: $O(ND^3)$ time — one backward sweep with $N-1$ transposed multiplications. Space is $O(D^2)$ for the accumulator.
Part 5: Scan Formulation
Forward with scan: Matrix multiplication is associative: $(A \cdot B) \cdot C = A \cdot (B \cdot C)$. We can use an inclusive scan with the matmul operator:
Y = inclusive_scan(A, operator=matmul)
Work/depth: Hillis-Steele scan performs $O(N \log N)$ matrix multiplications with $O(\log N)$ parallel depth, versus the sequential $O(N)$ work. This trades higher total work for lower latency on parallel hardware.
Backward with scan: The backward pass can be viewed as applying the adjoint operator. Define the "backward operator" for pairs $(G_i, A_i)$: $$(G, A) \oplus_{\text{back}} (G', A') = (G \cdot A'^T + G', A)$$
However, this is more naturally expressed as a right-to-left exclusive scan or by recognizing that we're computing a suffix of adjoint compositions.
Alternative formulation: The gradient flow can be written as: $$\frac{\partial L}{\partial A[k]} = \left(\sum_{i=k}^{N-1} G[i] \cdot \text{suffix}[k+1:i]\right) \cdot Y[k-1]^T$$
where suffix products flow right-to-left. This is a reversed scan with transposed products and gradient accumulation. The key insight: the backward scan mirrors the forward scan's structure but runs in reverse with transposed operators.
Common mistakes:
- Forgetting that matmul is non-commutative; must maintain strict left-to-right order in forward, right-to-left in backward
- Attempting $O(N^2D^3)$ backward by recomputing suffix products per gradient
- Numerical instability in long products: consider log-domain computation or orthogonal decompositions for stability
- Edge case $N=1$: gradient is simply $G[0]$ with identity as the "previous prefix"