Post

From Softmax Attention to FlashAttention-2

Derive one-pass softmax attention, implement a simplified Triton kernel, and connect each FlashAttention-2 optimization to the pinned open-source CUDA/CUTLASS implementation.

From Softmax Attention to FlashAttention-2

Introduction

This post derives scaled dot-product attention, turns stable softmax into an online recurrence, and implements a small one-pass forward kernel in Triton without materializing the full attention matrix. It then opens the production FlashAttention repository and connects each FlashAttention-2 optimization to the CUDA/CUTLASS code that implements it.

All upstream source links are pinned to Dao-AILab/flash-attention@b038b49 so that line numbers remain stable.

The simplified Triton kernel is for learning rather than a replacement for the production implementation. The common algorithmic core is:

1
2
3
4
5
Q-row ownership
    -> stream K/V tiles
    -> update online (m, l, U) state
    -> normalize once
    -> never write the N x N score matrix to HBM

1. What softmax attention computes

For one batch-head, let:

  • Q have shape (N_q, D);
  • K and V have shape (N_k, D);
  • D be the head dimension.

Scaled dot-product attention is:

\[S = \frac{QK^T}{\sqrt{D}}, \qquad P_{ij} = \frac{\exp(S_{ij})} {\sum_{r=0}^{N_k-1}\exp(S_{ir})}, \qquad O = PV.\]

Each query row compares with every key row. Softmax converts the scores into positive weights that sum to one, and the output is a weighted combination of the value rows.

Stable softmax

The numerically stable form subtracts each score row’s maximum:

\[m_i = \max_j S_{ij}, \qquad P_{ij} = \frac{\exp(S_{ij}-m_i)} {\sum_r \exp(S_{ir}-m_i)}.\]

Subtracting the maximum does not change the result because the same factor $e^{-m_i}$ appears in every numerator and in the denominator. It prevents large positive scores from overflowing exp.

2. Why ordinary attention is memory-hungry

A direct implementation commonly creates:

1
2
3
scores        = Q @ K.T       # N_q x N_k
probabilities = softmax(...)  # N_q x N_k
output        = probabilities @ V

When N_q = N_k = N, the score and probability matrices contain N^2 elements even though the final output contains only N * D. Writing and rereading those quadratic intermediates from HBM is the main problem FlashAttention removes.

FlashAttention keeps only a small score tile on chip:

1
2
3
4
5
6
one Q row/block
    for each K/V tile:
        score tile = Q tile @ K tile.T
        update online softmax state
        update output accumulator with V tile
    normalize once and store O

The complete N x N matrix is never stored in HBM.

3. The one-pass softmax attention equation

For one query row, maintain three values after processing some K/V tiles:

\[m = \max_{\text{processed }j} s_j,\] \[\ell = \sum_{\text{processed }j} e^{s_j-m},\] \[U = \sum_{\text{processed }j} e^{s_j-m}v_j.\]

U is deliberately unnormalized. The current attention output would be U / l, but FlashAttention-2 delays that division until all tiles have been processed.

For a new score tile $S_t$ and matching value tile $V_t$, compute:

\[\widetilde{m}_t = \operatorname{rowmax}(S_t), \qquad m' = \max(m, \widetilde{m}_t),\] \[\alpha = e^{m-m'}, \qquad P_t = e^{S_t-m'},\] \[\ell' = \alpha\ell + \operatorname{rowsum}(P_t),\] \[U' = \alpha U + P_tV_t.\]

After the final tile:

\[O = \frac{U}{\ell}.\]

These updates preserve the invariant:

\[\ell' = \sum_{\text{all processed }j}e^{s_j-m'}, \qquad U' = \sum_{\text{all processed }j}e^{s_j-m'}v_j.\]

The factor alpha rescales every old term from the old maximum to the new maximum. This is why the algorithm remains stable even when a later tile contains a much larger score.

Verify the recurrence before writing a kernel

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
32
33
import math
import torch


def online_attention_reference(q, k, v, key_tile=16):
    scale = 1.0 / math.sqrt(q.shape[-1])
    running_max = torch.tensor(
        -torch.inf, device=q.device, dtype=torch.float32
    )
    running_sum = torch.tensor(
        0.0, device=q.device, dtype=torch.float32
    )
    output_accumulator = torch.zeros_like(q)

    for start in range(0, k.shape[0], key_tile):
        k_tile = k[start : start + key_tile]
        v_tile = v[start : start + key_tile]
        scores = (k_tile @ q) * scale

        new_max = torch.maximum(running_max, scores.max())
        previous_scale = torch.exp(running_max - new_max)
        probabilities = torch.exp(scores - new_max)

        running_sum = (
            running_sum * previous_scale + probabilities.sum()
        )
        output_accumulator = (
            output_accumulator * previous_scale
            + probabilities @ v_tile
        )
        running_max = new_max

    return output_accumulator / running_sum

