Phase 06/Writing your own kernels/CUTLASS, CuTe and tensor-core programming
PHASE 06 · Writing your own kernels

CUTLASS, CuTe and tensor-core programming

0%
14 h7 subtopics3 lessons · 3 required
In plain English

Modern GPUs contain special circuits called tensor cores that multiply small blocks of numbers in one step, dozens of times faster than doing the arithmetic one number at a time. Using them well is like switching from hand-stitching to an industrial loom. The loom is fast, but it only accepts thread fed in exactly the right pattern, so most of the skill is in laying the data out and feeding it in time. CUTLASS is NVIDIA's open library of templates for doing that, and CuTe is its language for describing how a block of numbers is arranged in memory. In this topic you write a small tensor-core kernel yourself, build and run a CUTLASS example, and read a state-of-the-art CUTLASS kernel for the newest GPUs so you can recognise the parts that make it fast.

Why it matters

GEMM and attention are the two kernels that decide inference cost, and on Hopper and Blackwell they are only fast through tensor-core instructions (mma, wgmma), asynchronous copies (TMA) and the layouts CUTLASS encodes. FP8 GEMM, the main lever for cheaper decode, lives entirely in this world. Kernel roles at xAI, Baseten, CoreWeave and Thinking Machines all name CUTLASS or CuTe explicitly.

Hiring signal

xAI asks engineers to tune GEMM and attention kernels using CUTLASS, Tensor Cores and Nsight; Perplexity is porting its in-house CUDA kernels to the CuTe DSL so they run on GB200 and future racks; Liquid AI lists CUTLASS experience and tensor-core utilisation strategies as the preferred skill for its GPU performance engineer.

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Cohere, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Explain what a tensor core computes per instruction (mma shapes, input and accumulator types) and how a warp cooperates to feed it.
  • Write a WMMA-based fp16 GEMM kernel callable from PyTorch and measure it against cuBLAS.
  • Describe the CUTLASS 3.x hierarchy (kernel, collective mainloop, tiled MMA, tiled copy) and how CuTe layouts describe tiles and swizzles.
  • Build and run a CUTLASS example on a Turing GPU and read a Hopper warp-specialised GEMM example, identifying TMA and wgmma usage.
  • Explain FP8 GEMM scaling (per-tensor, per-block) and why the epilogue, not the MMA, is where accuracy is decided.

Key concepts

Tensor core and mma.sync
A warp-level instruction computing a small matrix product (for example 16x8x16 fp16 into fp32) in a few cycles; the only path to peak FLOPs.
WMMA API
The portable CUDA C++ warp matrix API (nvcuda::wmma) that wraps mma for 16x16x16 fragments; available since Volta, works on a T4.
wgmma
Hopper's warpgroup-level asynchronous MMA that reads operands directly from shared memory and accumulates in registers across 128 threads.
TMA
Tensor Memory Accelerator, Hopper hardware that copies multi-dimensional tiles between global and shared memory asynchronously with one thread issuing the copy.
CuTe layout
A (shape, stride) pair mapping logical coordinates to memory offsets; composable so tiling, partitioning and swizzling are algebra, not index arithmetic.
Swizzle
XOR-based permutation of shared-memory addresses that removes bank conflicts for the access pattern of an MMA fragment.
Warp specialisation
Dedicating producer warps to TMA loads and consumer warpgroups to wgmma so copy and compute overlap through a pipeline of shared-memory stages.
Epilogue
The post-MMA stage that applies scaling, bias, activation, quantisation and writes the output; where FP8 dequantisation and fusion happen.
FP8 block scaling
Storing a scale per tile of weights or activations (for example 128x128) so FP8's 3 or 2 mantissa bits cover the dynamic range; DeepGEMM and Blackwell MXFP formats use this.

