Persistent and warp-specialised kernels, and a tour of CUTLASS and CuTe
The two ideas behind today's fastest GPU kernels, and the library that packages them. Persistent kernels launch one block per SM and loop over the work. Warp-specialised kernels split a block into a producer warp that only moves data and consumer warps that only compute, meeting at a ring of shared-memory buffers. Write both in one program, then read CUTLASS 4: CuTe layouts, tensors and swizzles (run on a CPU), tiled MMA and copy, and Hopper's cooperative and ping-pong kernel schedules.
By Sandip Maity, Applied AI Engineer
Key takeaways
- A persistent kernel launches about one block per SM and loops over tiles, paying launch and prologue costs once and keeping per-block state (buffers, barriers) alive across tiles.
- Warp specialisation gives warps different jobs: a producer warp issues copies into a ring of stages while consumer warps compute. They meet only at acquire, commit, wait and release points.
- Consumers that must synchronise among themselves use a named barrier, because __syncthreads() would also wait for the producer.
- A CuTe layout is a shape and a stride: a function from coordinates to offsets. Tiling, thread mapping and swizzles are all compositions and divisions of layouts.
- CUTLASS's Hopper GEMMs are exactly this pattern at scale: a TMA producer warp group, tensor-core consumer warp groups, a persistent tile scheduler, and cooperative or ping-pong schedules.
Goal: understand persistent and warp-specialised kernels by writing one, then read CUTLASS 4 and CuTe well enough to find your way around a modern GEMM.
You need: async copies, TMA and pipelining and warp reductions. An Ampere or newer GPU to run the kernel; the CuTe demo runs on any machine with nvcc (no GPU needed). The code is in gpu_kernels/cuda/ in the companion repository; for CuTe, clone CUTLASS (header only): git clone --depth 1 --branch v4.8.1 https://github.com/NVIDIA/cutlass.git.
Honest limits. We compiled the warp-specialised kernel with nvcc 12.8 for sm_80 and checked its machine code, but have not run it on a GPU, so there are no timings; the program checks its own results. The CuTe demo was compiled and run on a CPU, and its output below is from that run (CUTLASS v4.8.1). CUTLASS's own GEMMs are far more complex than the kernel here; this lesson gives you the map, not the whole territory.
#Persistent kernels
The usual launch is one block per piece of work: one block per row, per tile, per head. When the pieces are small and many, that has costs: every block pays its prologue (setting up indices, barriers, shared memory), and the hardware has to schedule thousands of short blocks.
A persistent kernel launches about as many blocks as the GPU can run at once (one per SM here) and each block loops:
for (tile = blockIdx.x; tile < num_tiles; tile += gridDim.x) { ... }Each block sets up once and processes many tiles. This matters most when the per-block setup is expensive, as it is for a pipeline with barriers and a ring of stages. Real kernels often replace the fixed stride with a tile scheduler that hands out tiles in an order that reuses L2 cache, or dynamically with an atomic counter so that faster blocks take more work.
#Warp specialisation
In the pipelined matmul of the last lesson, every thread both copied and computed. Warp specialisation gives warps different jobs:
- a producer warp only issues copies into a ring of shared-memory stages;
- consumer warps only compute on full stages.
They meet at four points per stage: the producer acquires an empty stage and commits its copies; a consumer waits for a full stage and releases it when done. CUDA's cuda::pipeline with producer and consumer roles provides exactly these four calls.
flowchart LR P[Producer warp<br/>acquire, copy, commit] --> S0[stage 0] P --> S1[stage 1] P --> S2[stage 2] P --> S3[stage 3] S0 --> C[Consumer warps<br/>wait, compute, release] S1 --> C S2 --> C S3 --> C C -.release.-> P
Why bother, when every thread could do both? Because the roles want different resources. On Hopper, the producer needs almost no registers (one thread issues TMA copies), while tensor-core consumers need many; CUDA lets warp groups give up or claim registers at run time (setmaxnreg) so the consumers get more. And with the producer always running ahead, the consumers never wait for an address calculation or a load instruction of their own.
#A persistent, warp-specialised row sum
The task is deliberately simple, so the structure stands out: sum each row of a 16,384 × 4,096 float matrix. rowsum_simple uses one block per row. rowsum_ws launches one block per SM; in each block, warp 0 is the producer and warps 1 to 4 are consumers, with a four-stage ring of rows in shared memory.
gpu_kernels/cuda/warp_specialized_rowsum.cu · MIT licensed, on GitHub
// A persistent, warp-specialised kernel: one producer warp copies, four consumer warps compute.
//
// nvcc -O3 -std=c++17 -arch=sm_80 warp_specialized_rowsum.cu -o ws_rowsum && ./ws_rowsum
//
// Task: y[r] = sum of row r of a [ROWS x COLS] float32 matrix (memory bound, like many
// inference kernels). Two versions:
// rowsum_simple: one block per row; every thread loads and adds, then a block reduction.
// rowsum_ws: a persistent grid (one block per SM) loops over rows. In each block,
// warp 0 is the producer: it copies the next rows into a ring of STAGES
// shared-memory buffers with cp.async. Warps 1-4 are consumers: they wait
// for a full buffer, reduce it and hand the buffer back. The two roles meet
// only at the pipeline's acquire/commit/wait/release points, so loading
// row i+3 overlaps with reducing row i.
// Consumers synchronise among themselves with a named barrier (bar.sync 1, 128), because a
// __syncthreads() would also wait for the producer warp, which is busy elsewhere.
// This is the structure (much simplified) of Hopper GEMM kernels such as CUTLASS's
// warp-specialised schedules, where the producer uses TMA and the consumers use tensor cores.
#include <cooperative_groups.h>
#include <cuda/pipeline>
#include <cstdio>
#include <cstdlib>
#include <vector>
namespace cg = cooperative_groups;
constexpr int ROWS = 16384, COLS = 4096; // 256 MiB of float32
constexpr int STAGES = 4;
constexpr int CONSUMERS = 128; // four consumer warps
constexpr int THREADS = 32 + CONSUMERS; // plus one producer warp
__global__ void rowsum_simple(const float* __restrict__ x, float* __restrict__ y) {
__shared__ float red[32];
const float* row = x + (size_t)blockIdx.x * COLS;
float s = 0.f;
for (int i = threadIdx.x; i < COLS; i += blockDim.x) s += row[i];
for (int o = 16; o > 0; o >>= 1) s += __shfl_xor_sync(0xffffffff, s, o);
if ((threadIdx.x & 31) == 0) red[threadIdx.x >> 5] = s;
__syncthreads();
if (threadIdx.x < 32) {
s = threadIdx.x < blockDim.x / 32 ? red[threadIdx.x] : 0.f;
for (int o = 16; o > 0; o >>= 1) s += __shfl_xor_sync(0xffffffff, s, o);
if (threadIdx.x == 0) y[blockIdx.x] = s;
}
}
__device__ inline void consumer_barrier() { asm volatile("bar.sync 1, %0;" ::"n"(CONSUMERS)); }
__global__ void rowsum_ws(const float* __restrict__ x, float* __restrict__ y) {
extern __shared__ __align__(16) float buf[]; // STAGES x COLS floats
__shared__ float red[CONSUMERS / 32];
#pragma nv_diag_suppress static_var_with_dynamic_init // make_pipeline initialises it
__shared__ cuda::pipeline_shared_state<cuda::thread_scope_block, STAGES> state;
auto block = cg::this_thread_block();
const bool producer = threadIdx.x < 32;
auto pipe = cuda::make_pipeline(block, &state, producer ? cuda::pipeline_role::producer
: cuda::pipeline_role::consumer);
// Persistent loop: this block handles rows blockIdx.x, blockIdx.x + gridDim.x, ...
// Producer and consumers walk the same sequence, so iteration i always uses stage i % STAGES.
int i = 0;
for (int r = blockIdx.x; r < ROWS; r += gridDim.x, ++i) {
float* stage = buf + (size_t)(i % STAGES) * COLS;
if (producer) {
pipe.producer_acquire(); // wait until this stage is free
constexpr int PER_LANE = COLS / 32; // each lane copies a contiguous slice
const int lane = threadIdx.x;
cuda::memcpy_async(stage + lane * PER_LANE, x + (size_t)r * COLS + lane * PER_LANE,
cuda::aligned_size_t<16>(PER_LANE * sizeof(float)), pipe);
pipe.producer_commit();
} else {
pipe.consumer_wait(); // wait until the stage is full
const int c = threadIdx.x - 32;
float s = 0.f;
for (int k = c; k < COLS; k += CONSUMERS) s += stage[k];
pipe.consumer_release(); // the producer may refill it now
for (int o = 16; o > 0; o >>= 1) s += __shfl_xor_sync(0xffffffff, s, o);
if ((c & 31) == 0) red[c >> 5] = s;
consumer_barrier(); // consumers only
if (c == 0) y[r] = red[0] + red[1] + red[2] + red[3];
consumer_barrier(); // red is reused next iteration
}
}
}
#define CHECK(x) do { cudaError_t e = (x); if (e != cudaSuccess) { \
printf("CUDA error %s at %s:%d\n", cudaGetErrorString(e), __FILE__, __LINE__); exit(1); } } while (0)
int main() {
std::vector<float> hx((size_t)ROWS * COLS), hy(ROWS), ref(ROWS);
srand(0);
for (auto& v : hx) v = rand() / (float)RAND_MAX;
for (int r = 0; r < ROWS; ++r) {
double s = 0; for (int k = 0; k < COLS; ++k) s += hx[(size_t)r * COLS + k]; ref[r] = (float)s;
}
float *x, *y;
CHECK(cudaMalloc(&x, hx.size() * 4)); CHECK(cudaMalloc(&y, ROWS * 4));
CHECK(cudaMemcpy(x, hx.data(), hx.size() * 4, cudaMemcpyHostToDevice));
int sms; CHECK(cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, 0));
const size_t smem = (size_t)STAGES * COLS * sizeof(float); // 64 KiB: needs the opt-in below
CHECK(cudaFuncSetAttribute(rowsum_ws, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem));
cudaEvent_t e0, e1; CHECK(cudaEventCreate(&e0)); CHECK(cudaEventCreate(&e1));
const char* names[2] = {"rowsum_simple", "rowsum_ws"};
for (int which = 0; which < 2; ++which) {
auto run = [&] {
if (which == 0) rowsum_simple<<<ROWS, 256>>>(x, y);
else rowsum_ws<<<sms, THREADS, smem>>>(x, y);
};
run(); CHECK(cudaGetLastError()); CHECK(cudaDeviceSynchronize());
CHECK(cudaEventRecord(e0));
for (int k = 0; k < 20; ++k) run();
CHECK(cudaEventRecord(e1)); CHECK(cudaEventSynchronize(e1));
float ms; CHECK(cudaEventElapsedTime(&ms, e0, e1)); ms /= 20;
CHECK(cudaMemcpy(hy.data(), y, ROWS * 4, cudaMemcpyDeviceToHost));
double max_rel = 0;
for (int r = 0; r < ROWS; ++r) max_rel = fmax(max_rel, fabs(hy[r] - ref[r]) / fabs(ref[r]));
printf("%-14s %7.3f ms %6.0f GB/s max relative error %.1e (grid %d)\n", names[which], ms,
hx.size() * 4.0 / ms / 1e6, max_rel, which ? sms : ROWS);
}
return 0;
}The rest is Pro
Keep reading this full lab
Pro unlocks this full lab, including 1 animated diagram, every advanced lesson, the hands-on labs and completion certificates.
One year
$25
365 days, no auto-renewal
Lifetime Best value
$75
pay once, keep it forever
7-day refund, no questions asked. One payment, no auto-renewal.Compare plansHave a licence key?
Not ready? Keep learning free
Not ready? Take the free 5-day email course
One short email a day for five days, each built on a free lesson, then the occasional new lesson or offer. Unsubscribe in one click.
Still to come in this lab
- A tour of CUTLASS and CuTe
- What you can now do
- Common mistakes
- Exercise
- Going deeper
You will be able to answer
- Why launch a persistent kernel with about one block per SM instead of one block per tile?
- In the warp-specialised kernel, why do the consumer warps synchronise with bar.sync 1, 128 instead of __syncthreads()?
- A CuTe layout is printed as (_4,_8):(_8,_1). Which element is at offset 10?
- What distinguishes CUTLASS's ping-pong Hopper schedule from the cooperative one?