RESEARCH NOTE 雙語閱讀 · 重點批註

FlashAttention-4: Algorithm and Kernel Pipelining Co-Design for Asymmetric Hardware Scaling

Ted Zadouri, Markus Hoehnerbach, Jay Shah, Timmy Liu, Vijay Thakkar, Tri DaoarXiv 預印本2026

arXiv:2603.05451v1

模型:gpt-6-astra · REASONING:medium · DETAIL:high
輸入:29,965 tokens · 輸出:27,641 tokens(思考:812 tokens、其他輸出:26,829 tokens) · 總計:57,606 tokens

一句話掌握THE TAKEAWAY

FlashAttention-4 針對 Blackwell「矩陣乘法變快、其他單元未同步變快」的新瓶頸,協同設計 attention 演算法、記憶體配置與 GPU 核心流水線。

研究問題

當 tensor core 吞吐量成長快於指數運算與共享記憶體頻寬時,如何重設 attention 前向與反向傳播,使非矩陣乘法資源不再拖慢整體效能?

動機

FlashAttention-3 的暫存器配置、MMA 指令與流水線主要針對 Hopper;Blackwell 改用非同步寫入 TMEM 的 MMA、更大的運算 tile 與 2-CTA 協作模式,不能只靠移植舊核心充分利用新硬體。

方法

先以各硬體資源的每 tile 週期需求定位瓶頸,再設計前向 ping-pong 流水線、部分指數函數軟體模擬與條件式 softmax 重新縮放;反向則利用 TMEM 跨迭代重疊運算,並透過 2-CTA MMA 與 DSMEM 降低共享記憶體流量及全域原子歸約次數。另以快取感知排程改善負載平衡,並用 CuTe-DSL 實作。

主要貢獻

  • 把 attention 最佳化的焦點從單純減少 HBM 存取,推進到辨識並平衡 MMA、指數單元與共享記憶體的資源需求。
  • 前向利用 TMEM 與非同步 MMA 重疊 softmax;將部分指數運算移至 FMA 單元,並略過不必要的輸出重新縮放。
  • 反向以跨迭代流水線及 2-CTA 資料重排降低共享記憶體負擔,同時將全域原子歸約次數減半。
  • 提供快取感知的 LPT 排程、可重現的確定性反向模式,以及完全以 Python 內嵌 CuTe-DSL 撰寫的可組合實作。

主要結果

  • 正文報告 BF16 前向相較 cuDNN 9.13 最高加速 1.3 倍、相較 Triton 最高加速 2.7 倍,並主打最高 1613 TFLOPs/s、約 71% 理論峰值利用率。
  • 反向 roofline 估算中,共享記憶體需求由 1-CTA 的 3328 cycles 降至 2-CTA 的 2688 cycles;對應 MMA 需求皆為 2560 cycles,使兩者差距由約 30% 降至約 5%。
  • 三次多項式的 FP32 指數近似誤差高於硬體指令,但轉成 BF16 後,誤差主要由 BF16 量化決定;此證據來自區間內 4M 隨機輸入測試。
  • 單一核心編譯時間由 FA3 的前向 55s、反向 45s,降為 FA4 的 2.5s、1.4s。
  • 較新版 cuDNN 已納入本文部分技術;Figure 4 顯示其前向效能與 FA4 接近,不能把對 cuDNN 9.13 的加速幅度外推到所有版本。

限制

  • 主要證據是 attention 核心微基準測試,未提供完整模型訓練吞吐量、收斂品質或端到端推論延遲的驗證。
  • roofline 是簡化模型,未納入所有資源,例如暫存器頻寬、一般浮點運算與 L2 頻寬;表中的週期數不是實測核心延遲。
  • 指數近似的精度論證主要針對 BF16 消費端;不能據此宣稱 FP32 精度等同硬體指數運算,或所有輸入分布下的完整 attention 誤差均已驗證。
  • 確定性反向仍有同步與等待成本;正文的「最高 75%」是相對於非確定性的 1-CTA 反向版本,不是相對於最快的 2-CTA 版本。
  • PDF 存在需要釐清的記載差異:正文與圖說稱 B200,附錄卻寫 B100;首頁日期為 2026 年 3 月,附錄稱寫作時間為 March 2025。
  • 正文主打最高 1613 TFLOPs/s,但 Figure 5 的不同 head-dimension 設定標出 1654;引用峰值時應註明對應圖表與設定。
  • 條件式重新縮放的文字採用以 2 為底的閾值說明,更新公式則寫成自然指數形式;實作時需確認尺度轉換,不能直接混用。
重要度
回到頂端 ↑

1. 研究問題與缺口:非對稱硬體成長使瓶頸轉移

核心缺口不是 attention 缺少更快的矩陣乘法,而是舊有核心無法適應 tensor core 與其他硬體單元成長速度不一致的情況。作者因此把演算法調整與硬體流水線視為同一個設計問題。

p. 2

原文 SOURCE

A critical trend in accelerator evolution is the asymmetric scaling of hardware units. Although Blackwell B200 doubles the tensor core throughput compared to Hopper H100 (2.25 PFLOPS vs. 1 PFLOPS for FP16/BF16), other functional units (shared memory bandwidth, exponential units, and integer/floating point ALUs) scale more slowly or remain unchanged. As a result, non-MMA resources emerge as bottlenecks. Our roofline analysis (Sections 3.1 and 3.2) reveals that for typical attention workloads on Blackwell, surprisingly, shared memory traffic and exponential operations now dominate execution time, exceeding MMA compute by 25-60%. Additionally, Blackwell introduces new architectural features: 256 KB of tensor memory (TMEM) per SM for storing intermediate tensor core results, 128×128 MMA tiles (double the area of Hopper’s 64×128), and fully asynchronous tensor core operations that write directly to TMEM. Simply porting existing attention algorithms to this new hardware either leaves significant performance on the table or is impossible due to lack of forward compatibility for Hopper MMA instructions.

繁體中文 TRANSLATION

加速器演進的一項關鍵趨勢,是各硬體單元的成長並不對稱。雖然 Blackwell B200 的 tensor core 吞吐量相較 Hopper H100 約增加一倍(FP16/BF16 為 2.25 PFLOPS,相較於 1 PFLOPS),其他功能單元(共享記憶體頻寬、指數運算單元,以及整數/浮點 ALU)的成長卻較慢,甚至維持不變。因此,非 MMA 資源開始成為瓶頸。我們的 roofline 分析(第 3.1 與 3.2 節)顯示,出乎意料地,Blackwell 上典型 attention 工作負載的執行時間,現在主要受共享記憶體流量與指數運算支配,所需時間比 MMA 計算多出 25–60%。此外,Blackwell 引入新的架構特性:每個 SM 配備 256 KB 的 tensor memory(TMEM),用於儲存 tensor core 的中間結果;採用 \(128\times128\) MMA tile(面積是 Hopper \(64\times128\) 的兩倍);以及可直接寫入 TMEM 的全非同步 tensor core 運算。只把現有 attention 演算法移植到新硬體上,不是會浪費大量效能,就是因 Hopper MMA 指令不具向前相容性而無法執行。

2. 必要硬體概念:TMEM 與 2-CTA MMA

TMEM 將 MMA 累加器移出暫存器,擴大流水線重排空間;2-CTA MMA 則讓兩個 CTA 協作讀取運算元與保存輸出,但也引入固定配對與資料分割限制。

p. 3

原文 SOURCE

Blackwell introduces a new memory level called tensor memory (TMEM), a 256 KB on-chip memory per SM specifically designed for storing intermediate results of tensor core operations. Unlike shared memory, TMEM is warp-synchronous and tightly coupled with the tensor cores, enabling the matrix multiply-accumulate (MMA) units to write outputs directly to TMEM without consuming registers. This alleviates the extreme register pressure that plagued Hopper kernels and enables larger tile sizes. TMEM is allocated in 32-column (16 KB) granules and requires explicit programmer management for allocation, deallocation, and data movement.

