import torch
import torch.nn as nn
class model(nn.Module):
def __init__(self):
super(model,self).__init__()
self.mat = torch.randn(2,2)
def forward(self,x):
print('self.mat.device is',self.mat.device)
x = torch.mv(self.mat,x)
return x
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
m = model()
m.to(device)
x = torch.tensor([2.,1.])
x = x.to(device)
m(x)
输出是
self.mat.device is cpu
就在那之后
Traceback (most recent call last):
File "Z:\cudatest.py", line 21, in <module>
print(m(x))
File "E:\Python37\lib\site-packages\torch\nn\modules\module.py", line 532, in __call__
result = self.forward(*input, **kwargs)
File "Z:\cudatest.py", line 11, in forward
x = torch.mv(self.mat,x)
RuntimeError: Expected object of device type cuda but got device type cpu for argument #1 'self' in call to _th_mv