Gradients not flowing

legoh: <p>Hi all, I’m trying to do learning on graphs and I’m facing an issue of my weights in my model not updating. I have simplified the model and it still seems like my weights are not updating. I’m wondering 2 things, (1) am I doing any operations that are breaking the computational graph? Because most of the tensors seem to have backward enabled. (2) Is there a good way to check how gradients are flowing? I’m currently just trying to print the parameters and watch if they get updated.</p>
<p>I even tried my model with a very large learning rate (1e-1) to see if the weights get updated, but no luck.<br>
I deleted quite a few bits of code that did some graph learning as I wanted to simplify my model and isolate where the breakage is, so please pardon some excess unused variables. Here’s a snippet for my code:</p>
<pre><code class="lang-auto">class NeuraLBP(torch.nn.Module):
    def __init__(self, d_in_channels, p_in_channels, out_channels, h_size, e_size, n_embed, **kwargs):
        super(NeuraLBP, self).__init__(**kwargs)
        
        # Feature sizes
#         self.in_channels = in_channels
        self.out_channels = out_channels
        self.h_size = h_size
        self.n_embed = n_embed
        
        # Layers
        # Embedding for dummy nodes
        self.embed = torch.nn.Embedding(n_embed, out_channels)
        
        # Translation of node features
        self.dax_lin = torch.nn.Linear(d_in_channels, h_size, bias=False)
        self.pax_lin = torch.nn.Linear(p_in_channels, h_size, bias=False)
        
        # Custom MPNN from another paper
        self.mpnn = MPNN(in_channels=h_size, out_channels=out_channels, edge_feature=e_size, hidden_size=h_size)
        self.mpnn2 = MPNN(in_channels=out_channels, edge_feature=e_size, out_channels=out_channels, hidden_size=h_size)
        self.mpnn3 = MPNN(in_channels=out_channels, edge_feature=e_size, out_channels=out_channels, hidden_size=h_size)        
        # Weight translation layer
        self.weight_transform = torch.nn.Sequential(torch.nn.Linear(out_channels * 2, h_size * 4),
                                                    torch.nn.ReLU(),
                                                    torch.nn.Linear(h_size * 4, h_size * 4),
                                                    torch.nn.ReLU(),
                                                    torch.nn.Linear(h_size * 4, h_size * 2),
                                                    torch.nn.ReLU(),
                                                    torch.nn.Linear(h_size * 2, 1),
                                                    torch.nn.Tanh())

    
    def reset_parameters(self):        
        return
        
    def forward(self,
               pax_feat,
               dax_feat,
               pax_embed,
               assign_edge_index,
               assign_edge_attr,
               real_edges_original,
               real_edge_attr,
               sorted_edges,
               sorted_features,
               n_nodes):
        
        x = torch.cat((self.pax_lin(pax_feat), self.dax_lin(dax_feat)), dim=0)
        out = x
        all_feat = torch.cat((out[:pax_feat.size(0), :], self.embed(pax_embed), out[pax_feat.size(0):, :]), dim=0)
                
        wts = self.weight_transform(torch.cat((all_feat[sorted_edges[:, 0], :], all_feat[sorted_edges[:, 1], :]), dim=1))
        wts = wts.view(n_nodes, n_nodes)

        b_a, b_b = self.iter_simp_min_sum_batch_scatter(wts.unsqueeze(0), wts.t().unsqueeze(0), wts.unsqueeze(0).clone().detach(), 5)

        wts = wts + b_b.permute(0, 2, 1).squeeze(0)

        return wts

  def iter_simp_min_sum_batch_scatter(self, m_alpha_beta, m_beta_alpha, weights, n_iter):
        n = m_alpha_beta.size(1)
        for _ in range(n_iter):
            # Message passing
            beta_alpha_maxes, beta_alpha_indices = torch.topk(m_beta_alpha, 2, dim=1)
            m_alpha_beta_k = weights.permute(0, 2, 1) - beta_alpha_maxes[:, 0, :].unsqueeze(1)
            m_alpha_beta_k = m_alpha_beta_k.scatter_add_(dim=1, index=beta_alpha_indices[:, 0, :].unsqueeze(1),
                                                         src=beta_alpha_maxes[:, 0, :].unsqueeze(1))
            m_alpha_beta_k = m_alpha_beta_k.scatter_add_(dim=1, index=beta_alpha_indices[:, 0, :].unsqueeze(1),
                                                         src=beta_alpha_maxes[:, 1, :].unsqueeze(1) * -1).permute(0, 2,
                                                                                                                  1)

            alpha_beta_maxes, alpha_beta_indices = torch.topk(m_alpha_beta, 2, dim=1)
            m_beta_alpha_k = weights - alpha_beta_maxes[:, 0, :].unsqueeze(1)
            m_beta_alpha_k = m_beta_alpha_k.scatter_add_(dim=1, index=alpha_beta_indices[:, 0, :].unsqueeze(1),
                                                         src=alpha_beta_maxes[:, 0, :].unsqueeze(1))
            m_beta_alpha_k = m_beta_alpha_k.scatter_add_(dim=1, index=alpha_beta_indices[:, 0, :].unsqueeze(1),
                                                         src=alpha_beta_maxes[:, 1, :].unsqueeze(1) * -1).permute(0, 2,
                                                                                                                  1)

            m_alpha_beta = m_alpha_beta_k
            m_beta_alpha = m_beta_alpha_k

            
        return m_alpha_beta, m_beta_alpha
