ml-gpu-profiling
<!-- Loaded by foundry:perf-optimizer (opus + high) -->
$ npx -y skills add Borda/AI-Rig --agent claude-codeHow it fires
How this agent gets triggered: by you, by Claude, or both.
- Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
- You can call itInvoke it directly when you want it.
Context preview
The summary Claude sees to decide when to auto-load this agent.
<!-- Loaded by foundry:perf-optimizer (opus + high) -->
Agent definition
ml-gpu-profiling.md<!-- Loaded by foundry:perf-optimizer (opus + high) -->
ML / GPU Profiling (foundry:perf-optimizer specialized guidance)
Read only when workload involves GPU/ML profiling (CUDA, PyTorch training, model inference, DataLoader bottlenecks, mixed precision). Skip for pure CPU/IO profiling.
PyTorch Profiler
import torch
from torch.profiler import profile, record_function, ProfilerActivity
with profile(
activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
record_shapes=True,
profile_memory=True,
with_stack=True,
) as prof:
with record_function("model_inference"):
output = model(input_batch)
print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=20))
prof.export_chrome_trace("trace.json")GPU Utilization Monitoring
nvidia-smi dmon -s u
nvidia-smi --query-gpu=utilization.gpu,memory.used,memory.free --format=csv -l 1
uv tool install nvitop # or: pip install nvitop
nvitop
> **Platform notes** — nvidia-smi and CUDA-specific calls above apply to NVIDIA GPUs only: > - **Apple MPS**: use `torch.profiler` with `torch.device("mps")`; no nvidia-smi; monitor via Activity Monitor (GPU History) or Instruments (Metal System Trace) > - **AMD ROCm**: replace `nvidia-smi` with `rocm-smi`; `torch.profiler` with `ProfilerActivity.CPU` works; omit `ProfilerActivity.CUDA` > - **Intel Arc**: use Intel VTune Profiler or `torch.profiler` with XPU backend; no nvidia-smi
DataLoader Bottleneck Detection
`data_fraction = data_time / step_time` then `cpu_bound = data_fraction > 0.3` → pipeline CPU-bound. Fix: increase `num_workers`, add `pin_memory=True`, `persistent_workers=True` — or switch to faster augmentations (e.g. albumentations) when augmentation dominates `data_time`.
DataLoader Optimization
**Throughput parameters** (`num_workers`, `persistent_workers`, `pin_memory`, `prefetch_factor`): owned by `foundry:perf-optimizer` — tune based on `data_fraction` ratio (see Detection above). Set `num_workers > 0`, `pin_memory=True`, `persistent_workers=True` as first fix when DataLoader is bottleneck. **Correctness/reproducibility** (`worker_init_fn` seeding, split isolation, leakage detection): see `research:data-steward` (requires `research` plugin). If `research` plugin unavailable, apply throughput tuning only and flag correctness audit as out-of-scope.
Mixed Precision (torch.amp — PyTorch 2.0+)
# PyTorch 2.0+: device-agnostic API (torch.cuda.amp deprecated in 2.4)
from torch.amp import autocast, GradScaler
scaler = GradScaler("cuda")
for batch in loader:
with autocast("cuda", dtype=torch.float16):
output = model(batch)
loss = criterion(output, targets)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
# fp16: ~50% memory reduction; faster on Tensor Core GPUs
# measure: torch.cuda.memory_allocated() / torch.cuda.max_memory_allocated()# bfloat16: no GradScaler needed — bfloat16 has float32 exponent range, no underflow risk
with autocast("cuda", dtype=torch.bfloat16):
output = model(batch)
loss = criterion(output, targets)
loss.backward()
optimizer.step()Distributed Training Profiling
Profile DDP overhead by measuring all-reduce time. Common bottlenecks:
- Gradient bucket too small → too many all-reduce calls: `DDP(model, bucket_cap_mb=25)` (increase for large models)
- Uneven data distribution → fast workers wait for slow: `DistributedSampler(drop_last=True)` equalizes batches # NOTE: drops up to (world_size-1) samples per epoch — do not use in eval loops
- SyncBatchNorm overhead in small-batch regime: only use `sync_batchnorm` when `batch_per_gpu < 16`
3D Volumetric Data Performance
See `research:data-steward` (requires `research` plugin) — contains mmap (`np.load(..., mmap_mode="r")`), HDF5 chunk alignment, patch extraction patterns.
torch.compile
# PyTorch 2.0+
model = torch.compile(model) # default (inductor backend)
model = torch.compile(model, mode="reduce-overhead") # small batches
model = torch.compile(model, mode="max-autotune") # max speed, slower compile
model = torch.compile(model, dynamic=True) # prevents per-shape recompilation
# helps: repeated forward passes, simple/regular ops, training loops
# hurts: very dynamic shapes, heavy Python control flow, first inference (JIT cost)
Read more
<!-- Loaded by foundry:perf-optimizer (opus + high) -->
ML / GPU Profiling (foundry:perf-optimizer specialized guidance)
Read only when workload involves GPU/ML profiling (CUDA, PyTorch training, model inference, DataLoader bottlenecks, mixed precision). Skip for pure CPU/IO profiling.
PyTorch Profiler
import torch
from torch.profiler import profile, record_function, ProfilerActivity
with profile(
activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
record_shapes=True,
profile_memory=True,
with_stack=True,
) as prof:
with record_function("model_inference"):
output = model(input_batch)
print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=20))
prof.export_chrome_trace("trace.json")GPU Utilization Monitoring
nvidia-smi dmon -s u nvidia-smi --query-gpu=utilization.gpu,memory.used,memory.free --format=csv -l 1 uv tool install nvitop # or: pip install nvitop nvitop
> **Platform notes** — nvidia-smi and CUDA-specific calls above apply to NVIDIA GPUs only: > - **Apple MPS**: use `torch.profiler` with `torch.device("mps")`; no nvidia-smi; monitor via Activity Monitor (GPU History) or Instruments (Metal System Trace) > - **AMD ROCm**: replace `nvidia-smi` with `rocm-smi`; `torch.profiler` with `ProfilerActivity.CPU` works; omit `ProfilerActivity.CUDA` > - **Intel Arc**: use Intel VTune Profiler or `torch.profiler` with XPU backend; no nvidia-smi
DataLoader Bottleneck Detection
`data_fraction = data_time / step_time` then `cpu_bound = data_fraction > 0.3` → pipeline CPU-bound. Fix: increase `num_workers`, add `pin_memory=True`, `persistent_workers=True` — or switch to faster augmentations (e.g. albumentations) when augmentation dominates `data_time`.
DataLoader Optimization
**Throughput parameters** (`num_workers`, `persistent_workers`, `pin_memory`, `prefetch_factor`): owned by `foundry:perf-optimizer` — tune based on `data_fraction` ratio (see Detection above). Set `num_workers > 0`, `pin_memory=True`, `persistent_workers=True` as first fix when DataLoader is bottleneck. **Correctness/reproducibility** (`worker_init_fn` seeding, split isolation, leakage detection): see `research:data-steward` (requires `research` plugin). If `research` plugin unavailable, apply throughput tuning only and flag correctness audit as out-of-scope.
Mixed Precision (torch.amp — PyTorch 2.0+)
# PyTorch 2.0+: device-agnostic API (torch.cuda.amp deprecated in 2.4)
from torch.amp import autocast, GradScaler
scaler = GradScaler("cuda")
for batch in loader:
with autocast("cuda", dtype=torch.float16):
output = model(batch)
loss = criterion(output, targets)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
# fp16: ~50% memory reduction; faster on Tensor Core GPUs
# measure: torch.cuda.memory_allocated() / torch.cuda.max_memory_allocated()# bfloat16: no GradScaler needed — bfloat16 has float32 exponent range, no underflow risk
with autocast("cuda", dtype=torch.bfloat16):
output = model(batch)
loss = criterion(output, targets)
loss.backward()
optimizer.step()Distributed Training Profiling
Profile DDP overhead by measuring all-reduce time. Common bottlenecks:
- Gradient bucket too small → too many all-reduce calls: `DDP(model, bucket_cap_mb=25)` (increase for large models)
- Uneven data distribution → fast workers wait for slow: `DistributedSampler(drop_last=True)` equalizes batches # NOTE: drops up to (world_size-1) samples per epoch — do not use in eval loops
- SyncBatchNorm overhead in small-batch regime: only use `sync_batchnorm` when `batch_per_gpu < 16`
3D Volumetric Data Performance
See `research:data-steward` (requires `research` plugin) — contains mmap (`np.load(..., mmap_mode="r")`), HDF5 chunk alignment, patch extraction patterns.
torch.compile
# PyTorch 2.0+ model = torch.compile(model) # default (inductor backend) model = torch.compile(model, mode="reduce-overhead") # small batches model = torch.compile(model, mode="max-autotune") # max speed, slower compile model = torch.compile(model, dynamic=True) # prevents per-shape recompilation # helps: repeated forward passes, simple/regular ops, training loops # hurts: very dynamic shapes, heavy Python control flow, first inference (JIT cost)
Specialist-agent infrastructure for Python/ML OSS — the scaffolding that lets you maintain at scale without becoming a full-time reviewer.
Repo: Borda/AI-Rig
Other agents on ai-rig.
- challenger
Adversarial review — drills to bedrock, treats claims as unproven until evidence. NOT for: plan design (foundry:solution-architect), test coverage (foundry:qa-specialist), config formatting (foundry:curator). TRIGGER: "challenge this", "devil''s advocate", "poke holes in". SKIP:
Open agent - creator
Content specialist — blog posts, slide decks, social threads, talk abstracts. Reads approved outline, applies four-beat arc. NOT for in-code docs/README/FAQs (foundry:doc-scribe), release notes (oss:release). TRIGGER: "write a blog post", "create slides", "draft a thread". SKIP:
Open agent - curator
Config quality reviewer. Scope: agents/skills/rules (*.md) — verbosity, duplication, cross-refs, roster overlap; applies fixes. NOT for hooks (foundry:sw-engineer), ADRs (foundry:solution-architect), adversarial challenge (foundry:challenger). TRIGGER: "audit this agent",
Open agent - doc-scribe
Docs specialist — docstrings, API refs, README, standalone FAQ/comparison tables. NOT for CHANGELOG (oss:shepherd), linting (foundry:linting-expert), implementation (foundry:sw-engineer), narrative content (foundry:creator). TRIGGER: "write docs for", "add docstrings to",
Open agent - specialized-patterns
<!-- Loaded by foundry:doc-scribe (sonnet + medium) -->
Open agent - linting-expert
Python static analysis — ruff, mypy, pre-commit, lint/type fixes, type annotations. NOT for CI topology (oss:cicd-steward), test logic (foundry:qa-specialist), non-style implementation (foundry:sw-engineer), docstrings (foundry:doc-scribe). TRIGGER: "is this clean", "lint
Open agent

