CUDA 12.4 + PyTorch 2.4 环境配置:Windows/Linux 双平台 3 步验证 GPU 可用性
CUDA 12.4 PyTorch 2.4 环境配置Windows/Linux 双平台 3 步验证 GPU 可用性当你在本地机器或服务器上配置好 CUDA 和 PyTorch 环境后最令人沮丧的莫过于运行代码时发现 GPU 没有被正确识别和使用。本文将提供一个简洁高效的 3 步验证流程确保你的 GPU 能够被 PyTorch 正确调用适用于 Windows 和 Linux 双平台。1. 硬件与驱动基础检查在开始任何软件配置之前我们需要确保硬件和驱动层面已经准备就绪。1.1 确认 GPU 型号与计算能力首先你需要确认你的 NVIDIA GPU 是否支持 CUDA。并非所有 NVIDIA 显卡都支持 CUDA 计算特别是较老的显卡或某些专为图形设计优化的型号。在 Windows 上右键点击桌面空白处选择 NVIDIA 控制面板点击左下角的 系统信息在 显示 标签页中查看 GPU 型号在 Linux 上lspci | grep -i nvidia1.2 检查 NVIDIA 驱动版本驱动版本必须与你要安装的 CUDA 版本兼容。使用以下命令检查驱动版本Windows (PowerShell):nvidia-smiLinux:nvidia-smi你会看到类似这样的输出----------------------------------------------------------------------------- | NVIDIA-SMI 525.85.12 Driver Version: 525.85.12 CUDA Version: 12.0 | |--------------------------------------------------------------------------- | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | | | | MIG M. | || | 0 NVIDIA GeForce ... On | 00000000:01:00.0 On | N/A | | N/A 45C P8 10W / N/A | 500MiB / 8192MiB | 0% Default | | | | N/A | ---------------------------------------------------------------------------关键点驱动版本 (此处为 525.85.12)支持的 CUDA 版本 (此处显示为 12.0)1.3 安装合适的驱动如果你的驱动版本不支持你想要的 CUDA 版本需要先更新驱动。可以通过 NVIDIA 官网下载最新驱动或使用以下方式Linux (Ubuntu):sudo apt-get install nvidia-driver-525Windows: 从 NVIDIA 官网下载对应显卡型号的最新驱动并安装2. CUDA 与 PyTorch 安装验证2.1 确认 CUDA 安装安装 CUDA 工具包后验证其是否正确安装Windows:nvcc --versionLinux:nvcc --version正确安装会显示类似信息nvcc: NVIDIA (R) Cuda compiler release 12.4, V12.4.1312.2 安装 PyTorch 的正确版本PyTorch 版本必须与 CUDA 版本严格匹配。访问 PyTorch 官网 获取正确的安装命令。对于 CUDA 12.4 和 PyTorch 2.4安装命令通常如下Windows/Linux:pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu1242.3 验证 PyTorch 的 CUDA 支持创建一个简单的 Python 脚本或直接在 Python 解释器中运行import torch print(fPyTorch version: {torch.__version__}) print(fCUDA available: {torch.cuda.is_available()}) print(fCUDA version: {torch.version.cuda}) print(fGPU device count: {torch.cuda.device_count()}) print(fCurrent device: {torch.cuda.current_device()}) print(fDevice name: {torch.cuda.get_device_name(0)})预期输出示例PyTorch version: 2.4.0 CUDA available: True CUDA version: 12.4 GPU device count: 1 Current device: 0 Device name: NVIDIA GeForce RTX 30803. 三阶段验证流程现在进入核心的 3 步验证流程确保 GPU 能被 PyTorch 正确使用。3.1 第一步基础 GPU 信息检查import torch def check_gpu_basic(): if not torch.cuda.is_available(): print(CUDA is not available. Check your installation.) return False device_count torch.cuda.device_count() print(fFound {device_count} CUDA-capable device(s)) for i in range(device_count): print(f\nDevice {i}:) print(f Name: {torch.cuda.get_device_name(i)}) print(f Compute Capability: {torch.cuda.get_device_capability(i)}) print(f Total Memory: {torch.cuda.get_device_properties(i).total_memory / 1024**3:.2f} GB) return True check_gpu_basic()3.2 第二步张量运算验证创建一个简单的张量运算测试 GPU 计算能力def test_tensor_operations(): # 创建一个大型随机矩阵 x torch.randn(10000, 10000) # 将矩阵移动到 GPU 上 device torch.device(cuda if torch.cuda.is_available() else cpu) x x.to(device) # 执行矩阵乘法 start_time torch.cuda.Event(enable_timingTrue) end_time torch.cuda.Event(enable_timingTrue) start_time.record() result torch.mm(x, x.t()) end_time.record() torch.cuda.synchronize() elapsed_time start_time.elapsed_time(end_time) print(fMatrix multiplication (10000x10000) took {elapsed_time:.2f} ms on {device}) # 验证结果是否正确 test_value result[0, 0].item() print(fTest value at [0,0]: {test_value:.4f}) test_tensor_operations()3.3 第三步完整模型训练验证最后我们用一个简单的神经网络训练来验证 GPU 加速效果import torch.nn as nn import torch.optim as optim from torch.utils.data import TensorDataset, DataLoader import time def test_model_training(): # 创建模拟数据 num_samples 100000 input_size 100 output_size 10 X torch.randn(num_samples, input_size) y torch.randint(0, output_size, (num_samples,)) # 创建数据加载器 batch_size 1024 dataset TensorDataset(X, y) loader DataLoader(dataset, batch_sizebatch_size, shuffleTrue) # 定义简单模型 model nn.Sequential( nn.Linear(input_size, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, output_size) ) # 将模型移动到 GPU device torch.device(cuda if torch.cuda.is_available() else cpu) model model.to(device) # 训练设置 criterion nn.CrossEntropyLoss() optimizer optim.Adam(model.parameters(), lr0.001) # 训练循环 num_epochs 5 print(f\nStarting training on {device}...) for epoch in range(num_epochs): epoch_start time.time() running_loss 0.0 for inputs, labels in loader: inputs, labels inputs.to(device), labels.to(device) optimizer.zero_grad() outputs model(inputs) loss criterion(outputs, labels) loss.backward() optimizer.step() running_loss loss.item() epoch_time time.time() - epoch_start print(fEpoch {epoch1}/{num_epochs} - Loss: {running_loss/len(loader):.4f} - Time: {epoch_time:.2f}s) test_model_training()常见问题与解决方案4.1 CUDA 可用但 PyTorch 无法识别症状nvidia-smi显示 GPU 正常但torch.cuda.is_available()返回 False。可能原因PyTorch 版本与 CUDA 版本不匹配安装了 CPU-only 版本的 PyTorch环境变量问题解决方案确认 PyTorch 版本与 CUDA 版本匹配重新安装正确版本的 PyTorch检查环境变量CUDA_HOME和PATH是否包含 CUDA 路径4.2 内存不足错误症状RuntimeError: CUDA out of memory解决方案减小 batch size使用更小的模型清理 GPU 内存torch.cuda.empty_cache()4.3 多 GPU 环境配置如果你有多个 GPU可以这样利用它们import torch import torch.nn as nn # 检查可用 GPU 数量 device_count torch.cuda.device_count() print(fAvailable GPUs: {device_count}) # 方法1: 数据并行 model nn.Sequential(...) # 你的模型 if device_count 1: model nn.DataParallel(model) model model.to(cuda:0) # 主设备 # 方法2: 手动分配 batch_size 1024 tensors [torch.randn(batch_size, 100) for _ in range(10)] # 将不同张量分配到不同 GPU for i, tensor in enumerate(tensors): device fcuda:{i % device_count} tensors[i] tensor.to(device)性能优化技巧5.1 使用混合精度训练from torch.cuda.amp import autocast, GradScaler scaler GradScaler() for inputs, labels in loader: inputs, labels inputs.to(device), labels.to(device) optimizer.zero_grad() with autocast(): outputs model(inputs) loss criterion(outputs, labels) scaler.scale(loss).backward() scaler.step(optimizer) scaler.update()5.2 优化数据加载# 使用 pin_memory 和更多 workers 加速数据加载 loader DataLoader( dataset, batch_sizebatch_size, shuffleTrue, num_workers4, # 根据 CPU 核心数调整 pin_memoryTrue, # 加速 CPU 到 GPU 的数据传输 persistent_workersTrue )5.3 使用 CUDA 图优化# 创建 CUDA 图 g torch.cuda.CUDAGraph() # 预热 static_input torch.randn(batch_size, input_size, devicecuda) static_target torch.randint(0, output_size, (batch_size,), devicecuda) optimizer.zero_grad() with torch.cuda.graph(g): static_output model(static_input) static_loss criterion(static_output, static_target) static_loss.backward() optimizer.step() # 实际训练中使用图 for inputs, labels in loader: inputs.copy_(static_input) labels.copy_(static_target) g.replay() # 执行图跨平台注意事项6.1 Windows 特有配置确保 Visual Studio 已安装CUDA 编译需要检查 PATH 环境变量包含CUDA 安装路径 (如C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4\bin)CUDA 库路径 (如C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4\libnvvp)6.2 Linux 特有配置确保 gcc 版本与 CUDA 兼容检查/usr/local/cuda符号链接指向正确的 CUDA 版本添加以下到.bashrc或.zshrcexport PATH/usr/local/cuda/bin:$PATH export LD_LIBRARY_PATH/usr/local/cuda/lib64:$LD_LIBRARY_PATH版本兼容性参考下表列出了 PyTorch 与 CUDA 版本的对应关系PyTorch 版本支持的 CUDA 版本备注2.4.x12.4, 12.1, 11.8推荐 12.42.3.x12.1, 11.82.2.x11.8, 11.72.1.x11.8, 11.7自动化验证脚本为了方便使用这里提供一个完整的验证脚本保存为verify_gpu.pyimport torch import torch.nn as nn import torch.optim as optim from torch.utils.data import TensorDataset, DataLoader import time def print_system_info(): print(*50) print(System Information:) print(fPyTorch version: {torch.__version__}) print(fCUDA available: {torch.cuda.is_available()}) if torch.cuda.is_available(): print(fCUDA version: {torch.version.cuda}) print(fGPU device count: {torch.cuda.device_count()}) for i in range(torch.cuda.device_count()): print(f\nDevice {i}:) print(f Name: {torch.cuda.get_device_name(i)}) print(f Compute Capability: {torch.cuda.get_device_capability(i)}) print(f Total Memory: {torch.cuda.get_device_properties(i).total_memory / 1024**3:.2f} GB) print(*50 \n) def test_tensor_operations(): print(Testing tensor operations...) try: # 创建一个大型随机矩阵 size 10000 x torch.randn(size, size) # 将矩阵移动到 GPU 上 device torch.device(cuda if torch.cuda.is_available() else cpu) x x.to(device) # 执行矩阵乘法 start_time torch.cuda.Event(enable_timingTrue) end_time torch.cuda.Event(enable_timingTrue) start_time.record() result torch.mm(x, x.t()) end_time.record() torch.cuda.synchronize() elapsed_time start_time.elapsed_time(end_time) print(fMatrix multiplication ({size}x{size}) took {elapsed_time:.2f} ms on {device}) # 验证结果是否正确 test_value result[0, 0].item() print(fTest value at [0,0]: {test_value:.4f}) print(Tensor operations test passed!\n) return True except Exception as e: print(fTensor operations test failed: {str(e)}\n) return False def test_model_training(): print(Testing model training...) try: # 创建模拟数据 num_samples 50000 # 减小规模以加快测试速度 input_size 100 output_size 10 X torch.randn(num_samples, input_size) y torch.randint(0, output_size, (num_samples,)) # 创建数据加载器 batch_size 1024 dataset TensorDataset(X, y) loader DataLoader(dataset, batch_sizebatch_size, shuffleTrue) # 定义简单模型 model nn.Sequential( nn.Linear(input_size, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, output_size) ) # 将模型移动到 GPU device torch.device(cuda if torch.cuda.is_available() else cpu) model model.to(device) # 训练设置 criterion nn.CrossEntropyLoss() optimizer optim.Adam(model.parameters(), lr0.001) # 训练循环 num_epochs 2 # 减少epoch数以加快测试速度 print(f\nStarting training on {device}...) for epoch in range(num_epochs): epoch_start time.time() running_loss 0.0 for inputs, labels in loader: inputs, labels inputs.to(device), labels.to(device) optimizer.zero_grad() outputs model(inputs) loss criterion(outputs, labels) loss.backward() optimizer.step() running_loss loss.item() epoch_time time.time() - epoch_start print(fEpoch {epoch1}/{num_epochs} - Loss: {running_loss/len(loader):.4f} - Time: {epoch_time:.2f}s) print(Model training test passed!\n) return True except Exception as e: print(fModel training test failed: {str(e)}\n) return False def main(): print_system_info() if not torch.cuda.is_available(): print(WARNING: CUDA is not available. PyTorch cannot use GPU acceleration.) return tests_passed 0 tests_passed test_tensor_operations() tests_passed test_model_training() print(\n *50) print(fTest Summary: {tests_passed}/2 tests passed) if tests_passed 2: print(SUCCESS: Your GPU is properly configured for PyTorch!) else: print(WARNING: Some tests failed. Check your CUDA and PyTorch installation.) print(*50) if __name__ __main__: main()使用方法python verify_gpu.py这个脚本会自动检测你的系统配置运行张量运算和模型训练测试并给出明确的通过/失败指示。