Doubt in beginner tutorial regarding chain rule and manual gradient calculation

perceptron: <p>I’m going through <a href="https://pytorch.org/tutorials/beginner/pytorch_with_examples.html#warm-up-numpy" rel="nofollow noopener">this tutorial</a>.<br>
In <strong>Warm-up: numpy</strong> section the derivative of loss function with respect to <code>h</code> is being calculated as follows:</p>
<pre><code class="lang-auto">    grad_h = grad_h_relu.copy()
    grad_h[h &lt; 0] = 0
</code></pre>
<p>But according to chain rule, should not we do something like the following?</p>
<pre><code class="lang-auto">
'''
Derivative of loss function wrt h = derivative of loss function wrt h_relu * 
                                    derivative of h_relu wrt h
'''
def reluGrad(x):
    grad = x.copy()
    grad[x &gt; 0] = 1
    return grad
 
grad_h_relu_wrt_h = reluGrad(h_relu)
grad_h = grad_h_relu.dot(grad_h_relu_wrt_h.T)
</code></pre>
<p>I know something is fishy here because the dimensions of <code>grad_h</code> in the LHS, which must be equal to the dimensions of <code>h</code>, is not going to match with the dimensions of <code>grad_h_relu.dot(grad_h_relu_wrt_h.T)</code> in the RHS (since <code>grad_h_relu</code> and <code>grad_h_relu_wrt_h</code> are of same dimensions we are always going to end up with a square matrix in the RHS) but I am unable to figure out why this is wrong and how the calculation mentioned in the tutorial will lead to correct gradient calculation.</p>
<p>Did I misunderstand the tutorial code?<br>
Could someone please explain this?</p>

AladdinPerzon: <p>If I remember correctly computing the gradient of relu is a bit tricky precisely because of the problem your mentioning here in that the shapes don’t match. Let us say z is what’s computed before relu and let’s say the shape is 1x1000, and h is the result after passing it through relu. What happens when we compute the gradient of h w.r.t z (dh/dz) is that you have (in theory) to form the entire jacobian matrix.</p>
<p>This is because in theory every value from your input (1x1000) could have influenced every value in the resulting (1x1000) vector but of course since relu is applied element wise this is not actually the case. What happens then is that the only values would be along the diagonal of the jacobian and the rest would be zero (so some values of the diagonal would 1 if z &gt; 0 and 0 otherwise) so it wouldn’t even be a diagonal matrix. Forming the jacobian is thus a huge waste of computation, and in the example given here would be a 1000x1000 matrix that we would need to matrix multiply with z. So if we form the jacobian we have 1x1000 mm 1000x1000 and then the shapes would match.</p>
<p>You can simplify this and do as he does in the tutorial by simply element wise multiplying with the diagonal values directly so in our case doing 1x1000 * 1x1000. This is equivalent to also doing grad_h[h &lt; 0] = 0.</p>

