Skip to main content

Writing CUDA Kernels from Scratch, Part 2: Tensor Cores and Flash Attention

CUDAGPU ProgrammingTensor CoresFlash AttentionMatrix MultiplicationPTXPerformance OptimizationDeep Learning
Writing CUDA Kernels from Scratch, Part 2: Tensor Cores and Flash Attention
This post continues Writing CUDA Kernels from Scratch: A Beginner's Guide. Part 1 covered threads and blocks, shared-memory tiling and register blocking for matrix multiplication. If those terms are new, start there.

Part 1 ended with a register-blocked matmul kernel that was 3.5× faster than my naive one and still well behind cuBLAS. This post picks up from there, in Tensorax, the deep learning framework I'm writing from scratch in C++ and CUDA. It covers two things:

  • Finishing the matmul: block tiling, then my first kernel on Tensor Cores, using inline PTX assembly.
  • Attention: five kernels from naive to Flash-Attention-style, then the optimizations that took the Tensor Core version from 16.2 ms to 1.31 ms.

The best result: on one configuration, my attention kernel reaches 24.7 TFLOPS, 0.79× of cuDNN (PyTorch's fused attention). On most configurations it's 2–5× slower. I'll show both, and the mistakes in my own measurements I had to correct along the way.

Setup, and how things were measured

Everything runs on an RTX 3070 Ti Laptop GPU (Ampere, sm_86). The numbers come from two kinds of measurement, and they shouldn't be mixed:

  • Kernel time from Nsight Systems: GPU time for one launch after three warm-up launches. This is the kernel alone.
  • End-to-end time from the benchmark scripts: wall-clock time over many runs, including the Python wrapper, output allocation and synchronization.

The numbers in Part 1 came from an older version of the benchmark, so compare numbers within this post, not across the two posts.

Part A: Finishing the matmul

Block tiling: more outputs per thread

Part 1's last idea was register blocking: each thread computes several outputs and keeps operands in registers to reuse them. Block tiling pushes that further.

  • 1D block tiling: each thread computes 8 outputs in a column. One value read from shared memory feeds 8 multiply-adds instead of 1.
  • 2D block tiling: each thread computes a 4×4 tile of outputs. It loads 4 values of A and 4 of B into registers and does all 16 multiply-adds between them, an outer product.

Kernel time for each variant (Nsight Systems, 1024×1024×1024 fp32, one launch):

KernelKernel timevs naive
naive2.51 ms1.00×
smem coalesced2.50 ms1.01×
shared-memory cache blocking1.93 ms1.30×
tiled1.48 ms1.70×
1D block tiling624 µs4.03×
2D block tiling484 µs5.20×

One honest note: "smem coalesced" performs exactly like naive because, despite its name, it never actually uses the shared-memory load. It has the same inner loop with a different thread layout. Each real step after that adds operand reuse, and the speedup follows the reuse.

Tensor Cores

Everything so far runs on the GPU's normal CUDA cores, one multiply-add per instruction. Ampere GPUs also have Tensor Cores: units that multiply small matrices in a single instruction. A warp (32 threads) issues one mma.sync, and the hardware computes a whole 16×8 output tile.

There's no friendly C++ API for the exact form I wanted, so the kernel uses inline PTX, NVIDIA's GPU assembly. This is the wrapper from matmul.cu:

1__device__ __forceinline__ void mma_m16n8k8_tf32(
2    float d[4], const float a[4], const float b[2], const float c[4]) {
3    // TF32 inputs travel as 32-bit registers; the hardware keeps
4    // only 10 mantissa bits when it multiplies.
5    uint32_t a0 = __float_as_uint(a[0]), a1 = __float_as_uint(a[1]);
6    uint32_t a2 = __float_as_uint(a[2]), a3 = __float_as_uint(a[3]);
7    uint32_t b0 = __float_as_uint(b[0]), b1 = __float_as_uint(b[1]);
8    asm volatile(
9        "mma.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32 "
10        "{%0, %1, %2, %3}, {%4, %5, %6, %7}, {%8, %9}, {%10, %11, %12, %13};\n"
11        : "=f"(d[0]), "=f"(d[1]), "=f"(d[2]), "=f"(d[3])
12        : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1),
13          "f"(c[0]), "f"(c[1]), "f"(c[2]), "f"(c[3]));
14}

