File size: 7,028 Bytes
56fccf8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | # 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.
|