Careers Post-AI
AI infrastructure and systems: all chapters

AI infrastructure and systemsPart 1: Foundations

Chapter 3The ML software stack

30 min read, 1 lab, Beginner

"It worked on my machine" costs more in ML than anywhere else, because the machine includes a kernel driver, a CUDA version, a PyTorch build and a GPU architecture that all have to agree. This chapter maps those layers so that when torch.cuda.is_available() returns False at 2 a.m., you know exactly which one to check first.

After this chapter you can

  • Name each layer from GPU hardware to application and what it provides
  • Explain the difference between the driver's CUDA version and the toolkit and PyTorch CUDA versions
  • Choose a model file format (safetensors, GGUF, ONNX) and explain why pickle files are risky
  • Package a PyTorch application in a container that runs on CPU or GPU with pinned versions
  • Diagnose the classic failures: no GPU visible, driver too old, missing kernel image, out of memory

The layers from silicon to app

Every GPU workload runs on a stack where each layer depends on the one below and expects specific versions of it. This is the same layering you know from operating systems, a kernel driver below user-space libraries below applications, with one twist: the driver is shared, everything above it is yours.

LayerWhat it doesWho installs it
Kernel driver (nvidia.ko)Talks to the hardware, manages memory and schedulingThe host administrator, once per machine
User-mode driver (libcuda.so)Implements the CUDA driver API; ships with the kernel driverComes with the driver package
CUDA runtime (libcudart)The API programs call to allocate memory and launch kernelsBundled with PyTorch wheels or a CUDA base image
cuBLAS, cuDNN, NCCLTuned matmul, neural-network and multi-GPU communication kernelsBundled with PyTorch wheels
PyTorchTensors, autograd, and dispatch of each operation to a kernelYou, with pip or uv
Transformers, vLLM and similarModel architectures, loading weights, generation, servingYou

When you call a @ b on two CUDA tensors, PyTorch picks a cuBLAS routine for that shape and dtype, the runtime queues the kernel on a stream, the driver submits it to the GPU, and control returns to Python before the math finishes. That asynchrony is why benchmarks must synchronize before stopping the clock.

Three different CUDA versions

The word "CUDA version" refers to three different things, and confusing them causes most installation pain.

Driver CUDA version

  • Shown top right in nvidia-smi
  • The newest CUDA the installed driver can run
  • A ceiling, not something installed

Toolkit version

  • Shown by nvcc --version
  • The compiler and headers, needed only to build CUDA code
  • Often absent, and that is fine for running PyTorch

PyTorch build version

  • Shown by torch.version.cuda
  • The CUDA runtime bundled in your wheel
  • Must be supported by the driver

The rule: the driver must be at least as new as the CUDA runtime your software was built with. NVIDIA's compatibility guarantees help: within a major version, newer runtimes generally run on older drivers of the same family (minor version compatibility), so applications built with any CUDA 13.x release need a Linux driver of version 580 or newer, with some feature limits. An old driver with a new wheel fails; a new driver with an old wheel works.

Model file formats

A model on disk is a set of named tensors plus configuration (architecture, tokenizer, generation defaults). The format decides what can load it, how fast and how safely.

FormatWhat it isLoaded byWatch out for
safetensorsA JSON header plus raw tensor bytes; no codeTransformers, vLLM, most toolsDefault on Hugging Face; memory-maps quickly
PyTorch pickle (.bin, .pt)Python's pickle serializationtorch.loadUnpickling can execute arbitrary code
GGUFA single file with weights, metadata and tokenizer, often quantizedllama.cpp, Ollama, LM StudioMany quantization variants; pick by size and quality
ONNXA portable computation graph plus weightsONNX Runtime, TensorRT, browsersExport can fail on unusual operators

A typical Hugging Face model repository holds config.json (the architecture: layers, hidden size, heads), tokenizer files, generation_config.json and one or more model.safetensors shards. The SmolLM2-135M-Instruct repository used in the lab also includes several ONNX exports, so you can see the same model in two formats side by side.

Python packaging for GPU code

PyTorch publishes a separate build for each CUDA version, served from its own package index, because one wheel cannot contain every variant. The wheel bundles the CUDA runtime and libraries, so a machine needs only the driver, not a system-wide CUDA install.

# CPU-only build: small download, runs anywhere
pip install torch --index-url https://download.pytorch.org/whl/cpu
 
# Build bundled with CUDA 13.2 libraries: needs a recent NVIDIA driver
pip install torch --index-url https://download.pytorch.org/whl/cu132
 
# Check what you actually got
python -c "import torch; print(torch.__version__, torch.version.cuda, torch.cuda.is_available())"

A version string like 2.15.0+cpu tells you the CPU build was installed, a classic cause of a silently unused GPU. On Linux, the default pip install torch from PyPI pulls a CUDA build; on macOS you get a build with Apple's MPS backend.

For reproducibility, pin versions twice: the direct dependencies you choose in requirements.txt, and every transitive dependency in a lock file generated from a known-good environment (pip freeze, pip-compile or uv lock). Use one virtual environment per project; never install into the system Python.

