/inferencekit:optimizing-kernelsfrom inferencekit
Profile-driven loop for closing inference bottlenecks on NVIDIA, AMD, Apple Silicon or CPU. Covers custom engines, fusion, attention, matrix kernels and memory traffic with one change, correctness check, and end-to-end screen.
Ships in inferencekit. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Start from the measured critical path: host overhead, synchronization, poor memory/compute utilization, redundant traffic or repeated work. These losses occur in text, vision, audio and other models. This skill closes them one change at a time, each checked fast and kept as a revertible commit with its numbers; the full proof runs at milestones (optimizing-inference stage 7).
Use when:
Do not use when:
Reuse the run's starting choices, including quality and model-change permissions. Ask missing choices only when this skill is invoked alone. Device work stays inside existing authorization; inferencekit intake budget runs/<run-id> checks remaining resources, not a requirement to ask again.
Independent workers may write kernels in parallel in distinct files/branches. One coordinator integrates them sequentially, and one owner per device serializes warmup, captures, quality and timing. CPU-heavy builds on the benchmark host wait for measurements to finish (parallel.md).
Start with doctor and the hardware route. Use Nsight on NVIDIA, supported ROCm tracing/counters on AMD, Instruments/Metal/MLX capture on Apple, or a CPU profiler. For an unfamiliar architecture, runtime, flag or error, retrieve current official docs and verify installed support before selecting a tool. Keep unsupported checks NOT RUN; preserve available timeline or operator attribution with its tool version and source artifact, following profiling.
The CUDA skeleton, commands and kernel recipes below are NVIDIA examples. Use the target engine's native backend elsewhere; a CUDA API name in PyTorch does not establish CUDA-tool support on ROCm. For images and speech, use the registered media adapter, structural and semantic checks, and complete request timing in affordability. Token checks, GSM8K and the ikstep LLM jobs below do not prove media correctness. Keep the same fast-check, milestone and full-proof stages with the workload's own checks.
When the user authorizes numerical changes, judge image/speech kernels against the declared modality quality budget and hash-bound external protocol. Different output bytes alone do not reject that track; exact identity remains a pure-refactor requirement or a diagnostic. Each intermediate change gets one short fixed public correctness/quality screen; promoted milestones and the final candidate need full registered quality and balanced timing. Preserve own-output integrity and all cases. Do not infer permission to prune architecture or use another model from a lossy budget.
An explicit perceptual/task acceptance policy may make numerical similarity diagnostic as well. In that case, do not discard a kernel or baseline solely for LPIPS/SSIM, cross-engine tensor/PCM equality or rounding drift. Measure the prospectively chosen mathematical controls and task/perceptual checks; fresh blinded quality is still required for promotion. No missing perceptual evidence becomes PASS.
Load researching-optimizations before selecting custom work and again when progress stalls or the bottleneck moves. Check existing engine features and emitted compiler code first. Follow compiler inspection from source through graph and dispatch to the executed kernel; inspect IR/assembly when it can test a specific hypothesis.
Use the smallest useful experiment, reuse the harness and supervisor, and keep the old path runnable. Avoid unused helpers, headers and abstractions. Independent experiments can be written concurrently; each integrated A/B isolates one change.
perf/<model>-<hardware>, from the intake's repo), and runs/<run-id>/experiments.jsonl. Why: every kept change becomes a revertible checkpoint; nothing tried is lost.The plugin ships a correctness-first engine (skeleton/README.md) that already meets the custom-engine contract: an OpenAI streaming server, seeded sampling, top-20 logprobs from the full output layer, a checkpoint loader, a CUDA-graph decode loop and torch modules per architecture.
skeleton/ikengine/ (next to this file; ${CLAUDE_PLUGIN_ROOT}/skills/optimizing-kernels/ when installed) into the run directory and commit it as the first ledger commit.python -m ikengine.serve --model <dir> --port <port>) and validate it as its README says: its model check, the gates, and quality against the reference. It is your correctness anchor and A/A partner. No module for the architecture: write one against the Model contract in ikengine/engine_api.py, correct first.Model contract one change at a time (the loop below): kernels, fusion, byte cuts. Keep the server, the sampler, the logprob path and the proofs.ikstep job light; other modalities use registered checks. Baseline proof is reused until its config changes.ikstep job full for text). A claimed change needs interleaved A/B confidence intervals and a profile showing the mechanism. Missing reference: use the no-reference route.goals.after_target. A stated deadline: work to it minus the report reserve. Explicit zero reserve means continuous validation/packaging. Log the next untried lever and why.Do not run full gates, task evaluations, balanced rounds or a new profile after every edit. Exploration screens never become published proof. Final timing includes the complete client request; label step/microkernel measurements separately.
Commit trailers and retained/rejected experiment records: commit-ledger.md. Use the platform profiler and registered client timer; text CLI examples are in harness-commands.md.
These apply across model families; select by the measured problem, not a list of fashionable names. For each, estimate headroom, confirm the mechanism, screen quality, then time the whole request.
| Observed problem | NVIDIA | AMD | Apple | Tradeoff / proof |
|---|---|---|---|---|
| CPU launches and tiny kernels | CUDA Graphs, fusion, device sampling | Supported HIP graph/runtime capture, Triton/HIP fusion | Reuse Metal command submission, MLX compiled/fused paths | Verify fewer gaps; include dispatch and synchronization. Sampling applies only where the workload samples. |
| Repeated intermediate traffic | Producer-consumer fusion, layout/producer quantization | HIP/Triton/CK layouts and fused epilogues | Metal/MLX fusion, layouts and quantized producers | Measure bytes and end-to-end cost; quantization needs permission. Fusion can increase registers. |
| Poor matrix utilization | Shape-specific GEMM/GEMV, tiling, split-K, supported matrix instructions | gfx-specific MFMA/WMMA, CK/Triton/other supported compiler | Metal SIMD-group matrices or native MLX kernels | Include packing/reduction overhead and shape tails; matrix paths are generation/dtype specific. |
| Synchronization dominates | Persistent kernels or megakernels | Supported persistent HIP kernels with explicit synchronization | Supported persistent/threadgroup design; do not assume grid-wide barriers | Check residency, occupancy, deadlock hazards and actual saved critical path. HazyResearch examples are hardware-specific research. |
| Model pages or barely fits | Packing, cache sizing, expert residency, staged loading/offload | Same memory strategies with supported allocator/transfer paths | Unified-memory working set, packing, cache limits and staged loading | Peak host/device memory, swap, complete latency and quality; fitting alone is not a latency win. |
| Repeated computation | Validated state/prefix reuse or incremental updates | Same algorithm with native runtime state | Same algorithm with native runtime state | Reset/invalidation across requests and changing inputs; approximate reuse needs quality permission and a separate realistic workload. |
See research sources for current implementations. CPU routes use the same hypotheses with vectorization, threading and cache-aware libraries.
| Technique | Loss it closes | Mechanism evidence | Deep dive |
|---|---|---|---|
| CUDA graph for the whole step | host launch overhead | nsys: one graph launch per step, idle gaps gone | launch-overhead.md |
| GPU-side sampling, no per-token host sync | CPU on the critical path | nsys: no blocking D2H before the next launch | launch-overhead.md |
| Fusion: norm+RoPE+KV write, one QKV GEMV, gate-up with SiLU*up epilogue, residual+norm, act-quant into the producer | hand-offs (kernel count) | nsys: kernels per step down, step wall down | launch-overhead.md |
| FP8 block-scaled GEMV at M=1 (many blocks, 16-byte loads, per-block scales) | library GEMM tiles that cannot fill the GPU at M=1 | ncu: DRAM % of measured peak up, waves >= several | fp8-gemv.md |
| Split-K decode attention (flash-decoding) | too few blocks at batch 1, long context | ncu: waves up; nsys: attention's critical share down | attention-split-k.md |
| Programmatic dependent launch, trigger placed late | remaining hand-off between dependent kernels | step wall down in A/B; overlap between kernels shrinks | launch-overhead.md |
| Cheaper kernel prologue (hoist weight loads before the PDL wait, stage inputs asynchronously) | fixed per-kernel setup before streaming starts | prologue-only variant timing; in-step time above the bandwidth ideal | lessons.md |
| lm_head: precision, exact bound pruning (below), fusion with sampling | output-layer bytes measured for this checkpoint | bytes/token down; quality verdict at the logits | fp8-gemv.md, byte-cuts.md |
| Exact byte cuts: lossless re-encoding of 16-bit weights, bound-pruned output layer | bytes you did not need to read (moves the ceiling) | bytes/token down; proof tests pass; % of the recomputed ceiling | byte-cuts.md |
| MoE: gather-GEMV over the top-k experts, routing fused into the first expert kernel, top-k-order sum | library grouped-GEMM tiles and many helper kernels per MoE layer | nsys: kernels per layer down; ncu: DRAM % of measured peak up | moe-decode.md |
| Persistent kernel / megakernel | whatever hand-off is left | measured hand-off sum first | launch-overhead.md |
Why fusion helps at batch 1: activations are tiny (a 4,096-wide BF16 vector is 8 KB), so fusion saves almost no bytes. It saves kernels, and each dependent kernel costs a hand-off of the order of a microsecond or more.
Exact byte cuts keep the model identical (lossless track, no precision decision) and move the ceiling: estimate the exact byte floor at the start (ceilings.md, "Exact byte floor") and work them alongside kernels. Re-encoded weights store out-of-window elements as raw 16-bit values; a pruned head serves logprob requests from the full head. Each needs its proof recipe and a recomputed ceiling, and a rare_tokens PASS at the next milestone (byte-cuts.md); a lossy truncated vocabulary stays a hack.
For short prompts investigate launch overhead; for long prompts inspect matrix utilization and neighboring elementwise work. NVIDIA text examples and traps: prefill.md.
bench serve screen, and only claimed ones the A/B; a wait loop stops when the server dies.Keep the candidate check, screen, commit or rejection, and experiment id. A claimed gain additionally needs interleaved timing, a comparison CI and mechanism evidence from the supported platform profiler. Preserve tool versions and source hashes; never invent Nsight records for other backends.
experiments.jsonl and the report. Why: the next person will try the same idea.When this skill finishes a standalone engine optimization, check for an optional engine contribution after the final report. Within an optimizing-inference run, leave that step to its coordinator so the same result produces only one PR. Publication requires the user's explicit authorization and the completed engine-level proof, not a faster microbenchmark alone.
bench rounds ratio CI: derived from observed rounds; compare: observed); Amdahl bounds and bytes saved are derived; "this worked because X" is inferred until the mechanism profile is attached.bench decode) are labelled as such.references/attention-split-k.md (opens in a new tab)references/byte-cuts.md (opens in a new tab)references/commit-ledger.md (opens in a new tab)references/compiler-inspection.md (opens in a new tab)references/fp8-gemv.md (opens in a new tab)references/launch-overhead.md (opens in a new tab)references/lessons.md (opens in a new tab)references/moe-decode.md (opens in a new tab)references/prefill.md (opens in a new tab)skeleton/README.md (opens in a new tab)skeleton/ikengine/__init__.py (opens in a new tab)skeleton/ikengine/engine.py (opens in a new tab)skeleton/ikengine/engine_api.py (opens in a new tab)skeleton/ikengine/graph_loop.py (opens in a new tab)skeleton/ikengine/loader.py (opens in a new tab)skeleton/ikengine/models/__init__.py (opens in a new tab)skeleton/ikengine/models/dense.py (opens in a new tab)skeleton/ikengine/models/gemma4.py (opens in a new tab)skeleton/ikengine/models/qwen3_5.py (opens in a new tab)skeleton/ikengine/moe.py (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
kernel-optimization, inference-optimization, gpu-profiling, cuda, roc
npx claudepluginhub kittenml/inferencekit --plugin inferencekit9 skills in this plugin
/benchmarkingMeasure end-to-end inference latency, throughput, memory and cost against tuned baselines with balanced rounds and quality evidence. Use for engine/config comparisons and performance claims. Route text, image, audio and video to their own client timers and protocols; isolate device measurements./evaluating-quantizationChoose a compressed model format by measuring memory, complete-request speed and task/perceptual quality on the exact target hardware. Use for quantization, lower precision or fitting a model on cheaper hardware. Respect the chosen quality policy and separate model-change permissions./inference-triageRoute inference performance questions for text, image, audio, video and other models to the cheapest useful evidence: latency, throughput, memory, hardware cost or quality. Use when unsure where to start; select tools for NVIDIA, AMD, Apple Silicon or CPU and preserve resource authorization./optimizing-inferenceOptimize a model for faster responses, more requests, less memory or cheaper hardware. Ask simple quality and budget questions, research current implementations, tune the strongest supported baseline, investigate compiler/kernel bottlenecks and prove end-to-end results. Covers text, image, audio and video with modality-specific checks; accepts an intake or written brief./profilingFinds where inference time goes and why a kernel is slow on NVIDIA, AMD ROCm, Apple Metal and CPUs, routing to vendor timelines then supported kernel analysis; nsys only or the PyTorch profiler when GPU counters are blocked. Use for "where does the time go", "why is decode/prefill slow", "GPU idle", "launch overhead", "which kernel", "is this kernel memory-bound", "nsys", "ncu", "torch profiler", "profile". Never proves a speedup./proving-correctnessVerify correctness and agreed quality after engine, kernel, precision or model changes. Use before a performance claim and for quick exploration screens. Select exact, task or perceptual checks for text, image, audio, video and other supported tasks; keep missing evidence UNPROVEN.Other plugins' skills for the same job