How to create output equivalent to tf.gradients()?

malbergo: <p>I am trying to implement a loss function in Pytorch which requires me to get the gradient of the logit of a discriminator of a GAN as such: <div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/5/5b373c4a45846f6957270fb3482c37d5ce810654.jpg" data-download-href="https://discuss.pytorch.org/uploads/default/5b373c4a45846f6957270fb3482c37d5ce810654" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/2X/5/5b373c4a45846f6957270fb3482c37d5ce810654_2_690x63.jpg" alt="image" data-base62-sha1="d0VN3URlxgOJaEq3tsxRIpZyi3O" width="690" height="63" srcset="https://discuss.pytorch.org/uploads/default/optimized/2X/5/5b373c4a45846f6957270fb3482c37d5ce810654_2_690x63.jpg, https://discuss.pytorch.org/uploads/default/original/2X/5/5b373c4a45846f6957270fb3482c37d5ce810654.jpg 1.5x, https://discuss.pytorch.org/uploads/default/original/2X/5/5b373c4a45846f6957270fb3482c37d5ce810654.jpg 2x" data-dominant-color="E7E7E7"><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">image</span><span class="informations">779×72 12.4 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>
<p>There is an implementation of this in tensorflow already which uses the tf.gradients function:</p>
<pre><code class="lang-auto">   # -----------------------------------------------------------------------------------
    #     JS-Regularizer
    # -----------------------------------------------------------------------------------
    def Discriminator_Regularizer(D1_logits, D1_arg, D2_logits, D2_arg):
        with tf.name_scope('disc_reg'):
            D1 = tf.nn.sigmoid(D1_logits)
            D2 = tf.nn.sigmoid(D2_logits)
            grad_D1_logits = tf.gradients(D1_logits, D1_arg)[0]
            grad_D2_logits = tf.gradients(D2_logits, D2_arg)[0]
            grad_D1_logits_norm = tf.norm( tf.reshape(grad_D1_logits, [BATCH_SIZE//len(DEVICES),-1]) , axis=1)
            grad_D2_logits_norm = tf.norm( tf.reshape(grad_D2_logits, [BATCH_SIZE//len(DEVICES),-1]) , axis=1)
            
            #set keep_dims=True/False such that grad_D_logits_norm.shape == D.shape
            print('grad_D1_logits_norm.shape {} != D1.shape {}'.format(grad_D1_logits_norm.shape, D1.shape))
            print('grad_D2_logits_norm.shape {} != D2.shape {}'.format(grad_D2_logits_norm.shape, D2.shape))
            assert grad_D1_logits_norm.shape == D1.shape
            assert grad_D2_logits_norm.shape == D2.shape
            
            reg_D1 = tf.multiply(tf.square(1.0-D1), tf.square(grad_D1_logits_norm))
            reg_D2 = tf.multiply(tf.square(D2), tf.square(grad_D2_logits_norm))
            
            disc_regularizer = tf.reduce_mean(reg_D1 + reg_D2)
            
     return disc_regularizer
</code></pre>
<p>Does anyone know how to do the equivalent using autograd? Is this functionality possible in pytorch? It would be greatly appreciated.</p>
<p>My understanding is that tf.gradients(ys,xs) makes the symbolic derivatives of the sum of ys wrt to x. How is this different from autograd.grad()?</p>
<p>Michael</p>

richard: <p>I think you’re looking for <a href="http://pytorch.org/docs/master/autograd.html?highlight=autograd%20grad#torch.autograd.grad"><code>autograd.grad</code></a>. It computes the gradients of output wrt some inputs.</p>

malbergo: <p>Hi Richard,</p>
<p>Thanks for your response. Yes I figured this would be the implementation choice, but when I do try to use it, I am told:</p>
<blockquote>
<p>RuntimeError: grad can be implicitly created only for scalar outputs</p>
</blockquote>
<p>Whereas the version in tf works fine. Do you know what this error might be suggesting?</p>
<p>The shape of the (outputs, wrt inputs)  is ([512,1], [512,3]). They are both variables. Is this the issue?</p>

richard: <p>To compute gradients (which implies that the output of the function is scalar),</p>
<p>The outputs you pass to autograd.grad should be either of the following:</p>
<ul>
<li>A Variable wrapping a Tensor of size (1,) (something like a scalar)</li>
<li>An arbitrary tuple of Variables. In this case, you should specify a <code>grad_output=</code> for <code>autograd.grad</code> that has the same shape as the arbitrary tuple of Variables.</li>
</ul>

thang: <p>if you have found the answer to your solution can you share the code  please?</p>
<p>thank you !</p>

deepaksharma36: <p>An example1:</p>
<pre><code class="lang-auto">from torch.autograd import Variable
xx = Variable(torch.rand(1), requires_grad=True)
cc = 2*xx
torch.autograd.grad(cc, xx)
</code></pre>
<p>example 2:</p>
<pre><code class="lang-auto">xx = Variable(torch.rand(1), requires_grad=True)
cc = 2*xx
gg =3*cc
torch.autograd.grad(gg, xx)
</code></pre>

tengerye: <p>Would you please explain the second case? For example <a href="https://discuss.pytorch.org/t/pytorch-autograd-grad-only-one-element-tensors-can-be-converted-to-python-scalars/56681">here</a>.</p>

Jacquet_Gottfried: <p>I was also looking for a solution to the problem of JS regulation for PyTorch. I was inspired by the regularization method of the WGAN-GP. Here is the solution that I propose to you.</p>
<pre><code class="lang-auto">def discriminator_regularizer(critic, D1_args, D2_args):
    '''
    JS-Regularizer

    A Methode that regularize the gradient when discriminate real and fake. 
    This methode was proposed to deal with the problem of the choice of the 
    careful choice of architecture, paremeter intializaton and selction 
    of hyperparameters.
    
    GAN is highly sensitive to the choice of the latters. 
    According to "Stabilizing Training of Generative Adversarial Networks 
    through Regularization", Roth and al., This fragility is due to the mismathch or 
    non-overlapping support between the model distribution and the data distribution.
    :param critic : Discriminator network,
    :param D1_args : real value
    :param D2_args : fake value
    '''
    BATCH_SIZE, *others = D1_args.shape
    DEVICE              = D1_args.device

    D1_args     = Variable(D1_args, requires_grad=True) 
    D2_args     = Variable(D2_args, requires_grad=True)
    D1_logits, D2_logits = critic(D1_args), critic(D2_args)
    D1, D2 = torch.sigmoid(D1_logits), torch.sigmoid(D2_logits)
    
    grad_D1_logits = torch.autograd.grad(outputs=D1_logits, inputs=D1_args,
            create_graph=True, retain_graph=True,
            grad_outputs=torch.ones(D1_logits.size()).to(DEVICE))[0]

    grad_D2_logits = torch.autograd.grad(outputs=D2_logits, inputs=D2_args,
            create_graph=True, retain_graph=True,
            grad_outputs=torch.ones(D2_logits.size()).to(DEVICE))[0]

    grad_D1_logits_norm = torch.norm(torch.reshape(grad_D1_logits,(BATCH_SIZE,-1)), 
        dim=-1, keepdim=True)

    grad_D2_logits_norm = torch.norm(torch.reshape(grad_D2_logits,(BATCH_SIZE,-1)), 
        dim=-1, keepdim=True)

    assert grad_D1_logits_norm.shape == D1.shape
    assert grad_D2_logits_norm.shape == D2.shape

    reg_D1 = torch.multiply(torch.square(1. - D1), torch.square(grad_D1_logits_norm))
    reg_D2 = torch.multiply(torch.square(D2), torch.square(grad_D2_logits_norm))
    discriminator_regularizer =  torch.sum(reg_D1 + reg_D2).mean()
    return discriminator_regularizer

</code></pre>