# I got 'RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation' error

**URL:** <https://discuss.pytorch.org/t/i-got-runtimeerror-one-of-the-variables-needed-for-gradient-computation-has-been-modified-by-an-inplace-operation-error/36289>\
**Category:** Uncategorized\
**Created:** [February 3, 2019, 11:47am UTC](https://discuss.pytorch.org/t/i-got-runtimeerror-one-of-the-variables-needed-for-gradient-computation-has-been-modified-by-an-inplace-operation-error/36289 "2019-02-03T11:47:56Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![coincheung](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/c/ad7895/32.png) [@coincheung](https://discuss.pytorch.org/u/coincheung)\
**Post date:** [February 3, 2019, 3:00pm UTC](https://discuss.pytorch.org/t/i-got-runtimeerror-one-of-the-variables-needed-for-gradient-computation-has-been-modified-by-an-inplace-operation-error/36289/3 "2019-02-03T15:00:16Z")

</div>

Would you please show me how to fix this? I changed it like this:

```python
  def forward(self, logits, labels):
        N, C, H, W = logits.size()
        n_pixs = N * H * W
        logits = logits.permute(0, 2, 3, 1).contiguous().view(-1, C)
        with torch.no_grad():
            scores = F.softmax(logits, dim=1).cpu().detach()
            labels = labels.view(-1)
            labels_cpu = labels.cpu().detach()
            invalid_mask = labels_cpu==self.ignore_lb
            labels_cpu[invalid_mask] = 0
            picks = scores[torch.arange(n_pixs), labels_cpu]
            picks[invalid_mask] = 1
            sorteds, inds = torch.sort(picks)
            thresh = self.thresh if sorteds[self.n_min]<self.thresh else sorteds[n_min]
            labels[picks>thresh] = self.ignore_lb
        loss = self.criteria(logits, labels)
        return loss

```

But the problem still exists

---

_[View the full topic](https://discuss.pytorch.org/t/i-got-runtimeerror-one-of-the-variables-needed-for-gradient-computation-has-been-modified-by-an-inplace-operation-error/36289)._
