Giving Docker Containers the GPU: Check the Driver, Reserve the Device, Match PyTorch to the Driver's CUDA
The Gemma chat app ran on the CPU even with an RTX 4070, because the default PyTorch was built for a newer CUDA than driver 577 supports. Check the driver with nvidia-smi, reserve the GPU in compose, install the cu128 (or cu124) PyTorch build, rebuild, and watch 2.1 GB of model land on the card.
What you will learn
- Read nvidia-smi to find the driver version and the newest CUDA it supports
- Reserve NVIDIA GPUs for compose services with a deploy devices block
- Explain the 'driver too old' warning and fix it by installing a PyTorch wheel built for an older CUDA
- Confirm the model is on the card from the device picker and GPU memory
Before you start
- Dockerizing the local LLM chat stack
- Finishing the LLM app: the CPU/GPU picker
The chat app works end to end, but on the CPU, so replies are slow. Now we give it the GPU so Gemma runs on the graphics card. There are four steps: check the card and its driver, hand the GPU to the containers, install a PyTorch that matches the driver, and rebuild and check.
1. Check the card and the driver
In Task Manager under Performance, the lecture machine shows two GPUs. GPU 1 is the NVIDIA RTX 4070, the one we want. GPU 0 is the Intel graphics, so we leave it alone.
The CUDA toolkit is installed too, but the containers don't need it. They need the NVIDIA graphics driver, here version 577. Restart after installing it. Then in PowerShell:
nvidia-smi
It shows driver 577 and CUDA 12.9, the newest CUDA this driver supports, plus the card and its memory: about 8 GB, none in use yet.
NVIDIA's Container Toolkit guide at docs.nvidia.com covers Linux. On Windows, Docker Desktop with the WSL 2 backend passes the GPU into containers through the Windows driver, so there's nothing more to install.
2. Why the first try still used the CPU
On the first try, the api container warned that the NVIDIA driver is too old. The driver wasn't really the problem. The cause is a version mismatch: the default PyTorch was built for a newer CUDA than our driver supports, so PyTorch switches CUDA off and the app falls back to the CPU.
3. Hand the GPU to the containers
The FastAPI version keeps GPU settings in a second compose file, docker-compose.gpu.yml, that merges on top of the normal one:
services:
api:
# The /devices endpoint imports torch to enumerate GPUs, so the api needs
# GPU visibility too (no weights are loaded here, just detection).
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
worker:
# Cap concurrency: each worker process that runs inference loads its own copy
# of the model onto the GPU, so the default (one per CPU core) would exhaust
# GPU memory. Two is plenty for interactive chat.
command: celery -A app.core.celery_app.celery_app worker --loglevel=info --concurrency=2
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
In plain words: give this container every NVIDIA GPU. The api gets it too, because the devices endpoint imports torch to list the cards.
4. A PyTorch that matches the driver
In the backend Dockerfile, a build argument picks the CUDA build, and torch is installed from PyTorch's own index before the other ML packages:
# Install a torch built for the host's CUDA *before* the ML stack. The default
# PyPI torch wheel targets a newer CUDA than many drivers support, so torch
# silently disables the GPU ("driver too old", torch.cuda.is_available()==False)
# and the app falls back to CPU. cu128 matches a CUDA 12.8/12.9 driver and covers
# RTX 20/30/40/50-series. For an older (pre-Turing) GPU, build with
# --build-arg TORCH_CUDA=cu124 (or cu118 for very old cards).
ARG TORCH_CUDA=cu128
RUN pip install --no-cache-dir torch --index-url https://download.pytorch.org/whl/${TORCH_CUDA}
# torch is already installed above, so the torch pin in requirements-ml.txt
# is satisfied and not re-fetched from PyPI.
RUN pip install --no-cache-dir -r requirements-ml.txt
Order matters here. If requirements-ml.txt ran first, it would pull the default torch, and the problem would come back.
Rebuild and check
docker compose -f docker-compose.yml -f docker-compose.gpu.yml up --build
Pip downloads the CUDA build of PyTorch. In the lecture, all three images were built after almost eight minutes, and the containers were recreated.
Open the chat page at localhost:3000. The "run on" picker now offers the RTX 4070, so PyTorch inside the container can see the GPU. Send a message and watch the NVIDIA GPU in Task Manager: dedicated memory goes to 2.1 GB. That's the Gemma model on the graphics card.
The Django and Flask versions
Both need the same three things: a working driver, GPU access for the containers, and a PyTorch that matches. Only a few files differ.
| FastAPI | Django | Flask | |
|---|---|---|---|
| GPU block | second file, api and worker | main compose file, worker only (the api has no torch; it reads the device info the worker stores in Redis) | main compose file, api and worker |
| Worker concurrency | 2 | 1 (each child loads its own model copy) | not changed in this lecture |
| Torch build | ARG TORCH_CUDA=cu128 | ARG TORCH_INDEX_URL=.../whl/cu128, installed only when INSTALL_ML=true (set for the worker) | fixed to cu124, no argument |
| Start command | two -f files | docker compose up -d --build | docker compose up --build |
| Result in the lecture | 2.1 GB GPU memory | 77% utilisation while replying, 5.0 of 8 GB memory | 3.3 GB GPU memory |
The Django Dockerfile explains the cause the coding tool found: the default PyPI torch wheel is built for CUDA 13, which the CUDA 12.9 driver rejects. For an older driver, change the end of TORCH_INDEX_URL to cu126 or cu124, or to cpu for a CPU-only build. After the rebuild, /api/v1/device should report CUDA available true and active cuda, and the picker shows the card's name, which comes from the worker through Redis.
Flask pins cu124 because, as its Dockerfile notes, that build runs on any driver from 525 up. Its /api/v1/system call only asks torch whether CUDA is available and never loads the model, so it's cheap. With MODEL_DEVICE=auto, it picks cuda when CUDA is there and falls back to the CPU when it isn't.
Common mistakes
- Installing the CUDA toolkit and expecting containers to use it. They need the graphics driver.
- Trusting the "driver too old" message. Often the driver is fine and the torch wheel is too new.
- Installing requirements before the CUDA-specific torch. The default wheel wins.
- High worker concurrency on one GPU. Each process loads its own model copy and memory runs out.
Quick recap
| Step | Check |
|---|---|
| Driver | nvidia-smi: driver 577, CUDA 12.9 |
| Containers | deploy.resources.reservations.devices, driver nvidia, count all, capabilities gpu |
| PyTorch | cu128 (or cu124) from download.pytorch.org, before the other ML packages |
| Proof | picker shows the RTX 4070; GPU memory rises when you chat |
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
When the main model goes down, the backup has to be allowed to take the data, able to read the whole request and tested before the bad day. A simulated four-model chain for an EU customer: a 6,000-token request lands on mid-eu, flagged degraded; a 10,000-token request is served by nobody, on purpose.
Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
A bulk upload buries the chat. In a small simulation, one shared queue grows to 199 waiting and the middle chat answer takes 80.2 s. A bound plus a chat lane brings it to 0.35 s while 178 bulk jobs are told to retry in 10 s, and cancelling abandoned calls saves 21,000 wasted tokens.
Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
Six GPU replicas, two at 95% and four at 30%: round robin counts requests, and requests aren't equal. In a small simulation, least outstanding requests cuts p95 from 6.52 s to 3.05 s, prefix affinity lifts cache hits to 95% but pushes p95 to 11.45 s, a real health check takes errors from 48 to 2, and draining cuts 0 answers instead of 4.
A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
A queue doesn't lose a document, but it can hand one out twice. In a small simulation, a worker crash makes document two go from 3 to 6 chunks and the index holds 11 when the documents hold 8. An idempotent consumer brings it back to 8 with the same two deliveries, and a limit of three tries moves a poison file to a dead letter queue.
