agent/: verified PTX, CUDA C++, Triton and CuTe references
Browse filesAdds agent/ref/ (ptx, cuda-cpp, triton, cute-cutlass) and agent/tools/check_toolchain.py.
Every instruction and API was compiled with the container's own nvcc on sm_90a / CUDA 12.8: 39/41 PTX instructions assemble (tcgen05 is Blackwell-only and recorded as such), 24/24 CUDA C++ constructs compile, and the Triton tables come from introspecting the installed 3.6.0.
Measured facts that are easy to get wrong: wgmma.m64nNk16.f32 needs exactly N/2 accumulator registers per thread, so an m64n256k16 tile spends 128 registers on the accumulator alone; and Triton 3.6 accepts cache_modifier='.cg' with eviction_policy='evict_first' but ptxas rejects the pair.
check_toolchain.py re-derives the tables on whatever GPU the agent actually has.
- agent/README.md +25 -2
- agent/SKILL.md +19 -0
- agent/agents/kernel-implementer.md +6 -0
- agent/agents/kernel-profiler.md +4 -0
- agent/ref/cuda-cpp.md +171 -0
- agent/ref/cute-cutlass.md +105 -0
- agent/ref/ptx.md +169 -0
- agent/ref/triton.md +129 -0
- agent/tools/check_toolchain.py +180 -0
agent/README.md
CHANGED
|
@@ -14,9 +14,9 @@ Copy into a project so Claude Code can find it:
|
|
| 14 |
|
| 15 |
```bash
|
| 16 |
mkdir -p .claude/skills/kernel-optimization .claude/agents
|
| 17 |
-
cp -r agent/*.md agent/tools .claude/skills/kernel-optimization/
|
| 18 |
cp agent/agents/kernel-*.md .claude/agents/
|
| 19 |
-
rm .claude/skills/kernel-optimization/README.md
|
| 20 |
chmod +x .claude/skills/kernel-optimization/tools/*.sh # exec bits do not survive the download
|
| 21 |
```
|
| 22 |
|
|
@@ -35,6 +35,26 @@ faster", "implement a fused attention kernel", or "solve this KBench task".
|
|
| 35 |
| `pitfalls.md` | measurement lies, correctness traps, and how to read a profile without chasing a healthy-looking counter |
|
| 36 |
| `references.md` | which open-source kernel demonstrates which technique |
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
### Tools (`tools/`)
|
| 39 |
|
| 40 |
- **`roofline.py`** — measures the device rather than quoting a datasheet, then gives the floor and
|
|
@@ -47,6 +67,9 @@ faster", "implement a fused attention kernel", or "solve this KBench task".
|
|
| 47 |
how you confirm the MMA you intended actually issued and that nothing spilled.
|
| 48 |
- **`occupancy.py`** — finds the occupancy limiter and checks a persistent grid for the co-residency
|
| 49 |
deadlock.
|
|
|
|
|
|
|
|
|
|
| 50 |
- **`ledger.md`** — one row per variant. The column that matters records whether an abandoned variant
|
| 51 |
was *slower* or merely *broken*; dropping a good optimization over a fixable bug is the most common
|
| 52 |
way to leave 2x on the table.
|
|
|
|
| 14 |
|
| 15 |
```bash
|
| 16 |
mkdir -p .claude/skills/kernel-optimization .claude/agents
|
| 17 |
+
cp -r agent/*.md agent/ref agent/tools .claude/skills/kernel-optimization/
|
| 18 |
cp agent/agents/kernel-*.md .claude/agents/
|
| 19 |
+
rm .claude/skills/kernel-optimization/README.md # this file; not part of the skill
|
| 20 |
chmod +x .claude/skills/kernel-optimization/tools/*.sh # exec bits do not survive the download
|
| 21 |
```
|
| 22 |
|
|
|
|
| 35 |
| `pitfalls.md` | measurement lies, correctness traps, and how to read a profile without chasing a healthy-looking counter |
|
| 36 |
| `references.md` | which open-source kernel demonstrates which technique |
|
| 37 |
|
| 38 |
+
### Language references (`ref/`)
|
| 39 |
+
|
| 40 |
+
| file | covers |
|
| 41 |
+
|---|---|
|
| 42 |
+
| `ref/ptx.md` | inline PTX: constraints, cache hints, `cp.async`, TMA, `mbarrier`, `mma`/`wgmma`, `ldmatrix`/`stmatrix`, `setmaxnreg`, fast-math opcodes |
|
| 43 |
+
| `ref/cuda-cpp.md` | CUDA C++: opt-in shared memory, `cuda::pipeline`, cooperative groups, clusters/DSMEM, host-side TMA descriptors, build and debug flags |
|
| 44 |
+
| `ref/triton.md` | the Triton 3.6 API surface, launch knobs, idioms, and where it caps out |
|
| 45 |
+
| `ref/cute-cutlass.md` | CuTe layout algebra, swizzles, atoms, and where CUTLASS lives in the image |
|
| 46 |
+
|
| 47 |
+
**These are verified, not recalled.** Every instruction and API was compiled with the container's own
|
| 48 |
+
`nvcc` on `sm_90a` / CUDA 12.8: 39/41 PTX instructions assemble (the two that do not are recorded —
|
| 49 |
+
`tcgen05` is Blackwell-only), 24/24 CUDA C++ constructs compile, and the Triton tables come from
|
| 50 |
+
introspecting the installed 3.6.0.
|
| 51 |
+
|
| 52 |
+
Two examples of what that buys you. `wgmma.m64nNk16.f32` needs exactly **N/2 accumulator registers per
|
| 53 |
+
thread** — measured across five shapes — so an `m64n256k16` tile spends 128 registers on the accumulator
|
| 54 |
+
alone, which is what forces warp specialisation. And Triton 3.6 *accepts* `cache_modifier=".cg"`
|
| 55 |
+
together with `eviction_policy="evict_first"` but ptxas rejects the pair; the full combination matrix is
|
| 56 |
+
in `ref/triton.md`.
|
| 57 |
+
|
| 58 |
### Tools (`tools/`)
|
| 59 |
|
| 60 |
- **`roofline.py`** — measures the device rather than quoting a datasheet, then gives the floor and
|
|
|
|
| 67 |
how you confirm the MMA you intended actually issued and that nothing spilled.
|
| 68 |
- **`occupancy.py`** — finds the occupancy limiter and checks a persistent grid for the co-residency
|
| 69 |
deadlock.
|
| 70 |
+
- **`check_toolchain.py`** — re-derives every table in `ref/` by compiling on the machine you are
|
| 71 |
+
actually on. The docs were verified on sm_90a / CUDA 12.8; on a different GPU or toolkit some rows
|
| 72 |
+
change, and this tool wins over the docs.
|
| 73 |
- **`ledger.md`** — one row per variant. The column that matters records whether an abandoned variant
|
| 74 |
was *slower* or merely *broken*; dropping a good optimization over a fixable bug is the most common
|
| 75 |
way to leave 2x on the table.
|
agent/SKILL.md
CHANGED
|
@@ -12,6 +12,19 @@ percent still rank.
|
|
| 12 |
Read `profiling.md`, `toolchain.md`, `algorithms.md`, `hardware.md` and `pitfalls.md` in this directory
|
| 13 |
as you hit the corresponding phase. Tools are in `tools/`.
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
## The loop
|
| 16 |
|
| 17 |
```
|
|
@@ -114,6 +127,12 @@ registers spilled, and whether the compiler hoisted what you expected.
|
|
| 114 |
flash-attention, CUTLASS, DeepGEMM, ThunderKittens, Liger). Read for *technique*, not copy-paste — and
|
| 115 |
note that in a graded KBench environment those libraries are deliberately absent.
|
| 116 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
## Sub-agents
|
| 118 |
|
| 119 |
For a substantial optimization, delegate: `kernel-algorithmist` (restructure the maths),
|
|
|
|
| 12 |
Read `profiling.md`, `toolchain.md`, `algorithms.md`, `hardware.md` and `pitfalls.md` in this directory
|
| 13 |
as you hit the corresponding phase. Tools are in `tools/`.
|
| 14 |
|
| 15 |
+
**`ref/` holds the language references** — reach for them while writing code, not while planning:
|
| 16 |
+
|
| 17 |
+
| file | when |
|
| 18 |
+
|---|---|
|
| 19 |
+
| `ref/ptx.md` | inline PTX: cache hints, `cp.async`, TMA, `mbarrier`, `mma`/`wgmma`, `ldmatrix`, `setmaxnreg` |
|
| 20 |
+
| `ref/cuda-cpp.md` | CUDA C++: opt-in shared memory, pipelines, cooperative groups, clusters, TMA descriptors, build flags |
|
| 21 |
+
| `ref/triton.md` | Triton 3.6 API surface, launch knobs, idioms, and the traps |
|
| 22 |
+
| `ref/cute-cutlass.md` | CuTe layout algebra and where CUTLASS lives in the image |
|
| 23 |
+
|
| 24 |
+
Every instruction and API in `ref/` was verified by compiling it on the container toolchain (sm_90a,
|
| 25 |
+
CUDA 12.8) — but **you may not be on that machine**. Run `python3 tools/check_toolchain.py` to
|
| 26 |
+
re-derive the tables for the GPU you actually have; where it disagrees with the docs, it wins.
|
| 27 |
+
|
| 28 |
## The loop
|
| 29 |
|
| 30 |
```
|
|
|
|
| 127 |
flash-attention, CUTLASS, DeepGEMM, ThunderKittens, Liger). Read for *technique*, not copy-paste — and
|
| 128 |
note that in a graded KBench environment those libraries are deliberately absent.
|
| 129 |
|
| 130 |
+
For the instruction- and API-level detail those kernels are built from, use `ref/` (above). A worked
|
| 131 |
+
example of why it is there: `wgmma.m64nNk16.f32` needs exactly **N/2 accumulator registers per thread**,
|
| 132 |
+
so an `m64n256k16` tile spends 128 registers on the accumulator alone — half the architectural maximum.
|
| 133 |
+
That single fact decides whether your warpgroup tile needs warp specialisation, and it is the kind of
|
| 134 |
+
thing that costs an hour to rediscover by compile error.
|
| 135 |
+
|
| 136 |
## Sub-agents
|
| 137 |
|
| 138 |
For a substantial optimization, delegate: `kernel-algorithmist` (restructure the maths),
|
agent/agents/kernel-implementer.md
CHANGED
|
@@ -8,6 +8,12 @@ model: opus
|
|
| 8 |
You turn a specification into a correct, fast kernel. Read
|
| 9 |
`.claude/skills/kernel-optimization/toolchain.md`, `hardware.md` and `pitfalls.md` first.
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
## Rules
|
| 12 |
|
| 13 |
1. **Query the device; never hardcode it.** `torch.cuda.get_device_properties(0)` for
|
|
|
|
| 8 |
You turn a specification into a correct, fast kernel. Read
|
| 9 |
`.claude/skills/kernel-optimization/toolchain.md`, `hardware.md` and `pitfalls.md` first.
|
| 10 |
|
| 11 |
+
While writing code, the language references are in `.claude/skills/kernel-optimization/ref/` —
|
| 12 |
+
`ptx.md` (cache hints, `cp.async`, TMA, `mbarrier`, `mma`/`wgmma`, `ldmatrix`, `setmaxnreg`),
|
| 13 |
+
`cuda-cpp.md` (opt-in shared memory, pipelines, cooperative groups, clusters, TMA descriptors, build
|
| 14 |
+
flags), `triton.md` and `cute-cutlass.md`. They were verified by compiling on sm_90a / CUDA 12.8; run
|
| 15 |
+
`python3 tools/check_toolchain.py` to confirm against the machine you are actually on.
|
| 16 |
+
|
| 17 |
## Rules
|
| 18 |
|
| 19 |
1. **Query the device; never hardcode it.** `torch.cuda.get_device_properties(0)` for
|
agent/agents/kernel-profiler.md
CHANGED
|
@@ -21,6 +21,10 @@ You return a diagnosis, never a wall of counters. Read
|
|
| 21 |
3. **Then find the mechanism.** Sectors/request for coalescing, bank conflicts for swizzle, warp stall
|
| 22 |
reasons for latency, SASS for spills and whether the MMA issued.
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
`ncu` needs performance counters: `--cap-add SYS_ADMIN` on the container, or
|
| 25 |
`NVreg_RestrictProfilingToAdminUsers=0` on the host. `ncu --version` succeeding proves nothing — it
|
| 26 |
never touches a counter. Without access you get `ERR_NVGPUCTRPERM`.
|
|
|
|
| 21 |
3. **Then find the mechanism.** Sectors/request for coalescing, bank conflicts for swizzle, warp stall
|
| 22 |
reasons for latency, SASS for spills and whether the MMA issued.
|
| 23 |
|
| 24 |
+
When the SASS does not contain the instruction you expected, `.claude/skills/kernel-optimization/ref/`
|
| 25 |
+
tells you what the instruction should have been — `ptx.md` for the MMA/async-copy families and
|
| 26 |
+
`ref/triton.md` for what Triton 3.6 will and will not emit.
|
| 27 |
+
|
| 28 |
`ncu` needs performance counters: `--cap-add SYS_ADMIN` on the container, or
|
| 29 |
`NVreg_RestrictProfilingToAdminUsers=0` on the host. `ncu --version` succeeding proves nothing — it
|
| 30 |
never touches a counter. Without access you get `ERR_NVGPUCTRPERM`.
|
agent/ref/cuda-cpp.md
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CUDA C++ reference for kernel authors
|
| 2 |
+
|
| 3 |
+
Every API below **compiled with `nvcc -arch=sm_90a -std=c++17` on CUDA 12.8**, the toolchain in the task
|
| 4 |
+
containers. 24/24 of the constructs listed here were verified; nothing is quoted from memory.
|
| 5 |
+
|
| 6 |
+
## Building inside a task container
|
| 7 |
+
|
| 8 |
+
```python
|
| 9 |
+
from torch.utils.cpp_extension import load_inline
|
| 10 |
+
mod = load_inline(name="k", cpp_sources=cpp, cuda_sources=cu,
|
| 11 |
+
functions=["run"], extra_cuda_cflags=["-O3", "-arch=sm_90a", "--use_fast_math"])
|
| 12 |
+
```
|
| 13 |
+
or drive `nvcc` yourself and `torch.ops.load_library`. Use `-arch=sm_90a` rather than `sm_90`: the `a`
|
| 14 |
+
("architecture-specific") target is what enables `wgmma`, TMA and `setmaxnreg`.
|
| 15 |
+
|
| 16 |
+
Useful flags: `-lineinfo` (maps SASS back to source in `ncu`), `-Xptxas -v` (prints register and shared
|
| 17 |
+
memory usage per kernel — check this before you profile), `--use_fast_math` (turns `expf` into
|
| 18 |
+
`ex2.approx`, and changes results — make sure the tolerance allows it).
|
| 19 |
+
|
| 20 |
+
## Shared memory beyond 48 KB
|
| 21 |
+
|
| 22 |
+
The default limit is 48 KB per block. Hopper has ~227 KB opt-in, but you must ask for it **on the host**:
|
| 23 |
+
|
| 24 |
+
```cpp
|
| 25 |
+
cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, 200*1024);
|
| 26 |
+
kernel<<<grid, block, 200*1024>>>(...);
|
| 27 |
+
```
|
| 28 |
+
Query the real number rather than hardcoding it — `torch.cuda.get_device_properties(0)
|
| 29 |
+
.shared_memory_per_block_optin`. Forgetting the attribute gives a launch failure, not a slow kernel.
|
| 30 |
+
|
| 31 |
+
## Occupancy control
|
| 32 |
+
|
| 33 |
+
```cpp
|
| 34 |
+
__global__ void __launch_bounds__(256, 2) k(...) // 256 threads/block, ≥2 blocks/SM
|
| 35 |
+
```
|
| 36 |
+
The second argument caps registers per thread so the requested blocks fit. It is how you *force* a
|
| 37 |
+
tradeoff — but check `pitfalls.md` first: low occupancy is often correct, and a GEMM that wants 168
|
| 38 |
+
registers should keep them.
|
| 39 |
+
|
| 40 |
+
## Async copy — three levels of control
|
| 41 |
+
|
| 42 |
+
```cpp
|
| 43 |
+
// 1. Highest level: pipeline object
|
| 44 |
+
#include <cuda/pipeline>
|
| 45 |
+
__shared__ cuda::pipeline_shared_state<cuda::thread_scope_block, 2> state;
|
| 46 |
+
auto p = cuda::make_pipeline(cooperative_groups::this_thread_block(), &state);
|
| 47 |
+
p.producer_acquire(); cuda::memcpy_async(dst, src, 16, p); p.producer_commit();
|
| 48 |
+
p.consumer_wait(); /* use dst */ p.consumer_release();
|
| 49 |
+
|
| 50 |
+
// 2. Mid level: raw cp.async, you manage the groups
|
| 51 |
+
#include <cuda_pipeline.h>
|
| 52 |
+
__pipeline_memcpy_async(smem, gmem, 16);
|
| 53 |
+
__pipeline_commit();
|
| 54 |
+
__pipeline_wait_prior(0);
|
| 55 |
+
|
| 56 |
+
// 3. Lowest level: inline PTX (see ptx.md) when you need the exact issue point
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
`cuda::barrier<cuda::thread_scope_block>` with `arrive_and_wait()` is the composable barrier; it is the
|
| 60 |
+
C++ face of `mbarrier` and what TMA completion is signalled through.
|
| 61 |
+
|
| 62 |
+
## TMA descriptors (host side)
|
| 63 |
+
|
| 64 |
+
```cpp
|
| 65 |
+
#include <cuda.h>
|
| 66 |
+
CUtensorMap map;
|
| 67 |
+
cuuint64_t size[2] = {W, H}; cuuint64_t stride[1] = {W * sizeof(bf16)};
|
| 68 |
+
cuuint32_t box[2] = {64, 64}; cuuint32_t elem_stride[2] = {1, 1};
|
| 69 |
+
cuTensorMapEncodeTiled(&map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, ptr, size, stride, box, elem_stride,
|
| 70 |
+
CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B,
|
| 71 |
+
CU_TENSOR_MAP_L2_PROMOTION_L2_128B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE);
|
| 72 |
+
```
|
| 73 |
+
Build it **once in untimed setup**, pass it as a kernel argument (or `__grid_constant__`), then issue
|
| 74 |
+
copies from PTX. `CU_TENSOR_MAP_SWIZZLE_128B` is what makes the shared-memory tile bank-conflict-free —
|
| 75 |
+
the swizzle happens in hardware, so do not also pad. Link with `-lcuda` for the driver API.
|
| 76 |
+
|
| 77 |
+
## Cooperative groups
|
| 78 |
+
|
| 79 |
+
```cpp
|
| 80 |
+
#include <cooperative_groups.h>
|
| 81 |
+
#include <cooperative_groups/reduce.h>
|
| 82 |
+
namespace cg = cooperative_groups;
|
| 83 |
+
|
| 84 |
+
auto tile = cg::tiled_partition<32>(cg::this_thread_block());
|
| 85 |
+
float s = cg::reduce(tile, v, cg::plus<float>()); // warp reduction, no shuffle by hand
|
| 86 |
+
|
| 87 |
+
auto grid = cg::this_grid(); grid.sync(); // needs cudaLaunchCooperativeKernel
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
**`grid.sync()` deadlocks unless every block is resident.** Launch with
|
| 91 |
+
`cudaLaunchCooperativeKernel` and size the grid from `cudaOccupancyMaxActiveBlocksPerMultiprocessor ×
|
| 92 |
+
SM count` — this is the single most common way a persistent/megakernel hangs. `tools/occupancy.py`
|
| 93 |
+
checks it for you.
|
| 94 |
+
|
| 95 |
+
## Clusters and distributed shared memory (Hopper)
|
| 96 |
+
|
| 97 |
+
```cpp
|
| 98 |
+
__global__ void __cluster_dims__(2, 1, 1) k(...) {
|
| 99 |
+
auto c = cg::this_cluster();
|
| 100 |
+
int* peer = c.map_shared_rank(smem, 0); // read another block's shared memory
|
| 101 |
+
c.sync();
|
| 102 |
+
}
|
| 103 |
+
```
|
| 104 |
+
DSMEM lets blocks in a cluster share tiles without a round trip to global — useful when several blocks
|
| 105 |
+
consume the same B tile of a GEMM.
|
| 106 |
+
|
| 107 |
+
## Data types
|
| 108 |
+
|
| 109 |
+
```cpp
|
| 110 |
+
#include <cuda_bf16.h> __nv_bfloat162 v = __floats2bfloat162_rn(a, b); v = __hfma2(v, v, v);
|
| 111 |
+
#include <cuda_fp16.h> __half2 h = __floats2half2_rn(a, b);
|
| 112 |
+
#include <cuda_fp8.h> __nv_fp8_e4m3 q(1.5f); float back = (float)q;
|
| 113 |
+
```
|
| 114 |
+
Always use the **packed** (`x2`) intrinsics for 16-bit types: one instruction, two values. Scalar
|
| 115 |
+
`__hadd` on bf16 wastes half of every ALU slot.
|
| 116 |
+
|
| 117 |
+
## Warp intrinsics
|
| 118 |
+
|
| 119 |
+
```cpp
|
| 120 |
+
__shfl_xor_sync(0xffffffff, v, 16); // butterfly step
|
| 121 |
+
__reduce_add_sync(0xffffffff, u); // one-instruction integer warp reduce (sm_80+)
|
| 122 |
+
__ballot_sync(0xffffffff, pred);
|
| 123 |
+
__syncwarp();
|
| 124 |
+
```
|
| 125 |
+
Always the `_sync` forms with an explicit mask — the legacy non-sync intrinsics are removed.
|
| 126 |
+
|
| 127 |
+
## Atomics
|
| 128 |
+
|
| 129 |
+
```cpp
|
| 130 |
+
atomicAdd(p, v); // device scope
|
| 131 |
+
atomicAdd_block(p, v); // block scope: much cheaper when that suffices
|
| 132 |
+
atomicAdd((__nv_bfloat162*)p, __floats2bfloat162_rn(a, b)); // packed
|
| 133 |
+
```
|
| 134 |
+
Prefer a warp/block reduction followed by one atomic per block over one atomic per thread. Note that
|
| 135 |
+
atomics make a kernel **non-deterministic** in floating point — if your correctness check compares two
|
| 136 |
+
runs, that is where the mismatch comes from.
|
| 137 |
+
|
| 138 |
+
## Loads
|
| 139 |
+
|
| 140 |
+
```cpp
|
| 141 |
+
__ldg(p); // read-only cache
|
| 142 |
+
__ldcs(p); // streaming, evict-first
|
| 143 |
+
__ldlu(p); // last-use, do not keep
|
| 144 |
+
const float4* q = (const float4*)__builtin_assume_aligned(p, 16);
|
| 145 |
+
float4 v = *q; // 128-bit load
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
## wmma vs mma vs wgmma
|
| 149 |
+
|
| 150 |
+
`#include <mma.h>` gives `nvcuda::wmma` — portable, easy, and leaves performance on the table because
|
| 151 |
+
you do not control the fragment layout. Use it to get correct, then move to `mma.sync` (per-warp) or
|
| 152 |
+
`wgmma` (warpgroup) from `ptx.md` when you need the last 2x.
|
| 153 |
+
|
| 154 |
+
## Scheduling
|
| 155 |
+
|
| 156 |
+
```cpp
|
| 157 |
+
__nanosleep(100); // spin-loop backoff
|
| 158 |
+
cudaGridDependencySynchronize(); // PDL: wait for the prior kernel's data
|
| 159 |
+
cudaTriggerProgrammaticLaunchCompletion(); // let the next kernel start early
|
| 160 |
+
```
|
| 161 |
+
|
| 162 |
+
## Debugging
|
| 163 |
+
|
| 164 |
+
```bash
|
| 165 |
+
compute-sanitizer --tool memcheck ./a.out # OOB and misaligned access
|
| 166 |
+
compute-sanitizer --tool racecheck ./a.out # shared-memory races
|
| 167 |
+
cuobjdump -sass k.cubin | grep -cE 'LDL|STL' # register spills
|
| 168 |
+
nvcc -Xptxas -v ... # registers/smem per kernel, at compile time
|
| 169 |
+
```
|
| 170 |
+
Run `racecheck` once on any kernel with a hand-written barrier. A missing `__syncthreads()` usually
|
| 171 |
+
produces *correct* results at small shapes and garbage at graded ones.
|
agent/ref/cute-cutlass.md
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CuTe and CUTLASS
|
| 2 |
+
|
| 3 |
+
Verified in the task container: CUTLASS headers at **`/opt/pytorch/third_party/cutlass/include`** (96
|
| 4 |
+
example directories alongside them), and the Python CuTe DSL as **`cutlass` 4.6.1** with
|
| 5 |
+
`cutlass.cute` importable. A CuTe kernel compiles with:
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
nvcc -arch=sm_90a -std=c++17 -I/opt/pytorch/third_party/cutlass/include \
|
| 9 |
+
--expt-relaxed-constexpr -cubin -o /dev/null k.cu
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
`--expt-relaxed-constexpr` is required; without it the layout algebra fails to instantiate.
|
| 13 |
+
|
| 14 |
+
## The one idea to internalise
|
| 15 |
+
|
| 16 |
+
**A layout is a function from a logical coordinate to a memory offset.** Everything else in CuTe follows
|
| 17 |
+
from that.
|
| 18 |
+
|
| 19 |
+
```cpp
|
| 20 |
+
#include <cute/tensor.hpp>
|
| 21 |
+
using namespace cute;
|
| 22 |
+
|
| 23 |
+
auto layout = make_layout(make_shape(Int<8>{}, Int<16>{}), LayoutRight{});
|
| 24 |
+
auto t = make_tensor(make_gmem_ptr(ptr), layout);
|
| 25 |
+
t(3, 5); // coordinate -> element, offset computed by the layout
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
A layout is a `(Shape, Stride)` pair, and both can be **hierarchical**: `((4,2),(8,1))` is a perfectly
|
| 29 |
+
ordinary shape. Static extents are `Int<N>{}` (compile-time, folded away); dynamic ones are plain
|
| 30 |
+
integers. Prefer static wherever the shape is known — that is where the address arithmetic disappears.
|
| 31 |
+
|
| 32 |
+
## Operations you actually use
|
| 33 |
+
|
| 34 |
+
| operation | meaning |
|
| 35 |
+
|---|---|
|
| 36 |
+
| `composition(A, B)` | apply B then A — **a swizzle is just a composition** |
|
| 37 |
+
| `logical_divide(L, tile)` | split an axis into (tile, rest) — this is tiling |
|
| 38 |
+
| `zipped_divide` / `tiled_divide` | the same, arranged for thread/value partitioning |
|
| 39 |
+
| `local_tile(t, tile, coord)` | the tile this block owns |
|
| 40 |
+
| `local_partition(t, layout, idx)` | the elements this thread owns |
|
| 41 |
+
| `make_fragment_like(t)` | register tensor matching a partition |
|
| 42 |
+
| `size(L)`, `rank(L)`, `shape(L)`, `stride(L)` | introspection, mostly at compile time |
|
| 43 |
+
|
| 44 |
+
The pattern in nearly every CuTe kernel:
|
| 45 |
+
|
| 46 |
+
```
|
| 47 |
+
global tensor -> local_tile (block's tile)
|
| 48 |
+
-> local_partition (thread's elements)
|
| 49 |
+
-> make_fragment_like + copy (into registers)
|
| 50 |
+
-> gemm(mma, acc, a_frag, b_frag, acc)
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
## Copy and MMA atoms
|
| 54 |
+
|
| 55 |
+
```cpp
|
| 56 |
+
copy(copy_atom, src, dst); // one call; the atom knows if it is cp.async, TMA, or plain ld/st
|
| 57 |
+
gemm(mma_atom, acc, a, b, acc); // one call; the atom knows if it is mma.sync or wgmma
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
The value of atoms is that the *partitioning* is described once and the instruction selection is
|
| 61 |
+
separate. Swapping `SM80_CP_ASYNC_CACHEALWAYS` for an `SM90_TMA_LOAD` atom changes how data arrives
|
| 62 |
+
without touching the loop structure.
|
| 63 |
+
|
| 64 |
+
## Swizzles
|
| 65 |
+
|
| 66 |
+
```cpp
|
| 67 |
+
auto swizzled = composition(Swizzle<3,3,3>{}, smem_layout);
|
| 68 |
+
```
|
| 69 |
+
`Swizzle<B,M,S>` XORs bits of the offset so that consecutive rows land in different shared-memory banks.
|
| 70 |
+
Use it **instead of padding**, especially for 2-byte types where padding wastes a whole bank and breaks
|
| 71 |
+
128-bit vectorisation. If you use TMA with `CU_TENSOR_MAP_SWIZZLE_128B`, the hardware already swizzles —
|
| 72 |
+
do not swizzle again.
|
| 73 |
+
|
| 74 |
+
## Debugging layouts
|
| 75 |
+
|
| 76 |
+
```cpp
|
| 77 |
+
print(layout); print_layout(layout); // ASCII table of coord -> offset
|
| 78 |
+
print_tensor(t);
|
| 79 |
+
if (thread0()) { ... } // guard host-style printing
|
| 80 |
+
```
|
| 81 |
+
`print_layout` on a 2-D layout prints the actual offset grid. When a kernel produces transposed or
|
| 82 |
+
interleaved garbage, print the layout before you read any SASS — it is almost always a partitioning
|
| 83 |
+
mistake, not an instruction mistake.
|
| 84 |
+
|
| 85 |
+
## The Python CuTe DSL
|
| 86 |
+
|
| 87 |
+
```python
|
| 88 |
+
import cutlass, cutlass.cute as cute
|
| 89 |
+
```
|
| 90 |
+
Version 4.6.1 is installed. It expresses the same layout algebra in Python and JIT-compiles, which makes
|
| 91 |
+
it far quicker to iterate on a tiling scheme than a C++ rebuild. The concepts transfer exactly, so
|
| 92 |
+
prototype the partitioning here and port to C++ if you need the last increment of control.
|
| 93 |
+
|
| 94 |
+
## Reading CUTLASS itself
|
| 95 |
+
|
| 96 |
+
96 example directories ship in the container. Two things are worth reading before writing a Hopper GEMM:
|
| 97 |
+
|
| 98 |
+
- **the collective mainloop** — how a producer warp issuing TMA and consumer warps issuing `wgmma` are
|
| 99 |
+
actually wired together, including where the `mbarrier` phases flip
|
| 100 |
+
- **the epilogue** — how the accumulator is transformed and written back with a different tiling from
|
| 101 |
+
the mainloop, which is where fused activations and scaling belong
|
| 102 |
+
|
| 103 |
+
Read them for the *structure*. Copying a CUTLASS kernel wholesale into a task rarely works, because the
|
| 104 |
+
task's shapes and fusion are not the ones the example was tuned for — and in a graded container the
|
| 105 |
+
library may not be importable at all.
|
agent/ref/ptx.md
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PTX quick reference
|
| 2 |
+
|
| 3 |
+
Every instruction below was **assembled with `nvcc -arch=sm_90a` on CUDA 12.8** — the toolchain in the
|
| 4 |
+
task containers. Nothing here is from memory. Where something does *not* work, that is recorded too.
|
| 5 |
+
|
| 6 |
+
You reach for PTX when the compiler will not emit what you need: a specific cache policy, an async copy
|
| 7 |
+
you want issued at a precise point, an MMA shape the C++ API does not expose, or a warpgroup
|
| 8 |
+
instruction. For everything else, write CUDA C++ and read the SASS.
|
| 9 |
+
|
| 10 |
+
## Inline asm syntax
|
| 11 |
+
|
| 12 |
+
```cpp
|
| 13 |
+
asm volatile("instr.mod %0, [%1];" : "=f"(dst) : "l"(ptr) : "memory");
|
| 14 |
+
// ^template ^outputs ^inputs ^clobbers
|
| 15 |
+
```
|
| 16 |
+
|
| 17 |
+
| constraint | binds to |
|
| 18 |
+
|---|---|
|
| 19 |
+
| `"f"` / `"d"` | `.f32` / `.f64` register |
|
| 20 |
+
| `"r"` / `"l"` | `.u32` / `.u64` register — **shared-memory addresses are `"r"` (32-bit)**, global are `"l"` |
|
| 21 |
+
| `"h"` | `.u16` (fp8 pairs, bf16 halves) |
|
| 22 |
+
| `"=f"` output, `"+f"` read-modify-write | |
|
| 23 |
+
|
| 24 |
+
`volatile` stops the compiler sinking or duplicating the instruction; add `"memory"` when it orders
|
| 25 |
+
other accesses. Convert a shared pointer with `__cvta_generic_to_shared(ptr)` before passing it as `"r"`.
|
| 26 |
+
|
| 27 |
+
## Loads and stores — cache control
|
| 28 |
+
|
| 29 |
+
| instruction | effect |
|
| 30 |
+
|---|---|
|
| 31 |
+
| `ld.global.nc.f32` | read-only/`__ldg` path, uses the texture cache |
|
| 32 |
+
| `ld.global.L2::128B.f32` | prefetch a 128B L2 sector |
|
| 33 |
+
| `ld.global.L1::no_allocate.f32` | streaming: do not pollute L1 |
|
| 34 |
+
| `st.global.cs.f32` | evict-first store — for data nobody reads again |
|
| 35 |
+
| `ld.global.v4.f32 {a,b,c,d}` | one 128-bit transaction; **the single most reliable bandwidth win** |
|
| 36 |
+
|
| 37 |
+
Vectorize first. A `.v4.f32` (or `.v4.b32` for two bf16x2) load moves 16B per instruction, quartering
|
| 38 |
+
the instruction count and hitting the ideal 4 sectors/request that `ncu` reports.
|
| 39 |
+
|
| 40 |
+
## Async copy (Ampere+) — `cp.async`
|
| 41 |
+
|
| 42 |
+
```
|
| 43 |
+
cp.async.ca.shared.global [%smem], [%gmem], 16; // through L1
|
| 44 |
+
cp.async.cg.shared.global [%smem], [%gmem], 16; // bypass L1, for streamed tiles
|
| 45 |
+
cp.async.commit_group;
|
| 46 |
+
cp.async.wait_group 1; // let 1 group stay in flight
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
Sizes are 4, 8 or 16 bytes; 16 is the one worth using. This is what double buffering is built from:
|
| 50 |
+
issue group N+1, then `wait_group 1` and compute on group N.
|
| 51 |
+
|
| 52 |
+
## TMA (Hopper) — bulk tensor copy
|
| 53 |
+
|
| 54 |
+
```
|
| 55 |
+
cp.async.bulk.tensor.2d.shared::cluster.global.tile.mbarrier::complete_tx::bytes
|
| 56 |
+
[%smem], [%tmap, {%x, %y}], [%mbar];
|
| 57 |
+
cp.reduce.async.bulk.tensor.2d.global.shared::cta.add.tile.bulk_group
|
| 58 |
+
[%tmap, {%x, %y}], [%smem]; // accumulate a tile straight back to global
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
One thread issues the copy for the whole tile; the descriptor (`%tmap`) is built **on the host** with
|
| 62 |
+
`cuTensorMapEncodeTiled` (see `cuda-cpp.md`). TMA does the address arithmetic, the bounds checking and
|
| 63 |
+
the swizzle in hardware — this is why Hopper kernels spend so few instructions on addressing.
|
| 64 |
+
|
| 65 |
+
## Barriers
|
| 66 |
+
|
| 67 |
+
| instruction | use |
|
| 68 |
+
|---|---|
|
| 69 |
+
| `mbarrier.init.shared.b64 [%bar], %count` | initialise, once, by one thread |
|
| 70 |
+
| `mbarrier.arrive.expect_tx.shared::cta.b64` | arrival that also declares the incoming TMA byte count |
|
| 71 |
+
| `mbarrier.try_wait.parity.shared::cta.b64` | phase-flipping wait; the loop-friendly form |
|
| 72 |
+
| `fence.proxy.async.shared::cta` | order async-proxy writes (TMA/wgmma) against generic ones |
|
| 73 |
+
| `barrier.cluster.arrive` / `.wait` | Hopper cluster-wide sync |
|
| 74 |
+
|
| 75 |
+
`fence.proxy.async` is the one people forget: TMA writes shared memory through a *different proxy* than
|
| 76 |
+
ordinary stores, so without the fence your MMA can read a tile that is not there yet.
|
| 77 |
+
|
| 78 |
+
## Tensor cores
|
| 79 |
+
|
| 80 |
+
**Per-warp (`mma.sync`)** — portable back to Ampere:
|
| 81 |
+
```
|
| 82 |
+
mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {d0..d3}, {a0..a3}, {b0,b1}, {c0..c3};
|
| 83 |
+
mma.sync.aligned.m16n8k32.row.col.f32.e4m3.e4m3.f32 {d0..d3}, {a0..a3}, {b0,b1}, {c0..c3};
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
**Warpgroup (`wgmma`, Hopper)** — issued by 128 threads, operands read straight from shared memory via
|
| 87 |
+
a 64-bit descriptor:
|
| 88 |
+
```
|
| 89 |
+
wgmma.fence.sync.aligned;
|
| 90 |
+
wgmma.mma_async.sync.aligned.m64nNk16.f32.bf16.bf16 {d...}, %desc_a, %desc_b, 1,1,1,0,0;
|
| 91 |
+
wgmma.commit_group.sync.aligned;
|
| 92 |
+
wgmma.wait_group.sync.aligned 0;
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
**Accumulator size, measured** — `m64nNk16.f32` needs exactly **N/2 f32 registers per thread**:
|
| 96 |
+
|
| 97 |
+
| shape | acc regs/thread |
|
| 98 |
+
|---|---|
|
| 99 |
+
| `m64n8k16` | 4 |
|
| 100 |
+
| `m64n16k16` | 8 |
|
| 101 |
+
| `m64n64k16` | 32 |
|
| 102 |
+
| `m64n128k16` | 64 |
|
| 103 |
+
| `m64n256k16` | 128 |
|
| 104 |
+
|
| 105 |
+
Getting this wrong is a compile error (`Argument vector size mismatch`), not a silent bug — but it also
|
| 106 |
+
tells you the register budget up front: an `m64n256k16` accumulator alone is 128 registers, half the
|
| 107 |
+
architectural maximum, which is why big-N warpgroup tiles force warp specialisation.
|
| 108 |
+
|
| 109 |
+
**Feeding the MMA:**
|
| 110 |
+
```
|
| 111 |
+
ldmatrix.sync.aligned.m8n8.x4.shared.b16 {r0..r3}, [%smem];
|
| 112 |
+
ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {r0..r3}, [%smem]; // transposed, free
|
| 113 |
+
stmatrix.sync.aligned.m8n8.x4.shared.b16 [%smem], {r0..r3};
|
| 114 |
+
```
|
| 115 |
+
`ldmatrix` loads a fragment in exactly the layout the MMA wants. `.trans` transposes for free — never
|
| 116 |
+
transpose in registers by hand.
|
| 117 |
+
|
| 118 |
+
## Warp-level
|
| 119 |
+
|
| 120 |
+
| instruction | note |
|
| 121 |
+
|---|---|
|
| 122 |
+
| `shfl.sync.bfly.b32` | butterfly reduction: `log2(32)` = 5 steps |
|
| 123 |
+
| `redux.sync.add.u32` | whole-warp integer reduction in **one** instruction (sm_80+) |
|
| 124 |
+
| `elect.sync` | pick one leader lane — cheaper than `laneid == 0` |
|
| 125 |
+
| `vote.sync.ballot.b32` | predicate mask across the warp |
|
| 126 |
+
|
| 127 |
+
## Warp specialisation (Hopper)
|
| 128 |
+
|
| 129 |
+
```
|
| 130 |
+
setmaxnreg.dec.sync.aligned.u32 24; // producer warps: give registers back
|
| 131 |
+
setmaxnreg.inc.sync.aligned.u32 232; // consumer warps: take them
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
This is the mechanism behind producer/consumer kernels: DMA warps need almost no registers, MMA warps
|
| 135 |
+
need a great many, and the register file is redistributed at runtime rather than sized for the worst
|
| 136 |
+
case.
|
| 137 |
+
|
| 138 |
+
## Scheduling and math
|
| 139 |
+
|
| 140 |
+
| instruction | note |
|
| 141 |
+
|---|---|
|
| 142 |
+
| `griddepcontrol.wait` / `.launch_dependents` | programmatic dependent launch — overlap the tail of one kernel with the head of the next |
|
| 143 |
+
| `nanosleep.u32 N` | back off inside a spin loop; without it, spinning starves the warps you are waiting on |
|
| 144 |
+
| `ex2.approx.f32` | **the softmax primitive** — compute `exp(x)` as `ex2(x * 1.4427)`; far cheaper than `exp` |
|
| 145 |
+
| `rcp.approx.f32`, `rsqrt.approx.f32`, `tanh.approx.f32` | fast paths for normalisation and gelu |
|
| 146 |
+
| `cvt.rn.satfinite.e4m3x2.f32` | pack two floats into fp8x2 with saturation, one instruction |
|
| 147 |
+
| `cvt.rn.bf16x2.f32` | pack two floats into bf16x2 |
|
| 148 |
+
|
| 149 |
+
## Atomics
|
| 150 |
+
|
| 151 |
+
```
|
| 152 |
+
red.global.add.f32 [%p], %v; // fire-and-forget: no return value, no latency to hide
|
| 153 |
+
atom.global.add.v2.f32 {%d0,%d1}, [%p], {%v0,%v1}; // vector atomic
|
| 154 |
+
```
|
| 155 |
+
Use `red` whenever you discard the old value — `atom` makes the warp wait for a result you never read.
|
| 156 |
+
|
| 157 |
+
## Not available on sm_90a
|
| 158 |
+
|
| 159 |
+
`tcgen05.*` (Blackwell 5th-gen tensor core instructions) fails with *"Instruction not supported on
|
| 160 |
+
.target sm_90a"*. If you are targeting Hopper, `wgmma` is the top of the ladder.
|
| 161 |
+
|
| 162 |
+
## Verifying what you wrote
|
| 163 |
+
|
| 164 |
+
```bash
|
| 165 |
+
nvcc -arch=sm_90a -cubin -o /dev/null probe.cu # does it assemble?
|
| 166 |
+
cuobjdump -sass kernel.cubin | grep -E "HMMA|QGMMA|LDL|STL"
|
| 167 |
+
```
|
| 168 |
+
`LDL`/`STL` in the SASS means registers spilled. Zero `HMMA`/`QGMMA` where you expected tensor cores
|
| 169 |
+
means the MMA never issued — the commonest cause of a "why is my kernel at 5% of peak".
|
agent/ref/triton.md
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Triton reference
|
| 2 |
+
|
| 3 |
+
Verified against **Triton 3.6.0 / torch 2.11 / CUDA 12.8** — the versions in the task containers. The
|
| 4 |
+
API surface below was enumerated by introspection and the kernels were run on an H200.
|
| 5 |
+
|
| 6 |
+
## What exists in 3.6
|
| 7 |
+
|
| 8 |
+
| group | available |
|
| 9 |
+
|---|---|
|
| 10 |
+
| core | `dot`, `load`, `store`, `arange`, `zeros`, `full`, `where`, `sum`, `max`, `min`, `reduce`, `associative_scan`, `cumsum`, `sort`, `trans`, `permute`, `reshape`, `expand_dims`, `broadcast_to`, `split`, `join`, `interleave` |
|
| 11 |
+
| math | `exp`, `exp2`, `log`, `log2`, `sqrt`, `rsqrt`, `sigmoid`, `softmax`, `erf`, `sin`, `fma`, `maximum`, `minimum`, `clamp`, `abs`, `floor`, `ceil` |
|
| 12 |
+
| precision | `dot_scaled`, `cast`, `inline_asm_elementwise` |
|
| 13 |
+
| memory | `make_block_ptr`, `advance`, `atomic_add`, `atomic_cas`, `atomic_xchg`, `atomic_max`, `make_tensor_descriptor`, `load_tensor_descriptor`, `store_tensor_descriptor` |
|
| 14 |
+
| program | `program_id`, `num_programs`, `static_assert`, `static_print`, `device_print`, `assume`, `range`, `multiple_of`, `max_contiguous` |
|
| 15 |
+
| random | `rand`, `randn`, `randint`, `philox` |
|
| 16 |
+
|
| 17 |
+
Top level: `triton.jit`, `triton.autotune`, `triton.heuristics`, `triton.Config`, `triton.cdiv`,
|
| 18 |
+
`triton.next_power_of_2`, `triton.set_allocator`.
|
| 19 |
+
|
| 20 |
+
Cast with the **method** form, `x.to(tl.float32)` — there is no `tl.to`.
|
| 21 |
+
|
| 22 |
+
## Signatures worth knowing exactly
|
| 23 |
+
|
| 24 |
+
```python
|
| 25 |
+
tl.load(pointer, mask=None, other=None, boundary_check=(), padding_option='',
|
| 26 |
+
cache_modifier='', eviction_policy='', volatile=False)
|
| 27 |
+
|
| 28 |
+
tl.dot(input, other, acc=None, input_precision=None, allow_tf32=None,
|
| 29 |
+
max_num_imprecise_acc=None, out_dtype=tl.float32)
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
`tl.dot(a, b, acc)` accumulates into `acc` — pass it rather than writing `acc += tl.dot(a, b)`, which
|
| 33 |
+
materialises a temporary. `out_dtype=tl.float32` is the default and is what you want; fp16/bf16
|
| 34 |
+
accumulation drifts.
|
| 35 |
+
|
| 36 |
+
## A gotcha that costs a compile cycle — measured
|
| 37 |
+
|
| 38 |
+
`cache_modifier` and `eviction_policy` are accepted by Triton but **rejected by ptxas in combination**:
|
| 39 |
+
|
| 40 |
+
| `cache_modifier` | `eviction_policy` | result |
|
| 41 |
+
|---|---|---|
|
| 42 |
+
| none | none / `evict_first` / `evict_last` | ok |
|
| 43 |
+
| `.ca` | none | ok |
|
| 44 |
+
| `.ca` | `evict_first` / `evict_last` | **PTXAS error** |
|
| 45 |
+
| `.cg` | none | ok |
|
| 46 |
+
| `.cg` | `evict_first` / `evict_last` | **PTXAS error** |
|
| 47 |
+
| `.cs` | anything | **Triton CompilationError** |
|
| 48 |
+
|
| 49 |
+
`ptxas` says *"Modifier '.evict_first' cannot be combined with modifier '.cg'"*. Use one or the other,
|
| 50 |
+
never both, and do not use `.cs` at all in this version.
|
| 51 |
+
|
| 52 |
+
## The launch knobs
|
| 53 |
+
|
| 54 |
+
```python
|
| 55 |
+
kernel[grid](args..., BLOCK=128, num_warps=8, num_stages=4)
|
| 56 |
+
```
|
| 57 |
+
- **`num_stages`** — depth of the software pipeline in a `for` loop over K. This is where `cp.async`
|
| 58 |
+
double buffering comes from; 3-5 is typical. Too many and you run out of shared memory.
|
| 59 |
+
- **`num_warps`** — 4 or 8 for most kernels. 8 for big `tl.dot` tiles.
|
| 60 |
+
- Autotune over them and **cache the winner** per shape class:
|
| 61 |
+
|
| 62 |
+
```python
|
| 63 |
+
@triton.autotune(
|
| 64 |
+
configs=[triton.Config({'BM':128,'BN':128,'BK':64}, num_warps=8, num_stages=4),
|
| 65 |
+
triton.Config({'BM':64, 'BN':128,'BK':64}, num_warps=4, num_stages=5)],
|
| 66 |
+
key=['M','N','K']) # re-tunes when these change
|
| 67 |
+
@triton.jit
|
| 68 |
+
def kernel(...): ...
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
## Idioms
|
| 72 |
+
|
| 73 |
+
**Masked load/store** — always, unless the shape is guaranteed divisible:
|
| 74 |
+
```python
|
| 75 |
+
off = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
|
| 76 |
+
m = off < N
|
| 77 |
+
x = tl.load(X + off, mask=m, other=0.0)
|
| 78 |
+
```
|
| 79 |
+
`other=0.0` matters for reductions: the identity must not perturb the result (use `-inf` for a max).
|
| 80 |
+
|
| 81 |
+
**Block pointers** — let Triton reason about contiguity instead of raw arithmetic:
|
| 82 |
+
```python
|
| 83 |
+
p = tl.make_block_ptr(base=A, shape=(M, K), strides=(K, 1), offsets=(pid*BM, 0),
|
| 84 |
+
block_shape=(BM, BK), order=(1, 0))
|
| 85 |
+
a = tl.load(p, boundary_check=(0, 1))
|
| 86 |
+
p = tl.advance(p, (0, BK))
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
**TMA (Hopper)** — `make_tensor_descriptor` / `load_tensor_descriptor` / `store_tensor_descriptor` are
|
| 90 |
+
present in 3.6. This is how you get hardware descriptor copies without dropping to CUDA.
|
| 91 |
+
|
| 92 |
+
**Online softmax** — the running-max reformulation, in Triton:
|
| 93 |
+
```python
|
| 94 |
+
m_new = tl.maximum(m, tl.max(s, 1))
|
| 95 |
+
alpha = tl.exp2((m - m_new) * 1.4426950408889634)
|
| 96 |
+
acc = acc * alpha[:, None] + tl.dot(p, v)
|
| 97 |
+
```
|
| 98 |
+
Use `exp2` rather than `exp`; it maps to `ex2.approx.f32`, one instruction.
|
| 99 |
+
|
| 100 |
+
**`tl.dot_scaled`** — block-scaled MXFP4/MXFP8 matmul without unpacking scales by hand.
|
| 101 |
+
|
| 102 |
+
**Compile-time specialisation** — mark everything you can `tl.constexpr`, and help the compiler:
|
| 103 |
+
```python
|
| 104 |
+
tl.assume(stride_am > 0)
|
| 105 |
+
tl.multiple_of(off, 16)
|
| 106 |
+
tl.max_contiguous(off, BLOCK)
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
## When Triton is the wrong tool
|
| 110 |
+
|
| 111 |
+
Triton chooses layouts and schedules for you. That is why it is fast to write and why it caps out. Drop
|
| 112 |
+
to CUDA/CuTe when you need:
|
| 113 |
+
|
| 114 |
+
- an exact MMA fragment layout, or `wgmma` with a specific descriptor
|
| 115 |
+
- warp specialisation with `setmaxnreg` register reallocation
|
| 116 |
+
- a persistent kernel with a grid-wide barrier and precise co-residency control
|
| 117 |
+
- TMA choreography more intricate than descriptor load/store
|
| 118 |
+
|
| 119 |
+
See `toolchain.md` for the decision table.
|
| 120 |
+
|
| 121 |
+
## Reading what Triton generated
|
| 122 |
+
|
| 123 |
+
```bash
|
| 124 |
+
TRITON_KERNEL_DUMP=1 TRITON_DUMP_DIR=/tmp/d TRITON_ALWAYS_COMPILE=1 python3 k.py
|
| 125 |
+
# then: /tmp/d/*/k.ttgir (layouts Triton chose) k.ptx (what it emitted) k.cubin
|
| 126 |
+
```
|
| 127 |
+
`tools/dump_ir.sh triton <cmd>` does this and points you at the artifacts. Read the **`.ttgir`** to see
|
| 128 |
+
the layouts — that is where Triton's decisions are visible, and where you learn whether it picked the
|
| 129 |
+
swizzle you assumed.
|
agent/tools/check_toolchain.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""What does THIS machine actually support? Re-derives the tables in ref/ by compiling.
|
| 2 |
+
|
| 3 |
+
python3 check_toolchain.py [sm_90a]
|
| 4 |
+
|
| 5 |
+
The reference docs were verified on sm_90a / CUDA 12.8. On a different GPU or toolkit some rows change
|
| 6 |
+
-- tcgen05 appears on Blackwell, wgmma disappears below Hopper. Run this instead of trusting the tables.
|
| 7 |
+
"""
|
| 8 |
+
import json, os, subprocess, sys, tempfile
|
| 9 |
+
|
| 10 |
+
ARCH = sys.argv[1] if len(sys.argv) > 1 else None
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _arch():
|
| 14 |
+
if ARCH:
|
| 15 |
+
return ARCH
|
| 16 |
+
try:
|
| 17 |
+
import torch
|
| 18 |
+
cc = torch.cuda.get_device_capability(0)
|
| 19 |
+
a = f"sm_{cc[0]}{cc[1]}"
|
| 20 |
+
return a + "a" if cc[0] >= 9 else a # the 'a' target enables wgmma/TMA/setmaxnreg
|
| 21 |
+
except Exception:
|
| 22 |
+
return "sm_90a"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
PTX = [
|
| 26 |
+
("ld.global.nc", r'asm volatile("ld.global.nc.f32 %0, [%1];" : "=f"(f) : "l"(pf));', ""),
|
| 27 |
+
("ld.global.L2::128B", r'asm volatile("ld.global.L2::128B.f32 %0, [%1];" : "=f"(f) : "l"(pf));', ""),
|
| 28 |
+
("ld.global.v4.f32", r'asm volatile("ld.global.v4.f32 {%0,%1,%2,%3}, [%4];" : "=f"(v0),"=f"(v1),"=f"(v2),"=f"(v3) : "l"(pf));', "float v0,v1,v2,v3;"),
|
| 29 |
+
("cp.async.cg", r'asm volatile("cp.async.cg.shared.global [%0], [%1], 16;" :: "r"(smem), "l"(pf));', ""),
|
| 30 |
+
("cp.async.bulk.tensor (TMA)", r'asm volatile("cp.async.bulk.tensor.2d.shared::cluster.global.tile.mbarrier::complete_tx::bytes [%0], [%1, {%2, %3}], [%4];" :: "r"(smem), "l"(pf), "r"(x), "r"(y), "r"(bar));', ""),
|
| 31 |
+
("mbarrier.arrive.expect_tx", r'asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 %0, [%1], %2;" : "=l"(l) : "r"(smem), "r"(x));', ""),
|
| 32 |
+
("fence.proxy.async", r'asm volatile("fence.proxy.async.shared::cta;");', ""),
|
| 33 |
+
("barrier.cluster", r'asm volatile("barrier.cluster.arrive;"); asm volatile("barrier.cluster.wait;");', ""),
|
| 34 |
+
("mma.sync m16n8k16 bf16", r'asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};" : "+f"(v0),"+f"(v1),"+f"(v2),"+f"(v3) : "r"(a0),"r"(a1),"r"(a2),"r"(a3),"r"(b0),"r"(b1));', "float v0,v1,v2,v3; unsigned a0=0,a1=0,a2=0,a3=0,b0=0,b1=0;"),
|
| 35 |
+
("mma.sync m16n8k32 fp8", r'asm volatile("mma.sync.aligned.m16n8k32.row.col.f32.e4m3.e4m3.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};" : "+f"(v0),"+f"(v1),"+f"(v2),"+f"(v3) : "r"(a0),"r"(a1),"r"(a2),"r"(a3),"r"(b0),"r"(b1));', "float v0,v1,v2,v3; unsigned a0=0,a1=0,a2=0,a3=0,b0=0,b1=0;"),
|
| 36 |
+
("wgmma.fence/commit/wait", r'asm volatile("wgmma.fence.sync.aligned;"); asm volatile("wgmma.commit_group.sync.aligned;"); asm volatile("wgmma.wait_group.sync.aligned 0;");', ""),
|
| 37 |
+
("ldmatrix .x4", r'asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];" : "=r"(a0),"=r"(a1),"=r"(a2),"=r"(a3) : "r"(smem));', "unsigned a0,a1,a2,a3;"),
|
| 38 |
+
("stmatrix .x4", r'asm volatile("stmatrix.sync.aligned.m8n8.x4.shared.b16 [%0], {%1,%2,%3,%4};" :: "r"(smem),"r"(a0),"r"(a1),"r"(a2),"r"(a3));', "unsigned a0=0,a1=0,a2=0,a3=0;"),
|
| 39 |
+
("redux.sync.add", r'asm volatile("redux.sync.add.u32 %0, %1, -1;" : "=r"(x) : "r"(y));', ""),
|
| 40 |
+
("elect.sync", r'asm volatile("{.reg .pred p; .reg .b32 r; elect.sync r|p, -1; }");', ""),
|
| 41 |
+
("setmaxnreg", r'asm volatile("setmaxnreg.inc.sync.aligned.u32 232;");', ""),
|
| 42 |
+
("griddepcontrol", r'asm volatile("griddepcontrol.wait;");', ""),
|
| 43 |
+
("cvt e4m3x2", r'asm volatile("cvt.rn.satfinite.e4m3x2.f32 %0, %1, %2;" : "=h"(h) : "f"(f), "f"(f));', ""),
|
| 44 |
+
("ex2.approx.f32", r'asm volatile("ex2.approx.f32 %0, %1;" : "=f"(f) : "f"(f));', ""),
|
| 45 |
+
("red.global.add.f32", r'asm volatile("red.global.add.f32 [%0], %1;" :: "l"(pf), "f"(f));', ""),
|
| 46 |
+
("tcgen05 (Blackwell)", r'asm volatile("tcgen05.fence::before_thread_sync;");', ""),
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
TPL = """#include <cuda_fp16.h>
|
| 50 |
+
__global__ void k(float* pf, unsigned* pu) {{
|
| 51 |
+
float f = 0.f; unsigned x = 0, y = 0, smem = 0, bar = 0; unsigned short h = 0;
|
| 52 |
+
unsigned long long l = 0;
|
| 53 |
+
{decls}
|
| 54 |
+
{body}
|
| 55 |
+
if (f == 1.f) pf[0] = f; pu[0] = x + h;
|
| 56 |
+
}}
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def compile_ok(src, arch, extra=()):
|
| 61 |
+
with tempfile.NamedTemporaryFile("w", suffix=".cu", delete=False) as fh:
|
| 62 |
+
fh.write(src); p = fh.name
|
| 63 |
+
try:
|
| 64 |
+
r = subprocess.run(["nvcc", f"-arch={arch}", "-std=c++17", *extra, "-cubin", "-o", os.devnull, p],
|
| 65 |
+
capture_output=True, text=True)
|
| 66 |
+
return r.returncode == 0
|
| 67 |
+
finally:
|
| 68 |
+
os.unlink(p)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def wgmma_acc(arch):
|
| 72 |
+
"""wgmma.m64nNk16.f32 needs N/2 accumulator registers per thread -- confirm on this target."""
|
| 73 |
+
out = {}
|
| 74 |
+
for N in (8, 16, 64, 128, 256):
|
| 75 |
+
n = N // 2
|
| 76 |
+
regs = ",".join(f"%{i}" for i in range(n))
|
| 77 |
+
outs = ",".join(f'"+f"(d[{i}])' for i in range(n))
|
| 78 |
+
src = f"""__global__ void k(float* o) {{
|
| 79 |
+
unsigned long long da=0, db=0; float d[{n}];
|
| 80 |
+
#pragma unroll
|
| 81 |
+
for (int i=0;i<{n};++i) d[i]=0.f;
|
| 82 |
+
asm volatile("wgmma.fence.sync.aligned;");
|
| 83 |
+
asm volatile("wgmma.mma_async.sync.aligned.m64n{N}k16.f32.bf16.bf16 {{{regs}}}, %{n}, %{n+1}, 1,1,1,0,0;"
|
| 84 |
+
: {outs} : "l"(da), "l"(db));
|
| 85 |
+
asm volatile("wgmma.commit_group.sync.aligned;");
|
| 86 |
+
for (int i=0;i<{n};++i) o[i]=d[i];
|
| 87 |
+
}}"""
|
| 88 |
+
out[f"m64n{N}k16"] = (n, compile_ok(src, arch))
|
| 89 |
+
return out
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def triton_report():
|
| 93 |
+
try:
|
| 94 |
+
import torch, triton, triton.language as tl
|
| 95 |
+
except Exception as e:
|
| 96 |
+
return {"error": f"{type(e).__name__}: {e}"}
|
| 97 |
+
names = ["dot", "dot_scaled", "make_block_ptr", "make_tensor_descriptor",
|
| 98 |
+
"load_tensor_descriptor", "store_tensor_descriptor", "associative_scan",
|
| 99 |
+
"inline_asm_elementwise", "assume", "range", "sort", "histogram", "gather"]
|
| 100 |
+
rep = {"version": triton.__version__,
|
| 101 |
+
"present": [n for n in names if hasattr(tl, n)],
|
| 102 |
+
"absent": [n for n in names if not hasattr(tl, n)]}
|
| 103 |
+
# the cache_modifier x eviction_policy combination trap
|
| 104 |
+
import itertools
|
| 105 |
+
@triton.jit
|
| 106 |
+
def _k(X, Y, N, BLOCK: tl.constexpr, CM: tl.constexpr, EP: tl.constexpr):
|
| 107 |
+
o = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
|
| 108 |
+
m = o < N
|
| 109 |
+
tl.store(Y + o, tl.load(X + o, mask=m, other=0.0, cache_modifier=CM, eviction_policy=EP), mask=m)
|
| 110 |
+
x = torch.randn(4096, device="cuda"); y = torch.empty_like(x)
|
| 111 |
+
combos = {}
|
| 112 |
+
# a rejected combination makes Triton dump the whole failing PTX to the console; the point here is
|
| 113 |
+
# the verdict, not the dump, so silence both fds around the probe.
|
| 114 |
+
import contextlib, io
|
| 115 |
+
for cm, ep in itertools.product(["", ".ca", ".cg", ".cs"], ["", "evict_first", "evict_last"]):
|
| 116 |
+
buf = io.StringIO()
|
| 117 |
+
devnull = os.open(os.devnull, os.O_WRONLY)
|
| 118 |
+
saved = os.dup(1), os.dup(2)
|
| 119 |
+
try:
|
| 120 |
+
# flush FIRST: piped stdout is block-buffered, and anything still pending would other-
|
| 121 |
+
# wise be flushed into /dev/null once fd 1 is redirected -- silently eating the report.
|
| 122 |
+
sys.stdout.flush(); sys.stderr.flush()
|
| 123 |
+
os.dup2(devnull, 1); os.dup2(devnull, 2)
|
| 124 |
+
with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):
|
| 125 |
+
try:
|
| 126 |
+
_k[(4,)](x, y, x.numel(), BLOCK=1024, CM=cm, EP=ep); torch.cuda.synchronize()
|
| 127 |
+
v = "ok"
|
| 128 |
+
except Exception as e:
|
| 129 |
+
v = "PTXAS" if "ptxas" in str(e).lower() else type(e).__name__
|
| 130 |
+
finally:
|
| 131 |
+
sys.stdout.flush(); sys.stderr.flush()
|
| 132 |
+
os.dup2(saved[0], 1); os.dup2(saved[1], 2)
|
| 133 |
+
os.close(devnull); os.close(saved[0]); os.close(saved[1])
|
| 134 |
+
combos[f"{cm or 'none'}|{ep or 'none'}"] = v
|
| 135 |
+
rep["load_modifier_combos"] = combos
|
| 136 |
+
return rep
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def main():
|
| 140 |
+
arch = _arch()
|
| 141 |
+
nvcc = subprocess.run(["nvcc", "--version"], capture_output=True, text=True).stdout.strip().splitlines()
|
| 142 |
+
print(f"target {arch} {nvcc[-1] if nvcc else 'nvcc not found'}\n")
|
| 143 |
+
|
| 144 |
+
print("PTX instructions")
|
| 145 |
+
res = {}
|
| 146 |
+
for label, body, decls in PTX:
|
| 147 |
+
ok = compile_ok(TPL.format(body=body, decls=decls), arch)
|
| 148 |
+
res[label] = ok
|
| 149 |
+
print(f" {'ok ' if ok else 'NO '} {label}")
|
| 150 |
+
|
| 151 |
+
print("\nwgmma accumulator registers per thread (N/2 expected)")
|
| 152 |
+
for shape, (n, ok) in wgmma_acc(arch).items():
|
| 153 |
+
print(f" {'ok ' if ok else 'NO '} {shape:12s} {n} regs")
|
| 154 |
+
|
| 155 |
+
print("\nCuTe / CUTLASS")
|
| 156 |
+
for inc in ("/opt/pytorch/third_party/cutlass/include", "/usr/local/cutlass/include"):
|
| 157 |
+
if os.path.isdir(inc + "/cute"):
|
| 158 |
+
ok = compile_ok('#include <cute/tensor.hpp>\n__global__ void k(){}', arch,
|
| 159 |
+
(f"-I{inc}", "--expt-relaxed-constexpr"))
|
| 160 |
+
print(f" {'ok ' if ok else 'NO '} headers at {inc}")
|
| 161 |
+
break
|
| 162 |
+
else:
|
| 163 |
+
print(" -- no cute headers found")
|
| 164 |
+
|
| 165 |
+
print("\nTriton")
|
| 166 |
+
t = triton_report()
|
| 167 |
+
if "error" in t:
|
| 168 |
+
print(" " + t["error"])
|
| 169 |
+
else:
|
| 170 |
+
print(f" version {t['version']}")
|
| 171 |
+
print(f" present: {', '.join(t['present'])}")
|
| 172 |
+
if t["absent"]:
|
| 173 |
+
print(f" absent : {', '.join(t['absent'])}")
|
| 174 |
+
bad = [k for k, v in t["load_modifier_combos"].items() if v != "ok"]
|
| 175 |
+
print(f" tl.load cache_modifier|eviction_policy combos that FAIL: {', '.join(bad) or 'none'}")
|
| 176 |
+
print("\n(ref/*.md was verified on sm_90a / CUDA 12.8; anything above that disagrees wins.)")
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
if __name__ == "__main__":
|
| 180 |
+
main()
|