Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
F

FlashMLA

> 编程语言
Open source

FlashMLA: Efficient Multi-head Latent Attention Kernels

12.8K stars0 likes3 views
WebsiteGitHub

About

FlashMLA: Efficient Multi-head Latent Attention Kernels

FlashMLA

Introduction

FlashMLA is DeepSeek's library of optimized attention kernels, powering the DeepSeek-V3 and DeepSeek-V3.2-Exp models. This repository contains the following implementations:

Sparse Attention Kernels

These kernels power DeepSeek Sparse Attention (DSA), as introduced in this paper.

  • Token-level sparse attention for the prefill stage
  • Token-level sparse attention for the decoding stage, with FP8 KV cache

Dense Attention Kernels

  • Dense attention for the prefill stage
  • Dense attention for the decoding stage

News

  • 2026.09.10 Release of DeepSeek v4.1's Attention Kernels: We've released attention kernels for DeepSeek-V4.1, including both prefill and decoding (with FP8 or FP4 KV cache). We've also released a fused-norm-rope-attn-rope-cast kernel which fuses Q-norm (only used in V4, not V4.1), Q-RoPE, core attention, O-RoPE (conjugate), and cast-to-fp8, while retaining the same performance.
  • 2025.09.29 Release of Sparse Attention Kernels: With the launch of DeepSeek-V3.2, we are releasing the corresponding token-level sparse attention kernels. These kernels power the model's DeepSeek Sparse Attention (DSA) and achieve up to 640 TFlops during prefilling and 410 TFlops during decoding. We also release a deep-dive blog for our new FP8 sparse decoding kernel. Check it out here.
  • 2025.08.01 Kernels for MHA on SM100: Thanks to NVIDIA's PR for MHA forward / backward kernels on SM100!
  • 2025.04.22 Deep-Dive Blog: We'd love to share the technical details behind the new FlashMLA kernel! Check out our deep-dive write-up here.
  • 2025.04.22 Performance Update: We're excited to announce the new release of Flash MLA, which delivers 5% ~ 15% performance improvement for compute-bound workloads, achieving up to 660 TFlops on NVIDIA H800 SXM5 GPUs. The interface of the new version is fully compatible with the old one. Simply upgrade to the new version for an immediate performance boost!

Performance

Test & benchmark MLA decoding (Sparse & Dense):

bash
python tests/test_flash_mla_dense_decoding.py
python tests/test_flash_mla_sparse_decoding.py

The dense MLA decoding kernel achieves up to 3000 GB/s in memory-bound configuration and 660 TFLOPS in computation-bound configuration on H800 SXM5 with CUDA 12.8. The token-level sparse MLA decoding kernel (which uses an FP8 KV cache while performing the matrix multiplication in bfloat16) achieves 410 TFLOPS in compute-bound configuration on H800 SXM5 with CUDA 12.8, and achieves up to 700 TFlops on B200.

Test & benchmark MHA prefill (Dense):

bash
python tests/test_fmha_sm100.py

It achieves up to 1460 TFlops in forward and 1000 TFlops in backward computation on B200, as reported by NVIDIA.

Test & benchmark MLA prefill (Sparse):

bash
python tests/test_flash_mla_sparse_prefill.py

It achieves up to 640 TFlops in forward computation on H800 SXM5 with CUDA 12.8, and achieves up to 1450 TFlops on B200, CUDA 12.9.

Test & benchmark the fused norm RoPE attn RoPE cast kernel (Sparse):

bash
python tests/test_fused_norm_rope_attn_rope_cast.py

TileLang, Tile-Kernels, and DeepGEMM are required for running this test script.

This kernel fuses Q-norm (only used in V4, not V4.1), Q-RoPE, core attention, O-RoPE (conjugate) and cast-to-FP8 into a single kernel, saving times for those small kernels. Although it fuses many small operations, this kernel still keeps the same or even slightly higher TFlops (at the cost of having to permute the Q_b and Wv weights in advance). It achieves up to 1430 TFlops during prefill and 670 TFlops during decoding on B200.

Requirements

  • SM90 / SM100 (See the support matrix below)
  • CUDA 12.8 and above (CUDA 12.9+ is required for SM100 kernels)
  • PyTorch 2.0 and above

Support matrix:

Kernel GPU Architecture MLA Mode [1] Supported Models
Dense Decoding SM90 MQA DeepSeek V3 / V3.1
Sparse Decoding SM90 & SM100 MQA DeepSeek V3.2 / V4 / V4.1 [2]
Dense Prefill SM100 MHA DeepSeek V3 / V3.1 / V3.2
Sparse Prefill SM90 & SM100 MQA DeepSeek V3.2 / V4 / V4.1
Fused Norm RoPE Attn RoPE Cast SM100 MQA DeepSeek V4 / V4.1

[1]: Here "MLA Mode" refers to the mode used for MLA calculation. MQA stands for Multi-Query Attention mode (i.e. head_dim_k = 576 (for DeepSeek V3/V3.1/V3.2) or 512 (for DeepSeek V4/V4.1) with head_dim_v = 512), while MHA stands for Multi-Head Attention mode (i.e. head_dim_k = 192 / 128 with head_dim_v = 128). For a detailed explanation of these modes, please refer to the appendix of DeepSeek V3.2's Paper.

[2] Sparse Decoding for DeepSeek V4.1 is only available on SM100

Installation

bash
git clone https://github.com/deepseek-ai/FlashMLA.git flash-mla
cd flash-mla
git submodule update --init --recursive
pip install -v .

Usage

MLA Decoding

To use the MLA decoding kernels, call get_mla_metadata once before the decoding loop to get the tile scheduler metadata. Then, call flash_mla_with_kvcache in each decoding step. For example:

python
from flash_mla import get_mla_metadata, flash_mla_with_kvcache

tile_scheduler_metadata, num_splits = get_mla_metadata(
    cache_seqlens,
    s_q * h_q // h_kv,
    h_kv,
    h_q,
    is_fp8,
    topk,
)

for i in range(num_layers):
    ...
    o_i, lse_i = flash_mla_with_kvcache(
        q_i, kvcache_i, block_table, cache_seqlens, dv,
        tile_scheduler_metadata, num_splits,
        is_causal, is_fp8_kvcache, indices,
    )
    ...

Where

  • s_q is the number of q tokens per q sequence. If MTP (speculative decoding) is disabled, it should be 1.
  • h_kv is the number of key-value heads.
  • h_q is the number of query heads.

FP8 KV Cache: If is_fp8_kvcache is set to True, the kernel reads the KV cache in the "FP8 with scale" format (described below). It dequantizes the cache to bfloat16 and performs attention computation in bfloat16. The output is also in bfloat16. In this repository, is_fp8_kvcache=True is only supported together with indices (i.e. sparse attention); the dense decoding kernel reads bf16 / fp16 KV caches.

In the "FP8 with scale" format for DeepSeek V3.2 (head_dim = 576, sparse attention), a page block is page_block_size token-major rows of 656 Bytes each:

  • First 512 bytes: The "quantized NoPE" part, containing 512 float8_e4m3 values.
  • Next 16 bytes: Scale factors, containing 4 float32 values. The first float32 is the scale for the first 128 float8_e4m3 values, the second for the next 128, and so on.
  • Last 128 bytes: The "RoPE" part, containing 64 bfloat16 values. This part is not quantized for accuracy.

For DeepSeek V4 / V4.1 (head_dim = 512), the format is detected from the last dimension of k_cache (i.e. the bytes per token): 584 (V4), 528 (V4.1) or 288 (V4.1 fp4). In all three, a page block stores page_block_size data rows first and page_block_size scale rows afterwards:

  • V4: 584 Bytes per token. The data row is 448 Bytes of quantized NoPE (float8_e4m3) followed by 128 Bytes, i.e. the 64 bfloat16 RoPE values (not quantized). The scale row is 8 Bytes, of which the first 7 are float8_e8m0 scales and the 8th byte is padding; each scale covers 64 consecutive float8_e4m3 values of the NoPE part.
  • V4.1: 528 Bytes per token. The data row is 512 Bytes of float8_e4m3, i.e. the 64 RoPE dimensions are quantized as well and there is no bfloat16 part. The scale row is 16 Bytes of float8_e8m0, each scale covering 32 consecutive float8_e4m3 values.
  • V4.1 fp4: 288 Bytes per token. The data row is 256 Bytes containing 512 e2m1 values, 2 values per byte (the even-indexed one in the low nibble). The scale row is 32 Bytes of float8_e4m3, each scale covering 16 consecutive e2m1 values. This format is only valid for extra_k_cache, and only when k_cache is in the V4.1 format; otherwise extra_k_cache must have the same format as k_cache. In pratice we expect the sliding window (SWA) kv cache to be in FP8 and the compress attention (CA) kv cache to be in FP4.

