Volatile was removed and now has no effect. Use `with torch.no_grad():` instead

747 Views Asked by At

I tried to using Show And Tell model with COCO dataset. But, at one point my Torch program paused. Can anyone fix my code? Here is my code which causes the training to pause.

def to_var(x, volatile=True):
if torch.cuda.is_available():
    x = x.cuda()
return Variable(x, volatile=volatile)

And the warning was below.

utils.py:114: UserWarning: volatile was removed and now has no effect. Use with torch.no_grad(): instead. return Variable(x, volatile=volatile)

1

There are 1 best solutions below

0
On

In the new version of Pytorch volatile is removed and also Variable is not necessary. Any computation of a tensor with volatile=True wouldn’t be tracked by autograd. So your function can be rewritten as:

import torch
def to_var(x, volatile=True):
    if torch.cuda.is_available():
        x = x.cuda()
    x.requires_grad = not volatile
    return x

x = torch.tensor(1.0)
print(x.requires_grad)
x = to_var(x, volatile=True)
print(x.requires_grad)
x = to_var(x, volatile=False)
print(x.requires_grad)

Output:

>>> False
>>> False
>>> True