m16n8k8 means one instruction multiplies a 16×8 tile of A by an 8×8 tile of B and adds the result into a 16×8 tile of C. The inputs are TF32: fp32 numbers with the mantissa cut to 10 bits. That's less precise than fp32, which is the price of using Tensor Cores on fp32 data.

The kernel around it gives each block a 128×128 tile of C, split across 4 warps that each own a 64×64 piece. Every 16 columns of K, the block loads tiles of A and B into shared memory with float4 loads, and each warp runs 4 × 8 × 2 = 64 mma.sync calls on them.

Matmul end-to-end time (3 × 1024×1024 fp32, 100 runs, lower is better)
00.601.201.802.40s2.03NumPyCPU1.25naive1.25smemcoalesced1.06cacheblocking0.93tiled0.761D blocktiling0.632D blocktiling0.52MMATF320.09cuBLAS

End to end, the Tensor Core kernel takes 0.52 s for 100 runs (about 1.24 TFLOPS) against 0.63 s for 2D block tiling. cuBLAS takes 0.09 s (about 7.4 TFLOPS), so my best matmul is still roughly 6× slower. The kernel is missing things cuBLAS-class kernels rely on: it loads each tile synchronously with two block-wide barriers per step instead of prefetching the next tile while computing, and it reads Tensor Core fragments straight from shared memory without ldmatrix. Those are the next steps. The attention kernel below uses both, which is part of why it got further.

Part B: Attention

Scaled dot-product attention, as defined in the Transformer paper:

Attention(Q, K, V) = softmax(QKT√dk) V

Read inside out, that's four steps. A straightforward implementation, like eager PyTorch, runs each one as a separate kernel:

  1. QKᵀ: score every query against every key, giving an S×S score matrix per head.
  2. ÷ √d_k: scale every score.
  3. softmax: for each row, subtract the max, exponentiate, and divide by the sum, turning scores into weights.
  4. × V: take the weighted sum of the value rows.

TL;DR The two matrix multiplies do 98% of attention's math and keep the GPU busy. The scale and the softmax do under 2% of the math but take about 44% of the time, because they move a 537 MB score matrix through memory for a few operations per score. So the softmax is the part to fix, by making fewer trips to memory rather than doing fewer FLOPs. My first kernel used a naive three-pass softmax, and switching to a one-pass online softmax made it 2.8× faster.

Skip the profiling and jump to "Online softmax: three passes become one" ↓

Two terms come up a lot from here on, so here they are in plain language first. Think of a GPU as a very fast cook with a pantry down the hall:

Compute-bound
The cook is the bottleneck. Ingredients arrive faster than they can be chopped, so the kitchen is always busy cooking. To go faster, you need a faster cook or less cooking. Big matrix multiplies are like this: each number fetched gets used in thousands of multiplications.
Memory-bound
The trips to the pantry are the bottleneck. Each ingredient gets one quick chop, then the cook waits for the next one. A faster cook changes nothing. To go faster, you need fewer trips. The softmax is like this: it fetches each score, does one or two operations, and writes it back.

Which one a step is decides what's worth optimizing: making a memory-bound step do less math won't speed it up, but making fewer trips to memory will. The profile below puts numbers on this.

Profile of each step

Every kernel does two things: math, and moving data between the GPU's memory (DRAM) and its cores. Which one limits it depends on its arithmetic intensity: how many floating-point operations it does per byte it moves.

Arithmetic intensity (AI) = FLOPs ÷ bytes moved to and from memory.
A kernel can't finish faster than its math takes at peak compute, or faster than its data takes at full memory bandwidth, so its time is roughly the larger of the two. For the estimates below I use an NVIDIA A100 (40 GB): 19.5 TFLOPS in fp32 and 1,555 GB/s of HBM bandwidth. Dividing one by the other, it needs about 12.5 FLOPs per byte to keep its cores busy. Above that, a kernel is compute-bound. Below it, the kernel is memory-bound: its time is set by the bytes it moves, not the math it does.

