[Solved][Pytorch1.5] RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation

111367: <p>Hi,<br>
I’m facing the issue when I want to do backward() with 2 models, action_model and value_model. I’ve already searched related topic. They said that ‘pytorch 1.15’  always automatically check the ‘inplace’ when using backward(). However, it still report the same problem. How can I do backward() without missing previous parameter in model.</p>
<p>Thanks~~</p>
<aside class="onebox githubissue">
  <header class="source">
      <a href="https://github.com/pytorch/pytorch/issues/39141" target="_blank" rel="nofollow noopener">github.com/pytorch/pytorch</a>
  </header>
  <article class="onebox-body">
    <div class="github-row">
  <div class="github-icon-container" title="Issue">
	  <svg width="60" height="60" class="github-icon" viewBox="0 0 14 16" aria-hidden="true"><path d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"></path></svg>
  </div>

  <div class="github-info-container">
    <h4>
      <a href="https://github.com/pytorch/pytorch/issues/39141" target="_blank" rel="nofollow noopener">RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation?</a>
    </h4>

    <div class="github-info">
      <div class="date">
        opened <span class="discourse-local-date" data-format="ll" data-date="2020-05-28" data-time="12:32:03" data-timezone="UTC">12:32PM - 28 May 20 UTC</span>
      </div>

        <div class="date">
          closed <span class="discourse-local-date" data-format="ll" data-date="2020-06-01" data-time="14:08:15" data-timezone="UTC">02:08PM - 01 Jun 20 UTC</span>
        </div>

      <div class="user">
        <a href="https://github.com/honeytidy" target="_blank" rel="nofollow noopener">
          <img alt="honeytidy" src="https://avatars2.githubusercontent.com/u/1021165?v=4" class="onebox-avatar-inline" width="20" height="20">
          honeytidy
        </a>
      </div>
    </div>
  </div>
</div>

<div class="github-row">
  <p class="github-content">I am using pytorch-1.5 to do some gan test. My code is very simple gan code which just fit the sin(x)...</p>
</div>

<div class="labels">
    <span style="display:inline-block;margin-top:2px;background-color: #B8B8B8;padding: 2px;border-radius: 4px;color: #fff;margin-left: 3px;">module: autograd</span>
    <span style="display:inline-block;margin-top:2px;background-color: #B8B8B8;padding: 2px;border-radius: 4px;color: #fff;margin-left: 3px;">triaged</span>
</div>

  </article>
  <div class="onebox-metadata">
    
    
  </div>
  <div style="clear: both"></div>
</aside>

<p>This is error message:</p>
<pre><code class="lang-auto">File "train_test.py", line 234, in &lt;module&gt;
    flatten_imaginated_gru_hiddens).view(imagination_horizon+1, -1)
  File "/home/jeff/VirtualEnv/openai/lib/python3.7/site-packages/torch/nn/modules/module.py", line 550, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/jeff/dockers/pick_and_place/models.py", line 168, in forward
    state_value = self.fc4(hidden)
  File "/home/jeff/VirtualEnv/openai/lib/python3.7/site-packages/torch/nn/modules/module.py", line 550, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/jeff/VirtualEnv/openai/lib/python3.7/site-packages/torch/nn/modules/linear.py", line 87, in forward
    return F.linear(input, self.weight, self.bias)
  File "/home/jeff/VirtualEnv/openai/lib/python3.7/site-packages/torch/nn/functional.py", line 1610, in linear
    ret = torch.addmm(bias, input, weight.t())
 (print_stack at /pytorch/torch/csrc/autograd/python_anomaly_mode.cpp:60)
Traceback (most recent call last):
  File "train_test.py", line 255, in &lt;module&gt;
    action_loss.backward()
  File "/home/jeff/VirtualEnv/openai/lib/python3.7/site-packages/torch/tensor.py", line 198, in backward
    torch.autograd.backward(self, gradient, retain_graph, create_graph)
  File "/home/jeff/VirtualEnv/openai/lib/python3.7/site-packages/torch/autograd/__init__.py", line 100, in backward
    allow_unreachable=True)  # allow_unreachable flag
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [400, 1]], which is output 0 of TBackward, is at version 2; expected version 1 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck!
</code></pre>
<p>The problems are from action_model and value_model when I want to do backward() :</p>
<pre><code class="lang-auto">imaginated_values = value_model(flatten_imaginated_states,
                                          flatten_imaginated_gru_hiddens).view(imagination_horizon+1, -1)
         