Containers and the NVIDIA Container Toolkit

A container image freezes the user-space part of the stack: OS libraries, Python, PyTorch and its bundled CUDA libraries. The kernel driver cannot live in the image, because there is only one kernel and it belongs to the host. The NVIDIA Container Toolkit bridges the gap by mounting the host's driver libraries and GPU device files into the container at start.

Setting it up on a Linux host with an NVIDIA driver installed follows NVIDIA's install guide: add NVIDIA's package repository, install the toolkit, then configure Docker.

sudo apt-get install -y nvidia-container-toolkit      # after adding NVIDIA's repo
sudo nvidia-ctk runtime configure --runtime=docker
sudo systemctl restart docker
docker run --rm --gpus all ubuntu nvidia-smi           # should print the host's GPUs

Base image choices trade size for convenience. A slim Python image plus PyTorch wheels is small and transparent. NVIDIA's nvidia/cuda images add system CUDA libraries, with devel variants that include the compiler for building extensions. NGC framework images (nvcr.io/nvidia/pytorch:YY.MM-py3) ship a tested PyTorch, CUDA and library set, at a size of many gigabytes.

Classic failures and how to debug them

Most GPU stack failures fall into a handful of patterns. Work from the bottom of the stack up.

SymptomLikely causeCheck and fix
torch.cuda.is_available() is False, no errorCPU wheel, or container started without GPUstorch.__version__ ends in +cpu? Reinstall from a CUDA index. In Docker, add --gpus all
"The NVIDIA driver on your system is too old"Wheel built for a newer CUDA than the driver supportsCompare nvidia-smi CUDA version with torch.version.cuda; upgrade driver or install an older cuXXX wheel
"no kernel image is available for execution on the device"Wheel not compiled for this GPU architectureCompare torch.cuda.get_device_capability() with torch.cuda.get_arch_list(); CUDA 13 builds dropped pre-Turing GPUs such as the P100 and V100
"Failed to initialize NVML: Driver/library version mismatch"Driver upgraded but old kernel module still loadedReboot, or unload and reload the module
Docker: could not select device driver "" with capabilities: [[gpu]]NVIDIA Container Toolkit missing or Docker not configuredInstall the toolkit, run nvidia-ctk runtime configure, restart Docker
torch.OutOfMemoryError: CUDA out of memoryModel, batch or context too large; fragmentationDo the memory math from GPUs and accelerators; reduce batch or context; inspect torch.cuda.memory_summary()
ImportError ... undefined symbol in an extensionExtension compiled against a different PyTorchReinstall the extension built for your exact PyTorch and CUDA versions
# A ten-second triage script worth keeping in every image
nvidia-smi --query-gpu=name,driver_version,memory.total --format=csv
python - <<'EOF'
import torch
print("torch", torch.__version__, "built for CUDA", torch.version.cuda)
print("available", torch.cuda.is_available())
if torch.cuda.is_available():
    print(torch.cuda.get_device_name(0), "capability", torch.cuda.get_device_capability(0))
    print("compiled for", torch.cuda.get_arch_list())
EOF

Key terms

Kernel driver
The host operating system module that controls the GPU; there is exactly one per machine.
CUDA runtime
The library programs call to manage GPU memory and launch kernels, bundled with frameworks.
cuBLAS
NVIDIA's library of tuned linear algebra kernels, which PyTorch calls for matrix multiplication.
cuDNN
NVIDIA's library of tuned deep-learning primitives such as convolutions and attention.
Wheel
A prebuilt Python package; PyTorch publishes one per CUDA version on separate indexes.
safetensors
A model weight format of raw tensors plus a JSON header that cannot execute code when loaded.
GGUF
A single-file model format with metadata and quantized weights, used by llama.cpp.
NVIDIA Container Toolkit
Software that exposes the host's GPU driver and devices to containers.
Compute capability
A version number for a GPU architecture, such as 7.5 for Turing or 9.0 for Hopper.
Lab

Build a reproducible GPU-ready inference container

Intermediate, 60 min

Goal: build one Dockerfile that produces a CPU image or a GPU image from a build argument, with pinned versions and a pinned model revision, and run a Hugging Face model inside it.

You need: Docker (Docker Desktop on macOS or Windows, Docker Engine on Linux), about 5 GB of disk for the CPU image, and an internet connection. For the GPU path: a Linux machine with an NVIDIA GPU (Turing or newer), driver 580 or newer and the NVIDIA Container Toolkit, for example a cloud GPU VM. Colab and Kaggle cannot run Docker, so use the CPU path if you have no Linux GPU host. On Windows, run these commands in WSL 2.

  1. Create the project files.
mkdir llm-container && cd llm-container
requirements.txt
transformers==5.24.1
  1. Write the application. It prints every version that matters, then generates text. The model revision is a commit hash, so the weights cannot change under you.
run.py
import sys, time, torch, transformers
from transformers import AutoModelForCausalLM, AutoTokenizer
 
