Skip to content
Inference Academy

Async copies, TMA and software pipelining

How modern NVIDIA GPUs keep tensor cores fed: Ampere's cp.async copies global memory straight into shared memory without stalling the threads that issued them, a multi-stage software pipeline overlaps the copy of the next tiles with the maths on the current one, and Hopper's Tensor Memory Accelerator (TMA) moves a whole tile at the request of one thread, tracked by an mbarrier. Two complete programs, checked down to the machine instructions they compile to.

By

Key takeaways

  • In a plain tiled kernel, every K step loads, waits, computes and waits again, so the load latency is paid in full each time. A pipeline keeps several tiles in flight and pays it once.
  • cp.async (Ampere, sm_80) copies global memory to shared memory without going through registers and without blocking the issuing thread; commit groups and wait_prior say which copies must have landed.
  • With S stages, the pipeline needs S tiles of shared memory, which can lower occupancy: more stages are not always faster.
  • TMA (Hopper, sm_90) copies a whole multi-dimensional tile described by a tensor map, at the request of a single thread. An mbarrier counts the bytes, so the other threads simply wait on it.
  • Check that the async path is real: the compiled code should contain LDGSTS for cp.async and UTMALDG for TMA.
30 min · verified 2026-111 animated diagramHands-on labPro
Share

Goal: understand how modern GPUs hide memory latency inside a kernel, write a pipelined matmul with cp.async, and move tiles with Hopper's Tensor Memory Accelerator.

You need: shared-memory tiling, occupancy and latency hiding and tensor cores. To run the programs: an Ampere or newer GPU for the pipeline (an A10G, L4, A100 or any RTX 30 or 40 series card), and an H100 or H200 for TMA. A free Colab T4 compiles and runs the pipeline but cannot show its benefit (see below). The code is in gpu_kernels/cuda/ in the companion repository.

Honest limits. We compiled both programs with nvcc 12.8 (for sm_80 and sm_90a) and checked the compiled machine code for the asynchronous copy instructions, but we have not run them on a GPU for this page, so there are no timings here. Each program checks its own results when you run it. The TMA program follows the TMA example in NVIDIA's CUDA C++ Programming Guide.

#The problem with "load, sync, compute"

The tiled matmul from lesson 2 does this for every tile of K:

sequenceDiagram
  participant W as Warps in a block
  participant M as Global memory
  W->>M: load tile k
  M-->>W: (hundreds of cycles)
  Note over W: __syncthreads
  Note over W: compute tile k
  Note over W: __syncthreads
  W->>M: load tile k+1
  M-->>W: (hundreds of cycles again)

While a tile is loading, the block's warps have nothing to do. Other blocks on the same SM can run in the meantime (that is what occupancy buys), but a big tile uses a lot of shared memory, so few blocks fit, and the GPU spends much of its time waiting. The fix is a software pipeline: start loading tile k+2k+2 before computing tile kk, so by the time a tile is needed, it has already arrived.

Software pipelining: load the next tiles while computing this one
Interactive

Stages

tile 0tile 1tile 2tile 3tile 4tile 5tile 6tile 7■ load (global → shared)■ compute

Synchronous

48

3 stages

20

Speed-up

2.40×

The loads now hide behind compute: the tensor cores, not memory, set the pace.

Eight K tiles. A load takes the load time; compute on tile k starts when tile k has landed and tile k−1 is done. With S stages, tile k+S−1 is issued at the top of iteration k, as in the lesson's kernel. Loads can overlap each other (several are in flight). 1 stage = the synchronous kernel.

#Ampere: cp.async

Before Ampere, a load into shared memory went global memory → register → shared memory, and the thread stalled until the value reached the register. Ampere (sm_80) added cp.async: an instruction that copies global memory directly into shared memory and returns immediately. The thread keeps going and later asks whether its copies have landed.

The CUDA primitives (in <cuda_pipeline.h>) are:

Primitive What it does
__pipeline_memcpy_async(dst, src, bytes) Start a copy of 4, 8 or 16 bytes into shared memory
__pipeline_commit() Close the current group of copies
__pipeline_wait_prior(N) Wait until at most N of this thread's committed groups are still pending

The waits are per thread: a thread knows only that its own copies landed. Before reading a tile that other threads copied, a __syncthreads() is still needed.

#A three-stage pipelined matmul