繁體中文 TRANSLATION

Blackwell 引入稱為 tensor memory(TMEM)的新記憶體層級:每個 SM 擁有 256 KB 的晶片內記憶體,專門儲存 tensor core 運算的中間結果。TMEM 與共享記憶體不同,採取 warp 同步的操作方式,且與 tensor core 緊密耦合,使矩陣乘加(MMA)單元能直接把輸出寫入 TMEM,而不占用暫存器。這緩解了困擾 Hopper 核心的嚴重暫存器壓力,也讓更大的 tile 成為可能。TMEM 以 32 欄(16 KB)為配置單位,其配置、釋放與資料搬移都需要程式設計者明確管理。

p. 4

原文 SOURCE

2-CTA tensor core: Blackwell supports a 2-CTA tensor core MMA mode in which a CTA pair within the same thread block cluster cooperatively executes a single MMA, allowing the operation to read and write tensor memory from both CTAs. One thread in the pair initiates the MMA, but the peer CTA must be launched and remain active while the operation is in flight. Compared to single CTA MMAs that limit the dimension M to 128, the paired mode supports M = 128 or 256 by partitioning the A tile and the accumulator across the pair in dimension M and partitioning the B tile across the two CTAs in dimension N so that each CTA stages only half of B in its own shared memory while the hardware consumes the combined B tile during the multiply. This reduces redundant shared memory capacity and bandwidth, but since these operations touch tensor memory across the CTA pair, kernels must launch CTAs in fixed pairs and use a consistent 2-CTA mode for tensor memory and tensor core operations throughout the kernel.

繁體中文 TRANSLATION

2-CTA tensor core:Blackwell 支援 2-CTA tensor core MMA 模式,同一個 thread block cluster 內的一對 CTA 可協同執行一次 MMA,讓該運算讀寫兩個 CTA 的 tensor memory。配對中的一個執行緒負責發起 MMA,但在運算進行期間,另一個 CTA 必須已啟動且持續處於活動狀態。相較於將維度 \(M\) 限制為 128 的單一 CTA MMA,配對模式支援 \(M=128\) 或 256:它沿 \(M\) 維度把 A tile 與累加器分給兩個 CTA,並沿 \(N\) 維度分割 B tile,使各 CTA 只需在自己的共享記憶體暫存一半的 B,而硬體在乘法期間使用合併後的 B tile。這能減少重複占用的共享記憶體容量與頻寬;不過,由於這些運算會跨 CTA 配對存取 tensor memory,核心必須以固定配對啟動 CTA,且整個核心中的 tensor memory 與 tensor core 運算都必須一致使用 2-CTA 模式。

3. 前向設計:平衡 MMA、指數運算與重新縮放

前向的代表性設定中,指數運算與 MMA 有相同的理想週期需求。FA4 先讓兩者充分重疊,再用部分軟體指數模擬分散負載,並將可避免的重新縮放移出關鍵路徑。

p. 5

原文 SOURCE

Table 1 summarizes the analysis for two typical tile configurations. For \(M=N=d=128\), the resources are well-balanced, with shared memory (768 cycles) being slightly lower than both MMA compute and exponential unit (both 1024 cycles). For the larger tile size \(M=256, N=d=128\), the shared memory traffic increases to 1536 cycles due to reading MMA operands multiple times, while MMA compute and exponential unit double to 2048 cycles. This analysis motivates our kernel design to (1) use large tile sizes and maximize overlap between MMA operations and softmax computations (2) increase the throughput of exponential by using other hardware units (3) reduce the time of unnecessary non-matmul operations.

繁體中文 TRANSLATION

Table 1 彙整了兩種典型 tile 配置的分析。當 \(M=N=d=128\) 時,各資源需求相當平衡,共享記憶體所需的 768 cycles,略低於 MMA 計算與指數單元所需的時間(兩者皆為 1024 cycles)。當 tile 增大為 \(M=256, N=d=128\) 時,由於 MMA 運算元會被多次讀取,共享記憶體流量所需時間增為 1536 cycles,而 MMA 計算與指數單元所需時間都加倍至 2048 cycles。這項分析引導我們的核心設計採取三個方向:(1)使用大型 tile,並盡量重疊 MMA 運算與 softmax 計算;(2)利用其他硬體單元提高指數運算吞吐量;(3)減少不必要的非矩陣乘法運算時間。

Table 1原始 PDF 第 6 頁

Roofline analysis (cycles) for the attention forward pass. For both tile sizes, MMA compute and exponential unit are the primary bottlenecks.attention 前向傳播的 roofline 分析(單位:cycles)。兩種 tile 大小的主要瓶頸都是 MMA 計算與指數單元。
Resource\(128^3\)\(256\times128^2\)
MMA compute**1024****2048**
Shared memory7681536
Exponential unit**1024****2048**

表格註記:粗體依原表保留,表示主要瓶頸的週期數。此為簡化模型,未涵蓋暫存器頻寬、L2 頻寬與所有一般運算成本。

這張表在說什麼

表格把同一次 tile 迭代對不同硬體資源的需求換成時脈週期,以便直接比較。兩種設定都顯示指數單元與 MMA 同樣吃重,共享記憶體則稍低。

怎麼看

先選一個 tile 設定欄,向下比較三種資源;數值越大表示該資源需要服務的時間越長,而非效能越好。再橫向看 tile 加大後,三者都加倍,代表單靠放大 tile 並未消除指數瓶頸。

p. 6

原文 SOURCE

Since the Blackwell architecture doubled the tensor core flops again, taking care to overlap softmax and tensor core operations is even more crucial than on Hopper. We follow a ping-pong schedule similar to FA-3, where two tiles of the output are computed per thread block. While one tile’s tensor core operations are executed, the other tile computes softmax. While Hopper tensor cores hold the accumulator in registers, with four threads per row in an interleaved pattern, Blackwell tensor cores hold their accumulators in tensor memory. Additionally, a single accumulator tile on Blackwell is 128 by 128 elements large, where Hopper’s tile size was 64 by 128. The natural way to distribute work across these tiles is then to have two warpgroups of 128 threads each, with each thread processing an entire row. This eliminates the need for inter-warp shuffles to reduce the row max, and for multiple statistics registers per thread. Just like with FA-3, we explicitly synchronize the two softmax warpgroups to not overlap in their critical section, which is the part of exponential computation. Each softmax warpgroup proceeds by first loading the entire row into registers, then computing the maximum, then computing the softmax (i.e., subtract the max, rescale, exponentiate, convert to input precision), and finally computing the row sum. Another difference from FA-3 is that since we transfer P via tensor memory rather than register file, we can decouple the rescaling of the output to a separate “correction” warpgroup and thus take it out of the critical path.

繁體中文 TRANSLATION

由於 Blackwell 架構再次讓 tensor core 的 FLOPS 加倍,仔細安排 softmax 與 tensor core 運算重疊,比在 Hopper 上更加重要。我們沿用類似 FA-3 的 ping-pong 排程,每個 thread block 計算兩個輸出 tile。當其中一個 tile 執行 tensor core 運算時,另一個 tile 就計算 softmax。Hopper 的 tensor core 將累加器保存在暫存器中,每列由四個執行緒以交錯模式持有;Blackwell 的 tensor core 則將累加器保存在 tensor memory。此外,Blackwell 的單一累加器 tile 大小是 \(128\times128\) 個元素,而 Hopper 的 tile 大小為 \(64\times128\)。 因此,在這些 tile 之間分派工作的自然方式,是使用兩個各含 128 個執行緒的 warpgroup,每個執行緒處理完整的一列。這消除了為了歸約列最大值而進行跨 warp shuffle 的需要,也不再需要每個執行緒持有多組統計值暫存器。與 FA-3 相同,我們明確同步兩個 softmax warpgroup,避免它們的關鍵區段重疊,也就是指數計算的部分。每個 softmax warpgroup 都先將整列載入暫存器,再計算最大值,接著計算 softmax(亦即減去最大值、縮放、取指數、轉為輸入精度),最後計算列總和。 另一個與 FA-3 的差異是,我們透過 tensor memory 而非暫存器檔傳遞 P,因此可以把輸出重新縮放拆給獨立的「correction」warpgroup,將它移出關鍵路徑。

