この記事の対象読者
- Pythonの基本文法(pip、仮想環境)を理解している方
- PyTorchやTensorFlowでGPUを使いたいと考えている方
- 「CUDAのインストールで何度も失敗した」経験がある方
- ローカルでLLMや画像生成AIを動かしたい方
この記事で得られること
- CUDA・cuDNN・PyTorchの依存関係が複雑な「本当の理由」の理解
- 環境構築で失敗しないための具体的な手順とコード
- トラブル発生時の原因特定と解決方法
- Docker・conda・pip それぞれの使い分け方
この記事で扱わないこと
- GPUハードウェアの選び方(RTX 4090 vs A100 など)
- CUDA C++によるカーネル開発
- クラウドGPU(AWS、GCP、Lambda Labs等)の設定
1. CUDA地獄との出会い
「torch.cuda.is_available() が False を返す...」
ローカルAI開発を始めた人なら、この絶望を一度は経験したことがあるはず。私も例外ではなかった。
RTX 3080を積んだマシンを手に入れ、意気揚々とStable Diffusionを動かそうとした日のこと。公式サイトの通りに pip install torch を実行し、いざ起動。
RuntimeError: CUDA error: no kernel image is available for execution on the device
「え、GPUあるのに?」
そこから始まった3日間の地獄。CUDAをインストールし直し、cuDNNを入れ、PyTorchを再インストール。何度やっても動かない。ググって出てくる情報は断片的で、しかも古い。
最終的に原因は「PyTorchのwheelに含まれるCUDAバージョンと、システムにインストールされたCUDAドライバのバージョン不整合」だった。たった一行のコマンドミスで、丸3日を失ったのだ。
この記事は、過去の自分に送る手紙でもある。「CUDA地獄」の正体を理解し、二度と同じ轍を踏まないための完全ガイドだ。
ここまでで、CUDA地獄がどれほど厄介かイメージできたと思う。次は、この問題を理解するために必要な前提知識を整理しよう。
2. 前提知識の確認
本題に入る前に、この記事で使う用語を整理しておく。
2.1 GPU(Graphics Processing Unit)とは
もともと画像処理用に設計されたプロセッサ。CPUが「少数の複雑な計算を高速に」処理するのに対し、GPUは「大量の単純な計算を並列に」処理することに特化している。ディープラーニングの行列演算と相性が抜群に良い。
2.2 CUDA(Compute Unified Device Architecture)とは
NVIDIAが開発したGPU向けの並列コンピューティングプラットフォーム。簡単に言えば「NVIDIAのGPUで汎用計算をするための仕組み」。CUDAがないと、PyTorchはGPUを認識できない。
2.3 cuDNN(CUDA Deep Neural Network library)とは
NVIDIA製のディープラーニング用ライブラリ。畳み込み演算やRNN、Transformerなど、ニューラルネットワークでよく使う処理を高速化してくれる。PyTorchやTensorFlowの裏側で密かに働いている縁の下の力持ち。
2.4 NVIDIAドライバとは
OSとGPUハードウェアを繋ぐソフトウェア。ドライバのバージョンによって、対応できるCUDAのバージョンが決まる。古いドライバでは新しいCUDAが動かない。
2.5 Compute Capability(CC)とは
GPUアーキテクチャの世代を表す数値。例えばRTX 3000シリーズは 8.6、RTX 4000シリーズは 8.9。PyTorchのwheelは特定のCCに対応しており、古すぎるGPUだとそもそもサポート対象外になる。
これらの用語が押さえられたら、次に進もう。なぜこれらの依存関係がこんなに複雑なのか、その背景を見ていく。
3. なぜCUDA地獄は発生するのか
3.1 4層構造の依存関係
CUDA地獄の根本原因は、4つのレイヤーが相互に依存していることにある。
┌─────────────────────────────────────┐
│ PyTorch / TensorFlow │ ← アプリケーション層
├─────────────────────────────────────┤
│ cuDNN │ ← ライブラリ層
├─────────────────────────────────────┤
│ CUDA Toolkit │ ← ランタイム層
├─────────────────────────────────────┤
│ NVIDIA Driver │ ← ドライバ層
├─────────────────────────────────────┤
│ GPU Hardware (CC: 8.6 など) │ ← ハードウェア層
└─────────────────────────────────────┘
各レイヤーには「このバージョンと組み合わせて使ってね」という制約がある。そして厄介なことに、この制約は単純な「以上・以下」ではなく、特定の組み合わせのみが動作する。
3.2 バージョン互換性の非対称性
ここが最も混乱を招くポイントだ。
NVIDIAドライバは「前方互換性」がある:
ドライバ 535.xx → CUDA 11.x, 12.0, 12.1, 12.2 すべて動作
PyTorchのwheelは「特定バージョン」に固定:
torch==2.5.1+cu124 → CUDA 12.4用にビルドされている
→ CUDA 11.8環境では動作しない(かもしれない)
つまり、「最新のドライバを入れておけばOK」というわけではなく、「PyTorchがどのCUDAバージョンでビルドされているか」を意識する必要がある。
3.3 pip install torch の罠
何も考えずに pip install torch を実行すると、PyPIからCPU版がインストールされる。GPU版が欲しい場合は、明示的にCUDAバージョンを指定したURLからインストールする必要がある。
# これはCPU版がインストールされる(罠)
pip install torch
# GPU版はこちら(CUDA 12.4の場合)
pip install torch --index-url https://download.pytorch.org/whl/cu124
この仕様を知らずに「GPUあるのに動かない!」と悩む人が後を絶たない。
3.4 conda と pip の混在問題
conda環境でpipを使うと、依存関係の解決がカオスになる。condaはconda-forgeやnvidiaチャンネルから、pipはPyPIやPyTorch独自のwheelサーバーから取得する。両者の依存関係ツリーは独立しているため、矛盾が発生しやすい。
なぜこんなに複雑なのかが理解できたところで、抽象的な概念から具体的な解決策へと進んでいこう。
4. 依存関係の全体像を把握する
4.1 PyTorch バージョン別 CUDA 対応表(2025年1月時点)
| PyTorch | 対応CUDA | Python | 備考 |
|---|---|---|---|
| 2.9.0 | 12.6, 12.8, 13.0 | 3.9-3.12 | Blackwell対応 |
| 2.8.0 | 12.6, 12.8, 12.9 | 3.9-3.12 | 最新安定版 |
| 2.7.1 | 11.8, 12.6, 12.8 | 3.9-3.12 | CUDA 11.8最終対応 |
| 2.5.1 | 11.8, 12.1, 12.4 | 3.9-3.12 | 広く使われている |
| 2.4.x | 11.8, 12.1, 12.4 | 3.8-3.12 | Python 3.8最終 |
4.2 NVIDIAドライバと対応CUDAの関係
| ドライババージョン | 対応CUDA(最大) |
|---|---|
| 560.xx 以上 | CUDA 12.6 |
| 550.xx 以上 | CUDA 12.4 |
| 535.xx 以上 | CUDA 12.2 |
| 525.xx 以上 | CUDA 12.0 |
| 520.xx 以上 | CUDA 11.8 |
重要: ドライバは「前方互換」。新しいドライバは古いCUDAもサポートする。
4.3 GPUアーキテクチャとCompute Capability
| アーキテクチャ | CC | 代表的なGPU |
|---|---|---|
| Blackwell | 10.0, 12.0 | RTX 5090, 5080 |
| Ada Lovelace | 8.9 | RTX 4090, 4080, 4070 |
| Ampere | 8.6 | RTX 3090, 3080, A100 |
| Turing | 7.5 | RTX 2080, T4 |
| Volta | 7.0 | V100 |
| Pascal | 6.1 | GTX 1080, P100 |
注意: PyTorch 2.5以降、Pascal(CC 6.x)のサポートは縮小傾向。古いGPUを使っている場合は要確認。
依存関係の全体像が掴めたところで、具体的な実装例を見ていこう。
5. 実際に環境を構築してみよう
5.1 現在の環境を確認するスクリプト
まずは自分の環境を正確に把握することから始める。以下のスクリプトをコピペして実行しよう。
"""
GPU環境診断スクリプト
使い方: python check_gpu_env.py
必要なパッケージ: なし(標準ライブラリのみ)
"""
import subprocess
import sys
def run_command(cmd):
"""コマンドを実行して結果を返す"""
try:
result = subprocess.run(
cmd, shell=True, capture_output=True, text=True, timeout=30
)
return result.stdout.strip() if result.returncode == 0 else None
except Exception:
return None
def check_nvidia_driver():
"""NVIDIAドライバのバージョンを確認"""
output = run_command("nvidia-smi --query-gpu=driver_version --format=csv,noheader")
if output:
print(f"[OK] NVIDIA Driver: {output}")
return output
else:
print("[NG] NVIDIA Driver: 検出できません")
return None
def check_cuda_version():
"""nvidia-smiから対応CUDA バージョンを確認"""
output = run_command("nvidia-smi --query-gpu=compute_cap --format=csv,noheader")
cc = output if output else "不明"
# nvidia-smiのヘッダーからCUDAバージョンを取得
smi_output = run_command("nvidia-smi")
if smi_output and "CUDA Version:" in smi_output:
for line in smi_output.split("\n"):
if "CUDA Version:" in line:
cuda_ver = line.split("CUDA Version:")[1].strip().split()[0]
print(f"[OK] 対応CUDA (ドライバ上限): {cuda_ver}")
print(f"[OK] Compute Capability: {cc}")
return cuda_ver
print(f"[--] Compute Capability: {cc}")
return None
def check_pytorch():
"""PyTorchのインストール状況を確認"""
try:
import torch
print(f"[OK] PyTorch: {torch.__version__}")
print(f"[OK] CUDA available: {torch.cuda.is_available()}")
if torch.cuda.is_available():
print(f"[OK] CUDA version (PyTorch): {torch.version.cuda}")
print(f"[OK] cuDNN version: {torch.backends.cudnn.version()}")
print(f"[OK] GPU: {torch.cuda.get_device_name(0)}")
return True
except ImportError:
print("[--] PyTorch: インストールされていません")
return False
def main():
print("=" * 50)
print("GPU環境診断レポート")
print("=" * 50)
print(f"\nPython: {sys.version}")
print()
check_nvidia_driver()
check_cuda_version()
print()
check_pytorch()
print("\n" + "=" * 50)
print("診断完了")
print("=" * 50)
if __name__ == "__main__":
main()
5.2 実行結果の例
上記のスクリプトを実行すると、以下のような出力が得られる:
==================================================
GPU環境診断レポート
==================================================
Python: 3.11.5 (main, Sep 11 2023, 13:54:46) [GCC 11.2.0]
[OK] NVIDIA Driver: 550.54.14
[OK] 対応CUDA (ドライバ上限): 12.4
[OK] Compute Capability: 8.6
[OK] PyTorch: 2.5.1+cu124
[OK] CUDA available: True
[OK] CUDA version (PyTorch): 12.4
[OK] cuDNN version: 90100
[OK] GPU: NVIDIA GeForce RTX 3080
==================================================
診断完了
==================================================
この出力で CUDA available: False が表示された場合、次のセクションの設定ファイルを使って環境を再構築しよう。
5.3 設定ファイルのテンプレート
以下の3種類の設定ファイルを用意した。用途に応じて選択してほしい。
開発環境用(requirements-dev.txt)
# requirements-dev.txt
# 開発環境用 - CUDA 12.4対応
# 使い方: pip install -r requirements-dev.txt --index-url https://download.pytorch.org/whl/cu124
# PyTorch(CUDA 12.4)
--extra-index-url https://download.pytorch.org/whl/cu124
torch==2.5.1
torchvision==0.20.1
torchaudio==2.5.1
# 開発ツール
ipython>=8.0.0
jupyter>=1.0.0
tensorboard>=2.15.0
# デバッグ用
py-spy>=0.3.14
memory-profiler>=0.61.0
本番環境用(requirements-prod.txt)
# requirements-prod.txt
# 本番環境用 - バージョン固定で再現性を確保
# 使い方: pip install -r requirements-prod.txt --index-url https://download.pytorch.org/whl/cu124
# PyTorch(CUDA 12.4)- バージョン完全固定
--extra-index-url https://download.pytorch.org/whl/cu124
torch==2.5.1+cu124
torchvision==0.20.1+cu124
torchaudio==2.5.1+cu124
# 推論用ライブラリ
transformers==4.47.0
accelerate==1.2.1
safetensors==0.4.5
# サーバー
fastapi==0.115.6
uvicorn[standard]==0.34.0
CI/テスト環境用(requirements-test.txt)
# requirements-test.txt
# CI/テスト環境用 - CPU版で高速にテスト
# 使い方: pip install -r requirements-test.txt
# PyTorch(CPU版 - CI環境ではGPU不要な場合が多い)
--extra-index-url https://download.pytorch.org/whl/cpu
torch==2.5.1
torchvision==0.20.1
torchaudio==2.5.1
# テストツール
pytest>=8.0.0
pytest-cov>=4.1.0
pytest-xdist>=3.5.0
# 型チェック
mypy>=1.8.0
Docker用(Dockerfile)
# Dockerfile
# NVIDIA公式イメージをベースにした本番環境用
# ビルド: docker build -t myapp:cuda .
# 実行: docker run --gpus all myapp:cuda
FROM nvidia/cuda:12.4.0-cudnn-runtime-ubuntu22.04
# タイムゾーン設定(インタラクティブ入力を回避)
ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=Asia/Tokyo
# システムパッケージ
RUN apt-get update && apt-get install -y \
python3.11 \
python3.11-venv \
python3-pip \
git \
&& rm -rf /var/lib/apt/lists/*
# Python設定
RUN ln -sf /usr/bin/python3.11 /usr/bin/python
WORKDIR /app
# PyTorchインストール
RUN pip install --no-cache-dir \
torch==2.5.1 \
torchvision==0.20.1 \
torchaudio==2.5.1 \
--index-url https://download.pytorch.org/whl/cu124
# アプリケーションコード
COPY . .
RUN pip install --no-cache-dir -r requirements-prod.txt
# ヘルスチェック
HEALTHCHECK --interval=30s --timeout=10s \
CMD python -c "import torch; assert torch.cuda.is_available()"
CMD ["python", "main.py"]
docker-compose用(docker-compose.yml)
# docker-compose.yml
# 使い方: docker compose up -d
services:
app:
build: .
runtime: nvidia
environment:
- NVIDIA_VISIBLE_DEVICES=all
- NVIDIA_DRIVER_CAPABILITIES=compute,utility
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
volumes:
- ./data:/app/data
- ./models:/app/models
ports:
- "8000:8000"
restart: unless-stopped
基本的な使い方をマスターしたので、次はより実践的なユースケースを見ていこう。
6. よくあるエラーと対処法
| エラーメッセージ | 原因 | 対処法 |
|---|---|---|
torch.cuda.is_available() が False
|
CPU版PyTorchがインストールされている |
--index-url https://download.pytorch.org/whl/cu124 を付けて再インストール |
CUDA error: no kernel image is available |
GPUのCompute Capabilityに対応していないPyTorch | PyTorchのバージョンを確認、CCに対応したビルドを使用 |
CUDA out of memory |
GPUメモリ不足 | バッチサイズを小さく、torch.cuda.empty_cache() を呼ぶ、torch_dtype=torch.float16 を使用 |
libcudnn.so: cannot open shared object file |
cuDNNがインストールされていない |
conda install cudnn または Docker使用を推奨 |
CUDA driver version is insufficient |
ドライバが古い | NVIDIAドライバを更新(550.xx以上推奨) |
RuntimeError: CUDA error: invalid device ordinal |
指定したGPU番号が存在しない |
CUDA_VISIBLE_DEVICES 環境変数を確認 |
ImportError: libcublas.so.12 |
CUDAライブラリのパスが通っていない |
LD_LIBRARY_PATH を設定、または Docker使用 |
ユースケースが把握できたところで、この記事を読んだ後の学習パスを確認しよう。
7. ユースケース別ガイド
7.1 ユースケース1: Stable Diffusionをローカルで動かしたい
想定読者: 画像生成AIを自分のPCで試したい人
推奨構成: RTX 3060以上、VRAM 8GB以上、CUDA 12.4
サンプルコード:
"""
Stable Diffusion 環境構築スクリプト
使い方: python setup_sd.py
"""
import subprocess
import sys
def setup_stable_diffusion():
"""Stable Diffusion用の環境を構築する"""
# PyTorch(CUDA 12.4)をインストール
subprocess.check_call([
sys.executable, "-m", "pip", "install",
"torch==2.5.1", "torchvision==0.20.1",
"--index-url", "https://download.pytorch.org/whl/cu124"
])
# diffusers関連をインストール
subprocess.check_call([
sys.executable, "-m", "pip", "install",
"diffusers>=0.31.0",
"transformers>=4.47.0",
"accelerate>=1.2.0",
"safetensors>=0.4.0",
"xformers>=0.0.28" # メモリ効率化
])
print("セットアップ完了!")
def test_generation():
"""動作確認用の画像生成テスト"""
import torch
from diffusers import StableDiffusionPipeline
# GPU確認
if not torch.cuda.is_available():
raise RuntimeError("CUDAが利用できません")
print(f"GPU: {torch.cuda.get_device_name(0)}")
print(f"VRAM: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.1f} GB")
# パイプライン読み込み(float16でメモリ節約)
pipe = StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
torch_dtype=torch.float16,
safety_checker=None
).to("cuda")
# メモリ効率化
pipe.enable_attention_slicing()
# テスト生成
image = pipe("a photo of an astronaut riding a horse on mars").images[0]
image.save("test_output.png")
print("test_output.png に保存しました")
if __name__ == "__main__":
setup_stable_diffusion()
test_generation()
7.2 ユースケース2: LLMをローカルで推論したい
想定読者: ChatGPT風のAIを自分のPCで動かしたい人
推奨構成: RTX 4070以上、VRAM 12GB以上、CUDA 12.4
サンプルコード:
"""
ローカルLLM推論スクリプト
使い方: python local_llm.py
必要VRAM: 8GB以上(量子化モデル使用時)
"""
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
def setup_llm(model_name: str = "microsoft/phi-2"):
"""
ローカルLLMをセットアップする
Args:
model_name: HuggingFaceのモデル名
Returns:
model, tokenizer のタプル
"""
# GPU確認
if not torch.cuda.is_available():
raise RuntimeError("CUDAが利用できません")
device = "cuda"
print(f"使用GPU: {torch.cuda.get_device_name(0)}")
# 量子化設定(VRAMが少ない場合)
vram_gb = torch.cuda.get_device_properties(0).total_memory / 1024**3
if vram_gb < 12:
print(f"VRAM {vram_gb:.1f}GB: 4bit量子化を使用")
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.float16
)
else:
print(f"VRAM {vram_gb:.1f}GB: float16を使用")
quantization_config = None
# トークナイザー読み込み
tokenizer = AutoTokenizer.from_pretrained(model_name)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
# モデル読み込み
model = AutoModelForCausalLM.from_pretrained(
model_name,
quantization_config=quantization_config,
torch_dtype=torch.float16,
device_map="auto",
trust_remote_code=True
)
return model, tokenizer
def generate_response(model, tokenizer, prompt: str, max_length: int = 200):
"""テキスト生成を行う"""
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=max_length,
do_sample=True,
temperature=0.7,
top_p=0.9,
pad_token_id=tokenizer.pad_token_id
)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
return response
if __name__ == "__main__":
model, tokenizer = setup_llm("microsoft/phi-2")
prompt = "Pythonでフィボナッチ数列を計算する関数を書いてください。"
response = generate_response(model, tokenizer, prompt)
print(response)
7.3 ユースケース3: 機械学習モデルの学習を高速化したい
想定読者: 自分のデータでモデルを学習させたい人
推奨構成: RTX 3080以上、VRAM 10GB以上、CUDA 12.4
サンプルコード:
"""
GPU活用のベストプラクティス - 学習高速化
使い方: python train_with_gpu.py
"""
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset
from torch.cuda.amp import autocast, GradScaler
import time
def create_dummy_data(n_samples: int = 10000, n_features: int = 100):
"""ダミーデータを生成"""
X = torch.randn(n_samples, n_features)
y = torch.randint(0, 10, (n_samples,))
return X, y
def train_with_mixed_precision(model, train_loader, epochs: int = 10):
"""
Mixed Precision Training(AMP)を使った高速学習
float16とfloat32を自動で切り替え、メモリ使用量と計算時間を削減
"""
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
# AMP用のスケーラー
scaler = GradScaler()
print(f"Training on: {device}")
print(f"Mixed Precision: Enabled")
start_time = time.time()
for epoch in range(epochs):
model.train()
total_loss = 0.0
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
# autocastブロック内でfloat16を自動適用
with autocast():
output = model(data)
loss = criterion(output, target)
# スケーリングしてバックプロパゲーション
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
total_loss += loss.item()
avg_loss = total_loss / len(train_loader)
print(f"Epoch {epoch+1}/{epochs}, Loss: {avg_loss:.4f}")
elapsed = time.time() - start_time
print(f"\n学習完了: {elapsed:.2f}秒")
return model
class SimpleModel(nn.Module):
"""シンプルな分類モデル"""
def __init__(self, n_features: int = 100, n_classes: int = 10):
super().__init__()
self.layers = nn.Sequential(
nn.Linear(n_features, 256),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(256, 128),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(128, n_classes)
)
def forward(self, x):
return self.layers(x)
if __name__ == "__main__":
# GPU情報表示
if torch.cuda.is_available():
print(f"GPU: {torch.cuda.get_device_name(0)}")
print(f"VRAM: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.1f} GB")
else:
print("警告: GPUが利用できません")
# データ準備
X, y = create_dummy_data(n_samples=50000, n_features=100)
dataset = TensorDataset(X, y)
train_loader = DataLoader(dataset, batch_size=256, shuffle=True, num_workers=4, pin_memory=True)
# モデル作成と学習
model = SimpleModel(n_features=100, n_classes=10)
trained_model = train_with_mixed_precision(model, train_loader, epochs=10)
# モデル保存
torch.save(trained_model.state_dict(), "model.pth")
print("model.pth に保存しました")
8. 学習ロードマップ
この記事を読んだ後、次のステップとして以下をおすすめする。
初級者向け(まずはここから)
- PyTorch公式チュートリアル - 基本的なテンソル操作から学べる
- NVIDIA CUDA インストールガイド - 公式の手順を一度読んでおく
- PyTorch Previous Versions - バージョン別のインストールコマンド一覧
中級者向け(実践に進む)
- nvidia-docker - コンテナでのGPU利用をマスター
- PyTorch Profiler - パフォーマンスボトルネックの特定
- HuggingFace Accelerate - 分散学習やmixed precisionを簡単に
上級者向け(さらに深く)
- CUDA C++ Programming Guide - CUDAの内部動作を理解
- PyTorch Internals - PyTorchの拡張方法
- triton-lang - カスタムGPUカーネルを書く
9. まとめ
この記事では、CUDA地獄について以下を解説した:
- CUDA地獄の正体は「4層の依存関係」と「バージョン互換性の複雑さ」
- 環境診断スクリプトで現状を正確に把握することが第一歩
- Docker、conda、pip それぞれに適した使い方がある
- トラブルシューティング表で素早く原因を特定できる
私の所感
正直なところ、CUDA周りの複雑さはNVIDIAとPyTorchコミュニティの「技術的負債」だと思っている。CUDAがプロプライエタリであること、PyTorchのwheelがCUDAバージョンごとにビルドされていること、そしてpipとcondaの依存関係解決が別々に動くこと。これらが絡み合って「地獄」を生み出している。
とはいえ、この複雑さの裏側には「GPU計算を可能な限り高速化したい」という開発者たちの執念がある。一度環境が整えば、CPUの何十倍もの速度でモデルを動かせる恩恵を受けられる。
最終的なおすすめは「Docker一択」だ。環境構築の再現性が担保され、他のプロジェクトとの依存関係衝突も防げる。ローカル開発でも nvidia-docker を使えば、CUDA地獄とおさらばできる。
この記事が、過去の私と同じように苦しんでいる誰かの助けになれば幸いだ。