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:
- 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.
- Standard self-attention spends most of its wall-clock time waiting on memory, even when the GPU's Tensor Cores are less than utilized.
Both phenomena are governed by the Roofline Model, which relates an operator's Arithmetic Intensity () to the hardware's Ridge Point:
For an NVIDIA H100 SXM GPU delivering of dense bfloat16 Tensor Core compute and () of HBM3 bandwidth, the ridge point is:
Any kernel with arithmetic intensity below is Memory-bound (bottlenecked by HBM3 bandwidth); any kernel above it is Compute-bound (bottlenecked by Tensor Core math pipes).
2.The Prefill versus Decode arithmetic intensity ledger#
Using our first-principles calculator (labs/llm/roofline-flash), let us evaluate Llama-3-8B ( parameters, in bfloat16) at sequence length across batch sizes :
- Prefill Phase ( tokens processed in parallel): Every weight matrix is loaded once from HBM and multiplied against token vectors via dense GEMM:
- Decode Phase ( new tokens generated per step): Every single decoding step must reload all bytes of model weights plus all historical KV cache vectors from HBM just to compute token outputs:
| Batch Size () | Sequence Length () | Prefill Intensity () | Prefill Hardware Regime | Decode Intensity () | Decode Hardware Regime |
|---|---|---|---|---|---|
| Compute-bound ( ridge) | Extreme Memory-bound ( peak) | ||||
| Compute-bound ( ridge) | Memory-bound ( peak) | ||||
| Compute-bound ( ridge) | Memory-bound (KV cache dominates) |
@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 , decoding achieves —leaving of the H100's Tensor Cores idle while waiting on HBM reads. Even when batching concurrent requests, the growing KV cache denominator prevents decode intensity from crossing the 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 in HBM, standard attention executes three separate kernel stages:
- Read from HBM, compute , and write back to HBM ( writes).
- Read from HBM, compute , and write back to HBM ( reads and writes).
- Read and from HBM, compute , and write to HBM.
At , , and heads, materializing and transfers over of intermediate HBM traffic per layer! Yet each Streaming Multiprocessor (SM) on an A100/H100 has fast on-chip SRAM ( per SM) operating at —nearly faster than HBM3.
Dao et al. (FlashAttention, arXiv:2205.14135[1]FlashAttention: Fast and Memory-Efficient Exact Attention with IO-AwarenessOpen arXiv:2205.14135 ↗) fused all three steps into a single CUDA kernel by tiling into blocks in SRAM and streaming blocks across them. The mathematical obstacle is that Softmax couples every column in a row through its global maximum and denominator .
Online Softmax resolves this by maintaining a running row maximum and a rescaled running sum as each key/value tile arrives in SRAM:
Suppose after processing tiles , our unnormalized output accumulator satisfies . When tile updates the row maximum from to , multiplying by uses the exponential law :
After the final tile completes, dividing by yields the exact full-sequence attention output without ever writing or to HBM. Furthermore, during backpropagation, FlashAttention avoids storing the matrices by saving only the compact log-sum-exp vector and recomputing attention tiles on-chip in SRAM.
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 HBM traffic, it achieved only of theoretical peak FLOPs on A100. FlashAttention-2 (Dao, arXiv:2307.08691[2]FlashAttention-2: Faster Attention with Better Parallelism and Work PartitioningOpen arXiv:2307.08691 ↗) identified three GPU microarchitectural bottlenecks and fixed them:
- Inverting the outer and inner loops: FlashAttention-1 placed blocks in the outer loop and blocks in the inner loop, forcing every inner step to read and atomically accumulate partial updates to and in HBM. FlashAttention-2 moves to the outer loop and streams in the inner loop so the accumulator stays entirely inside registers/SRAM for the full lifetime of the loop.
- Warp partitioning (Split- over Split-): Instead of splitting across 4 warps in a threadblock (which requires shared-memory barrier synchronization after every GEMM to sum ), FlashAttention-2 assigns disjoint rows of to each warp. Every warp streams the shared tiles from SRAM with zero inter-warp communication.
- Causal block skipping: For any tile where all column indices exceed all row indices (), the entire block is skipped instead of computing and masking zeros, saving nearly of causal attention FLOPs.
5.PagedAttention (vLLM): Virtual memory for the KV cache#
Even with GQA and FlashAttention-2, production serving engines wasted 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 (e.g., or 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]Efficient Memory Management for Large Language Model Serving with PagedAttentionOpen arXiv:2309.06180 ↗) mapped operating-system virtual memory directly onto the KV cache:
- Fixed-size physical KV blocks: HBM is partitioned into small, uniform physical pages (e.g., tokens per block).
- 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 (at most unused token slots at the tail of a sequence).
- Copy-on-Write (CoW) prefix sharing: When multiple requests share a system prompt or conduct parallel sampling (), 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:
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.py6.References and next chapter#
- Dao et al., FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (2022).
- Dao, FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning (2023).
- Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention (2023).
- Continue to Chapter 3: Distributed Training & Compute-Optimal Scaling: Megatron-LM, ZeRO, and Chinchilla Laws.
References
- [1]
- [2]
- [3]