Take a typical head size: B=4, H=8, S=2048, d_k = d_v = 64, in fp32. The score matrix is 32 heads × 2048 × 2048 × 4 bytes = 537 MB, and every step after QKᵀ reads it and writes it back:

StepCompute (FLOPs)HBM trafficAI (FLOP/B)BottleneckEst. time (A100)
1. QKᵀ17.18 GFLOP (2BHS²d_k)570.43 MB (read Q, K; write P)30.1Compute-bound (0.88 ms compute vs 0.37 ms memory)0.88 ms
2. ÷ √d_k0.13 GFLOP (BHS²)1,073.74 MB (read P; write P′)0.125Memory-bound (0.01 ms compute vs 0.69 ms memory)0.69 ms
3. softmax0.54 GFLOP (≈ 4BHS²)1,073.74 MB (read P′; write A)0.50Memory-bound (0.03 ms compute vs 0.69 ms memory)0.69 ms
4. × V17.18 GFLOP (2BHS²d_k)570.43 MB (read A, V; write O)30.1Compute-bound (0.88 ms compute vs 0.37 ms memory)0.88 ms
Total35.03 GFLOP3,288.34 MB (3.29 GB)10.7Mixed3.14 ms

Why each step lands where it does:

  • QKᵀ is compute-bound (AI 30.1). Each element of Q and K is loaded once and used in 2,048 dot products, so there's a lot of math per byte. Most of its traffic is writing the 537 MB score matrix, and that's what caps its AI at roughly d_k/2 ≈ 32. That's still above 12.5, so the math takes longer than the memory (0.88 vs 0.37 ms).
  • ÷ √d_k is memory-bound (AI 0.125). One multiply per score, against 4 bytes read and 4 bytes written. It's 100× below the ridge point: the math would take 0.01 ms, but moving 1.07 GB takes 0.69 ms.
  • softmax is memory-bound (AI 0.50). About 4 operations per score (max, subtract and exponentiate, sum, divide) for the same 8 bytes. A 2,048-score row fits on chip, so each score is read once and written once, and that's still 25× below the ridge point: 0.03 ms of math, 0.69 ms of memory.
  • × V is compute-bound (AI 30.1). The mirror image of QKᵀ: each weight in A is used for 64 output columns and each row of V for 2,048 queries. Reading the 537 MB weight matrix dominates the traffic, and the AI again comes out near d_k/2.
Standard attention, step by step (B=4, H=8, S=2048, d_k=64, fp32, A100)
Share of FLOPsscale + softmax: 1.9%
49.0%
49.0%
QKᵀ: 49.0%÷ √d_k: 0.38%softmax: 1.5%× V: 49.0%
Share of time (estimated)scale + softmax: 44%
28.0%
22.0%
22.0%
28.0%
QKᵀ: 28.0%÷ √d_k: 22.0%softmax: 22.0%× V: 28.0%

FLOPs and bytes counted exactly; times are roofline estimates on an A100 (40 GB), each step as its own kernel, taking the larger of compute time and memory time. Not measured.

Arithmetic intensity of each step on an A100 (FLOPs per byte, log scale)
0.1110100QKᵀ30.1× V30.1softmax0.5÷ √d_k0.125compute-bound at12.5

The two matmuls do 98% of the FLOPs, and they're compute-bound: the GPU spends their time doing math, which is what it's built for. The scale and the softmax do under 2% of the FLOPs but take 44% of the time, and almost all of it is spent waiting on memory. Per FLOP, the softmax costs about 25× more time than a matmul. Even with the scale folded into the QKᵀ kernel, as many implementations do, the softmax alone is still over a quarter of the time.

Head size shifts the balance. The matmuls' cost per score grows with d_k, and the softmax's doesn't. At d_k = 64 the element-wise steps are 44% of the time. At d_k = 512, the journal's reference workload below, the matmuls dominate.

So the softmax is the step worth optimizing, and the goal isn't fewer FLOPs. It's fewer bytes: keep the scores on chip instead of writing a 537 MB matrix and reading it back. That's the idea behind Flash Attention. My kernels get there in stages, and the first stage is the softmax itself.

The naive softmax: where the time goes

