Pytorch 如何有条件地使用torch.cuda.device()

Pytorch 如何有条件地使用torch.cuda.device(),pytorch,Pytorch,我有一些代码封装在: with torch.cuda.device(self.device): # do a bunch of stuff 在我的\uuuu init\uuuuu中,我有: self.device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu') 但我对如何处理设备是cpu的情况有点困惑。因为torch.cuda.device已明确用于cuda。我应该为函数编写

我有一些代码封装在:

with torch.cuda.device(self.device):
    # do a bunch of stuff
在我的
\uuuu init\uuuuu
中,我有:

self.device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')

但我对如何处理设备是cpu的情况有点困惑。因为
torch.cuda.device
已明确用于
cuda
。我应该为函数编写一个装饰器吗?似乎有点过分了

根据

设备(torch.device或int)–要选择的设备索引如果此参数为负整数或
None
,则为no op

基于此,我们可以使用

with torch.cuda.device(self.device if self.device.type == 'cuda' else None):
    # do a bunch of stuff

self.device
不是CUDA设备时,这将是不可操作的。“device(torch.device或int)–要选择的设备索引。如果此参数为负整数或
None
,则为no op。因此,可能类似于
使用torch.cuda.device(self.device如果self.device.type!=“cuda”否则为None):
可以工作吗?如果没有明确的用例示例,很难说。很好(请随意添加答案,我会接受)!作为一个后续问题,有没有一种全局设置的方法,而不是在我需要使用这个上下文块的任何地方积极搜索?我没有真正使用这个功能,因为我通常会显式地将我的张量和模型参数移动到特定的设备(例如,
model.to('cuda:1')
t=torch.tensor)([1,2,3])。到('cuda:1')
)。但似乎有一个函数可以选择一个设备,可能是一个全局解决方案。啊,对了!出于某种原因,我以为我测试了它,但它不起作用。但现在都完成了。谢谢