为什么我们要在pytorch中使用to(device)方法?
torch.Tensor.to
是多用途方法。
不仅可以进行类型转换,还可以进行 CPU 到 GPU 张量移动以及 GPU 到 CPU 张量移动:
tensor = torch.randn(2, 2)
print(tensor)
tensor = tensor.to(torch.float64)
print(tensor) #dtype=torch.float64
tensor = tensor.to("cuda")
print(tensor) #device='cuda:0', dtype=torch.float64)
tensor = tensor.to("cpu")
print(tensor) #dtype=torch.float64
tensor = tensor.to(torch.float32)
print(tensor) # won't print dtype=torch.float32 since it is by default
Run Code Online (Sandbox Code Playgroud)
由于CPU和GPU是不同种类的存储器,因此它们必须有一种通信方式。这就是为什么我们有to("cuda")
,并且to("cpu")
我们调用张量。
通常当您加载训练数据集(图像)时:
to("cuda")
您可以像这样创建张量并将它们移动到 GPU。
torch.zeros(1000).to("cuda")
Run Code Online (Sandbox Code Playgroud)
但有一个技巧,有时你甚至可以将它们直接加载到 GPU,而不会弄乱 CPU。
torch.zeros(1000, device="gpu")
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4215 次 |
最近记录: |