## compute lambda target
lambda_target_values = utils.lambda_target(imaginated_rewards, imaginated_values,
                                                   gamma, lambda_)

## update_value model
value_loss = 0.5 * mse_loss(imaginated_values, lambda_target_values.detach())
value_optimizer.zero_grad()
value_loss.backward(retain_graph=True) 
#--------------------------------------------------------------
 # retain_graph=True : 
# reserve the parameters in the process of backpropagation 
 # when encountering two more outputs from the forward processing.
#--------------------------------------------------------------
clip_grad_norm_(value_model.parameters(), clip_grad_norm)
value_optimizer.step()

 ## update action model (multiply -1 for gradient ascent)
action_loss = -1*(lambda_target_values.mean())
action_optimizer.zero_grad()
action_loss.backward()
clip_grad_norm_(action_model.parameters(), clip_grad_norm)
action_optimizer.step()
</code></pre>

albanD: <p>Hi,</p>
<p>This is most likely happening because <code>value_optimizer.step()</code> actually modifies the weights of the model inplace while the original value of these weights is needed to compute <code>action_loss.backward()</code>.<br>
Is that the issue?</p>

111367: <p>Right. But, when I degrade my pytorch version from 1.5.1 to 1.4.0, it worked… I don’t know what’s going on.  Even though I use retained_graph in backward(), it still report the same issue.<br>
Thanks.</p>

111367: <p>Thanks albanD~<br>
I find a way that it won’t pop up the issue by rearranging the code like the following bellow:</p>
<pre><code class="lang-auto">value_loss = 0.5 * mse_loss(imaginated_values, lambda_target_values.detach())
value_optimizer.zero_grad()

action_loss = -1*(lambda_target_values.mean())
action_optimizer.zero_grad()

value_loss.backward(retain_graph=True)
action_loss.backward()

clip_grad_norm_(value_model.parameters(), clip_grad_norm)
clip_grad_norm_(action_model.parameters(), clip_grad_norm)

value_optimizer.step()
action_optimizer.step()
</code></pre>
<p>It won’t get the issue of  missing weights again. Thanks~</p>

albanD: <p>Before 1.5, these tests were not working properly for the optimizers. That’s why you didn’t see any error. But the computed gradients were not correct.</p>

raharth: <p>Hi albanD,</p>
<p>I think I’m running into a very similar problem.</p>
<p>I’m working on a Policy Gradient, in this algorithm you typically use some memory you sample from. The memory contains the last lets say 10 episodes the algorithm played. What you store are the log probabilities for the actions it chose. In this case you actually reuse data points even though they have already been updated, knowing that they are slightly wrong in the gradient, since they model would predict a slightly different probability after the first update. To be mathematically correct you would need to use importance sampling (p_old/p_new) but since this fraction is close to 1 of you use a sufficiently small learning rate this is typically dropped.</p>
<p>So some pseudo code would roughly look like this:</p>
<pre><code class="lang-auto">for episode in range(episodes_to_play):
    episode = play_episode()
    store_episode_in_memory(episode)
    drop_some_really_old_stuff_from_memory()
    log_probability, rewards = sample_some_memory()
    loss = REINFORCELOSS(log_probability, rewards)
    loss.backward(retain_graph=True)

</code></pre>
<p>I might have understood your explanation wrongly, but as far as I got it this is not possible anymore? The memory contains episodes that have already been used to train, but are still “fresh” enough to be not too far from the real distribution.</p>
<p>So my two questions:</p>
<ol>
<li>Do I understand your explanation correctly and is the multiple iteration over the loss.backward() the problem why this throws errors, even if I use retain_graph=True?</li>
<li>How can I fix this and get back to the old behavior?</li>
</ol>
<p>Thank you very much for your time!</p>

