如何告诉PyTorch不使用GPU?

87

我希望进行CPU和GPU之间的一些时间比较以及一些分析,并想知道是否有办法告诉不使用GPU,而是仅使用CPU?我意识到我可以安装另一个仅支持CPU的,但希望有更简单的方法。

6个回答

86
在运行代码之前,请运行此Shell命令来告诉torch没有GPU可用:
export CUDA_VISIBLE_DEVICES=""

这将告诉它仅使用一个GPU(id为0的那个),以此类推:

export CUDA_VISIBLE_DEVICES="0"

2
这似乎仍然给我一个错误UserWarning:CUDA初始化:在您的系统上找不到NVIDIA驱动程序 - Chris Stryczynski
@UmangGupta - 我在代码中的许多地方都调用了.cuda()。这是否意味着代码默认配置为使用GPU?如果是,我应该做什么更改才能使其在GPU上运行? - Shreyesh Desai
5
你可以将.cuda()替换为.cpu()来确保你的代码使用 CPU 运行。这很麻烦,但我认为这是最简单的方法。对于未来,在顶部声明 device 并使用 .to 将模型/张量移动到设备上。关于如何做到这一点...请参考 MBT 的回答或此链接 https://dev59.com/plQJ5IYBdhLWcg3wr363#53332659。 - Umang Gupta
一旦我这样做了,我该如何重新启用它? - Salih
@Salih 你可以使用命令 export CUDA_VISIBLE_DEVICES="0" 来启用 GPU:0。 - Umang Gupta

57
我只想补充一点,也可以在PyTorch代码中这样做: 以下是从PyTorch 0.4.0迁移指南中摘取的一个小例子:
# at beginning of the script
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

...

# then whenever you get a new Tensor or Module
# this won't copy if they are already on the desired device
input = data.to(device)
model = MyModule(...).to(device)

我认为这个例子已经很好地解释了。但如果有任何问题,请随时提出!
使用上面示例中的语法的一个巨大优势是,您可以创建在CPU上运行的代码,如果没有GPU可用,也可以在GPU上运行而不更改任何一行。

与使用torch.cuda.is_available()if语句不同,您也可以将设备设置为CPU,如下所示:

device = torch.device("cpu")

此外,您可以使用device标志在所需的设备上创建张量:

mytensor = torch.rand(5, 5, device=device)

这将在之前指定的{{device}}上直接创建张量。
我想指出,您可以使用此语法在{{CPU}}和{{GPU}}之间切换,也可以在不同的{{GPU}}之间切换。
希望这对您有所帮助!

21

使用Python最简单的方法是:

os.environ["CUDA_VISIBLE_DEVICES"]=""

1
我没有与CUDA兼容的GPU,在我的情况下,这个解决方案不起作用(警告仍然出现)。 - ferrum
1
这不起作用。我有一张GPU,它仍在使用中。 - Salih

11

强制使用CPU的方法有多种:

  1. Set default tensor type:

    torch.set_default_tensor_type(torch.FloatTensor)
    
  2. Set device and consistently reference when creating tensors:
    (with this you can easily switch between GPU and CPU)

    device = 'cpu'
    # ...
    x = torch.rand(2, 10, device=device)
    
  3. Hide GPU from view:

    import os
    
    os.environ["CUDA_VISIBLE_DEVICES"]=""
    

8

通用

如先前的答案所示,您可以使用以下方式在CPU上运行PyTorch:

device = torch.device("cpu")

对训练模型进行比较

我想补充一下如何在 CPU 上加载以前训练好的模型(示例取自PyTorch 文档)。

注意:确保输入到模型中的所有数据也在 CPU 上。

推荐的加载方式

model = TheModelClass(*args, **kwargs)
model.load_state_dict(torch.load(PATH, map_location=torch.device("cpu")))

加载整个模型

model = torch.load(PATH, map_location=torch.device("cpu"))

0
这是一个真实世界的例子:原始带GPU的函数与新的带CPU的函数。
来源:https://github.com/zllrunning/face-parsing.PyTorch/blob/master/test.py 在我的情况下,我已经编辑了这4行代码:
#totally new line of code
device=torch.device("cpu")



#net.cuda()
net.to(device)

#net.load_state_dict(torch.load(cp))
net.load_state_dict(torch.load(cp, map_location=torch.device('cpu')))

#img = img.cuda()
img = img.to(device)


#new_function_with_cpu
def evaluate(image_path='./imgs/116.jpg', cp='cp/79999_iter.pth'):
    device=torch.device("cpu")
    n_classes = 19
    net = BiSeNet(n_classes=n_classes)
    #net.cuda()
    net.to(device)
    #net.load_state_dict(torch.load(cp))
    net.load_state_dict(torch.load(cp, map_location=torch.device('cpu')))
    net.eval()

    to_tensor = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),])

    with torch.no_grad():
        img = Image.open(image_path)
        image = img.resize((512, 512), Image.BILINEAR)
        img = to_tensor(image)
        img = torch.unsqueeze(img, 0)
        #img = img.cuda()
        img = img.to(device)
        out = net(img)[0]
        parsing = out.squeeze(0).cpu().numpy().argmax(0)
        return parsing


















#original_function_with_gpu


def evaluate(image_path='./imgs/116.jpg', cp='cp/79999_iter.pth'):

    n_classes = 19
    net = BiSeNet(n_classes=n_classes)
    net.cuda()
    net.load_state_dict(torch.load(cp))
    net.eval()

    to_tensor = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),])

    with torch.no_grad():
        img = Image.open(image_path)
        image = img.resize((512, 512), Image.BILINEAR)
        img = to_tensor(image)
        img = torch.unsqueeze(img, 0)
        img = img.cuda()
        out = net(img)[0]
        parsing = out.squeeze(0).cpu().numpy().argmax(0)
        return parsing






网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接