Ollama: GPU与CUDA配置
GPU 是本地 AI 的加速器——从步秒 5 token 到秒 50 token,差距十倍。
💡 提示:使用
CUDA_VISIBLE_DEVICES 环境变量可以精确控制Ollama使用哪些GPU。例如 CUDA_VISIBLE_DEVICES=0 只使用第一块GPU,CUDA_VISIBLE_DEVICES=0,1 使用前两块。在多GPU服务器上,这个变量既能指定推理用的GPU,也能避免Ollama占用其他任务正在使用的GPU资源。
📋 前置知识:需要先掌握以下内容
- 第2课:Ollama安装与环境配置
1. 你将学到
- Ollama GPU 加速原理:GGUF 量化 + GPU Offloading
- NVIDIA CUDA 环境检测与配置
- AMD ROCm 与 Apple Metal 加速
- 多 GPU 推理与内存分配策略
- VRAM 估算与模型参数量换算
2. 一个开发者的真实故事
⚠️ 警告: CUDA 版本和 NVIDIA 驱动版本必须匹配。驱动过旧会导致
nvidia-smi 正常但 Ollama 无法使用 GPU。建议安装 NVIDIA 驱动 ≥ 535 和 CUDA ≥ 12.0,并确认 nvidia-smi 输出中 CUDA Version 与实际 CUDA Toolkit 一致。
(1) 痛点:CPU 推理太慢
Alice 的 SaaS 产品需要实时分析客户反馈,CPU 推理速度只有 5 tokens/s,一条 200 token 的回复要等 40 秒,用户体验极差。她的服务器有 NVIDIA GPU 但 Ollama 没用上。
(2) 解法:GPU 加速 10 倍提速
配置 CUDA 后,同一模型推理速度从 5 tokens/s 提升到 55 tokens/s,200 token 回复只需 3.6 秒:
BASH
# Verify GPU detection
ollama run --verbose llama3.2 "test"
# Before (CPU): eval speed: 5.0 tokens/s
# After (GPU): eval speed: 55.0 tokens/s
3. GPU 加速原理
💡 提示: Ollama 会自动将尽可能多的模型层加载到 GPU,剩余层放 CPU RAM(混合模式)。当 VRAM 不足装下整个模型时,自动降级为 GPU+CPU 混合推理,速度介于纯 GPU 和纯 CPU 之间。
(1) GGUF 量化 + GPU Offloading 架构
⚠️ 注意:当GPU显存(VRAM)不足以加载完整模型时,Ollama会自动回退到GPU+CPU混合模式——部分模型层在GPU推理,剩余层在CPU推理。混合模式的性能显著低于纯GPU模式,且CPU推理速度取决于系统RAM带宽。如果推理速度远低于预期(如8B模型低于20 tok/s),请检查是否发生了VRAM不足的CPU回退。
flowchart LR
A[Model GGUF<br/>Q4_K_M] --> B{Load Strategy}
B -->|Full GPU| C[GPU VRAM<br/>Fast Inference]
B -->|Partial| D[GPU Layers<br/>+ CPU RAM<br/>Hybrid Mode]
B -->|CPU Only| E[CPU RAM<br/>Slow Inference]
Ollama 使用"层卸载"策略:将模型层分配到 GPU(快)和 CPU(慢):
| 模式 | 分配策略 | 速度 | 内存需求 |
|---|---|---|---|
| 全 GPU | 所有层在 VRAM | 最快(50+ tok/s) | VRAM ≥ 模型大小 |
| 混合模式 | 部分层 GPU + 部分 CPU | 中等(15-30 tok/s) | VRAM < 模型大小 |
| 纯 CPU | 所有层在 RAM | 最慢(3-10 tok/s) | RAM ≥ 模型大小 |
(2) VRAM 需求估算公式
TEXT
📖 仅展示
VRAM needed (GB) ≈ Parameters (B) × Quantization bytes × 1.2 (overhead)
Examples:
7B Q4_K_M: 7 × 0.5 bytes × 1.2 ≈ 4.2 GB
8B Q4_K_M: 8 × 0.5 bytes × 1.2 ≈ 4.8 GB
70B Q4_K_M: 70 × 0.5 bytes × 1.2 ≈ 42 GB
| 模型 | 量化 | 最小 VRAM | 推荐 VRAM |
|---|---|---|---|
| 3B | Q4_K_M | 2 GB | 4 GB |
| 8B | Q4_K_M | 5 GB | 8 GB |
| 8B | Q8_0 | 9 GB | 12 GB |
| 70B | Q4_K_M | 42 GB | 48 GB (2×24GB) |
| 70B | Q8_0 | 75 GB | 80 GB (4×24GB) |
4. NVIDIA CUDA 配置
(1) CUDA 安装验证
| 步骤 | 命令 | 预期输出 |
|---|---|---|
| 检查 GPU | nvidia-smi |
显示 GPU 型号和 VRAM |
| 检查 CUDA 版本 | nvidia-smi | grep "CUDA Version" |
CUDA Version: 12.x |
| 检查 nvcc | nvcc --version |
显示 CUDA 工具链版本 |
| 验证 Ollama | ollama run --verbose model |
显示 eval speed |
💡 提示: Ollama 不需要单独安装 CUDA Toolkit——NVIDIA 驱动即可。只需确保 可运行,Ollama 自动检测并使用 GPU。
(2) 平台特定配置
| 平台 | 配置要点 | 注意事项 |
|---|---|---|
| Linux | 安装 NVIDIA 驱动 | 最简单,原生支持 |
| Windows WSL2 | Windows 安装 NVIDIA 驱动 | WSL2 自动继承 GPU |
| Windows 原生 | 安装 NVIDIA 驱动 | Ollama 0.5+ 原生支持 |
▶ 示例 1: Linux CUDA 环境验证
BASH
# Step 1: Check GPU is visible
nvidia-smi --query-gpu=name,memory.total,driver_version --format=csv
# NVIDIA GeForce RTX 4090, 24576 MiB, 550.54.15
# Step 2: Verify CUDA version
nvidia-smi | grep "CUDA Version"
# CUDA Version: 12.4
# Step 3: Test Ollama GPU acceleration
ollama run --verbose llama3.2 "Hello"
# Look for: "load duration" (should be < 1s with GPU)
# Look for: "eval speed" (should be 30+ tokens/s with GPU)
# Step 4: Check which device Ollama is using
OLLAMA_DEBUG=1 ollama run llama3.2 "test" 2>&1 | grep -i cuda
# cuda: detected devices [0]
输出:
TEXT
📖 仅展示
I'm a helpful AI assistant running locally on your machine...
▶ 示例 2: WSL2 GPU 配置
POWERSHELL
# On Windows: verify NVIDIA driver installed
nvidia-smi
# Enter WSL2
wsl
# Inside WSL2: verify GPU passthrough
nvidia-smi
# Should show same GPU as Windows
# Install Ollama in WSL2
curl -fsSL https://ollama.com/install.sh | sh
# Test GPU inference
ollama run --verbose llama3.2 "Hello"
# eval speed should show GPU-level performance
输出:
TEXT
📖 仅展示
// 执行成功
5. AMD ROCm 与 Apple Metal
(1) AMD ROCm 支持(Linux 限定)
| GPU 系列 | 支持 | 说明 |
|---|---|---|
| RX 7900 XTX | ✅ | ROCm 5.7+ |
| RX 7900 XT | ✅ | ROCm 5.7+ |
| RX 6800 XT | ✅ | ROCm 5.5+ |
| RX 580 | ❌ | 不支持 |
| Windows | ❌ | ROCm 仅支持 Linux |
BASH
# Verify ROCm is working
rocminfo | grep "gfx"
# Should show gfx1100 (RDNA3) or gfx1030 (RDNA2)
# Ollama auto-detects AMD GPU on Linux
ollama run --verbose llama3.2 "Hello"
# Should show: using AMD GPU
(2) Apple Metal 加速
| 硬件 | 统一内存 | 推荐模型 |
|---|---|---|
| M1 (8GB) | 8 GB | 3B Q4_K_M |
| M2 (16GB) | 16 GB | 8B Q4_K_M |
| M3 Pro (18GB) | 18 GB | 8B Q4_K_M |
| M4 Max (128GB) | 128 GB | 70B Q4_K_M |
💡 提示: Apple Silicon 的统一内存架构是天然优势——VRAM = RAM,M4 Max 128GB 可运行 70B 模型。
▶ 示例 3: Apple Metal 验证
BASH
# On macOS: Metal acceleration is automatic
ollama run --verbose llama3.2 "Hello"
# Check Metal usage in logs
# Look for: "using Metal" in debug output
OLLAMA_DEBUG=1 ollama run llama3.2 "test" 2>&1 | grep -i metal
# Monitor GPU usage
# Open Activity Monitor → GPU tab
# Or use: sudo powermetrics --samplers gpu_power -i 1000
输出:
TEXT
📖 仅展示
I'm a helpful AI assistant running locally on your machine...
6. 多 GPU 策略
(1) 多 GPU 配置选项
| 环境变量 | 默认值 | 说明 |
|---|---|---|
| OLLAMA_NUM_GPU | 自动 | 使用的 GPU 数量 |
| CUDA_VISIBLE_DEVICES | 全部 | 指定可见 GPU |
| OLLAMA_LLD_LIBRARY_PATH | auto | 驱动类型(cuda/rocm/metal) |
(2) 多 GPU 场景对比
| 场景 | GPU 配置 | 可运行模型 | 策略 |
|---|---|---|---|
| 单 GPU 8GB | 1× RTX 3060 | 8B Q4_K_M | 全层卸载到 GPU |
| 单 GPU 24GB | 1× RTX 4090 | 8B Q8_0 / 70B Q2_K | 全层卸载 |
| 双 GPU 48GB | 2× RTX 4090 | 70B Q4_K_M | 模型切分到两块 GPU |
| 四 GPU 320GB | 4× A100 80GB | 405B 量化 | 张量并行 |
▶ 示例 4: 多 GPU 配置
BASH
# Use 2 GPUs for inference
export OLLAMA_NUM_GPU=2
ollama serve
# Or specify which GPUs to use
export CUDA_VISIBLE_DEVICES=0,1
ollama serve
# Verify multi-GPU usage
nvidia-smi # Both GPUs should show memory usage during inference
# Run a large model that needs 2 GPUs
ollama run llama3.1:70b "Explain quantum computing"
输出:
TEXT
📖 仅展示
I'm a helpful AI assistant running locally on your machine...
▶ 示例 5: GPU 内存分配诊断
BASH
#!/bin/bash
# GPU memory diagnostic script
echo "=== GPU Memory Report ==="
echo ""
nvidia-smi --query-gpu=index,name,memory.total,memory.used,memory.free --format=csv
echo ""
echo "=== Model Memory Estimation ==="
estimate_vram() {
local params=$1 # in billions
local quant=$2 # bytes per parameter
local overhead=1.2
local vram=$(echo "scale=1; $params * $quant * $overhead" | bc)
echo " ${params}B model (${quant}B/param): ~${vram}GB VRAM needed"
}
estimate_vram 3 0.5 # Q4_K_M ~0.5 bytes/param
estimate_vram 8 0.5 # Q4_K_M
estimate_vram 8 1.0 # Q8_0
estimate_vram 70 0.5 # Q4_K_M
estimate_vram 70 1.0 # Q8_0
echo ""
echo "=== Recommendation ==="
total_vram=$(nvidia-smi --query-gpu=memory.total --format=csv,noheader,nounits | awk '{sum+=$1} END {print sum}')
echo "Total VRAM: ${total_vram}MB (~$((total_vram/1024))GB)"
if [ "$total_vram" -gt 40000 ]; then
echo "Can run: 70B Q4_K_M (recommended) or 8B Q8_0"
elif [ "$total_vram" -gt 8000 ]; then
echo "Can run: 8B Q4_K_M (recommended)"
elif [ "$total_vram" -gt 4000 ]; then
echo "Can run: 3B Q4_K_M"
else
echo "GPU VRAM too low. Use CPU-only mode with 16GB+ RAM."
fi
输出:
TEXT
📖 仅展示
# 命令执行成功
7. 综合示例:GPU 部署决策脚本
PYTHON
# ============================================
# Comprehensive: GPU deployment decision engine
# Analyzes hardware and recommends model config
# ============================================
import subprocess
import json
from dataclasses import dataclass
from typing import Optional
@dataclass
class GPUInfo:
name: str
vram_mb: int
index: int
@dataclass
class ModelRecommendation:
model: str
quantization: str
vram_needed_gb: float
fits: bool
strategy: str
def detect_gpus() -> list[GPUInfo]:
"""Detect available GPUs via nvidia-smi."""
try:
result = subprocess.run(
["nvidia-smi", "--query-gpu=index,name,memory.total",
"--format=csv,noheader,nounits"],
capture_output=True, text=True
)
gpus = []
for line in result.stdout.strip().split("\n"):
if line:
parts = [p.strip() for p in line.split(",")]
gpus.append(GPUInfo(
index=int(parts[0]),
name=parts[1],
vram_mb=int(float(parts[2]))
))
return gpus
except Exception:
return []
def estimate_vram(params_b: float, quant_bytes: float) -> float:
"""Estimate VRAM needed for a model."""
return params_b * quant_bytes * 1.2
def recommend_models(total_vram_gb: float) -> list[ModelRecommendation]:
"""Recommend models based on available VRAM."""
models = [
("llama3.2:3b", 3.2, 0.5, "Q4_K_M"),
("llama3.1:8b", 8.0, 0.5, "Q4_K_M"),
("llama3.1:8b", 8.0, 1.0, "Q8_0"),
("llama3.1:70b", 70.0, 0.5, "Q4_K_M"),
]
recs = []
for name, params, qbytes, quant in models:
needed = estimate_vram(params, qbytes)
fits = needed <= total_vram_gb
if fits:
strategy = "Full GPU offload"
elif needed <= total_vram_gb * 1.5:
strategy = "Hybrid (partial GPU + CPU)"
else:
strategy = "CPU only or multi-GPU required"
recs.append(ModelRecommendation(
model=name, quantization=quant,
vram_needed_gb=round(needed, 1),
fits=fits, strategy=strategy
))
return recs
# Main analysis
if __name__ == "__main__":
gpus = detect_gpus()
if not gpus:
print("No NVIDIA GPU detected. Using CPU-only mode.")
print("Recommended: llama3.2:3b with 8GB+ RAM")
else:
total_vram = sum(g.vram_mb for g in gpus) / 1024
print(f"Detected {len(gpus)} GPU(s):")
for g in gpus:
print(f" GPU {g.index}: {g.name} ({g.vram_mb}MB)")
print(f"Total VRAM: {total_vram:.1f}GB")
print()
print("Model Recommendations:")
for r in recommend_models(total_vram):
status = "✅" if r.fits else "❌"
print(f" {status} {r.model} ({r.quantization}): "
f"{r.vram_needed_gb}GB - {r.strategy}")
❓ 常见问题
Q Ollama 显示 CPU 推理但我有 GPU 怎么办?
A 运行 确认驱动正常。Linux 检查用户是否在 video 组:。重启 Ollama 服务:。
Q GPU 推理速度比预期慢怎么办?
A 可能是混合模式(部分层在 CPU)。检查 输出中 GPU 层数。减少 num_ctx 可降低 KV Cache 内存占用,让更多层卸载到 GPU。
Q AMD GPU 在 Windows 上能用吗?
A 目前 ROCm 仅支持 Linux。Windows 上 AMD GPU 无法加速 Ollama。建议使用 Linux 或考虑 NVIDIA GPU。
Q Mac 上的 Metal 加速需要配置吗?
A 不需要。macOS 上 Ollama 自动使用 Metal 加速,零配置。只要 Mac 有 Apple Silicon 或 AMD GPU,就能自动检测。
Q 多 GPU 时模型如何分配?
A Ollama 自动将模型层均匀分配到可用 GPU。设置 指定使用 N 块 GPU。 可选择特定 GPU。
Q VRAM 不够但 RAM 够,能跑大模型吗?
A 可以。Ollama 自动使用混合模式——部分层在 GPU,部分在 CPU RAM。速度介于纯 GPU 和纯 CPU 之间。
📖 小节
- GPU 加速通过层卸载实现:全 GPU 最快,混合模式居中,纯 CPU 最慢
- VRAM 估算:参数量 × 量化字节数 × 1.2 开销系数
- NVIDIA 只需安装驱动(无需 CUDA Toolkit),Ollama 自动检测
- AMD ROCm 仅限 Linux,Apple Metal 在 macOS 上零配置
- 多 GPU 通过 OLLAMA_NUM_GPU 和 CUDA_VISIBLE_DEVICES 控制
- Alice 的场景:GPU 加速后推理速度从 5 tok/s 提升到 55 tok/s
📝 作业
- 基础题(难度⭐):验证你机器上的 GPU 加速是否生效,使用 对比 CPU 和 GPU 推理速度。
- 进阶题(难度⭐⭐):根据你的 GPU VRAM 大小,计算能运行的最大模型(哪个参数量+哪个量化等级),并与实测对比验证。
- 挑战题(难度⭐⭐⭐):在多 GPU 环境下测试不同 GPU 分配策略(单 GPU vs 多 GPU),记录推理速度、首 token 延迟和内存占用,输出性能对比报告。