Naive softmax computes softmax(x)ᵢ = exp(xᵢ − max) / Σ exp(xⱼ − max) directly, in three passes over the scores: (1) find the max, (2) sum the exponentials, (3) divide each exponential by the sum. Each pass needs the previous pass's result: the exponentials need the final max (subtracting it keeps exp from overflowing), and the division needs the final sum. So as written, the passes can't be merged.

TL;DR Naive softmax touches every score four times: it reads the score matrix three times and writes it once. Each pass does only one or two operations per score, so all three passes are memory-bound, and the math is about 2.5% of the time. The cost is set by how many times the matrix crosses the memory bus, not by how many FLOPs it does. In my attention kernel the three passes are even worse, because each one recomputes every Q·K dot product. Online softmax merges the passes.

Skip the profiling and jump to "Online softmax: three passes become one" ↓

Profile of the naive softmax, pass by pass

Take the same score matrix as before: 537 MB on the same A100, and run the naive softmax over it as written, with each pass a sweep through memory. As in the attention table, subtract-and-exponentiate counts as one operation:

PassCompute (FLOPs)HBM trafficAI (FLOP/B)BottleneckEst. time (A100)
1. find the max0.13 GFLOP (BHS²)536.87 MB (read S)0.25Memory-bound (0.007 ms compute vs 0.35 ms memory)0.35 ms
2. sum of exponentials0.27 GFLOP (2BHS²)536.87 MB (read S)0.50Memory-bound (0.014 ms compute vs 0.35 ms memory)0.35 ms
3. normalize0.27 GFLOP (2BHS²)1,073.74 MB (read S; write P)0.25Memory-bound (0.014 ms compute vs 0.69 ms memory)0.69 ms
Total0.67 GFLOP2,147.48 MB (2.15 GB)0.31Memory-bound1.38 ms

Why each pass lands where it does:

  • Pass 1 is memory-bound (AI 0.25). One comparison per score, against a 4-byte read. That's 50× below the ridge point: the comparisons would take 0.007 ms, but reading 537 MB takes 0.35 ms.
  • Pass 2 is memory-bound (AI 0.50). A subtract-and-exponentiate and an add per score, for the same 4 bytes. The exponential sounds expensive, but GPUs compute it on dedicated special-function units, so the pass is still 25× below the ridge point. It waits on memory just like pass 1.
  • Pass 3 is memory-bound (AI 0.25). It recomputes each exponential and divides it by the sum: two operations per score again, but now it reads 4 bytes and writes 4 bytes. Twice the traffic of the other passes, so twice the time.
Naive softmax, pass by pass (537 MB score matrix, fp32, A100)
Share of FLOPs0.67 GFLOP in total
20.0%
40.0%
40.0%
pass 1: max: 20.0%pass 2: sum of exp: 40.0%pass 3: normalize: 40.0%
Share of time (estimated)math: 2.5% of the time
25.0%
25.0%
50.0%
pass 1: max: 25.0%pass 2: sum of exp: 25.0%pass 3: normalize: 50.0%

FLOPs and bytes counted exactly; times are roofline estimates on an A100 (40 GB), each pass as one sweep through memory, taking the larger of compute time and memory time. Not measured.

Arithmetic intensity of each pass on an A100 (FLOPs per byte, log scale)
0.1110100pass 2: sum of exp0.5pass 1: max0.25pass 3: normalize0.25whole softmax0.31compute-bound at12.5

Every pass is memory-bound, so the FLOPs barely matter: the math is about 0.035 ms of the 1.38 ms. What matters is how many times the score matrix crosses the memory bus. Naive softmax reads it three times and writes it once, which is 2.15 GB of traffic for a 537 MB matrix.

That's also why the softmax in the attention table took 0.69 ms: that number assumes each 2,048-score row stays on chip, so every score is read once and written once. Written as three passes over memory, the same softmax takes twice as long. Each pass removed saves a full 537 MB read, which makes the number of passes the thing to attack.

The same three passes inside my attention kernel

My first attention kernel fuses all four steps into one and never writes the score matrix to memory. Instead, it stores no scores at all, and pays for that elsewhere. It runs the naive softmax with one thread per output element: one query row × one of the d_v output columns. Since it keeps no scores, every one of the three passes recomputes every Q·K dot product:

1// one thread = one (query row, output column); condensed from attn.cu
2float m = -FLT_MAX;                                  // pass 1: row max
3for (int j = 0; j < S; j++) m = fmaxf(m, dot(q, K[j]) * scale);
4
5float l = 0.0f;                                      // pass 2: sum of exps
6for (int j = 0; j < S; j++) l += expf(dot(q, K[j]) * scale - m);
7
8float out = 0.0f;                                    // pass 3: normalize, x V
9for (int j = 0; j < S; j++)
10    out += expf(dot(q, K[j]) * scale - m) / l * V[j][col];

On the reference workload (B=4, H=8, S=256, d_k = d_v = 512) that's 4.2 million threads, each computing 256 dot products of length 512 (1,024 FLOPs each) per pass.

Profile of the naive attention kernel

The kernel has five sections, and my section profiler, benchmarks/profile_sections.py, uses the same names. Here's the work in each one:

Kernel sectionPer threadTotal workShare
Setup: index math, pointersa few integer ops~0~0%
Softmax pass 1: find the row max256 dot products1,100 GFLOP33.3%
Softmax pass 2: sum of exponentials256 dot products, 256 exp1,100 GFLOP + 1.1 G exp33.3%
Softmax pass 3: normalize, multiply by V256 dot products, 256 exp, 256 divides1,102 GFLOP + 1.1 G exp33.4%
Write the output1 store4.2 M stores~0%
Total executed~3,300 GFLOP100%
Actually needed (Q·Kᵀ and P·V once)4.3 GFLOP0.13%
Naive attention kernel: where the work goes
By kernel sectionsoftmax passes: >99.9%
33.3%
33.3%
33.4%
setup: ~0%softmax pass 1: max: 33.3%softmax pass 2: sum of exp: 33.3%softmax pass 3: normalize, ×V: 33.4%write output: ~0%
By causecaused by the 3-pass softmax: 66.5%
66.5%
33.2%
Q·K redone in softmax passes 2 and 3: 66.5%Q·K redone by each of 512 output columns: 33.2%softmax math (max, scale, sum, divide): 0.19%Q·Kᵀ and P·V, needed once: 0.13%

Shares of executed floating-point work, counted from the kernel source; the 2.1 billion exponentials are on top. The measured total for this kernel is 3.02 s, about 1 s per pass.

Split by cause instead of by section, the softmax's own math (max, scale, sum, divide) is only about 0.2% of the work. Almost everything else is Q·K recomputed:

  • Two-thirds: recomputed in passes 2 and 3. This is the price of the three-pass shape, and it's what online softmax removes.
  • One-third: recomputed by each of the 512 output columns. The threads that share a query row each compute that row's scores again. That's the thread layout, and it's the fix after online softmax.

Together, every score is computed 1,536 times, about 770× more arithmetic than attention needs. The GPU isn't idle: it runs over a trillion floating-point operations per second, almost all of them redundant.

Online softmax: three passes become one

Online softmax breaks the two dependencies behind the three passes by keeping running values and correcting them when they turn out to be wrong.

For a plain softmax over a matrix, online softmax keeps two running values per row: the max m and the sum l. When a new score raises the max, the sum so far was computed against a max that was too small, so it gets multiplied by exp(m_old − m_new) to move it onto the new scale. That folds passes 1 and 2 into one:

1// pass 1: max and sum together
2float m = -FLT_MAX, l = 0.0f;
3for (int j = 0; j < S; j++) {
4    float new_m = fmaxf(m, x[j]);
5    l = l * expf(m - new_m) + expf(x[j] - new_m);   // rescale the old sum
6    m = new_m;
7}
8// pass 2: normalize
9for (int j = 0; j < S; j++) p[j] = expf(x[j] - m) / l;

On the same 537 MB score matrix and the same A100:

Naive softmaxOnline softmax
Passes over memory3 reads, 1 write2 reads, 1 write
HBM traffic2,147 MB1,611 MB
Operations per score5up to 7
AI (FLOP/B)0.310.58
Est. time (A100)1.38 ms1.04 ms

Online softmax does more math, up to 7 operations per score instead of 5, because of the extra exponential and multiply for the rescale. It's still faster, 1.04 ms instead of 1.38 ms, because it moves 25% fewer bytes. On a memory-bound kernel, extra FLOPs are nearly free, and every pass you remove saves a full trip through memory.

