def try_gpu(i=0):
"如果存在,则返回gpu(i),否则返回CPU()"
if torch.cuda.device_count() >= i+1
return torch.devide(f'cuda:{i}')
return torch.device('cpu')
def try_all_gpus():
"返回所有可用的GPU,如果没有,则返回cpu“
devices = [torch.device(f'cuda{i}' for i in range(torch.cuda.device_count()))]
return devices if devices else [torch.device('cpu')]
1.查询张量所在的设备 x.device
2.在GPU上创建一个随机张量 x = torch.ones(2,3,device = try_gpu())
3.不同GPU上的张量的移动:Z=X.cuda(1)#将X这一张量移到cuda(1)上,实际上是copy
4.GPU上的运算:在GPU上的运算:X+Y,需要保证X,Y在同一个GPU上
5.在GPU上运行神经网络:
net = nn.Sequential(nn.Linear(3,1))
net = net.to(device= try_gpu())
# 在cpu上创建了net,又将net的参数copy移到了cpu:0上了