ByteGuideHub
Observability & eBPF • • 14 min read

Detecting GPU Memory Leaks and Fragmentation in Self-Hosted ML Inference with eBPF CUDA Allocator Tracing

Step-by-step guide to tracing CUDA memory allocations with eBPF uprobes on self-hosted ML inference servers to detect GPU memory leaks and fragmentation, with configs, BPF maps, and comparison tables.

Sponsored / Ad Space

Detecting GPU Memory Leaks and Fragmentation in Self-Hosted ML Inference with eBPF CUDA Allocator Tracing

Quick Summary (TL;DR) GPU memory leaks on self-hosted inference servers are notoriously hard to catch because the CUDA caching allocator (in PyTorch, TensorFlow, etc.) hides them behind a pool of reserved memory. nvidia-smi shows you totals, not attribution. This guide shows how to attach eBPF uprobes to libcudart.so and libcuda.so, capture every cudaMalloc/cudaFree (and driver-level cuMemAlloc/cuMemFree) into BPF maps, aggregate in userspace, and distinguish true leaks (allocation/free mismatches) from fragmentation (live-allocation size distribution drift). You’ll get working BCC code, comparison tables, and production hardening tips.


Why GPU Memory Leaks Hide in Plain Sight

A self-hosted inference server looks healthy right up until it doesn’t. Memory utilization creeps from 40% to 85% over six hours, then a request throws CUDA out of memory and the pod restarts. Nothing in your standard observability stack flagged it.

The root cause is architectural. ML frameworks don’t call cudaMalloc for every tensor. They use a caching allocator that reserves large slabs from the driver and sub-allocates tensors from those slabs. When a tensor is freed, the memory returns to the framework’s pool — not to the GPU. So nvidia-smi keeps reporting the reserved total even when logical memory is released, and conversely, a bug that “leaks” a tensor reference never shows up as a growing nvidia-smi number until the pool itself grows.

This creates two distinct failure modes that look identical from the outside:

  • Leaks — a reference is held forever (a Python object in a global list, a closure captured in a callback, a cache keyed by request ID that never evicts). The allocator’s live-bytes counter grows monotonically.
  • Fragmentation — many small live allocations interleave with free blocks, so a large request for a contiguous block fails even though total free memory is sufficient.

eBPF uprobes let you see inside both, at the syscall-adjacent boundary of the CUDA libraries, with per-process and per-call-stack attribution — no application recompile required.

How eBPF uprobes Intercept CUDA Allocations

A uprobe is a breakpoint the kernel inserts into a user-space function’s entry (or return) instruction. When the traced process calls cudaMalloc, execution traps into the eBPF program, which can read the function arguments (via the ABI registers), record them in a BPF map, and return. Overhead is on the order of microseconds per call.

flowchart TD
    A[Inference Process] -->|cudaMalloc ptr,size| B[libcudart.so]
    B -->|uprobe entry| C[eBPF Program]
    C -->|read args via pt_regs| D[(BPF Hash Map<br/>pid -> alloc record)]
    B -->|internal call| E[libcuda.so<br/>cuMemAlloc]
    E -->|uprobe entry| C
    F[Userspace Aggregator] -->|poll every 5s| D
    F -->|leak / frag report| G[Logs / Prometheus]
    A -->|cudaFree ptr| B
    B -->|uprobe entry| C

Tracing both layers matters: the runtime API (cudaMalloc) reflects what your framework asks for, while the driver API (cuMemAlloc) reflects what the caching allocator actually reserves from the device. The gap between them is your fragmentation signal.

Prerequisites and Environment Setup

RequirementMinimumNotes
Kernel5.8+uprobes + BTF for CO-RE; 5.15 LTS recommended
DistroUbuntu 22.04 / Debian 12 / RHEL 9BTF must be enabled (/sys/kernel/btf/vmlinux)
ToolingBCC 0.26+ or bpftrace 0.18+BCC for the full program below
PrivilegesCAP_BPF + CAP_PERFMON (or root)Avoid running inference as root; use a sidecar
CUDA libslibcudart.so, libcuda.soMust be readable from the tracer’s mount namespace
Python3.9+For the userspace aggregator

Install BCC:

# Ubuntu 22.04
sudo apt-get install -y bpfcc-tools python3-bpfcc linux-headers-$(uname -r)
# Verify BTF
ls /sys/kernel/btf/vmlinux

If your inference runs inside a container, mount the CUDA libs and kernel headers into the tracer container and share the host PID namespace (--pid=host) so uprobes resolve correctly.


Step 1: Identify CUDA Allocator Symbols to Trace

Confirm the exact symbol names in your libraries — they differ across CUDA versions.

