Pytorch 使用cuda进行自动求导出现的幺蛾子

首先我们来简单地举个pytorch自动求导的例子:

x = torch.randn(3)
x = Variable(x, requires_grad = True)
y = x * 2
gradients = torch.FloatTensor([0.1, 1.0, 0.0001])
y.backward(gradients)
x.grad

在Ipython中会直接显示x.grad的值

Variable containing:
 0.2000
 2.0000
 0.0002
[torch.FloatTensor of size 3]

怎么样,是不是很Easy?

那我们来试一下使用cuda吧

将代码简单改动,就是将x转化为cuda变量

x = torch.randn(3)
x = Variable(x, requires_grad = True)
x = x.cuda() # 需要你的计算机有GPU
y = x * 2
gradients = torch.FloatTensor([0.1, 1.0, 0.0001])
y.backward(gradients)
x.grad

我们来显示一下,

print(x.grad)
None

惊不惊喜,意不意外?
问题出在第三行,cuda的定义要在Variable变量的定义之前,不然第3行会把requires_grad这个bool 搞成False。心好累
改成下边这样子就可以了

x = torch.randn(3)
x = Variable(x.cuda(), requires_grad = True)
#x = x.cuda() # 需要你的计算机有GPU
y = x * 2
gradients = torch.FloatTensor([0.1, 1.0, 0.0001])
y.backward(gradients)
x.grad
Variable containing:
 0.2000
 2.0000
 0.0002
[torch.FloatTensor of size 3]

你可能感兴趣的:(Pytorch 使用cuda进行自动求导出现的幺蛾子)