Figure 1原始 PDF 第 6 頁

FlashAttention-4 forward pipeline. The superscript \(H\) denotes the matrices corresponding to the ”high” Q tile, and superscript \(L\) denotes matrices corresponding to the ”low” Q tile. Each Q tile corresponds to 128 query tokens.FlashAttention-4 的前向流水線。上標 \(H\) 表示對應「high」Q tile 的矩陣,上標 \(L\) 表示對應「low」Q tile 的矩陣。每個 Q tile 對應 128 個 query token。

這張圖在說什麼

左圖呈現每個 CTA 負責兩個 Q tile,並沿 K、V tile 執行內層迴圈。右圖將兩個 Q tile 的 MMA 與 softmax 排成 ping-pong 時序,示範如何在指數計算期間推進另一個 tile 的矩陣乘法。

怎麼看

先看左側 Q 列與 CTA 的對應,再沿內層迴圈理解 K、V 的分塊掃描。右侧由左往右是時脈週期,對照 tensor core 與 MUFU.EX2 各列:圖中單次 GEMM 標為 512 cycles,softmax 指數工作標為 1024 cycles;觀察兩個 tile 的工作如何交錯,而非把這張示意圖當成完整核心的實測時間線。

p. 7

原文 SOURCE

Software emulation via polynomial approximation. To increase exponential throughput, we implement a software emulation of \(2^x\) using floating-point FMA units, which can operate in parallel with MUFU. We use the classical range reduction technique (Cody-Waite) and then the polynomial approximation [16]. The key insight is to decompose the exponential computation: \[2^x=2^{\lfloor x\rfloor}2^{x-\lfloor x\rfloor}\tag{4}\] where \(\lfloor x\rfloor\) is the integer part and \(x-\lfloor x\rfloor\in[0,1)\) is the fractional part. The integer part \(2^{\lfloor x\rfloor}\) can be computed efficiently using bit manipulation of the IEEE 754 floating-point representation. Since the exponent field directly represents powers of two, computing \(2^{\lfloor x\rfloor}\) amounts to a shift and add operation on the exponent bits, which can be done using integer ALU instructions. For the fractional part, we approximate \(2^{x_{\mathrm{frac}}}\) where \(x_{\mathrm{frac}}\in[0,1)\) using a polynomial: \[2^{x_{\mathrm{frac}}}\approx\sum_{i=0}^{n}p_i x_{\mathrm{frac}}^i\tag{5}\] with \(p_0=1.0\) and the remaining coefficients chosen to minimize the relative approximation error over \([0,1)\), calculated using the Sollya software package [4]. The polynomial evaluation uses Horner’s method with FMA instructions, achieving high throughput.

繁體中文 TRANSLATION

以多項式近似進行軟體模擬。為提高指數運算吞吐量,我們使用浮點 FMA 單元實作 \(2^x\) 的軟體模擬,而這些單元可與 MUFU 平行運作。我們先使用經典的範圍縮減技術(Cody-Waite),再套用多項式近似 [16]。關鍵想法是將指數運算分解為: \[2^x=2^{\lfloor x\rfloor}2^{x-\lfloor x\rfloor}\tag{4}\] 其中 \(\lfloor x\rfloor\) 是整數部分,\(x-\lfloor x\rfloor\in[0,1)\) 是小數部分。 整數部分 \(2^{\lfloor x\rfloor}\) 可以透過對 IEEE 754 浮點表示進行位元操作來有效率地計算。由於指數欄位直接表示 2 的次方,計算 \(2^{\lfloor x\rfloor}\) 相當於對指數位元進行位移與加法,可用整數 ALU 指令完成。 對小數部分,我們用多項式近似 \(2^{x_{\mathrm{frac}}}\),其中 \(x_{\mathrm{frac}}\in[0,1)\): \[2^{x_{\mathrm{frac}}}\approx\sum_{i=0}^{n}p_i x_{\mathrm{frac}}^i\tag{5}\] 其中 \(p_0=1.0\),其餘係數由 Sollya 軟體套件 [4] 計算,目標是將 \([0,1)\) 區間內的相對近似誤差降到最低。多項式透過 Horner 法搭配 FMA 指令求值,以達到高吞吐量。

p. 8

原文 SOURCE

Partial emulation. Although polynomial emulation increases exponential throughput, it comes at a cost: additional registers (to hold intermediate values and coefficients), higher register bandwidth consumption, and longer latency compared to the MUFU instruction. Using emulation for all exponential evaluations would increase register pressure and could cause spills that negate the throughput benefit. Instead, we apply emulation to only a subset of the entries in each softmax row (10–25%), with the remaining entries computed via hardware MUFU.EX2. The exact fraction is tuned empirically based on the ratio of MMA and exponential throughput for a given tile configuration. Numerical accuracy. Table 2 compares the accuracy of polynomial approximations of different degrees against the hardware MUFU.EX2 instruction, measured on 4M random inputs in \([0,1)\). We report two metrics: the FP32-level error (before any quantization) and the BF16-level error (after rounding the FP32 output to BF16), both measured against a FP64 reference. At the FP32 level, the degree-3 polynomial has a maximum relative error of \(8.8\times10^{-5}\), roughly 600× higher than hardware. However, after rounding to BF16, the errors become nearly indistinguishable: the quantization error of BF16 (\(\sim3.9\times10^{-3}\)) dominates the polynomial approximation error for all degrees \(\geq3\). The degree-3 polynomial matches hardware to within 1 BF16 ULP on 99% of inputs, which is sufficient for attention computation where the softmax output is consumed with BF16 precision. Higher-degree polynomials close the FP32 gap: degree 5 matches hardware to within 2× in maximum relative error, at the cost of two additional FMA instructions per evaluation.

繁體中文 TRANSLATION

部分模擬。雖然多項式模擬提高了指數運算吞吐量,卻也有代價:需要額外暫存器來保存中間值與係數、消耗更多暫存器頻寬,且延遲比 MUFU 指令更長。若所有指數求值都使用模擬,會增加暫存器壓力,甚至導致 spill,抵銷吞吐量收益。因此,我們只對每列 softmax 中的一部分元素(10–25%)使用模擬,其餘元素仍由硬體 MUFU.EX2 計算。具體比例依給定 tile 配置下 MMA 與指數運算的吞吐量比值,透過實驗調整。 數值精度。Table 2 在 \([0,1)\) 區間的 4M 個隨機輸入上,比較不同次數的多項式近似與硬體 MUFU.EX2 指令的精度。我們報告兩種指標:FP32 層級的誤差(尚未進行任何量化),以及 BF16 層級的誤差(將 FP32 輸出捨入為 BF16 之後),兩者都以 FP64 結果為參考。 在 FP32 層級,三次多項式的最大相對誤差為 \(8.8\times10^{-5}\),約為硬體的 600 倍。然而,捨入為 BF16 後,誤差幾乎無法區分:對所有次數 \(\geq3\) 的多項式,BF16 的量化誤差(\(\sim3.9\times10^{-3}\))都大於多項式近似誤差。三次多項式在 99% 的輸入上與硬體結果相差不超過 1 個 BF16 ULP,對於以 BF16 精度使用 softmax 輸出的 attention 計算而言已足夠。更高次的多項式能縮小 FP32 精度差距:五次多項式的最大相對誤差在硬體的 2 倍以內,但每次求值要多使用兩條 FMA 指令。