# Runtime API
nm -D --defined-only /usr/local/cuda/lib64/libcudart.so | grep -E 'cudaMalloc|cudaFree'
# Driver API
nm -D --defined-only /usr/lib/x86_64-linux-gnu/libcuda.so.1 | grep -E 'cuMemAlloc|cuMemFree'

Typical output includes cudaMalloc, cudaMallocAsync, cudaFree, cuMemAlloc_v2, cuMemFree_v2. Trace the _v2 variants for the driver API — modern CUDA versions route through them.

Tip: PyTorch’s caching allocator calls cudaMalloc in large chunks (default 2 MB granularity, up to 20 MB for small pools). To see logical tensor allocations, you’d need to hook c10::cuda::CUDACachingAllocator::malloc, but for leak detection the cudaMalloc/cudaFree pair is sufficient and far more stable across versions.


Step 2: Write the eBPF uprobe Program (BCC)

Here’s a minimal but production-usable BCC program. It records every allocation with size, pointer, PID, and a user stack trace, and removes the record on free.

#!/usr/bin/env python3
# gpu_alloc_trace.py
from bcc import BPF
import ctypes as ct

bpf_text = r"""
#include <uapi/linux/ptrace.h>

struct alloc_key_t {
    u64 pid;
    u64 ptr;
};

struct alloc_info_t {
    u64 size;
    u64 ts;
    int stack_id;
};

BPF_HASH(allocs, struct alloc_key_t, struct alloc_info_t, 262144);
BPF_HASH(live_bytes, u64, u64);          // pid -> live bytes
BPF_HASH(alloc_count, u64, u64);         // pid -> count
BPF_HASH(free_count, u64, u64);          // pid -> count
BPF_STACK_TRACE(stacks, 16384);

int trace_alloc(struct pt_regs *ctx, u64 size) {
    u64 pid = bpf_get_current_pid_tgid() >> 32;
    // Filter: only trace allocations >= 1 MB to bound overhead
    if (size < 1048576) return 0;

    u64 ptr = 0;
    // On x86_64 return value is in rax after the call; here we read the
    // caller's rax at entry is not the return. We use a return probe instead.
    return 0;
}

// Entry: capture size and timestamp
int alloc_enter(struct pt_regs *ctx, u64 size) {
    u64 pid = bpf_get_current_pid_tgid() >> 32;
    if (size < 1048576) return 0;
    struct alloc_key_t key = {};
    key.pid = pid;
    key.ptr = 0; // filled on return
    struct alloc_info_t info = {};
    info.size = size;
    info.ts = bpf_ktime_get_ns();
    info.stack_id = stacks.get_stackid(ctx, BPF_F_USER_STACK);
    allocs.update(&key, &info);
    return 0;
}

// Return: capture pointer, update live bytes
int alloc_return(struct pt_regs *ctx) {
    u64 pid = bpf_get_current_pid_tgid() >> 32;
    u64 ret = PT_REGS_RC(ctx);
    if (ret == 0) return 0;
    struct alloc_key_t key = {};
    key.pid = pid;
    key.ptr = 0;
    struct alloc_info_t *info = allocs.lookup(&key);
    if (!info) return 0;
    struct alloc_key_t real = {};
    real.pid = pid;
    real.ptr = ret;
    allocs.update(&real, info);
    allocs.delete(&key);

    u64 *lb = live_bytes.lookup(&pid);
    u64 new_lb = (lb ? *lb : 0) + info->size;
    live_bytes.update(&pid, &new_lb);
    u64 *ac = alloc_count.lookup(&pid);
    u64 new_ac = (ac ? *ac : 0) + 1;
    alloc_count.update(&pid, &new_ac);
    return 0;
}

int free_enter(struct pt_regs *ctx, u64 ptr) {
    u64 pid = bpf_get_current_pid_tgid() >> 32;
    struct alloc_key_t key = {};
    key.pid = pid;
    key.ptr = ptr;
    struct alloc_info_t *info = allocs.lookup(&key);
    if (!info) return 0;
    u64 *lb = live_bytes.lookup(&pid);
    if (lb && *lb >= info->size) {
        u64 new_lb = *lb - info->size;
        live_bytes.update(&pid, &new_lb);
    }
    allocs.delete(&key);
    u64 *fc = free_count.lookup(&pid);
    u64 new_fc = (fc ? *fc : 0) + 1;
    free_count.update(&pid, &new_fc);
    return 0;
}
"""

Note: The snippet above is a skeleton to show the BPF map structure. In practice you’ll attach alloc_enter/alloc_return as an entry/return probe pair on cudaMalloc and free_enter on cudaFree. BCC’s attach_uprobe and attach_uretprobe handle this; the return probe reads PT_REGS_RC(ctx) for the pointer.


