Gradient Computation Through Consecutive Matrix Multiplications
Machine LearningModel answerLast updated
Derive gradients for each weight matrix in a chain of matrix products using the chain rule and implement an efficient backward pass.
You are implementing a neural network layer that consists of a sequence of trainable weight matrices multiplied together, with no activation functions between them. The layer performs pure linear transformations through successive matrix products.
Given trainable parameters $W_1, W_2, \ldots, W_n$, the layer computes:
$$ P = W_1 W_2 \cdots W_n $$
For input data $X$, the forward computation produces:
$$ Y = P,X = W_1 W_2 \cdots W_n, X $$
During training, you receive the upstream gradient from the loss function:
$$ \Delta = \frac{\partial \mathcal{L}}{\partial Y} $$
where $\Delta$ has the same dimensions as $Y$.
Your task is to derive and implement the backward pass:
-
Derive the gradient $\dfrac{\partial \mathcal{L}}{\partial W_j}$ for each individual weight matrix $W_j$, where $1 \le j \le n$. Show the derivation using matrix calculus or the chain rule, explaining why the gradient takes its particular form.
-
Verify dimensionality: confirm that $\dfrac{\partial \mathcal{L}}{\partial W_j}$ has the same shape as $W_j$.
-
Design an efficient algorithm: describe how to compute all $n$ gradients without redundant matrix multiplications. The algorithm should run in $O(n)$ matrix products, not $O(n^2)$.
Dimensions and Setup
- Each $W_j \in \mathbb{R}^{m_{j-1} \times m_j}$, so consecutive multiplications are well-defined
- The composite $P \in \mathbb{R}^{m_0 \times m_n}$
- For batched input, $X \in \mathbb{R}^{m_n \times B}$ and $Y, \Delta \in \mathbb{R}^{m_0 \times B}$
- Matrices can be rectangular; only adjacent inner dimensions must match
- No activation functions or biases exist within this layer
- The loss may sum or average over the batch dimension
What to Address
- How do you isolate a single $W_j$ within the product chain?
- What role do the "left context" and "right context" matrices play?
- How do you ensure correct transpose operations and matrix ordering?
- How do you avoid recomputing the same intermediate products for different $j$?
- How does the batch dimension get handled correctly?
Hints
Hint 1
Separate the product into three parts: everything before W_j, the matrix W_j itself, and everything after W_j
Hint 2
Use the matrix differential identity: d(AB) = (dA)B + A(dB) and the trace trick to extract gradients
Hint 3
Compute left-to-right and right-to-left accumulated products in two separate passes to reuse intermediate results
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Derivation
Isolating Individual Matrices
To find $\frac{\partial \mathcal{L}}{\partial W_j}$, decompose the product by separating $W_j$ from its neighbors:
$$ P = W_1 \cdots W_{j-1} \cdot W_j \cdot W_{j+1} \cdots W_n $$
Define:
- Left prefix: $L_j = W_1 W_2 \cdots W_{j-1}$ (identity if $j=1$)
- Right suffix: $R_j = W_{j+1} W_{j+2} \cdots W_n$ (identity if $j=n$)
Then $P = L_j W_j R_j$ and $Y = L_j W_j R_j X$.
Applying the Chain Rule
Using the matrix differential approach, the change in loss due to a small perturbation $dW_j$ is:
$$ d\mathcal{L} = \text{tr}\left(\Delta^T dY\right) $$
Since $Y = L_j W_j R_j X$, we have:
$$ dY = L_j (dW_j) R_j X $$
Substituting:
$$ d\mathcal{L} = \text{tr}\left(\Delta^T L_j (dW_j) R_j X\right) $$
Using the cyclic property of trace, $\text{tr}(ABCD) = \text{tr}(DABC)$:
$$ d\mathcal{L} = \text{tr}\left((R_j X \Delta^T L_j)^T dW_j\right) $$
By the definition of matrix gradient, this means:
$$ \frac{\partial \mathcal{L}}{\partial W_j} = L_j^T \Delta X^T R_j^T $$
Dimensionality Check
- $L_j \in \mathbb{R}^{m_0 \times m_{j-1}}$, so $L_j^T \in \mathbb{R}^{m_{j-1} \times m_0}$
- $\Delta \in \mathbb{R}^{m_0 \times B}$
- $X \in \mathbb{R}^{m_n \times B}$, so $X^T \in \mathbb{R}^{B \times m_n}$
- $R_j \in \mathbb{R}^{m_j \times m_n}$, so $R_j^T \in \mathbb{R}^{m_n \times m_j}$
Computing the product dimensions:
$$ L_j^T \Delta X^T R_j^T: \quad m_{j-1} \times m_0 \cdot m_0 \times B \cdot B \times m_n \cdot m_n \times m_j = m_{j-1} \times m_j $$
This matches $W_j \in \mathbb{R}^{m_{j-1} \times m_j}$ exactly. The batch dimension $B$ is contracted through the middle multiplications.
Efficient Implementation
Naive Approach (Inefficient)
Computing $L_j$ and $R_j$ separately for each $j$ would require $O(n^2)$ matrix products total, since you'd recompute overlapping prefix and suffix products.
Optimized Two-Pass Algorithm
Forward accumulation (left-to-right):
L = [I] # L[0] = identity
for j in range(1, n+1):
L[j] = L[j-1] @ W[j]
Backward accumulation (right-to-left):
R = [I] # R[n] = identity
for j in range(n-1, 0, -1):
R[j] = W[j+1] @ R[j+1]
Gradient computation:
for j in range(1, n+1):
dW[j] = L[j-1].T @ Delta @ X.T @ R[j].T
This performs exactly $2n$ matrix products for prefix/suffix accumulation, plus $n$ gradient computations, achieving $O(n)$ complexity.
Practical Considerations
Batch averaging: If the loss averages over the batch (common in training), divide each gradient by $B$:
$$ \frac{\partial \mathcal{L}}{\partial W_j} = \frac{1}{B} L_j^T \Delta X^T R_j^T $$
Memory efficiency: When $B$ is small relative to the hidden dimensions, computing $\Delta X^T$ first (shape $m_0 \times m_n$) can be more cache-efficient than materializing large prefix matrices.
Connection to autodiff: Standard reverse-mode automatic differentiation naturally implements this by maintaining a gradient accumulator flowing backward through the computation graph, which is exactly the right-suffix accumulation.
Common mistakes:
- Forgetting transpose operations on $L_j$ and $R_j$
- Incorrect matrix multiplication order (non-commutative)
- Computing $L_j$ and $R_j$ from scratch for each $j$ instead of accumulating
- Not contracting the batch dimension properly
Time Complexity
- Forward pass: $O(n)$ matrix multiplications
- Backward pass: $O(n)$ matrix multiplications (prefix sweep + suffix sweep + gradient assembly)
- Total: $O(n)$ end-to-end, assuming each matrix product costs $O(d^3)$ for typical dimension $d$