pytorch-kernel-optimization

A guide to making PyTorch models and GPU operations run more efficiently. PyTorch is a framework for building and training machine-learning models, and the guide covers both built-in optimisations and custom GPU code.

In plain words
What is it for?
Use it to tune model throughput or latency, apply torch.compile, improve tensor and memory handling, write custom autograd or CUDA/Triton code, use mixed precision, and profile workloads.
Why use it?
It helps identify slow computation, inefficient memory use, excessive data movement, and input bottlenecks. It also helps choose between compiler settings, tensor changes, and custom extensions.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/amd-agi/apex/pytorch-kernel-optimization
Any agent
npx skills add AMD-AGI/Apex --skill pytorch-kernel-optimization
Clone the repo
git clone --depth 1 https://github.com/AMD-AGI/Apex

Made for: Claude Code, Codex.

Per session 57 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 823 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00057 $0.00823
Opus 5 $0.00028 $0.00411
Sonnet 5 $0.00011 $0.00165
Haiku 4.5 $0.00006 $0.00082

Measured 2d ago against content hash fa9f73ec0e55, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

pytorch-kernel-optimization scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

tools/skills/pytorch-kernel-optimization/SKILL.md · 40 lines

How it starts

The opening of the file, as written. The whole thing — 40 lines — stays where its author put it; the contents beside it link to each section on GitHub.

PyTorch Kernel Optimization

Purpose

  • Equip PyTorch workflows with concrete optimization patterns from high-level APIs to custom kernels.
  • Provide practical snippets for compilation, extensions, mixed precision, memory efficiency, and profiling.

When to Use

  • Tuning PyTorch models for throughput/latency on GPU.
  • Deciding between compiler-level optimizations and custom kernels (C++/CUDA/Triton).
  • Profiling and addressing bottlenecks in compute or input pipelines.

How to Use

  • Efficient tensor ops: favor contiguous layouts (.contiguous() when needed); use channels_last for convs; replace Python loops with vectorized ops; prefer in-place ops (add_, mul_, out=) when autograd-safe.
  • torch.compile: wrap functions or models with @torch.compile; choose modes:
    • "default" balanced, "reduce-overhead" for small batches/CUDA graphs, "max-autotune" for peak perf, "max-autotune-no-cudagraphs" when graphs undesirable.
    • Use fullgraph=True for whole-graph capture; set dynamic=False when shapes are static.
  • Custom autograd: implement torch.autograd.Function saving minimal tensors; recompute in backward when memory-bound (e.g., checkpointed attention); use custom backward formulas for fused ops (e.g., SiLU).
  • CUDA extensions: build with CUDAExtension (-O3, --use_fast_math, -arch=sm_80); enforce input checks in C++ bindings; expose kernels via PYBIND11_MODULE.
  • Mixed precision: train with torch.cuda.amp + GradScaler; mix dtypes per op if needed; leverage bfloat16 when supported.
  • Memory optimization: apply gradient checkpointing (checkpoint, checkpoint_sequential); use memory-efficient attention via scaled_dot_product_attention; consider activation offloading (CPU swap) when memory-bound.
  • Data loading: configure DataLoader with num_workers, pin_memory, prefetch_factor, persistent_workers, drop_last; implement fast collate; prefetch to GPU with custom loader using streams and non-blocking copies.
  • Model optimization: fuse Conv+BN (fuse_conv_bn), apply quantization (quant.fuse_modules, prepare, convert), prune weights via torch.nn.utils.prune; ensure evaluation mode during quantization calibration.
  • CUDA graphs: capture steady workloads via torch.cuda.CUDAGraph; warm up then capture forward/backward; reuse static input/output buffers; note torch.compile(mode=\"reduce-overhead\") can leverage graphs automatically.
  • Profiling:
    • Use torch.profiler.profile with CPU/CUDA activities, schedules, and tensorboard_trace_handler; enable record_shapes, profile_memory, with_stack.
    • Review prof.key_averages().table(sort_by=\"cuda_time_total\"); iterate on hotspots.

Read the full file on GitHub · 40 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen · 40 lines · 57 tokens per session scan A fa9f73ec0e55

Subscribe to this mod's changes

pytorch-kernel-optimization is a skill published in the GitHub repository AMD-AGI/Apex (76 stars, last pushed 5d ago), licensed MIT. It adds 57 tokens to every session and 823 once invoked, about $0.0003 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.

Related

Other skills, from other repositories

write-triton-kv-cache-append-kernel

Guide the agent through implementing a Triton kernel that writes newly computed K and V tensors into a pre-allocated KV cache during LLM inference. This covers two cache layouts (contiguous and paged / vLLM-style PagedAttention), unified prefill and decode handling via a slotmapping tensor, GQA/MQA where the cache…

tensormux/kernel-skills · 0 tokens

write-triton-rope-kernel

Guide the agent through implementing a correct Triton kernel that applies Rotary Position Embeddings (RoPE) to query and key tensors before attention. This covers the two incompatible layout conventions (GPT-NeoX/HuggingFace-LLaMA vs GPT-J/original-paper), pre-computed cos/sin table consumption, per-token position…

tensormux/kernel-skills · 0 tokens

choose-launch-configuration

Guide the agent through selecting the correct and efficient thread block dimensions and grid dimensions for a CUDA kernel, covering occupancy analysis, register and shared memory constraints, tail effects, persistent kernels, and when to use cudaOccupancyMaxActiveBlocksPerMultiprocessor as a decision tool.

tensormux/kernel-skills · 0 tokens

optimize-shared-memory-tiling

Guide the agent through designing and tuning shared memory tiling strategies for CUDA kernels, covering bank conflict analysis and elimination, tile shape selection, double buffering with async copy, occupancy tradeoffs from shared memory allocation, and the decision of when smem tiling is worth the complexity.

tensormux/kernel-skills · 0 tokens

write-cuda-layernorm-kernel

Guide the agent through designing and implementing a correct, efficient CUDA LayerNorm (and RMSNorm) kernel, covering mean/variance computation strategies, Welford online accumulation, epsilon placement, affine transform application, backward pass structure, and decomposition for non-power-of-two hidden dimensions.

tensormux/kernel-skills · 0 tokens

write-cuda-reduction-kernel

Guide the agent through designing and implementing a correct, efficient CUDA reduction kernel for a given operator (sum, max, min, or custom binary associative op), covering warp-level primitives, block-level reduction, multi-block strategies, and when to use CUB instead.

tensormux/kernel-skills · 0 tokens