See tests/quant.py for quantization and dequantization details.

Sparse Attention (indices tensor): The indices tensor (if provided) enables token-level sparse attention by instructing the kernel to compute attention only for specified tokens.

  • Shape: indices should be a 3D tensor of shape (batch_size, seq_len_q, topk).
  • Format: indices_in_kvcache[i][j][k] = (the index of the page block where token t resides) * page_block_size + (the offset of token t within the page block), where t is the k-th token for the j-th query sequence in the i-th batch. Since the index of the page block has already been encoded into indices_in_kvcache, the kernel does not require the block_table parameter.
  • Invalid entries: Set invalid indices to -1.

Return Values: The kernel returns (out, lse), where:

  • out is the attention result.
  • lse is the log-sum-exp value of the attention scores for each query head.

See tests/test_flash_mla_dense_decoding.py and tests/test_flash_mla_sparse_decoding.py for complete examples.

Sparse MLA Prefill

For the sparse MLA prefill kernel, call flash_mla_sparse_fwd directly with the following parameters:

  • q: Query tensor of shape [s_q, h_q, d_qk]
  • kv: Key-Value tensor of shape [s_kv, h_kv, d_qk]
  • indices: Indices tensor of shape [s_q, h_kv, topk]
  • sm_scale: A scalar value

Note on batching: This kernel does not support a batch dimension. For multi-batch inference, reshape the input tensors and adjust the indices parameter to simulate batch processing.

Invalid indices: Set invalid entries in indices to -1 or any number >= s_kv.

Return Values and Equivalent PyTorch Code: The kernel returns (out, max_logits, lse). This is equivalent to the following PyTorch operations:

…

See tests/test_flash_mla_sparse_prefill.py for a complete example.

Dense MHA Prefill

This kernel implements the standard dense Multi-Head Attention (MHA) forward and backward operations. It can be called using:

  • flash_attn_varlen_func
  • flash_attn_varlen_qkvpacked_func
  • flash_attn_varlen_kvpacked_func

The usage is similar to the flash_attn package. See tests/test_fmha_sm100.py for a complete example.

Fused norm + RoPE + attn + RoPE + cast kernel

In the DeepSeek-V4.1 release, we also provide a fused kernel that combines Q-norm (only used in V4, not in V4.1), Q-RoPE, core attention, O-RoPE (conjugate) and the cast to FP8 into a single kernel. It removes the extra time spent on these small kernels while keeping the same or even slightly higher TFlops, at the cost of having to permute the Q_b and Wv weights in advance.

In DeepSeek-V4.1 attention, Q ([hidden_size]) is first projected to [q_lora_rank] (the Q_a projection) and then to [num_attention_heads, head_dim] (the Q_b projection). After core attention, the output ([num_attention_heads, head_dim]) is reshaped to [o_groups, num_attention_heads // o_groups * head_dim], and each of its rows is projected to [o_lora_rank] (the Wv projection), giving an [o_groups, o_lora_rank] matrix. That matrix is reshaped to [o_groups * o_lora_rank] and finally projected to `[h

Issues· 129 open

View all issuesOpen on GitHub
  • #220

    [Portability][MSVC] GNU always_inline attributes on SM90 device lambdas fail to compile

    Updated Sep 6, 2026
  • #218

    [Portability][MSVC] Replace compound-literal-style dependent-type initialization in dense MLA decode

    Updated Aug 30, 2026
  • #217

    [Portability][MSVC] Replace __int128_t in shared-memory load/store paths 3

    Updated Aug 30, 2026
  • #212

    Sparse MLA decode is not batch-invariant: a row's output depends on its batchmates (1-2 ULP), flipping argmax at near-tie tokens

    Updated Aug 21, 2026
  • #211

    PyBind11 interface: How should function signature and CUDA error handling be handled for registered kernels?

    Updated Aug 18, 2026
  • #210

    10 rounds of hand-written fused attention that never beat a 3-kernel cuBLAS stack — trajectory, where each round died, and a correctness trap

    Updated Aug 7, 2026
  • #206

    DeepSeek-Coder-V2-Lite-Instruct 16B running locally on an RTX 2050 laptop

    Updated Aug 3, 2026
  • #204

    flashmla dense decoding test lack fp8 kv cache case

    Updated Aug 3, 2026
  • #169

    dual gemm

    Updated Jul 13, 2026
  • #172

    Use `pyproject.toml`

    Updated Jul 9, 2026

> Tags

C++

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 28, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言