The program below has two kernels with identical maths: 64 × 64 output tiles, K tiles of 16, 256 threads each computing 4 × 4 outputs in registers. tiled_sync loads the usual way; tiled_pipelined keeps three stages of tiles in shared memory.

gpu_kernels/cuda/pipelined_matmul.cu · MIT licensed, on GitHub

cpp
// A shared-memory tiled matmul, then the same kernel with a multi-stage cp.async pipeline.
//
//   nvcc -O3 -std=c++17 -arch=sm_80 pipelined_matmul.cu -o pipelined_matmul && ./pipelined_matmul
//
// Both kernels compute C = A x B in float32 with 64x64 output tiles, K tiles of 16 and
// 4x4 outputs per thread (256 threads). The only difference is how tiles reach shared memory:
//   tiled_sync:      every thread loads, waits (__syncthreads), computes, waits again.
//   tiled_pipelined: copies for tile k+STAGES-1 are issued with cp.async while tile k is
//                    computed, so memory latency hides behind arithmetic.
// cp.async needs compute capability 8.0 (Ampere) or newer for real asynchrony; on older GPUs
// the same code compiles but the copies are synchronous, so expect no gain on a T4.
#include <cuda_pipeline.h>
#include <cstdio>
#include <cstdlib>
#include <vector>

constexpr int BM = 64, BN = 64, BK = 16, THREADS = 256, STAGES = 3;

__device__ inline void compute_tile(const float (*As)[BK], const float (*Bs)[BN], float acc[4][4]) {
  const int ty = threadIdx.x / 16, tx = threadIdx.x % 16;
#pragma unroll
  for (int k = 0; k < BK; ++k) {
    float a[4], b[4];
#pragma unroll
    for (int i = 0; i < 4; ++i) a[i] = As[ty * 4 + i][k];
#pragma unroll
    for (int j = 0; j < 4; ++j) b[j] = Bs[k][tx * 4 + j];
#pragma unroll
    for (int i = 0; i < 4; ++i)
#pragma unroll
      for (int j = 0; j < 4; ++j) acc[i][j] += a[i] * b[j];
  }
}

__device__ inline void store_tile(float* C, int N, float acc[4][4]) {
  const int ty = threadIdx.x / 16, tx = threadIdx.x % 16;
  const int row0 = blockIdx.y * BM + ty * 4, col0 = blockIdx.x * BN + tx * 4;
  for (int i = 0; i < 4; ++i)
    for (int j = 0; j < 4; ++j) C[(size_t)(row0 + i) * N + col0 + j] = acc[i][j];
}

// Requires M % 64 == 0, N % 64 == 0, K % 16 == 0 (kept simple on purpose).
__global__ void tiled_sync(const float* A, const float* B, float* C, int M, int N, int K) {
  __shared__ __align__(16) float As[BM][BK];
  __shared__ __align__(16) float Bs[BK][BN];
  const int t = threadIdx.x;
  float acc[4][4] = {};
  for (int k0 = 0; k0 < K; k0 += BK) {
    // each thread loads one float4 of A (64x16 tile) and one float4 of B (16x64 tile)
    *reinterpret_cast<float4*>(&As[t / 4][(t % 4) * 4]) =
        *reinterpret_cast<const float4*>(&A[(size_t)(blockIdx.y * BM + t / 4) * K + k0 + (t % 4) * 4]);
    *reinterpret_cast<float4*>(&Bs[t / 16][(t % 16) * 4]) =
        *reinterpret_cast<const float4*>(&B[(size_t)(k0 + t / 16) * N + blockIdx.x * BN + (t % 16) * 4]);
    __syncthreads();                 // tile is in shared memory
    compute_tile(As, Bs, acc);
    __syncthreads();                 // everyone is done before the tile is overwritten
  }
  store_tile(C, N, acc);
}

