MCPcopy Create free account
hub / github.com/deepseek-ai/FlashMLA

github.com/deepseek-ai/FlashMLA @main

Chat with this repo
repository ↗ · DeepWiki ↗ · + Follow
544 symbols 972 edges 78 files ⚖ MIT 54 documented · 10% ● updated 2d ago★ 13,33774 open issues

Browse by type

⨍ Functions 363◇ Types & classes 181
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

FlashMLA

Breaking change notice (2026.09.30): In the 2026.09.30 release, we removed support for the Hopper architecture and for earlier models (including DeepSeek V3 / V3.2 / V4.0), and we changed the FP8 / FP4 KV cache format. This version is therefore not compatible with previous ones. If you need to run those models or use the old KV cache format, please switch to this commit.

Introduction

FlashMLA is DeepSeek's library of optimized attention kernels, powering inference of the DeepSeek-V4.1 model on NVIDIA GPUs and Huawei Ascend NPUs. This repo contains token-level sparse attention kernels for prefill and for decoding with an FP8 / FP4 KV cache, a fused kernel that combines Q-norm, Q-RoPE, attention, O-RoPE (conjugate) and the cast to FP8, and dense attention kernels for prefill and backward. The sparse kernels power DeepSeek Sparse Attention (DSA), as introduced in this paper.

FlashMLA 是 DeepSeek 的高性能注意力算子库,支撑着 DeepSeek-V4.1 模型在 NVIDIA GPU 与华为昇腾 NPU 上的推理。该仓库支持 prefill 与使用了 FP8 或 FP4 格式的 KV 缓存的 decoding 计算,以及一个高性能的融合了 Attention 前后的小操作的融合 kernel。此外,该仓库还提供了稠密 Attention 的 prefill 与反向传播算子。

News

  • 2026.11.26 Update of Ascend Attention Kernels: We've released the fused norm+RoPE+attention+RoPE+cast kernel for the Huawei Ascend 950 NPU. We've also optimized the existing Ascend sparse prefill and decoding kernels, which now achieve up to 425 TFlops (98.5% hardware peak) and 372 TFlops (86.1% hardware peak) during prefill and decoding, respectively.

我们发布了华为昇腾 NPU 平台上的 fused norm+RoPE+attention+RoPE+cast 融合算子,同时优化了原有昇腾 Prefill、Decoding 算子的性能,在 Prefill 时能够达到 425 TFlops(98.5% 硬件极限),在 Decoding 时能够达到 372 TFlops(86.1% 硬件极限)。

  • 2026.09.30 Release of Ascend Attention Kernels: We've released sparse attention prefill and decoding kernels for the Huawei Ascend 950 NPU, which achieve up to 410 TFlops (95% hardware peak) and 360 TFlops (83% of hardware peak) during prefill and decoding, respectively. We've also released a deep-dive technical report on the algorithms and optimization techniques behind these kernels.

我们发布了华为昇腾 NPU 平台上的稀疏注意力 Prefill 和 Decoding 算子,其在 Prefill 时能够达到 410 TFlops(95% 硬件极限),在 Decoding 时能达到 360 TFlops(83% 硬件极限)。此外,我们还发布了 一篇简短的技术报告,介绍了这个算子背后所使用到的算法与优化技术。

We also optimize the performance of the fused norm-RoPE-attn-RoPE-cast kernel under decoding settings by around 10% - 15%.

我们还将 fused norm-RoPE-attn-RoPE-cast kernel 的 decoding 的性能优化了 10% - 15%。

Note that this release removes support for the Hopper architecture and for earlier models (including DeepSeek V3 / V3.2 / V4.0), and changes the FP8 / FP4 KV cache format, so it is not compatible with previous versions. If you need to run those models or use the old KV cache format, please switch to this commit.

请注意,这个版本移除了对 NVIDIA Hopper 架构显卡与前代模型(包括 DeepSeek V3 / V3.2 / V4.0)的支持,并且改变了 KV cache 的格式。如果您希望使用 Hopper 显卡、推理前代模型或者使用旧的 KV cache 格式,请切换至 这个 commit。

  • 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 the fused norm RoPE attn RoPE cast kernel (Sparse):

