import torch
import time
import gc
import math
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from collections import defaultdict
from dataclasses import dataclass
from typing import List, Dict, Optional
# ==========================================
# 1. TELEMETRY & DATA STRUCTURES
# ==========================================
@dataclass
class MemEvent:
event_type: str # 'alloc' or 'free'
addr: int
size: int # in bytes
timestamp: float
tensor_id: int
# In a real implementation, you would capture the Python stack trace here
# using the 'inspect' module.
class FragmentationMonitor:
"""
Context manager to capture GPU memory allocation events.
NOTE: Hooking malloc/free in Python adds overhead. Use for debugging, not training.
"""
def __init__(self):
self.events = []
self.active_tensors = {} # addr -> size
self.counter = 0
self._prev_alloc_hook = None
self._prev_free_hook = None
def __enter__(self):
if not torch.cuda.is_available():
raise RuntimeError("CUDA not available")
# Clear cache to start clean
torch.cuda.empty_cache()
# Register hooks
self._prev_alloc_hook = torch.cuda.memory._record_memory_history()
# Note: PyTorch does not expose raw function pointers for hooks easily in Python
# without C++ extensions. For this toolkit, we will poll snapshots
# or use a simplified simulation for the 'Repro Harness'.
# Below is a polling approach for the 'capture' phase.
print("[Toolkit] Monitoring started (Simulation/Polling mode)...")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# Restore state
torch.cuda.memory._record_memory_history(enabled=None)
print(f"[Toolkit] Monitoring finished. Captured {len(self.events)} events.")
def capture_snapshot(self):
"""Captures the current state of memory segments."""
return torch.cuda.memory_snapshot()
# ==========================================
# 2. HEURISTICS ENGINE
# ==========================================
class FragmentationAnalyzer:
def __init__(self, snapshot_data):
self.snapshot = snapshot_data
self.segments = snapshot_data # List of segments
def calculate_fragmentation_index(self):
"""
Fragmentation Index = 1 - (Largest Contiguous Block / Total Free Memory)
"""
total_free = 0
largest_contiguous = 0
current_run = 0
# This requires parsing the segment list
# For simplicity, we calculate based on torch.cuda.mem_get_info()
# and memory_stats() in a real scenario, but here we simulate the logic:
free_mem, total_mem = torch.cuda.mem_get_info()
allocated = torch.cuda.memory_allocated()
reserved = torch.cuda.memory_reserved()
# "Heap Fragmentation" approx
if reserved == 0: return 0.0
# A simple heuristic based on unused reserved memory
waste = reserved - allocated
# If we have lots of reserved but little allocated, and OOMs are happening,
# it's fragmentation.
return 1.0 - (allocated / reserved) if reserved > 0 else 0.0
def diagnose(self):
print("\n--- DIAGNOSIS REPORT ---")
# 1. Stats
free, total = torch.cuda.mem_get_info()
reserved = torch.cuda.memory_reserved() / (1024**3)
allocated = torch.cuda.memory_allocated() / (1024**3)
print(f"GPU Total: {total / (1024**3):.2f} GB")
print(f"Reserved (PyTorch): {reserved:.2f} GB")
print(f"Allocated (Tensors): {allocated:.2f} GB")
print(f"Internal Waste: {reserved - allocated:.2f} GB")
# 2. Segmentation Analysis
# Simulate deep analysis of segments
num_segments = len(self.segments)
print(f"Number of Memory Segments: {num_segments}")
if num_segments > 10:
print("[!] WARNING: High segment count indicates severe fragmentation.")
return {
"reserved": reserved,
"allocated": allocated,
"segments": num_segments
}
# ==========================================
# 3. VISUALIZER (The "MRI Scan")
# ==========================================
def plot_memory_map(snapshot, filename="fragmentation_map.png"):
"""
Generates a visual map of GPU memory.
Red = Occupied, Green = Free (but reserved by allocator)
"""
if not snapshot:
print("No data to plot.")
return
fig, ax = plt.subplots(figsize=(12, 8))
# Accumulate total size to set axis limits
max_addr = 0
# Flatten segments into blocks for plotting
# PyTorch snapshot format: List of segments, each with blocks
for i, segment in enumerate(snapshot):
seg_start = segment['addr']
seg_size = segment['total_size']
# Draw segment container
rect = mpatches.Rectangle((seg_start, i), seg_size, 1,
linewidth=1, edgecolor='black', facecolor='none', linestyle='--')
ax.add_patch(rect)
# Draw blocks inside segment
for block in segment['blocks']:
b_start = block['addr'] - seg_start # Relative offset (usually)
# The snapshot 'addr' in block is absolute usually
# Visual positioning logic
x = block['addr']
width = block['size']
color = 'red' if block['state'] == 'active_allocated' else 'lightgreen'
rect = mpatches.Rectangle((x, i), width, 1, color=color)
ax.add_patch(rect)
if x + width > max_addr:
max_addr = x + width
ax.set_xlim(0, max_addr)
ax.set_ylim(0, len(snapshot) + 1)
ax.set_xlabel("Memory Address (Bytes)")
ax.set_ylabel("Segment Index")
ax.set_title("GPU Memory Fragmentation Map (Red=Used, Green=Free/Fragmented)")
plt.tight_layout()
plt.savefig(filename)
print(f"[Toolkit] Saved memory map to {filename}")
plt.close()
# ==========================================
# 4. REPRO HARNESS & RECOMMENDER
# ==========================================
def repro_harness(ops_sequence):
"""
Accepts a list of tuples: [('alloc', size_mb), ('free', idx), ('sleep', t)]
Allows reproducing fragmentation patterns in isolation.
"""
print("\n--- REPRO HARNESS ACTIVE ---")
tensors = []
for op, val in ops_sequence:
if op == 'alloc':
# Allocate size in MB
size_bytes = int(val * 1024 * 1024)
# Allocate float32 (4 bytes)
num_el = size_bytes // 4
try:
t = torch.randn(num_el, device='cuda')
tensors.append(t)
print(f"Allocated {val} MB")
except RuntimeError as e:
print(f"OOM at {val} MB allocation!")
return False
elif op == 'free':
if val < len(tensors):
tensors[val] = None
torch.cuda.empty_cache() # Force free
print(f"Freed tensor index {val}")
return True
def generate_recommendations():
print("\n--- CODE RECOMMENDATIONS ---")
recommendations = [
"1. PIN MEMORY LIFECYCLES: Allocate large persistent buffers (e.g., cached KV, Replay Buffers) at the start of the script, before training loops.",
"2. AVOID INTERLEAVED SIZES: If mixing small and large tensors, group allocations. Don't create/destroy tiny temp tensors inside a loop that also allocates huge activations.",
"3. USE `empty_cache` STRATEGICALLY: Call `torch.cuda.empty_cache()` only at the end of an epoch or a distinct phase, NOT inside the training step batch loop.",
"4. GRADIENT ACCUMULATION: If OOM is the issue, reduce batch size and accumulate gradients.",
"5. CHECKPOINTING: Use `torch.utils.checkpoint` to trade compute for memory to flatten the memory curve."
]
for rec in recommendations:
print(rec)
# ==========================================
# MAIN EXECUTION FLOW
# ==========================================
if __name__ == "__main__":
# 1. Simulate a messy workload
print("Simulating fragmented workload...")
# Allocate some big blocks
big_boys = [torch.randn(500_000_000, device='cuda') for _ in range(2)] # ~2GB each
# Allocate many small blocks
small_boys = [torch.randn(10_000, device='cuda') for _ in range(1000)]
# Free every other big block to create holes
for i in range(0, len(big_boys), 2):
big_boys[i] = None
# Free half the small blocks
for i in range(0, len(small_boys), 2):
small_boys[i] = None
# Force an allocation that might fit in total free memory but not contiguous
try:
# Attempt to allocate 3GB (assuming 2GB freed from big boys + slack)
# This will likely fail or cause PyTorch to request more VRAM from OS
crash_test = torch.randn(750_000_000, device='cuda')
except RuntimeError:
print("Expected OOM or aggressive caching occurred.")
# 2. Capture Telemetry
snapshot = torch.cuda.memory_snapshot()
# 3. Analyze
analyzer = FragmentationAnalyzer(snapshot)
stats = analyzer.diagnose()
# 4. Visualize
plot_memory_map(snapshot)
# 5. Recommendations
generate_recommendations()