MODEL = "HuggingFaceTB/SmolLM2-135M-Instruct"
REVISION = "12fd25f77366fa6b3b4b768ec3050bf629380bac"   # pin the exact model commit
 
print(f"python {sys.version.split()[0]}  torch {torch.__version__}  transformers {transformers.__version__}")
print(f"torch built for CUDA: {torch.version.cuda}  GPU visible: {torch.cuda.is_available()}")
device = "cuda" if torch.cuda.is_available() else "cpu"
if device == "cuda":
    print("GPU:", torch.cuda.get_device_name(0))
 
tok = AutoTokenizer.from_pretrained(MODEL, revision=REVISION)
model = AutoModelForCausalLM.from_pretrained(MODEL, revision=REVISION, dtype=torch.bfloat16 if device == "cuda" else torch.float32).to(device)
print(f"parameters: {sum(p.numel() for p in model.parameters()):,}  dtype: {model.dtype}  device: {device}")
 
messages = [{"role": "user", "content": "In one sentence, what does a GPU driver do?"}]
inputs = tok.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(device)
t0 = time.time()
out = model.generate(**inputs, max_new_tokens=60, do_sample=False)
new = out[0, inputs["input_ids"].shape[1]:]
print(f"\n{tok.decode(new, skip_special_tokens=True)}\n")
print(f"{len(new)} tokens in {time.time() - t0:.2f}s")
  1. Write the Dockerfile. The PyTorch index is a build argument: the CPU index by default, the CUDA 13.2 index for GPUs.
Dockerfile
FROM python:3.12-slim
 
ARG TORCH_VERSION=2.15.0
ARG TORCH_INDEX=https://download.pytorch.org/whl/cpu
 
ENV PIP_NO_CACHE_DIR=1 PYTHONUNBUFFERED=1 HF_HOME=/models
WORKDIR /app
 
COPY requirements.txt .
RUN pip install "torch==${TORCH_VERSION}" --index-url "${TORCH_INDEX}" \
 && pip install -r requirements.txt
 
COPY run.py .
ENTRYPOINT ["python", "run.py"]
  1. Build and run the CPU image. The -v flag keeps downloaded weights in a named volume so later runs skip the download.
docker build -t llm-demo:cpu .
docker run --rm -v hf-cache:/models llm-demo:cpu

Expect torch 2.15.0+cpu, torch built for CUDA: None, parameters: 134,515,008, a one-sentence answer and a timing line. On an Apple silicon Mac, Docker builds a Linux arm64 image, and the run still uses the CPU, because containers cannot reach the Apple GPU.

  1. Build and run the GPU image on a Linux NVIDIA host.
docker build -t llm-demo:gpu --build-arg TORCH_INDEX=https://download.pytorch.org/whl/cu132 .
docker run --rm --gpus all -v hf-cache:/models llm-demo:gpu

Expect torch built for CUDA: 13.2, GPU visible: True, your GPU's name and dtype: torch.bfloat16.

  1. Break it on purpose, and record each error message. Run the GPU image without --gpus all (the app silently falls back to CPU). On a host with a driver older than 580, the GPU image reports that the driver is too old. Run docker run --rm --gpus all --entrypoint python llm-demo:gpu -c "import torch; print(torch.cuda.get_arch_list())" to see which architectures the wheel supports.

  2. Lock the full dependency set from the working image, so the next build is identical, and commit it.

docker run --rm --entrypoint pip llm-demo:cpu freeze > requirements.lock
docker images llm-demo

Then change the Dockerfile to install from requirements.lock. Compare the CPU and GPU image sizes from docker images: the GPU image is several gigabytes larger because it carries the CUDA libraries.

Check your work: both images (or the CPU one, if you have no GPU host) print the expected version lines and generate text, you have a requirements.lock, and your notes list the exact error each deliberate break produced. Push the folder to a public repository with a README stating the driver requirement.

Stretch: pin the base image by digest (docker images --digests python) instead of by tag, add a non-root user, and check whether the same container produces identical output on two machines with do_sample=False.

Check yourself

nvidia-smi shows CUDA Version 12.8, but your newly installed PyTorch wheel reports torch.version.cuda as 13.2 and fails at startup. What is the root-cause fix?

Why can the kernel driver not be packaged inside a container image?

A colleague wants to load a .bin model file downloaded from an unknown account. What is the main risk, and the better option?

On an older NVIDIA P100 GPU, a recent PyTorch CUDA 13 build fails with 'no kernel image is available for execution on the device'. What happened?

Recap

  • The GPU stack runs from kernel driver through CUDA runtime and libraries to PyTorch and your app; only the driver is shared with the host.
  • The CUDA version in nvidia-smi is a ceiling: the driver must be at least as new as the CUDA runtime bundled in your PyTorch wheel.
  • Prefer safetensors for weights; GGUF serves llama.cpp-style runtimes, ONNX serves portable runtimes, and pickles can execute code.
  • PyTorch publishes one wheel per CUDA version on separate indexes, so pin versions and the index, and lock transitive dependencies.
  • In containers the NVIDIA Container Toolkit injects the host driver; debug from the bottom of the stack up.

Go deeper