python tests/test-fused-norm-rope-attn-rope-cast.py

TileLang, Tile-Kernels, and DeepGEMM (DeepGEMM-Ascend for Ascend) are required to run this test script.

This kernel fuses Q-norm (only used in V4, not V4.1), Q-RoPE, core attention, O-RoPE (conjugate) and the cast to FP8 into a single kernel, which saves the overhead of those small kernels. Although it fuses many small operations, it still achieves the same or even slightly higher TFlops, at the cost of having to permute the q_b_proj and wv_proj weights in advance (only CUDA needs this permutation).

On B200 with CUDA 13.3, it achieves up to 1460 TFlops during prefill and 950 TFlops during decoding. On the Ascend 950DT NPU, it achieves up to 406 TFlops during prefill and 350 TFlops during decoding.

This kernel supports both NVIDIA GPUs (sm100 / sm103) and Huawei Ascend NPUs.

Test & benchmark MLA prefill (Sparse):

python tests/test-sparse-prefill.py

It achieves up to 1350 TFlops on B200 with CUDA 13.3. In practice, we highly recommend using the fused-norm-rope-attn-rope-cast kernel for better performance.

On the Huawei Ascend 950 NPU, it achieves up to 410 TFlops, which is 95% of the theoretical hardware peak.

Test & benchmark MLA decoding (Sparse):

python tests/test-sparse-decode.py

It achieves up to 1024 TFlops on B200 with CUDA 13.3. In practice, we highly recommend using the fused-norm-rope-attn-rope-cast kernel for better performance.

On the Huawei Ascend 950 NPU, it achieves up to 360 TFlops, which is 83% of the theoretical hardware peak.

Test & benchmark MHA prefill (Dense):

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.

This kernel currently supports CUDA only; Ascend is not supported.

Requirements

For the NVIDIA platform:

  • NVIDIA SM100 / SM103 GPU
  • CUDA 13.1 and above (CUDA 13.2 and above is recommended, since it provides the native cvt.rn.bf16x2 conversions that the quantized decoding kernels use; on CUDA 13.1 they fall back to a slower widening through FP32)
  • PyTorch 2.10 and above

For the Huawei platform:

  • Huawei Ascend 950 NPU
  • CANN 9.2.0 and above (provides the bisheng compiler and the Ascend C headers used at build time)
  • torch_npu
  • PyTorch 2.10 and above

FlashMLA CUDA wheels use PyTorch's Stable C++ ABI and CPython's Limited API (abi3, minimum CPython 3.10). A CUDA wheel built once can therefore be used with PyTorch 2.10+ and CPython 3.10+ without recompilation, subject to the GPU architectures compiled into it. On the Ascend platform, however, the wheel obtains the native device stream through an Ascend-only torch_npu bridge, and must therefore be built for a torch_npu version compatible with the installed PyTorch.

Installation

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

--no-build-isolation is required: setup.py imports torch (and torch_npu on the Ascend platform) while building, and this repository does not declare them as PEP 518 build requirements.

The build target platform is detected automatically (/dev/davinci_manager means Ascend, anything else means CUDA) and can be overridden with FLASH_MLA_BUILD_TARGET_PLATFORM=CUDA or FLASH_MLA_BUILD_TARGET_PLATFORM=ASCEND.

On the Ascend platform, ASCEND_HOME_PATH must point to the root of the CANN installation (default: /usr/local/Ascend/ascend-toolkit/latest).

After the CUDA extension is built, a register-spill check runs over the produced .so. The CUTLASS FMHA kernels are exempt, but if any kernel defined by this repository spills registers the build fails with "Register spilling detected. Build failed!"; export FLASH_MLA_SKIP_REG_SPILL_CHECK=1 to skip the check.

Usage

DeepSeek Sparse Attention (DSA) Decoding

To use the DSA 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:

from flash_mla import get_mla_metadata, flash_mla_with_kvcache

