Shortcuts

torch.set_default_device

torch.set_default_device(device)[源码]

设置默认的 torch.Tensordevice 上分配。这不会影响带有显式 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()

Parameters

设备 (设备字符串) – 要设置为默认的设备

示例:

>>> torch.get_default_device()
device(type='cpu')
>>> torch.set_default_device('cuda')  # 当前设备是 0
>>> torch.get_default_device()
device(type='cuda', index=0)
>>> torch.set_default_device('cuda')
>>> torch.cuda.set_device('cuda:1')  # 当前设备是 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)
优云智算