</code></pre>
<p>And here’s my training loop:</p>
<pre><code class="lang-auto">model = NeuraLBP(d_in_channels=14, p_in_channels=6, out_channels=512, h_size=512, e_size=1, n_embed=1000) 
model.reset_parameters()
model.train()
model = model.to(device)
optim = torch.optim.Adam(model.parameters(), lr=1e-1)
loss_fn = torch.nn.CrossEntropyLoss()

list_loss = []
list_acc = []
for i in range(5):
    for d in d_loader:
        optim.zero_grad()
        pax_feat = d.pax_feat.to(device)
        dax_feat = d.dax_feat.to(device)
        pax_embed = d.pax_embed.to(device)
        assign_edge_index = d.assign_edge_index.to(device)
        assign_edge_attr = d.assign_edge_feat[:, 0].view(-1, 1).to(device) * -1.0
        real_edges_original = d.real_edges_original.to(device)
        real_edge_attr = d.real_edge_attr[:, 0].view(-1, 1).to(device) * -1.0
        data.sorted_edges = d.sorted_edges.type(torch.LongTensor)
        data.sorted_features = d.sorted_features.type(torch.FloatTensor)
        sorted_edges = d.sorted_edges.to(device)
        sorted_features = d.sorted_features.to(device) * -1.0
        n_nodes = d.dax_feat.size(0)
        out = model(pax_feat,
                   dax_feat,
                   pax_embed,
                   assign_edge_index,
                   assign_edge_attr,
                   real_edges_original,
                   real_edge_attr,
                   sorted_edges,
                   sorted_features,
                   n_nodes)
        out = torch.softmax(out, dim=1)

        # Organize the labels - CE labels
        row, col = torch.where(d.lbl_mat &gt; 0)
        labels = torch.zeros((d.lbl_mat.size(0)), dtype=int) - 100
        labels[row] = col
        labels = labels.to(device)

        loss = loss_fn(out, labels)
        list_loss.append(float(loss))
        print(float(loss))
        with torch.no_grad():
            acc = acc_func(out, labels)
            list_acc.append(acc)

        loss.backward()
        optim.step()

</code></pre>

albanD: <p>Hi,</p>
<p>I did not read all the code, but you use <code>.detach()</code> in there that explicitly prevent gradients from flowing. Could that be the reason?</p>

legoh: <p>When I pass the parameters into the function, I use <code>self. iter_simp_min_sum_batch_scatter(wts.unsqueeze(0), wts.t().unsqueeze(0), wts.unsqueeze(0).clone().detach(), 5)</code>, so technically, only 1 input is detached from the computational graph right?</p>
<p>The parameters correspond to <code>(m_alpha_beta, m_beta_alpha, weights, n_iter)</code>, so only <code>weights</code> should be non-learnable, <code>m_alpha_beta</code> and <code>m_beta_alpha</code> should still be part of the graph. Or do I have to explicitly copy it to another variable and detach it to prevent it from affecting the others?</p>

albanD: <p>No .detach() is out of place so it won’t change the others.<br>
Is there any place where you get something that does not require gradients and have to set requires_grad again? no right?<br>
In that case, what are the gradients you get? Maybe the gradient of your net are actually 0?</p>

legoh: <p>No, there’s no place where i reset the gradient.</p>
<p>How do I check what are the gradients I’m getting? I get a loss value that’s for sure, but I’m not sure what’s the gradients I’m getting and how to check that.</p>

albanD: <p>After you zero out your gradient and call .backward() on your loss, each parameter in your model will have a field <code>.grad</code> that contains its gradients. It is this field that is used by the optimizer when you do opt.step().</p>