tile_scheduler_metadata, num_splits = get_mla_metadata()    # A placeholder only. The actual scheduling metadata is generated on the first call to flash_mla_with_kvcache

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,
        indices=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 / FP4 KV Cache Format

For decoding, this kernel currently supports only the FP8 and FP4 KV cache formats. Unquantized (bfloat16) KV cache format is not supported.

For DeepSeek V4.1 (head_dim = 512), the format is detected from the last dimension of k_cache (i.e. the bytes per token): 528 (V4.1) or 288 (V4.1 fp4). In both formats, each token stores its quantized raw data first, followed immediately by its scales:

  • V4.1 (528 bytes per token): the first 512 bytes are float8_e4m3 values covering all 512 dimensions. The 64 RoPE dimensions are quantized as well, so there is no bfloat16 part. The last 16 bytes are float8_e8m0 scales, one for every 32 consecutive float8_e4m3 values.
  • V4.1 fp4 (288 bytes per token): the first 256 bytes contain 512 e2m1 values, 2 values per byte, the even-indexed one in the low nibble. The last 32 bytes are float8_e4m3 scales, one for every 16 consecutive e2m1 values. This format is only valid for extra_k_cache when k_cache is in the V4.1 format.

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

indices Tensor

The indices tensor 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 use the block_table parameter; you still have to pass it, since it is a required positional argument of flash_mla_with_kvcache (None is fine).
  • Invalid entries: Set invalid indices to -1.

Return Values

The kernel returns (out, lse), where: - out is the attention result, [batch_size, seq_len_q, h_q, head_dim_v], bfloat16. - lse is the log-sum-exp value of the attention scores for each query head, [batch_size, h_q, seq_len_q], float32. Its shape is transposed with respect to out.

See tests/test-sparse-decode.py for complete examples.

DeepSeek Sparse Attention (DSA) Prefill

For the DSA 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 - d_v: Optional, the dimension of the value vectors. Can only be 512, which is also the default. - attn_sink: Optional, [h_q], float32. If provided, the output is additionally scaled by exp(lse) / (exp(lse) + exp(attn_sink)). It has no effect on the returned lse and max_logits. - topk_length: Optional, [s_q], int32. If provided, the i-th query token only attends to the first topk_length[i] indices.

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), where max_logits and lse are in the natural logarithm. This is equivalent to the following PyTorch operations:

```python Q: [s_q, h_q, d_qk], bfloat16 kv: [s_kv, h_kv, d_qk], bfloat16 indices: [s_q, h_kv, topk], int32

kv = kv.squeeze(1) # [s_kv, d_qk], h_kv must be 1 indices = indices.squeeze(1) # [s_q, topk] invalid = (indices < 0) | (indices >= s_kv) # [s_q, topk], the kernel ignores th

Core symbols most depended-on inside this repo

browse all functions →

Shape

Method 205
Class 161
Function 158
Enum 20

Languages

C++75%
Python25%

Modules by API surface

csrc/sm100/prefill/dense/kernel/sm100_fmha_bwd_mla_kernel_tma_warpspecialized.hpp28 symbols
csrc/sm100/prefill/dense/kernel/sm100_fmha_bwd_kernel_tma_warpspecialized.hpp28 symbols
csrc/sm100/prefill/dense/collective/fmha_fusion.hpp28 symbols
tests/lib.py24 symbols
csrc/sm100/prefill/dense/kernel/sm100_fmha_fwd_kernel_tma_warpspecialized.hpp20 symbols
csrc/sm100/prefill/dense/common/gather_tensor.hpp18 symbols
csrc/sm100/prefill/dense/collective/sm100_fmha_mla_fwd_mainloop_tma_warpspecialized.hpp17 symbols
benchmark/bench_flash_mla.py17 symbols
csrc/sm100/prefill/dense/collective/sm100_fmha_fwd_mainloop_tma_warpspecialized.hpp16 symbols
csrc/api/sparse_decode.h16 symbols
csrc/api/common.h14 symbols
tests/kernelkit/bench.py13 symbols

For agents

$ claude mcp add FlashMLA \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page