torch.set_default_device¶
- torch.set_default_device(device)[源码][源码]¶
设置默认的
torch.Tensor
分配到device
上。这不会影响那些带有明确device
参数的工厂函数的调用。工厂函数调用将像传入了device
参数一样执行。若要仅暂时更改默认设备,而非全局设置,请改用
with torch.device(device):
。默认设备初始为
cpu
。如果您将默认张量设备设置为另一个设备(例如cuda
),但没有指定设备索引,张量将分配到该设备类型当前的设备上,即使在调用了torch.cuda.set_device()
之后也是如此。警告
此函数会对每次调用 torch API 的 Python 代码(不仅仅是工厂函数)带来轻微的性能开销。如果这给您带来了问题,请在 https://github.com/pytorch/pytorch/issues/92701 上评论反馈
注意
这不会影响创建与输入共享相同内存的函数,例如:
torch.from_numpy()
和torch.frombuffer()
- 参数
device (设备 或 字符串) – 要设置为默认值的设备
示例
>>> 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)