Abstract

Derive the arithmetic intensity ridge point on an NVIDIA H100, eliminate quadratic HBM traffic via Online Softmax SRAM tiling, and reclaim fragmented KV cache memory with vLLM's PagedAttention.

1.Why FLOPs alone cannot explain LLM latency#

When engineers optimize deep learning models solely by counting floating-point operations (FLOPs), two paradoxes appear immediately:

  1. Autoregressive generation is orders of magnitude slower per token than prompt prefill, even though the per-token linear algebra executes the exact same matrix weights.
  2. Standard self-attention spends most of its wall-clock time waiting on memory, even when the GPU's Tensor Cores are less than 25%25\% utilized.

Both phenomena are governed by the Roofline Model, which relates an operator's Arithmetic Intensity (I=FLOPs/Bytes transferred\mathcal{I} = \text{FLOPs} / \text{Bytes transferred}) to the hardware's Ridge Point:

Iridge=Peak Compute Throughput (FLOPs/s)Peak HBM Bandwidth (Bytes/s)\mathcal{I}_{\text{ridge}} = \frac{\text{Peak Compute Throughput (FLOPs/s)}}{\text{Peak HBM Bandwidth (Bytes/s)}}
(1)

For an NVIDIA H100 SXM GPU delivering 989 TFLOPS989\text{ TFLOPS} of dense bfloat16 Tensor Core compute and 3.35 TB/s3.35\text{ TB/s} (3350 GB/s3350\text{ GB/s}) of HBM3 bandwidth, the ridge point is:

IridgeH100=989×1012 FLOPs/s3350×109 Bytes/s≈295.2 FLOPs/Byte\mathcal{I}_{\text{ridge}}^{\text{H100}} = \frac{989 \times 10^{12}\text{ FLOPs/s}}{3350 \times 10^{9}\text{ Bytes/s}} \approx \mathbf{295.2\text{ FLOPs/Byte}}
(2)

Any kernel with arithmetic intensity below 295.2 FLOPs/Byte295.2\text{ FLOPs/Byte} is Memory-bound (bottlenecked by HBM3 bandwidth); any kernel above it is Compute-bound (bottlenecked by Tensor Core math pipes).

Figure 1: H100 SXM Roofline operating regimes for LLM Prefill and Decode alongside single-layer HBM read/write traffic reduction in FlashAttention-2.
Figure 1: H100 SXM Roofline operating regimes for LLM Prefill and Decode alongside single-layer HBM read/write traffic reduction in FlashAttention-2.

2.The Prefill versus Decode arithmetic intensity ledger#

Using our first-principles calculator (labs/llm/roofline-flash), let us evaluate Llama-3-8B (N=8.03BN = 8.03\text{B} parameters, 15.0 GB15.0\text{ GB} in bfloat16) at sequence length S=4096S = 4096 across batch sizes B∈{1,16,128}B \in \{1, 16, 128\}:

  • Prefill Phase (B×SB \times S tokens processed in parallel): Every weight matrix is loaded once from HBM and multiplied against B×SB \times S token vectors via dense GEMM:
Iprefill≈2NBS2N+BytesKV(B,S)\mathcal{I}_{\text{prefill}} \approx \frac{2 N B S}{2 N + \text{Bytes}_{\text{KV}}(B, S)}
(3)
  • Decode Phase (B×1B \times 1 new tokens generated per step): Every single decoding step must reload all 2N2N bytes of model weights plus all B×SB \times S historical KV cache vectors from HBM just to compute BB token outputs:
Idecode≈2NB2N+BytesKV(B,S)≤B FLOPs/Byte\mathcal{I}_{\text{decode}} \approx \frac{2 N B}{2 N + \text{Bytes}_{\text{KV}}(B, S)} \le B\text{ FLOPs/Byte}
(4)
Batch Size (BB) Sequence Length (SS) Prefill Intensity (FLOPs/B\text{FLOPs/B}) Prefill Hardware Regime Decode Intensity (FLOPs/B\text{FLOPs/B}) Decode Hardware Regime
B=1B = 1 40964096 3,891.03,891.0 Compute-bound (13.2×13.2\times ridge) 0.970.97 Extreme Memory-bound (0.3%0.3\% peak)
B=16B = 16 40964096 3,963.03,963.0 Compute-bound (13.4×13.4\times ridge) 14.3114.31 Memory-bound (4.8%4.8\% peak)
B=128B = 128 40964096 3,254.53,254.5 Compute-bound (11.0×11.0\times ridge) 69.5069.50 Memory-bound (KV cache dominates)
python
@dataclass
class GPUConfig:
    name: str
    fp16_tflops: float
    hbm_bandwidth_gbps: float
    vram_gb: float

    @property
    def ridge_point(self) -> float:
        return (self.fp16_tflops * 1e12) / (self.hbm_bandwidth_gbps * 1e9)