Subtopics

  1. 1. Tensor cores from the programmer's view

    Fragment shapes, supported types per generation (Volta fp16 through Blackwell FP4), warp-cooperative loading, why fp32 accumulation is the norm.

  2. 2. A WMMA GEMM by hand

    Shared-memory tiling, loading fragments, mma per k-step, storing accumulators; where it falls short of cuBLAS and why.

  3. 3. CUTLASS 3.x architecture

    Device, kernel, collective mainloop and epilogue layers; dispatch policies per architecture; how a GEMM is assembled from TiledMma and TiledCopy.

  4. 4. CuTe layouts and tiling algebra

    Shape and stride, hierarchical shapes, composition, local_tile and local_partition, swizzle functors; reading a layout printout.

  5. 5. Hopper mainloop with TMA and wgmma

    Producer and consumer warps, mbarrier pipelines, shared-memory stage count, cluster multicast; reading example 48.

  6. 6. FP8 GEMM and the epilogue

    E4M3 and E5M2, per-tensor versus block scaling, fused dequantisation and activation, accuracy checks against bf16; how DeepGEMM structures an FP8 kernel.

  7. 7. Python kernel authoring on NVIDIA

    CuTe DSL and the CUTLASS Python interface, where they sit relative to Triton, and how engines call CUTLASS kernels through custom ops.

Resources

repo
  • CUTLASS repository ↗
    Start with the README, then media/docs for the CuTe documentation.
  • CUTLASS examples directory ↗
    Example 08 (Turing tensor-op GEMM) and example 48 (Hopper warp-specialised GEMM) are used in the lessons.
  • DeepGEMM ↗
    A compact FP8 GEMM library built on CUTLASS/CuTe primitives; the clearest production FP8 reference.
documentation
article

Hands-on lessons

L1

WMMA fp16 GEMM via load_inline versus cuBLAS on a T4

Colab T4 · freenotebook180 minrequired

Goal · A tensor-core GEMM written with the WMMA API, compiled through torch.utils.cpp_extension.load_inline, verified against torch.matmul and benchmarked against it and against a scalar fp32 kernel.

  1. 1On a Colab T4, write a scalar fp32 tiled GEMM kernel (shared-memory tiles of 32x32) with load_inline and verify it for 1024x1024.
  2. 2Write wmma_gemm using nvcuda::wmma fragments of 16x16x16 fp16 with fp32 accumulators; each warp computes a 16x16 output tile, with a block of 4 warps covering 32x32 and a shared-memory staged K loop.
  3. 3Compile with -arch=sm_75 and extra flags -lineinfo; verify against torch.matmul in fp16 at rtol 1e-2 for 256, 1024 and 4096 square sizes, including a non-multiple-of-16 size with padding.
  4. 4Benchmark all three (scalar, wmma, torch.matmul) with CUDA events at 1024, 2048 and 4096; compute TFLOPs as 2*M*N*K divided by time.
  5. 5Dump PTX with --ptx (or cuobjdump on the built extension) and grep for wmma.mma.sync; count the instructions in the inner loop.
  6. 6Increase the warp tile to 32x32 (four fragments per warp) and re-measure; explain the change in a markdown cell using register and shared-memory reuse.
  7. 7Record the fraction of T4 peak (about 65 TFLOPs fp16 tensor core) that each kernel reaches.
Deliverable
A notebook with the three kernels, correctness asserts, the TFLOPs table and the PTX excerpt.
Check
The PTX contains wmma.mma.sync instructions; the wmma kernel is at least 4x faster than the scalar fp32 kernel at 4096 and passes the rtol 1e-2 check for all sizes; the 32x32 warp tile is faster than the 16x16 one.
Fallback
Use a Kaggle T4. Without any GPU, write the wmma kernel anyway, compile to PTX on Colab's CPU runtime with nvcc --ptx if available, and verify the instruction appears; skip the timings.
L2

Build and run a CUTLASS tensor-op example on a T4

Colab T4 · freecli120 minrequired

