Pidoku

CUTLASS and CuTe: Layouts as Algebra

Module 25 Lesson 25.c 1h 30m Difficulty 5/5

Prerequisites 25.a, 11.g, 6.b, 4.f


Before you start: words you need#

WordPlain meaning
CUTLASSNVIDIA’s open-source library of CUDA C++ templates (and, since version 4, Python DSLs) for GEMMs, convolutions and attention. cuBLAS and many engine kernels are built from the same ideas.
CuTeThe core of CUTLASS 3 and 4: a small algebra of layouts and tensors that describes where every element lives, for every thread, at every level of the memory hierarchy.
LayoutA function from a coordinate to an offset, written shape:stride, e.g. (4,8):(8,1) is a 4 × 8 row-major matrix.
ModeOne dimension of a layout. Modes can be nested: ((2,4),8) has a first mode that is itself 2 × 4.
CompositionApplying one layout to the output of another: (A ∘ B)(i) = A(B(i)). Tiling, transposing and partitioning are all compositions.
SwizzleAn XOR applied to shared-memory addresses so that the threads of a warp hit different banks.
AtomThe smallest hardware operation CuTe knows: one MMA instruction or one copy instruction, with its thread-and-value layout.
TV layoutThread–value layout: which thread holds which value of a tile.

1. What is it?#

CUTLASS is the reference implementation of fast linear algebra on NVIDIA GPUs. Since CUTLASS 3 (2023), everything in it is built on CuTe, whose one big idea is:

Every arrangement of data — a matrix in HBM, a swizzled tile in shared memory, the fragment one thread holds for a tensor-core instruction — is a layout: a function from coordinates to offsets. Layouts can be composed, divided and inverted with a few algebraic operations.

With that, a kernel author does not write index arithmetic. They say “tile this tensor by 128 × 64”, “give me the part thread 37 owns for this MMA”, “copy this with TMA”, and CuTe derives the addresses. The same algebra is exposed in Python in CuTe DSL (CUTLASS 4, 2025), which FlashAttention-4, FlashInfer’s Blackwell kernels and CUTLASS’s own Blackwell examples use.

Facts checked on 13 November 2026: CUTLASS 4.8.1 (October 2026) is current; its README still calls CuTe DSL “public beta”.


2. Why does it exist?#

Before CuTe, CUTLASS 2.x expressed every combination of tile size, data type, layout and architecture with separate hand-written “iterator” classes. Each new tensor-core generation multiplied them. The index arithmetic was where bugs and performance cliffs lived: a wrong stride is a wrong answer; a right stride with a bad shared-memory pattern is a 2–8× slowdown from bank conflicts.

Hopper and Blackwell made it worse. A wgmma or tcgen05.mma operand must sit in shared memory in a specific swizzled layout, described by a descriptor; TMA must write that same layout; each thread’s accumulator fragment (or TMEM lane) has another layout again. Writing these by hand for every tile shape is not feasible. A single algebra that can produce and check all of them is.

For an inference engineer, CuTe matters even if you never write a kernel: it is how to read CUTLASS, FlashAttention-3/4, FlashInfer, FlashMLA and DeepGEMM (which borrows CuTe concepts without the full algebra), and how to understand their constraints (“head dimension must be a multiple of 64”, “N must be a multiple of 16”).


3. Simple analogy#

A layout is a seating chart. The shape is how the hall is arranged (4 rows of 8 seats); the stride is how seat numbers advance (next row = +8, next seat = +1). Change the stride to (1,4) and the same hall is numbered down the columns instead.

Composition is re-seating a group by a second chart: “the tour group’s guest i sits at the seat the hall chart gives for the group chart’s entry i”. Tiling is “split the hall into blocks of 4 × 4 and number the blocks”. Swizzling is a usher who shuffles which door (bank) each row uses so that eight guests arriving together do not queue at the same door.


4. Tiny example: layouts are functions#

The program below implements CuTe’s evaluation rule (split a 1-D coordinate column-major over the shape, then dot with the stride), prints two layouts, checks a composition, and measures a swizzle against shared-memory banks.