Table 2原始 PDF 第 8 頁

Accuracy of \(2^x\) polynomial emulation on \([0,1)\), measured against FP64 reference on 4M random inputs. FP32 columns measure the raw polynomial output; BF16 columns measure after rounding to BF16. The BF16 quantization error dominates for all degrees \(\geq3\).在 \([0,1)\) 區間內,以 4M 個隨機輸入、相對於 FP64 參考值測量 \(2^x\) 多項式模擬的精度。FP32 欄測量原始多項式輸出;BF16 欄測量捨入成 BF16 後的結果。對所有次數 \(\geq3\) 的多項式,誤差都由 BF16 量化誤差主導。
MethodFP32 vs FP64 / Max rel errFP32 vs FP64 / Mean rel errBF16 vs FP64 / Max rel errBF16 vs FP64 / Mean rel err
Ideal (FP64→BF16)——\(3.89\times10^{-3}\)\(1.41\times10^{-3}\)
Hardware MUFU.EX2\(1.41\times10^{-7}\)\(3.04\times10^{-8}\)\(3.89\times10^{-3}\)\(1.41\times10^{-3}\)
Degree 3\(8.77\times10^{-5}\)\(5.43\times10^{-5}\)\(3.90\times10^{-3}\)\(1.41\times10^{-3}\)
Degree 4\(3.05\times10^{-6}\)\(1.84\times10^{-6}\)\(3.89\times10^{-3}\)\(1.41\times10^{-3}\)
Degree 5\(1.44\times10^{-7}\)\(5.48\times10^{-8}\)\(3.89\times10^{-3}\)\(1.41\times10^{-3}\)

表格註記:原表雙層表頭以「群組 / 欄名」展平;破折號保留原表缺值。

這張表在說什麼

未量化前,三次近似確實遠不如硬體準確;但轉成 BF16 後,各方法的誤差落在幾乎相同的範圍。Ideal 列提供純粹由 FP64 轉 BF16 的誤差基準,支持作者關於量化主導的解釋。

怎麼看

先看 Ideal 列建立 BF16 誤差底限,再比較 Hardware 與 Degree 3 的 FP32 最大誤差,最後轉到 BF16 欄。所有誤差指標越低越好;測試對象是區間內的指數函數求值,不是完整 attention 輸出或模型品質。

p. 9

原文 SOURCE

Conditional rescaling. The step \(e^{m_{j-1}-m_j}O_{j-1}\) requires a vector multiplication. We make two simple observations: 1. Rescaling is only necessary when \(m_j>m_{j-1}\), i.e., when new larger values are found. 2. We can tolerate some ”slack” in the rescaling: only rescale when \(m_j-m_{j-1}>\tau\), where \(\tau\) is a threshold (typically set to \(\log_2(256)=8.0\), corresponding to a rescaling factor of 256.0). As long as we keep track of the statistics (the total scaling we have done), we can still get the true denominator at the end to get the right final output. In FlashAttention-4, we modify the algorithm as: \[O_j=\begin{cases}e^{m_{j-1}-m_j}O_{j-1}+e^{S_j-m_j}V_j&\text{if }m_j-m_{j-1}>\tau\\O_{j-1}+e^{S_j-m_{j-1}}V_j&\text{otherwise}\end{cases}\tag{6}\] When \(m_j-m_{j-1}\leq\tau\), we skip updating m and continue using \(m_{j-1}\). This maintains the correctness because at the end of the computation, all accumulated values are renormalized by the true maximum \(m_{\mathrm{final}}\) and the final normalizer \(\ell_{\mathrm{final}}\): \[\mathrm{Output}=\frac{1}{\ell_{\mathrm{final}}}O_{\mathrm{final}}\] This modification significantly reduces the number of rescaling operations while maintaining numerical accuracy, as the final normalization step corrects any small deviations introduced by skipping intermediate rescaling. In practice, to avoid warp divergence, we rescale when any of the threads in the warp needs rescaling.

繁體中文 TRANSLATION

條件式重新縮放。步驟 \(e^{m_{j-1}-m_j}O_{j-1}\) 需要一次向量乘法。我們提出兩個簡單觀察: 1. 只有當 \(m_j>m_{j-1}\),也就是找到新的更大值時,才需要重新縮放。 2. 我們可以容許重新縮放保留一些「餘裕」:只有在 \(m_j-m_{j-1}>\tau\) 時才重新縮放,其中 \(\tau\) 是閾值(通常設為 \(\log_2(256)=8.0\),對應 256.0 的縮放因子)。只要持續追蹤統計值,也就是已執行的總縮放量,最後仍能得到真正的分母,進而取得正確的最終輸出。 在 FlashAttention-4 中,我們將演算法修改為: \[O_j=\begin{cases}e^{m_{j-1}-m_j}O_{j-1}+e^{S_j-m_j}V_j&\text{若 }m_j-m_{j-1}>\tau\\O_{j-1}+e^{S_j-m_{j-1}}V_j&\text{其他情況}\end{cases}\tag{6}\] 當 \(m_j-m_{j-1}\leq\tau\) 時,我們略過 m 的更新,繼續使用 \(m_{j-1}\)。這能維持正確性,因為計算結束時,所有累加值都會透過真正的最大值 \(m_{\mathrm{final}}\) 與最終正規化因子 \(\ell_{\mathrm{final}}\) 重新正規化: \[\mathrm{Output}=\frac{1}{\ell_{\mathrm{final}}}O_{\mathrm{final}}\] 這項修改在維持數值精度的同時,大幅減少重新縮放次數,因為最終正規化步驟會修正略過中間重新縮放所引入的微小偏差。 實務上,為避免 warp divergence,只要 warp 中任何執行緒需要重新縮放,我們就會執行重新縮放。

4. 反向設計:從共享記憶體瓶頸到 2-CTA 資料重排

反向每次迭代包含五次 MMA,主要限制改為共享記憶體流量。FA4 先用 TMEM 改排相鄰迭代的工作,再以 2-CTA 與 DSMEM 重組 dQ,降低運算元載入及原子累加成本。

p. 10

原文 SOURCE

Table 3 summarizes the analysis for the typical tile configuration \(M=N=d=128\). The shared memory traffic time of 3328 cycles exceeds both the MMA compute time (2560 cycles) and the exponential unit time (1024 cycles), indicating that shared memory bandwidth is the primary bottleneck, though less severely than global memory traffic would suggest. This motivates our kernel design to maximize overlap between MMA operations and other computations to hide shared memory latency.

繁體中文 TRANSLATION

Table 3 彙整了典型 tile 配置 \(M=N=d=128\) 的分析。共享記憶體流量所需的 3328 cycles,超過 MMA 計算時間(2560 cycles)與指數單元時間(1024 cycles),顯示共享記憶體頻寬是主要瓶頸,不過其嚴重程度低於全域記憶體流量所暗示的情況。這促使我們的核心設計盡量重疊 MMA 運算與其他計算,以隱藏共享記憶體延遲。

Table 3原始 PDF 第 11 頁

