方法
在CPU上生成,转义至GPU
a = torch.tensor([1,2])
## method 1
device = torch.device('cuda:0') # with referenve to the specific free cuda ID
b = a.to(device)
## method 2
c = a.cuda(0) # with referenve to the specific free cuda ID
在cpu上先生成tensor,然后转义至指定CUDA ID的GPU上
- 优点:方便调试,更加灵活;一般都是在cpu上先创建所有的tensor, 然后进行实验debug的,这样如果报错的话,报错显示会比较友好,方便进行初步的调试。
- 缺点:慢,尤其是频繁地在cpu和gpu之间转义参数的话,会明显增加代码的时间开销。
直接在GPU上生成tensor
device = torch.device('cuda:0') # with referenve to the specific free cuda ID
d = torch.tensor([1,2], device=device) # generate tensor on gpu directly
- 优点:快,省去了从cpu转移到gpu的时间开销。
- 缺点:调试麻烦。一开始就在gpu上实验的话,报错会很玄。一般都是代码在cpu上都debug好了之后,在改在gpu上生成,加快速度。
6.22日补充:最后一种直接在GPU上生成tensor的方法自己试了一下(torch版本0.4.1),发现生成的tensor并不在GPU上:
后来再查找资料发现,FloatTensor这个构造方法并不支持所有type,也就意味着直接在torch.FloatTensor()
的device
参数里指定GPU将出错,有人推荐可以用torch.cuda.FloatTensor
代替:
这点在更高版本的torch(1.3.1)得到了证实:
这…太坑爹了,那好奇这个device参数有啥用?