一般来说我们最常见到的用法是这样的:
device= torch.device("cuda"if torch.cuda.is_available()else"cpu")
同:
if torch.cuda.is_available():
device= torch.device("cuda")else:
device= torch.device("cpu")
这个device的用处是作为Tensor或者Model被分配到的位置。因此,在构建device对象后,紧跟的代码往往是:
data= data.to(device)
model= Model(...).to(device)
表示将构建的张量或者模型分配到相应的设备上。
更一般的,可以通过:
torch.device('cuda',0)
torch.device('cuda:0')
来指定使用的具体设备。如果没有显式指定设备序号的话则使用torch.cuda.current_device()对应的序号。