torch.set_default_device¶
- torch.set_default_device(device)[source][source]¶
设置默认的
torch.Tensor
分配在device
上。这不会影响使用显式device
参数调用的工厂函数调用。工厂调用将像传递device
作为参数一样执行。要仅临时更改默认设备而不是全局设置它,请使用
with torch.device(device):
代替。默认设备最初是
cpu
。如果您将默认张量设备设置为另一个设备(例如,cuda
),而没有设备索引,则张量将分配在设备类型的当前设备上,即使在调用torch.cuda.set_device()
之后也是如此。警告
此函数对每次 Python 调用 torch API 都会产生轻微的性能成本(不仅是工厂函数)。如果这给您带来问题,请在 https://github.com/pytorch/pytorch/issues/92701 上发表评论
注意
这不会影响创建与输入共享相同内存的张量的函数,例如:
torch.from_numpy()
和torch.frombuffer()
- 参数
device (device 或 string) – 要设置为默认设备的设备
示例
>>> torch.get_default_device() device(type='cpu') >>> torch.set_default_device('cuda') # current device is 0 >>> torch.get_default_device() device(type='cuda', index=0) >>> torch.set_default_device('cuda') >>> torch.cuda.set_device('cuda:1') # current device is 1 >>> torch.get_default_device() device(type='cuda', index=1) >>> torch.set_default_device('cuda:1') >>> torch.get_default_device() device(type='cuda', index=1)