Go
// cute.go — CuTe-style layouts as plain functions from a coordinate to an offset,
// composition of layouts, and a 128-byte swizzle checked against shared-memory banks.
package main

import (
	"fmt"
	"strings"
)

// Layout is a flat CuTe layout: shapes and strides per mode (column-major / colexicographic).
type Layout struct{ shape, stride []int }

func (l Layout) size() int {
	n := 1
	for _, s := range l.shape {
		n *= s
	}
	return n
}

// at maps a 1-D coordinate to an offset: split i colexicographically, dot with the strides.
func (l Layout) at(i int) int {
	off := 0
	for k, s := range l.shape {
		off += (i % s) * l.stride[k]
		i /= s
	}
	return off
}

// print2D shows a rank-2 layout as a matrix of offsets (rows = mode 0, cols = mode 1).
func print2D(name string, l Layout) {
	fmt.Printf("%s  (%d,%d):(%d,%d)\n", name, l.shape[0], l.shape[1], l.stride[0], l.stride[1])
	for r := 0; r < l.shape[0]; r++ {
		var row []string
		for c := 0; c < l.shape[1]; c++ {
			row = append(row, fmt.Sprintf("%3d", l.at(r+c*l.shape[0])))
		}
		fmt.Println("   " + strings.Join(row, ""))
	}
}

// swizzle implements CuTe's Swizzle<B,M,S> on an element offset.
func swizzle(off, b, m, s int) int {
	yyy := ((1 << b) - 1) << (m + s)
	return off ^ ((off & yyy) >> s)
}

// wavefronts: how many shared-memory passes 8 threads need when each reads 16 bytes
// starting at the given byte addresses (32 banks of 4 bytes).
func wavefronts(addrs []int) int {
	perBank := map[int]map[int]bool{}
	for _, a := range addrs {
		for w := 0; w < 4; w++ { // a 16-byte read touches 4 consecutive 4-byte words
			word := a/4 + w
			bank := word % 32
			if perBank[bank] == nil {
				perBank[bank] = map[int]bool{}
			}
			perBank[bank][word] = true
		}
	}
	worst := 0
	for _, words := range perBank {
		worst = max(worst, len(words))
	}
	return worst
}

func main() {
	colMajor := Layout{[]int{4, 8}, []int{1, 4}}
	rowMajor := Layout{[]int{4, 8}, []int{8, 1}}
	print2D("column-major", colMajor)
	print2D("row-major   ", rowMajor)

	// Composition: view the row-major 4x8 matrix through an 8x4 layout B. (A o B)(i) = A(B(i)).
	B := Layout{[]int{8, 4}, []int{4, 1}}
	composed := Layout{[]int{8, 4}, []int{1, 8}} // what CuTe's composition(A, B) simplifies to
	same := true
	for i := 0; i < B.size(); i++ {
		if rowMajor.at(B.at(i)) != composed.at(i) {
			same = false
		}
	}
	fmt.Println("A o B equals (8,4):(1,8) at every coordinate:", same)

	// An 8 x 64 BF16 tile, rows of 128 bytes. 8 threads read 16-byte chunk c of rows 0..7
	// (the pattern of ldmatrix and of a tensor-core operand fetch).
	const rowElems, elemBytes = 64, 2
	for _, c := range []int{0, 3} {
		var plain, swz []int
		for r := 0; r < 8; r++ {
			off := r*rowElems + c*8 // element offset of chunk c in row r
			plain = append(plain, off*elemBytes)
			swz = append(swz, swizzle(off, 3, 3, 3)*elemBytes) // Swizzle<3,3,3> on elements = 128B swizzle
		}
		fmt.Printf("chunk %d: plain %d wavefronts, swizzled %d wavefronts; swizzled chunks per row:",
			c, wavefronts(plain), wavefronts(swz))
		for _, a := range swz {
			fmt.Printf(" %d", (a%128)/16)
		}
		fmt.Println()
	}
}
column-major  (4,8):(1,4)
     0  4  8 12 16 20 24 28
     1  5  9 13 17 21 25 29
     2  6 10 14 18 22 26 30
     3  7 11 15 19 23 27 31