raharth: <p>I initially thought this would solve the problem but unfortunately it didn’t. I will leave the comment though.</p>
<p>I think I have also verified that this happens due to this particular change, using PyTorch 1.4 it works perfectly fine</p>
<hr>
<p>I think I have found a solution, assuming that my understanding of the problem is accurate:<br>
Simply cloning the loss before calling .backward(). Is that an accurate solution or did I miss something?</p>
<pre><code class="lang-auto">for episode in range(episodes_to_play):
    episode = play_episode()
    store_episode_in_memory(episode)
    drop_some_really_old_stuff_from_memory()
    log_probability, rewards = sample_some_memory()
    loss = REINFORCELOSS(log_probability, rewards).clone()
    loss.backward(retain_graph=True)
</code></pre>

xurong_li: <p>Hi,<br>
I implemented the triplet loss and trained the model with the loss.<br>
however, when I passed the three inputs to the model, the same error occurs.<br>
The code is shown below, and the model is Resnet or EfficientNet.<br>
whether I use the Pyotrch1.5 or 1.4,1.3, both of them are wrong. I don‘t know the reason.<br>
Even I changed the ‘inplace operation’ in Resnet code, the error still exists in the running process.</p>
<p>def train(epoch):<br>
model.train()  #<br>
total_loss = 0.0<br>
total_size = 0<br>
for batch_idx, (data, target) in enumerate(train_loader):  # 一个batch<br>
if args.cuda:<br>
data[0], target[0] = data[0].cuda(), target[0].cuda()<br>
data[1], target[1] = data[1].cuda(), target[1].cuda()<br>
data[2], target[2] = data[2].cuda(), target[2].cuda()</p>
<pre><code>        data[0], target[0] = Variable(data[0]), Variable(target[0])
        data[1], target[1] = Variable(data[1]), Variable(target[1])
        data[2], target[2] = Variable(data[2]), Variable(target[2])

        optimizer.zero_grad()

        anchor = model.forward(data[0])
        positive = model.forward(data[1])
        negative = model.forward(data[2])

        loss_cls_0 = criterion(anchor, target[0].long())
        loss_cls_1 = criterion(positive, target[1].long())
        loss_cls_2 = criterion(negative, target[2].long())
        loss_cls = loss_cls_0 + loss_cls_1 + loss_cls_2

        loss_tri = triplet_loss.forward(anchor, positive, negative)

        loss = loss_tri + loss_cls


        total_loss += loss.data.cpu()[0]
        total_size += data[0].size(0)

        loss.backward()
        optimizer.step()</code></pre>

Leming_Shen: <p>Thank you very very much!! I’ve also had this problem and tried many times but all failed until I saw your post. That was really helpful!</p>

Yufei_Ye: <p>This is very helpful!<br>
I would like to provide a tiny failing example, though I’m not fully convinced this gradient checking is not an overkill.</p>
<pre><code class="lang-auto">enc = nn.Conv2d(3, 5, 3, 1, 1)
dec = nn.Conv2d(5, 3, 3, 1, 1)

e_opt = torch.optim.Adam(enc.parameters(), lr=1e-4)
g_opt = torch.optim.Adam(dec.parameters(), lr=1e-4)

N = 1
H = W = 8

for i in range(2):
    g_opt.zero_grad()
    e_opt.zero_grad()

    image = torch.randn(N, 3, H, W)
    z = enc(image)
    recon = dec(z)

    c1_loss = F.l1_loss(recon, image)

    # encoder
    c1_loss.backward(retain_graph=True)
    e_opt.step()

    # decoder
    g_opt.zero_grad()
    # must do this line:
    # c1_loss = F.l1_loss(dec(z.detach()), image)
    c1_loss.backward()
    g_opt.step()
</code></pre>
<p>It’s a simple encoder-decoder (placeholder) network. Here I have two separate optimizers for the decoder and encoder respectively. Both are optimizing c1_loss. I first backprop c1 and update encoder. Then I clear the gradient in decoder and re-backprop c1_loss.  This will trigger the same runtime error. However, the resulting gradient should be right in this way?</p>
<p>Of course I wrote some unnecessary steps for this simple example, but it is pretty common to optimize encoder with c1_loss + enc_loss, and optimize decocer with c1_loss + dec_loss.</p>