Step 3: Track Allocations and Frees in BPF Maps

The BPF maps above give you three views:

MapKeyValuePurpose
allocs(pid, ptr)size, ts, stack_idLive allocation table
live_bytespidu64Running total of live bytes per process
alloc_countpidu64Total allocations
free_countpidu64Total frees
stacksstack_idstack traceAttribution to source line

The alloc_count - free_count delta is your first leak signal. A healthy process oscillates; a leaking process grows monotonically after warm-up.


Step 4: Detect Leaks with a Userspace Aggregator

Poll the maps every few seconds, compute deltas, and emit Prometheus metrics or structured logs.

from bcc import BPF
import time

b = BPF(src_file="gpu_alloc_trace.bpf.c")
# Attach uprobes (paths from Step 1)
b.attach_uprobe(name="/usr/local/cuda/lib64/libcudart.so",
                sym="cudaMalloc", fn_name="alloc_enter")
b.attach_uretprobe(name="/usr/local/cuda/lib64/libcudart.so",
                   sym="cudaMalloc", fn_name="alloc_return")
b.attach_uprobe(name="/usr/local/cuda/lib64/libcudart.so",
                sym="cudaFree", fn_name="free_enter")

live = b["live_bytes"]
ac = b["alloc_count"]
fc = b["free_count"]

while True:
    time.sleep(10)
    for k, v in live.items():
        pid = k.value
        a = ac.get(k, None)
        f = fc.get(k, None)
        if a and f:
            delta = a.value - f.value
            if delta > 1000:  # threshold: >1000 unmatched allocs
                print(f"[LEAK?] pid={pid} live={v.value} "
                      f"unmatched={delta}")

Wire the print into your log pipeline with a severity=warning tag, and add a Prometheus gauge gpu_alloc_unmatched{pid=...}. Alert when the gauge is non-zero for >5 minutes.


Step 5: Measure Fragmentation from Allocation Sizes

Fragmentation is subtler. You infer it from the distribution of live allocation sizes plus the largest contiguous free block the allocator can serve.

Two signals:

  1. Size histogram skew — if the 95th percentile of live allocation size grows while the median stays flat, small allocations are fragmenting the pool.
  2. Reserved vs. live gap — cuMemAlloc (driver) total minus cudaMalloc (runtime) live total. If this gap stays large after a workload settles, the caching allocator is holding fragmented slabs.

Extend the BPF program to record a log2-bucketed size histogram per PID:

BPF_HISTOGRAM(size_hist, int, 64);

int alloc_return(struct pt_regs *ctx) {
    // ... existing code ...
    int bkt = bpf_log2l(info->size);
    size_hist.increment(bkt);
    return 0;
}

Then in userspace, compare size_hist snapshots over time. A shifting right tail with a stable left tail is the classic fragmentation signature.

Step 6: Correlate with Inference Requests and Containers

To turn a leak into an actionable ticket, you need which request and which container. Two cheap hooks:

  • Container attribution: BPF already gives you pid; resolve it to a cgroup with bpf_get_current_cgroup_id() and map to the container ID via /sys/fs/cgroup.
  • Request attribution: Add a bpf_get_current_comm() call to capture the process name (e.g., python3), and if your inference server sets a thread name per request (vLLM and Triton do), include it in the record.

A minimal correlation table:

SignalSourceUse
pidbpf_get_current_pid_tgid()Process-level attribution
cgroup_idbpf_get_current_cgroup_id()Container attribution
commbpf_get_current_comm()Thread/worker identity
stack_idBPF_STACK_TRACESource-line attribution
tsbpf_ktime_get_ns()Time-series correlation with request logs

Join ts against your request log (Triton’s inference_request_duration_us, vLLM’s request_latency_seconds) to see whether leaks correlate with a specific endpoint or batch size.


Comparison: eBPF Tracing vs. CUDA APIs vs. nvidia-smi

ApproachAttributionOverheadRequires RecompileDetects FragmentationBest For
nvidia-smi / DCGMDevice-level onlyNegligibleNoNoCapacity planning, OOM alerts
cudaMemGetInfo pollingProcess-levelLowNoWeakQuick sanity checks
PyTorch torch.cuda.memory_statsFramework-levelLowNoYes (frame stats)PyTorch-only workloads
cuda-memcheck / compute-sanitizerPer-call, per-lineVery high (10-100x)NoNoDebugging, not production
eBPF uprobes (this guide)Per-call, per-process, per-container, per-stack~1-3 µs/call; <2% with size filterNoYes (histogram + reserved/live gap)Production leak/frag hunting