H100_SXM = GPUConfig("NVIDIA H100 SXM (80GB)", fp16_tflops=989.0, hbm_bandwidth_gbps=3350.0, vram_gb=80.0)


@dataclass
class ModelLedger:
    name: str
    num_layers: int
    hidden_size: int
    num_q_heads: int
    num_kv_heads: int
    head_dim: int
    intermediate_size: int
    vocab_size: int
    mla_kv_lora_rank: int = 0

    def total_params(self) -> int:
        emb = 2 * self.vocab_size * self.hidden_size
        attn = self.hidden_size * (2 * self.num_q_heads + 2 * self.num_kv_heads) * self.head_dim
        ffn = 3 * self.hidden_size * self.intermediate_size
        norm = 2 * self.hidden_size
        return emb + self.num_layers * (attn + ffn + norm)

    def kv_cache_bytes(self, batch_size: int, seq_len: int, bytes_per_elem: int = 2) -> int:
        if self.mla_kv_lora_rank > 0:
            return self.num_layers * batch_size * seq_len * self.mla_kv_lora_rank * bytes_per_elem
        return 2 * self.num_layers * batch_size * seq_len * self.num_kv_heads * self.head_dim * bytes_per_elem

    def arithmetic_intensity(self, batch_size: int, seq_len: int) -> dict[str, float]:
        params = self.total_params()
        weight_bytes = params * 2
        kv_bytes = self.kv_cache_bytes(batch_size, seq_len)
        prefill_ai = (2.0 * params * batch_size * seq_len) / (weight_bytes + kv_bytes)
        decode_ai = (2.0 * params * batch_size) / (weight_bytes + kv_bytes)
        return {"prefill_flops_per_byte": prefill_ai, "decode_flops_per_byte": decode_ai}

At B=1B = 1, decoding achieves 0.97 FLOPs/Byte0.97\text{ FLOPs/Byte}—leaving 99.6%99.6\% of the H100's Tensor Cores idle while waiting on HBM reads. Even when batching B=128B = 128 concurrent requests, the growing KV cache denominator prevents decode intensity from crossing the 295.2 FLOPs/Byte295.2\text{ FLOPs/Byte} ridge point.

3.FlashAttention: IO-aware SRAM tiling and Online Softmax#

During training and long-context prefill, the linear projections are compute-bound, but self-attention itself is severely memory-bound. Given Q,K,V∈RN×dQ, K, V \in \mathbb{R}^{N \times d} in HBM, standard attention executes three separate kernel stages:

  1. Read Q,KQ, K from HBM, compute S=QK⊤/d∈RN×NS = QK^\top / \sqrt{d} \in \mathbb{R}^{N \times N}, and write SS back to HBM (O(N2)O(N^2) writes).
  2. Read SS from HBM, compute P=Softmax⁡(S)∈RN×NP = \operatorname{Softmax}(S) \in \mathbb{R}^{N \times N}, and write PP back to HBM (O(N2)O(N^2) reads and writes).
  3. Read PP and VV from HBM, compute O=PV∈RN×dO = PV \in \mathbb{R}^{N \times d}, and write OO to HBM.

At N=32768N = 32768, B=4B = 4, and H=32H = 32 heads, materializing SS and PP transfers over 1,024 GB1,024\text{ GB} of intermediate HBM traffic per layer! Yet each Streaming Multiprocessor (SM) on an A100/H100 has fast on-chip SRAM (192 KB–256 KB192\text{ KB}\text{--}256\text{ KB} per SM) operating at ∼19 TB/s\sim 19\text{ TB/s}—nearly 6×6\times faster than HBM3.

Dao et al. (FlashAttention, arXiv:2205.14135[1][1] · FlashAttention-1 · 2022FlashAttention: Fast and Memory-Efficient Exact Attention with IO-AwarenessOpen arXiv:2205.14135 ↗) fused all three steps into a single CUDA kernel by tiling QQ into blocks Qi∈RBr×dQ_i \in \mathbb{R}^{B_r \times d} in SRAM and streaming blocks Kj,Vj∈RBc×dK_j, V_j \in \mathbb{R}^{B_c \times d} across them. The mathematical obstacle is that Softmax couples every column in a row through its global maximum m(x)=max⁡kxkm(x) = \max_k x_k and denominator ℓ(x)=∑kexk−m(x)\ell(x) = \sum_k e^{x_k - m(x)}.

