gpu-training-acceleration
Use when optimizing PyTorch training speed or memory on CUDA GPUs — global flags, torch.compile, fused optimizers, mixed precision, gradient checkpointing, kernel fusion, memory layout, or latent-space training. Applies to any PyTorch training workload. Triggers: "torch.compile", "TF32", "fused optimizer", "mixed precision", "bf16", "fp16", "gradient checkpointing", "Triton kernel", "CUDA flags", "GPU slow", "GPU memory"
Best use case
gpu-training-acceleration is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Use when optimizing PyTorch training speed or memory on CUDA GPUs — global flags, torch.compile, fused optimizers, mixed precision, gradient checkpointing, kernel fusion, memory layout, or latent-space training. Applies to any PyTorch training workload. Triggers: "torch.compile", "TF32", "fused optimizer", "mixed precision", "bf16", "fp16", "gradient checkpointing", "Triton kernel", "CUDA flags", "GPU slow", "GPU memory"
Teams using gpu-training-acceleration should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/gpu-training-acceleration/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How gpu-training-acceleration Compares
| Feature / Agent | gpu-training-acceleration | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Use when optimizing PyTorch training speed or memory on CUDA GPUs — global flags, torch.compile, fused optimizers, mixed precision, gradient checkpointing, kernel fusion, memory layout, or latent-space training. Applies to any PyTorch training workload. Triggers: "torch.compile", "TF32", "fused optimizer", "mixed precision", "bf16", "fp16", "gradient checkpointing", "Triton kernel", "CUDA flags", "GPU slow", "GPU memory"
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# GPU Training Acceleration
## When to Use
- Starting a new PyTorch training pipeline and want maximum GPU utilization
- Debugging slow training throughput (GPU util < 90%)
- Running out of GPU memory and need to trade compute for memory
- Deciding whether to use torch.compile and how to apply it safely
- Choosing optimizer kernels (fused vs standard)
- Setting up mixed precision (bf16/fp16)
- Writing custom CUDA/Triton kernels that interact with AMP
- Pre-computing encoder features to skip expensive forward passes during training
- For generative model evaluation metrics, see `genai-evaluation-metrics` skill
## Core Principles
### Config-Gated Acceleration
Every acceleration flag must be controlled by config, not hardcoded. Features like `torch.compile` can break on specific PyTorch versions or model architectures. Config gating lets you toggle without code changes:
```yaml
runtime:
compile: false # torch.compile on decoder sub-modules
fused_adamw: true # fused AdamW kernel
precision: bf16 # mixed precision dtype
```
```python
# Good: config-gated
if cfg.training.runtime.compile:
model.decoder = torch.compile(model.decoder)
# Bad: always-on
model.decoder = torch.compile(model.decoder) # Breaks when Inductor has bugs
```
### Compile Sub-Modules, Not Full Models
`torch.compile` on the full model triggers recompilation when input shapes change (common with variable-length audio/text). Compile only the fixed-shape decoder sub-modules:
```python
# Good: compile specific sub-modules with stable shapes
model.ctc_adapter = torch.compile(model.ctc_adapter)
model.ar_decoder = torch.compile(model.ar_decoder)
# Leave encoder (variable input length) uncompiled
# Bad: compile entire model
model = torch.compile(model) # Recompiles on every new input length
```
### Log Acceleration State
Always log which acceleration features are active — essential for debugging throughput differences between runs:
```python
log.info("Acceleration: compile=%s fused_adamw=%s amp=%s amp_dtype=%s",
compile_enabled, fused_adamw, amp_enabled, amp_dtype)
```
## Patterns
### Global CUDA Flags
Set these once at startup before any CUDA operations:
```python
def set_cuda_acceleration_flags():
"""Enable hardware acceleration features. Call before model creation."""
# TF32 for matmul (3x faster than FP32, negligible accuracy loss)
torch.set_float32_matmul_precision("high")
torch.backends.cuda.matmul.allow_tf32 = True
# cuDNN TF32 + autotuner
torch.backends.cudnn.allow_tf32 = True
torch.backends.cudnn.benchmark = True # Autotuner picks fastest conv algorithm
# Dynamo cache (for torch.compile)
torch._dynamo.config.cache_size_limit = 64
```
### Fused AdamW
Single CUDA kernel per optimizer step instead of per-parameter:
```python
optimizer = torch.optim.AdamW(
model.parameters(),
lr=cfg.lr,
fused=True, # Requires CUDA, ~10-15% optimizer step speedup
)
```
### Flash Attention (Zero Code)
PyTorch 2.1+ `nn.TransformerEncoder`/`Decoder` auto-dispatch to SDPA/Flash Attention. No code needed — just use the standard modules:
```python
# This automatically uses Flash Attention when available
encoder_layer = nn.TransformerEncoderLayer(d_model=1024, nhead=8, batch_first=True)
encoder = nn.TransformerEncoder(encoder_layer, num_layers=6)
```
### Mixed Precision with Accelerate
```python
from accelerate import Accelerator
accelerator = Accelerator(mixed_precision="bf16")
model, optimizer = accelerator.prepare(model, optimizer)
# Forward/backward automatically uses bf16 where safe
```
### GPU Memory Monitoring
Use `memory_reserved()` to match `nvidia-smi`, not `memory_allocated()`:
```python
# memory_allocated(): active tensors only (~5 GB typical)
# memory_reserved(): caching allocator pool (~58 GB, matches nvidia-smi)
gpu_mem_gb = torch.cuda.memory_reserved() / 1e9
```
### Handling torch.compile Failures
`torch.compile` Inductor bugs are version-specific and non-deterministic. Pattern:
1. Gate behind config flag (`compile: true/false`)
2. Default to `false` until verified stable on your PyTorch version
3. Test in a fastrun before enabling in fullrun
4. Log compile state so you can correlate with speed differences
```python
if cfg.training.runtime.compile:
try:
model.decoder = torch.compile(model.decoder)
log.info("torch.compile enabled on decoder")
except Exception as e:
log.warning("torch.compile failed, continuing without: %s", e)
cfg.training.runtime.compile = False
```
### Gradient Checkpointing
Trade ~10% speed for ~50% memory by recomputing activations in backward. Config-gate with `runtime.gradient_checkpointing`.
See [references/gradient-checkpointing.md](references/gradient-checkpointing.md) for implementation.
### Fused Add + LayerNorm (Triton) & Residual in FP32
Fuse residual addition with normalization into a single Triton kernel, and keep the residual stream in FP32 to prevent numerical drift.
See [references/triton-fused-ops.md](references/triton-fused-ops.md) for Triton kernel patterns and FP32 residual implementation.
### Custom Autograd with AMP & Multi-Tier Attention Fallback
Use `@custom_fwd`/`@custom_bwd` for custom autograd ops under mixed precision, and a 3-tier attention fallback (SDPA > xformers > math).
See [references/custom-autograd-amp.md](references/custom-autograd-amp.md) for implementation details.
### Memory Layout, In-Place Operations, `empty_cache()` & NVCC Build
Contiguous memory enforcement, in-place ops for peak memory reduction, strategic `empty_cache()` placement, and NVCC build flags.
See [references/memory-optimization.md](references/memory-optimization.md) for all memory optimization patterns.
### Latent Space Training
Pre-compute encoder/VAE features offline and train on latents to skip the encoder entirely. Config-gate with `data.use_latent`.
See [references/latent-space-training.md](references/latent-space-training.md) for offline pre-computation and config patterns.
## Quick Reference
| Technique | Speed Impact | Memory Impact | Config Key |
|-----------|-------------|---------------|------------|
| TF32 matmul/cuDNN | Up to 3x | None | `torch.backends.cuda.matmul.allow_tf32` |
| `cudnn.benchmark` | 5-20% for convs | None | `torch.backends.cudnn.benchmark` |
| Fused AdamW | ~10-15% optim step | None | `fused=True` |
| Mixed precision (bf16/fp16) | ~2x throughput | ~50% less | `mixed_precision: bf16` |
| Flash Attention (SDPA) | 2-4x attention | O(N) vs O(N^2) | Auto in PyTorch 2.0+ |
| torch.compile (sub-modules) | 20-70% on compiled parts | None | `runtime.compile` |
| Gradient checkpointing | ~10% slower | ~50% less | `runtime.gradient_checkpointing` |
| Fused Add+Norm (Triton) | Eliminates memory pass | Less | `fused_add_norm=True` |
| Residual in FP32 | None | Slight overhead | `residual_in_fp32=True` |
| Latent space training | Skip encoder entirely | Much less | `data.use_latent` |
| In-place operations | Marginal | Less peak | Code pattern |
| `--use_fast_math` (NVCC) | Faster kernels | None | Build flag |
## Anti-Patterns
- **Compiling the full model**: Variable-length inputs cause constant recompilation. Compile stable-shape sub-modules only.
- **Always-on torch.compile**: Inductor bugs are PyTorch-version-specific. Gate behind config, default off, test first.
- **Skipping `cudnn.benchmark`**: Free speedup for conv-heavy models. Only skip if input sizes change every batch (rare in practice with padding).
- **Using `memory_allocated()` for GPU monitoring**: Shows ~5 GB when nvidia-smi shows ~58 GB. Use `memory_reserved()`.
- **Hardcoding acceleration flags**: All flags must be in config. Hardcoded flags can't be toggled for debugging or A/B comparison.
- **Forgetting to log acceleration state**: Two runs with different compile/fused settings look identical in W&B unless you log the flags.
- **`empty_cache()` in training loop**: Forces CUDA caching allocator to re-allocate every iteration. Only use before/after memory-intensive phases.
- **Missing `@custom_fwd`/`@custom_bwd`**: Custom autograd functions silently run in FP32 inside autocast, negating mixed-precision gains.
- **Non-contiguous tensors to CUDA kernels**: Silent wrong results or crashes. Always check `stride(-1) == 1` or call `.contiguous()`.
- **Running encoder during training when latents are available**: Pre-compute once, train on latents. The encoder adds zero learning signal.
## See Also
- `genai-evaluation-metrics` — Evaluation metrics during training (memory management)
- `webdataset-streaming` — Latent-space data loading from tar shards
- `wandb-experiment-tracking` — Logging acceleration state to W&BRelated Skills
slurm-gpu-training
Use when running ML training on HPC clusters with Slurm, including job submission, environment setup, monitoring, and failure triage. Applies to any GPU training workload on Slurm-managed clusters. Triggers: "sbatch", "srun", "Slurm", "SBATCH", "job submission", "HPC", "cluster", "walltime", "squeue"
ml-ablation-design
Use when designing ablation studies to compare model components, loss functions, or architectural choices. Covers synthetic data experiments, variant loops, production metrics, and W&B grouping. Triggers: "ablation", "ablation study", "variant comparison", "controlled experiment", "synthetic data experiment"
genai-evaluation-metrics
Use when evaluating generative models — choosing metrics (FID, IS, KID, sFID, FDD, FVD, PRDC, LPIPS, SSIM, AuthPct, Vendi), setting up online or offline evaluation, feature extractor selection, distributed computation, memory management during sampling. Triggers: "FID", "IS", "KID", "inception score", "frechet", "LPIPS", "SSIM", "evaluation metrics", "generative evaluation", "FVD"
youtube-wiki
Use when reading a YouTube video (especially an AI/ML interview, podcast, or technical talk) and producing a faithful, timestamped wiki entry the user can return to weeks later. Fetches the transcript via yt-dlp, sections by chapters or LLM-detected topics, summarizes per-section with parallel subagents, preserves verbatim quotes with speaker attribution, and runs a coverage test against the raw transcript. Triggers: "youtube wiki", "video wiki", "summarize this youtube", "watch this interview", "read this talk", "digest this video", "https://youtu.be/", "https://www.youtube.com/watch"
pdf-reader
Use when reading PDF papers, reports, or long documents where text, figures, and tables must all be captured and chunk-summarized without truncation. Converts PDF to a markdown + paper_content.json workspace, extracts figures and tables as standalone files, then delegates to arxiv-latex-reader's progressive two-layer reading (section index + on-demand deep reads). Triggers: "read pdf", "pdf to markdown", "summarize pdf", "pdf paper", "extract figures from pdf", "extract tables from pdf", "marker pdf", "pymupdf", "docling", "paper digest", "pdf reader"
insert-wiki
Use when capturing a single URL (X tweet, LinkedIn post, HN thread, short blog, news article, GitHub gist or issue) as a small persistent markdown entry the user can re-read later for motivation or grep across future sessions. Verbatim body + author + tags + a one-line "Why I saved this" hook. Writes to docs/wikis/YYYY-MM-DD-<slug>.md. WebFetch by default; CDP via Playwright MCP for login-walled hosts (x.com, twitter.com, linkedin.com). Redirects YouTube / arXiv / GitHub repo URLs to their specialized skills. Triggers: "insert wiki", "add to wiki", "insert this", "save this tweet", "capture this post", "add this to my wiki", "remember this link", "https://x.com/", "https://twitter.com/", "https://linkedin.com/posts/"
idea-feasibility
Use when evaluating whether a research or product idea is actually feasible — buildable, evaluable, and de-risked by available checkpoints, code, datasets, and GPU budget. Normalizes the idea, gathers primary-source evidence (arXiv, GitHub, project pages, model hosts), scores it against four mandatory hard gates, and emits a verdict + falsifiable MVP. Triggers: "idea feasibility", "is this idea feasible", "feasibility check", "can we do this", "is this practical", "worth pursuing", "评估想法可行性", "可行性分析", "这个 idea 能做吗", "这个想法靠谱吗"
idea-explore
Use when proposing new research ideas grounded in a seed paper or method — surfaces the gaps that the citation cone hasn't filled, the drawbacks the community already complains about in the official repo's GitHub issues, and the adjacent angles the literature suggests. Orchestrates followup-analysis (already-done exclusion), GitHub-issue mining (known drawbacks), and academic-deep-research (adjacent literature) into a ranked candidate-ideas report. Triggers: "idea explore", "idea-explore", "propose ideas", "explore ideas", "new directions", "research gaps", "what's missing", "build on this paper", "探索想法", "提出新想法", "研究空白"
idea-box
Use when promoting an idea from a fleeting thought into a tracked artifact with a lifecycle. Defines a per-idea on-disk directory (./idea_box/<slug>/) and a hard-gated state machine (explored → feasible/blocked → building → built/killed) that the existing reader/evaluator skills (idea-feasibility, ml-ablation-design, academic-deep-research, followup-analysis, arxiv-latex-reader, pdf-reader, github-reader, blog-reader) plug into. Public repo ships only the convention; idea data lives in the user's private idea-box repo. Triggers: "idea box", "idea-box", "new idea", "advance idea", "list ideas", "kill idea", "想法箱", "新想法", "推进想法", "列出想法"
github-reader
Use when reading a GitHub repository (especially a research code release with an accompanying paper) and producing a faithful digest that covers the implementation logic, the main insight, and the key reported results. Research-first with graceful fallback for non-paper repos. Handles arXiv link detection and delegates paper reading to arxiv-latex-reader / pdf-reader. Triggers: "read repo", "read this github", "analyze github", "digest repo", "github reader", "extract from github", "summarize this codebase", "read this code", "https://github.com/"
blog-reader
Use when reading a long technical blog post (ML research, engineering deep-dives, Distill/Lil'Log-style posts) and producing a faithful, figure-aware summary. Handles context-over-limit via section-based chunking, captures important figures via multimodal Read, and runs a coverage test to catch missing information. Triggers: "read this blog", "summarize this post", "read blog", "digest this article", "long blog post", "read this article", "blog summary", "distill post", "summarize url", "chunk and summarize"
arxiv-latex-reader
Use when reading large arxiv papers without context overflow. Progressive two-layer reading: index all sections (~2k tokens), then deep-read on demand. Never truncates. Triggers: "read paper", "paper sections", "section index", "progressive reading", "paper_content.json", "section summary"