Roofline analysis for the attention backward pass with \(M=N=d=128\). Shared memory traffic is the bottleneck, exceeding MMA compute time by approximately 30%. In the 2-CTA setting with \(M=256\) and \(N=d=128\) (with an exception to the dQ mma, with \(M=N=128\) and \(d=256\)), shared memory traffic exceeds MMA compute time by approximately 5%.在 \(M=N=d=128\) 下,attention 反向傳播的 roofline 分析。共享記憶體流量是瓶頸,所需時間比 MMA 計算約高 30%。在 \(M=256\)、\(N=d=128\) 的 2-CTA 設定中(dQ MMA 例外,採 \(M=N=128\)、\(d=256\)),共享記憶體流量所需時間僅比 MMA 計算約高 5%。
ResourceCycles (\(N=d=128\)) / 1-CTA (\(M=128\))Cycles (\(N=d=128\)) / 2-CTA (\(M=256\))
MMA compute25602560
Shared memory (MMA operands)20481536
Shared memory (dS write)256256
Shared memory (dS DSMEM)0384
Shared memory (dQ write + read)1024512
Total shared memory\(\underline{\mathbf{3328}}\)\(\underline{\mathbf{2688}}\)
Exponential unit10241024

表格註記:雙層表頭已展平;總共享記憶體數值保留原表粗體與底線。表說對 dQ 的維度命名與正文的重排描述使用不同表達方式,這裡忠實保留表說,理解資料流時請配合 Figure 3。

這張表在說什麼

2-CTA 不只降低 MMA 運算元流量,也把 dQ 寫入與回讀的週期需求減半;代價是新增 DSMEM 交換。總共享記憶體需求仍下降,且更接近 MMA 計算需求。

怎麼看

先比較最後的 Total shared memory 與 MMA compute,再往上追查流量下降的來源。接著注意 dS DSMEM 從 0 增為 384,理解此方法不是沒有通訊成本;數字是各設定的資源週期估算,不是端到端加速比,週期需求越低越有利。

p. 11

原文 SOURCE

In FA-4, TMEM enables additional schedules compared to FA-3 that provide significant overlap between MMA and non-MMA operations. Specifically, just as with the forward pass, we are trying to hide the latency of the softmax calculation. In FA-3, the softmax computation overlaps with the MMA for dP. From the previous section, we know that on Blackwell we need at least two MMA operations to run concurrently. We achieve this by using the dQ and dK MMA’s of the previous iteration. This requires careful management of shared memory and tensor memory resources between loading, MMA, compute, and reduction operations. In particular, note that we do not have sufficient tensor memory to fit five accumulator tiles. At most, four tiles of 128 by 128 elements can fit and dV and dK accumulate, and thus cannot share their space. In our implementation, we have S and P share one of the tmem blocks (at offset 0) and we have dP, dS and dQ share the other one. We demonstrate the computational graph of the FA-4 bwd in Figure 2.

繁體中文 TRANSLATION

相較於 FA-3,FA-4 的 TMEM 允許更多排程方式,讓 MMA 與非 MMA 運算得以大幅重疊。具體而言,與前向傳播相同,我們試圖隱藏 softmax 計算的延遲。在 FA-3 中,softmax 計算與 dP 的 MMA 重疊。根據前一節,我們知道在 Blackwell 上至少需要讓兩次 MMA 運算與之並行。 我們透過使用前一次迭代的 dQ 與 dK MMA 達成這點。這需要在載入、MMA、計算與歸約操作之間,謹慎管理共享記憶體與 tensor memory 資源。特別要注意,我們沒有足夠的 tensor memory 容納五個累加器 tile;最多只能放入四個 \(128\times128\) 元素的 tile,而且 dV 與 dK 會持續累加,因此不能與其他資料共用空間。在我們的實作中,S 與 P 共用一個 tmem 區塊(位移為 0),dP、dS 與 dQ 則共用另一個區塊。Figure 2 展示 FA-4 反向傳播的計算圖。

Figure 2原始 PDF 第 10 頁

FlashAttention-4 backward computation graph (5 MMA operations + 2 elementwise operations), showing the 1-CTA MMA mode software pipeline order across the prologue, main loop, and tail.FlashAttention-4 反向傳播計算圖(5 次 MMA 運算加上 2 次逐元素運算),呈現 1-CTA MMA 模式下,前置階段、主迴圈與尾端階段的軟體流水線順序。

這張圖在說什麼

計算圖將一次反向迭代的相依關係拆開,讓前一迭代的梯度 MMA 插入本次迭代的 softmax 計算時段。不同 TMEM 區域的標示則說明中間量如何共用有限的儲存空間。

怎麼看

由左至右依序看 Prologue、Main Loop、Tail,先追蹤 S 到 P,再追蹤 dP 到 dS,最後看 dQ、dK、dV。虛線表示相依關係,圖例另區分 MMA、逐元素操作、SMEM 與原子歸約;注意主迴圈混用本次與前次迭代的下標,因此不是單一迭代依序做完所有工作。

p. 12

原文 SOURCE

Shared memory traffic. With five GEMMs in the backward pass, we use MMA tile shape of \(M=256\) and \(N=K=128\), which roughly halves the shared memory traffic for operand B. In the FlashAttention backward pass, each CTA holds a fixed KV tile (parallelize the outer loop across N CTAs) and streams over M tiles in the inner loop. The accumulation of dQ is a reduction in the KV sequence in the outer loop, but the 2-CTA MMA only splits the output tile, not the reduction axis, and the reduction dimension of the dQ MMA is N, which is naturally split across the CTA pair. As a result, each CTA still needs the full reduction for the rows it owns. To address this conflict on the reduction axis, we use distributed shared memory (DSMEM) to exchange half of the dS between the two CTAs since they are in the same cluster. This approach repacks dS so that it is partitioned along the non-reduction axis, with each CTA owning its \(\frac{M}{2}\) rows and holding the full \(2N\) reduction. As a result, the per CTA dQ MMA tile shape is \((\frac{M}{2},2N)(2N,d)\) and accumulates a tile \((\frac{M}{2},d)\) in tensor memory. In 2-CTA MMA mode, the MMAs for S, dP, dV and dK run with the tile \(M=256\), while dQ uses \(M=128\) but with double reduction \(2N=256\). We then reordered the software pipeline with respect to the 1-CTA variant to hide the DSMEM latency. We compute dP for the current tile before computing dQ for the tile of the previous iteration. The dQ tile is small enough to fit in TMEM alongside P, reusing the same TMEM region as S, so we no longer reuse the same TMEM region for dP and dQ as we do in the 1-CTA mode. With this new pipelining ordering, we can compute the element-wise dS of the current tile in parallel with the dQ MMA of the tile from the previous iteration. See Figure 3 for an illustration of how the dQ step is decomposed. dQ atomic adds. A complementary benefit of this dQ decomposition is that it halves the number of global atomic reductions. Atomic updates introduce nondeterminism and are expensive as they occur in every iteration of the inner loop. Consequently, each CTA writes only half of the dQ tile and performs half as many global atomic reductions as the 1-CTA counterpart.

繁體中文 TRANSLATION

