Getting RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn but the element 0 in my case is just a tensor of fixed float values that only needs to be subtracted from nn.Parameter and hence, does not need the grad_fn

h3li05: <p>Hey!<br>
I’m trying to implement a text classification model that retrieves K batches from replay memory based on nearest neighbour approach(using a specific encoding of our test document that needs to be classified as key) and first trains on this batch to adjust to adjust its weight minimising log likelihood loss. However, an additional constraint is to be enforced which tries to minimise the euclidean distance between the original weight parameters and the newly trained parameters.<br>
Hence, I’m trying to define a custom loss function to enforce the weight constraint: <img src="https://discuss.pytorch.org/uploads/default/original/3X/6/5/653e9e88cfcfe86ef39b8283a754dd0fe845e49b.png" alt="58%20PM" data-base62-sha1="erEnUBylippPabpoRodc0J4193B" width="307" height="74"><br>
where,<br>
W contains weight parameters to be trained<br>
˜W contains the base parameters<br>
I’ve freezed the base network’s weights since they are not supposed to be changed</p>
<pre><code class="lang-auto"># base model weights
            self.base_weights = list(self.classifier.parameters())
            # # Freeze the base model weights
            for param in self.base_weights:
                param.requires_grad = False
</code></pre>
<p>And here is my local adaptation code:</p>
<pre><code class="lang-auto"># create a local copy of the classifier network
        adaptive_classifier = copy.deepcopy(self.classifier)
        optimizer = transformers.AdamW(
            adaptive_classifier.parameters(), lr=1e-3)
# Current model weights
        curr_weights = list(adaptive_classifier.parameters())
        # Train the adaptive classifier for L epochs with the rt_batch
        for _ in trange(self.L, desc='Local Adaptation'):

            # zero out the gradients
            optimizer.zero_grad()
            likelihood_loss, _ = adaptive_classifier(
                K_contents, attention_mask=K_attn_masks, labels=K_labels)

            diff = torch.Tensor([0]).cuda()
            # Iterate over base_weights and curr_weights and accumulate the euclidean norm
            # of their differences
            for base_param, curr_param in zip(self.base_weights, curr_weights):
                diff += (base_param-curr_param).pow(2).sum()
            # Total loss due to log likelihood and weight restraint
            diff_loss = 0.001*diff.sqrt()
            diff_loss.backward()
            likelihood_loss.backward()
            optimizer.step()
</code></pre>
<p>But when I try to run the code, I get the error<br>
<code> RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn</code><br>
I freezed the base_weights because I got <code>RuntimeError: Cuda Out of Memory </code> when they had not been. I suppose the weights were being tracked causing the above mentioned error.<br>
Can anyone please point out the flaws in my implementation?<br>
Or please suggest a more efficient implementation.<br>
Any help would be highly appreciated.<br>
Thanks in advance  <img src="https://discuss.pytorch.org/images/emoji/apple/blush.png?v=12" title=":blush:" class="emoji" alt=":blush:" loading="lazy" width="20" height="20"></p>

albanD: <p>Hi,</p>
<p>Few things:</p>
<ul>
<li>You can replace this to be more efficient:</li>
</ul>
<pre><code class="lang-auto">diff_loss.backward()
likelihood_loss.backward()
</code></pre>
<p>by</p>
<pre><code class="lang-auto">(diff_loss + likelihood_loss).backward()
</code></pre>
<ul>
<li>When you do <code>list(foo.parameters())</code>, you get a reference to the weights. So if you change them to not require gradients, then you basically change all your weights in your network not to require gradients. You can add <code>.clone().detach()</code> if you want to get a different Tensor that does not require gradients.</li>
</ul>

h3li05: <p>Thanks.<br>
I thought that model.parameters() returned a copy of weights.<br>
I solved the issue by creating an empty <code>base_weights</code> list and appended the individual parameter weight data. However, your method seems more compact and wouldn’t require the cuda() method to be called on the weights</p>
<pre><code class="lang-auto">  # base model weights
    self.base_weights = list()
    for param in self.classifier.parameters():
        self.base_weights.append(param.data.cuda())
</code></pre>

albanD: <p>Small detail: You should not do <code>param.data.cuda()</code> but <code>param.detach().cuda()</code>. As <code>.data</code> should not be used anymore.</p>