| # CUDA C++ reference for kernel authors |
|
|
| Every API below **compiled with `nvcc -arch=sm_90a -std=c++17` on CUDA 12.8**, the toolchain in the task |
| containers. 24/24 of the constructs listed here were verified; nothing is quoted from memory. |
| |
| ## Building inside a task container |
| |
| ```python |
| from torch.utils.cpp_extension import load_inline |
| mod = load_inline(name="k", cpp_sources=cpp, cuda_sources=cu, |
| functions=["run"], extra_cuda_cflags=["-O3", "-arch=sm_90a", "--use_fast_math"]) |
| ``` |
| or drive `nvcc` yourself and `torch.ops.load_library`. Use `-arch=sm_90a` rather than `sm_90`: the `a` |
| ("architecture-specific") target is what enables `wgmma`, TMA and `setmaxnreg`. |
| |
| Useful flags: `-lineinfo` (maps SASS back to source in `ncu`), `-Xptxas -v` (prints register and shared |
| memory usage per kernel — check this before you profile), `--use_fast_math` (turns `expf` into |
| `ex2.approx`, and changes results — make sure the tolerance allows it). |
| |
| ## Shared memory beyond 48 KB |
| |
| The default limit is 48 KB per block. Hopper has ~227 KB opt-in, but you must ask for it **on the host**: |
| |
| ```cpp |
| cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, 200*1024); |
| kernel<<<grid, block, 200*1024>>>(...); |
| ``` |
| Query the real number rather than hardcoding it — `torch.cuda.get_device_properties(0) |
| .shared_memory_per_block_optin`. Forgetting the attribute gives a launch failure, not a slow kernel. |
| |
| ## Occupancy control |
| |
| ```cpp |
| __global__ void __launch_bounds__(256, 2) k(...) // 256 threads/block, ≥2 blocks/SM |
| ``` |
| The second argument caps registers per thread so the requested blocks fit. It is how you *force* a |
| tradeoff — but check `pitfalls.md` first: low occupancy is often correct, and a GEMM that wants 168 |
| registers should keep them. |
| |
| ## Async copy — three levels of control |
| |
| ```cpp |
| // 1. Highest level: pipeline object |
| #include <cuda/pipeline> |
| __shared__ cuda::pipeline_shared_state<cuda::thread_scope_block, 2> state; |
| auto p = cuda::make_pipeline(cooperative_groups::this_thread_block(), &state); |
| p.producer_acquire(); cuda::memcpy_async(dst, src, 16, p); p.producer_commit(); |
| p.consumer_wait(); /* use dst */ p.consumer_release(); |
| |
| // 2. Mid level: raw cp.async, you manage the groups |
| #include <cuda_pipeline.h> |
| __pipeline_memcpy_async(smem, gmem, 16); |
| __pipeline_commit(); |
| __pipeline_wait_prior(0); |
| |
| // 3. Lowest level: inline PTX (see ptx.md) when you need the exact issue point |
| ``` |
| |
| `cuda::barrier<cuda::thread_scope_block>` with `arrive_and_wait()` is the composable barrier; it is the |
| C++ face of `mbarrier` and what TMA completion is signalled through. |
| |
| ## TMA descriptors (host side) |
| |
| ```cpp |
| #include <cuda.h> |
| CUtensorMap map; |
| cuuint64_t size[2] = {W, H}; cuuint64_t stride[1] = {W * sizeof(bf16)}; |
| cuuint32_t box[2] = {64, 64}; cuuint32_t elem_stride[2] = {1, 1}; |
| cuTensorMapEncodeTiled(&map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, ptr, size, stride, box, elem_stride, |
| CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, |
| CU_TENSOR_MAP_L2_PROMOTION_L2_128B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); |
| ``` |
| Build it **once in untimed setup**, pass it as a kernel argument (or `__grid_constant__`), then issue |
| copies from PTX. `CU_TENSOR_MAP_SWIZZLE_128B` is what makes the shared-memory tile bank-conflict-free — |
| the swizzle happens in hardware, so do not also pad. Link with `-lcuda` for the driver API. |
| |
| ## Cooperative groups |
| |
| ```cpp |
| #include <cooperative_groups.h> |
| #include <cooperative_groups/reduce.h> |
| namespace cg = cooperative_groups; |
| |
| auto tile = cg::tiled_partition<32>(cg::this_thread_block()); |
| float s = cg::reduce(tile, v, cg::plus<float>()); // warp reduction, no shuffle by hand |
| |
| auto grid = cg::this_grid(); grid.sync(); // needs cudaLaunchCooperativeKernel |
| ``` |
| |
| **`grid.sync()` deadlocks unless every block is resident.** Launch with |
| `cudaLaunchCooperativeKernel` and size the grid from `cudaOccupancyMaxActiveBlocksPerMultiprocessor × |
| SM count` — this is the single most common way a persistent/megakernel hangs. `tools/occupancy.py` |
| checks it for you. |
|
|
| ## Clusters and distributed shared memory (Hopper) |
|
|
| ```cpp |
| __global__ void __cluster_dims__(2, 1, 1) k(...) { |
| auto c = cg::this_cluster(); |
| int* peer = c.map_shared_rank(smem, 0); // read another block's shared memory |
| c.sync(); |
| } |
| ``` |
| DSMEM lets blocks in a cluster share tiles without a round trip to global — useful when several blocks |
| consume the same B tile of a GEMM. |
|
|
| ## Data types |
|
|
| ```cpp |
| #include <cuda_bf16.h> __nv_bfloat162 v = __floats2bfloat162_rn(a, b); v = __hfma2(v, v, v); |
| #include <cuda_fp16.h> __half2 h = __floats2half2_rn(a, b); |
| #include <cuda_fp8.h> __nv_fp8_e4m3 q(1.5f); float back = (float)q; |
| ``` |
| Always use the **packed** (`x2`) intrinsics for 16-bit types: one instruction, two values. Scalar |
| `__hadd` on bf16 wastes half of every ALU slot. |
|
|
| ## Warp intrinsics |
|
|
| ```cpp |
| __shfl_xor_sync(0xffffffff, v, 16); // butterfly step |
| __reduce_add_sync(0xffffffff, u); // one-instruction integer warp reduce (sm_80+) |
| __ballot_sync(0xffffffff, pred); |
| __syncwarp(); |
| ``` |
| Always the `_sync` forms with an explicit mask — the legacy non-sync intrinsics are removed. |
|
|
| ## Atomics |
|
|
| ```cpp |
| atomicAdd(p, v); // device scope |
| atomicAdd_block(p, v); // block scope: much cheaper when that suffices |
| atomicAdd((__nv_bfloat162*)p, __floats2bfloat162_rn(a, b)); // packed |
| ``` |
| Prefer a warp/block reduction followed by one atomic per block over one atomic per thread. Note that |
| atomics make a kernel **non-deterministic** in floating point — if your correctness check compares two |
| runs, that is where the mismatch comes from. |
|
|
| ## Loads |
|
|
| ```cpp |
| __ldg(p); // read-only cache |
| __ldcs(p); // streaming, evict-first |
| __ldlu(p); // last-use, do not keep |
| const float4* q = (const float4*)__builtin_assume_aligned(p, 16); |
| float4 v = *q; // 128-bit load |
| ``` |
|
|
| ## wmma vs mma vs wgmma |
|
|
| `#include <mma.h>` gives `nvcuda::wmma` — portable, easy, and leaves performance on the table because |
| you do not control the fragment layout. Use it to get correct, then move to `mma.sync` (per-warp) or |
| `wgmma` (warpgroup) from `ptx.md` when you need the last 2x. |
|
|
| ## Scheduling |
|
|
| ```cpp |
| __nanosleep(100); // spin-loop backoff |
| cudaGridDependencySynchronize(); // PDL: wait for the prior kernel's data |
| cudaTriggerProgrammaticLaunchCompletion(); // let the next kernel start early |
| ``` |
|
|
| ## Debugging |
|
|
| ```bash |
| compute-sanitizer --tool memcheck ./a.out # OOB and misaligned access |
| compute-sanitizer --tool racecheck ./a.out # shared-memory races |
| cuobjdump -sass k.cubin | grep -cE 'LDL|STL' # register spills |
| nvcc -Xptxas -v ... # registers/smem per kernel, at compile time |
| ``` |
| Run `racecheck` once on any kernel with a hand-written barrier. A missing `__syncthreads()` usually |
| produces *correct* results at small shapes and garbage at graded ones. |
|
|