无GPU环境中运行出错解决方法:AssertionError: Torch not compiled with CUDA enabled

发布时间 2023-11-16 23:11:39作者: 夕月一弯

在執行pytorch代碼的時候,突然看到報錯

AssertionError: Torch not compiled with CUDA enabled

這說明了

1. 你pytoch确实安装了

2. 你安装的是cpu版本

作为验证,你可以在python编辑器输入下列代码

如果要在无GPU环境中运行,需要进行一些修改。

1.  情况一:将出现 ‘gpu:0’ 的地方修改为 ‘cpu:0’

例如:将如下代码修改为

input_ids_tensor = torch.tensor([encoded['input_ids']]).to('gpu:0')
attention_mask_tensors = torch.tensor([encoded['attention_mask']]).to('gpu:0')
model = BertModel.from_pretrained('bert-base-uncased',output_hidden_states=True).to('gpu:0')

修改为

input_ids_tensor = torch.tensor([encoded['input_ids']]).to('cpu:0')
attention_mask_tensors = torch.tensor([encoded['attention_mask']]).to('cpu:0')
model = BertModel.from_pretrained('bert-base-uncased', output_hidden_states=True).to('cpu:0')

2. 情况二:在代码开始加上以下内容:

if torch.cuda.is_available():
    device = torch.device("cuda")
    print('There are %d GPU(s) available.' % torch.cuda.device_count())
    print('We will use the GPU:', torch.cuda.get_device_name(0))
else:
    print('No GPU available, using the CPU instead.')
    device = torch.device("cpu")

然后将出现 .cuda()的地方改成 .to(device) 就可以在无gpu的环境中运行。