共享記憶體流量。反向傳播包含五次 GEMM,我們使用 \(M=256\)、\(N=K=128\) 的 MMA tile 形狀,讓運算元 B 的共享記憶體流量大致減半。在 FlashAttention 反向傳播中,每個 CTA 持有固定的 KV tile(將外層迴圈平行分派給 N 個 CTA),並在內層迴圈串流處理 M 個 tile。dQ 的累加是在外層迴圈沿 KV 序列進行歸約,但 2-CTA MMA 只分割輸出 tile,而不分割歸約軸;dQ MMA 的歸約維度是 N,原本自然分散於配對的兩個 CTA。因此,每個 CTA 對自己負責的列仍需要完整的歸約資料。為解決歸約軸上的衝突,我們利用兩個 CTA 位於同一 cluster 的條件,以分散式共享記憶體(DSMEM)交換一半的 dS。這個方法重新打包 dS,讓它沿非歸約軸分割,每個 CTA 擁有自己的 \(\frac{M}{2}\) 列,且持有完整的 \(2N\) 歸約範圍。因此,每個 CTA 的 dQ MMA tile 形狀為 \((\frac{M}{2},2N)(2N,d)\),並在 tensor memory 中累加一個 \((\frac{M}{2},d)\) tile。在 2-CTA MMA 模式中,S、dP、dV 與 dK 的 MMA 使用 \(M=256\) 的 tile,而 dQ 使用 \(M=128\),但歸約範圍加倍為 \(2N=256\)。接著,相較於 1-CTA 版本,我們重新安排軟體流水線以隱藏 DSMEM 延遲。我們先計算目前 tile 的 dP,再計算前一次迭代 tile 的 dQ。dQ tile 足夠小,可以與 P 一起放入 TMEM,重用 S 所在的 TMEM 區域,因此不再像 1-CTA 模式那樣讓 dP 與 dQ 共用同一個 TMEM 區域。採用新的流水線順序後,我們可以同時計算目前 tile 的逐元素 dS,以及前一次迭代 tile 的 dQ MMA。dQ 步驟的分解方式見 Figure 3。 dQ 原子加法。這種 dQ 分解還有另一項效益:將全域原子歸約的次數減半。原子更新會引入非確定性,而且在內層迴圈每次迭代都會發生,因此成本高昂。如此一來,每個 CTA 只寫入一半的 dQ tile,執行的全域原子歸約次數也只有 1-CTA 對應版本的一半。

Figure 3原始 PDF 第 11 頁

In the 2-CTA backward dQ step, the CTA pair uses DSMEM to exchange half of the dS tile so each CTA forms an \((\frac{M}{2}\times2N)\) operand and can run a CTA-pair UMMA with a doubled reduction.在 2-CTA 反向傳播的 dQ 步驟中,CTA 配對使用 DSMEM 交換一半的 dS tile,使每個 CTA 形成一個 \((\frac{M}{2}\times2N)\) 運算元,並能執行歸約範圍加倍的 CTA-pair UMMA。

這張圖在說什麼

圖中從原本按 KV 分割的 dS、K 資料出發,展示如何在同一 cluster 內交換 dS,再轉成適合 2-CTA MMA 的配置。最終每個 CTA 只負責一半輸出列,但其歸約包含兩個原始 KV tile。

怎麼看

依 (a) 至 (f) 由左往右讀:先辨認 dS 與 K 的邏輯乘法,再看 CTA 配對,接著追蹤 (d) 的 DSMEM 交換箭頭。到 (e) 時,確認 dS 已由局部歸約片段變為 \(\frac{M}{2}\) 列、\(2N\) 欄;最後 (f) 的每個 CTA 輸出為 \(\frac{M}{2}\times d\),這正是減少後續全域歸約的關鍵。

p. 12

原文 SOURCE

Our backward kernel introduces nondeterminism for the gradient computation due to inter-CTA reductions in global memory (affecting dQ in general, and dK/dV in the case of GQA). To ensure reproducibility and facilitate reliable debugging during training, we also provide a deterministic execution mode. The standard solution, which we also adopt, is to serialize the global reductions using a semaphore lock. Specifically, each CTA writing to a common dQ tile must acquire the lock according to a predefined order, perform its reduction, and then release the lock by incrementing the semaphore counter. This lock-based approach impacts performance for two main reasons: (1) issuing the memory fence to ensure device-wide visibility of the semaphore write (required for correct acquire–release semantics), and (2) introducing stalls as each CTA waits for previous CTAs reducing on a common dQ tile to complete. In load-imbalanced situations, a naive choice of CTA order can severely degrade performance. In general, we do CTA swizzling in the head and batch dimensions to reduce stalls (up to L2 cache capacity, cf. Section 3.3). For causal masking, we additionally launch KV blocks in descending order, traverse query blocks in ascending order starting from the diagonal, and order the dQ reductions by descending query block index. This “shortest-processing-time-first” (SPT) schedule ensures that no CTA is stalled on its first dQ write.

繁體中文 TRANSLATION

我們的反向核心因為在全域記憶體中進行跨 CTA 歸約,而在梯度計算中引入非確定性(一般情況影響 dQ;在 GQA 情況也影響 dK/dV)。為確保可重現性,並讓訓練期間的除錯可靠,我們也提供確定性執行模式。我們採用的標準解法,是以 semaphore lock 將全域歸約序列化。具體而言,每個要寫入同一 dQ tile 的 CTA,都必須按照預先定義的順序取得鎖定、執行歸約,再遞增 semaphore 計數器以釋放鎖定。 這种基於鎖定的方法會影響效能,主要有兩個原因:(1)必須發出 memory fence,確保整個裝置都能看見 semaphore 的寫入,這是正確 acquire–release 語意所必需的;(2)每個 CTA 都要等待先前對同一 dQ tile 進行歸約的 CTA 完成,因而產生停滯。當負載不平衡時,若天真地選擇 CTA 順序,效能可能嚴重下降。一般而言,我們在 head 與 batch 維度進行 CTA swizzling,以減少停滯,範圍以 L2 快取容量為限(見第 3.3 節)。對 causal masking,我們另外以遞減順序啟動 KV 區塊,從對角線開始依遞增順序走訪 query 區塊,並按 query 區塊索引遞減的順序排列 dQ 歸約。這種「最短處理時間優先」(SPT)排程可確保每個 CTA 第一次寫入 dQ 時都不會停滯。

5. 排程:兼顧負載平衡與 L2 資料重用

長工作先做能改善尾端負載不均,但若破壞 L2 重用也可能適得其反。本文採快取容量感知的 head 分組,並為不同長度 batch 建立可快取的重新排序中繼資料。

p. 13

原文 SOURCE

LPT for causal masking. The standard attention grid is given by (mblocks, heads, batches) and is computed in increasing order left-to-right. But scores are masked out above the diagonal, so for fixed head and batch, SMs end up inefficiently processing worktiles from shortest to longest. On the other hand, a naive LPT order is also suboptimal, since for different batches, mainloop KV loads won’t hit in L2 cache, and loading all KV heads first can thrash the L2 cache if they exceed its capacity. Instead, we always process batches as the outermost dimension, and swizzle over heads. This means that we divide heads into sections that don’t overflow L2 cache; the tile scheduler then traverses the grid by heads per section, mblocks in reverse order, sections, and finally batches. In particular, for MQA or GQA, we always traverse all query heads per KV head before varying over mblocks. Empirically, we validate that this LPT order is highly effective; for example, for BF16 and head dimension 128 we obtain 4-8% FLOPS gain for MHA and 7-14% for MQA 8 as measured on an H200 GPU.

繁體中文 TRANSLATION

用於 causal masking 的 LPT。標準 attention 網格為(mblocks、heads、batches),並依左到右各維度的遞增順序計算。但對角線上方的分數會被遮罩,因此在固定 head 與 batch 下,SM 最後會以低效率的方式,從最短工作 tile 處理到最長工作 tile。另一方面,天真的 LPT 順序也不是最佳選擇:不同 batch 的主迴圈 KV 載入不會命中 L2 快取,而若先載入所有 KV head、其大小又超過容量,就可能造成 L2 快取反覆置換。因此,我們始終把 batch 當作最外層維度,並對 head 做 swizzling。也就是將 head 分成不會超出 L2 容量的區段;tile 排程器依序走訪區段內的 head、反向排列的 mblock、各區段,最後才是 batch。特別是在 MQA 或 GQA 中,我們會先走訪每個 KV head 對應的所有 query head,再改變 mblock。實驗驗證這個 LPT 順序相當有效;例如,在 H200 GPU 上,對 BF16 與 head dimension 128 的設定,MHA 的 FLOPS 提升 4–8%,MQA 8 則提升 7–14%。