For any key-tile size, this produces the same result as:

1
2
3
direct = torch.softmax(
    k @ q / math.sqrt(q.shape[-1]), dim=0
) @ v

4. What FlashAttention-2 changes

FlashAttention-1 already introduced tiling and online softmax. FlashAttention-2 improves the work assignment and removes unnecessary non-matmul operations.

4.1 Delay output normalization

The normalized FA1 recurrence can be written as:

\[O' = \frac{\alpha\ell}{\ell'}O + \frac{P_tV_t}{\ell'}.\]

FA2 instead accumulates the unnormalized U:

\[U' = \alpha U + P_tV_t,\]

and performs O = U / l once at the end. This avoids repeatedly dividing and rescaling every output element.

The production implementation keeps row_max, row_sum, and the output accumulator in registers. On each tile it rescales the old state by exp2(old_max - new_max), then normalizes only in the epilogue:

1
2
3
4
5
float scores_scale =
    exp2f((scores_max_prev(mi) - scores_max_cur)
          * softmax_scale_log2);
row_sum(mi) *= scores_scale;
acc_o_rowcol(mi, ni) *= scores_scale;

Source: softmax_rescale_o, lines 128-179 and normalize_softmax_lse, lines 181-200.

4.2 Assign each Q block to one CTA

The outer parallel dimension is the Q sequence:

1
2
3
CTA 0 owns Q rows   0..Br-1
CTA 1 owns Q rows  Br..2Br-1
...

Each CTA loops over all K/V tiles and exclusively owns its output tile. The forward pass therefore needs no atomic accumulation.

That ownership is explicit in the source. A kernel computes one m_block, and compute_attn_1rowblock forms the corresponding kBlockM x head_dim Q and O tiles:

1
2
const int m_block = blockIdx.x;
compute_attn_1rowblock(params, bidb, bidh, m_block);

Source: flash_fwd_kernel.h, lines 1087-1104 and the gQ row-block tile, lines 164-179.

4.3 Partition warps only along Q rows

FA2 stacks warps along Q rows rather than splitting a softmax row across the K-column dimension:

1
2
3
4
5
CTA query block
├── warp 0 -> complete softmax rows
├── warp 1 -> complete softmax rows
├── warp 2 -> complete softmax rows
└── warp 3 -> complete softmax rows

Each warp sees the complete K-column extent for its Q rows, avoiding cross-warp communication for the softmax reduction.

The CUTLASS tile layout stacks the warp dimension along M, the Q-row dimension, while leaving N unsplit:

1
2
3
4
using TiledMma = TiledMMA<
    typename Base::MMA_Atom_Arch,
    Layout<Shape<Int<kNWarps>, _1, _1>>,
    Tile<Int<16 * kNWarps>, _16, _16>>;

Source: kernel_traits.h, lines 74-77.

4.4 Overlap K/V movement with tensor-core work

FA2 pipelines global-to-shared-memory copies with the current tile’s matrix multiplications. The next K tile is issued with cp.async while the current tile performs QK, online softmax, and PV:

1
2
3
4
5
6
copy(gmem_tiled_copy_QKV, tKgK(..., n_block - 1), tKsK, ...);
cute::cp_async_fence();

softmax.softmax_rescale_o(acc_s, acc_o, scale_log2);
Tensor rP = convert_type<Element>(acc_s);
gemm_rs(acc_o, tOrP, tOrVt, ...);

Source: flash_fwd_kernel.h, lines 314-376. The two matrix products are tensor-core MMA operations selected by the TiledMma type; acc_s and acc_o remain FP32 accumulators.

Production kernels additionally use tensor-core MMA, swizzled shared memory, asynchronous K/V pipelines, FP16/BF16 inputs, causal masks, dropout, and a specialized backward pass. The implementations below isolate the forward algorithm first.

5. Correctness and benchmark contract

Both kernels use contiguous tensors with shape:

1
[batch_heads, sequence_length, head_dim]

The Triton path uses FP16 Q/K/V/output with FP32 online-softmax and output accumulation.

The direct reference materializes the score matrix only for testing. It computes in FP32 and then converts to the input dtype:

1
2
3
4
5
6
7
8
9
10
def attention_reference(q, k, v):
    scale = 1.0 / math.sqrt(q.shape[-1])
    scores = (
        torch.matmul(q.float(), k.float().transpose(-1, -2))
        * scale
    )
    output = torch.matmul(
        torch.softmax(scores, dim=-1), v.float()
    )
    return output.to(q.dtype)

Correctness tests use:

1
2
3
4
5
TEST_SHAPES = (
    (2, 17, 32),
    (3, 33, 64),
    (4, 64, 64),
)

Lengths 17 and 33 deliberately exercise partial key tiles and partially populated Q blocks.

Each benchmark:

  • checks correctness before timing;
  • reuses compiled callables;
  • uses triton.testing.do_bench;
  • reports the two attention matmuls:
\[\text{FLOPs} \approx 4 B_h N^2 D.\]

The count omits exponentials, reductions, and rescaling, so TFLOP/s is an attention convention rather than a complete instruction count.

6. A compact Triton implementation

This implementation follows the forward path in Triton Tutorial 06: Fused Attention, with a deliberately narrow feature set:

  • FlashAttention-2 forward only;
  • non-causal attention;
  • FP16 Q/K/V and FP16 output;
  • FP32 online-softmax and output accumulation;
  • four warps, with no warp specialization;
  • no FP8, tensor descriptors, autotuning, or backward kernel.

One program owns a block of 64 Q rows. It keeps that Q tile resident and processes K/V blocks of 32 or 64 rows:

1
2
3
4
5
6
7
scores = Q_tile @ K_tile.T / sqrt(D)
m_new = max(m, rowmax(scores))
alpha = exp2(m - m_new)
p = exp2(scores - m_new[:, None])
l = alpha * l + rowsum(p)
U = alpha[:, None] * U + p.to(fp16) @ V_tile
m = m_new

tl.dot lowers both matrix products to tensor-core operations. U is a BLOCK_M x D FP32 accumulator. The BLOCK_M x BLOCK_N score tile stays on chip, so the kernel never creates an N x N output.

The kernel uses base-2 exponentiation like the official tutorial. Multiplying the softmax scale by log2(e) preserves the same mathematical softmax while mapping to exp2.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import triton
import triton.language as tl


@triton.jit
def triton_flash_attention2_kernel(
    q_ptr,
    k_ptr,
    v_ptr,
    o_ptr,
    softmax_scale,
    N_CTX: tl.constexpr,
    HEAD_DIM: tl.constexpr,
    BLOCK_M: tl.constexpr,
    BLOCK_N: tl.constexpr,
):
    query_block = tl.program_id(0)
    batch_head = tl.program_id(1)
    query_indices = (
        query_block * BLOCK_M + tl.arange(0, BLOCK_M)
    )
    key_offsets = tl.arange(0, BLOCK_N)
    dimensions = tl.arange(0, HEAD_DIM)
    query_mask = query_indices < N_CTX
    tensor_base = batch_head * N_CTX * HEAD_DIM
    q_offsets = (
        tensor_base
        + query_indices[:, None] * HEAD_DIM
        + dimensions[None, :]
    )
    q = tl.load(
        q_ptr + q_offsets,
        mask=query_mask[:, None],
        other=0.0,
    )

    running_max = (
        tl.zeros((BLOCK_M,), dtype=tl.float32)
        - float("inf")
    )
    running_sum = (
        tl.zeros((BLOCK_M,), dtype=tl.float32) + 1.0
    )
    output_accumulator = tl.zeros(
        (BLOCK_M, HEAD_DIM), dtype=tl.float32
    )
    qk_scale = softmax_scale * 1.44269504

    for key_start in tl.range(0, N_CTX, BLOCK_N):
        key_indices = key_start + key_offsets
        key_mask = key_indices < N_CTX
        kv_offsets = (
            tensor_base
            + key_indices[:, None] * HEAD_DIM
            + dimensions[None, :]
        )

        keys = tl.load(
            k_ptr + kv_offsets,
            mask=key_mask[:, None],
            other=0.0,
        )
        scores = tl.dot(q, tl.trans(keys))
        scores = tl.where(
            key_mask[None, :],
            scores * qk_scale,
            -1.0e6,
        )

        tile_max = tl.max(scores, axis=1)
        new_max = tl.maximum(running_max, tile_max)
        probabilities = tl.math.exp2(
            scores - new_max[:, None]
        )
        previous_scale = tl.math.exp2(
            running_max - new_max
        )
        tile_sum = tl.sum(probabilities, axis=1)

        values = tl.load(
            v_ptr + kv_offsets,
            mask=key_mask[:, None],
            other=0.0,
        )
        output_accumulator *= previous_scale[:, None]
        output_accumulator = tl.dot(
            probabilities.to(tl.float16),
            values,
            output_accumulator,
        )
        running_sum = (
            running_sum * previous_scale + tile_sum
        )
        running_max = new_max

    tl.store(
        o_ptr + q_offsets,
        (output_accumulator / running_sum[:, None]).to(
            tl.float16
        ),
        mask=query_mask[:, None],
    )

The launcher specializes sequence length, head dimension, and tile sizes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def launch_triton_attention(q, k, v, output):
    batch_heads, sequence_length, head_dim = q.shape
    block_m = 64
    block_n = min(64, head_dim)
    grid = (
        triton.cdiv(sequence_length, block_m),
        batch_heads,
    )

    triton_flash_attention2_kernel[grid](
        q,
        k,
        v,
        output,
        1.0 / math.sqrt(head_dim),
        N_CTX=sequence_length,
        HEAD_DIM=head_dim,
        BLOCK_M=block_m,
        BLOCK_N=block_n,
        num_warps=4,
        num_stages=3,
    )

Triton correctness

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def test_triton_attention():
    for index, shape in enumerate(TEST_SHAPES):
        torch.manual_seed(20261015 + index)
        q = torch.randn(
            shape, device="cuda", dtype=torch.float16
        )
        k = torch.randn_like(q)
        v = torch.randn_like(q)

        output = torch.empty_like(q)
        launch_triton_attention(q, k, v, output)
        torch.cuda.synchronize()

        torch.testing.assert_close(
            output,
            attention_reference(q, k, v),
            atol=2e-2,
            rtol=2e-2,
        )

The Triton kernel passes all three test shapes.

Triton benchmark

Measured on an NVIDIA B300:

(batch_heads, N, D)Triton msTriton TFLOP/s
(16, 256, 64)0.010226.23
(16, 512, 64)0.012387.33

This is still narrower than the production tutorial—there is no causal path, autotuning, descriptors, FP8, backward, or warp specialization—but it now has the defining blockwise tensor-core FA2 forward dataflow.

7. Reading the production FA2 loop

The production forward loop can be read as the same recurrence with concrete GPU mechanisms attached:

Algorithm stepProduction mechanismPinned source
Own one Q/output tileOne CTA calls compute_attn_1rowblock for one m_blockflash_fwd_kernel.h#L1087-L1104
Stage K/V tilescp.async, fences, and waits move GMEM to SMEMflash_fwd_kernel.h#L250-L326
Compute QK^TCUTLASS gemm using tensor-core TiledMmaflash_fwd_kernel.h#L328-L331
Mask scoresCausal/local/padding mask rewrites invalid scoresflash_fwd_kernel.h#L337-L339
Update online softmaxRescale old row sum and output accumulatorsoftmax.h#L128-L179
Compute PVConvert probabilities, then tensor-core gemm_rsflash_fwd_kernel.h#L352-L376
Normalize and storeDivide once, convert dtype, and write Oflash_fwd_kernel.h#L442-L474

The most important reading trick is to separate the invariant from the mechanism. row_max, row_sum, and acc_o are the mathematical state. cp.async, shared-memory layouts, MMA fragments, masks, and fences are the hardware-specific machinery that keeps that state fed efficiently.

8. Day 12: a separate CuTe DSL exercise

The detailed CuTe DSL implementation has been removed from this article so the source discussion stays focused on Triton and the upstream FlashAttention-2 kernel. A smaller educational implementation remains as a separate exercise:

That exercise is useful for learning CuTe tensor layouts and MMA fragments, but it should not be confused with the architecture-tuned production FA2 kernel above.

9. Takeaways

FlashAttention-2 is not merely “attention without the score matrix.” Its performance comes from preserving the online-softmax invariant while making several coordinated scheduling choices:

  1. parallelize over Q blocks so each CTA owns its output;
  2. partition warps along Q rows to avoid cross-warp softmax reductions;
  3. keep the output accumulator unnormalized until the epilogue;
  4. overlap K/V staging with tensor-core work; and
  5. never spill the quadratic score or probability matrix to HBM.

The next article follows how FlashAttention-3 keeps this mathematical core but rebuilds the schedule around Hopper’s asynchronous TMA and WGMMA units.

This post is licensed under CC BY 4.0 by the author.