Ollama: GPU and CUDA Configuration

GPU is the accelerator for local AI — from 5 tokens per second to 50 tokens per second, a tenfold difference.

💡 Tip: Use the CUDA_VISIBLE_DEVICES environment variable to precisely control which GPUs Ollama uses. For example, CUDA_VISIBLE_DEVICES=0 uses only the first GPU, while CUDA_VISIBLE_DEVICES=0,1 uses the first two. On multi-GPU servers, this variable lets you specify Inference GPUs and avoid Ollama occupying GPUs that other tasks are using.

📋 Prerequisites: You need to master the following first

1. What You Will Learn


2. A Real Developer's Story

⚠️ Warning: CUDA version and NVIDIA driver version must match. Outdated drivers may result in nvidia-smi working normally but Ollama being unable to use the GPU. We recommend installing NVIDIA driver ≥ 535 and CUDA ≥ 12.0, and confirming that the CUDA Version in nvidia-smi output matches the actual CUDA Toolkit.

(1) The Pain Point: CPU Inference Is Too Slow

Alice's SaaS product needs real-time analysis of customer feedback. CPU Inference speed is only 5 tokens/s — a 200-token reply takes 40 seconds, resulting in a terrible user experience. Her server has an NVIDIA GPU but Ollama isn't using it.

(2) The Solution: GPU Acceleration Delivers 10x Speedup

After configuring CUDA, the same Model's Inference speed increased from 5 tokens/s to 55 tokens/s — a 200-token reply now takes only 3.6 seconds:

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 Acceleration Principles

💡 Tip: Ollama automatically loads as many Model layers as possible onto the GPU, placing remaining layers in CPU RAM (hybrid mode). When VRAM is insufficient for the full Model, it automatically falls back to GPU+CPU hybrid Inference, with speed between pure GPU and pure CPU.

(1) GGUF Quantization + GPU Offloading Architecture

⚠️ Note: When GPU VRAM is insufficient to load the full Model, Ollama automatically falls back to GPU+CPU hybrid mode — some Model layers run on the GPU, and remaining layers run on the CPU. Hybrid mode performance is significantly lower than pure GPU mode, and CPU Inference speed depends on system RAM bandwidth. If Inference speed is far below expectations (e.g., 8B Model below 20 tok/s), check whether VRAM-insufficient CPU fallback is occurring.

100%
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 uses a "layer offloading" strategy, distributing Model layers between GPU (fast) and CPU (slow):

Mode Allocation Strategy Speed Memory Requirements
Full GPU All layers in VRAM Fastest (50+ tok/s) VRAM ≥ Model size
Hybrid mode Some layers GPU + some CPU Medium (15-30 tok/s) VRAM < Model size
CPU only All layers in RAM Slowest (3-10 tok/s) RAM ≥ Model size

(2) VRAM Requirement Estimation Formula

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
Model Quantization Minimum VRAM Recommended 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 Configuration

(1) CUDA Installation Verification

Step Command Expected Output
Check GPU nvidia-smi Shows GPU model and VRAM
Check CUDA version nvidia-smi | grep "CUDA Version" CUDA Version: 12.x
Check nvcc nvcc --version Shows CUDA toolkit version
Verify Ollama ollama run --verbose model Shows eval speed
💡 Tip: Ollama doesn't need a separate CUDA Toolkit installation — the NVIDIA driver is sufficient. Just ensure nvidia-smi is runnable; Ollama auto-detects and uses the GPU.

(2) Platform-Specific Configuration

Platform Configuration Key Points Notes
Linux Install NVIDIA driver Simplest, native support
Windows WSL2 Install NVIDIA driver on Windows WSL2 auto-inherits GPU
Windows native Install NVIDIA driver Ollama 0.5+ native support

▶ Example 1: Linux CUDA Environment Verification

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]

Output:

TEXT
I'm a helpful AI assistant running locally on your machine...

▶ Example 2: WSL2 GPU Configuration

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

Output:

TEXT
// Execution successful

5. AMD ROCm and Apple Metal

(1) AMD ROCm Support (Linux Only)

GPU Series Support Notes
RX 7900 XTX ROCm 5.7+
RX 7900 XT ROCm 5.7+
RX 6800 XT ROCm 5.5+
RX 580 Not supported
Windows ROCm only supports 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 Acceleration

Hardware Unified Memory Recommended Model
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
💡 Tip: Apple Silicon's unified memory architecture is a natural advantage — VRAM = RAM. An M4 Max with 128GB can run 70B Models.

▶ Example 3: Apple Metal Verification

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

Output:

TEXT
I'm a helpful AI assistant running locally on your machine...

6. Multi-GPU Strategies

(1) Multi-GPU Configuration Options

Environment Variable Default Description
OLLAMA_NUM_GPU Auto Number of GPUs to use
CUDA_VISIBLE_DEVICES All Specify visible GPUs
OLLAMA_LLD_LIBRARY_PATH auto Driver type (cuda/rocm/metal)

(2) Multi-GPU Scenario Comparison

Scenario GPU Configuration Runnable Models Strategy
Single GPU 8GB 1× RTX 3060 8B Q4_K_M Full offload to GPU
Single GPU 24GB 1× RTX 4090 8B Q8_0 / 70B Q2_K Full offload
Dual GPU 48GB 2× RTX 4090 70B Q4_K_M Model split across two GPUs
Quad GPU 320GB 4× A100 80GB 405B Quantized Tensor parallelism

▶ Example 4: Multi-GPU Configuration

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"

Output:

TEXT
I'm a helpful AI assistant running locally on your machine...

▶ Example 5: GPU Memory Allocation Diagnostics

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
    local quant=$2
    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

Output:

TEXT
# Command executed successfully

7. Comprehensive Example: GPU Deployment Decision Script

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}")

❓ FAQ

Q Ollama shows CPU Inference but I have a GPU, what should I do?
A Run nvidia-smi to confirm the driver is working. On Linux, check if the user is in the video group: sudo usermod -aG video $USER. Restart the Ollama service: sudo systemctl restart ollama.
Q GPU Inference speed is slower than expected, what should I do?
A This may be hybrid mode (some layers on CPU). Check the --verbose output for GPU layer count. Reducing num_ctx can lower KV Cache memory usage, allowing more layers to offload to GPU.
Q Can AMD GPU work on Windows?
A Currently ROCm only supports Linux. AMD GPUs cannot accelerate Ollama on Windows. We recommend using Linux or considering an NVIDIA GPU.
Q Does Metal acceleration on Mac require configuration?
A No. On macOS, Ollama automatically uses Metal acceleration with zero configuration. Any Mac with Apple Silicon or an AMD GPU is auto-detected.
Q How are Models distributed across multiple GPUs?
A Ollama automatically distributes Model layers evenly across available GPUs. Set OLLAMA_NUM_GPU=N to specify using N GPUs. CUDA_VISIBLE_DEVICES lets you select specific GPUs.
Q Can I run a large Model if VRAM is insufficient but RAM is adequate?
A Yes. Ollama automatically uses hybrid mode — some layers on GPU, some on CPU RAM. Speed falls between pure GPU and pure CPU.

📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Verify whether GPU acceleration is working on your machine, using --verbose to compare CPU and GPU Inference speeds.
  2. Intermediate (Difficulty ⭐⭐): Based on your GPU VRAM size, calculate the largest Model you can run (which parameter count + which Quantization level), and verify with actual testing.
  3. Advanced (Difficulty ⭐⭐⭐): Test different GPU allocation strategies in a multi-GPU environment (single GPU vs multi-GPU), recording Inference speed, first-token latency, and memory usage, and output a performance comparison report.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