p. 13

原文 SOURCE

LPT for variable sequence length. For varlen, we also have to contend with load imbalance due to variation among batches. For instance, in decode workloads, different batches might attend to different amounts of context, and in mixed or continuous batching, some batches might be prefill while others are decode. The list of query and KV sequence lengths per batch is typically stored as attention metadata on device, and the standard varlen attention kernel reads these integers at runtime while processing batches in increasing order. However, the given batch order may be arbitrarily suboptimal with respect to load balancing – for example, we could have shorter square prefills followed by long-context decodes. To ameliorate this, we can enforce an LPT order by launching a preprocessing kernel to sort batches according to their maximum per-worktile execution time, writing out the additional metadata of a virtual to actual batch index mapping that will be subsequently read back into the attention kernel in order to traverse batches in sorted order. This metadata can be cached and thus results in no performance loss from sorting.

繁體中文 TRANSLATION

用於可變序列長度的 LPT。對 varlen 而言,我們還必須處理由 batch 之間差異造成的負載不平衡。例如,在 decode 工作負載中,不同 batch 可能關注不同長度的上下文;在混合或連續批次處理中,有些 batch 可能處於 prefill,其他則處於 decode。每個 batch 的 query 與 KV 序列長度清單,通常會以 attention 中繼資料的形式儲存在裝置上;標準 varlen attention 核心在執行時讀取這些整數,並依 batch 索引遞增順序處理。然而,給定的 batch 順序在負載平衡上可能任意地不理想,例如先出現較短、query 與 KV 等長的 prefill,接著才是長上下文 decode。為改善此情況,可以啟動前處理核心,根據每個 batch 中最耗時工作 tile 的執行時間來排序 batch,藉此強制採用 LPT 順序;再寫出虛擬 batch 索引到實際 batch 索引的額外映射中繼資料,供 attention 核心之後讀回,以排序後的順序走訪 batch。這份中繼資料可以快取,因此不會因排序而損失效能。

6. 實作框架:CuTe-DSL 的編譯效率與可組合性

框架貢獻與執行期加速不同:CuTe-DSL 保留低階控制,同時縮短單核心編譯時間,並將遮罩、稀疏模式與排程整理成可組合元件。

p. 14

原文 SOURCE

Fast compilation through JIT. Compile time has been a bottleneck in past FlashAttention implementations, due to complex C++ template metaprograms. By embedding CuTe-DSL in Python with just-in-time (JIT) compilation, FlashAttention-4 achieves faster build times compared to traditional C++ template-based approaches. As shown in Table 4, FlashAttention-4 reduces compile time by 20-30× compared to FlashAttention-3. This rapid iteration cycle significantly improves developer productivity, enabling faster experimentation and debugging during kernel development.

繁體中文 TRANSLATION

透過 JIT 加速編譯。過去的 FlashAttention 實作使用複雜的 C++ 樣板元程式,使編譯時間成為瓶頸。FlashAttention-4 將 CuTe-DSL 內嵌於 Python,並使用即時(JIT)編譯,相較傳統以 C++ 樣板為基礎的方法,能更快完成建置。如 Table 4 所示,FlashAttention-4 相較 FlashAttention-3 將編譯時間縮短約 20–30 倍。這種快速迭代週期大幅改善開發者生產力,讓核心開發期間的實驗與除錯更迅速。

Table 4原始 PDF 第 14 頁

Compile time for a single kernel: FA3 (C++ templates) and FA4 (CuTe-DSL). Typically FA2 and FA3 require precompiling hundreds of kernels for different attention variants.單一核心的編譯時間:FA3(C++ 樣板)與 FA4(CuTe-DSL)。FA2 與 FA3 通常需要為不同 attention 變體預先編譯數百個核心。
MethodForward passBackward pass
FlashAttention-355s45s
FlashAttention-42.5s1.4s
Speedup22×32×

這張表在說什麼

前向與反向的單核心編譯都從數十秒降至數秒。這支持快速原型開發的主張,但與 GPU 執行期效能屬於不同指標。

怎麼看

先分別沿 Forward pass 與 Backward pass 欄比較 FA3、FA4,秒數越低越好;最後看 Speedup 列,倍數越高越好。原文段落概括為 20–30 倍,表中反向數值則明列 32 倍。

p. 14

原文 SOURCE

Our vision is to provide a comprehensive framework for building all kinds of attention variants with best-in-class performance. Rather than implementing each attention variant from scratch, FlashAttention-4 factors common functionality into independent, composable primitives. Operations such as block-sparse patterns, masking strategies, variable sequence length handling, and work scheduling are all exposed as orthogonal primitives that can be freely combined. This modular design ensures that optimizations and new features benefit all attention implementations built on the framework while still achieving the highest performance by compiling down to efficient GPU kernels.

繁體中文 TRANSLATION

我們的願景是提供完整框架,讓各種 attention 變體都能以頂尖效能實作。FlashAttention-4 不要求每種 attention 變體都從頭開始實作,而是把共通功能拆成獨立、可組合的基礎元件。區塊稀疏模式、遮罩策略、可變序列長度處理與工作排程等操作,都以彼此獨立、可自由組合的基礎元件形式提供。這種模組化設計讓最佳化與新功能能惠及所有建構在框架上的 attention 實作,同時透過編譯成高效率 GPU 核心來維持最高效能。

7. 主要結果:比較條件、前向效能與確定性代價

效能結論必須綁定 GPU、head dimension、序列長度與基線版本。FA4 對舊版 cuDNN 與 Triton 的优势明顯,但新版 cuDNN 已追近;確定性反向則展示排程能降低而非消除可重現性的成本。

p. 15

原文 SOURCE

Benchmark settings. We measure runtime on a B200 GPU for different settings (with/without causal mask, head dimensions 64, 128, and (192, 128)) for BF16 inputs. We vary the sequence length as 1k, 2k, ..., 32k, and set batch size so that the total number of tokens is 32k. We set the hidden dimension to 2048, and head dimension to be either 64 or 128 (i.e., 32 heads or 16 heads). For the (192, 128) configuration used in DeepSeek V3 [7], we use 16 heads with 192 query dimensions and 128 key/value dimensions. To calculate the FLOPs of the forward pass, we use \(4\cdot\mathrm{seqlen}^2\cdot\mathrm{head\ dimension}\cdot\mathrm{number\ of\ heads}\). With causal masking, we divide this number by 2 to account for the fact that approximately only half of the entries are calculated. To get the FLOPs of the backward pass, we multiply the forward pass FLOPs by 2.5 (since there are 2 matmuls in the forward pass and 5 matmuls in the backward pass, due to recomputation).

繁體中文 TRANSLATION

基準測試設定。我們在 B200 GPU 上,以 BF16 輸入測量不同設定的執行時間,包括有/無 causal mask,以及 head dimension 64、128 與(192, 128)。我們將序列長度設為 1k、2k、……、32k,並調整 batch size,使 token 總數維持 32k。我們將 hidden dimension 設為 2048,head dimension 則為 64 或 128,也就是 32 或 16 個 head。對 DeepSeek V3 [7] 使用的(192, 128)配置,我們使用 16 個 head,query 維度為 192,key/value 維度為 128。前向 FLOPs 的計算採用 \(4\cdot\mathrm{seqlen}^2\cdot\mathrm{head\ dimension}\cdot\mathrm{number\ of\ heads}\)。使用 causal masking 時,將此數字除以 2,以反映實際上大約只計算一半的元素。反向 FLOPs 則以前向 FLOPs 乘以 2.5,因為前向有 2 次矩陣乘法,而反向因重新計算而有 5 次。

p. 15

原文 SOURCE