Online Softmax resolves this by maintaining a running row maximum mi(j)m_i^{(j)} and a rescaled running sum ℓi(j)\ell_i^{(j)} as each key/value tile jj arrives in SRAM:

minew=max⁡ ⁣(miold, rowmax⁡(Sij)),αi=exp⁡ ⁣(miold−minew)m_i^{\text{new}} = \max\!\big(m_i^{\text{old}},\, \operatorname{rowmax}(S_{ij})\big), \qquad \alpha_i = \exp\!\big(m_i^{\text{old}} - m_i^{\text{new}}\big)
(5)
ℓinew=αiℓiold+rowsum⁡ ⁣(exp⁡(Sij−minew)),O~inew=αiO~iold+exp⁡(Sij−minew)Vj\ell_i^{\text{new}} = \alpha_i \ell_i^{\text{old}} + \operatorname{rowsum}\!\Big(\exp(S_{ij} - m_i^{\text{new}})\Big), \qquad \tilde{O}_i^{\text{new}} = \alpha_i \tilde{O}_i^{\text{old}} + \exp(S_{ij} - m_i^{\text{new}}) V_j
(6)

Suppose after processing tiles 1…j−11 \dots j-1, our unnormalized output accumulator satisfies O~i(j−1)=∑t<jexp⁡(Sit−mi(j−1))Vt\tilde{O}_i^{(j-1)} = \sum_{t < j} \exp(S_{it} - m_i^{(j-1)}) V_t. When tile jj updates the row maximum from mi(j−1)m_i^{(j-1)} to mi(j)m_i^{(j)}, multiplying O~i(j−1)\tilde{O}_i^{(j-1)} by αi=exp⁡(mi(j−1)−mi(j))\alpha_i = \exp(m_i^{(j-1)} - m_i^{(j)}) uses the exponential law ea⋅eb=ea+be^a \cdot e^b = e^{a+b}:

αiO~i(j−1)+exp⁡(Sij−mi(j))Vj=∑t≤jexp⁡ ⁣(Sit−mi(j))Vt\alpha_i \tilde{O}_i^{(j-1)} + \exp(S_{ij} - m_i^{(j)}) V_j = \sum_{t \le j} \exp\!\big(S_{it} - m_i^{(j)}\big) V_t
(7)

After the final tile completes, dividing O~i\tilde{O}_i by ℓi\ell_i yields the exact full-sequence attention output Oi=Softmax⁡(Si)VO_i = \operatorname{Softmax}(S_i) V without ever writing SS or PP to HBM. Furthermore, during backpropagation, FlashAttention avoids storing the O(N2)O(N^2) matrices by saving only the compact log-sum-exp vector Li=mi+log⁡ℓi∈RNL_i = m_i + \log \ell_i \in \mathbb{R}^N and recomputing attention tiles on-chip in SRAM.

python
def tiled_flash_attention(q: Tensor, k: Tensor, v: Tensor, block_size: int = 16) -> Tensor:
    """
    Exact blockwise attention using Online Softmax rescaling without materializing the N x N matrix.
    Shapes: q, k, v of shape [B, H, N, D].
    """
    b, h, n, d = q.shape
    scale = 1.0 / math.sqrt(d)
    out = torch.zeros_like(q, dtype=torch.float32)

    for i_start in range(0, n, block_size):
        i_end = min(i_start + block_size, n)
        q_block = q[:, :, i_start:i_end, :].float()  # [B, H, Br, D]
        br = i_end - i_start

        m_i = torch.full((b, h, br, 1), float("-inf"), device=q.device, dtype=torch.float32)
        l_i = torch.zeros((b, h, br, 1), device=q.device, dtype=torch.float32)
        acc_o = torch.zeros((b, h, br, d), device=q.device, dtype=torch.float32)

        q_pos = torch.arange(i_start, i_end, device=q.device)[:, None]

        for j_start in range(0, i_end, block_size):
            j_end = min(j_start + block_size, n)
            k_block = k[:, :, j_start:j_end, :].float()
            v_block = v[:, :, j_start:j_end, :].float()
            k_pos = torch.arange(j_start, j_end, device=q.device)[None, :]

            scores = (q_block @ k_block.transpose(-2, -1)) * scale
            scores = scores.masked_fill(k_pos > q_pos, float("-inf"))

            block_max = scores.max(dim=-1, keepdim=True).values
            m_new = torch.maximum(m_i, block_max)
            # Rescale previous accumulator and denominator to the new running maximum m_new.
            alpha = torch.exp(m_i - m_new)
            p_tilde = torch.exp(scores - m_new)

            l_i = alpha * l_i + p_tilde.sum(dim=-1, keepdim=True)
            acc_o = alpha * acc_o + (p_tilde @ v_block)
            m_i = m_new

        out[:, :, i_start:i_end, :] = acc_o / l_i

    return out.to(q.dtype)

