Optimizing MLA Attention Inference: Tiling and Shared Memory Tuning
This article explains how Multi-Head Latent Attention (MLA) reduces KV cache size during LLM inference and how tiling and shared memory limits shape FlashAttention-style kernels on Hopper GPUs. It covers hardware coupling, KV cache paging, warp specialization, a kernel selection checklist, and a minimal benchmarking procedure.
1. Background: Why Attention Slows Down Inference
When a large language model generates each new token, it reads the Keys and Values of all previous tokens. This data is the KV cache. As the context grows from a few thousand tokens to hundreds of thousands, the memory bandwidth needed to read the KV cache increases quickly. That cost often exceeds the cost of the matrix multiplications themselves. As a result, GPU compute units wait for data, and utilization stays low.
Inference optimization is therefore shifting from “compute faster” to “read less, and read smarter.” This article covers open-source inference implementations and Hopper-class GPUs such as the H100. Its conclusions may not apply to all hardware.
2. MLA: Reducing the KV Cache with Low-Rank Compression
Multi-Head Latent Attention (MLA) jointly compresses Keys and Values using low-rank projection. The input first passes through a down-projection that produces a smaller latent vector. During inference, only this latent vector is cached. When computing attention, an up-projection restores it to Keys and Values.
The approaches differ in engineering cost:
- MHA: Each head caches its own K/V. The cache is the largest, but the implementation is the simplest.
- GQA: Multiple query heads share one set of K/V. The cache shrinks in proportion to the number of groups.
- MLA: Caches a low-dimensional latent vector. The cache is the smallest, but the up-projection adds computation.
Implementations differ in practice. In the approach used by models such as DeepSeek-V2, rotary position embedding (RoPE) cannot be reordered with the up-projection directly. A separate, smaller decoupled RoPE key must be stored in addition. Other implementations use the associative property of matrix multiplication to fold the up-projection into the query and output projections. Attention then runs directly in the latent space. These details change the memory access pattern of the kernel, so each choice needs to be checked separately.
Compression reduces memory use but adds computation. If the kernel is not implemented specifically for MLA, inference speed may drop.
3. FlashAttention: Tiling and On-Chip Reuse
The FlashAttention family changes the order of computation, but the mathematical definition of attention stays the same. It splits Q, K, and V into fixed-size blocks along the sequence dimension and computes block by block. It maintains the intermediate statistics needed for online softmax: the running maximum and the normalization sum. This avoids materializing the full attention matrix in memory. The size of that matrix grows with the square of the sequence length.
Block sizes are typically 64, 128, and so on, and the right values require tuning. The main constraints are:
- head_dim: Larger dimensions require more registers and shared memory per block.
- Shared memory limit: On Hopper, each SM has about 228 KB of shared memory. A single thread block can request up to about 227 KB, and this must be explicitly configured.
- Register pressure: When blocks are too large, registers spill to memory, and performance drops noticeably.
- Pipeline stages: Multi-stage pipelines need a buffer reserved for each stage.
Tiling adds scheduling and boundary-handling overhead. Smaller blocks mean more management work. Larger blocks can reduce occupancy and may prevent the kernel from launching.
4. Three Key Points of MLA-Specific Kernels
Hardware coupling: Kernels written for newer GPU instruction sets and memory hierarchies, such as kernels that use Hopper’s TMA and WGMMA instructions, usually cannot run directly on older architectures or on accelerators from other vendors. In some cases compilation fails. In others, performance drops significantly.
KV cache paging: The KV cache is managed in fixed-size pages, for example 16 or 64 tokens per page. This makes memory allocation more regular and aligns reads more easily with the compute pace of the tensor cores. The page size must match the kernel’s block size.
Warp-level scheduling: In the GPU, SM, and warp execution hierarchy, some warps can be dedicated to loading data while the others compute. The two pipelines overlap, which hides memory latency. Warp specialization on Hopper is this type of design.
5. Selection and Validation Checklist
Check each item when selecting a kernel:
- Hardware and instruction set: Confirm that the GPU architecture (for example, sm_90), driver, and CUDA version match the kernel.
- Resource usage: Record the shared memory and register usage of each kernel, along with its occupancy. Use
nvcc --ptxas-options=-vto see compile-time usage. Use Nsight Compute to confirm runtime occupancy. - KV cache block size: Confirm that it aligns with the kernel block size and page size.
- Scheduling: Check whether warp specialization and asynchronous copy are enabled.
- Metric definitions: Record throughput (tokens/s), time to first token (TTFT), time per output token (TPOT), peak memory, and memory bandwidth utilization using consistent definitions.
- Accuracy regression: Compare the maximum absolute error of the output against a high-precision reference implementation. Check task metrics on a fixed evaluation set for any drop.
- Rollback plan: Keep the previous kernel, or keep the GQA or MHA implementation. Switch back when compilation fails, accuracy is abnormal, or performance regresses.
Minimal benchmark steps:
- Fix the environment: Record the driver, CUDA, framework, and model weight versions. Lock GPU clocks when needed to reduce measurement variance.
- Establish a baseline: Run the existing implementation with the same model weights and record all metrics.
- Prepare fixed workloads: For example, use input lengths of 1K, 8K, and 32K, a fixed output length of 128, and batch sizes of 1, 8, and 32.
- Warm up and repeat: Run 3 to 5 warm-up rounds. Then measure at least 10 rounds, and report the median and p99.
- Check numerical error: Compare the old and new outputs, and confirm the error is within tolerance.
- Profile performance: For the most time-consuming kernels, use Nsight Compute to check memory throughput and compute throughput. Determine which one is the bottleneck.
6. Common Mistakes
- Switching to the MLA structure but keeping the old attention kernel. Memory usage drops, but speed does not improve.
- Ignoring hardware coupling and deploying a kernel written for a newer architecture on older cards.
- Using blocks that are too large, causing shared memory overflow or low occupancy.
- Comparing throughput across different input lengths or batch sizes, which makes the results incomparable.
- Relying on a single run and ignoring warm-up and run-to-run variance.
Conclusion
Each layer of optimization, from the low-rank compression of MLA to tiled computation, shared memory reuse, and warp-level scheduling, must match specific hardware features. When evaluating an inference approach, check it item by item against the checklist above. Then confirm the gains with benchmarks that use consistent metrics. Some cloud providers and open-source inference engines already package these kernels in their stacks. Before use, check the official documentation for the supported hardware and configurations.