ptrblck: <p>The error is raised, as the second <code>c1_loss.backward()</code> call would also try to calculate the gradients in <code>enc</code> using the already updated parameters and would thus yield this error.<br>
Based on the code snippet it seems the second <code>backward</code> call is needed to calculate the gradients in <code>dec</code> only, which would then be updated in <code>g_opt.step()</code> (explained to me by <a class="mention" href="/u/alband">@albanD</a> <img src="https://discuss.pytorch.org/images/emoji/apple/wink.png?v=9" title=":wink:" class="emoji" alt=":wink:"> ).<br>
If so, then you could use this neat approach:</p>
<pre><code class="lang-python">    c1_loss.backward(inputs=list(dec.parameters()))
    g_opt.step()
</code></pre>
<p>which would only accumulate the gradients into the passed leaf tensors.</p>

Tair_Tahar: <p>I have been facing this problem for over 8 hours, not being able to understand my problem.<br>
Could anyone try to help?<br>
This is my class for performing the REINFORCE policy gradient:</p>
<p>def update_policy(self, rewards, log_probs, entropies, gamma):<br>
R = torch.zeros(1, 1)<br>
loss = 0<br>
for i in reversed(range(len(rewards))):<br>
R = gamma * R + rewards[i]<br>
loss = loss - (log_probs[i]<em>(Variable®.expand_as(log_probs[i]))).sum() - (constantA</em>entropies[i]).sum()<br>
loss = loss / len(rewards)</p>
<pre><code>    optimizer.zero_grad()  #zero up gradients since pytorch accumulates in "backward()"
    loss.backward(retain_graph=True)
    nn.utils.clip_grad_norm_(self.parameters(), 40)
    optimizer.step()
</code></pre>
<p>def act(self, state):<br>
mu, sigma = self.forward(Variable(state))<br>
sigma = F.softplus(sigma)<br>
epsilon = torch.randn(mu.size())<br>
action = (mu + sigma.sqrt()<em>Variable(epsilon)).data<br>
prob = normal(action, mu, sigma)<br>
entropy = -0.5</em>((sigma+2*pi.expand_as(sigma)).log()+1)<br>
log_prob = prob.log()<br>
return action, prob, log_prob, entropy</p>
<pre><code>def forward(self, state):
    x = state
    x = (F.relu(self.linear1(x), inplace=True))
    mu = self.linear2(x)
    sigma = self.linear2_(x)
    return mu, sigma
</code></pre>
<p>By logs it looks like the problem derives from " sigma = self.linear2_(x)" But I am not entirely sure of that.</p>
<p>Thanks a lot!!</p>

