Pytorch.device使用及理解

Pytorch to(device)

Pytorch.device理解

device=cuda之类的
转载合并了一下其他同学的讲解.
链接: https://blog.csdn.net/shaopeng568/article/details/95205345
torch.device代表将torch.Tensor分配到的设备的对象。torch.device包含一个设备类型(‘cpu’或‘cuda’)和可选的设备序号。如果设备序号不存在,则为当前设备。如:torch.Tensor用设备构建‘cuda’的结果等同于‘cuda:X’,其中X是torch.cuda.current_device()的结果。

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model.to(device)

这两行代码放在读取数据之前。

mytensor = my_tensor.to(device)

这行代码的意思是将所有最开始读取数据时的tensor变量copy一份到device所指定的GPU上去,之后的运算都在GPU上进行。

这句话需要写的次数等于需要保存GPU上的tensor变量的个数;一般情况下这些tensor变量都是最开始读数据时的tensor变量,后面衍生的变量自然也都在GPU上.

如果是多个GPU
在代码中的使用方法为:

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = Model()
if torch.cuda.device_count() > 1:
  model = nn.DataParallel(model,device_ids=[0,1,2])

pytorch中model=model.to(device)用法

https://blog.csdn.net/weixin_36670529/article/details/106068761
https://blog.csdn.net/weixin_36670529/article/details/106068761
device=torch.device(“cpu”)代表的使用cpu,而device=torch.device(“cuda”)则代表的使用GPU。
当我们指定了设备之后,就需要将模型加载到相应设备中,此时需要使用model=model.to(device),将模型加载到相应的设备中。将由GPU保存的模型加载到CPU上。