Virtualization and the GPU driver stack: hypervisors, IOMMU, MIG, one CUDA call down

What sits between your training code and a GPU that is not yours alone: the hypervisor, the IOMMU, the ways one GPU is shared, and one CUDA call from Python down through the driver and its firmware. Measured inside the VM this knowledge base runs in and against the hypervisor underneath it; the GPU side from NVIDIA's open kernel modules (no GPU here). A child of Topic: operating-systems. Data as of October 2026. Reading: 47 min, plus 26 in closed details.

The idea in one screen

Both layers between your training code and a cloud GPU get out of the way on the hot path: guest code runs directly on the CPU and a CUDA launch is a few stores into mapped memory plus a doorbell, so you pay only at the boundaries: a VM exit (about 0.92 µs here) each time the guest touches what the hypervisor must see, and a system call into the driver at start-up, allocation and errors.

Fig. 1: two stacks, one rule: the hot path never asks permission

  1. Two stacks. Left, the VM this page ran in: your process, the guest kernel, the hypervisor (QEMU 5.2 on Apple's Hypervisor.framework; a cloud uses KVM or Nitro in the same place), the CPU. Right, one CUDA call as NVIDIA's open kernel modules 615.71.09 lay it out: PyTorch, the CUDA runtime, the user-mode driver libcuda, the kernel driver nvidia.ko, the GSP firmware, the GPU.
  2. Guest code runs directly. The guest's arithmetic, its system calls and its page faults run on the CPU without the hypervisor seeing them: the stream passes through the hypervisor's layer without stopping.
  3. A VM exit at the boundary. A store to a device register, the idle instruction or an interrupt hands control to the hypervisor and back: 0.92 µs per exit measured on this laptop (section 2).
  4. A launch is stores plus a doorbell. libcuda writes the launch into memory the GPU can read and stores a token into the mapped doorbell register; the GPU fetches the work by DMA. No system call, and no exit even in a VM (section 9).
  5. ioctls at start-up, allocation and errors. The first call, an allocation or an error enters the kernel driver by ioctl, which on Turing and later GPUs forwards the work by RPC to the resource manager running as firmware on the GPU (section 9).

You need: limited direct execution, system calls and the cost of a context switch from the root Topic: operating-systems (section 9 there is this page's intuition); page tables and the TLB from Virtual memory; namespaces, cgroups and the device controller from Containers and isolation. CUDA programming is Topic: cuda-and-gpu-programming's; the GPU as silicon is Topic: hardware's; MIG as a cluster scheduling unit is Kubernetes for ML's.

Hypervisor (VMM)
the program that runs whole operating systems as guests, as a kernel runs processes.
VM exit
the CPU stopping the guest and handing control to the hypervisor with a reason, then resuming it.
Nested paging (EPT, stage 2)
a second page table, owned by the hypervisor, from guest-physical to host-physical addresses.
IPI
an inter-processor interrupt: one CPU interrupting another, for example to wake a thread.
virtio, virtqueue
a device interface made for VMs: shared rings in guest memory instead of emulated registers.
IOMMU
an MMU for devices: it translates and checks every DMA address a device issues.
MIG, MPS, time slicing
three ways to share one GPU, from hardware partitions to taking turns.
User-mode driver
libcuda.so.1, installed with the host's driver; the kernel driver is nvidia.ko.
GSP
the GPU System Processor: a processor on Turing and later GPUs that runs the driver's resource manager as firmware.
Channel, doorbell
a GPU work queue in memory, and the register store that tells the GPU the queue moved.
MechanismWhat it costs hereWhen it bites in MLCommand that shows it
VM exitmeasured 0.92 µs per exit on this laptop's hypervisoranything that traps often: interrupts, device registers, idleon a KVM host: perf kvm stat
Cross-CPU wake-up in a VMmeasured 25.3 µs, against 2.00 µs on one CPUdata-loader hand-offs, thread pools, NCCL proxy threadsgrep IPI /proc/interrupts
Nested page walkderived up to 24 memory reads per TLB miss, against 4large, random memory access in a VMperf stat -e dTLB-load-misses
virtio disk and networkmeasured 1 interrupt per request at queue depth 1, 0.11 at 32data loading inside a VMgrep virtio /proc/interrupts
IOMMU and passthroughnot run here: no IOMMU in this VMevery cloud GPU VM; GPU peer-to-peer and RDMAls /sys/kernel/iommu_groups
Sharing one GPUsource isolation differs completelyinference and notebooks on shared GPUsnvidia-smi mig -lgi
First CUDA call against the millionthmeasured the search for a driver, call by call; source launches need no system callslow start-up, "no CUDA-capable device"strace -f -e trace=openat,ioctl
Driver against runtime versionmeasured errors 35, 34 and 100 reproduceda new image on an old hostnvidia-smi, torch.version.cuda
How this page was measured, and the OSTEP chapter map (provenance)

Linux runs: Docker Desktop's Linux VM on an Apple M1 Pro (Linux 5.10.104-linuxkit, arm64, 5 virtual CPUs, about 10 GB), October 2026, images kb-os-lab:1 (the root's lab image) and kb-os-virt:1 (the CUDA topic's kb-gpu-lab:1: CUDA 13.4.2 toolkit for arm64, plus strace). Containers were not privileged; strace needed --cap-add SYS_PTRACE, and one CUDA case used --device-cgroup-rule 'c 195:* rwm', both stated where used. macOS runs, labelled as contrasts: the hypervisor process that runs the VM, and a tiny VM of our own built on Apple's Hypervisor.framework. There is no GPU here: everything above the kernel driver was run for real; the kernel driver and the GPU are taught from NVIDIA's open source and documentation and tagged not run here. Labels: measured ran here; source read from source or documentation. Timings on a shared laptop VM vary from run to run, so each is a median of three runs and the raw files show the spread. Scripts and raw outputs: src/exp/ and src/raw/ in the repository. The root page, section 9, gave the intuition in one screen; this page goes down to the code: the Linux kernel at the version that ran here (v5.10) and a current one (v6.12), QEMU with Apple's Hypervisor.framework, NVIDIA's open kernel modules at 615.71.09, and the CUDA 13.4 runtime and user-mode driver run for real in a container with no GPU.

OSTEPHereWhat this page adds
Appendix B, Virtual Machine Monitors1 to 4hardware virtualization (EL2, VMX), KVM's API, VM exits measured, nested paging, the information gap measured as a slow wake-up
6 Limited Direct Execution1, 2the same idea one level down: the guest kernel runs directly, the hypervisor keeps control through traps
19 TLBs, 20 Advanced Page Tables4two-dimensional page walks, VMIDs, huge pages in both stages
36 I/O Devices6, 7, 9virtqueues, DMA and the IOMMU, doorbells and command buffers on a GPU
26 to 28 Concurrency, Locks5why a sleeping lock's wake-up is dearer in a VM

OSTEP is free at pages.cs.wisc.edu/~remzi/OSTEP; Appendix B is vmm-intro.pdf. Read it alongside sections 1 to 4 here.

1. Virtual machines against containers, and what makes a CPU virtualizable

Appendix B, 6

The problem. A cloud provider sells slices of one big machine to strangers. Each wants root, their own kernel and drivers, and the certainty that the neighbour cannot read their memory or crash their kernel. A container cannot promise that: every container shares one kernel, so a kernel bug is everyone's bug. A virtual machine (VM) gives each customer a whole kernel of their own; the hypervisor (or virtual machine monitor, VMM) does for operating systems what an operating system does for processes.

How it works: limited direct execution, one level down. A kernel runs your program directly on the CPU and takes control back only on a system call, fault or timer (OSTEP chapter 6). A hypervisor does the same to a whole kernel: the guest kernel's instructions run directly, at full speed, and the hypervisor takes over only when the guest does something it must not do alone, such as touch a device or reprogram the interrupt controller. That hand-over is a trap; in a VM it is a VM exit. OSTEP's appendix calls it extending "the notion of limited direct execution" so the VMM can "interpose on key events (such as traps)" (OSTEP Appendix B).

arm64 (this laptop)Runsx86-64 equivalent
EL0your process (Python, the training job)ring 3
EL1the (guest) kernelring 0, VMX non-root mode
EL2the hypervisor (KVM's core, Apple's Hypervisor.framework)VMX root mode (Intel VT-x), or SVM host mode (AMD-V)
EL3firmware (secure monitor)SMM, roughly

Which instructions must trap. Popek and Goldberg (1974, Theorem 1, paraphrased): a VMM can be built if every sensitive instruction (one that reads or changes the machine's control state) is also privileged (traps outside the most privileged mode). Then the deprivileged guest kernel traps on every sensitive act and the hypervisor emulates it: trap and emulate. x86 broke the rule: Robin and Irvine "found that seventeen instructions violate" it, for example POPF, which in user mode silently ignores a change to the interrupt flag instead of trapping. Three answers followed:

Binary translationVMware: rewrite the guest kernel's problem instructions before they run. Any x86; complex.
ParavirtualizationXen: change the guest kernel to call the hypervisor directly (a hypercall). Fast; needs a modified guest.
Hardware supportIntel VT-x and AMD-V added a mode for the hypervisor (VMX root) and made sensitive guest instructions exit to it; ARM added EL2. Every cloud uses this, plus paravirtual devices (section 6).

Who is the hypervisor? Type 1 (bare metal): the hypervisor is what boots (Xen, VMware ESXi). Type 2 (hosted): a program on an ordinary OS; here, QEMU on macOS asking the macOS kernel, through Hypervisor.framework, to enter the guest. Linux's KVM blurs the two: a kernel module turns Linux into the hypervisor, and a user-space program (QEMU, Firecracker, cloud-hypervisor) provides the virtual devices. AWS's Nitro System uses "a custom-developed, minimized hypervisor based on KVM" with device work moved onto dedicated cards (AWS Nitro whitepaper).

The sources and examples behind trap and emulate (depth)

Popek and Goldberg: CACM 1974. Robin and Irvine examined the Pentium's instruction set in 2000 (USENIX Security 2000); besides POPF, SGDT/SIDT reveal where the real descriptor tables are. A guest kernel that executes POPF thinking it disabled interrupts would be wrong, and the hypervisor would never know. Binary translation scans the guest kernel's code before it runs and rewrites the problem instructions into safe sequences. On paravirtualization OSTEP says such a system "can be made to be nearly as efficient a system without a VMM".

Inside a hardware-virtualized VM, which loop slows down more against bare metal: a million getpid() system calls, or a million 4 KiB disk reads?

Fig. 2: where the isolation boundary sits

Containers: one kernel, separated by namespaces and cgroups (the Containers and isolation page owns how). VMs: one kernel per guest, separated by the CPU's virtualization hardware, so a guest kernel crash or exploit stays in its guest. The price is the boundary crossings of sections 2 to 6. Sandboxes for untrusted code (Firecracker, gVisor) sit between the two and are on the containers page.

2. A VM exit, measured

Appendix B

What an exit is. When the guest does something the hypervisor asked to see, the CPU stops the guest, saves its registers, switches to the hypervisor's privilege level and jumps to its handler with a syndrome saying why (on arm64 the exception class, EC; on x86 the exit reason). The handler emulates the effect and resumes the guest. Everything a guest does is either free (runs directly) or costs one of these round trips.

Measured: our own tiny VM on this laptop. This VM cannot run KVM (no /dev/kvm: the M1 Pro has no nested virtualization), but macOS's Hypervisor.framework has the same shape (create a VM, map memory, create a vCPU, hv_vcpu_run until an exit). src/exp/hvf_exits.c builds a VM with one vCPU and two instructions of guest code, an instruction that exits and a branch back to it, and times one exit round trip 20,000 times.

Fig. 3: a system call never leaves the guest; a device register store does

  1. Three privilege levels, two worlds. In the guest, your process runs at EL0 and the guest kernel at EL1. Below them, at EL2, the hypervisor: here Apple's Hypervisor.framework in the macOS kernel. QEMU, the program that emulates the devices, is an ordinary macOS process; each vCPU is one of its threads, sitting in hv_vcpu_run while the guest runs.
  2. getpid() stays in the guest. EL0 to EL1 and back, exactly as on bare metal: the guest kernel handles its own system calls and page faults, and the hypervisor never sees them.
  3. A store to a device register exits. str x1, [x2] to an address with no memory behind it: the CPU saves the guest's state, enters EL2 with exception class 0x24, and hv_vcpu_run returns into QEMU, which emulates the device and enters the guest again. One round trip: 0.92 µs.
  4. Every reason costs about the same. A hypercall (hvc #0, class 0x16) took 0.88 µs and the idle instruction (wfi, class 0x01) 0.88 µs: the floor is the trip to EL2 and out to QEMU and back, not the reason.
  5. A forced exit from another thread. Another host thread calls hv_vcpus_exit and the running vCPU is pulled out: 1.08 µs from the call to the exit. This is how a VMM interrupts a vCPU that is running guest code (section 5).
  6. About three system calls' worth. The root page measured a read system call at 0.316 µs; an exit is roughly three of them. Cheap once; a fast VM is designed to keep it rare.
Guest instructionWhy it exitsException classMedian per exit measured
hvc #0a hypercall: the guest asks the hypervisor for something0x160.88 µs
str x1, [x2] to an address with no memorya device register (MMIO): the hypervisor must emulate the device0x240.92 µs
wfi"wait for interrupt": the guest kernel's idle instruction0x010.88 µs
(another host thread calls hv_vcpus_exit)a forced exit, how a VMM interrupts a running vCPUcanceled1.08 µs from the call to the exit

measured macOS host, not the VM: Apple M1 Pro, Hypervisor.framework, 3 runs of 20,000 exits (2,000 kicks), median of the three run medians; timer resolution 0.042 µs. Raw: src/raw/hvf_macos.txt.

Reading it. About 0.9 µs per exit, whatever the reason, is the floor: the hardware switch to EL2, Apple's kernel code, the return to our user-space loop, and back. The guest's own system calls, page faults and arithmetic never exit; idle, device registers, timer and interrupt-controller registers, hypercalls and host interrupts do.

When it bites in ML
  • A GPU's work does not exit: with passthrough the GPU's registers are mapped straight into the guest, so writing a doorbell is an ordinary store (sections 7 and 9). The CUDA kernel itself never notices the VM.
  • What exits is the CPU side: interrupts, idle and wake-ups (section 5), disk and network I/O (section 6). A data loader with many threads handing work to each other is the part of a training job that pays.

perf kvm stat live

On a KVM host (not inside the guest): exits per second by reason, and the time each took.

The hypervisor's API as a program: a minimal KVM monitor, and where each exit is handled (depth)

KVM exposes all of this to an ordinary Linux process through one device file. The shape of every VMM (QEMU, Firecracker) is this loop; LWN's Using the KVM API builds a complete one in about 100 lines.

a minimal KVM monitor (C; the calls of LWN's example; not run here: this VM has no /dev/kvm)
int kvm  = open("/dev/kvm", O_RDWR);
int vm   = ioctl(kvm, KVM_CREATE_VM, 0);             // a VM is a file descriptor
void *mem = mmap(NULL, 0x1000, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
// guest "physical" memory is ordinary memory of this process
struct kvm_userspace_memory_region r = { .guest_phys_addr = 0x1000, .memory_size = 0x1000, .userspace_addr = (long)mem };
ioctl(vm, KVM_SET_USER_MEMORY_REGION, &r);
int vcpu = ioctl(vm, KVM_CREATE_VCPU, 0);             // a virtual CPU is another fd
struct kvm_run *run = mmap(NULL, mmap_size, PROT_READ|PROT_WRITE, MAP_SHARED, vcpu, 0);
for (;;) {
    ioctl(vcpu, KVM_RUN, 0);                          // enter the guest; returns on an exit
    switch (run->exit_reason) {
    case KVM_EXIT_IO:   /* the guest touched an I/O port: emulate the device */  break;
    case KVM_EXIT_MMIO: /* a device register in memory: emulate it */          break;
    case KVM_EXIT_HLT:  return 0;                                    // the guest idled
    }
}

Kernel side, Linux v6.12: case KVM_RUN, KVM_CREATE_VCPU, KVM_SET_USER_MEMORY_REGION; the exit codes KVM_EXIT_IO 2, KVM_EXIT_HLT 5, KVM_EXIT_MMIO 6. Only exits the kernel cannot finish itself come back to user space; many (timer, some interrupt work) are handled inside KVM.

ExitKVM on arm64 (v6.12)KVM on Intel (v6.12)Typical cause
IdleESR_ELx_EC_WFxEXIT_REASON_HLTa guest CPU has nothing to run
Device registerESR_ELx_EC_DABT_LOWIO_INSTRUCTION, EPT_VIOLATIONemulated devices, virtio "kicks" (section 6)
System registerESR_ELx_EC_SYS64MSR_WRITE, CPUIDtimers, interrupt controller, feature probing
HypercallESR_ELx_EC_HVC64VMCALLparavirtual services (steal time, power off)
Interrupt for the host(IRQ exit)EXTERNAL_INTERRUPTa device of the host's fired while the guest ran

3. Cloud instances, and the VM these pages ran in

Why it matters. Every number on these OS pages came from inside a VM, and so does almost every cloud GPU you will train on. Both are recognisable from inside, and both pay the same kinds of cost: exits for idle and devices, slower cross-CPU wake-ups, two-stage page walks, and time the host takes without telling you.

On a cloud instance, the questions to ask
  • systemd-detect-virt names the hypervisor (kvm, amazon, microsoft, xen) from firmware tables; lspci -nn shows virtio or vendor-specific devices next to the passed-through GPU.
  • grep -c ^processor /proc/cpuinfo counts vCPUs, which on many instance types are hyperthreads, not cores; lscpu shows threads per core.
  • top's st column is steal time where the hypervisor reports it; a large value means your vCPUs wait for the host (section 5).

This VM, in one line. On macOS, Docker Desktop 4.11 starts the Linux VM as an ordinary process: QEMU 5.2 with -accel hvf (guest code runs directly through Hypervisor.framework), -smp 5 -m 10240 (5 vCPUs, each a thread of the QEMU process, and 10 GiB of "physical" memory that is ordinary memory of that process), QEMU's generic virt board with a GICv2 interrupt controller emulated by QEMU itself, and virtio disk and network. Inside, arm64 has no CPUID "hypervisor" bit, but the hardware gives it away: GIC-0 on every interrupt line, millions of IPIs, a virtio disk with one queue per vCPU, steal time always 0, no /dev/kvm and no IOMMU (table in the closed block below).

measured src/exp/vmid.sh in an unprivileged container; raw: src/raw/vmid.txt, which also lists the kernel's virtualization config (CONFIG_PARAVIRT=y, CONFIG_VIRTIO_BALLOON=y, CONFIG_KVM=y compiled in but unusable here).

The VM from both sides: QEMU's command line, PCI and virtio devices, interrupts (recorded outputs)
What the guest seesWhat it tells you
GIC-0 on every line of /proc/interruptsLinux's GICv2 driver (irq-gic.c names its chip "GIC-%d"); its CPU interface is memory-mapped registers that QEMU emulates. Section 5 shows why that matters.
IPI0, IPI1 counts in the millionsinter-processor interrupts, the subject of section 5
virtio1-req.0 to .4, one per CPUthe virtual disk has one request queue per vCPU (multi-queue), each with its own interrupt (section 6)
clock source , cpuidle driver nonetime comes from the CPU's own counter (virtualized by the hardware, no exit to read it); idle is a plain wfi, which exits
steal time on every CPUthis hypervisor offers no paravirtual steal clock, so the guest cannot see time stolen by macOS (section 5)
no /dev/kvm, no /sys/class/iommuno nested virtualization (KVM inside this guest is impossible) and no virtual IOMMU (section 7 is from sources)

The VM process's command line (disk path, console pipe, MAC address and network token removed):


measured ps -o args= of the VM process and qemu-system-aarch64 --version on the macOS host (src/exp/host_qemu.sh; raw: src/raw/host_qemu.txt).

ArgumentMeans
-accel hvfrun guest code directly on the CPU through Apple's Hypervisor.framework (the exits of section 2), instead of emulating every instruction in software
-cpu host -smp 5 -m 10240the guest sees this CPU's features, 5 virtual CPUs and 10 GiB of memory
-machine virt,highmem=offQEMU's generic arm64 board: a PL011 serial port, a PL031 clock, a PCIe host bridge, and, when no version is asked for and KVM is not in use, a GICv2 interrupt controller emulated by QEMU itself (finalize_gic_version, hw/arm/virt.c L1802-1806, QEMU v6.2.0)
-device virtio-blk-pci, virtio-net-devicea paravirtual disk on PCI and a paravirtual network card on a memory-mapped bus (section 6)
-kernel ... -append ... mitigations=offboot the linuxkit kernel directly, with CPU side-channel mitigations off
PCI devices: vendor:device, class, driver

1b36:0008 is QEMU's PCIe host bridge (Red Hat's vendor ID); 1af4:1001 is a virtio block device.

virtio devices: device ID, vendor, driver

Device 1 is network, 2 is block; vendor 0x554d4551 is the ASCII bytes "QEMU" read as a little-endian number.

/proc/interrupts (the lines that matter)

The QEMU process on the Mac has 5 vCPU threads. While your training job in this VM is idle, what are those threads doing on macOS?

4. Memory: two translations, and the 24-step page walk

Appendix B, 19, 20

The problem. The guest kernel believes it owns "physical" memory from address 0 and builds page tables onto it. That memory is really part of the hypervisor's process (QEMU's 10 GiB here), scattered across the host's RAM. So every guest access needs two translations: guest virtual to guest physical (the guest's tables), then guest physical to host physical (tables the hypervisor owns and the guest cannot see). Virtual memory owns the first translation, the TLB and huge pages; this is the second layer.

Shadow page tables, then nested paging. Before hardware help, the hypervisor kept a shadow page table from guest virtual straight to host physical and write-protected the guest's own tables, so every page-table update exited to be mirrored. With nested paging (Intel EPT, AMD NPT, ARM stage 2) the CPU walks both sets itself, the guest edits its tables with no exits, and the TLB caches the combined result tagged with a VM identifier (VMID on arm64, VPID on Intel) so switching VMs does not flush it. The price moves to the TLB miss: every pointer in the guest's walk is guest-physical and needs a host walk of its own.

Fig. 4: one TLB miss in a VM, each plate one memory reference

Predict before it plays: with 4 guest levels and 4 host levels, how many memory reads does one miss take?

  1. A TLB miss in a VM. The guest's table register holds a guest-physical address, so the CPU cannot read even the first guest table until the host's tables have translated that address. The four large plates are the guest's tables; the small plates in front of each are the host's (stage-2) tables. Every plate is one memory reference.
  2. Guest level 0: a host walk, then the entry. Four host reads turn the table's guest-physical address into a host-physical one; then one read of the guest's own entry: 5 references so far.
  3. Guest level 1: the same again. The entry gave the next table's address, again guest-physical: another four host reads plus the entry, 10.
  4. Guest level 2. Four host reads and the entry: 15.
  5. Guest level 3. Four host reads and the entry: 20. This entry gives the data page's guest-physical address.
  6. The data page needs one more host walk. Four reads: 24 references in all for one miss, against 4 without a VM.
  7. The TLB caches the combined result. One entry from guest virtual to host physical, tagged with the VM's identifier (VMID on arm64, VPID on Intel) so switching VMs does not flush it. Page-walk caches keep most real misses far shorter than this worst case.
  8. Huge pages shorten both walks. With 2 MiB pages backing the guest on the host, every host walk ends one level early: 19 references. With 2 MiB pages in both stages: 15.

derived with g guest levels and h host levels, each of the g guest table pointers needs a host walk (h reads) plus the read of the guest entry, and the final data address one more host walk: g(h+1) + h = (g+1)(h+1) - 1 references. Analysed in Bhargava et al., ASPLOS 2008, which also proposed the page-walk caches that keep most misses far shorter in practice.

ConfigurationMemory references on a full TLB miss
No VM, 4-level page table4
VM, 4 KiB pages in both stages (4 x 4 levels)24
VM, host backs the guest with 2 MiB pages (4 x 3)19
VM, host backs with 1 GiB pages (4 x 2)14
VM, 2 MiB pages in both stages (3 x 3)15
VM, five-level tables in both stages (5 x 5)35
Cost measured here, inside the VM: the root page measured a TLB miss at 7.6 ns against 1.1 ns for a hit. That already includes the stage-2 walk; separating it needs the same test on bare metal, which this setup cannot run. Most misses are far shorter than the worst case because the walk's upper levels are cached.
When it bites in ML
  • Large, random memory access: embedding tables, a shuffled in-memory dataset, a hash join in a data pipeline. Sequential tensor work hits the TLB and barely notices.
  • Huge pages help twice in a VM, and only if both layers use them: transparent huge pages in the guest, and huge pages backing the guest on the host (the cloud's choice, not yours).

Memory overcommit, and why GPU VMs cannot do it. Because guest memory is memory of the hypervisor's process, a host can promise its VMs more than it has: a balloon driver in the guest gives pages back on request, KSM merges identical pages across VMs, and the host can swap. A VM with a passed-through device cannot: the device writes guest memory by DMA at any moment, so every page it might touch must stay put. VFIO pins the pages it maps for a device, and QEMU maps all of guest RAM for it, so a GPU VM's whole memory is pinned when it starts: one reason large GPU VMs boot slowly and cannot be overcommitted.

Sources for overcommit and pinning (depth)

This kernel has CONFIG_VIRTIO_BALLOON=y; KSM, kernel docs. VFIO charges pinned pages against the locked-memory limit (vfio_pin_map_dma checks RLIMIT_MEMLOCK, Linux v6.12). QEMU maps every RAM region of the guest for the device as the region appears (vfio_listener_region_add calls vfio_dma_map, hw/vfio/common.c L864 and L1063, QEMU v6.2.0). Shadow page tables are described in OSTEP Appendix B: correct, but every page-table update and many page faults cost an exit.

5. Interrupts, and why a cross-CPU wake-up costs ten times more here

Appendix B, 26 to 28

The question the sibling pages left open. Scheduling measured a context switch on one CPU at 1.30 to 1.56 µs but a hand-off between two CPUs at 25.6 to 51.4 µs in this VM; Concurrency found the same for a futex wake-up on another CPU. Both suspected the hypervisor. This section measures it and follows the path through the hypervisor's source.

Inter-processor interrupts. An IPI is one CPU interrupting another. When thread A on CPU 1 writes to a pipe and thread B, asleep on it, last ran on CPU 2, the kernel marks B runnable on CPU 2 and sends CPU 2 a reschedule IPI. An idle arm64 CPU sleeps in wfi, so it always needs the interrupt. Linux also sends function-call IPIs ("run this on your CPU now"); membarrier() sends one to every CPU running a thread of the caller and waits, a direct way to time an IPI round trip from user space.

Test (CPUs of the VM)One way, µs measuredIPIs per operation
Pipe hand-off, both processes on CPU 12.000 (a context switch on one CPU)
Pipe hand-off, CPUs 1 and 2, idle between hand-offs25.31 reschedule IPI to each side per round trip
Same, with a nice 19 busy loop keeping both CPUs awake15.41 reschedule IPI to each side per round trip
Spin on one shared cache line, CPUs 1 and 2 (nobody sleeps)0.0540
membarrier with no other thread running0.54 per call0 (just the system call)
membarrier, one thread spinning on CPU 215.0 per call1 function-call IPI to CPU 2
membarrier, threads spinning on CPUs 2, 3, 491.1 per call1 function-call IPI to each

measured src/exp/ipi.c in a container with --cpuset-cpus 1,2,3,4; medians of 3 runs (raw: src/raw/ipi.txt). After each test the program reads /proc/interrupts and divides the IPI counts it added by the number of operations. The sibling pages' numbers came from other runs on the same VM at other times; the spread between runs is itself a property of a laptop VM shared with other work.

Reading it. Moving the byte between CPUs through memory costs 0.054 µs: the cache-coherence hardware is fast. The interrupt is slow: one IPI round trip costs about 14.5 µs (membarrier with one peer, minus the bare system call), and a sleeping wake-up 12.7 times a same-CPU switch. Three IPIs at once cost 30.2 µs each, 2.1 times what three independent ones would: they queue behind each other somewhere.

Who does what, step by step, and the measured totals

Steps from the Linux v5.10 GICv2 driver and QEMU v6.2.0's HVF code (the upstream form of the patches in Docker's QEMU 5.2). Times: the totals are the one-way medians measured above; the per-step costs are measured separately on the macOS host (section 2's exits and kick, and a host thread woken from pselect the way QEMU does it). Bare hardware: macOS's own pipe hand-off on the same laptop; bare-metal Linux was not measured here.

Where the time goes. On this guest's emulated GICv2, sending an IPI is a store to a distributor register, and taking one is a load to acknowledge it and a store to end it. All three are device registers, so all three are VM exits into QEMU, which emulates the controller while holding its one global lock. If the target vCPU was idle, its host thread is asleep in pselect and must be woken with a signal. Step through it, against the same hand-off on bare hardware:

Fig. 5: one wake-up, three exits, and a sleeping host thread when the target is idle

  1. Thread A on vCPU 1 writes to the pipe. The guest kernel finds thread B asleep; B last ran on vCPU 2, which is idle, so it must send vCPU 2 a reschedule IPI (resched_curr, smp_send_reschedule).
  2. vCPU 1 writes the distributor register: VM exit 1. A store to the emulated GICv2 distributor (GICD_SGIR) is an MMIO access: vCPU 1's host thread returns from hv_vcpu_run into QEMU. One exit cost 0.92 µs on this laptop.
  3. QEMU emulates the interrupt controller. Holding its global lock, QEMU marks the interrupt pending for vCPU 2 and kicks vCPU 2's thread: a signal plus hv_vcpus_exit. vCPU 1 re-enters the guest.
  4. macOS wakes vCPU 2's sleeping host thread. vCPU 2 had run wfi (idle), exited, and QEMU put its thread to sleep in pselect. The signal wakes it: waking an idle host thread this way took 29.2 µs (median) in a separate test.
  5. vCPU 2's thread injects the interrupt. It takes the global lock, marks the virtual IRQ pending (hv_vcpu_set_pending_interrupt) and enters the guest.
  6. The guest acknowledges the IPI: VM exit 2. Linux reads the CPU interface's acknowledge register (GICC_IAR): another MMIO access, another exit.
  7. The guest ends the IPI: VM exit 3. After the handler, Linux writes the end-of-interrupt register (GICC_EOIR): a third exit.
  8. Thread B runs and reads the byte. The scheduler on vCPU 2 switches to B. Measured: 25.3 µs one way for the whole path.
The pieces of the path, each measured on the macOS host (depth)
Piece of the pathCost measured on the macOS host
One VM exit (MMIO), three per wake-up (send, acknowledge, end)0.92 µs each, 2.7 µs for three
Forcing a running vCPU out (hv_vcpus_exit)1.08 µs
Waking an idle host thread from pselect with a signal29.2 µs median (the fastest tenth under 14.4 µs, the slowest tenth over 157.1 µs)
The same pipe hand-off natively on macOS1.80 µs one way

So. With the target idle, the wake-up is dominated by the host waking a sleeping vCPU thread: about 29 µs on this laptop, the same size as the 25.3 µs measured inside. With the target busy, no host thread sleeps and 15.4 µs remain: exits and the kick explain 3.8 µs; the other 11.5 µs are QEMU's interrupt-controller emulation and the guest's scheduler work, not measured separately. The superlinear cost of three IPIs fits exits queuing on QEMU's single global lock (likely, not traced). A hand-off inside the VM was 14.0 times the same hand-off natively on the host.

How real hypervisors avoid most of this source
  • Interrupt controller in the hypervisor's kernel, helped by hardware: KVM's in-kernel controller, and GICv3's virtual CPU interface, Intel's APICv and posted interrupts or AMD's AVIC, let the guest acknowledge and end interrupts without exiting.
  • Halt polling: KVM, or the guest itself, polls briefly before sleeping an idle vCPU, trading CPU for wake-up latency.
  • Dedicated cores: a vCPU pinned to its own physical core never waits for the host scheduler.
The same, with the kernel documentation's words (depth)
How real hypervisors avoid most of this source
  • Interrupt controller in the hypervisor's kernel, helped by hardware. KVM emulates it in the kernel (no trip to user space), and with GICv3's virtual CPU interface (arm64), APICv and posted interrupts (Intel) or AVIC (AMD), the guest acknowledges and ends interrupts without exiting at all.
  • Halt polling. KVM can poll briefly before putting an idle vCPU to sleep, "at least saving us a trip through the scheduler, normally on the order of a few micro-seconds" (halt-polling.rst, Linux v6.12); a guest can poll before halting, so that "a remote vCPU [can] avoid sending an IPI" and "the VM-exit cost can be avoided" (guest-halt-polling.rst).
  • Dedicated cores. Instances that pin each vCPU to its own physical core never wait for the host scheduler; small or burstable instances share cores and do.

Steal time. When the host runs something else while your vCPU wants to run, the guest only learns of it through a paravirtual clock. This hypervisor offers none, so the steal column here is 0 on every CPU even while macOS runs other programs. KVM reports it; on a cloud VM, top's st or the 8th number of the cpu lines in /proc/stat is the noisy neighbour made visible (Scheduling, CPU accounting).

When it bites in ML, and the fixes
  • Fine-grained hand-offs between threads (DataLoader workers to the main process, a pin-memory thread, thread pools that sleep between tasks, futex wake-ups): 10 to 30 µs each in a VM instead of 1 to 2. Hand off less often: a batch per queue message, not a sample; prefetch_factor so a worker is never woken for one item.
  • Step-time jitter on small or shared instances: steal time and slow wake-ups show up as a long tail. Prefer dedicated physical cores for latency-sensitive input pipelines; watch st.
  • Spinning sidesteps the wake-up at the price of a core: NCCL's proxy threads busy-poll while work is in flight; glibc's adaptive mutexes and OpenMP's wait policy spin briefly.
The same list, with every example (depth)
When it bites in ML, and the fixes
  • Fine-grained hand-offs between threads: DataLoader workers handing batches to the main process, a pin-memory thread, thread pools that sleep between tasks (OpenMP, Python's ThreadPoolExecutor), futex wake-ups. In a VM each hand-off is 10 to 30 µs instead of 1 to 2. Hand off less often: bigger work items per queue message (a batch, not a sample), prefetch_factor so a worker is never woken for one item.
  • Step-time jitter on small or shared instances: steal time and slow wake-ups show up as a long tail, not a mean shift. Prefer instance types with dedicated physical cores for latency-sensitive input pipelines; watch st.
  • NCCL's proxy threads busy-poll while work is in flight, which sidesteps the wake-up cost at the price of a CPU each. Likewise keep communicating threads near each other and let short waits spin (glibc's adaptive mutexes, OpenMP's wait policy) where a core can be spared.

grep -E 'IPI0|IPI1|Rescheduling|Function call' /proc/interrupts

Run it twice, a second apart: the difference is IPIs per second per CPU (x86 names them RES and CAL).

The wake-up path in source, line by line (depth)

The waker calls resched_curr, which sends the reschedule IPI (smp_send_reschedule). The only way to skip it is a CPU that is idle but polling a flag (set_nr_if_polling); an arm64 CPU idles in wfi (__cpu_do_idle). membarrier: membarrier.c L170 and L264, Linux v5.10. On a GICv2 the send is gic_ipi_send_mask writing GIC_DIST_SOFTINT; taking it is gic_handle_irq: GIC_CPU_INTACK, GIC_CPU_EOI. QEMU runs hv_vcpu_run between unlocking and relocking its global lock, and MMIO exits become address_space_write (hvf.c L1119-1175, QEMU v6.2.0); idle vCPUs sleep and are kicked in hvf_wait_for_ipi, hvf_kick_vcpu_thread. The host's idle cores sleep deeply, and a woken thread may land on a core that was asleep. Steal time accounting: cputime.c L237-243; arm64 asks the hypervisor through a firmware call, has_pv_steal_clock.

The VM's vCPU 2 is running a busy loop when vCPU 1 sends it an IPI. Which of these does not happen in this VM?

Notifications are the cost: batching buys them back

Predict the kicks and interrupts for each mode before it plays.

An illustration of the protocol with four requests; the measured ratios are in the table below.

6. Devices without the exits: virtio

36

The problem. An emulated real disk means the guest's normal driver pokes device registers, and every poke exits to the hypervisor: several exits per 4 KiB read, plus an emulated interrupt with its own exits (section 5).

How virtio works. virtio is a device interface made for VMs: guest and hypervisor share a virtqueue in guest memory, in three parts:

Descriptor tableentries of (guest address, length, flags, next): "here is a buffer" (struct vring_desc)
Available ringwritten by the guest: "these descriptor chains are ready for you" (struct vring_avail)
Used ringwritten by the device: "I finished these, this many bytes" (struct vring_used)

A request is three descriptors (header "read sector N", data buffer, status byte). The guest adds them, bumps the available index, and only then kicks the device: one register write, one exit. The device reads the request straight out of guest memory, does the I/O, writes the used ring and injects one interrupt. With the event index feature each side says "notify me only when your index passes N", so a busy queue needs neither a kick per request nor an interrupt per completion.

virtio in the specification and the kernel source (depth)

virtio: Russell, virtio, 2008; OASIS VIRTIO 1.2 specification; the three parts in include/uapi/linux/virtio_ring.h, Linux v5.10. The event index is VIRTIO_RING_F_EVENT_IDX, bit 29 (vring_need_event, used by virtqueue_kick_prepare_split). Both of this VM's virtio devices offer it (section 3's feature bits). For QEMU, the device side reads guest memory as its own memory.

Fig. 6: four 4 KiB reads through one virtqueue

  1. An empty queue. The guest has four 4 KiB reads to do, one at a time (queue depth 1). Each request needs three descriptors: a header (read sector N), the data buffer, a status byte.
  2. Request 1 posted. The guest driver fills the three descriptors and puts the chain's head in the available ring: plain memory writes, no exit yet.
  3. Kick: one register write, one VM exit. The device has no idea the ring moved until the guest notifies it; with nothing else outstanding, the guest must.
  4. The device does the read. QEMU reads the request out of guest memory, reads the disk image, writes the data straight into the guest's buffer and adds a used entry.
  5. Interrupt: request 1 completes. One injected interrupt (with its own exits, section 5); the guest frees the descriptors and only then issues the next read.
  6. Requests 2, 3 and 4: the same four beats. One request at a time, each pays its own kick and its own interrupt: four kicks and four interrupts for four reads. Measured at queue depth 1: 1.0 interrupt per request.
4 KiB random O_DIRECT reads, 20,000 eachQueue depth 1Queue depth 32
Requests per second1574860975 (3.9 times)
Time per request63.5 µs (1 / rate)508.6 µs mean completion latency (Little's law: 32 / rate = 524.8 µs)
virtio-blk interrupts per request1.00.11: 8.9 completions per interrupt

measured fio 3.33 with libaio on a 256 MiB file on the VM's virtio-blk disk, interrupts counted from the virtio1-req.* lines of /proc/interrupts and requests from /sys/block/vda/stat (src/exp/virtio.sh; raw: src/raw/virtio.txt). The disk image is a file on the Mac's SSD that macOS caches, so absolute times are not a real NVMe drive's; the Storage page measured the disk side in depth.

Reading it. At queue depth 1, every request pays its own kick and its own interrupt, each with its exits; at depth 32, the event index lets one interrupt report about nine completions and the rate nearly quadruples. This is the I/O version of section 5's lesson: in a VM, notifications are the expensive part, and batching is how you buy them back.

Device in QEMU (here)the kick exits to QEMU in user space, which does the I/O with system calls.
vhostthe data path moves into the host kernel: the kick wakes a kernel thread, no trip to QEMU.
vhost-useranother user-space process polls the rings (DPDK, SPDK): no notifications while busy.
vDPA, passthroughthe NIC implements virtqueues itself, or the guest gets a real device (sections 7, 8).
The four device paths in more detail (depth)
Device in QEMU (here)The kick exits to QEMU in user space, which does the I/O with ordinary system calls on the disk image.
vhostThe device's data path moves into the host kernel (vhost-net; this kernel builds it as a module, CONFIG_VHOST_NET=m): the kick wakes a kernel thread, no trip to QEMU.
vhost-userThe data path runs in another user-space process polling the rings (DPDK for networks, SPDK for storage): no notifications at all while busy.
vDPA, passthroughThe NIC itself implements virtqueues (vDPA), or the guest gets a real device or a slice of one (sections 7, 8): the hypervisor leaves the data path.
When it bites in ML
  • Small random reads from a virtual disk at queue depth 1 (a dataset of millions of small files read one at a time) pay the notification costs on every file. Shards read sequentially with several outstanding requests do not.
  • The network of a cloud VM is a virtio or vendor paravirtual NIC unless RDMA NICs are passed through: the data path for checkpoints to object storage, not for NCCL on GPU clusters (section 7).

grep virtio /proc/interrupts; cat /sys/block/vda/queue/scheduler

7. The IOMMU and device passthrough: giving a VM a real GPU

36

not run here: this VM has no IOMMU and no device to pass through; taught from the kernel's VFIO documentation and source, and NVIDIA's NCCL guide.

The problem. A GPU cannot be emulated at any useful speed, so the guest is given the real device (passthrough). But a device writes to memory by DMA (direct memory access: the device itself reads and writes RAM, without the CPU), using physical addresses. A guest driver programs the GPU with guest-physical addresses, which are wrong on the host; worse, a malicious guest could program it to write anywhere in the host's memory.

How it works: an MMU for devices. The IOMMU (Intel VT-d, AMD-Vi, ARM SMMU) sits between devices and memory and translates every DMA address through page tables of its own, one set per device domain. The hypervisor fills them so the device's addresses are the guest's physical addresses, mapped to exactly the host pages backing that guest and nothing else. The same unit remaps the device's interrupts so they reach the right guest.

Fig. 7: the GPU speaks guest-physical; the IOMMU makes it land in this guest only

  1. A GPU passed through to VM A. The guest's own driver programs the GPU with guest-physical addresses, here a buffer at 0x1000. Below, host RAM page by page: pages backing VM A, pages of another guest B, and the hypervisor's own (addresses and layout illustrative).
  2. The GPU's DMA crosses the IOMMU. Through the PCIe switch the write reaches the IOMMU, which looks 0x1000 up in VM A's domain table, a page table the hypervisor filled, and sends it to the host page that backs VM A's 0x1000.
  3. An address outside VM A is blocked. 0x9000 has no entry in VM A's table: the DMA faults at the IOMMU and never reaches guest B's page or the host's. The same unit remaps the device's interrupts so they reach VM A only.
  4. Every page it may touch is pinned. A device cannot take a page fault the way a CPU can, so VFIO pins every page it maps into the IOMMU, and QEMU maps all of guest RAM: the whole VM's memory is locked at start, with no balloon, KSM or host swap (section 4).
  5. Peer to peer must go up and back. A GPU and a NIC under one PCIe switch could talk directly. In a VM, Access Control Services force their traffic up through the IOMMU and back down, so GPU-to-NIC bandwidth depends on the IOMMU path and on ATS (below).

Linux exposes this as VFIO: "from a device and host perspective, this simply turns the VM into a userspace driver" (VFIO documentation, Linux v6.12).

VFIO as a program: the steps of the kernel documentation's example (depth)

"The VFIO driver is an IOMMU/device agnostic framework for exposing direct device access to userspace, in a secure, IOMMU protected environment". The steps of its own example:

int container = open("/dev/vfio/vfio", O_RDWR);          // an IOMMU context
int group = open("/dev/vfio/26", O_RDWR);              // the device's IOMMU group
ioctl(group, VFIO_GROUP_SET_CONTAINER, &container);
ioctl(container, VFIO_SET_IOMMU, VFIO_TYPE1_IOMMU);
ioctl(container, VFIO_IOMMU_MAP_DMA, &dma_map);       // "device address X is this memory": pins it
int device = ioctl(group, VFIO_GROUP_GET_DEVICE_FD, "0000:06:0d.0");
// then mmap the device's registers (BARs) and hand them to the guest

From vfio.rst lines 177-213. Mapping pins the pages (vfio_pin_pages_remote), which is section 4's "a GPU VM cannot overcommit memory". Newer kernels add iommufd, a general replacement for the container.

IOMMU groups and ACS. The IOMMU can only isolate what it can tell apart. Devices behind a bridge that lets them talk to each other directly, without passing the IOMMU, are inseparable: "a group is a set of devices which is isolatable from all other devices in the system. Groups are therefore the unit of ownership used by VFIO" (vfio.rst lines 55-71). PCIe switches use Access Control Services (ACS) to force device-to-device traffic up through the IOMMU, which makes small groups possible. That is exactly the tension with GPU clusters:

Peer-to-peer GPU traffic against isolation

NCCL's guide: on bare metal, "IO virtualization (also known as VT-d or IOMMU) can interfere with GPU Direct by redirecting all PCI point-to-point traffic to the CPU root complex, causing a significant performance reduction or even a hang", so bare-metal clusters disable ACS on their PCIe switches. In a VM that is not an option: "Virtual machines require ACS to function, hence disabling ACS is not an option. To run with maximum performance inside virtual machines, ATS needs to be enabled in network adapters" (ATS, Address Translation Services, lets the device cache IOMMU translations itself). And NCCL reads the PCI topology from /sys: "Having /sys expose a virtual PCI topology can result in sub-optimal performance" (NCCL GPU troubleshooting).

What passthrough costs. Once set up, almost nothing on the data path: the GPU's registers are mapped into the guest by stage-2 page tables, so a doorbell write is an ordinary store, and the GPU's DMA goes through the IOMMU's translation cache. The costs are at the edges: pinning all guest memory at boot, IOTLB misses for scattered DMA, interrupts that must be remapped, and a guest that sees whatever PCI topology the hypervisor chose to show it.

When it bites in ML
  • Multi-GPU training inside VMs: whether GPU-to-GPU and GPU-to-NIC traffic goes peer to peer or through the CPU decides all-reduce bandwidth. Check what NCCL saw (NCCL_DEBUG=INFO) and the topology (nvidia-smi topo -m); a VM's real topology can be given to NCCL as an XML file (NCCL_TOPO_FILE; "by default, NCCL will load /var/run/nvidia-topologyd/virtualTopology.xml if present", NCCL environment variables).
  • Slow or failing peer-to-peer with "OK" from nvidia-smi topo -p2p on bare metal: IOMMU settings or ACS, per the NCCL guide.
  • A GPU VM that takes minutes to boot: its memory is being pinned and mapped.

ls /sys/kernel/iommu_groups/; lspci -nnk | grep -A3 -i nvidia

On a host, a passed-through GPU shows Kernel driver in use: vfio-pci; inside the guest the same GPU shows nvidia.

A VM with a passed-through GPU is given 512 GiB of memory. Why can the host not lend 200 GiB of it to another VM while this one is idle?

8. SR-IOV and the ways to share one GPU

not run here: no GPU; from NVIDIA's MIG, MPS, vGPU and GPU Operator documentation and the kernel's SR-IOV documentation.

The problem. Passthrough gives one guest a whole device. An 80 GB data-centre GPU is far more than a notebook, a small model's inference server or a CI job needs, and an idle GPU is expensive. The question is how to split one GPU between several processes, containers or VMs, and what each split gives up.

SR-IOV first, because NICs use it. Single Root I/O Virtualization lets one PCIe device present a physical function (PF, the full device, managed by the host) and many lightweight virtual functions (VFs), each with its own PCI identity, so each can be passed through to a different VM with section 7's machinery. On Linux you create them by writing a number to /sys/bus/pci/devices/<address>/sriov_numvfs (pci-iov-howto.rst, Linux v6.12). This is how a GPU VM gets its own slice of an InfiniBand or RoCE NIC for RDMA.

Why GPUs are harder: how the GPU itself schedules. A GPU runs work from one CUDA context (the per-process state: address space, loaded kernels, streams) concurrently, but "work launched to the compute engine from work queues belonging to different CUDA contexts cannot execute concurrently": between processes the GPU time-slices (MPS architecture). Every sharing scheme is a different answer to that:

Fig. 8: three ways to put jobs A and B on one GPU: take turns, merge, or cut

  1. One GPU, as MIG sees it. An A100 40GB: 7 compute slices (groups of SMs) in a row, time running from back to front, and 8 memory slices below (L2 banks, memory controllers and DRAM). Jobs A (blue) and B (purple) both want it.
  2. Time slicing: take turns. Contexts of different processes cannot run at once, so the GPU switches between A and B over time, each getting the whole chip in its turn. Both allocate from one pool of memory: no memory limit and no fault isolation between them.
  3. MPS: merge. One server process merges A's and B's work, so both run on the SMs at the same moment. Their address spaces are separate, but memory bandwidth and caches are shared and an error in one can affect the other.
  4. MIG: cut. A 4g.20gb instance at memory slice 0 for A and a 3g.20gb at slice 4 for B: each has its own SMs, L2 slices, memory controllers and DRAM, so its own memory, bandwidth and faults.
  5. Up to seven instances. Seven 1g.5gb instances, each a 5 GB GPU to CUDA (CUDA_VISIBLE_DEVICES=MIG-<uuid>), reconfigured only while the GPU is idle. vGPU puts either time slicing or a MIG instance behind a hypervisor; passthrough is one whole GPU per VM. Profiles and placements are NVIDIA's for the A100 40GB (lab below); slice proportions on the stage are illustrative.
Time slicingMPSMIGvGPUPassthrough
What it isseveral processes or pods use the same GPU; the GPU switches between their contextsa server process merges clients' work so it runs concurrentlythe hardware is cut into up to 7 instances, each with its own SMs, L2 slices and memorya hypervisor-side manager gives each VM a virtual GPU, time-sliced or backed by a MIG instanceone whole GPU per VM
Concurrency between usersno, one context at a timeyesyes, physically separatetime-sliced or MIG-backedn/a
Memory isolationno: any replica can use all the memoryaddress spaces isolated ("MPS client processes have fully isolated GPU address spaces")yes, dedicated memory per instanceyeswhole GPU
Memory bandwidth and cache QoSnonoyesper modewhole GPU
Error isolationno (time slicing has "no memory or fault-isolation between replicas")no (limited containment on Volta and later)yesyesyes
Max partitionsconfigurable replicas487per vGPU profile1
Reconfigureany timeat process launchwhen the GPU is idleper VMper VM
Sources for the sharing table (depth)

Streams, MPS and MIG columns from the MIG user guide's table "CUDA Concurrency Mechanisms" (MIG concepts): MPS "does not offer error isolation between clients", and with MIG "each instance's processors have separate and isolated paths through the entire memory system - the on-chip crossbar ports, L2 cache banks, memory controllers, and DRAM address busses" (MIG introduction); MPS's limited containment from the MPS documentation. Time slicing from the GPU Operator guide: "A request for more than one time-sliced GPU does not guarantee that the pod receives access to a proportional amount of GPU compute power." vGPU's time-sliced schedulers are "best effort" (the default), "equal share" and "fixed share" (vGPU scheduling policies).

MIG in practice. A MIG-capable GPU (A100 and later data-centre parts) is enabled once (on A100 and A30, "setting MIG mode ... requires a GPU reset"), then carved into GPU instances from fixed profiles, each named by its compute slices and memory: on an H100 80GB, 1g.10gb (1/7 of the SMs, 1/8 of the memory, up to 7 of them), 2g.20gb, 3g.40gb, 4g.40gb, 7g.80gb (MIG supported profiles). Profiles can only sit at certain positions, so the order you create them in matters. Each instance then appears to CUDA as its own device: CUDA_VISIBLE_DEVICES=MIG-<uuid>.

When it bites in ML
  • Training wants whole GPUs. Sharing is for inference, notebooks, small fine-tunes and CI. A training job on a time-sliced GPU shares memory with strangers and can be slowed or killed by their faults.
  • "My job got slower and nothing changed" on a shared node: another pod was scheduled on the same time-sliced GPU. nvidia-smi on the node lists every process on the GPU.
  • MIG memory is a hard wall: a 1g.10gb instance is a 10 GB GPU to PyTorch, and NCCL between MIG instances is limited ("only P2P between MIG instances on the same GPU is supported" with R570, MIG deployment considerations).

MIG placement on an A100 40GB: creation order matters

Predict first: can you fit a 3g.20gb after placing two 1g.5gb and a 2g.10gb? Pick a profile, then one of its allowed starts on the 8 memory slices; click an instance to remove it. Placements are NVIDIA's, for an A100 40GB, from nvidia-smi mig -lgipp in the MIG user guide; nothing here ran on a GPU.

Examples from the guide:
memory slice index
The placement rules this lab uses, and the H100 profiles (depth)
$ nvidia-smi mig -lgipp          (A100-SXM4-40GB, from the MIG user guide)
GPU 0 Profile ID 19 Placements: {0,1,2,3,4,5,6}:1      1g.5gb
GPU 0 Profile ID 20 Placements: {0,1,2,3,4,5,6}:1      1g.5gb+me  (1 instance at most)
GPU 0 Profile ID 15 Placements: {0,2,4,6}:2            1g.10gb
GPU 0 Profile ID 14 Placements: {0,2,4}:2              2g.10gb
GPU 0 Profile ID 9 Placements: {0,4}:4                 3g.20gb
GPU 0 Profile ID 5 Placement : {0}:4                   4g.20gb
GPU 0 Profile ID 0 Placement : {0}:8                   7g.40gb

"The syntax of the placement is {<index>}:<GPU Slice Count>". Instances may not overlap, and the compute slices (the number before "g") add up to at most 7. The guide warns: "As GPU Instances are created and destroyed at different locations, fragmentation can occur, and the physical position of one GPU Instance will play a role in which other GPU Instances can be instantiated next to it" (MIG concepts); and "due to a known issue with the APIs, the profile ID 9 or 3g.20gb must be specified first", because the driver's automatic placement of smaller instances can take the positions a 3g.20gb needs. Try the "1-1-2, then 3g" example to see it. The H100 80GB has the same seven profiles at twice the memory (1g.10gb, 1g.10gb+me, 1g.20gb, 2g.20gb, 3g.40gb, 4g.40gb, 7g.80gb) (supported profiles); its placement listing is not reproduced here.

After creating GPU instances you create compute instances inside them (nvidia-smi mig -cgi 9,3g.20gb -C does both), and each appears to CUDA as its own device: CUDA_VISIBLE_DEVICES=MIG-<uuid>. "The created MIG devices are not persistent across system reboots."

nvidia-smi mig -lgip; nvidia-smi mig -lgipp; nvidia-smi -L

9. One CUDA call down: from Python to the GPU

36

The problem. y = x @ w on CUDA tensors returns in a few microseconds and the GPU does the work later. Between the two sit the libraries and driver in the hero figure, invisible until they fail. Writing kernels and the GPU as hardware are Topic: cuda-and-gpu-programming's (its Compiler explorer has the same CUDA 13.4 toolchain) and Topic: hardware's.

Each layer: what it is, where it comes from, its job in y = x @ w (depth)
LayerWhat it is, where it comes fromIts job in y = x @ w
PyTorchyour wheel or imagethe dispatcher picks the CUDA implementation of matmul, which calls cuBLAS; elementwise ops launch PyTorch's own kernels
CUDA runtime libcudart.so.13part of the toolkit; PyTorch's CUDA wheels load it from the nvidia-cuda-runtime wheel (_preload_cuda_deps, torch/__init__.py L351-362, v2.14.1)the convenient API: creates a context implicitly, registers the program's kernels, turns cudaLaunchKernel into driver calls
CUDA driver libcuda.so.1the user-mode driver, installed with the host's driver package, not with the toolkit; a container gets the host's copy mounted inthe real work in user space: contexts, memory, module loading, JIT compiling PTX, building command buffers and submitting them
Kernel driver nvidia.ko, nvidia-uvm.kothe host's kernel modules; NVIDIA's open-gpu-kernel-modules are the open-source versionowns the hardware: memory allocation and mapping, channels, interrupts, faults, power, reset; reached by ioctl on /dev/nvidia*
GSP firmware gsp_*.bininstalled with the driver in /lib/firmware/nvidia/615.71.09/, one file per GPU architectureon Turing and later GPUs, runs most of the resource manager on the GPU's own processor (below)
GPUa PCIe device (passed through in a VM)fetches commands from memory by DMA and runs them

Where the resource manager runs: the GSP. On Turing and later GPUs the driver by default offloads "GPU initialization and management tasks" to the GPU System Processor (GSP), "driven by firmware files distributed with the driver" (NVIDIA driver README 615.71.09, GSP Firmware). In the open driver that firmware is a build of the resource manager itself (GSP-RM), booted by the kernel module and reached by RPC messages through shared queues; the open modules work only this way. So three pieces must carry the same version: libcuda, nvidia.ko and the firmware.

GSP in the open source and the README (depth)

Where the resource manager runs: the GSP. "Some GPUs include a GPU System Processor (GSP) which can be used to offload GPU initialization and management tasks. This processor is driven by firmware files distributed with the driver", and "the GSP firmware will be used by default for all Turing and later GPUs" (NVIDIA driver README 615.71.09, GSP Firmware). In the open driver the firmware is a build of the resource manager itself, booted by the kernel module (_kgspBootGspRm, kernel_gsp.c L5429) and reached by RPC messages through shared queues (_kgspRpcSendMessage, L525). The open modules work only this way: they "must be used with GSP firmware and user-space NVIDIA GPU driver components from a corresponding 615.71.09 driver release" (README). So three pieces must carry the same version: libcuda, nvidia.ko and the firmware.

Fig. 9: the same ioctl, two places the resource manager can run

First panel: GSP disabled (NVreg_EnableGpuFirmware=0, proprietary modules only, or GPUs before Turing): the resource manager runs on the host CPU inside nvidia.ko. Second: the default on Turing and later: nvidia.ko forwards the call as an RPC to GSP-RM on the GPU. Neither changes the launch path, which never enters the kernel. Check with nvidia-smi -q: "GSP Firmware Version" shows a version, or "N/A" if disabled. NVIDIA's known issues for the open modules (always GSP) against the proprietary modules with GSP disabled include "GPU initialization is slower", mitigated by nvidia-persistenced (section 11; open kernel modules README).

What happens with no GPU: four cases, run for real. A small CUDA program (src/exp/cuda/rt_probe.cu, built with the runtime as a shared library) and a driver-API probe (drv_probe.c, which dlopens libcuda.so.1 the way the runtime does) were run in the CUDA 13.4.2 image under strace and LD_DEBUG. Every recorded trace line is stepped in a closed block at the end of this section.

CasecudaGetDeviceCount returns measuredWhy
1. No driver at all (any container started without the NVIDIA runtime)35 cudaErrorInsufficientDriver: "CUDA driver version is insufficient for CUDA runtime version"; cudaDriverGetVersion gives 0the runtime looked for libcuda.so.1 in five directories and found none; "insufficient" here means "absent"
2. The toolkit's stub libcuda.so found as libcuda.so.134 cudaErrorStubLibrary: "CUDA driver is a stub library"the stub exists so programs can be linked on machines without a driver; it refuses to run
3. The real user-mode driver 615.71.09, no kernel module100 cudaErrorNoDevice: "no CUDA-capable device is detected"; driver version 13040libcuda loaded, then failed to open /dev/nvidiactl (details below)
4. As 3, with the container's device cgroup opened for major 195100, and open now fails with ENXIOthe kernel has no driver registered for character major 195

How the kernel side is organised. Every device file of nvidia.ko shares one set of file operations; a few ioctls (the version handshake below) are handled in its Linux layer and the rest go to the resource manager (RM), where everything is an object with a handle (a client per process, a device, memory, a channel) that ioctls allocate, control, free and map. Unified memory has its own device, /dev/nvidia-uvm. libcuda's last act in case 3 was one such ioctl, 0xc020462a: NV_ESC_RM_CONTROL (decoded in the closed block below).

The version handshake. Among the first things a client sends on /dev/nvidiactl is NV_ESC_CHECK_VERSION_STR: the kernel compares the client's version string with its own and on a mismatch logs "NVRM: API mismatch ... Please make sure that this kernel module and all NVIDIA driver components have the same version". That is the dmesg line after a driver upgrade without a reboot: new user-mode libraries meet the old module still loaded.

Launching work without a system call. A GPU channel is a queue of work in memory: a pushbuffer holds the commands (launch this kernel, copy this, wait on that semaphore), a ring called the GPFIFO points at pushbuffer segments, and a doorbell register tells the GPU the ring moved. The open driver's unified-memory module submits work exactly so: fill a GPFIFO entry, barrier, write the put pointer, barrier, store a token into the doorbell (VOLTA_USERMODE_A, NOTIFY_CHANNEL_PENDING at offset 0x90). Once mapped every piece is ordinary memory, so a launch is plain stores: no system call, and no exit even in a VM.

Fig. 10: one CUDA call down, the first in a process against the millionth

The first CUDA call of a process against a launch in the training loop: what enters the kernel, and what is plain memory writes. Steps from the open driver's interface; the order inside the closed libcuda is simplified.

  1. dlopen("libcuda.so.1"): enters the kernel. The runtime looks for the user-mode driver (here it searched five directories, case 1) and maps it: openat and mmap system calls.
  2. open("/dev/nvidiactl"): enters the kernel. cuInit opens the control device, character 195:255. In a container this is where the device cgroup says yes or no.
  3. ioctl NV_ESC_CHECK_VERSION_STR: enters the kernel. The version handshake with nvidia.ko: an exact or relaxed match of the version strings, or the "API mismatch" message in the kernel log.
  4. ioctl NV_ESC_RM_ALLOC, NV_ESC_RM_CONTROL: enters the kernel. Resource-manager objects: a client for this process, then a device and subdevice per GPU; control calls ask what the GPUs are. With GSP, nvidia.ko forwards them to GSP-RM on the GPU.
  5. open("/dev/nvidia0"), open("/dev/nvidia-uvm"): enters the kernel. The GPU itself, and the unified-memory device (UVM_INITIALIZE, UVM_REGISTER_GPU) that gives CPU and GPU one virtual address space.
  6. Create the context, allocate and map: enters the kernel. A GPU address space, channels with their GPFIFO ring and pushbuffer, and the usermode doorbell page: RM allocations, then NV_ESC_RM_MAP_MEMORY and mmap so the process can write them directly.
  7. Load the kernel's module, lazily at first launch: enters the kernel. Pick the cubin for this GPU from the fatbin, or JIT-compile the PTX; allocate GPU memory for the code and copy it there.
  8. Write the launch into the pushbuffer: user space. Methods: which kernel, grid and block sizes, the parameter buffer. Ordinary stores into mapped memory.
  9. Add a GPFIFO entry, barrier, update GPPut: user space. The ring entry points at the new pushbuffer segment; a memory barrier orders the writes (uvm_channel.c L984-1015 shows the same sequence).
  10. Ring the doorbell: one store. The channel's token stored to NOTIFY_CHANNEL_PENDING in the mapped usermode page. In a VM with passthrough this is not an exit: the page is mapped by stage-2 tables.
  11. The GPU fetches and runs the kernel. By DMA from the pushbuffer, through the IOMMU in a VM. The CPU returned long ago. Seven of these eleven steps entered the kernel.
The handshake and the submission path in source (depth)

The version handshake. Among the first things a client sends on /dev/nvidiactl is NV_ESC_CHECK_VERSION_STR. The kernel compares the client's version string with its own, exactly, or only up to the first dot if the client asks for "relaxed" checking; on a mismatch it logs "NVRM: API mismatch: the client ... has the version ..., but this kernel module has the version ... Please make sure that this kernel module and all NVIDIA driver components have the same version" (RmPerformVersionCheck, osapi.c L1199-1302). That is the message in dmesg after a driver upgrade without a reboot: the new user-mode libraries meet the old module still loaded.

Launching work without a system call. A GPU channel is a queue of work: a pushbuffer in memory holds the commands ("methods": launch this kernel with these parameters, copy this, wait for that semaphore), a ring called the GPFIFO holds pointers to pushbuffer segments, and a doorbell register tells the GPU's host interface that the ring moved. The open driver's own unified-memory module submits work exactly like this, and its code shows each step: fill a GPFIFO entry pointing at the pushbuffer, a memory barrier, write the new put pointer, a write barrier, and ring the doorbell by storing a token into the doorbell register (internal_channel_submit_work, uvm_channel.c L984-1015; write_gpu_put, uvm_turing_host.c L222-236). The doorbell lives in a "usermode" register page, the class VOLTA_USERMODE_A with NOTIFY_CHANNEL_PENDING at offset 0x90 (clc361.h), an object any RM client can allocate and map. Every piece is ordinary memory once mapped, so a process holding the mappings can launch with plain stores: no system call, no exit even in a VM.

What is verified and what is inferred

Verified from the open source: the device files, the ioctl protocol, the RM object model, the channel, GPFIFO and doorbell mechanism, and that kernel-side code (UVM) submits work with stores alone. Inferred: that the closed libcuda launches kernels the same way, by mapping its channels and the usermode page at context creation; it is the design the open interface supports, and the root page's description, but libcuda itself cannot be read. On a GPU machine, strace -f -c over a steady training loop confirms or refutes it in a minute. This replaces the root page's "not verified from a primary source" with this narrower statement.

When it bites in ML
  • A slow first step on a new GPU: the libraries had no cubin for it and the driver is JIT-compiling PTX (watch the compute cache grow); or lazy loading is loading hundreds of kernels at first use (binary compatibility and the compute cache are owned by The compiler stack).
  • "no CUDA-capable device is detected" in a container: case 3 or 4. The driver is there but the device files are not, or the cgroup forbids them: the container was started without the NVIDIA runtime or without --gpus.
  • "Found no NVIDIA driver on your system": PyTorch's message for case 1 (device_count_impl, c10/cuda/CUDAFunctions.cpp L17-64, v2.14.1); torch.cuda.is_available() returns False for cases 1 and 3 without raising, because it calls cudaGetDeviceCount (torch/cuda/__init__.py L209-228). The CPU-only wheel used here never even looks for a driver.
  • CUDA initialised before fork(): the child inherits a driver state it cannot use; PyTorch avoids touching CUDA in is_available() only if PYTORCH_NVML_BASED_CUDA_CHECK=1 (same file). See the Processes page on start methods.

strace -f -e trace=openat,ioctl,mmap -o trace.txt python train.py; LD_DEBUG=libs python -c "import torch; torch.cuda.init()" 2>&1 | grep libcuda

Case 3, line by line: the device node libcuda makes, and the ioctl decoded (depth)

Case 3, line by line. The user-mode driver came from the image's forward-compatibility directory (/usr/local/cuda/compat, section 10). Its cuInit did, in order: read /proc/driver/nvidia/params (the kernel module's parameters: absent), look for /usr/bin/nvidia-modprobe (a setuid helper that loads the module and creates device files: absent), then, running as root, delete whatever was at /dev/nvidiactl and create it itself:


The node is character device 195:255, exactly the kernel driver's numbers (NV_MAJOR_DEVICE_NUMBER 195, NV_MINOR_DEVICE_NUMBER_CONTROL_DEVICE 255). Creating it worked (Docker grants CAP_MKNOD); opening it failed with EPERM, because the container's device cgroup only allows a short list of devices (the Containers and isolation page covers the device controller). libcuda retried eight times, scanned /sys/bus/pci/devices/*/config for an NVIDIA device, read /proc/modules for a loaded nvidia module, and finally sent one ioctl to the file descriptor -1 it never got: 0xc020462a. That number decodes, with Linux's _IOC layout, into the whole protocol:

BitsFieldValueMeaning, from the open driver
30-31direction3read and write: the kernel copies the argument in and back out
16-29size32 bytesthe size of NVOS54_PARAMETERS: client handle, object handle, command, flags, a pointer to the command's own parameters, their size, a status
8-15type'F'NV_IOCTL_MAGIC, every NVIDIA ioctl
0-7number0x2ANV_ESC_RM_CONTROL: "run control command cmd on object hObject"

The sources. nvidia.ko registers one set of file operations for all its device files: open, unlocked_ioctl, mmap, poll, release (nvidia_fops, nv.c L259-269). A handful of ioctls are handled in the Linux layer, such as the version handshake (below); everything else goes to the resource manager (RM), the OS-independent core of the driver (default: rm_ioctl, nv.c L2981-2982). In RM everything is an object with a handle: a client (your process), a device, a subdevice, a memory allocation, a channel. The escapes allocate objects (NV_ESC_RM_ALLOC 0x2B), free them, run control calls on them (NV_ESC_RM_CONTROL), and map them into the process (NV_ESC_RM_MAP_MEMORY, followed by an mmap of the device file, nvidia_mmap). Unified memory has its own device, /dev/nvidia-uvm, with ioctls such as UVM_REGISTER_GPU and UVM_MIGRATE.

The four no-GPU cases and CPU-only PyTorch: every recorded trace line, stepped (evidence)

Every line below was recorded in the CUDA 13.4.2 image (kb-os-virt:1) on this page's Linux VM, which has no GPU. Pick a case, then step through the trace: each step highlights the real line and says what it means, with the source that explains it. The table above is the summary; this is the evidence.

Inside the binary: what the driver loads (depth)

Inside the binary: what the driver loads. Your program's GPU code is not in the CPU part of the executable. It sits in a section called .nv_fatbin, a container (fatbin) holding machine code for specific GPUs (cubin, SASS) and the portable intermediate form (PTX). The test program was built for sm_80 and sm_90 plus PTX for compute_90:


measured cuobjdump -lelf -lptx and readelf -S on the built executable (raw: src/raw/cuda.txt; the tab shows the cubin sizes and the PTX). The executable carries two cubins per architecture: the two holding vadd come from this file; the object file alone has one per architecture, so the two small cubins with no kernels were added when nvcc linked the program (most likely by its device-link step).

At load time the driver picks, for the GPU it finds: a cubin for the same major compute capability and an equal or lower minor ("a cubin with code compiled for compute capability 8.6 ... can be loaded and executed on GPUs with compute capability 8.6 or 8.9"); otherwise it JIT-compiles the PTX, which works on any equal or newer GPU, and caches the result in the "compute cache" (~/.nv/ComputeCache, CUDA_CACHE_PATH) (CUDA Programming Guide 1.3.4; environment variables). Since CUDA 12.3 modules load lazily by default: a kernel is loaded at its first launch, not at start-up (CUDA_MODULE_LOADING, Lazy Loading).

What the driver would load on a GPU: the test program built with nvcc -cudart shared -gencode arch=compute_80,code=sm_80 -gencode arch=compute_90,code=sm_90 -gencode arch=compute_90,code=compute_90. The CUDA topic's Compiler explorer shows the SASS and PTX of many kernels for four GPU generations; here the point is only what the driver receives.

ldd rt_probe: the runtime is linked, the driver is not

cubins in the executable: size and kernels
the PTX the driver would JIT for a newer GPU (first lines)

measured src/exp/cuda/run.sh and run_dev.sh; raw: src/raw/cuda.txt, src/raw/cuda_dev.txt. Containers ran unprivileged with --cap-add SYS_PTRACE for strace; case 4 added --device-cgroup-rule 'c 195:* rwm'.

10. Two versions, and what a GPU container borrows from the host

The problem. A CUDA program depends on two independently installed things: the runtime it was built with (inside your image or wheel: torch.version.cuda) and the driver on the machine it runs on (host: nvidia-smi prints its version and the newest CUDA version it supports). Clusters upgrade drivers rarely and carefully; images change every week. "CUDA driver version is insufficient for CUDA runtime version" is the result of the two drifting apart.

Measured here: the versions this image reports, and what it declares (depth)

Measured here. The runtime reported 13040 (CUDA 13.4) in every case. The driver version was 0 with no libcuda (case 1 of section 9), and 13040 with the 615.71.09 user-mode driver from the image's /usr/local/cuda/compat. The image also declares what it needs, for the NVIDIA container toolkit to check before starting it: NVIDIA_REQUIRE_CUDA=cuda>=13.4 plus a list of accepted driver branches for data-centre GPUs (brand=tesla,driver>=535,driver<536, and likewise 570, 580, 590, 595, 610). "If the version of the NVIDIA driver is insufficient to run this version of CUDA, the container does not start" (container toolkit, NVIDIA_REQUIRE_CUDA).

The driver (libcuda) isCompatibilityRequirements
newer than the runtimebackward compatibilitynone
older than the runtime, same major versionminor version compatibilityno PTX (needs SASS for the GPU), the target architecture given to nvcc; some new features return cudaErrorCallRequiresNewerDriver
older than the runtime's major versionforward compatibilitythe cuda-compat package; data-centre GPUs (and some RTX and Jetson) only
Sources for the compatibility rules (depth)

From CUDA Compatibility: why and minor version compatibility: minimum drivers CUDA 13.x ">= 580", 12.x ">= 525", 11.x ">= 450"; "Applications that compile device code to PTX will not work on older drivers". Forward compatibility: "the cuda-compat-13-4 package is built using the NVIDIA driver libraries version 615", installed into /usr/local/cuda-13.4/compat/, and "This package only provides the libraries, and does not configure the system to find such libraries" (you set LD_LIBRARY_PATH); errors 803 CUDA_ERROR_SYSTEM_DRIVER_MISMATCH and 804 CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE. Since CUDA 13.4 the Linux driver is no longer bundled with the toolkit.

Will it run? The rules interact, so predict before you pick

Pick the host's driver branch and what your application was built with. The rules and the forward-compatibility matrix are NVIDIA's (Table 3 of the forward compatibility page, driver branches 535 to 615).

The container toolkit at the driver level. A GPU container is section 9's stack cut in two: the image brings PyTorch and the runtime; the host must lend it the user-mode driver that matches its kernel module, the device files, and permission to open them. Each missing piece is one of section 9's measured failures. The NVIDIA Container Toolkit (or a CDI spec it generates) supplies all three and checks NVIDIA_REQUIRE_CUDA first; how it does so (bind mounts, the device cgroup's BPF program, CDI) is owned by Containers and isolation.

Why forward compatibility can work at all. Section 9's version handshake is between the user-mode driver and the kernel module. Forward compatibility swaps only the user-mode half: a newer libcuda (from the compat package) talks to an older nvidia.ko. NVIDIA: "forward compatibility is defined between the kernel driver and the CUDA driver", which is also why it can JIT PTX where minor version compatibility cannot (the compat package brings its own PTX compiler, libnvidia-ptxjitcompiler, visible in this image's compat directory).

Version facts, as of October 2026 (volatile; from NVIDIA's CUDA Compatibility pages and this page's image)
FactValue
Minimum driver for minor version compatibilityCUDA 13.x: 580; 12.x: 525; 11.x: 450
Newest toolkit and its driverCUDA 13.4, driver branch 615 (615.71.09 here); cuda-compat-13-4 is built from driver 615
Forward-compatibility targets in the matrixdriver branches 535, 570, 580, 590, 595, 610 (data-centre GPUs)
Toolkit installersince CUDA 13.4 the Linux driver is no longer bundled

Fig. 11: what comes from the image, what must come from the host, and the error when it does not

Errors measured here (section 9, cases 1 to 4) except the version mismatch, which is the open module's message read in source. Why the toolkit mounts the host's libcuda rather than trusting the image's: the version handshake wants the two halves of the driver to agree; the compat package is the one sanctioned exception.

When it bites in ML
  • A new PyTorch wheel on an old cluster: PyTorch's CUDA wheels ship the runtime; the cluster's driver is older. Within the same CUDA major and with SASS for your GPU it runs (minor version compatibility); across a major version it needs the compat package or an older wheel. PyTorch's own error for an old driver: "The NVIDIA driver on your system is too old (found version ...)" (CUDAFunctions.cpp).
  • Custom kernels compiled to PTX only (a JIT extension, some Triton or third-party builds) fail under minor version compatibility even when everything else works.
  • A driver upgraded without a reboot: user-mode libraries and module disagree: section 9's "API mismatch" in dmesg.

nvidia-smi | head -4; python -c "import torch; print(torch.version.cuda, torch.cuda.is_available())"; ls /usr/local/cuda/compat

11. GPU memory and the driver, from the operating system's side

not run here except where marked: no GPU; from the open kernel modules at 615.71.09 and NVIDIA's documentation.

GPU memory is not Linux's memory. The kernel's page allocator, page cache, swap and OOM killer (the Virtual memory page) know nothing about the GPU's own memory. The driver's resource manager hands it out in response to RM allocation ioctls; above it, PyTorch's caching allocator keeps freed blocks for reuse (the Memory allocators page). So "CUDA out of memory" is never solved by the host's swap, and GPU memory a crashed process held comes back only when the driver tears its client down.

Kind of memoryWhat the OS doesWhere on these pages
Device memory (cudaMalloc)nothing: RM allocates it; the CPU can reach parts of it through a PCIe window (BAR1) mapped by mmap on the device file (nvidia_mmap)here; Memory allocators
Pinned host memory (pin_memory=True)ordinary RAM, locked so the GPU's DMA can target it; counts against RLIMIT_MEMLOCKVirtual memory, section 9
Managed memory (cudaMallocManaged)pages migrate between CPU and GPU on page faults, serviced by nvidia-uvm.kohere
System memory used by the GPU directly (HMM, Grace Hopper)the GPU uses the process's own page tables, through Linux's HMM or hardware coherencehere

Unified memory and HMM: the GPU takes page faults. With managed memory one pointer works on both sides; a GPU access to a page the CPU holds faults, the GPU records the fault in a buffer, and nvidia-uvm.ko services faults in batches by unmapping, migrating and remapping the page, which is expensive and proportional to the page size. With Linux's HMM even plain malloc memory becomes reachable from the GPU (open kernel modules only). How to use managed memory well, and prefetching, are owned by GPU memory hierarchy and Streams, CUDA graphs and multi-GPU.

Unified memory and HMM in the documentation and source (depth)

With managed memory, one pointer works on both sides. On systems where CPU and GPU each have their own page tables, a fault means the page must be unmapped from its owner, mapped for the requester, and "the physical page backing this virtual page must be moved/migrated to the processor requesting access: this can be an expensive operation, and the amount of work is proportional to the page size" (CUDA Programming Guide, unified memory). The GPU records its faults in a buffer and the UVM driver services them in batches (uvm_parent_gpu_service_replayable_faults). With Linux's HMM (heterogeneous memory management), even plain malloc memory becomes reachable from the GPU; it "requires Linux kernel version 6.1.24+, 6.2.11+ or 6.3+, devices with compute capability 7.5 or higher and a CUDA driver version 535+ installed with Open Kernel Modules" (same guide; the open module's support starts at uvm_hmm.c).

GPUDirect RDMA. For multi-node training the NIC should move data straight to and from GPU memory: the nvidia-peermem module lets the InfiniBand stack pin GPU pages for the NIC, or, with the open driver and a recent kernel, NCCL uses DMA-BUF instead. In a VM both devices sit behind the IOMMU and section 7's ACS and ATS rules apply.

Driver state lives as long as someone holds it open. The kernel module tears the device down on the last file close, so without a long-lived client every short CUDA job re-initialises the GPU, "on the order of seconds"; nvidia-persistenced is a daemon that simply keeps the device files open (the old nvidia-smi -pm 1 is deprecated). GPU errors are logged by the kernel driver as Xid messages (dmesg | grep "NVRM: Xid"), which a container or VM may not be allowed to read: ask whoever runs the host. CUDA_VISIBLE_DEVICES filters and reorders the devices the runtime enumerates; below it, a container sees only the device files it was given.

GPUDirect, persistence, Xid and device visibility in the sources (depth)

GPUDirect RDMA: the NIC writes into GPU memory. For multi-node training the network card should move data straight to and from GPU memory. The nvidia-peermem module lets the InfiniBand stack pin GPU pages for the NIC (nvidia_p2p_get_pages); "GDRDMA can also be enabled by using the DMA-BUF feature of recent Linux kernels combined with the open source Nvidia GPU driver. In this case, NCCL will automatically detect and enable DMA-BUF so the nvidia-peermem module will not be necessary" (NCCL GPU troubleshooting). In a VM, both devices sit behind the IOMMU and section 7's ACS and ATS rules apply.

Driver state lives as long as someone holds it open. The kernel module "tears down the device on the last file close" (nv_stop_device, nv.c L2216). Without a long-lived client, every short CUDA job re-initialises the GPU, which "leads to long load times for each CUDA job, on the order of seconds" (driver persistence). The old fix, persistence mode (nvidia-smi -pm 1), now logs "Persistence mode is deprecated and will be removed in a future release. Please use nvidia-persistenced instead" (nv.c L2259-2265): a daemon that simply keeps the device files open.

When the GPU fails, the kernel log says so. GPU errors (a kernel's illegal memory access, a fallen-off-the-bus GPU, ECC errors) are logged by the kernel driver as Xid messages: "Under Linux, the Xid error messages are logged in the kernel log buffer ... Grep for 'NVRM: Xid'" (Xid errors). A training job that dies with a vague CUDA error should be read together with dmesg on the host; inside a container or a VM you may not be allowed to read it (this page's containers could not), so ask whoever runs the host.

Which GPUs a process sees. CUDA_VISIBLE_DEVICES filters and reorders devices for the CUDA runtime: "setting CUDA_VISIBLE_DEVICES=2,1 makes device 0 not visible and enumerates device 2 before device 1", accepts UUIDs and MIG instance names, and cudaGetDeviceCount() "includes only the visible devices" (CUDA environment variables). Below it, a container only sees the device files it was given, and its device cgroup decides which it may open (section 9, cases 3 and 4).

When it bites in ML
  • GPU memory "used" with no process running: a zombie or a process in another container still holds the device open; the driver frees its memory when the last handle closes.
  • Each job's first CUDA call takes seconds on a node without nvidia-persistenced.
  • Managed memory "works" but is slow: pages migrate back and forth on faults; prefetch (cudaMemPrefetchAsync) or use device memory.
  • Ranks pick the wrong GPUs: a launcher sets CUDA_VISIBLE_DEVICES and the code also indexes devices by local rank, or CUDA_DEVICE_ORDER differs from nvidia-smi's PCI order.

nvidia-smi -q -d MEMORY,ECC; dmesg | grep -i "NVRM: Xid"; systemctl status nvidia-persistenced; ls -l /dev/nvidia*

Depth: beliefs to unlearn, and interview rehearsal

Eight common beliefs, and what is true (each points to its section)
BeliefWhat is true
"A VM is slow because it emulates the CPU."Guest code runs directly on the CPU; only exits cost (about 0.92 µs each here). Interrupts, idle and device access are where the time goes (sections 2, 5).
"GPU passthrough adds overhead to every kernel."The GPU's registers and DMA go through stage-2 tables and the IOMMU, not through the hypervisor; launches do not exit. The costs are pinned memory, topology and peer-to-peer (section 7).
"Containers isolate GPUs like VMs do."A container sees device files the host passed in; the GPU is shared with whatever else uses it unless MIG or exclusive scheduling separates them (section 8).
"Time-sliced GPUs give each pod a fair share.""A request for more than one time-sliced GPU does not guarantee that the pod receives access to a proportional amount of GPU compute power", and there is no memory or fault isolation (section 8).
"nvidia-smi shows CUDA 13.0, so I cannot run a CUDA 13.4 build."That is the newest CUDA the driver was released with; minor version compatibility runs any 13.x build with SASS for the GPU (section 10).
"The CUDA toolkit in my image includes the driver."The image has the runtime and a stub libcuda; the real driver comes from the host (section 9, cases 1 and 2).
"torch.cuda.is_available() is False, so there is no GPU."It is False with no driver library, with no device files, and with a forbidden device cgroup: four different fixes (section 9).
"Steal time is zero, so nothing else runs on my host."Only if the hypervisor reports it; this one does not (section 5).
Interview rehearsal: eight questions with answers (optional)
What is a VM exit, and name three things that cause one.
The CPU stopping the guest and handing control to the hypervisor with the reason (exception class or exit reason), which emulates the effect and resumes the guest. Causes: accessing an emulated device register (MMIO, port I/O), the idle instruction (wfi, hlt), accessing interrupt-controller or timer registers that are not virtualized in hardware, hypercalls, and host interrupts. Guest system calls and page faults do not exit with hardware virtualization and nested paging. About 0.9 µs per exit was measured on an M1 Pro's hypervisor.
Why can a TLB miss cost up to 24 memory reads in a VM?
With nested paging the guest's page-table pointers are guest-physical addresses, so each of the 4 guest levels needs a 4-level host walk plus its own read (20), and the final guest-physical address needs one more host walk (4): (4+1)(4+1)-1 = 24. Huge pages in either stage shorten it (19 with 2 MiB host pages); page-walk caches make most misses much cheaper.
A thread hand-off between CPUs is 10 times slower in a VM than on bare metal. Why, and what would you do?
The wake-up needs an inter-processor interrupt. Sending it, acknowledging it and ending it can each exit to the hypervisor if the interrupt controller is emulated, and if the target vCPU was idle its host thread must be woken by the host scheduler. Fixes at the platform level: in-kernel and hardware-assisted interrupt virtualization (vGIC on GICv3/v4, APICv and posted interrupts, AVIC), halt polling, dedicated cores. In the application: fewer, larger hand-offs, brief spinning where a core can be spared.
What does the IOMMU do in GPU passthrough, and why do GPU VMs pin all their memory?
It translates and checks every DMA address the device issues, so a guest's GPU sees guest-physical addresses mapped to that guest's host pages and nothing else; it also remaps interrupts. Because a device cannot take page faults like a CPU, the pages it may DMA into must stay resident: VFIO pins every page it maps, and QEMU maps all guest RAM, so balloon, KSM or swap-based overcommit cannot apply.
Compare time slicing, MPS and MIG for sharing a GPU between two inference services.
Time slicing: contexts take turns; no concurrency, no memory limit or fault isolation between users. MPS: one server merges the clients' work so it runs concurrently; separate address spaces but shared memory bandwidth and caches and no full error isolation. MIG: hardware partitions with their own SMs, L2 slices, memory controllers and DRAM; predictable latency and fault isolation, up to 7 instances, reconfigured only when idle. For two latency-sensitive services from different teams, MIG.
Walk me through what happens below cudaMalloc on the first call in a process.
The runtime loads libcuda.so.1 (the user-mode driver, from the host), which initialises: opens /dev/nvidiactl, checks versions with the kernel module, allocates RM objects (client, device, subdevice) by ioctl, opens /dev/nvidiaN, creates a context with its channels and maps them; then the allocation itself is an RM allocation ioctl plus a mapping into the GPU's address space. Later kernel launches write into mapped command buffers and ring a doorbell without a system call.
A container prints "no CUDA-capable device is detected" on a GPU node. How do you debug it?
Check, in order: is libcuda.so.1 present (the NVIDIA container runtime or CDI injects it; without it the error is "driver version is insufficient"), do /dev/nvidiactl and /dev/nvidiaN exist in the container, may the container open them (device cgroup: EPERM), is CUDA_VISIBLE_DEVICES empty or wrong, and does the host see the GPU (nvidia-smi, dmesg Xid). strace -f -e openat,ioctl shows which step fails.
Your image is built with CUDA 13.4 and the cluster runs driver 570. Will it run?
Driver 570 belongs to CUDA 12.8, a different major version, so minor version compatibility does not apply; the toolkit's minimum for 13.x is 580. On data-centre GPUs, install cuda-compat-13-4 in the image and put /usr/local/cuda/compat on LD_LIBRARY_PATH: NVIDIA's matrix marks that combination compatible. On consumer GPUs, use a 12.x build or upgrade the driver.