yunfan0621: <p>Thanks for this solution, but it seems that it only works for pytorch with version higher than 1.8 (otherwise there is no input argument named `inputs’ for backward()). Is there any other elegant solution to specify the scope of gradients when doing backward()?</p>

ptrblck: <p>I don’t think the same functionality was available before the added <code>inputs</code> arguments, so you would need to update to the latest release. CC <a class="mention" href="/u/alband">@albanD</a> to correct me</p>

albanD: <p>Hi,</p>
<p>Indeed, the only way to get something similar with earlier releases is to use <code>autograd.grad()</code> and then populate the <code>.grad</code> fields manually with the gradient it returned.</p>

blessing: <p>I met the same problem as you, I passed the two inputs to the backbone, the error appeared.<br>
But when there is only one input, the error disappears .May I ask how you solve this problem?<br>
This is my code:<br>
inputs = inputs.cuda(cfg[‘GPU’], non_blocking=True)<br>
labels = labels.cuda(cfg[‘GPU’], non_blocking=True)<br>
inputs_ = inputs_.cuda(cfg[‘GPU’], non_blocking=True)<br>
labels_ = labels_.cuda(cfg[‘GPU’], non_blocking=True)<br>
features = backbone(inputs)<br>
features_ = backbone(inputs_)<br>
outputs = head(features, labels)<br>
outputs_ = head(features_, labels_)<br>
lossx = loss(outputs, labels) + loss(outputs_, labels_)<br>
optimizer.zero_grad()<br>
lossx.backward()<br>
optimizer.step()</p>

Hyunil: <p>Thanks! It worked in my codes.<br>
But, I have a question for this. Isn’t there any effects from action_loss to value_optimizer?<br>
I mean, in my minor knowledge, I didn’t understand why the computational graph of<br>
“value_loss → action_loss → value_optimizer → action_optimizer” have each correct optimizing value.</p>
<p>Could you anyone help me and explain this shortly? thanks.</p>

noahcao: <p>Thanks for all wonderful discussions.</p>
<p>I just wanted to confirm that the following two solutions would give the same and right optimization results (pytorch 1.9.0).</p>
<p>In such a pipeline:</p>
<blockquote>
<p>optim1 = optim.Adam(G.parameters())<br>
optim2 = optim.Adam(D.parameters())<br>
G = Model1()<br>
D = Model2()<br>
recons, z = G(input)<br>
loss1 = loss_func1(recons)<br>
diff = D(z)<br>
loss2 = loss_func2(diff)<br>
loss3 = loss_func3(diff)<br>
loss_G = loss1 + loss2  # we don’t want to update D parameters here<br>
loss_D = loss3</p>
</blockquote>
<h3><a name="solution-1-1" class="anchor" href="#solution-1-1"></a>Solution <span class="hashtag-raw">#1</span></h3>
<blockquote>
<p>optim1.zero_grad()<br>
loss_G.backward(retain_graph=True)<br>
optim2.zero_grad()<br>
loss_D.backward()<br>
optim1.step()<br>
optim2.step()</p>
</blockquote>
<h3><a name="solution-2-2" class="anchor" href="#solution-2-2"></a>Solution <span class="hashtag-raw">#2</span></h3>
<blockquote>
<p>optim1.zero_grad()<br>
loss_G.backward(retain_graph=True, inputs=list(G.parameters()))<br>
optim1.step()<br>
optim2.zero_grad()<br>
loss_D.backward(inputs=list(D.parameters()))<br>
optim2.step()</p>
</blockquote>
<p>Both of the solutions come from the previous solutions. Thanks again.</p>

hfzarslan: <p>I am facing the same issue and has beem stuck for 1 day<br>
here my code</p>
<pre><code class="lang-auto">class RNN(nn.Module):
    
    def __init__(self,input_size, output_size, hidden_size=64):

        super().__init__()

        self.input_size  = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size
        
        self.xh = nn.Linear(self.input_size, self.hidden_size, bias=False)


        self.hh = nn.Linear(self.hidden_size, self.hidden_size)
        self.hy = nn.Linear(self.hidden_size, self.output_size)
        
        self.h = torch.zeros(self.hidden_size, requires_grad=True)
        
        self.tanh = nn.Tanh()
        self.softmax = nn.Softmax(dim=1)
        self.sigmoid = nn.Sigmoid()

    def rnn_cell(self, x_t):  
        
        first_h = self.hh(self.h)
        
        second_x = self.xh(x_t)

        act = second_x + first_h
        
        self.h = self.tanh(act)

        updated_c = self.sigmoid(self.hy(self.h))

        return updated_c


    def forward(self, inp):
        return self.rnn_cell(inp)
</code></pre>
<p>here is training code</p>
<pre><code class="lang-auto">def train(train_x,  valid_x, lr, epochs, hidden_units, net='RNN'):
    
    for step, (data, label) in enumerate(train_x):
        inputs = np.array(data)
        break

    if net=='RNN':
        model = RNN(inputs.shape[1], 1, hidden_units)
    elif net == 'LSTM':
        h = torch.zeros(hidden_units).requires_grad_()
        c = torch.zeros(hidden_units).requires_grad_()
        model = LSTM(inputs.shape[1], 1, hidden_units)
    elif net == 'GRU':
        St_1 = torch.zeros(hidden_units).requires_grad_()
        model = GRUModel(inputs.shape[1], 1, hidden_units)
    model.to(device)
    
    
    train_loss, val_loss = [],[]
    train_accuracy, val_accuracy = [], []
    optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9)
    criterion = nn.BCELoss()

    
    
    for ep in range(epochs):
        running_loss, correct = 0, 0
        for i, (data, label) in enumerate(train_x):
            data, label = Variable(data), Variable(label)
            data, label = data.to(device), label.to(device)
            
            optimizer.zero_grad()
            
            if net == 'RNN':
                net_out= model(data)
            elif net == 'LSTM':
                net_out, h, c = model(data, h, c)
            elif net == 'GRU':
                net_out, St_1 = model(data, St_1)
                
            
            label = torch.reshape(label, (label.shape[0], 1))
            net_out = torch.reshape(net_out, (label.shape[0], 1))
            label = label.float()
            loss = criterion(net_out, label)
            loss.backward(retain_graph=True, inputs=list(model.parameters()))
            optimizer.step()

            running_loss += loss.item()
#             pred = torch.argmax(net_out, axis=1)  # get the index of the max log-probability
#             actual = torch.argmax(label, axis=1)
            out = (net_out&gt;0.5).float()
            correct += out.eq(label).sum()



        print(running_loss)
        print("Epoch:", ep)
        print(correct.item())
        print("Training Accuracy:", 100. * correct.item() / len(train_x.dataset))
        print("Train Loss:", running_loss / len(train_x.dataset))
        train_loss.append(running_loss / len(train_x.dataset))
        train_accuracy.append(correct / len(train_x.dataset))


#         test_loss = 0
#         correct = 0
#         with torch.no_grad():
#             for batch_idx, (data, target) in enumerate(valid_x):
#                 data, target = Variable(data), Variable(target)
#                 data, target = data.to(device), target.to(device)
#     #                 data = data.view(-1, 784)
#                 if net == 'RNN':
#                     net_out, _ = model(data, h)
#                 elif net == 'LSTM':
#                     net_out, _, _ = model(data, h, c)
#                 elif net == 'GRU':
#                     net_out, _ = model(data, St_1)
#                 net_out = torch.reshape(net_out, (net_out.shape[0],))
#                 # sum up batch loss
#                 target = target.float()
#                 test_loss += criterion(net_out, target).item()
#     #                 pred = torch.argmax(net_out, axis=1)  # get the index of the max log-probability
#     #                 actual = torch.argmax(label, axis=1)
#                 out = (net_out&gt;0.5).float()
#                 correct += out.eq(target).sum()
#             val_loss.append(test_loss / len(valid_x.dataset))
#             val_accuracy.append(correct / len(valid_x.dataset))

#         print("Validation Accuracy:" , 100. * correct.item() / len(valid_x.dataset))
#         print("Validation Loss:", test_loss / len(valid_x.dataset)) 
#         print("----------------------------------------------------------")
    
    return model, train_loss, train_accuracy, val_loss, val_accuracy
        
        
    
    

</code></pre>
<p>Here is the error list:</p>
<pre><code class="lang-auto">/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/torch/autograd/__init__.py:147: UserWarning: Error detected in MmBackward. Traceback of forward call that caused the error:
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/ipykernel_launcher.py", line 16, in &lt;module&gt;
    app.launch_new_instance()
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/traitlets/config/application.py", line 845, in launch_instance
    app.start()
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/ipykernel/kernelapp.py", line 619, in start
    self.io_loop.start()
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/tornado/platform/asyncio.py", line 199, in start
    self.asyncio_loop.run_forever()
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/asyncio/base_events.py", line 570, in run_forever
    self._run_once()
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/asyncio/base_events.py", line 1859, in _run_once
    handle._run()
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/asyncio/events.py", line 81, in _run
    self._context.run(self._callback, *self._args)
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/tornado/ioloop.py", line 688, in &lt;lambda&gt;
    lambda f: self._run_callback(functools.partial(callback, future))
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/tornado/ioloop.py", line 741, in _run_callback
    ret = callback()
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/tornado/gen.py", line 814, in inner
    self.ctx_run(self.run)
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/tornado/gen.py", line 775, in run
    yielded = self.gen.send(value)
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/ipykernel/kernelbase.py", line 358, in process_one
    yield gen.maybe_future(dispatch(*args))
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/tornado/gen.py", line 234, in wrapper
    yielded = ctx_run(next, result)
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/ipykernel/kernelbase.py", line 261, in dispatch_shell
    yield gen.maybe_future(handler(stream, idents, msg))
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/tornado/gen.py", line 234, in wrapper
    yielded = ctx_run(next, result)
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/ipykernel/kernelbase.py", line 536, in execute_request
    self.do_execute(
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/tornado/gen.py", line 234, in wrapper
    yielded = ctx_run(next, result)
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/ipykernel/ipkernel.py", line 302, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/ipykernel/zmqshell.py", line 539, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 2898, in run_cell
    result = self._run_cell(
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 2944, in _run_cell
    return runner(coro)
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/IPython/core/async_helpers.py", line 68, in _pseudo_sync_runner
    coro.send(None)
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3169, in run_cell_async
    has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3361, in run_ast_nodes
    if (await self.run_code(code, result,  async_=asy)):
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3441, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "&lt;ipython-input-61-f6fbdf7371e3&gt;", line 2, in &lt;module&gt;
    net, train_loss, train_accuracy, val_loss, val_accuracy = train(train_loader,  valid_loader, lr=0.0001, epochs=10,  hidden_units=64, net='RNN')
  File "&lt;ipython-input-60-3bb8b3924f63&gt;", line 35, in train
    net_out= model(data)
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1051, in _call_impl
    return forward_call(*input, **kwargs)
  File "&lt;ipython-input-59-cdbb099f3af3&gt;", line 39, in forward
    return self.rnn_cell(inp)
  File "&lt;ipython-input-59-cdbb099f3af3&gt;", line 25, in rnn_cell
    first_h = self.hh(self.h)
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1051, in _call_impl
    return forward_call(*input, **kwargs)
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/torch/nn/modules/linear.py", line 96, in forward
    return F.linear(input, self.weight, self.bias)
  File "/Users/arslan/anaconda3/envs/torch_env/lib/python3.8/site-packages/torch/nn/functional.py", line 1847, in linear
    return torch._C._nn.linear(input, weight, bias)
 (Triggered internally at  /Users/distiller/project/conda/conda-bld/pytorch_1623459044803/work/torch/csrc/autograd/python_anomaly_mode.cpp:104.)
  Variable._execution_engine.run_backward(
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
&lt;ipython-input-61-f6fbdf7371e3&gt; in &lt;module&gt;
      1 torch.autograd.set_detect_anomaly(True)
----&gt; 2 net, train_loss, train_accuracy, val_loss, val_accuracy = train(train_loader,  valid_loader, lr=0.0001, epochs=10,  hidden_units=64, net='RNN')

&lt;ipython-input-60-3bb8b3924f63&gt; in train(train_x, valid_x, lr, epochs, hidden_units, net)
     44             label = label.float()
     45             loss = criterion(net_out, label)
---&gt; 46             loss.backward(retain_graph=True, inputs=list(model.parameters()))
     47             optimizer.step()
     48 

~/anaconda3/envs/torch_env/lib/python3.8/site-packages/torch/_tensor.py in backward(self, gradient, retain_graph, create_graph, inputs)
    253                 create_graph=create_graph,
    254                 inputs=inputs)
--&gt; 255         torch.autograd.backward(self, gradient, retain_graph, create_graph, inputs=inputs)
    256 
    257     def register_hook(self, hook):

~/anaconda3/envs/torch_env/lib/python3.8/site-packages/torch/autograd/__init__.py in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables, inputs)
    145         retain_graph = create_graph
    146 
--&gt; 147     Variable._execution_engine.run_backward(
    148         tensors, grad_tensors_, retain_graph, create_graph, inputs,
    149         allow_unreachable=True, accumulate_grad=True)  # allow_unreachable flag

RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [64, 64]], which is output 0 of TBackward, is at version 2; expected version 1 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck!
</code></pre>
<p>can you <a class="mention" href="/u/ptrblck">@ptrblck</a> <a class="mention" href="/u/alband">@albanD</a>  please help me I’ll be very thankful to all of you</p>

ptrblck: <p>I guess the error is raised, since you are not detaching the hidden state, are retaining the graph, and updating the parameters in each iteration. This would cause the intermediate forward activations from the previous iterations be become “stale” and the gradient computation would fail.<br>
I don’t know what your exact use case is, but you might want to <code>detach()</code> the hidden and cell states in each iteration and remove <code>retain_graph=True</code> as well.</p>