Attention goes one step further. The softmax weights are only ever used to multiply V, so the normalize pass can be folded in too: keep a running output acc next to m and l, rescale it with the same factor, and divide by l once at the very end. That's how three passes become one. This is the loop from my tiled kernel:

1float m = -FLT_MAX, l = 0.0f, acc = 0.0f;
2for (int j = 0; j < S; j++) {
3    float score   = dot(q, K[j]) * scale;     // computed once per key
4    float new_m   = fmaxf(m, score);
5    float exp_old = expf(m - new_m);          // rescales everything so far
6    float exp_new = expf(score - new_m);
7    acc = acc * exp_old + exp_new * V[j][col];
8    l   = l   * exp_old + exp_new;
9    m   = new_m;
10}
11out = acc / l;                                // normalize once, at the end

The correction is cheap compared with what it replaces. Per key, per thread:

Naive softmax (3 passes)Online softmax (1 pass)
Q·K dot products3 × 1,024 FLOPs1 × 1,024 FLOPs
Exponentials22
Other math3 scales, a divide, a multiply-adda scale, 5 multiplies and adds
Total~3,080 FLOPs + 2 exp~1,030 FLOPs + 2 exp

Keeping the running values correct costs a few extra multiplies per key. Not recomputing the scores saves two 1,024-FLOP dot products per key. That predicts about a 3× speedup. The tiled kernel does exactly this, and also stages K and V in shared memory: it measures 1.09 s against naive's 3.02 s, 2.8×. The output is the same as the naive three-pass softmax, up to floating-point rounding. Only the order of operations changes.

Computing each score once

Online softmax removed the 3× from the passes, but not the 512×. The tiled kernel still runs one thread per output column, and each one recomputes the same dot products, so it still executes about 1,100 GFLOP for 4.3 GFLOP of real work.

The flash kernel changes the mapping. One thread per query row computes each score once, keeps the block of scores in shared memory, and reuses them for all 512 output columns. That brings the arithmetic down to about what attention needs, and the time from 1.09 s to 97.6 ms.

This is Flash Attention

That structure has a name. Flash Attention (Dao et al., 2022) combines three ideas, and by now all of them have come up:

  • Tiling: load a block of queries and stream K and V through on-chip shared memory, block by block.
  • Online softmax: keep the running max, sum and output for each query row, and rescale them when a new block raises the max.
  • No score matrix: scores are produced, used and thrown away on chip. The 537 MB matrix is never written to memory.

That last point is the goal from the profile at the start: fewer bytes, not fewer FLOPs. Here's the same A100 example (B=4, H=8, S=2048, d_k = 64, fp32) done the flash way, with 64 query rows per block like my kernel:

Standard attentionFlash Attention
Score matrix in HBMwritten and read backnever
Compute (FLOPs)35.03 GFLOP34.9 GFLOP
HBM traffic3,288 MB~1,107 MB
AI (FLOP/B)10.7~31.5
BottleneckMixedCompute-bound
Est. time (A100)3.14 ms1.79 ms

The traffic is now just Q and O once (17 MB each), plus K and V (34 MB together) read once by each of the 32 query blocks. The whole kernel becomes compute-bound, and 1.79 ms is essentially the time of the two matmuls alone: the softmax has gone from 44% of the time to nearly free. (Roofline estimate, not measured, and it ignores K/V hits in L2, which would lower the traffic further.)

Two follow-ups matter for the rest of this post. FlashAttention-2 (Dao, 2023) splits each block's query rows across warps and trims the non-matmul work, for example by dividing by the sum only once at the end. My kernels use both. FlashAttention-3 (Shah et al., 2024) targets Hopper GPUs and their dedicated copy and async-matmul hardware, which my Ampere GPU doesn't have.

My flash kernel has the right structure but runs on CUDA cores. The remaining kernels make the same work run faster rather than doing less of it:

  • flash optimized: float4 loads, warp-shuffle reductions and a lazy max update. 15.0 ms.
  • MMA: Q·Kᵀ and P·V on Tensor Cores, fp16 multiply with fp32 accumulate. 10.1 ms with fp32 inputs, 4.7 ms with fp16 inputs (see below).