4.FlashAttention-2: Loop inversion and warp partitioning#

While FlashAttention-1 eliminated O(N2)O(N^2) HBM traffic, it achieved only 25%–40%25\%\text{--}40\% of theoretical peak FLOPs on A100. FlashAttention-2 (Dao, arXiv:2307.08691[2][2] · FlashAttention-2 · 2023FlashAttention-2: Faster Attention with Better Parallelism and Work PartitioningOpen arXiv:2307.08691 ↗) identified three GPU microarchitectural bottlenecks and fixed them:

  1. Inverting the outer and inner loops: FlashAttention-1 placed K,VK, V blocks in the outer loop and QQ blocks in the inner loop, forcing every inner step to read and atomically accumulate partial updates to OiO_i and ℓi\ell_i in HBM. FlashAttention-2 moves QiQ_i to the outer loop and streams Kj,VjK_j, V_j in the inner loop so the accumulator O~i\tilde{O}_i stays entirely inside registers/SRAM for the full lifetime of the loop.
  2. Warp partitioning (Split-QQ over Split-KK): Instead of splitting KK across 4 warps in a threadblock (which requires shared-memory barrier synchronization after every GEMM to sum QKj⊤Q K_j^\top), FlashAttention-2 assigns disjoint rows of QiQ_i to each warp. Every warp streams the shared Kj,VjK_j, V_j tiles from SRAM with zero inter-warp communication.
  3. Causal block skipping: For any tile where all column indices exceed all row indices (jstart>iendj_{\text{start}} > i_{\text{end}}), the entire block is skipped instead of computing and masking zeros, saving nearly 50%50\% of causal attention FLOPs.

5.PagedAttention (vLLM): Virtual memory for the KV cache#

Even with GQA and FlashAttention-2, production serving engines wasted 60%–80%60\%\text{--}80\% of GPU memory on KV cache fragmentation. Because an LLM's output length is unknown ahead of time, early serving frameworks pre-allocated a contiguous HBM slab of size Smax⁡S_{\max} (e.g., 40964096 or 3276832768 tokens) for every active request. This caused three forms of waste:

  • Internal fragmentation: Reserved slots for future tokens that a short completion never uses.
  • Reservation waste: Slots held idle while waiting for future decoding steps.
  • External fragmentation: Contiguous slabs of varying sequence lengths cannot pack cleanly into HBM.

Kwon et al. (vLLM / PagedAttention, arXiv:2309.06180[3][3] · vLLM / PagedAttention · 2023Efficient Memory Management for Large Language Model Serving with PagedAttentionOpen arXiv:2309.06180 ↗) mapped operating-system virtual memory directly onto the KV cache:

  1. Fixed-size physical KV blocks: HBM is partitioned into small, uniform physical pages (e.g., Bblock=16B_{\text{block}} = 16 tokens per block).
  2. Logical-to-physical Page Table: Each sequence appends to logical blocks on demand; a block table maps logical block IDs to non-contiguous physical HBM blocks, driving internal fragmentation below 4%4\% (at most 1515 unused token slots at the tail of a sequence).
  3. Copy-on-Write (CoW) prefix sharing: When multiple requests share a system prompt or conduct parallel sampling (n>1n > 1), their page tables point to the exact same physical KV blocks with reference counting. Only when a branch mutates a partially filled block does vLLM allocate a new physical page and copy those 16 tokens.

Run the Roofline and Online Softmax tiled attention lab on CPU:

bash
labs/.venv/bin/python -m unittest discover -s labs/llm/roofline-flash -p 'test_*.py' -v
labs/.venv/bin/python labs/llm/roofline-flash/roofline_flash.py

6.References and next chapter#

References

  1. [1]
  2. [2]
  3. [3]

Share