- 環境說明
- TensorFlow 安裝與 GPU 驅動兼容
- CUDA/H800 特殊注意事項
- PyCharm 和終端環境變量設置方法
- 測試 GPU 是否可用的 Python 腳本
# 使用 TensorFlow 2.13 在 NVIDIA H800 上啟用 GPU 加速完整指南在使用 TensorFlow 進行深度學習訓練時,充分利用 GPU 能力至關重要。本文記錄了在 Linux 環境下使用 TensorFlow 2.13 搭配 NVIDIA H800 GPU 的完整過程,包括常見問題處理和 PyCharm/終端環境設置。---## 📌 系統環境- 操作系統:Ubuntu 20.04
- Python:3.8(Anaconda 環境)
- TensorFlow:2.13.1
- CUDA 驅動:11.8(支持 H800)
- GPU:NVIDIA H800(三卡)---## ? TensorFlow 與 CUDA 驅動兼容性TensorFlow 2.13 支持的 CUDA 和 cuDNN 版本如下:| 組件 | 版本 |
|--------------|------------|
| CUDA | 11.8 |
| cuDNN | 8.6 |
| NVIDIA Driver | >= 525.x |確保 CUDA 驅動已正確安裝(例如 `/usr/local/cuda-11.8/`),并且 `nvidia-smi` 命令能正確輸出 GPU 信息。---## 📥 安裝 TensorFlow(GPU 支持)建議使用 `pip` 安裝 TensorFlow(不建議 `conda install tensorflow`,會拉取 CPU 版本):```bash
pip install tensorflow==2.13.1
安裝完畢后驗證:
python -c "import tensorflow as tf; print(tf.__version__)"
🧪 GPU 可用性驗證腳本
創建一個腳本 verify_tf_gpu.py
:
import os
import tensorflow as tf
import time# 打印當前 LD_LIBRARY_PATH
print("LD_LIBRARY_PATH at runtime:", os.environ.get("LD_LIBRARY_PATH", ""))# 設置 memory growth,避免多 GPU 時報錯
gpus = tf.config.list_physical_devices('GPU')
if gpus:try:for gpu in gpus:tf.config.experimental.set_memory_growth(gpu, True)except RuntimeError as e:print("Error setting memory growth:", e)print("TensorFlow version:", tf.__version__)
print("GPU devices detected:")
for gpu in gpus:print(f" {gpu}")if not gpus:print("? No GPU detected. TensorFlow is running on CPU.")exit(1)print("? GPUs detected. Running a test computation...")# 測試矩陣乘法
start = time.time()
a = tf.random.normal([1000, 1000])
b = tf.random.normal([1000, 1000])
product = tf.matmul(a, b)
_ = product.numpy()
elapsed = time.time() - startprint("Matrix multiplication complete.")
print(f"Elapsed time: {elapsed:.2f} seconds")
print("? TensorFlow successfully used the GPU.")
🛠 環境變量設置
? 終端環境設置
在 .bashrc
或 .zshrc
中添加以下內容:
export LD_LIBRARY_PATH=/home/your_user/anaconda3/envs/your_env/lib:/usr/lib64:/usr/lib:/lib64:/lib
使其生效:
source ~/.bashrc
或者在運行腳本前臨時設置:
LD_LIBRARY_PATH=/home/your_user/anaconda3/envs/your_env/lib:$LD_LIBRARY_PATH python verify_tf_gpu.py
? PyCharm 環境變量設置
-
打開
Run > Edit Configurations
-
選擇你的運行配置(或創建新配置)
-
設置環境變量:
LD_LIBRARY_PATH=/home/your_user/anaconda3/envs/your_env/lib:/usr/lib64:/usr/lib:/lib64:/lib PYTHONUNBUFFERED=1
🧯 遇到的問題及解決方案
? 錯誤:Cannot dlopen some GPU libraries
這是因為 LD_LIBRARY_PATH
未正確設置,導致 TensorFlow 找不到 CUDA 動態庫。
? 解決:確保 CUDA 庫所在路徑加到 LD_LIBRARY_PATH
。
? 錯誤:ValueError: Memory growth cannot differ between GPU devices
? 原因:只對部分 GPU 設置了 memory growth。
? 解決:確保對所有 GPU 執行:
for gpu in tf.config.list_physical_devices('GPU'):tf.config.experimental.set_memory_growth(gpu, True)
🔚 結語
TensorFlow 在高性能 GPU(如 NVIDIA H800)上運行時,環境配置需格外小心。環境變量設置、驅動兼容、memory growth 的統一設置,都是關鍵環節。希望本文能幫你順利開啟 GPU 加速之旅 🚀。