albanD: <p>Hey,</p>
<p>I think the confusion comes from what the backward pass computes.<br>
if you function is <code>y = relu(x)</code> and you have a loss L.<br>
Then the backward is computing <code>dL/dx = dL/dy * dy/dx</code>. Where <code>dy/dx</code> is the jacobian of the relu function. But keep in mind that you need to do a matrix product with the gradient flowing back.</p>
<p>The Jacobian of the relu is very close to an identity matrix with 1 on the diagonal for positive inputs and 0 on the diagonal for negative inputs.<br>
So the matrix product here will effectively 0 out the entries in the grad flowing back when the input was negative. And just keep it as is when the input was positive.</p>
<p>In the tutorial code,</p>
<pre><code class="lang-auto">    grad_h = grad_h_relu.copy()
</code></pre>
<p>Is here only to make sure you don’t modify inplace the gradient flowing back inplace (in case it would be used somewhere else.</p>
<pre><code class="lang-auto">    grad_h[h &lt; 0] = 0
</code></pre>
<p>Zero out the entries corresponding to inputs that were negative.<br>
Note that this is single op is the same as doing the matrix product from the chain rule.</p>
<p>In your code sample, <code>grad = x.copy()</code> does not look right. <code>x</code> should be input to the forward pass while <code>grad</code> should be the gradient flowing back (the input of the backward function).</p>

perceptron: <p>Thank you so much for the detailed responses. <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=9" title=":slight_smile:" class="emoji" alt=":slight_smile:"></p>
<p>So, my approach to calculate relu’s gradient was flawed and an alternative but inefficient way of calculating <code>grad_h</code> would be:</p>
<pre><code class="lang-auto">    grad_h = grad_h_relu.copy()
    grad_h = grad_h_relu.dot(Jacobian(h_relu))
</code></pre>
<p>right?<br>
Also, in this example, we are processing a batch of 64 examples together. <code>h</code> is of size <code>[64, 100]</code> and so is <code>h_relu</code>. So how do we calculate the Jacobian of matrices?</p>

albanD: <blockquote>
<p>an alternative but inefficient way of calculating <code>grad_h</code> would be:</p>
</blockquote>
<p>Yes exactly.</p>
<blockquote>
<p>Also, in this example, we are processing a batch of 64 examples together. <code>h</code> is of size <code>[64, 100]</code> and so is <code>h_relu</code> . So how do we calculate the Jacobian of matrices?</p>
</blockquote>
<p>From the autograd point of view, “batch” does not exist, so I usually find it easier to just consider it a function of 2D → 2D.<br>
If you want to reuse the logic above, you need to flatten input/output to make then 1D/1D.<br>
And compute the corresponding Jacobian. Since elements in the batch don’t interact accross batches, then the full Jacobian will be a block diagonal matrix. Where each block is the Jacobian you defined for a single sample.</p>

perceptron: <p>Okay, so we can flatten a matrix to make it a vector and then compute the Jacobian of that but I’m not very sure about how this big Jacobian will fit in this equation:</p>
<pre><code class="lang-auto">grad_h = grad_h_relu.dot(Jacobian(h_relu))
</code></pre>
<p>Here, <code>grad_h</code> and <code>grad_h_relu</code> are of size <code>[64, 100]</code>. Since <code>h_relu</code> is of size <code>[64, 100]</code> and relu is a pointwise operation, after flattening we will get a vector of size <code>6400</code> whose Jacobian would be a square matrix of size <code>[6400, 6400]</code>.<br>
This representation of combined Jacobians of all the samples can not be multiplied with <code>grad_h_relu</code> directly. So, I am not sure how the two matrices on the LHS would be multiplied.<br>
One thing I can think of is, flatten the <code>grad_h_relu</code> to make it a vector of size <code>6400</code> then multiply with the Jacobian which is of size <code>[6400, 6400]</code> so we will get a vector of size <code>6400</code> which we will unflatten to make it of size <code>[64, 100]</code>. Is this the way we do it?</p>
<p>I don’t know if this forum is the right to place to discuss this or not as this discussion is not relevant to PyTorch specifically, and I apologize for bringing it up here if this is not. The doubt came while going through one of the PyTorch tutorials mentioned in the site and I thought many people using this forum would have gone through the tutorial, so thought of asking it here <img src="https://discuss.pytorch.org/images/emoji/apple/thinking.png?v=9" title=":thinking:" class="emoji" alt=":thinking:"></p>

albanD: <p>Since you now consider a 1D → 1D function. You need to make sure to view your inputs the right way before/after the formula.<br>
And so her you want to flatten <code>grad_h_relu</code> before the dot product and make sure to view the 1D result as the 2D Tensor you want.</p>
<blockquote>
<p>I don’t know if this forum is the right to place to discuss this or not</p>
</blockquote>
<p>It definitely is <img src="https://discuss.pytorch.org/images/emoji/apple/smiley.png?v=12" title=":smiley:" class="emoji" alt=":smiley:" loading="lazy" width="20" height="20"></p>