Sub topic 13
Running GPU workloads in containers
Prerequisites
Assume you know basic Docker commands, have used a machine-learning framework such as PyTorch, and understand that a GPU has a driver installed by the host operating system. This chapter focuses on connecting that host GPU to a container safely and predictably.
What a GPU container contains
A container can include the CUDA user-space libraries that an ML framework needs. It does not normally include the host's GPU kernel driver. The driver stays on the host because it must communicate with the host kernel and physical device.
The host therefore needs:
- An NVIDIA GPU and a compatible NVIDIA driver
- Docker
- The NVIDIA Container Toolkit
- An image containing a compatible CUDA runtime and ML framework
The CUDA version in the image must be supported by the host driver. A newer driver can usually run images with older CUDA runtimes. An older driver might fail when the image requires a newer CUDA version.
Requesting the GPU
The --gpus all option asks Docker to expose all available GPUs to the container. This command checks whether the container can communicate with the GPU:
docker run --rm --gpus all \
nvidia/cuda:12.4.1-base-ubuntu22.04 \
nvidia-sminvidia-smi reports the GPU model, driver version, and memory use. If Docker cannot find the GPU, check the host driver and NVIDIA Container Toolkit before debugging Python code.
You can expose only selected devices:
docker run --rm --gpus '"device=0"' \
nvidia/cuda:12.4.1-base-ubuntu22.04 \
nvidia-smiThe unusual quoting preserves the device expression when the shell passes it to Docker.
Building an ML image
A training image usually starts from a framework image or a CUDA-enabled base image. Install application dependencies in the image, then run the training command.
FROM pytorch/pytorch:2.4.0-cuda12.4-cudnn9-runtime
WORKDIR /app
COPY requirements.lock .
RUN pip install --no-cache-dir --require-hashes -r requirements.lock
COPY src/ ./src/
CMD ["python", "-m", "src.train"]Build and run it like this:
docker build -t ml-train:dev .
docker run --rm --gpus all ml-train:devThe image's CUDA libraries and PyTorch build must agree. Installing a CPU-only PyTorch package into a CUDA image does not make it GPU-enabled.
Exercise
What is the most likely cause if nvidia-smi works on the host but fails inside the container?
Show answer
Check that Docker uses the NVIDIA Container Toolkit and that the container was started with --gpus. Then check driver and image CUDA compatibility.