Attention kernels, end-to-end (B=4, H=8, S=256, d=512, log scale)
0.1 ms1 ms10 ms100 ms1 s10 snaive3.02 stiled1.09 sflash97.6 msflash optimized15 msMMA, fp32 in10.1 msMMA, fp16 in4.7 msPyTorch fp321.3 msPyTorch fp160.25 ms

From the journal's summary after the switch to fp16 inputs. PyTorch here is cuDNN's fused attention.

From naive to the fp16 Tensor Core kernel is a 640× speedup. PyTorch's fp16 attention was still 19× faster. The rest of the post is about that gap.

The optimization journal

The first correct Tensor Core kernel took 16.2 ms. I kept a journal in the repo for every change I tried. Below are only the ones that worked and stayed. The workload is B=4, H=8, S=256, d=512 throughout, and run-to-run noise was about ±5–10%.

Tensor Core attention, change by change: time per call (lower is better)
04.59.013.518.0ms16.2start12.7cp.async10.74warps8.4O inregs4.7fp16inputs4.1split-Q3.7lazyrescale2.0template1.31.trans0.29cuDNN

B=4, H=8, S=256, d=512. The first four bars use fp32 inputs, the rest fp16. The timing method changed a few times over the journal, so read the bars as a trend, not side-by-side runs. cuDNN is shown for reference.

1. Moving data less

  • Double-buffered cp.async: load the next K/V chunk while the Tensor Cores work on the current one. 16.2 → 12.7 ms.
  • Four warps on P·V: split the output columns across 4 warps instead of 1. 12.7 → 10.7 ms.
  • Output in registers: accumulate straight into the mma.sync result instead of reading and writing the output tile in shared memory on every block. 10.7 → 8.4 ms.

2. fp16 inputs

The Tensor Cores already multiplied in fp16, so fp32 inputs were being converted chunk by chunk in shared memory. Taking fp16 inputs adds no new rounding and drops that conversion, the same way inference stacks keep the KV cache in fp16. Measured side by side: 10.1 → 4.7 ms. From here I compare against PyTorch's fp16 attention (0.25 ms).

3. Every warp runs every phase (split-Q)

Q·Kᵀ and softmax were still running on warp 0 only. Following Flash Attention 2, each block now takes 64 query rows, 16 per warp, and all four warps run every phase on their own rows. Softmax moves fully into registers: the row max and sum are combined with __shfl_xor_sync, and the probabilities go straight into the next Tensor Core instruction. 4.7 → 4.1 ms.

Before: warp 0 does QKᵀ + softmaxwarp 0QKᵀ for all 16 rowswarp 1idle, waiting at __syncthreadswarp 2idle, waiting at __syncthreadswarp 3idle, waiting at __syncthreadsAfter: split-Q across 4 warpswarp 0QKᵀ on rows 0–15warp 1QKᵀ on rows 16–31warp 2QKᵀ on rows 32–47warp 3QKᵀ on rows 48–63QKᵀsoftmaxP·V

Before: only warp 0 computed QKᵀ and softmax for the block while three warps waited. After (split-Q): each warp owns 16 query rows and all four run every phase.

4. Reading what the compiler produced

A lazy rescale (only rescale the output when the running max grows past a threshold) took it to 3.7 ms. Then nvcc -Xptxas=-v showed the real problem:

1sdpa_kernel_mma_fp16:
2  40 registers / thread
3  1024 bytes stack frame, 0 spill stores, 0 spill loads

The 1024-byte stack frame was exactly the output accumulator. Because the loop over output chunks had a runtime bound, the compiler had put the whole array in local memory. Making the chunk count a template parameter gives every loop a compile-time bound:

1template <int DV_CHUNKS>           // d_v / 16, chosen at launch
2__global__ void sdpa_kernel_mma_fp16(...) {
3    float oacc[DV_CHUNKS][2][4];      // now pinned to registers
4    ...
5    #pragma unroll
6    for (int i = 0; i < DV_CHUNKS; i++) { /* rescale, P·V */ }
7}

Up to d=256 the accumulator now lives fully in registers. At d=512 it partly spills at the 255-register limit, and it's still much faster: 3.7 → 2.0 ms, the biggest single step in the journal.

