KatInterview

Gradient Computation Through Consecutive Matrix Multiplications

Machine LearningModel answer
HardModel answerMachine Learningbackpropagationmatrix-calculusgradient-descent

Last 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:

  1. 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.

  2. Verify dimensionality: confirm that $\dfrac{\partial \mathcal{L}}{\partial W_j}$ has the same shape as $W_j$.

  3. 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