1 torch.device用法,device分成‘cuda’和‘cpu’两种模式,可以通过torch.cuda.current_device()查看当前device模式和对应的index,对应的torch.device有两个参数,第一个是str格式,即cuda或者cpu,第二个是对应的index,是个整型格式,如1,2等,使用如下:
>>> torch.device('cuda:0')
>>> torch.device('cuda', 0) #上面两种等价
device(type='cuda', index=0)
>>> torch.device('cpu')
device(type='cpu')
>>> torch.device('cuda') # current cuda device
device(type='cuda')
>>> torch.device(1) #输入数字默认是cuda模式
device(type='cuda', index=1)
>>> torch.randn((2,3), device=torch.device('cuda:1'))
>>> torch.randn((2,3), device='cuda:1')
>>> torch.randn((2,3), device=1) # legacy
>>> 以上三种等价
>>> torch.randn((2,3)).cuda() #这个也是变成cuda模式
2 梯度计算,一般都是loss.backward(),这里要求loss必须是包含一个数的tensor,因为loss.backward()是loss.backward(torch.Tensor([1]))的缩写,后面的torch.Tensor([1])是一个系数,如果loss是包含多个元素,则后面对应的也要多个元素的系数,使用示例:
x = torch.ones(3, requires_grad=True)
y = x * 1024
y.backward()
print(x.grad)
>>> 这种会报错,因为y有多个元素
x = torch.ones(3, requires_grad=True)
y = x * 1024
y.backward(torch.tensor([1,0.1,0.01])
print(x.grad)
>>> 这种是成功的,结果是 tensor([1024.0000, 102.4000, 10.2400])