legoh: <p>If that’s the case, I should be printing out the <code>parameter().grad</code> after a <code>loss.backward()</code> call to identify the gradients?</p>

albanD: <p>Yes<br>
this would print all of them:</p>
<pre><code class="lang-auto">for p in model.parameters():
    print(p.grad)
</code></pre>

legoh: <p>Wow, you are right, the gradients are actually 0. Is there a reason for this? Would the gradients be 0 if there’s a break in the computational graph?</p>

albanD: <p>They shoud be None before the first backward pass. If they become 0 after that first backward pass, that means that gradient were propagated.</p>
<p>You will need to check your function but it is quite easy to write functions that have a gradient of 0. If you do step functions for example.<br>
One thing you can use is <code>some_tensor.register_hook()</code> that you can use to get the gradient for any Tensor in your model.<br>
If you use given it the <code>print</code> function, it will print that gradient. If you need something more fancy you can use:</p>
<pre><code class="lang-auto">def my_hook(grad):
    print("Gradient for some_tensor")
    print(grad)
</code></pre>

legoh: <p>I see, so I have to register a hook on the tensor first? That will print the gradient with respect to the tensor right, not the parameters?</p>
<p>Also, I wonder if I could be facing zero gradients because of initializations in my weight matrix?</p>

albanD: <aside class="quote no-group" data-username="legoh" data-post="11" data-topic="94656">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/l/82dd89/48.png" class="avatar"> legoh:</div>
<blockquote>
<p>I see, so I have to register a hook on the tensor first? That will print the gradient with respect to the tensor right, not the parameters?</p>
</blockquote>
</aside>
<p>You have to register the hook before calling backward. And it will print the gradient of the tensor you called <code>register_hook()</code> on.</p>
<blockquote>
<p>Also, I wonder if I could be facing zero gradients because of initializations in my weight matrix?</p>
</blockquote>
<p>It is possible, if you’re in a local minima where the gradient in all direction is 0.</p>

legoh: <p>I see okay, so it means I should be doing something like:</p>
<pre><code class="lang-auto">output = model(inputs)

loss = loss_function(output, labels)
model.weight_transform.register_hook()
loss.backward()

print(model.weight_transform.grad)
</code></pre>
<p>Hmm okay, I’ll have a look to see if a better initialization can help get gradients. How can I tell if at the last stage of the output, the gradients are likely going to be 0? Is there any way for this? One explanation could be if the input is 0 right?</p>

albanD: <p>No, this:</p>
<pre><code class="lang-auto">def my_hook(grad):
  print("In the hook")
  print(grad)

output = model(inputs)

loss = loss_function(output, labels)
model.weight_transform.register_hook(my_hook)
loss.backward()  # The hook will be called in the middle of the backward pass
</code></pre>

legoh: <p>I see ok. Do you have any debugging tips as to why the gradients hit 0? At the start of the training for some initializations, I see some gradients. But that diminishes pretty quickly. Seems to happen if my <code>weight_transform</code> layer outputs from a non-linearity like <code>Tanh()</code> or <code>Sigmoid()</code></p>

albanD: <p>It’s hard to say. But non-linearities can lead to gradients that go to 0. For example if you give as input to a relu layer values that are all negative.<br>
Or if you give to tanh values that are large in absolute value.</p>
<p>Note that if you initially have gradients and then it goes to 0, that means that your model is properly converging a minimum value of the loss function that you provided.</p>

legoh: <blockquote>
<p>Or if you give to tanh values that are large in absolute value.</p>
</blockquote>
<p>Hmm this could suggest why too.</p>
<blockquote>
<p>Note that if you initially have gradients and then it goes to 0, that means that your model is properly converging a minimum value of the loss function that you provided.</p>
</blockquote>
<p>But sadly, it seems like my accuracy doesn’t improve, and there’s still a <code>loss</code> value. So I think it’s likely some form of local minima? I’m not sure if I can tell also if that the network has sufficient representational power.</p>

albanD: <p>It’s hard to say indeed…<br>
But it does sound like you’re getting stuck in a local minimum.</p>

legoh: <p>Would agree. I’ll have a better look at it. What’s a normal / expectable maximum gradient like? I’ve been looking at the maximum gradient being propagated backwards to have a rough idea whether there’s any sufficient learning.</p>

albanD: <p>The scale of the gradient depends on many things, in particular, the value of the Tensor itself.<br>
Also, the learning rate you use might change completely the scale of the gradients you expect to see.</p>
<p>I am afraid I don’t have an answer for the beyond: whatever works for your model <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=9" title=":slight_smile:" class="emoji" alt=":slight_smile:"></p>