Pythonアプリケーション実行時に "AssertionError: Torch not compiled with CUDA enabled" が発生する - Python

Pythonアプリケーション実行時に "AssertionError: Torch not compiled with CUDA enabled" が発生する現象と対処法の紹介です。

現象

アプリケーションの実行時、特に処理時に以下のエラーが発生します。
エラーメッセージ
AssertionError: Torch not compiled with CUDA enabled

または、
エラーメッセージ
raise AssertionError("Torch not compiled with CUDA enabled")

原因

GPUを利用する環境で、インストールされているTorch / PyTochのバージョンがCPU専用バージョンであることが原因です。

対処法

PyTochのアンインストール

CPU専用版のPyTochをアンインストールします。コマンドプロンプトまたは、venv環境で次のコマンドを実行します。
pip uninstall torch

キャッシュのクリア

次のコマンドを実行し、キャッシュをクリアします。
pip cache purge

PyTochのインストール

PyTochをインストールします。このとき、アプリによっては、最新版が動作環境でない場合もあるため、インストールするPyTochによって実行するコマンドが異なります。
コマンドは(https://pytorch.org/get-started/previous-versions/)にて確認できます。

PyToch 2.2系では新しすぎて動作しないアプリの場合は、PyToch 2.1系または、2.0系をインストールします。
PyToch 2.2系 CUDA 11.8
pip install torch==2.2.2 torchvision==0.17.2 torchaudio==2.2.2 --index-url https://download.pytorch.org/whl/cu118
PyToch 2.2系 CUDA 12.1
pip install torch==2.2.2 torchvision==0.17.2 torchaudio==2.2.2 --index-url https://download.pytorch.org/whl/cu121
PyToch 2.1系 CUDA 11.8
pip install torch==2.1.2 torchvision==0.16.2 torchaudio==2.1.2 --index-url https://download.pytorch.org/whl/cu118
PyToch 2.1系 CUDA 12.1
pip install torch==2.1.2 torchvision==0.16.2 torchaudio==2.1.2 --index-url https://download.pytorch.org/whl/cu121
PyToch 2.0.1 CUDA 11.8
pip install torch==2.0.1 torchvision==0.15.2 torchaudio==2.0.2 --index-url https://download.pytorch.org/whl/cu118
PyToch 2.0 CUDA 11.8
pip install torch==2.0.0 torchvision==0.15.1 torchaudio==2.0.1 --index-url https://download.pytorch.org/whl/cu118
著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。
掲載日: 2024-05-17
iPentec all rights reserverd.