Situation: You’re running a large multi-worker GPU training job and need to reliably detect memory leaks or fragmentation across many machines/workers.Data-collection method- Use NVML (pynvml) for lightweight, accurate per-GPU metrics; fall back to nvidia-smi if NVML not available.- Sample periodically (e.g., every 5–15s) and write to a central time-series store (Prometheus, InfluxDB, or a log + batch uploader).- Collect per-process and per-GPU fields: - timestamp, host, worker_id, gpu_id - total_memory, free_memory, used_memory (NVML) - process PID + gpu_memory_usage_by_process - application-level allocator stats where possible (e.g., PyTorch: torch.cuda.memory_allocated(), torch.cuda.memory_reserved(), torch.cuda.max_memory_allocated()) — dump these periodically and at key events (epoch end, validation). - allocator metadata: number of live tensors, cached blocks (if available), and fragmentation = reserved - allocated - optional: periodic heap dumps (torch.cuda.memory_snapshot() or nsys capture for deep dives) triggered when anomalies detectedExample sampler (Python/pynvml):python
import time, json
from pynvml import nvmlInit, nvmlDeviceGetCount, nvmlDeviceGetHandleByIndex, nvmlDeviceGetMemoryInfo
nvmlInit()
count = nvmlDeviceGetCount()
while True:
ts = time.time()
records = []
for i in range(count):
h = nvmlDeviceGetHandleByIndex(i)
mem = nvmlDeviceGetMemoryInfo(h)
records.append({"ts":ts,"gpu":i,"total":mem.total,"used":mem.used,"free":mem.free})
send_to_tsdb(records) # push to Prometheus pushgateway / Influx / file
time.sleep(10)
Visualization approach- Per-worker time series: used_memory over time per GPU (line charts). Overlay application-level allocator metrics (allocated vs reserved vs HWM).- Aggregated HWM: show max per worker/GPU (high-water mark) as a heatmap or bar chart to quickly identify workers with highest peaks.- Heatmap of memory usage across workers × time to spot correlated growth patterns.- Fragmentation panel: plot (reserved - allocated) and fragmentation ratio = (reserved - allocated)/reserved.- Event annotations: mark epoch boundaries, gradient accumulation changes, checkpoint/save moments.- Drill-down links: from Grafana on anomaly to detailed logs, PyTorch snapshots, or nsys traces.Patterns and interpretation- True leak: - Persistent monotonic increase in allocated or reserved memory across many sampling intervals without corresponding frees, not explained by training phases; HWM keeps rising over hours. - Leak indicator: allocated and reserved both trend upward and do not drop after expected release points (end of step/epoch/validation). - Alert rule: sustained >X% increase in HWM over Y minutes (e.g., >10% every hour for 3 hours).- Fragmentation (allocator-level): - Reserved stays high or grows while allocated fluctuates per step — large reserved - allocated gap and growing fragmentation ratio. - Symptoms: free memory reported by OS is low, but active allocated stays moderate; subsequent large allocations fail while some memory is “unused” inside allocator. - Mitigation: torch.cuda.empty_cache(), change allocator behavior, or reduce max_allocated block size; inspect pool allocator stats.- Episodic/expected growth (gradient accumulation, larger batch or checkpointing): - Stepwise increases that coincide with known events (increase in gradient accumulation steps, longer sequences, checkpointing) and then plateau. - Allocated increases during prologue (forward/backward), then drops at step boundaries; HWM may spike but does not keep rising across epochs. - Confirm by correlating with annotations (start of gradient_accumulation change) and with profiler traces.Operational best practices- Centralized short-interval monitoring + longer-term aggregated HWM retention.- Baseline runs: capture normal memory profile for typical epochs to distinguish expected patterns.- Alerts conservative: require sustained trend, not single spikes.- Automate capture of detailed traces (nsys/torch profiler) when anomaly thresholds trigger to reduce tracing overhead.- Regularly sample allocator internals (PyTorch) and include them in dashboards for precise root cause analysis.This combination gives quick detection (time series + heatmaps), precise diagnosis (allocator metrics + fragmentation), and low overhead (periodic NVML sampling with on-demand deep traces).