__global__ void tiled_pipelined(const float* A, const float* B, float* C, int M, int N, int K) {
  __shared__ __align__(16) float As[STAGES][BM][BK];
  __shared__ __align__(16) float Bs[STAGES][BK][BN];
  const int t = threadIdx.x;
  const int ktiles = K / BK;

  auto issue = [&](int stage, int kt) {  // start (not finish) the copies for K tile kt
    const int k0 = kt * BK;
    __pipeline_memcpy_async(&As[stage][t / 4][(t % 4) * 4],
                            &A[(size_t)(blockIdx.y * BM + t / 4) * K + k0 + (t % 4) * 4], 16);
    __pipeline_memcpy_async(&Bs[stage][t / 16][(t % 16) * 4],
                            &B[(size_t)(k0 + t / 16) * N + blockIdx.x * BN + (t % 16) * 4], 16);
  };

  // Prologue: put STAGES-1 tiles in flight. Commit even when there is nothing to copy, so
  // the number of committed groups stays in step with the loop below.
  for (int s = 0; s < STAGES - 1; ++s) {
    if (s < ktiles) issue(s, s);
    __pipeline_commit();
  }

  float acc[4][4] = {};
  for (int kt = 0; kt < ktiles; ++kt) {
    __pipeline_wait_prior(STAGES - 2);  // this thread's copies for tile kt have landed
    __syncthreads();                    // ...and everyone else's; also, tile kt-1 is no longer being read
    const int next = kt + STAGES - 1;   // refill the stage that tile kt-1 used
    if (next < ktiles) issue(next % STAGES, next);
    __pipeline_commit();
    compute_tile(As[kt % STAGES], Bs[kt % STAGES], acc);
  }
  store_tile(C, N, acc);
}

#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() {
  const int M = 2048, N = 2048, K = 2048;
  std::vector<float> hA((size_t)M * K), hB((size_t)K * N), hC((size_t)M * N);
  srand(0);
  for (auto& v : hA) v = rand() / (float)RAND_MAX - 0.5f;
  for (auto& v : hB) v = rand() / (float)RAND_MAX - 0.5f;

  float *A, *B, *C;
  CHECK(cudaMalloc(&A, hA.size() * 4)); CHECK(cudaMalloc(&B, hB.size() * 4)); CHECK(cudaMalloc(&C, hC.size() * 4));
  CHECK(cudaMemcpy(A, hA.data(), hA.size() * 4, cudaMemcpyHostToDevice));
  CHECK(cudaMemcpy(B, hB.data(), hB.size() * 4, cudaMemcpyHostToDevice));

  dim3 grid(N / BN, M / BM);
  cudaEvent_t e0, e1;
  CHECK(cudaEventCreate(&e0)); CHECK(cudaEventCreate(&e1));
  const char* names[2] = {"tiled_sync", "tiled_pipelined"};
  for (int which = 0; which < 2; ++which) {
    auto run = [&] {
      if (which == 0) tiled_sync<<<grid, THREADS>>>(A, B, C, M, N, K);
      else tiled_pipelined<<<grid, THREADS>>>(A, B, C, M, N, K);
    };
    run(); CHECK(cudaDeviceSynchronize());            // warm-up
    CHECK(cudaEventRecord(e0));
    for (int r = 0; r < 20; ++r) run();
    CHECK(cudaEventRecord(e1)); CHECK(cudaEventSynchronize(e1));
    float ms; CHECK(cudaEventElapsedTime(&ms, e0, e1)); ms /= 20;

    CHECK(cudaMemcpy(hC.data(), C, hC.size() * 4, cudaMemcpyDeviceToHost));
    double max_err = 0;                                // check 256 random entries on the CPU
    for (int s = 0; s < 256; ++s) {
      int i = rand() % M, j = rand() % N; double ref = 0;
      for (int k = 0; k < K; ++k) ref += (double)hA[(size_t)i * K + k] * hB[(size_t)k * N + j];
      max_err = fmax(max_err, fabs(ref - hC[(size_t)i * N + j]));
    }
    printf("%-16s %8.3f ms  %7.0f GFLOP/s  max error %.2e\n", names[which], ms,
           2.0 * M * N * K / ms / 1e6, max_err);
  }
  return 0;
}

The rest is Pro

Keep reading this full lab

Pro unlocks this full lab, 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?

Sandip MaityBuilt by Sandip Maity, who runs self-hosted LLM inference in production.

Not ready? Keep learning free

Or follow the free roadmap →

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

  1. Hopper: the Tensor Memory Accelerator
  2. What you can now do
  3. Common mistakes
  4. Exercise
  5. Going deeper

You will be able to answer

  • A pipelined kernel has 3 stages and has committed 2 groups of copies before its main loop. At iteration k it calls __pipeline_wait_prior(1). What does that guarantee?
  • Why does the pipelined kernel commit a group even when it has nothing left to copy?
  • In the TMA kernel, why does only thread 0 issue the copy, while every thread waits on the barrier?
  • Your 3-stage pipelined kernel runs no faster than the synchronous one on a T4. What is the most likely reason?