Goal · CUTLASS built from source for sm_75 in Colab, example 08 (Turing tensor-op GEMM) running and verified, and its throughput compared with your l1 kernel and torch.matmul.

  1. 1In a Colab T4 shell, git clone --depth 1 https://github.com/NVIDIA/cutlass and create a build directory.
  2. 2Configure with cmake -DCUTLASS_NVCC_ARCHS=75 -DCUTLASS_ENABLE_TESTS=OFF -DCUTLASS_UNITY_BUILD_ENABLED=ON and build only the example target with make 08_turing_tensorop_gemm -j2.
  3. 3Run the example binary and confirm it prints that the result passed its reference check; record the problem size it uses.
  4. 4Open examples/08_turing_tensorop_gemm/turing_tensorop_gemm.cu and annotate the template arguments (element types, layouts, threadblock shape, warp shape, instruction shape, stages).
  5. 5Modify the problem size to 4096x4096x4096 and add cudaEvent timing around the GEMM; rebuild and record TFLOPs.
  6. 6Compare with your l1 wmma kernel and torch.matmul from l1 at 4096; write one paragraph on where the gap comes from (pipelining stages, swizzled shared memory, larger warp tiles).
Deliverable
A build log excerpt, the annotated template parameters, and a three-way TFLOPs comparison table.
Check
The example reports a passed verification; the CUTLASS kernel reaches at least 2x the TFLOPs of your l1 wmma kernel at 4096 and at least 60 percent of torch.matmul.
Fallback
If the Colab build runs out of time, build on a Kaggle T4 session; if no GPU is available, run cmake configure only, read the generated kernel instantiation and complete the annotation step without timings.
L3

Read a Hopper warp-specialised GEMM and model CuTe layouts in Python

CPU · your Macreading-code150 minrequired

Goal · An annotated walkthrough of CUTLASS example 48 identifying TMA, wgmma, pipeline stages and the epilogue, plus a 60-line Python model of CuTe layouts that reproduces offsets for tiled and swizzled layouts.

  1. 1In a CUTLASS clone, open examples/48_hopper_warpspecialized_gemm and list the types chosen for the collective mainloop (dispatch policy, tile shape, cluster shape, stage count) and the epilogue.
  2. 2Follow the mainloop type into include/cutlass/gemm/collective and find where TMA descriptors are created and where the producer warp issues copies and the consumer warpgroup issues wgmma; record path:line for each.
  3. 3Find the pipeline barrier type and explain in two sentences how stages are handed from producer to consumer.
  4. 4Read the CuTe layout documentation under media/docs and write cute_layout.py with a Layout class holding nested shapes and strides and an offset(coord) method, including composition of a tile onto a parent layout.
  5. 5Verify your model: Layout (4,8) with strides (8,1) gives offset 19 for coordinate (2,3); Layout (4,8) with strides (1,4) gives offset 14 for the same coordinate; a 2x2 tiling of the row-major layout reproduces the offset table printed in the CuTe documentation.
  6. 6Implement a Swizzle(B=1, M=0, S=1) functor as in the docs and show which pairs of coordinates no longer share a shared-memory bank for a 16-byte-per-row access.
  7. 7Write a one-page note on what CuTe buys over hand-written index math, with reference to a specific line of example 48 that would be unreadable without it.
Deliverable
cutlass-ex48-notes.md with at least 8 path:line references, and cute_layout.py with its assertions.
Check
cute_layout.py assertions pass (offsets 19 and 14 for the two layouts) and the notes name the exact files where TMA copies and wgmma are issued.

Build your own

Build your own tensor-core GEMM

CUDA C++Colab T4 · free~12 h

An fp16 GEMM that climbs from scalar CUDA to WMMA tensor cores to a CUTLASS/CuTe kernel, with an fp8 variant where the hardware supports it, each step verified against torch.matmul and benchmarked in TFLOP/s.

The real thing: github.com/NVIDIA/cutlass/tree/main/examples/08_turing_tensorop_gemm ↗

How you know a stage passes

