Lesson 8 (2019) discussion & wiki

Yeah, I get these mixed up too—I always have to go back and rederive things with explicit indices in the chain rule and then see if I can spot the matrix multiplications afterwards. Is there an easier way? I guess just memorize some matrix derivative identities? Probably time to work through the matrix calculus post :slight_smile:

As an example, for calculating the derivative of the loss with respect to weight W_{ij} from a linear layer y_{nj} = \sum_i x_{ni} W_{ij} + b_j (here n is the batch index), I’d have to do the following: W_{ij} affects the loss via y_{nj} for every n in the batch (but not via any of the other activations for some index other than j), so if we already know all those upstream derivatives \partial \mathcal{L}/\partial y_{nj} (aka out.g), then the chain rule gives

\frac{\partial \mathcal{L}}{\partial W_{ij}} = \sum_n \frac{\partial \mathcal{L}}{\partial y_{nj}} \frac{\partial y_{nj}}{\partial W_{ij}}

Here \partial y_{nj}/ \partial W_{ij} = x_{ni}, so

\frac{\partial \mathcal{L}}{\partial W_{ij}} = \sum_n \frac{\partial \mathcal{L}}{\partial y_{nj}} x_{ni}

and yeah, if I squint I can write that as a matrix multiplication as x.t() @ out.g.

I actually kind of like all the explicit indices (otherwise I tend to forget things like the batch index), and I think it makes the chain rule a little easier to feel than with the matrix notation, but it’s definitely a little tedious…

5 Likes