5. Removing work from the hot path

  • ldmatrix.trans for V: transpose each 8×8 tile while loading it, instead of copying V into a second transposed buffer behind an extra barrier. 1.3–1.9× faster depending on head size, 1.31 ms at the reference workload.
  • exp2 softmax: fold the softmax scale and log₂e into Q so each exponential is a cheaper exp2. 2–3% at large head sizes.

6. Removing bank conflicts

Nsight Compute flagged an 11-way bank conflict on 79% of shared-memory loads. Every row stride was a power of two, so the rows ldmatrix reads together landed on the same banks. Padding each row by 8 fp16 (16 bytes) spreads them out:

Unpadded rows: 128-byte stride0481216202428bankrow 0row 1row 2row 3row 4row 5row 6row 78 passes: 8-way bank conflict on banks 0–3

Eight lanes each read 16 bytes (4 banks) from a different row. With 128-byte rows every read lands on banks 0–3 and they queue up. Padding each row by 16 bytes shifts each row 4 banks over, so all eight reads go through at once.

The gain is largest at long sequences with small heads, where the Q·Kᵀ loop dominates. (At the d=512 reference workload it costs about 9%, but I kept it for the wins everywhere else.)

ConfigBeforeAfterSpeedup
B=4, S=2048, d=642.80 ms1.80 ms1.56×
B=4, S=4096, d=648.91 ms6.20 ms1.44×
B=4, S=8192, d=6436.6 ms22.2 ms1.65×
B=1, S=8192, d=648.88 ms5.65 ms1.57×

Where it stands against cuDNN

The fairest comparison is a sweep: same fp16 inputs for both, many sequence lengths and head sizes, at least 50 iterations per cell. Here is my kernel's speed as a fraction of cuDNN's (1.0 would be a tie):

Tensorax speed relative to cuDNN, fp16, B=4, H=8 (higher is better)
0.00×0.25×0.50×0.75×1.00×× cuDNNcuDNN2565121024204840968192sequence length Sd = 64d = 128d = 256d = 512
  • Best case: B=4, H=8, S=8192, d=64: 24.7 TFLOPS against cuDNN's 31.3 TFLOPS, 0.79×. Long sequences with small heads keep the Tensor Cores busy, and the gap mostly closes.
  • Worst cases: short sequences, where cuDNN is up to about 6× faster, and large head sizes, where it stays 2–3× faster even at long sequences.
  • Not supported: d=1024. Q alone would need 128 KB of shared memory per block, and this GPU allows 99 KB.

At large head sizes, the likely limits are shared memory and repeated loads. At d=512, Q takes 64 KB of shared memory, so only one block fits on each SM, and every block re-reads all of K and V. Cutting that footprint, for example by streaming Q in chunks like K, is the next structural change.

What I learned

  1. Count the work before you optimize it. Naive attention did 770× more arithmetic than it needed. The first two big wins, online softmax and computing each score once, came from doing less work, not from doing the same work faster.
  2. Look at what the compiler produced. One ptxas -v run showed my "registers" were in local memory. Fixing that gave the biggest step in the journal.
  3. Profiler predictions are local. Nsight predicted a 31.8% speedup from fixing bank conflicts. The real result was anything from −9% to +65% depending on the shape.

What's next

  • Attention: stream Q through shared memory instead of keeping all of it resident, so more than one block fits per SM at large head sizes; persistent blocks; d=1024 support.
  • Matmul: bring over what worked in attention, meaning cp.async double buffering, ldmatrix and padded shared memory, and see how much of the 6× gap to cuBLAS it closes.

Try it

1pip install tensorax
2
3# or from source, with the benchmarks
4git clone https://github.com/NotShrirang/tensorax.git
5cd tensorax
6pip install -e .
7python benchmarks/matmul_benchmark.py
8python benchmarks/attn_sweep.py      # full (B, S, d) sweep vs PyTorch fp16

The full journal, with every step's hypothesis and result, including the experiments that didn't work, is in docs/profiling/RESULTS.md. The kernels are in csrc/cuda/kernels.

References


If this resonated, pass it along.

All content licensed under CC BY-SA 4.0 unless otherwise noted.