row-major     (4,8):(8,1)
     0  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
A o B equals (8,4):(1,8) at every coordinate: true
chunk 0: plain 8 wavefronts, swizzled 1 wavefronts; swizzled chunks per row: 0 1 2 3 4 5 6 7
chunk 3: plain 8 wavefronts, swizzled 1 wavefronts; swizzled chunks per row: 3 2 1 0 7 6 5 4

Three lessons in twenty lines of output:

  1. Same shape, different stride, different matrix. Layout is data, not code.
  2. Composition is just function composition, and CuTe can simplify the result back into a shape:stride layout. Here, reading the row-major matrix through (8,4):(4,1) gives (8,4):(1,8), its transpose.
  3. A 128-byte swizzle turns an 8-way bank conflict into none. Without it, chunk c of every row is at the same byte offset modulo 128, so all eight threads hit the same four banks. XOR-ing the chunk index with the row index spreads them over all 32 banks. This exact pattern is TMA’s “128B swizzle” mode and the layout wgmma and tcgen05.mma descriptors expect.

5. Technical explanation#

The pieces of CuTe#

ConceptWhat it isC++CuTe DSL (Python)
IntTuplean int or a nested tuple of ints, static or dynamicmake_shape(Int<128>{}, K)(128, K)
Layoutshape : stridemake_layout(shape, stride)cute.make_layout(shape, stride=...)
Tensorpointer (or iterator) + layoutmake_tensor(make_gmem_ptr(p), layout)cute.make_tensor(ptr, layout)
Tilingsplit into tileszipped_divide, local_tilecute.zipped_divide, cute.local_tile
Partitioningwhich part a thread ownslocal_partition, thr_mma.partition_Athr_mma.partition_A(...)
Atomsone hardware instructionMMA_Atom<SM90_64x128x16_F32BF16BF16_SS>, Copy_Atom<SM90_TMA_LOAD,...>tcgen05.MmaF16BF16Op, cpasync.CopyBulkTensorTileG2SOp
Tiled atomsan atom repeated over warps and valuesTiledMMA, TiledCopycute.make_tiled_mma, cute.make_tiled_copy_tv

Static versus dynamic. Int<128>{} (C++) or a Constexpr (Python) is known at compile time, so the compiler can unroll and constant-fold; a runtime K is not. Fast kernels make tile shapes static and only problem sizes dynamic.

The four operations that do all the work#

  • Coalesce: merge modes that are contiguous. (2,4):(1,2) is just 8:1.
  • Composition A ∘ B: reindex A by B. Used to apply a swizzle, transpose, or restrict to a sub-tile.
  • Complement: “the rest” of a layout inside a larger space — the layout of the other tiles when you have picked one tile. It is what makes division possible.
  • Logical divide A / B = A ∘ (B, complement(B)): split A into “inside a tile” (mode 0) and “which tile” (mode 1). zipped_divide and local_tile are conveniences on top.

So “tile a 4096 × 4096 matrix by 128 × 64 and give me tile (m, k)” is:

C++
// CuTe C++
Tensor mA = make_tensor(make_gmem_ptr(A), make_shape(M, K), make_stride(K, Int<1>{}));  // row-major
auto   cta_tiler = make_shape(Int<128>{}, Int<64>{});
Tensor gA = local_tile(mA, cta_tiler, make_coord(m_blk, _));   // (128, 64, k_tiles)
Python
# CuTe DSL, from CUTLASS's Blackwell tutorial fp16_gemm_0.py
gA = cute.local_tile(mA_mkl, mma_tiler_mnk, mma_coord_mnk, proj=(1, None, 1))  # (bM, bK, RestK)

The trailing _ / None keeps the K dimension so the mainloop can walk it.

Thread–value layouts and atoms#

A tensor-core instruction defines which thread holds which value of its A, B and C fragments. CuTe writes that as a TV layout: (thread, value) → (m, n). A TiledMMA repeats the atom over warpgroups and over M, N. Then:

