Write cuda gemm kernel

From tensormux/kernel-skills · View interactive version

Write cuda gemm kernel is an AI agent skill from the GitHub repository tensormux/kernel-skills. Guide the agent through designing and implementing a correct, performance-aware CUDA GEMM kernel (C = alpha * A * B + beta * C) for a specific problem configuration, including decisions about tiling s

How to use this skill

Skill file

Skill: Write CUDA GEMM Kernel

Purpose

Guide the agent through designing and implementing a correct, performance-aware CUDA GEMM kernel (C = alpha * A * B + beta * C) for a specific problem configuration, including decisions about tiling strategy, memory hierarchy usage, tensor core eligibility, and when to defer to cuBLAS or CUTLASS instead.

Use this when

Do not use this when

Inputs the agent should gather first

Required reasoning process

  1. Decide whether to write a custom kernel at all. If cuBLAS or CUTLASS covers the use case, state that explicitly and stop. Only proceed if there is a concrete reason a custom kernel is necessary.
  1. Determine tensor core eligibility. For SM70+: WMMA API requires M/N/K tiles of 16x16x16 (fp16) or 8x32x16 / 32x8x16 variants. For SM80+: PTX MMA instructions offer more shapes. Requirements: fp16 or bf16 inputs, fp32 accumulator, K dimension divisible by the fragment K size, A and B pointers 16-byte aligned. If these are not met, fall back to scalar (SIMT) accumulation and document why.
  1. Choose the tiling hierarchy. A standard 3-level tiling strategy:

Justify the chosen tile sizes given smem capacity and register pressure.

  1. Design the shared memory layout. Load A tile as BM x BK and B tile as BK x BN into shared memory. Determine whether row-major or column-major smem layout reduces bank conflicts for the warp access pattern. Add padding columns/rows to eliminate bank conflicts if needed (typically +1 or +2 columns).
  1. Plan the load pattern. Each thread must participate in loading the A and B tiles collaboratively. Assign contiguous global memory addresses to contiguous threads to ensure coalesced loads. Use vectorized loads (float4, uint4, int4) when alignment and size allow. On SM80+, use cp.async (or cuda::memcpy_async) to overlap global loads with computation via double buffering.
  1. Design double buffering. Allocate two smem buffers for A and two for B. While computing on buffer[ping], issue async loads for buffer[pong]. This hides global memory latency behind arithmetic. Requires cp.async.wait_group or __pipeline_commit / __pipeline_wait_prior fence placement to be correct.
  1. Write the inner loop. The K-loop iterates over BK-wide slices. Each iteration: load tile into smem, sync, compute warp-level MMA or thread-level outer product, sync before next load. If double buffering: restructure so loads and computes are interleaved without extra syncs blocking overlap.
  1. Handle boundary conditions. For M % BM != 0, N % BN != 0, K % BK != 0: guard loads with bounds checks. Either pad tensors to multiples of tile size externally, or predicate the load/store with per-thread index checks. Predicated loads should return 0 for out-of-bounds positions so partial tiles accumulate correctly.
  1. Write the epilogue. Apply alpha scaling to the accumulator, load the C tile, apply beta scaling, add, then store. If beta == 0, skip the C load entirely. If fusing a bias or activation, apply it here in registers before the final store. Use vectorized stores when alignment allows.
  1. Estimate register pressure. The accumulator array dominates. For a thread tile of TM x TN with fp32 accumulators, that is TM*TN registers. Add registers for A fragments and B fragments in the inner loop. Total must stay under the per-thread register limit (255 on current hardware). If over, reduce tile size or annotate __launch_bounds__.

Kernel design rules

Correctness requirements

Performance requirements

Output format

The final response must include:

  1. Decision rationale: whether a custom kernel is appropriate, or whether cuBLAS/CUTLASS should be used instead — with explicit reasoning.
  2. Tile configuration table: BM, BN, BK, WM, WN, TM, TN (or MMA fragment shape), thread block dimensions, grid dimensions, smem size per block.
  3. Memory layout diagram (ASCII or description): how A and B tiles are laid out in smem, including any padding.
  4. Kernel code: complete, compilable CUDA kernel with all helper functions (device functions for warp reduction, fragment load, etc.). No pseudocode.
  5. Host launch code: grid/block dims, smem size, kernel call with all parameters.
  6. Correctness notes: explicit list of boundary conditions handled and how.
  7. Performance notes: expected arithmetic intensity, estimated occupancy, known bottlenecks.
  8. Known limitations: shapes or hardware where this kernel will underperform or is incorrect.

Common failure modes

Review checklist

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.