We report forward pass results in Figs. 4 and 5, showing that FlashAttention-4 is 1.1-1.3× faster than cuDNN 9.13 and 2.1-2.7× faster than Triton. For medium and long sequences (4k and above), FlashAttention-4 consistently outperforms all baselines across different head dimensions and causal masking settings. The gains are larger for the causal case, which we attribute to the longest-processing-time first (LPT) scheduler.

繁體中文 TRANSLATION

我們在 Figures 4 與 5 報告前向結果,顯示 FlashAttention-4 比 cuDNN 9.13 快 1.1–1.3 倍,比 Triton 快 2.1–2.7 倍。對中長序列(4k 以上),FlashAttention-4 在不同 head dimension 與 causal masking 設定下,都持續優於所有基線。causal 情況的收益更大,我們將此歸因於最長處理時間優先(LPT)排程器。

Figure 4原始 PDF 第 15 頁

Forward pass TFLOPS on B200 (FP16/BF16) with head dimension 128. Left: non-causal attention. Right: causal attention. FA4 achieves 1.1-1.3× speedup over cuDNN 9.13.0 and 2.1-2.7× over Triton across sequence lengths. Since the initial release of our implementation, newer versions of cuDNN have incorporated many of the techniques described in this paper, yielding similar performance to FA4.B200 上 head dimension 128 的前向 TFLOPS(FP16/BF16)。左:非 causal attention。右:causal attention。在不同序列長度下,FA4 相較 cuDNN 9.13.0 加速 1.1–1.3 倍,相較 Triton 加速 2.1–2.7 倍。自本實作初次發布後,較新版 cuDNN 已納入本文多項技術,因而達到與 FA4 相近的效能。

這張圖在說什麼

圖中可同時看到 FA4 對較舊基線的明顯优势,以及與新版 cuDNN 的接近程度。非 causal 長序列下,新版 cuDNN 有些柱略高於 FA4,因此版本差異是解讀結論的必要條件。

怎麼看

左右圖分開比較;橫軸是序列長度,縱軸 TFLOPs/s 越高越好。每一組先比 FA4 與 cuDNN 9.13.0、Triton,再比 cuDNN 9.19.1.2;不要因圖例順序不同而混淆顏色,亦不要將非 causal 與 causal 的 FLOPs 計數直接視為相同工作量。

Figure 5原始 PDF 第 15 頁

Forward pass TFLOPS comparison between cuDNN and FA4 on B200 (FP16/BF16) with head dimension (192, 128) for causal attention (typically used in DeepSeek V3 architecture)在 B200 上,以 head dimension(192, 128)執行 causal attention 時,cuDNN 與 FA4 的前向 TFLOPS 比較(FP16/BF16);此配置通常用於 DeepSeek V3 架構。

這張圖在說什麼

此圖補充不對稱 head-dimension 設定,長序列下 FA4 高於圖中的兩個 cuDNN 版本,但最短序列並非全面勝出。圖上 32K 的 FA4 標為 1654,與摘要主打 1613 的峰值敘述不同,引用時應保留此設定差異。

怎麼看

橫軸為 1K 至 32K 序列長度,縱軸 TFLOPs/s 越高越好。先比較 1K、2K 的短序列,再看 4K 以上;對照同組三根柱,而不要將此圖的峰值與 head dimension 128 的 Figure 4 混成單一設定。

p. 16

原文 SOURCE

We report backward pass results in Fig. 6. FlashAttention-4 achieves consistent speedups across long sequence lengths and causal masking, demonstrating the effectiveness of our 2-CTA backward pass. We also show the performance of the deterministic backward pass in Fig. 7. Our careful swizzling and scheduling results in a much faster deterministic backward pass, getting up to 75% the speed of the nondeterministic backward pass of the 1-CTA backward pass.

繁體中文 TRANSLATION

我們在 Figure 6 報告反向結果。FlashAttention-4 在長序列與 causal masking 設定下都取得穩定加速,展示了 2-CTA 反向傳播的有效性。 我們也在 Figure 7 展示確定性反向傳播的效能。經過仔細設計的 swizzling 與排程,使確定性反向傳播快得多,最高可達非確定性 1-CTA 反向傳播速度的 75%。

Figure 6原始 PDF 第 16 頁

Backward pass TFLOPS on B200 (FP16/BF16) with head dimension 128. Left: non-causal attention. Right: causal attention.B200 上 head dimension 128 的反向 TFLOPS(FP16/BF16)。左:非 causal attention。右:causal attention。

這張圖在說什麼

在長序列設定中,FA4 的反向吞吐量高於圖中的 FA2 與 cuDNN 版本,支持整體反向設計有效。短 causal 序列則不是全面領先,因此作者結論特別強調長序列。

怎麼看

先將左右兩個 masking 設定分開,再於相同序列長度下比較各柱;縱軸 TFLOPs/s 越高越好。特別看 8K 至 32K,再回頭檢查 1K、2K 的例外;反向 FLOPs 使用前向的 2.5 倍估算,因此不要直接把其 TFLOPs/s 當成前向延遲的比例。

Figure 7原始 PDF 第 16 頁

Ablations for Deterministic Backward pass on B200 (FP16/BF16) with head dimension 128. Causal attention – SPT, LPT with reverse mblock order, LPT, and naive with no batch/head swizzle.B200 上 head dimension 128 的確定性反向傳播消融比較(FP16/BF16)。causal attention 比較 SPT、反向 mblock 順序的 LPT、LPT,以及不做 batch/head swizzle 的樸素版本。

這張圖在說什麼

同樣要求確定性時,排程方式仍造成很大的效能差異;SPT 在圖中各序列長度皆最高。這支持作者以啟動與歸約順序降低鎖定等待的設計,而非聲稱同步成本已消失。

怎麼看

橫軸為 1024 至 32768 的序列長度,縱軸 TFLOPs/s 越高越好。依序比較黃色 naive、綠色 LPT、藍色反向 mblock LPT 與橘色 SPT;例如 8192 時四者分別標為 350、720、790、920。圖中沒有非確定性 1-CTA 的柱,因此不能只用此圖獨立重算正文的 75%。

8. 重現與引用限制:附錄設定需再核對

論文提供暖機次數、重複測量與函式庫版本,但 GPU 型號和寫作日期與正文存在差異。這些問題不直接否定方法,卻影響結果可重現性與效能主張的精確引用。

p. 20

原文 SOURCE

We benchmark the speed on a B100 180GB SXM6 (1000W). We warmup with 5 runs, then repeat the benchmarks 10 times, and take the average timing. We generally used the latest versions of the libraries at the time of writing (March 2025). Specifically, we use: • CUDA 13.1 • FlashAttention 2.8.3 • Triton 3.6 • PyTorch 2.10.0 • CuTe-DSL 4.4.1 For cuDNN, in the main paper, we compare to cuDNN 9.13 and the latest version cuDNN 9.19.1.2. Starting from version 9.13 and 9.14 [20], we have worked with the cuDNN team to incorporate some techniques from FlashAttention-4 into cuDNN so that our work can benefit as many practitioners as possible.

繁體中文 TRANSLATION

我們在 B100 180GB SXM6(1000W)上測量速度。我們先執行 5 次暖機,再重複基準測試 10 次,並取平均時間。 我們通常使用寫作當時(2025 年 3 月)最新版的函式庫。具體使用版本如下: • CUDA 13.1 • FlashAttention 2.8.3 • Triton 3.6 • PyTorch 2.10.0 • CuTe-DSL 4.4.1 cuDNN 方面,主文比較 cuDNN 9.13 與最新版 cuDNN 9.19.1.2。從 9.13 與 9.14 版本 [20] 開始,我們就與 cuDNN 團隊合作,將 FlashAttention-4 的部分技術整合進 cuDNN,讓我們的工作能惠及盡可能多的實務使用者。