快捷方式

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 (devicestring) – 要设置为默认设备的设备

示例

>>> 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)

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

获取面向初学者和高级开发者的深入教程

查看教程

资源

查找开发资源并获得您的问题的解答

查看资源