C++
ThrMMA thr_mma = tiled_mma.get_slice(threadIdx.x);
Tensor tCgC = thr_mma.partition_C(gC);   // this thread's slice of the output tile
Tensor tCrC = thr_mma.make_fragment_C(tCgC);  // registers (Hopper) shaped to match

On Blackwell, “this thread’s slice” of the accumulator is in TMEM, and the epilogue builds a tcgen05 load atom (Ld32x32bOp) whose TV layout encodes the warp-to-lane rule from 25.a. The author never writes “warp 2 reads lanes 64–95”; the atom’s layout says it.

Swizzles#

Swizzle<B, M, S> XORs B bits starting at bit M+S into the B bits starting at bit M. In element units for 16-bit types, Swizzle<3,3,3> is the 128-byte swizzle (8 chunks of 16 bytes per 128-byte row); Swizzle<2,3,3> and Swizzle<1,3,3> are 64 and 32 bytes. A swizzled shared-memory tile is a ComposedLayout: swizzle ∘ offset ∘ layout. CUTLASS picks the swizzle from the tile’s contiguous width; TMA’s tensor map and the MMA descriptor are generated from the same object, which is why they agree.

The CUTLASS C++ stack on top of CuTe#

GemmUniversalAdapter            host-side: arguments, workspace, launch
  └─ GemmUniversal kernel       persistent loop, warp roles, tile scheduler (25.e, 25.j)
       ├─ CollectiveMma         mainloop: TMA + pipeline + wgmma / tcgen05 (built by CollectiveBuilder)
       └─ CollectiveEpilogue    epilogue: fusion tree (EVT), TMA store

CollectiveBuilder picks tile shapes, stage counts and schedules from a short description (types, layouts, alignment, architecture tag such as cutlass::arch::Sm100). Epilogue Visitor Trees (EVT) let you describe fused epilogues — per-row scale × per-column scale + bias, then SiLU, then cast to FP8 — as a tree of nodes that CUTLASS compiles into the store path. vLLM’s FP8 and NVFP4 GEMMs use exactly this (csrc/quantization/w8a8/cutlass/Epilogues.md in the vLLM tree documents its EVT epilogues).

CuTe DSL in one paragraph#

CuTe DSL is the same algebra in Python, compiled through MLIR straight to PTX/cubin without nvcc’s template instantiation. Kernels are @cute.kernel functions launched from @cute.jit host functions; cute.compile(...) produces a callable. Compile times are seconds rather than minutes (the FlashAttention-4 authors report 20–30× faster compiles than the C++ templates, 13.l), and it interoperates with PyTorch through DLPack. CUTLASS 4.8 also previews cute_ext, higher-level building blocks (GEMM mainloops, TMA epilogues) usable inside ordinary CuTe DSL kernels.


6. Under the hood: from algebra to instructions#

What cute.copy(tma_atom, tAgA[(None, k)], tAsA[(None, stage)], tma_bar_ptr=bar) becomes:

  1. On the host, make_tiled_tma_atom took the global tensor’s layout and the shared-memory (swizzled) layout, checked they are compatible, and called cuTensorMapEncodeTiled with the box size and swizzle mode CuTe derived.
  2. tma_partition divided the global tensor so that mode 1 is “which K tile”; indexing it with k gives TMA coordinates.
  3. The copy emits one cp.async.bulk.tensor.2d...mbarrier::complete_tx::bytes with those coordinates and the stage’s shared-memory address.

And cute.gemm(tiled_mma, acc, tCrA[k], tCrB[k], acc) on Blackwell becomes one tcgen05.mma per K-block of the atom, with shared-memory descriptors computed from the swizzled layouts of sA and sB. Everything that can be static is folded at compile time; what reaches the GPU is a short sequence of address-free instructions.

When it goes wrong, CuTe fails at compile time with a static assertion such as “layouts are not compatible” or “TMA box exceeds 256 elements” rather than at run time with wrong numbers. That is the practical payoff of the algebra.