eBPF wins because it’s the only option that gives you attribution without recompilation and runs in production.


Production Hardening and Overhead Control

A few rules keep the tracer safe:

  1. Filter by size. Only trace allocations ≥1 MB. This drops ~95% of calls in most inference workloads and keeps overhead under 2%.
  2. Cap map sizes. allocs at 262144 entries is ~8 MB. Monitor BPF_MAP_LOOKUP_ELEM misses; increase only if you see drops.
  3. Sample stacks. Use bpf_get_stackid with BPF_F_USER_STACK | BPF_F_FAST_STACK_CMP and cap stacks at 16384 to avoid stack-trace flooding.
  4. Run as a sidecar, not in-process. A separate tracer container with --pid=host and CAP_BPF avoids coupling failures.
  5. Kill switch. Expose an environment variable GPU_TRACE_ENABLED=false that the aggregator checks before attaching; lets you disable without redeploying.
  6. Rate-limit alerts. A leak that grows 1 MB/min is noise; one that grows 100 MB/min is an incident. Alert on the derivative, not the absolute value.

Interpreting Results: Leak vs. Fragmentation Signatures

SignatureLeakFragmentation
alloc_count - free_countGrows monotonicallyOscillates, flat trend
live_bytesGrows steadilyStable
cuMemAlloc reserved totalGrows with live bytesGrows while live bytes flat
Size histogramUnchangedRight tail shifts
OOM triggerAfter long uptimeUnder large-batch requests
RecoveryRestart processCall torch.cuda.empty_cache() or restart

If alloc_count - free_count grows but live_bytes is flat, you’re seeing pointer reuse (the allocator returns the same address after free) — not a leak. If live_bytes grows but reserved total is flat, the caching allocator is absorbing it — a soft leak that will eventually OOM. If reserved total grows while live bytes are flat, that’s fragmentation.


Conclusion and Next Steps

GPU memory leaks and fragmentation are invisible to standard tooling because the caching allocator sits between your code and nvidia-smi. eBPF uprobes on cudaMalloc/cudaFree (and their driver-API counterparts) give you per-call, per-process, per-container attribution with negligible overhead — no recompile, no sanitizer, production-safe.

Next steps to make this operational:

  1. Package the BCC program and aggregator as a DaemonSet with --pid=host and CAP_BPF.
  2. Emit gpu_alloc_unmatched, gpu_live_bytes, and gpu_frag_ratio as Prometheus gauges.
  3. Build a Grafana panel comparing reserved vs. live bytes per container.
  4. Add a runbook: when unmatched > 1000 for 5 min, dump the top 10 stack traces from stacks and page the on-call.
  5. Extend the tracer to hook cudaMallocAsync and cuMemAllocAsync if you’re on CUDA 11.2+ with async allocators.

The result: OOM incidents become traceable, reproducible, and fixable — instead of mysterious pod restarts.


FAQ

Does eBPF uprobe tracing work with the CUDA driver API as well as the runtime API? Yes. You can attach uprobes to libcudart.so for cudaMalloc/cudaFree and to libcuda.so for cuMemAlloc/cuMemFree. PyTorch and most frameworks use the runtime API, but the caching allocator ultimately calls the driver API, so tracing both layers gives you the clearest picture of real device allocations versus framework-level caching.

What is the performance overhead of tracing every CUDA allocation with eBPF? Each uprobe hit costs roughly 1-3 microseconds. Inference workloads that allocate thousands of tensors per request can see measurable overhead, so filter by allocation size (for example, only sizes above 1 MB) or sample a fraction of calls. In practice, tracing only large allocations keeps overhead under 2% while still exposing leaks and fragmentation.

Can eBPF tracing detect fragmentation, or only leaks? It detects both, but differently. Leaks appear as allocation/free count mismatches that grow over time. Fragmentation appears as a growing spread between total allocated bytes and the largest contiguous free block, which you infer by tracking the distribution of live allocation sizes and free-list behavior in the caching allocator.

Do I need to modify or recompile my inference application? No. uprobes attach to user-space shared libraries at runtime, so no application changes or recompilation are required. You only need root or CAP_BPF/CAP_SYS_ADMIN privileges on the host and the CUDA libraries present in the container or host filesystem.

Why not just use nvidia-smi or DCGM to detect GPU memory leaks? nvidia-smi and DCGM report device-level totals, which include cached and reserved memory, so a leak inside the caching allocator can be invisible until the process crashes with an out-of-memory error. eBPF uprobes give per-call, per-process attribution with stack traces, letting you pinpoint the exact allocation site that never frees.

Sponsored / Ad Space