Using TMA Load, Prefetch, and Multicast Load in CuTe DSL
How to move a tile of a tensor into shared memory with the Tensor Memory Accelerator, written in Python with CuTe DSL and run on a B300
Yifan Yang wrote a really nice walkthrough called "Using TMA Load, Prefetch, and Multicast Load in CuTe", which shows step by step how to drive the Tensor Memory Accelerator (TMA), the unit that recent NVIDIA GPUs use to copy tiles of a tensor into fast on-chip memory. Since then, NVIDIA has released CuTe DSL, a Python library for writing GPU kernels with CuTe's layouts, tensors and copy atoms. If you start writing GPU kernels today, there is a good chance you will start there, so I thought it would be useful to redo that walkthrough entirely in CuTe DSL.
In this article, we will load a tile of a matrix from global memory into shared memory with the TMA (section 3), prefetch it into the L2 cache instead (section 4), and finally load it once and deliver it to several thread blocks at the same time with a multicast load (section 5). I'll follow the structure of Yifan's post, with the same three operations and the same number of figures, but all the code here is CuTe DSL, and I ran every code block in this article on an NVIDIA B300 with nvidia-cutlass-dsl 4.8.0. Where the hardware did something I didn't expect, I'll show you what happened.
I'll assume that you know what a warp is (32 threads that execute together) and not much more about GPUs. Everything else, including what shared memory is and what a thread block cluster is, gets a short introduction right before we need it. We'll leave the TMA store, reductions and swizzled layouts for another time.
1. A Few GPU Basics
Before we can talk about the TMA, we need a picture of where data lives on a GPU and who works on it, so let's go over that briefly.
When you launch a kernel, you launch a grid of thread blocks. NVIDIA's documentation calls a thread block a CTA (cooperative thread array), and so does CuTe, so I will use that name. A CTA is a group of warps that are guaranteed to run together on one SM (streaming multiprocessor), which is the GPU's equivalent of a CPU core. The B300 I used has 148 SMs, and a kernel usually launches far more CTAs than that, which the hardware then schedules onto the SMs as they become free. The grid and the CTAs can be up to three-dimensional, and every CTA can ask for its coordinate in the grid, which in CuTe DSL is cute.arch.block_idx().
Then there is memory, and here it helps to go from far to near:
- Global memory is the large memory on the GPU package (HBM). Every SM can read and write it, and this is where your PyTorch tensors live. It is big but far away, so a load from it takes a long time.
- The L2 cache sits between the SMs and global memory and is shared by all SMs. On the B300 it holds 126.5 MiB. A load that finds its data in L2 comes back much sooner than one that has to go out to global memory.
- Shared memory is a small, fast memory inside each SM (a few hundred KB). Each CTA gets its own piece of it, which all threads of that CTA can read and write, and which disappears when the CTA finishes. Unlike a cache, shared memory is managed by the program: data is only there if the kernel put it there.
- Registers are private to each thread and are the fastest storage of all.
- Each SM also has an L1 cache, which in fact uses the same on-chip storage as shared memory.
Finally, the tensor cores are the units in each SM that do small matrix multiplications very fast. They read their inputs from registers or shared memory.
Most fast kernels follow the same pattern with all of this: cut the big matrices into tiles, give each CTA one tile (or a sequence of tiles), copy the tile from global memory into shared memory, and then work on it from there, since every thread of the CTA can now reach it quickly. The TMA is a piece of hardware for exactly that copy.
2. Why TMA?
As tensor cores get faster from one GPU generation to the next, the hard part becomes feeding them. A useful way to think about this is Little's law: the amount of data that has to be in flight equals the throughput times the latency. If the tensor cores consume data faster, but the time it takes to fetch data from memory stays about the same, then more data has to be in flight at any moment, and every byte of it has to sit in some buffer while it is on its way. Let's look at which buffers those are.
Before the Ampere generation (A100), a tile went from global memory through L2 and L1 into each thread's registers, and only then did the threads store it into shared memory, as shown in the top row of Figure 1 below. L1 and the registers held the tile only for a moment, purely as staging buffers, and the registers used that way were not available for the actual computation. With Ampere, NVIDIA added an asynchronous copy instruction that loads data directly from global memory into shared memory, "optionally bypassing L1 cache, and eliminating the need for intermediate register file (RF) usage", as the A100 announcement put it. That is the middle row of the figure.
As we can see in Figure 1, the asynchronous copy already gives us the short path. But there is a second problem, which is less obvious. Even with the asynchronous copy, every thread issues its own copy instructions, and every thread computes the addresses of the elements it copies: row times stride plus column, checks against the matrix edges, and so on. A typical GEMM kernel (a matrix multiplication) roughly goes through the stages address generation, load, MMA (the tensor core math), epilogue (whatever happens to the result, like adding a bias or applying an activation) and store. When the tensor cores and the memory system get faster, the other stages have to keep up, and address generation and the epilogue both run on the SM's regular arithmetic units (NVIDIA calls them CUDA cores), which did not get faster at the same rate. So the CUDA cores end up being the bottleneck, partly because they are busy computing addresses.
This is where the TMA comes in. With Hopper (H100), NVIDIA added a unit to each SM that does the address generation in hardware. One thread hands it a descriptor, which describes the whole tensor in global memory (its base address, shape and strides) and the size of the tile, together with the coordinate of the tile that it wants, and the TMA unit generates all the addresses and moves the data into shared memory by itself (the bottom row of Figure 1). As NVIDIA's Hopper announcement puts it, this frees the threads to do other independent work, for example the epilogue of the previous tile. The B300 I used here is a Blackwell GPU, which has the same TMA.
There are a few ways to use the TMA. You can build the descriptor with the CUDA driver API and write the PTX instructions yourself (PTX is the assembly-like language that CUDA compiles to), which works but is quite error-prone. Triton supports the TMA as well, but in my experience it gives you less control over what happens inside the kernel. CuTe DSL sits in between: it builds the descriptor for you from a tensor and a layout, and lets you decide exactly which tile goes where. That's what we'll use.
3. TMA Load
3.1 The Example
Let's start with a tiny example that is easy to draw. We have a matrix of shape [N, K] = [6, 8] in global memory, stored row-major (one row after the other) in fp32, and filled with the numbers 0 to 47. We want to cut it into tiles of shape [CTA_N, CTA_K] = [2, 4], so there are 3 x 2 tiles, and we launch one CTA per tile, i.e., a grid of shape (3, 2). The CTA at grid coordinate (1, 1) should then load tile (1, 1), which is rows 2 and 3 and columns 4 to 7, into its shared memory, as shown in Figure 2 below.
This mapping from tiles to CTAs is just the simplest one. A kernel can just as well let a CTA load several tiles one after another, or in some other order, and the code below only changes in one line (the one that picks the tile).
3.2 Host Code
A CuTe DSL program has two kinds of functions. A function decorated with @cute.jit runs on the host (the CPU). It sets things up and launches kernels. A function decorated with @cute.kernel is the kernel itself, which runs on the GPU. When we call the @cute.jit function for the first time, CuTe DSL traces it together with the kernel it launches, compiles both, and then runs them. In both kinds of functions, plain Python integers (like our tile size) become constants in the compiled code, which is what we want for anything that describes shared memory.
Two more CuTe words before the code. A layout maps a coordinate to an offset in memory, and it is written as shape : stride. Our row-major [2, 4] tile has the layout (2, 4) : (4, 1), since moving down one row skips 4 elements and moving right one column skips 1. A tensor is a pointer together with a layout.
Here is the host code:
import torch
import cutlass
import cutlass.cute as cute
from cutlass.cute.nvgpu import cpasync
from cutlass.cute.runtime import from_dlpack
CTA_N, CTA_K = 2, 4 # the tile that one CTA loads
@cute.jit
def tma_load(b: cute.Tensor, out: cute.Tensor):
# 1. the shared memory layout of one tile, row-major
smem_layout = cute.make_layout((CTA_N, CTA_K), stride=(CTA_K, 1))
# 2. the TMA copy atom (it holds the descriptor) and the TMA tensor
tma_atom, gB = cpasync.make_tiled_tma_atom(
cpasync.CopyBulkTensorTileG2SOp(), b, smem_layout, (CTA_N, CTA_K)
)
# 3. one CTA per tile, one warp per CTA
N, K = b.shape
tma_load_kernel(tma_atom, gB, smem_layout, out).launch(
grid=(N // CTA_N, K // CTA_K, 1), block=(32, 1, 1)
)
Let's go through it step by step:
- We describe the layout the tile should have in shared memory: shape (CTA_N, CTA_K) and row-major strides (CTA_K, 1). Since CTA_N and CTA_K are Python integers, this layout is fully known at compile time, which the TMA requires, because the descriptor has to know the tile size when it is built.
make_tiled_tma_atombuilds the TMA descriptor from the global tensorb(its address, shape and strides) and the shared memory layout. The first argument says which TMA operation we want:CopyBulkTensorTileG2SOpis a bulk copy of a tile of a tensor from global to shared memory (G2S). The last argument is the CTA tiler, the size of the tile each CTA copies. The function returns two things. The first is the copy atom, CuTe's object for "one hardware copy instruction plus everything it needs", which here includes the descriptor. The second is a TMA tensor, which we will look at closely in a moment, since it's the least obvious part of the whole API.- We launch the kernel with one CTA per tile, so a (6 / 2, 8 / 4) = (3, 2) grid. Each CTA has 32 threads, a single warp, because the TMA only needs one thread to drive it. (A real kernel would have more warps that do something with the tile, but we don't need them here.)
The copy atom is handed to the kernel as a regular argument. Under the hood, the descriptor is a 128-byte object that is passed as a kernel parameter (in the PTX, the first parameter is a 128-byte, 64-byte-aligned blob), so the kernel cannot change it, and we don't have to do anything special to make that happen.
3.3 Device Code
Now for the kernel. I kept it in one piece, since the order of the steps matters:
@cute.kernel
def tma_load_kernel(tma_atom: cute.CopyAtom, gB: cute.Tensor,
smem_layout: cute.Layout, out: cute.Tensor):
bx, by, _ = cute.arch.block_idx()
tidx, _, _ = cute.arch.thread_idx()
tile_bytes = cute.size_in_bytes(out.element_type, smem_layout)
# 1. shared memory for the tile and for one mbarrier
smem = cutlass.memory.SmemAllocator()
sB = smem.allocate_tensor(out.element_type, smem_layout, 128)
mbar = smem.allocate_array(cutlass.Int64, 1)
# 2. one thread initializes the barrier; the others wait for it
with cute.arch.elect_one():
cute.arch.mbarrier_init(mbar, 1)
cute.arch.mbarrier_init_fence()
cute.arch.barrier()
# 3. this CTA's tile of the TMA tensor, partitioned for the copy
gTile = cute.local_tile(gB, (CTA_N, CTA_K), (bx, by))
tBsB, tBgB = cpasync.tma_partition(
tma_atom, 0, cute.make_layout(1),
cute.group_modes(sB, 0, 2), cute.group_modes(gTile, 0, 2),
)
# 4. arm the barrier with the byte count, then issue the copy
with cute.arch.elect_one():
cute.arch.mbarrier_arrive_and_expect_tx(mbar, tile_bytes)
cute.copy(tma_atom, tBgB, tBsB, tma_bar_ptr=mbar)
# 5. every thread waits until phase 0 of the barrier completes
cute.arch.mbarrier_wait(mbar, 0)
# 6. the tile is in shared memory; copy it out so we can check it
for i in cutlass.range(tidx, cute.size(sB), 32):
n, k = i // CTA_K, i % CTA_K
out[bx * CTA_N + n, by * CTA_K + k] = sB[n, k]
Before we go through the steps, we need one more piece of background, namely the mbarrier. The TMA works asynchronously: the thread that issues the copy gets control back right away, long before the data has arrived. So the CTA needs some way to find out when the tile is complete. That is the job of an mbarrier, a 64-bit object in shared memory that counts two things: arrivals of threads and bytes of pending transactions. When the barrier is initialized, we tell it how many arrivals to expect. A thread can also tell it to expect a number of bytes, and the TMA unit counts down the bytes as the data lands in shared memory. When both counts have reached zero, the barrier completes its current phase, and every thread that waits on that phase can continue. The first phase is phase 0, the next one phase 1, and so on, which is what lets a kernel reuse the same barrier for the next tile.
With that, let's go through the kernel:
- We allocate shared memory for the tile,
sB, with the layout from the host, aligned to 128 bytes (the third argument; we will see in section 5 why this number matters), and 8 bytes for the mbarrier. (In CuTe DSL 4.8 the allocator lives incutlass.memory; the oldercutlass.utils.SmemAllocatorstill works but prints a deprecation warning.) - One thread initializes the barrier and says that one arrival is expected.
elect_one()picks a single thread of the warp to run the body. The fence makes the initialization visible to the TMA unit, andcute.arch.barrier(), a plain barrier for all threads of the CTA, makes sure that no thread touches the mbarrier before it is initialized. - Now we find our tile.
local_tile(gB, (CTA_N, CTA_K), (bx, by))cutsgBinto tiles of shape (CTA_N, CTA_K) and returns the one at tile coordinate (bx, by). In NumPy terms, this isgB[CTA_N * bx : CTA_N * (bx + 1), CTA_K * by : CTA_K * (by + 1)], so for CTA (1, 1) we get rows 2 to 3 and columns 4 to 7. Thentma_partitionreshapes the global tile and the shared memory tile into the form thatcute.copyexpects from a TMA atom. We'll look at its arguments and at what comes out in section 3.4. - One thread arrives on the barrier and, in the same instruction, tells it to expect
tile_bytesbytes, which is 2 x 4 x 4 = 32 bytes here. Then we issue the copy, and we pass the barrier along withtma_bar_ptr, so that the TMA unit knows which barrier to count down. Note thatcute.copyis called by the whole warp, not inside anif. I'll explain why in section 3.5, since getting this wrong makes the kernel hang. - All threads wait for phase 0 of the barrier to complete. The arrival from step 4 has already happened, so the phase completes exactly when all 32 bytes have landed in shared memory.
- At this point, the tile is in shared memory and visible to every thread of the CTA. Yifan's version printed two elements here. I copy the whole tile back to an output tensor instead, so that we can compare it with the input on the host.
3.4 The TMA Tensor and tma_partition
The one thing in this kernel that is genuinely confusing at first is gB, the TMA tensor that make_tiled_tma_atom returned. You might expect it to be our matrix in global memory, but it isn't. Instead of values, its entries are coordinates. If we print it on the host while the kernel is traced, we get
tensor<(0,0) o (6,8):(1@1,1@0)>
This says: a tensor with shape (6, 8), starting at coordinate (0, 0), where moving down one row adds 1 to coordinate number 1 (that's what 1@1 means), and moving right one column adds 1 to coordinate number 0 (1@0). So the entry at row n and column k is the coordinate (k, n), with the column first. That is the order in which the TMA hardware counts dimensions: innermost (fastest-moving) first. Figure 3 below shows the whole tensor.
Why would we want a tensor of coordinates? The TMA instruction does not take addresses. It takes the descriptor plus the coordinate of the corner of the box it should copy, and the descriptor already contains the box size. So, what a CTA really has to compute is that one coordinate. And since the coordinate tensor has the same shape as the real matrix, we can cut it up with exactly the same CuTe operations that we use on the shared memory tile (local_tile, tma_partition and so on), and the coordinates stay in sync with the shared memory side automatically. We never materialize this tensor anywhere, which is why it has no pointer, only a starting coordinate and a layout.
As you can see in Figure 3, tile (1, 1) starts at row 2 and column 4, so its top-left entry is (4, 2). And indeed, in the PTX that CuTe DSL generates for this kernel, which you can keep by setting the environment variable CUTE_DSL_KEEP=ptx (together with CUTE_DSL_DUMP_DIR), the copy is this single instruction, cut down here to the part that matters:
cp.async.bulk.tensor.2d.shared::cta.global.tile
.mbarrier::complete_tx::bytes.L2::cache_hint
[smem], [desc, {c0, c1}], [mbar], policy;
Let's read it from left to right: a bulk tensor copy of a 2D tile from global memory to this CTA's shared memory, which reports completion as bytes on an mbarrier, with an L2 cache hint. Its operands are the shared memory address, the descriptor plus the two coordinates (c0, c1), and the mbarrier. For CTA (1, 1), the coordinates come out as (4, 2): in the PTX, c0 is the CTA's column in the grid times 4 and c1 its row times 2.
Now back to tma_partition(atom, cta_coord, cta_layout, smem_tensor, gmem_tensor). It expects mode 0 (the first dimension) of both tensors to be the whole tile, which is why we first group the two dimensions of each tile into one with group_modes(..., 0, 2). The second and third arguments only matter for multicast (section 5), where several CTAs share one copy. With a single CTA, its coordinate is 0 and the layout of the CTAs is make_layout(1). If we print what comes out for our tile, we get
tBgB: ((4,2),1) : ((1@0,1@1),0)
tBsB: (8,1) : (1,0)
(slightly simplified). The first mode, (4, 2), is one TMA instruction's worth of the tile, and the second mode, of size 1, counts how many instructions we need. Since one TMA instruction can copy our whole tile, we need exactly one. cute.copy loops over that second mode, so if the tile were bigger than what one instruction can copy, it would issue several instructions here.
3.5 Who Issues the Copy?
Now let's look at a detail that I got wrong at first while writing this article. Since the TMA only needs one thread, it seems natural to let only thread 0 issue the copy:
if tidx == 0:
cute.arch.mbarrier_arrive_and_expect_tx(mbar, tile_bytes)
cute.copy(tma_atom, tBgB, tBsB, tma_bar_ptr=mbar)
When I ran this version, the kernel never finished, and I had to kill it after 60 seconds. The version from section 3.3, where the whole warp calls cute.copy, finishes right away. The PTX shows why. cute.copy with a TMA atom already contains the election of one thread:
elect.sync %r11|%p5, -1;
not.pred %p6, %p5;
@%p6 bra $L__BB0_6;
...
cp.async.bulk.tensor.2d.shared::cta.global.tile...
elect.sync with the mask -1 asks all 32 threads of the warp to agree on one leader, and every thread that is not the leader jumps over the copy. If only thread 0 gets there, because the other 31 threads took the other branch of our if, the instruction is waiting for 31 threads that never show up. That's my reading of the hang, and it matches what we saw. So, in CuTe DSL, the rule is: call cute.copy with a TMA atom from a full warp, and use elect_one() only for the things you do by hand, like the mbarrier calls.
There are also some rules about alignment that the CUDA programming guide lists for TMA copies of multi-dimensional tensors. The two that you are most likely to run into are that the strides of the global tensor have to be multiples of 16 bytes, and that the shared memory address has to be aligned to 128 bytes. Our [6, 8] fp32 matrix has a row stride of 8 x 4 = 32 bytes, so it's fine. (A [6, 6] fp32 matrix, for example, would not be.) We will run into the 128-byte rule in section 5.
3.6 Running It
Finally, here is the code that runs everything:
b = torch.arange(6 * 8, dtype=torch.float32, device="cuda").reshape(6, 8)
out = torch.zeros_like(b)
tma_load(from_dlpack(b, assumed_align=16), from_dlpack(out, assumed_align=16))
torch.cuda.synchronize()
print(torch.equal(out, b)) # True
from_dlpack turns a PyTorch tensor into a CuTe tensor without copying it, and assumed_align=16 promises that the data pointer is 16-byte aligned, which the TMA requires for the global address. The first call compiles the kernel, and the result is True: every CTA copied its tile into shared memory and back out, and together the six tiles reproduce the matrix. I also ran the same kernel with a more realistic tile of [64, 128] on a [256, 256] bf16 matrix, by changing only CTA_N, CTA_K and the input, and that matched as well.
4. TMA Prefetch
The TMA can also move a tile from global memory into the L2 cache instead of into shared memory. This is a prefetch: a hint to the hardware that we will need that data soon. It is useful when you know which tile you will load next but cannot load it yet, for example because the shared memory buffer for it is still in use. If the prefetch has finished by the time the real load comes, the load is served from L2 instead of from global memory.
4.1 Host Code
The nice thing is that the host side does not change at all. We build exactly the same copy atom with CopyBulkTensorTileG2SOp, and whether it loads or prefetches is decided in the kernel:
@cute.jit
def tma_prefetch(b: cute.Tensor):
smem_layout = cute.make_layout((CTA_N, CTA_K), stride=(CTA_K, 1))
tma_atom, gB = cpasync.make_tiled_tma_atom(
cpasync.CopyBulkTensorTileG2SOp(), b, smem_layout, (CTA_N, CTA_K)
)
N, K = b.shape
tma_prefetch_kernel(tma_atom, gB, smem_layout, b.element_type).launch(
grid=(N // CTA_N, K // CTA_K, 1), block=(32, 1, 1)
)
4.2 Device Code
The kernel is a subset of the load kernel:
@cute.kernel
def tma_prefetch_kernel(tma_atom: cute.CopyAtom, gB: cute.Tensor,
smem_layout: cute.Layout, dtype: cutlass.Constexpr):
bx, by, _ = cute.arch.block_idx()
# 1. no data lands in shared memory, but tma_partition still wants a
# shared memory tensor, so we give it one on a null pointer
sB = cute.make_tensor(
cute.make_ptr(dtype, 0, cute.AddressSpace.smem, assumed_align=128),
smem_layout,
)
# 2. the same tile and partition as in the load kernel
gTile = cute.local_tile(gB, (CTA_N, CTA_K), (bx, by))
_, tBgB = cpasync.tma_partition(
tma_atom, 0, cute.make_layout(1),
cute.group_modes(sB, 0, 2), cute.group_modes(gTile, 0, 2),
)
# 3. one thread issues the prefetch; there is nothing to wait for
with cute.arch.elect_one():
cute.prefetch(tma_atom, tBgB)
Compared with the load, three things are gone. There is no shared memory to allocate, since the data only goes as far as L2. (tma_partition still wants a shared memory tensor to compute the partition from, so we give it one that sits on a null pointer and is never touched.) There is no mbarrier either, since a prefetch has no way to report completion. It runs in the background, and the kernel doesn't wait for it. And instead of cute.copy, we call cute.prefetch with the same atom and the same partitioned TMA tensor.
Underneath, cute.prefetch reuses the load atom: it fills in a dummy mbarrier pointer and an empty multicast mask, and asks for the prefetch form of the instruction. The PTX for our kernel contains
cp.async.bulk.prefetch.tensor.2d.L2.global.tile.L2::cache_hint
[desc, {c0, c1}], policy;
which is the same instruction family with the same descriptor and coordinates, but with L2 as the destination and no shared memory address or barrier.
There is one difference to cute.copy that is easy to miss. cute.prefetch does not elect a thread by itself. Without the elect_one() around it, the PTX has no elect.sync, and all 32 threads of the warp issue the same prefetch. That is harmless, since it's only a hint, but it's 31 instructions too many, so I wrap it in elect_one(). (This is the reverse of the rule for cute.copy, so it's worth remembering both.)
4.3 Does It Help?
Since we can read the SM's cycle counter inside a kernel (cute.arch.clock64()), I wanted to see what a prefetch actually buys. I used a 64 x 128 bf16 tile (16 KiB) and timed a single TMA load of it from the moment the copy is issued until the barrier completes, in four situations. Before every launch, I wrote 1 GiB of other data, which evicts the tile from the 126.5 MiB L2. Each CTA then waits for 20,000 cycles before the timed load, in every situation, so that the only difference is what happened before the wait. With 16 CTAs and 50 launches per situation, here are the medians:
- Cold, nothing done before the load: 1,531 cycles.
- The tile was brought into L2 by an ordinary PyTorch read after the eviction: 940 cycles.
- The CTA issued a TMA prefetch of the tile before the wait: 875 cycles.
- The CTA had already loaded the same tile into shared memory once before the wait: 500 cycles.
In other words, the prefetch cut the latency of the load by about 40% and made it about as fast as an L2 hit, which is what we hoped for. When I made the wait shorter, a wait of 2,000 cycles was already enough to get the full benefit. Without any wait at all, the load right after the prefetch took about 1,170 cycles, presumably because the prefetch was still on its way.
What I can't explain is the last number. A second load of the same tile by the same CTA is faster than an L2 hit by another 375 cycles or so. My guess is that some other state along the way (the address translation, for example) is also warm in that case, but I haven't verified that.
5. TMA Multicast Load
5.1 Clusters
For the last operation, we need one more piece of the hardware: the thread block cluster, which Hopper introduced. A cluster is a group of CTAs (up to 8 of them on any GPU that has clusters) that the hardware guarantees to run at the same time, on SMs that are close to each other. Because they run at the same time, the CTAs of a cluster can read and write each other's shared memory, which NVIDIA calls distributed shared memory, and they can wait for each other with a cluster-wide barrier. Like the grid, a cluster has a shape, for example (1, 2, 1) for two CTAs side by side, and each CTA can ask for its rank in the cluster, a number from 0 to the cluster size minus 1.
A multicast load uses this: the tile is read from L2 once, and the TMA writes it into the shared memory of several CTAs of the cluster. This is very common in GEMMs, where neighboring CTAs need the same tile of one of the two input matrices. For example, two CTAs that compute output tiles next to each other in the same row both need the same tile of A. Without multicast, both of them read it from L2. With multicast, it is read once, which saves L2 bandwidth.
5.2 The Example
Let's change our example so that two CTAs load the same tile. We keep the grid of tiles and put two CTAs in a cluster side by side, which is a cluster shape of (1, 2). The grid of CTAs gets twice as wide, and cluster (x, y) loads tile (x, y) into both of its CTAs.
I also had to make the tile wider than in section 3. I first tried to multicast our [2, 4] fp32 tiles, and the kernel failed with CUDA_ERROR_MISALIGNED_ADDRESS. We will see in section 5.5 why, but the short answer is that each CTA's piece of the tile has to start on a 128-byte boundary in shared memory. So we use a [6, 64] fp32 matrix and tiles of [2, 32], which makes every row 128 bytes long. As shown in Figure 4, that gives 3 x 2 tiles again, and a grid of 3 x 4 CTAs grouped into 3 x 2 clusters.
5.3 Host Code
CTA_N, CTA_K = 2, 32 # 32 floats = 128 bytes per row
CLUSTER_N, CLUSTER_K = 1, 2 # two CTAs per cluster, side by side
CLUSTER = CLUSTER_N * CLUSTER_K
@cute.jit
def tma_multicast(b: cute.Tensor, out: cute.Tensor):
smem_layout = cute.make_layout((CTA_N, CTA_K), stride=(CTA_K, 1))
# 1. a multicast copy op, and the number of CTAs that share each tile
tma_atom, gB = cpasync.make_tiled_tma_atom(
cpasync.CopyBulkTensorTileG2SMulticastOp(), b, smem_layout,
(CTA_N, CTA_K), num_multicast=CLUSTER,
)
# 2. CLUSTER times as many CTAs as tiles, grouped into clusters
N, K = b.shape
grid = (N // CTA_N * CLUSTER_N, K // CTA_K * CLUSTER_K, 1)
tma_multicast_kernel(tma_atom, gB, smem_layout, out).launch(
grid=grid, block=(32, 1, 1), cluster=(CLUSTER_N, CLUSTER_K, 1)
)
There are only two differences to the host code of the plain load:
- The copy operation is now
CopyBulkTensorTileG2SMulticastOp, and we tellmake_tiled_tma_atomwithnum_multicasthow many CTAs share each tile. (The plainCopyBulkTensorTileG2SOprefuses anynum_multicastother than 1.) As we will see, the atom uses this number to divide the work among the CTAs. - We launch a grid that is twice as wide, and pass the cluster shape to
launch. That's all it takes in CuTe DSL to launch with clusters.
5.4 Device Code
@cute.kernel
def tma_multicast_kernel(tma_atom: cute.CopyAtom, gB: cute.Tensor,
smem_layout: cute.Layout, out: cute.Tensor):
bx, by, _ = cute.arch.block_idx()
tidx, _, _ = cute.arch.thread_idx()
tile_bytes = cute.size_in_bytes(out.element_type, smem_layout)
# 1. same as the load kernel
smem = cutlass.memory.SmemAllocator()
sB = smem.allocate_tensor(out.element_type, smem_layout, 128)
mbar = smem.allocate_array(cutlass.Int64, 1)
# 2. initialize the barrier, then make sure that every CTA in the
# cluster has done so before anyone issues a copy
with cute.arch.elect_one():
cute.arch.mbarrier_init(mbar, 1)
cute.arch.mbarrier_init_fence()
cute.arch.cluster_arrive_relaxed()
cute.arch.cluster_wait()
# 3. the tile belongs to the cluster, so index it by cluster id
cx, cy, _ = cute.arch.cluster_idx()
gTile = cute.local_tile(gB, (CTA_N, CTA_K), (cx, cy))
# 4. partition by this CTA's rank: each CTA gets its share of the tile
rank = cute.arch.block_idx_in_cluster()
tBsB, tBgB = cpasync.tma_partition(
tma_atom, rank, cute.make_layout(CLUSTER),
cute.group_modes(sB, 0, 2), cute.group_modes(gTile, 0, 2),
)
# 5. expect the whole tile, issue our share to every CTA in the mask
mask = cutlass.Int16((1 << CLUSTER) - 1)
with cute.arch.elect_one():
cute.arch.mbarrier_arrive_and_expect_tx(mbar, tile_bytes)
cute.copy(tma_atom, tBgB, tBsB, tma_bar_ptr=mbar, mcast_mask=mask)
cute.arch.mbarrier_wait(mbar, 0)
# 6. every CTA writes out its own copy of the tile
for i in cutlass.range(tidx, cute.size(sB), 32):
out[bx, by, i // CTA_K, i % CTA_K] = sB[i // CTA_K, i % CTA_K]
Most of it is the load kernel again. Here is what changed:
- Shared memory and the mbarrier are allocated as before. Every CTA has its own tile buffer and its own barrier.
- After initializing the barrier, every CTA waits for all the CTAs of the cluster (
cluster_arrive_relaxedfollowed bycluster_wait). This matters now, since another CTA's TMA copy will write into our shared memory and count down our barrier. If the other CTA issued its copy before we had initialized our barrier, its TMA would count down a barrier that hasn't been set up yet. Thembarrier_init_fencebefore it makes the initialization visible to the whole cluster (in the PTX it isfence.mbarrier_init.release.cluster). - The tile now belongs to the cluster and not to the CTA, so we pick it with the cluster's coordinate in the grid,
cluster_idx(), instead of the CTA's. Both CTAs of a cluster get the samegTile. - This is where multicast differs from a plain load. We pass the CTA's rank in the cluster and a layout with one entry per CTA to
tma_partition, and it gives each CTA only its share of the tile to issue. We'll see in a moment which share. - Every CTA arms its own barrier with the bytes of the whole tile, not just its own share, and then issues its share with
mcast_mask. The mask is a 16-bit number with one bit per rank in the cluster, and a set bit means that this CTA receives the data. Here both bits are set (binary 11), so every share goes to both CTAs. If we set only bit 0, the data would only land in CTA 0. - Every CTA writes its copy of the tile to its own slot of the output, so that we can check on the host that both of them received the full tile.
Figure 5 shows what happens for one cluster. The tile has two rows, and the cluster has two CTAs, so CTA 0 issues row 0 and CTA 1 issues row 1. Each of the two copies writes its row into the shared memory of both CTAs.
This explains the byte count in step 5. When a share arrives, the TMA counts down the barrier at the same position in every CTA that receives it. So each CTA's barrier receives the bytes from both copies, 256 in total, and its phase completes only when the whole tile is in that CTA's shared memory. That's why we don't need a cluster-wide barrier after the copy, and why each CTA can simply wait on its own barrier, as in the plain load.
Why split the tile at all instead of letting CTA 0 issue the whole thing? Each SM has its own TMA unit, and if one CTA issued everything, only one of those units would be busy. As far as I can tell, the split exists so that issuing the copies doesn't become the bottleneck, since every CTA's TMA unit now issues a part of the work. (I didn't measure this one.)
The multicast form of the instruction in the PTX looks like this:
cp.async.bulk.tensor.2d.shared::cluster.global.tile
.mbarrier::complete_tx::bytes.multicast::cluster.L2::cache_hint
[smem], [desc, {c0, c1}], [mbar], mask, policy;
Compared with the plain load, the destination is now shared::cluster instead of shared::cta, and the multicast::cluster qualifier adds the mask operand.
Here is the code that runs it and checks that every CTA holds the tile of its cluster:
b = torch.arange(6 * 64, dtype=torch.float32, device="cuda").reshape(6, 64)
out = torch.zeros(3, 4, CTA_N, CTA_K, device="cuda") # one per CTA
tma_multicast(from_dlpack(b, assumed_align=16),
from_dlpack(out, assumed_align=16))
torch.cuda.synchronize()
# CTA (x, y) is in cluster (x, y // 2) and should hold that cluster's tile
tiles = b.reshape(3, 2, 2, 32).permute(0, 2, 1, 3)
print(torch.equal(out, tiles.repeat_interleave(2, dim=1))) # True
5.5 How the Tile Is Split
In Figure 5, I claimed that CTA 0 issues row 0 and CTA 1 issues row 1. You might wonder how I know that, since every CTA's final shared memory looks the same either way. To find out, I ran a variant of the kernel where only one CTA of the cluster issues its copy (the call to cute.copy sits inside if rank == issuer:), every CTA expects only one share's worth of bytes, and shared memory is filled with -1 beforehand. After the wait, whatever is not -1 must have come from the one copy that was issued. When CTA 0 is the only one to issue, row 0 shows up in both CTAs and row 1 stays at -1. When it is CTA 1, it is the other way around.
So, how does CuTe decide which CTA gets which part? It cuts the tile along its slowest-moving dimension, in other words, into pieces that are contiguous in shared memory. Our tile is row-major, so the slowest-moving dimension is the row, and each CTA gets whole rows. If the slowest dimension does not have enough entries for all CTAs, CuTe cuts it completely and continues with the next dimension. I checked both cases with a 2 x 2 cluster (four CTAs), as summarized in Figure 6 below.
As shown in Figure 6, a [4, 32] tile gives one row to each of the four CTAs, and a [2, 64] tile gives each CTA half a row: CTA 0 gets row 0, columns 0 to 31, CTA 1 gets row 0, columns 32 to 63, and so on. In both cases, CTA r issues the r-th contiguous quarter of the tile in shared memory order.
This also explains the error from section 5.2. The TMA requires the shared memory address of every copy to be aligned to 128 bytes. With a [2, 4] fp32 tile, each CTA's share is one row of 16 bytes, so CTA 1's share starts 16 bytes into the buffer, which is not a multiple of 128, and the copy fails with a misaligned address. With [2, 32], each share is 128 bytes and starts on a 128-byte boundary. So, when you pick a tile shape for multicast, make sure that the tile size divided by the cluster size is still a multiple of 128 bytes. (The tiles of a real GEMM are usually large enough that this doesn't come up, but it's good to know where the error comes from when it does.)
6. Summary
To summarize: the TMA is a unit in each SM, since Hopper, that copies tiles of a tensor between global and shared memory on its own, so that the threads don't have to compute addresses or pass the data through registers. In CuTe DSL, using it comes down to a handful of calls:
- On the host,
make_tiled_tma_atombuilds the descriptor from the global tensor and the shared memory layout, and returns a copy atom together with a TMA tensor of coordinates. - In the kernel,
local_tilepicks the tile in that coordinate tensor, andtma_partitioncuts both sides into the shapecute.copyexpects. - A load is
cute.copywith an mbarrier that counts the bytes. Call it from a full warp, since it elects the issuing thread itself, and wait on the barrier's phase. - A prefetch is
cute.prefetchwith the same atom. It needs no shared memory and no barrier, and it does not elect a thread, so wrap it inelect_one(). On the B300, it made a cold load about as fast as an L2 hit. - A multicast load uses the multicast op and
num_multicast, launches with clusters, synchronizes the cluster after the barriers are initialized, and passes each CTA's rank totma_partition. Each CTA issues a contiguous slice of the tile to every CTA in the mask, and each CTA's barrier waits for the whole tile.
From here, the natural next steps are the TMA store, swizzled shared memory layouts, and pipelines that keep several tiles in flight. The tutorials in the CUTLASS repository cover those, and they use exactly the pieces we went through here.
Sources
- CuTe DSL TMA tutorial (tma_v0.py) in the CUTLASS repository
- CuTe DSL API reference: cpasync
- CUTLASS Hopper dense GEMM in CuTe DSL, which uses multicast
- CUDA Programming Guide: Asynchronous Data Copies (TMA)
- PTX ISA: cp.async.bulk.tensor
- NVIDIA Hopper Architecture In-Depth
- NVIDIA Ampere Architecture In-Depth
- Colfax Research: CUTLASS Tutorial on the Hopper TMA