7. Performance implications#

  • Bank conflicts are a layout property. The Go program’s 8 → 1 passes is the whole story of shared-memory swizzling (6.b showed the global-memory analogue, coalescing).
  • Static shapes buy unrolling. A Int<64>{} head dimension lets the compiler unroll the K loop and keep indices in registers. This is why attention libraries ship separate kernels for head dimensions 64, 128, 192 and 256 and refuse others.
  • Alignment constraints come from layouts. TMA needs 16-byte-aligned strides; MMA atoms need K multiples of 16 (BF16) or 32 (FP8). A model with a hidden size that breaks these falls off the fast path (4.f’s silent fallback).
  • CUTLASS templates are expensive to compile. A large CUTLASS-based extension can take tens of minutes and gigabytes of RAM to build; that is a real cost in CI and image builds, and one reason for the move to CuTe DSL and JIT compilation (DeepGEMM, FlashInfer).

8. Production implications#

  • Most teams use CUTLASS through someone else. vLLM, SGLang and TensorRT-LLM include CUTLASS-based GEMMs (FP8 block-scaled, NVFP4, grouped MoE); FlashInfer and FlashAttention-4 ship CuTe DSL kernels. Pin the CUTLASS version these use: a CUTLASS bump can change tile heuristics and therefore performance and numerics (25.l).
  • Use the CUTLASS profiler before writing anything. cutlass_profiler enumerates every compiled kernel configuration for a problem shape and reports the fastest. It is the quickest way to find out whether a better configuration exists than the one your engine picks.
  • Know when CuTe is overkill. Elementwise, norm and quantisation kernels are better in Triton (6.e). CuTe earns its complexity on GEMM, attention and fused GEMM epilogues.
  • CuTe DSL kernels JIT-compile on first use. Expect a cold-start compile on the first request of a new shape unless the library caches compiled kernels (FlashInfer ships flashinfer-cubin and flashinfer-jit-cache wheels for this). Warm caches in your image or at start-up.

9. Common mistakes#

  1. Reading a layout as row-major by default. CuTe is column-major (colexicographic) by default: make_layout((4,8)) is (4,8):(1,4).
  2. Mixing static and dynamic integers carelessly. A dynamic tile size silently disables unrolling and can push indices into local memory.
  3. Swizzling only one side. A shared-memory layout swizzled for TMA but described unswizzled to the MMA (or the reverse) gives wrong results that pass small tests.
  4. Ignoring alignment. A tensor whose row stride is not a multiple of 16 bytes cannot use TMA; the library falls back or fails at descriptor creation.
  5. Fighting the algebra. Writing manual index arithmetic inside a CuTe kernel defeats the compile- time checks; express it as a layout instead.
  6. Assuming CUTLASS C++ and CuTe DSL share binaries or tuning. They share concepts, not compiled kernels; performance must be measured separately.

10. Hands-on exercise#

  1. Extend the Go program to support nested shapes (a mode that is itself a tuple). Check that ((2,2),(2,4)):((1,4),(2,8)) prints as a 4 × 8 matrix, and explain its pattern.
  2. Change the swizzle to Swizzle<2,3,3> (64-byte). How many passes does chunk 0 now need? Why?
  3. With CUTLASS 4.8 installed (pip install nvidia-cutlass-dsl), run the notebooks in examples/python/CuTeDSL/notebooks/1_dsl_features that print layouts, and reproduce the Go output with cute.make_layout and cute.composition.
  4. Read examples/python/CuTeDSL/cute/blackwell/tutorial/tutorial_gemm/fp16_gemm_0.py (about 200 lines). For each tensor (gA, tCgA, tCrA, tAsA, tCtAcc), write down its shape and which memory it lives in.

11. Interview questions#

  1. What is a CuTe layout, and why is “a function from coordinates to offsets” a useful definition?
  2. Explain composition and logical divide. How do they give you tiling?
  3. Why does a 128-byte swizzle remove bank conflicts for tensor-core operand loads? Show the XOR.
  4. What is a TV layout, and how does it let one kernel source target several MMA instructions?
  5. What do CollectiveBuilder and Epilogue Visitor Trees do in CUTLASS 3/4?
  6. When would you write a kernel in CuTe DSL rather than Triton, and the reverse?
  7. Why do attention kernels support only a few head dimensions?

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in