requires_grad=True for two variables

Abueidda: <p>Hi all,</p>
<p>I have a model that has multiple inputs, and I was wondering if it is possible to find the gradients of the output with respect to the inputs.</p>
<p>The layout is as follows:</p>
<p>output = f(inp1, inp2, …)</p>
<p>To do so, we minimize the loss: Solve MSE optimization problem loss ||output-target||</p>
<p>Then after the model is trained I am interested in finding the sensitivities:<br>
d(output)/d(inp1), d(output)/d(inp2), …</p>
<p>I believe it is doable, but I am not sure how. Any help/hint is appreciated.</p>

albanD: <p>Hi,</p>
<p>First, make sure your inputs require gradients:</p>
<ul>
<li>If they don’t, just call <code>requires_grad_()</code> on them before giving them to your net</li>
<li>If they do and are leaf (inp1.is_leaf()) then you’re good to go</li>
<li>If they do but are not leafs, you can do <code>inp1.retain_grad()</code> to make sure the .grad field will be populated properly.</li>
</ul>
<p>Then if output is a scalar, you can simply <code>.backward()</code> on the output.<br>
Otherwise, if you want the full jacobian, you can use the <code>torch.autograd.functional</code> package from pytorch 1.5.<br>
If you want the sum of the gradients for each element in the output, you can do <code>output.sum().backward()</code>.</p>

Abueidda: <p>Hi albanD,</p>
<p>Many thanks for the response. May you elaborate on what you mean by leaf? I will try to do it along the lines you suggested and come back to you, Thanks again</p>

albanD: <p>A leaf Tensor is a Tensor that does not have history. You can check it with <code>your_tensor.is_leaf()</code>.<br>
When calling <code>.backward()</code>, it will populate the .grad field of all the leaf Tensors that require gradients that were use in the computation of the output.</p>

Abueidda: <p>Thanks again for the explanation</p>
<p>I have the following after output.backward() statement</p>
<p>inpt2_grad = grad(output, inp2, torch.ones(inp2.size()[0], 1, device=dev), create_graph=True, retain_graph=True)</p>
<p>inpt2_grad       = inpt2_grad.cpu().numpy()</p>
<p>I get the following error at the line where I have: inpt2_grad = grad(output, inp2, torch…<br>
Mismatch in shape: grad_output[0] has a shape of torch.Size([15625, 1]) and output[0] has a shape of torch.Size([]).</p>

Abueidda: <p>Also,</p>
<p>If I do the following<br>
inp2_grad = inp2.grad<br>
print(inp2_grad)<br>
inp2_grad       = inp2_grad.detach().cpu().numpy()</p>
<p>I get None when I print inp2_grad<br>
Also, I cannot make it a numpy array</p>

albanD: <p>Hi,</p>
<p>The issue here is that the grad_output should be of the same size as the output. In this case, the output is a scalar so you can actually leave the grad_output field empty to get a Tensor containing a single 1.</p>
<p>Autograd.grad does not populate the .grad field of the Tensor, it returns the gradients directly and you should get it the same way you do in your post above. Note that it returns a tuple though so you might need to do <code>inpt2_grad, = xxx</code>.</p>

Abueidda: <p>Thanks, albanD.</p>
<p>I did the following:<br>
inpt2_grad = grad(output, inpt2, create_graph=True, retain_graph=True)</p>
<p>But now I am encountering a new issue:<br>
One of the differentiated Tensors appears to not have been used in the graph. Set allow_unused=True if this is the desired behavior.</p>
<p>Any insights of what allow_unused does? I tried to read the documentation, but I got lost.</p>
<p>Also, if I add the allow_unused=True statement, grad(output,…) returns None.</p>

albanD: <p>This error means that pytorch cannot find any link between output and inpt2. Meaning that output was not computed in a differentiable way based on inpt2.<br>
So you want to double check your code to make sure that output does depend on input2 (or if it does not, you can remove this call and replace it by a Tensor full of 0s).</p>

Abueidda: <p>Thanks. I see.</p>
<p>So let me layout the code, and you might be able to tell me if there is something wrong:</p>
<p>class Grad_finder:</p>
<pre><code>def fun1(x1, x2, x3): 

    x1.requires_grad_(True)
    x1.retain_grad()
    x2.requires_grad_(True)
    x2.retain_grad()
    

    
    '''
    we minimize the loss
    '''
    for i in range(epochs):
        L1 = f(x1, x3) # f is a neural network model
        L2 = g(L1, x2) # g is a defined function
        L3 = h(x1, x3) # h is a defined function
    
        loss = L2 - L3
        optimizer.zero_grad()
        loss.backward(retain_graph=True)
        optimzer.step()
    
    # now f is trained 
    L1 = f(x1, x3)
    L2 = g(L1, x2)
    
    return L2
    
def fun2(x1, x2, x3): 

    x1.requires_grad_(True)
    x1.retain_grad()
    x2.requires_grad_(True)
    x2.retain_grad()
    
    L2 = fun1(x1, x2, x3)
    
    '''
    Here i want to find :
    dL2/dx2
    '''
    
    return dL2dx2
</code></pre>
<p>dL2dx2 = Grad_finder.fun2(x1, x2, x3)<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/a/1/a1f7b63319d19cd5ba7fb9f1469e7a3dd5381c1e.png" data-download-href="https://discuss.pytorch.org/uploads/default/a1f7b63319d19cd5ba7fb9f1469e7a3dd5381c1e" title="Capture"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/a/1/a1f7b63319d19cd5ba7fb9f1469e7a3dd5381c1e_2_316x500.png" alt="Capture" data-base62-sha1="n6PAK8O9GzwYfqyqBVbvcmvCS3c" width="316" height="500" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/a/1/a1f7b63319d19cd5ba7fb9f1469e7a3dd5381c1e_2_316x500.png, https://discuss.pytorch.org/uploads/default/optimized/3X/a/1/a1f7b63319d19cd5ba7fb9f1469e7a3dd5381c1e_2_474x750.png 1.5x, https://discuss.pytorch.org/uploads/default/original/3X/a/1/a1f7b63319d19cd5ba7fb9f1469e7a3dd5381c1e.png 2x" data-dominant-color="F9F9FA"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">Capture</span><span class="informations">539×851 76.1 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>

albanD: <p>Ok, so the only potentially differentiable link I can see between L2 and x2 is <code>L2 = g(L1, x2)</code>.<br>
So what is <code>g</code> here?</p>

Abueidda: <p>I think this is what I am missing: the relationship between L2 and x2. They are implicitly related. I have to revisit the problem and see how I can proceed. Many thanks, albanD.</p>