AssertionError: Torch not compiled with CUDA enabled解决方法

本文档记录了在Windows环境下遇到PyTorch无法使用CUDA的问题,通过卸载并重新安装特定版本的PyTorch(支持CUDA 11.6)成功解决了问题。在更新PyTorch版本后,确认了CUDA的可用性,但需要注意张量操作必须在同一设备上进行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

遇到问题

(base) C:\Users\m1521>python
Python 3.9.7 (default, Sep 16 2021, 16:59:28) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> a = torch.ones((3, 1))
>>> a  = a.cuda(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\ProgramData\Anaconda3\lib\site-packages\torch\cuda\__init__.py", line 221, in _lazy_init
    raise AssertionError("Torch not compiled with CUDA enabled")
AssertionError: Torch not compiled with CUDA enabled

解决方法

卸载torch

(base) C:\Users\m1521>pip uninstall torch
Found existing installation: torch 1.13.1
Uninstalling torch-1.13.1:
  Would remove:
    c:\programdata\anaconda3\lib\site-packages\functorch\*
    c:\programdata\anaconda3\lib\site-packages\torch-1.13.1.dist-info\*
    c:\programdata\anaconda3\lib\site-packages\torch\*
    c:\programdata\anaconda3\lib\site-packages\torchgen\*
    c:\programdata\anaconda3\scripts\convert-caffe2-to-onnx.exe
    c:\programdata\anaconda3\scripts\convert-onnx-to-caffe2.exe
    c:\programdata\anaconda3\scripts\torchrun.exe
Proceed (Y/n)? y
  Successfully uninstalled torch-1.13.1

重新选择新的PyTorch版本解决这个问题:从11.7 变到11.6

在这里插入图片描述
仍然使用pip下载

pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116

测试结果

(base) C:\Users\m1521>python
Python 3.9.7 (default, Sep 16 2021, 16:59:28) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.cuda.is_available()
True
>>> a = torch.ones((3, 1))
>>> a = a.cuda(0)
>>> b = torch.ones((3,1))
>>> a + b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!
>>>
>>> b = torch.ones((3,1)).cuda(0)
>>> a + b
tensor([[2.],
        [2.],
        [2.]], device='cuda:0')
>>>

参考

  1. https://github.com/pytorch/pytorch/issues/30664
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值