Try to update the some variables while guarantee they can be autograded properly

sunnylyu: <p>Hi,<br>
I’m trying to modify self.message1 and self.message2 using two different mlps. But I find that the gradients of these two mlps are None for each epoch all the time. But I use the same way to modify the variable F_ue_update using mlp3, the gradients of its weights and bias are not None.<br>
Here is some parts of my code.<br>
Thanks for any help.</p>
<pre><code class="lang-auto">    def message(self, F_ue, E, agg_ue, P, Noise): 
        if self.device.type == "cuda":
            P = P.to(self.device)
            Noise = Noise.to(self.device)
        for m in range(self.M):
            for k in range(self.K):
                message_input1 = torch.cat((E[m,k,:], agg_ue[m,:], P[m], Noise[k]), 0)
                message_input_var1 = torch.autograd.Variable(message_input1, requires_grad=True)
                self.message_bs[m, k, :] = self.mlp1(message_input_var1)

        agg_bs = torch.mean(self.message_bs, dim=0)
        agg_bs = agg_bs.to(self.device) # of size [K, 2MN]
        for k in range(self.K):
            for m in range(self.M):
                message_input = torch.cat((F_ue[:, k], E[m, k, :], agg_bs[k, :], P[m], Noise[k]), 0)
                message_input_var = torch.autograd.Variable(message_input, requires_grad=True)
                self.message_ue[k, m, :] = self.mlp2(message_input_var)

def update(self, E, F_ue, agg_bs, P, Noise):
        if self.device.type == "cuda":
            P = P.to(self.device)
            Noise = Noise.to(self.device)
        F_ue_update = torch.zeros(F_ue.shape)
        for k in range(self.K):
            edge_cat_ue = torch.cat([E[m, k, :] for m in range(self.M)], dim=0)
            message_input3 = torch.cat((edge_cat_ue, F_ue[:, k], agg_bs[k,:], P[0], Noise[k]), 0)
            message_input_var3 = torch.autograd.Variable(message_input3, requires_grad=True)
            F_ue_update[:, k] = self.mlp3(message_input_var3)
            
        F_ue_update = F_ue_update.to(self.device)
</code></pre>
<pre><code class="lang-auto">F_ue = model(F_ue0, edge_feature, P, Noise)
W = getW(F_ue, P, K)
loss = loss + Loss(W, H_complex, Noise)
optimizer.zero_grad()
loss.backward()
for name, param in model.named_parameters():    
     if param.grad is not None:
        print(f'Parameter: {name}')    # Only mlp3 weight and bias be printed
optimizer.step()
</code></pre>

ptrblck: <p>Is this a double post from <a href="https://discuss.pytorch.org/t/loss-does-not-decrease-during-the-training-and-the-gradients-for-all-mlps-are-0/184238/3">here</a> or could you explain what the difference is?<br>
You are still recreating the deprecated <code>Variable</code>s and are thus detaching the tensor from the computation graph. Don’t use deprecated objects and use differentiable operations (such as <code>torch.cat</code> or <code>torch.stack</code>) instead of recreating tensors as already explained.</p>

sunnylyu: <p>I modified message function compared to the previous post, the rest of them are the same.<br>
I’m sorry but I still don’t understand what you mean by using deprecated objects. Do you mean in the getW function that I cannot create a new variable W? But if I don’t create a new complex variable, how can I transfer the real outputs from mlps into complex to compute for the loss (as I mentioned in the previous post)?</p>
<p>For this post, I don’t understand why the parameters of only mlp1 and mlp2 don’t have gradients. You mentioned that I used .detach() so it will be detached from its original graph. So I modified the message and update functions to avoid using .clone().detach(), now the parameters of mlp3 can be updated properly but not for mlp1 and mlp2. I don’t understand why because all mlps are used in the same way.</p>
<p>Sorry for my poor explaintion please let me know if anything is misunderstanding. I really appreciate your help.</p>

ptrblck: <aside class="quote no-group" data-username="sunnylyu" data-post="3" data-topic="184289">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/sunnylyu/48/62123_2.png" class="avatar"> sunnylyu:</div>
<blockquote>
<p>I’m sorry but I still don’t understand what you mean by using deprecated objects.</p>
</blockquote>
</aside>
<p><code>Variable</code> is deprecated since PyTorch <code>0.4</code> so don’t use it.</p>
<aside class="quote no-group" data-username="sunnylyu" data-post="3" data-topic="184289">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/sunnylyu/48/62123_2.png" class="avatar"> sunnylyu:</div>
<blockquote>
<p>Do you mean in the getW function that I cannot create a new variable W?</p>
</blockquote>
</aside>
<p>Yes, recreating a new tensor from another one will detach it from the computation graph as seen here:</p>
<pre data-code-wrap="python"><code class="lang-python">x = torch.randn(1, requires_grad=True)
y = x + 1
print(y.grad_fn)
# &lt;AddBackward0 object at 0x0000025A0007C370&gt;
# a valid grad_fn indicates y is attached to a computation graph

z = torch.tensor(y)
# UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).
print(z.grad_fn)
# None
print(z.is_leaf)
# True
# Note the Userwarning! You can see that z is a leaf tensor without a gradient history!
</code></pre>
<p>Instead create the output via differentiable operations. E.g. if you want to concatenate different tensors into one use <code>torch.cat</code> or <code>torch.stack</code>.</p>

sunnylyu: <p>Thanks for your example. I still have several questions.</p>
<ul>
<li>
<p>Do you have any suggestion about fix the getW function? I really need to transfer the real outputs into complex.</p>
</li>
<li>
<p>Also, for the message function, I think I only modify the variables values in each iteration instead of creating new tensors to store the result by calculating mlp1 and mlp2, but it turns out that they cannot be properly autograded.</p>
</li>
</ul>