Write tests/test_gemm.py first. Each kernel is compiled with torch.utils.cpp_extension.load_inline (CUTLASS stages add its include path) and compared with torch.matmul using torch.testing.assert_close (fp16 inputs, fp32 accumulate, rtol 1e-2, atol 1e-2) at square sizes 256 to 4096 and at (1000, 777, 333). bench.py records TFLOP/s per kernel per size into results.csv, and a ptx.py dumps PTX and greps for the expected instructions. Run `pytest -q` on the Colab T4; a stage passes when its tests and all earlier tests are green.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01scalar fp32 baseline with shared-memory tiling
    A classic 32x32 shared-memory tiled fp32 GEMM that handles arbitrary M, N, K with bounds checks.
    test · assert_close passes at all sizes; bench.py records its TFLOP/s at 4096 as the baseline row of results.csv.
  2. 02WMMA 16x16x16 warp tiles
    Each warp computes a 16x16 output tile with nvcuda::wmma fragments over fp16 inputs and fp32 accumulators, loading A and B tiles through shared memory.
    test · ptx.py finds wmma.mma.sync in the PTX; the kernel is at least 4x faster than stage 1 at 4096 and passes the tolerance check at every size.
  3. 03bigger warp tiles and double buffering
    Warps compute 32x32 (2x2 fragments), the block computes 128x128, and global-to-shared loads of the next K slice overlap the current MMA through a two-stage buffer.
    test · Throughput at 4096 improves by at least 1.5x over stage 2 and reaches at least 40 percent of torch.matmul; all tests still pass.
  4. 04CUTLASS 2.x device GEMM for sm_75
    A cutlass::gemm::device::Gemm instantiation (TensorOp, fp16 in, fp32 accumulate, sm_75 tile shapes from example 08) wrapped as a torch extension so the Python tests call it exactly like your kernels.
    test · CUTLASS passes every tolerance test and reaches at least 60 percent of torch.matmul at 4096; results.csv has the row and the README names the chosen threadblock, warp and instruction shapes.
  5. 05CuTe layouts in Python and in the kernel
    A cute_layout.py that models Layout(shape, stride), composition and swizzle and predicts offsets, and a CuTe-based kernel (cute::make_tensor, partition, copy and gemm) that uses the same layouts for its shared-memory tiles.
    test · cute_layout.py assertions reproduce the offsets printed by a tiny CuTe print_layout program for two tiled layouts and one swizzled layout; the CuTe kernel passes the tolerance tests.
  6. 06fp8 path where supported, int8 otherwise
    On sm_89 or newer, an fp8 e4m3 GEMM with per-tensor scales (CUTLASS 3.x collective); on the T4, an int8 tensor-op GEMM with per-channel scales as the stand-in, with the same scale handling and the same test file.
    test · Low-precision GEMM matches an fp32 reference of the dequantized inputs within rtol 5e-2 and is at least 1.3x faster than the fp16 CUTLASS kernel at 4096; the README states which path ran and why.

No GPU? Use a Kaggle T4 if Colab has no GPU. With no GPU, write stages 1 to 3 and compile to PTX with nvcc --ptx (available in the CUDA toolkit on Colab CPU runtimes), verify the wmma instructions appear, run cute_layout.py on the Mac, and skip timings.

Knowledge check

QWhy do tensor-core kernels accumulate in fp32 even when inputs are fp16 or fp8?

Products of many low-precision terms overflow or lose precision quickly; a wider accumulator keeps the sum exact enough, and the cost is small because accumulation happens inside the tensor core.

QWhat does TMA change about how a GEMM mainloop is written on Hopper?

One thread issues an asynchronous multi-dimensional tile copy into shared memory and signals an mbarrier, so warps no longer spend registers and instructions on loads and producer and consumer roles can be separated.

QIn CuTe, what is a layout and why compose them?

A mapping from logical coordinates to offsets expressed as shape and stride; composition lets you express tiling, partitioning among threads and swizzling as functions rather than hand-written index arithmetic.

QWhere in an FP8 GEMM is model accuracy mostly decided?

In the scaling scheme and the epilogue, where per-tensor or per-block scales are applied and results are dequantised; the MMA itself is exact given its inputs.

QWhy does your WMMA kernel lag cuBLAS or CUTLASS even though both use tensor cores?

It lacks multi-stage software pipelining, swizzled shared memory to avoid bank conflicts, larger warp tiles for register reuse and tuned block shapes; the MMA instruction is the same.

Completion

  • All 7 subtopics marked done
  • All 3 required lessons done
  • Lesson l1 wmma kernel verified with PTX evidence and the speedup threshold met.
  • Lesson l2 CUTLASS example built, verified and compared.
  • Lesson l3 notes and cute_layout.py assertions complete.
  • Can sketch the Hopper producer/consumer mainloop and explain the role of TMA, wgmma and the pipeline barrier.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →