Self-Hosted eBPF GPU Observability: Tracing CUDA Memory, Kernel Latency & Contention
Quick Summary (TL;DR)
- What: Use eBPF uprobes attached to
libcudart.soto tracecudaMalloc,cudaFree, andcudaLaunchKerneldirectly from user space—no application changes required.- Why: NVML/DCGM give you device-level telemetry but no per-process, per-kernel, or call-stack attribution. eBPF fills that gap.
- How: Write a libbpf/BCC program → export counters via a Prometheus exporter → join with DCGM metrics in Grafana.
- Cost: Typically <5% CPU overhead with aggregation and sampling.
- Prereqs: Linux 5.8+ (BTF/CO-RE), NVIDIA driver + CUDA toolkit,
CAP_BPFor root.
Self-hosting AI inference and training nodes means you own the entire telemetry stack—and the blame when a job OOMs a GPU or a kernel stalls for 40 ms. The usual suspects (NVML, DCGM, nvidia-smi) tell you that a GPU is saturated, but not which process, which CUDA call, or which code path caused it. eBPF closes that gap by letting you instrument the CUDA runtime itself from the kernel, without recompiling a single line of application code.
This guide walks through a production-ready pipeline: instrumenting CUDA memory allocation, measuring kernel launch latency, detecting cross-process contention, and shipping everything to Prometheus and Grafana.
Why eBPF for GPU Observability?
Traditional GPU monitoring lives at the device boundary. NVML exposes utilization, memory, temperature, and power. DCGM adds profiling counters. Both are excellent—but they’re blind to the caller. When three inference workers share one A100, NVML says “95% utilization” and nothing more.
eBPF operates at the syscall and user-function boundary. By attaching uprobes to exported functions in libcudart.so, you can capture:
- Every
cudaMalloc/cudaFreewith size, PID, and call stack. - Every
cudaLaunchKernelwith entry/exit timestamps for queue latency. - Context switches and scheduling delays that reveal contention.
flowchart LR
A[App / PyTorch / Triton] -->|cudaMalloc, cudaLaunchKernel| B[libcudart.so]
B --> C[libcuda.so → kernel driver]
C --> D[GPU Hardware]
B -.uprobe.-> E[eBPF Program]
C -.kprobe.-> E
E --> F[BPF Maps]
F --> G[Prometheus Exporter]
D --> H[DCGM Exporter]
G --> I[Prometheus]
H --> I
I --> J[Grafana Dashboards]
The result: you can answer “which Python worker leaked 8 GB of VRAM over the last hour?” in seconds instead of hours.
Prerequisites and Environment Setup
Before writing probes, confirm your node meets these requirements.
| Requirement | Minimum | Recommended |
|---|---|---|
| Linux kernel | 4.18 | 5.8+ (BTF, CO-RE, CAP_BPF) |
| NVIDIA driver | 450.x | 535.x+ |
| CUDA toolkit | 11.0 | 12.x |
| Build tools | clang, llvm, bpftool | Same + libbpf-dev |
| Privileges | root | CAP_BPF + CAP_PERFMON |
Install the toolchain:
# Debian/Ubuntu
sudo apt install -y clang llvm libbpf-dev bpftool linux-headers-$(uname -r) \
python3-bpfcc bpfcc-tools prometheus-node-exporter
Verify BTF is available (required for CO-RE):
ls /sys/kernel/btf/vmlinux && bpftool btf dump file /sys/kernel/btf/vmlinux | head
Locate the CUDA runtime library—this is the uprobe target:
ldconfig -p | grep libcudart
# /usr/local/cuda/lib64/libcudart.so.12
Note: If your workloads run in containers, mount
/usr/local/cudaand the host’s/sys/kernel/btfinto the exporter’s namespace, or run the exporter as a DaemonSet withhostPID: true.
Instrumenting CUDA Memory Allocation with eBPF
Tracing cudaMalloc and cudaFree
The simplest approach uses BCC for a quick prototype. This attaches uprobes to the entry and return probes of cudaMalloc:
from bcc import BPF
bpf_src = r"""
#include <uapi/linux/ptrace.h>
struct alloc_t {
u64 size;
u64 ts;
};
BPF_HASH(pending, u32, struct alloc_t); // pid -> pending alloc
BPF_HISTOGRAM(size_hist, u64, 64); // log2 buckets
BPF_HASH(per_proc, u32, u64); // pid -> bytes in flight
int trace_malloc_entry(struct pt_regs *ctx, size_t size) {
u32 pid = bpf_get_current_pid_tgid() >> 32;
struct alloc_t a = { .size = size, .ts = bpf_ktime_get_ns() };
pending.update(&pid, &a);
return 0;
}
int trace_malloc_return(struct pt_regs *ctx) {
u32 pid = bpf_get_current_pid_tgid() >> 32;
struct alloc_t *a = pending.lookup(&pid);
if (!a) return 0;
u64 bytes = a->size;
per_proc.increment(&pid, bytes);
size_hist.increment(bpf_log2l(bytes));
pending.delete(&pid);
return 0;
}
"""
b = BPF(text=bpf_src)
lib = "/usr/local/cuda/lib64/libcudart.so.12"
b.attach_uprobe(name=lib, sym="cudaMalloc", fn_name="trace_malloc_entry")
b.attach_uretprobe(name=lib, sym="cudaMalloc", fn_name="trace_malloc_return")
The entry probe records the requested size and timestamp; the return probe commits it to per-PID counters and a log₂ histogram. This gives you both who is allocating and how large the allocations are.
Capturing Allocation Sizes and Call Stacks
Sizes alone don’t explain why memory grew. Add a stack trace on the entry probe to attribute allocations to Python frames or C++ call sites:
int trace_malloc_entry(struct pt_regs *ctx, size_t size) {
u32 pid = bpf_get_current_pid_tgid() >> 32;
struct alloc_t a = {};
a.size = size;
a.ts = bpf_ktime_get_ns();
bpf_get_stack(ctx, a.stack, sizeof(a.stack), 0);
pending.update(&pid, &a);
return 0;
}
Aggregate by (pid, stack_id) in a BPF_HASH and resolve symbols in user space with b.sym() or by shelling out to addr2line. In practice, you’ll discover that a suspicious 2 GB allocation actually comes from PyTorch’s caching allocator requesting a large segment—valuable context NVML can never provide.
Tracing Kernel Launch Latency
Hooking into cudaLaunchKernel
Kernel launch latency is the gap between when the host submits a kernel and when the GPU begins executing it. With eBPF, you measure host-side submission cost directly via cudaLaunchKernel entry/exit, and you can cross-reference with device-side timestamps from CUPTI or DCGM for total queue time.
struct launch_t { u64 ts; u32 gx, gy, gz; };
BPF_HASH(launch_pending, u32, struct launch_t);
BPF_HISTOGRAM(submit_ns, u64, 64);
int on_launch(struct pt_regs *ctx) {
u32 pid = bpf_get_current_pid_tgid() >> 32;
struct launch_t l = { .ts = bpf_ktime_get_ns() };
launch_pending.update(&pid, &l);
return 0;
}
int on_launch_ret(struct pt_regs *ctx) {
u32 pid = bpf_get_current_pid_tgid() >> 32;
struct launch_t *l = launch_pending.lookup(&pid);
if (!l) return 0;
u64 delta = bpf_ktime_get_ns() - l->ts;
submit_ns.increment(bpf_log2l(delta));
launch_pending.delete(&pid);
return 0;
}
Measuring Queue and Execution Time
Host-side submit time is only half the story. The queue latency—time the kernel waits in the hardware queue—is derived by subtracting the host submit completion timestamp from the first device-side execution timestamp reported by CUPTI or a stream callback. A practical pattern:
- eBPF captures submit timestamp
T_submitper(pid, stream). - CUPTI (or a lightweight
cudaEventRecordinstrumentation) capturesT_start. queue_latency = T_start - T_submit.
When queue latency spikes but submit time stays flat, that’s a hardware/scheduling issue (another process hogging the GPU). When submit time spikes, it’s CPU-side contention—context switching, Python GIL, or driver locks. Distinguishing these two is the single biggest win from eBPF-based tracing.
Detecting Cross-Process GPU Contention
Monitoring Context Switches and SM Utilization
GPU contention rarely announces itself. Two training jobs sharing a GPU cause SM thrashing that looks like 100% utilization in NVML but delivers 40% of expected throughput. Attach a kprobe to the NVIDIA driver’s context-switch path (nvidia_unlocked_ioctl or _nv012T symbols depending on driver version) and count switches per PID:
BPF_HASH(ctx_switches, u32, u64);
int on_ctx_switch(struct pt_regs *ctx) {
u32 pid = bpf_get_current_pid_tgid() >> 32;
ctx_switches.increment(&pid);
return 0;
}
High switch counts for a single PID, combined with sub-baseline SM utilization from DCGM, is a strong contention signal.
Correlating with NVML/DCGM Metrics
The magic happens when you join eBPF and DCGM data. Use the DCGM exporter with --collectors set to include DCGM_FI_PROF_SM_ACTIVE and DCGM_FI_DEV_MEM_COPY_UTIL, then label-match on gpu and pid:
# prometheus.yml snippet
scrape_configs:
- job_name: 'ebpf-gpu'
static_configs:
- targets: ['localhost:9433']
- job_name: 'dcgm'
static_configs:
- targets: ['localhost:9400']
A PromQL query to find processes with high contention:
sum by (pid, process) (rate(ebpf_gpu_ctx_switches_total[1m]))
/ on(gpu) group_left
avg by (gpu) (DCGM_FI_PROF_SM_ACTIVE)
Building the Observability Pipeline
Exporting Metrics to Prometheus
Wrap your BPF maps in a small Go or Python HTTP server exposing /metrics. Use the prometheus_client library—it’s the fastest path to a working exporter:
from prometheus_client import start_http_server, Gauge
import time
alloc_gauge = Gauge('ebpf_gpu_alloc_bytes', 'Bytes allocated', ['pid', 'process'])
def poll():
for pid, bytes_ in b["per_proc"].items():
alloc_gauge.labels(pid=pid.value, process=proc_name(pid.value)).set(bytes_.value)
start_http_server(9433)
while True:
poll()
time.sleep(5)
For production, prefer a Go exporter with libbpfgo or cilium/ebpf—lower overhead and better concurrency.
Visualizing with Grafana
Import or build a dashboard with three rows:
- Memory: stacked area of
ebpf_gpu_alloc_bytesby process, overlaid withDCGM_FI_DEV_FB_USED. - Latency: heatmap of
ebpf_gpu_submit_nshistogram, plus p99 line for queue latency. - Contention: scatter plot of ctx-switch rate vs. SM utilization per GPU.
Set alert rules on:
ebpf_gpu_alloc_bytes> 90% of device memory for >5 min.- p99 submit latency > 50 µs sustained.
- ctx-switch rate > baseline × 2 for any PID.
flowchart TD
A[eBPF probes] --> B[BPF Maps]
B --> C[Exporter /metrics]
C --> D[Prometheus]
D --> E[Grafana]
D --> F[Alertmanager]
F --> G[PagerDuty / Slack]
Comparison: eBPF vs. Traditional GPU Monitoring
| Capability | NVML / nvidia-smi | DCGM | eBPF + CUPTI |
|---|---|---|---|
| Device utilization | ✅ | ✅ | ✅ (via join) |
| Per-process attribution | ⚠️ (limited) | ⚠️ (limited) | ✅ |
| Per-kernel launch latency | ❌ | ⚠️ (profiling mode) | ✅ |
| Call-stack context | ❌ | ❌ | ✅ |
| Memory allocation sizes | ❌ | ❌ | ✅ |
| Contention detection | ❌ | ⚠️ | ✅ |
| Overhead | Negligible | Low–medium | Low (<5%) |
| Requires app changes | No | No | No |
| Kernel version requirement | Any | Any | 4.18+ |
The takeaway: eBPF doesn’t replace DCGM—it complements it by adding the caller-side context that device metrics fundamentally cannot provide.
Best Practices and Pitfalls
- Aggregate in-kernel. Never push per-event data to user space at high frequency. Use histograms and hashes; sample when necessary.
- Filter by PID early. Attach probes only to processes you care about (check
commorpidin the entry probe) to avoid tracing system-wide noise. - Version-pin your CUDA symbols.
cudaMallocis stable, but internal symbols shift across driver versions—pinlibcudart.sopaths in your exporter config. - Handle uprobe attach failures gracefully. If
libcudart.soisn’t loaded at start time, retry attachment on a timer. - Watch for re-entrancy.
bpf_get_stackcan be expensive; cache stack IDs and resolve symbols in user space. - Secure your probes. BPF programs run with elevated privileges—use signed programs, restrict loader access, and audit changes.
- Correlate, don’t duplicate. Let DCGM own device-level metrics and eBPF own call-level metrics. Joining them in Prometheus is cheaper than re-implementing either.
Conclusion
Self-hosted AI infrastructure demands observability that goes beyond “the GPU is busy.” eBPF uprobes on the CUDA runtime give you per-process memory attribution, per-kernel latency breakdowns, and cross-process contention signals—all without touching application code. Pair them with DCGM via Prometheus and Grafana, and you get a unified view: device metrics for capacity planning, call-level traces for debugging.
Start small: instrument cudaMalloc first, add launch latency next, then layer in contention detection. Within a week you’ll wonder how you ever debugged GPU OOMs with nvidia-smi alone.
FAQ
What are the system requirements for running eBPF GPU probes?
Linux kernel 4.18 or later (5.8+ recommended for BTF and CO-RE), NVIDIA drivers with the CUDA toolkit, and root or CAP_BPF privileges. Kernel headers must be available for compilation.
Can eBPF probes capture CUDA API calls without modifying the application?
Yes. Uprobes attach to exported functions in libcudart.so and intercept calls like cudaMalloc and cudaLaunchKernel transparently—no code changes, no recompilation.
How does eBPF-based GPU observability differ from NVML/DCGM? NVML and DCGM provide device-level metrics (utilization, memory, temperature) but lack per-process, per-kernel, and call-stack context. eBPF traces individual CUDA API calls, enabling fine-grained attribution and latency analysis.
Is there performance overhead when using eBPF for GPU tracing? Typically under 5% CPU when using aggregation and sampling. Avoid tracing every kernel launch in high-frequency workloads—use in-kernel histograms or sampling to keep overhead predictable.
Can I trace GPU memory allocations across multiple processes? Yes. Probes capture PID and process name, letting you attribute allocations to specific workloads. Use BPF hashes to aggregate per-process statistics and export them as labeled Prometheus metrics.