RESEARCH NOTE 雙語閱讀 · 重點批註

FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision

Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri DaoarXiv 預印本2024

arXiv:2407.08608v2

模型:gpt-6-astra · REASONING:medium · DETAIL:high
輸入:40,467 tokens · 輸出:22,733 tokens(思考:516 tokens、其他輸出:22,217 tokens) · 總計:63,200 tokens

一句話掌握THE TAKEAWAY

FlashAttention-3 透過非同步排程與 FP8 量化設計,讓注意力運算更充分利用 Hopper GPU,並降低含離群值輸入的 FP8 數值誤差。

研究問題

如何在不改變標準注意力核心運算的前提下,重新設計資料搬移、矩陣乘法與 softmax 的執行順序,以利用 Hopper 的非同步硬體及 FP8 Tensor Cores,同時控制量化誤差?

動機

FlashAttention-2 已減少中間結果的 HBM 存取,但在 H100 上僅達約 35% 利用率。剩餘瓶頸不只是記憶體流量,也包括同步執行模式、softmax 與矩陣乘法間的相依性,以及 FP8 的資料布局與精度限制。

方法

以 warp-specialization 分離資料生產者與計算消費者,搭配循環共享記憶體緩衝區;用跨 warpgroup 的 pingpong 排程與 warpgroup 內的兩階段管線重疊 GEMM 和 softmax;為 FP8 實作核心內轉置與暫存器重排,再以 block quantization 與 incoherent processing 降低量化誤差。

主要貢獻

  • 將 FlashAttention 的 GPU 執行模式改為明確利用 TMA 與 Tensor Cores 非同步能力的生產者—消費者管線。
  • 跨迭代重新安排 GEMM 與 softmax,緩解低吞吐量非矩陣運算造成的等待。
  • 解決連續兩次 FP8 WGMMA 的布局不相容問題,並整合區塊量化與隨機正交變換。
  • 提供 H100 上的前向、反向效能評估、方法消融與相對 FP64 的數值誤差比較。

主要結果

  • 作者概括 FP16 前向相對 FlashAttention-2 加速約 1.5–2.0 倍,反向約 1.5–1.75 倍;摘要報告最高約 740 TFLOPs/s、75% 利用率。
  • FP8 前向接近 1.2 PFLOPs/s,但相對 cuDNN 的優勢取決於序列長度、head dimension 與是否使用 causal mask。
  • 固定非因果 FP16 消融設定下,完整方法達 661 TFLOPs/s;移除 GEMM-softmax 管線或 warp-specialization 後,分別為 582 與 570 TFLOPs/s。
  • 含合成離群值的數值實驗中,FP8 RMSE 由基線的 2.4e-2 降至 9.1e-3,約改善 2.6 倍;FP16 FlashAttention-2 與 FlashAttention-3 的 RMSE 均為 1.9e-4。
  • 三階段管線沒有優於兩階段:編譯器未實現預期的完整重疊,而且額外暫存器需求迫使區塊縮小。

限制

  • 實證集中於 H100 SXM5;對其他加速器的適用性是作者預期,而非本文已驗證的結果。
  • FP8 數值驗證使用合成輸入與輸出 RMSE,不能直接推論大型模型訓練穩定性或下游任務品質。
  • 本文 FP8 核心尚未整合 FP16 版本已有的 persistent kernel 與負載平衡策略,因此短序列與 causal masking 的效能仍有弱點。
  • 管線深度、區塊大小、暫存器壓力與編譯器排程互相牽制,不能假設增加重疊階段必然更快。
  • LLM 推論最佳化與低精度注意力對大規模訓練的影響仍列為未來工作。
重要度
回到頂端 ↑

1. 研究問題與缺口

研究缺口已從「避免中間矩陣的昂貴存取」轉向「讓不同硬體單元有效並行」。作者將非同步依賴處理與低精度誤差控制視為必須共同解決的演算法問題。

p. 2

原文 SOURCE

More fundamentally, FlashAttention-2’s algorithm adheres to a simplified synchronous model and makes no explicit use of asynchrony and low-precision in its design. Asynchrony is a result of hardware specialization to accelerate the most important operations in a ML workload: specific hardware units performing matrix multiplication (Tensor Cores) or memory loading (Tensor Memory Accelerator – TMA), separate from the rest of the CUDA cores performing logic, integer, and floating point computation. Low precision such as FP8 in Hopper and FP4 in Blackwell, continuing the trend of FP16 (Pascal in 2017) and BF16 (Ampere in 2020), is a proven technique to get double or quadruple throughput for the same power and chip area. We review the capabilities afforded by Hopper in these directions in § 2.2. The technical challenge is to redesign FlashAttention-2 to make use of these hardware features: asynchrony requires overlapping computation between matmul and softmax even though one depends on the output of the other, and low-precision requires care to minimize quantization error, especially in the case of outlier features in LLMs [20, 54].

繁體中文 TRANSLATION

更根本地說,FlashAttention-2 的演算法遵循簡化的同步模型,其設計並未明確利用非同步與低精度。非同步來自硬體的專門化:為了加速機器學習工作負載中最重要的運算,特定硬體單元負責矩陣乘法(Tensor Cores)或記憶體載入(Tensor Memory Accelerator,TMA),與其餘負責邏輯、整數及浮點運算的 CUDA cores 分開運作。Hopper 的 FP8 與 Blackwell 的 FP4 等低精度格式,延續了 FP16(2017 年的 Pascal)與 BF16(2020 年的 Ampere)的趨勢;這是已獲證實能在相同功耗與晶片面積下,取得兩倍或四倍吞吐量的技術。我們在 § 2.2 回顧 Hopper 在這些方向提供的能力。技術挑戰在於重新設計 FlashAttention-2 以利用這些硬體特性:非同步需要讓 matmul 與 softmax 的計算重疊,即使其中一者依賴另一者的輸出;低精度則必須謹慎降低量化誤差,尤其當 LLM 中存在離群特徵時 [20, 54]。

p. 2

原文 SOURCE

To validate our method empirically, we benchmark FlashAttention-3 on the H100 SXM5 GPU over a range of parameters and show that (1) FP16 achieves 1.5-2.0× speedup over FlashAttention-2 in the forward pass (reaching up to 740 TFLOPs/s) and 1.5-1.75× in the backward pass, (2) FP8 achieves close to 1.2 PFLOPs/s, and (3) for large sequence length, FP16 outperforms and FP8 is competitive with a state-of-the-art implementation of attention from NVIDIA’s cuDNN library. We also validate that FP16 FlashAttention-3 yields the same numerical error as FlashAttention-2 and is better than the standard attention implementation as intermediate results (e.g., softmax rescaling) are kept in FP32. Moreover, FP8 FlashAttention-3 with block quantization and incoherent processing is 2.6× more accurate than standard attention with per-tensor quantization in cases with outlier features.

繁體中文 TRANSLATION

為了以實驗驗證方法,我們在 H100 SXM5 GPU 上,以一系列參數對 FlashAttention-3 進行效能測試,結果顯示:(1) FP16 的前向運算相對 FlashAttention-2 加速 1.5–2.0 倍,最高達 740 TFLOPs/s,反向運算則加速 1.5–1.75 倍;(2) FP8 接近 1.2 PFLOPs/s;(3) 在長序列下,FP16 優於 NVIDIA cuDNN 函式庫中最先進的注意力實作,而 FP8 則具有競爭力。我們也驗證,FP16 FlashAttention-3 的數值誤差與 FlashAttention-2 相同,且優於標準注意力實作,因為中間結果(例如 softmax 的重新縮放)保留為 FP32。此外,在具有離群特徵的情況下,採用區塊量化與 incoherent processing 的 FP8 FlashAttention-3,比使用逐張量量化的標準注意力準確 2.6 倍。

2. 核心概念:融合注意力與非同步硬體

FlashAttention 保留標準注意力的運算目標,但不將完整分數與機率矩陣寫入 HBM。Hopper 再提供非同步搬移、非同步矩陣乘法與動態暫存器分配,使更積極的工作分工成為可能。

p. 4

原文 SOURCE

Following Dao et al. [17], we let standard attention denote an implementation of attention on the GPU that materializes the intermediate matrices S and P to HBM. The main idea of FlashAttention was to leverage a local version of the softmax reduction to avoid these expensive intermediate reads/writes and fuse attention into a single kernel. Local softmax corresponds to lines 18-19 of the consumer mainloop in Algorithm 1 together with the rescalings of blocks of O. The simple derivation that this procedure indeed computes O can be found in [15, §2.3.1].

繁體中文 TRANSLATION

沿用 Dao 等人 [17] 的定義,我們以 standard attention 指稱一種 GPU 注意力實作:它會將中間矩陣 \(S\) 與 \(P\) 實際寫入 HBM。FlashAttention 的核心想法,是利用局部版本的 softmax 歸約,避免這些昂貴的中間讀寫,並將注意力融合成單一核心。局部 softmax 對應到 Algorithm 1 消費者主迴圈的第 18–19 行,以及對 \(O\) 各區塊的重新縮放。證明此程序確實能算出 \(O\) 的簡單推導可見 [15, §2.3.1]。

p. 3

原文 SOURCE

Asynchrony and warp-specialization: GPUs are throughput processors that rely on concurrency and asynchrony to hide memory and execution latencies. For async memory copy between GMEM and SMEM, Hopper has the Tensor Memory Accelerator (TMA) as a dedicated hardware unit [38, §7.29]. Furthermore, unlike prior architectures such as Ampere, the Tensor Core of Hopper, exposed via the warpgroup-wide WGMMA instruction [40, §9.7.14], is also asynchronous and can source its inputs directly from shared memory. Hardware support for asynchrony allows for warp-specialized kernels, where the warps of a CTA are divided into producer or consumer roles that only ever issue either data movement or computation. Generically, this improves the compiler’s ability to generate optimal instruction schedules [4]. In addition, Hopper supports the dynamic reallocation of registers between warpgroups via setmaxnreg [40, §9.7.17.1], so those warps doing MMAs can obtain a larger share of RMEM than those just issuing TMA (for which only a single thread is needed).

繁體中文 TRANSLATION

非同步與 warp-specialization:GPU 是吞吐量導向的處理器,仰賴並行與非同步來隱藏記憶體及執行延遲。針對 GMEM 與 SMEM 之間的非同步記憶體複製,Hopper 配備專用硬體單元 Tensor Memory Accelerator(TMA)[38, §7.29]。此外,不同於 Ampere 等先前架構,Hopper 的 Tensor Core 透過作用於整個 warpgroup 的 WGMMA 指令 [40, §9.7.14] 提供介面,本身也能非同步執行,並可直接從共享記憶體取得輸入。 硬體對非同步的支援,使 warp 分工的核心成為可能:同一個 CTA 內的 warps 被分配為生產者或消費者,只負責發出資料搬移或計算操作。一般而言,這能改善編譯器產生最佳指令排程的能力 [4]。此外,Hopper 可透過 setmaxnreg [40, §9.7.17.1] 在 warpgroups 之間動態重新分配暫存器,讓執行 MMA 的 warps 比僅發出 TMA 的 warps 取得更多 RMEM;後者其實只需要單一執行緒。

3.1 方法:生產者—消費者分工與 pingpong 排程

第一層重疊是讓資料搬移與計算分工,第二層則讓不同消費者 warpgroup 交錯執行 softmax 與 GEMM,以利用不同硬體單元。

p. 5

原文 SOURCE

For our implementation of Algorithm 1 on Hopper, we use setmaxnreg for (de)allocations, TMA for loads of \(Q_i\) and \(\{K_j,V_j\}_{0\leq j<T_c}\), and WGMMA to execute the GEMMs in the consumer mainloop, with the SS or RS prefix indicating whether the first operand is sourced from shared memory or register file. For interpreting the execution flow of Algorithm 1, note that issuing TMA loads does not stall on the completion of other loads due to asynchrony. Moreover, in the producer mainloop, no waits will be issued for the first \(s\) iterations as the buffer gets filled.

繁體中文 TRANSLATION

在 Hopper 上實作 Algorithm 1 時,我們使用 setmaxnreg 來分配或釋放暫存器,使用 TMA 載入 \(Q_i\) 與 \(\{K_j,V_j\}_{0\leq j<T_c}\),並使用 WGMMA 執行消費者主迴圈中的 GEMM;SS 或 RS 前綴表示第一個運算元是來自共享記憶體還是暫存器檔。理解 Algorithm 1 的執行流程時,應注意由於非同步特性,發出 TMA 載入不會因等待其他載入完成而停滯。此外,在生產者主迴圈最初填滿緩衝區的 \(s\) 次迭代中,不會發出任何等待操作。

p. 5

原文 SOURCE

Since the exponential is performed by a separate hardware unit (the multi-function unit), ideally we’d want the exponential calculation to be scheduled when the Tensor Cores are performing the matmul. To do so, we use synchronization barriers (bar.sync instructions) to force the GEMMs (GEMM1 – PV of one iteration, and GEMM0 – QK⊤ of the next iteration) of warpgroup 1 to be scheduled before the GEMMs of warpgroup 2. As a result, the softmax of warpgroup 1 will be scheduled while warpgroup 2 is performing its GEMMs. Then the roles swap, with warpgroup 2 doing softmax while warpgroup 1 doing GEMMs (hence, “pingpong” scheduling). This is illustrated in Fig. 1. Though in practice the pingpong scheduling is not as clean as depicted in the figure, we generally find this to improve performance (e.g., from 570 TFLOPS to 620-640 TFLOPS for FP16 forward with head dimension 128 and sequence length 8192).

繁體中文 TRANSLATION

由於指數運算由另一個獨立硬體單元(multi-function unit)執行,理想上,我們希望在 Tensor Cores 執行矩陣乘法時安排指數計算。為此,我們使用同步屏障(bar.sync 指令),強制讓 warpgroup 1 的 GEMM——某次迭代的 GEMM1,即 \(PV\),以及下一次迭代的 GEMM0,即 \(QK^\top\)——排在 warpgroup 2 的 GEMM 之前。因此,warpgroup 1 的 softmax 會在 warpgroup 2 執行 GEMM 時獲得排程。接著交換角色,由 warpgroup 2 執行 softmax,warpgroup 1 執行 GEMM,因此稱為「pingpong」排程。Fig. 1 展示了這個安排。實務上的 pingpong 排程雖然不像圖中那麼整齊,但我們通常觀察到它能改善效能;例如,當 head dimension 為 128、序列長度為 8192 時,FP16 前向吞吐量由 570 TFLOPS 提升至 620–640 TFLOPS。

Figure 1原始 PDF 第 6 頁

Pingpong scheduling for 2 warpgroups to overlap softmax and GEMMs: the softmax of one warpgroup should be scheduled when the GEMMs of another warpgroup are running. The same color denotes the same iteration.讓兩個 warpgroups 的 softmax 與 GEMM 重疊的 pingpong 排程:一個 warpgroup 的 softmax 應安排在另一個 warpgroup 執行 GEMM 時進行。相同顏色表示相同迭代。

這張圖在說什麼

兩條工作列展示不同 warpgroup 如何輪流占用 Tensor Cores 與執行 softmax 的硬體資源。重點是跨工作群的時間互補,而不是消除每個工作群自身的資料相依性。

怎麼看

先沿向右的時間軸看 warpgroup 1,再垂直對照 warpgroup 2:找出一列的 Softmax 與另一列的 GEMM0、GEMM1 是否重疊。同色代表同一次迭代;空白表示示意中的等待或未安排工作,不能直接當作量測延遲。

3.2 方法:warpgroup 內的兩階段管線

單次迭代中的 GEMM—softmax—GEMM 有不可忽略的資料相依性。作者透過暫存多個迭代的中間結果,將重疊機會移到跨迭代層次,但必須付出暫存器成本。

p. 6

原文 SOURCE

In the attention algorithm, operations within the inner loop (main loop) have sequential dependencies that impede parallelization within a single iteration. For example, (local) softmax (lines 18 to 19) relies on the output \(S_i^{(j)}\) of the first GEMM, while the second GEMM takes its result \(\widetilde{P}_i^{(j)}\) as an operand. Indeed, the wait statements in lines 17 and 21 of Algorithm 1 serialize the execution of softmax and GEMMs. However, we can break these dependencies by pipelining across iterations through additional buffers in registers. Pursuing this idea, we propose the following two-stage GEMM-softmax pipelining algorithm:

繁體中文 TRANSLATION

在注意力演算法中,內迴圈(主迴圈)的操作具有先後相依性,使單次迭代內的平行化受到阻礙。例如,局部 softmax(第 18–19 行)依賴第一個 GEMM 的輸出 \(S_i^{(j)}\),而第二個 GEMM 又以它的結果 \(\widetilde{P}_i^{(j)}\) 作為運算元。事實上,Algorithm 1 第 17 與第 21 行的等待敘述,讓 softmax 與 GEMM 依序執行。不過,我們可以透過暫存器中的額外緩衝區,建立跨迭代管線來打破這些執行限制。沿著這個想法,我們提出以下兩階段 GEMM-softmax 管線演算法:

Figure 2原始 PDF 第 6 頁

2-stage WGMMA-softmax pipelining兩階段 WGMMA-softmax 管線。

這張圖在說什麼

圖中將第一個 WGMMA、softmax 與第二個 WGMMA 分成三條時間列,展示不同迭代的工作交錯。前端需先產生足夠的中間結果,尾端則需完成剩餘的輸出累加。

怎麼看

由左向右讀時間,先追蹤編號 0 的三個步驟確認相依順序,再比較 softmax 1 與 WGMMA1 的 0 是否重疊。編號與顏色用來區分迭代;這裡的兩階段不必等於循環 SMEM 緩衝區的階段數。

p. 7

原文 SOURCE

Register pressure To maintain optimal performance, register spilling should be minimized. However, the 2-stage pipeline requires additional registers to store intermediate results and maintain context between stages. Specifically, an extra Snext must be kept in registers, leading to extra register usage of size \(B_r \times B_c \times \operatorname{sizeof}(\mathrm{float})\) per threadblock. This increased register demand may conflict with using larger block sizes (another common optimization), which is also register-hungry. In practice, trade-offs should be made based on profiling results.

繁體中文 TRANSLATION

暫存器壓力 為了維持最佳效能,應盡量減少 register spilling。不過,兩階段管線需要額外暫存器來儲存中間結果,並保留階段之間的執行狀態。具體而言,額外的 Snext 必須保留在暫存器中,讓每個 threadblock 增加 \(B_r \times B_c \times \operatorname{sizeof}(\mathrm{float})\) 的暫存器用量。這種增加的暫存器需求,可能與採用較大區塊的另一種常見最佳化衝突,因為較大區塊同樣需要大量暫存器。實務上,應根據效能剖析結果進行取捨。

3.3 方法:FP8 布局轉換與精度控制

FP8 的挑戰分為兩類:能否合法且高效率地串接兩次 WGMMA,以及如何減少離群值造成的量化誤差。前者靠核心內轉置與相容的置換,後者靠區塊縮放與量化前的正交混合。

p. 8

原文 SOURCE

First, we note that the input tensors Q, K, and V are typically given as contiguous in the head dimension, while to satisfy the k-major constraint on FP8 WGMMA for the second GEMM we need V, or rather the tiles of V loaded into SMEM, to be contiguous in the sequence length dimension. Since the TMA load itself cannot change the contiguous dimension, we then need to either (1) transpose V in GMEM as a pre-processing step, or (2) do an in-kernel transpose of tiles of V after loading them into SMEM. To implement option (1), we can either (1a) fuse the transpose to the epilogue of a preceding step such as the rotary embedding, or (1b) call a standalone pre-processing transpose kernel to exchange the strides of the sequence length and head dimensions. However, (1a) is difficult to integrate into a standard library, and (1b) is too wasteful in a memory-bound situation such as inference. Instead, for FP8 FlashAttention-3 we opt for option (2). For the in-kernel transpose, we take advantage of the LDSM (ldmatrix) and STSM (stmatrix) instructions, which involve a warp of threads collectively loading SMEM to RMEM and storing RMEM to SMEM at a granularity of 128 bytes. The LDSM/STSM instructions are both register efficient, allowing us to execute them in the producer warpgroup, and capable of transposing layouts when doing memory copy. Moreover, after the first iteration we can arrange for the transpose of the next V tile to be executed in the shadow of the two WGMMAs that involve the preceding V and current K tile.

繁體中文 TRANSLATION

首先,輸入張量 \(Q\)、\(K\) 與 \(V\) 通常沿 head dimension 連續儲存;但為了滿足第二個 GEMM 的 FP8 WGMMA 所要求的 k-major 布局,\(V\)——更確切地說,是載入 SMEM 的 \(V\) 區塊——必須沿序列長度維度連續儲存。由於 TMA 載入本身無法改變連續儲存的維度,我們必須選擇:(1) 在前處理階段於 GMEM 中轉置 \(V\),或 (2) 將 \(V\) 區塊載入 SMEM 後,在核心內轉置。若採用選項 (1),可以 (1a) 將轉置融合到先前步驟的收尾階段,例如 rotary embedding;或 (1b) 呼叫獨立的前處理轉置核心,交換序列長度與 head dimension 的 strides。不過,(1a) 難以整合至標準函式庫,(1b) 則在推論這類受記憶體頻寬限制的情境中過於浪費。 因此,FP8 FlashAttention-3 採用選項 (2)。為了在核心內轉置,我們利用 LDSM(ldmatrix)與 STSM(stmatrix)指令,由一個 warp 的執行緒共同以 128 bytes 為單位,將 SMEM 載入 RMEM,或將 RMEM 存回 SMEM。LDSM/STSM 指令的暫存器需求低,因此能在 producer warpgroup 中執行,而且可在複製記憶體時轉換布局。此外,第一次迭代之後,可以安排下一個 \(V\) 區塊的轉置,與涉及前一個 \(V\) 區塊及目前 \(K\) 區塊的兩次 WGMMA 同時進行,以隱藏轉置成本。

p. 8

原文 SOURCE

Second, we observe that unlike with FP16, the memory layout of the FP32 accumulator of an FP8 WGMMA is different from that assumed for its operand A when held in registers. We depict fragments of these two layouts in Fig. 3 and Fig. 4, where the entries are held in registers per thread in the listed order. By using byte permute instructions, we can then transform the first WGMMA’s accumulator into a format suitable for the second WGMMA, and compatibly with the layout of the V tile produced by the in-kernel transpose. Specifically, with reference to Fig. 3, we change the order in sequence to \[\{d0\ d1\ d4\ d5\ d2\ d3\ d6\ d7\},\] and this register permutation is then replicated over every 8 bytes. In terms of the logical shape of the P tile, this manuever permutes its columns (e.g., columns 0189 now become the first four columns). For WGMMA to then compute the correct output tile, we can correspondingly arrange for the in-kernel transpose to write out a matching row permutation of the V tile.

繁體中文 TRANSLATION

其次,我們觀察到,與 FP16 不同,FP8 WGMMA 的 FP32 累加器記憶體布局,和運算元 A 位於暫存器時所要求的布局不同。Fig. 3 與 Fig. 4 畫出這兩種布局的局部內容,各元素按照圖示順序保存在各執行緒的暫存器中。使用 byte permute 指令後,我們可以把第一個 WGMMA 的累加器轉換成適合第二個 WGMMA 的格式,並與核心內轉置產生的 \(V\) 區塊布局相容。具體而言,參照 Fig. 3,我們將順序改為 \[\{d0\ d1\ d4\ d5\ d2\ d3\ d6\ d7\},\] 再把這個暫存器置換套用到每 8 bytes。從 \(P\) 區塊的邏輯形狀來看,這個操作會置換它的欄,例如原本的第 0、1、8、9 欄現在變成最前面的四欄。為了讓 WGMMA 算出正確的輸出區塊,我們可以相應地安排核心內轉置,對 \(V\) 區塊寫出配對的列置換。

Figure 3原始 PDF 第 8 頁

FP32 accumulator register WGMMA layout – rows 0 and 8, threads 0-3, entries 0-7.WGMMA 的 FP32 累加器暫存器布局——第 0 與第 8 列、執行緒 0–3、元素 0–7。

這張圖在說什麼

此圖顯示第一個 WGMMA 累加結果在各執行緒暫存器中的局部分布。它是布局轉換的來源端,需與 Figure 4 的輸入布局一起閱讀。

怎麼看

先固定一個執行緒標籤,例如 T0,追蹤其 d0 到 d7 分布,再比較相鄰位置是否由不同執行緒持有。圖只畫出指定列、執行緒與元素的片段,不是完整矩陣。

Figure 4原始 PDF 第 8 頁

FP8 operand A register WGMMA layout – rows 0 and 8, threads 0-3, entries 0-7.WGMMA 的 FP8 運算元 A 暫存器布局——第 0 與第 8 列、執行緒 0–3、元素 0–7。

這張圖在說什麼

此圖顯示第二個 WGMMA 要求的 FP8 輸入排列。與 Figure 3 對照可見,同一執行緒持有元素的邏輯位置不同,因此需要 byte permute 與配對的值矩陣置換。

怎麼看

對照 Figure 3 中同一執行緒的位置,先看每列中相鄰兩格的歸屬,再追蹤 a0 到 a7 的排列。不要把 d 與 a 的標號視為同一種儲存順序;兩圖正是在展示它們的差異。

p. 8

原文 SOURCE

Block quantization: we keep one scalar per block, so that for each of Q, K, V we split the tensor into blocks of size \(B_r \times d\) or \(B_c \times d\) and quantize them separately. This quantization can be fused with an operation right before attention (e.g., rotary embedding) with no additional slow down (since rotary embedding is memory-bandwidth bound). As the FlashAttention-3 algorithm naturally operates on blocks, we can scale each block of S to account for this block quantization at no computation cost.

繁體中文 TRANSLATION

區塊量化:我們為每個區塊保留一個純量,因此對 \(Q\)、\(K\)、\(V\) 中的每個張量,都將其切分成 \(B_r \times d\) 或 \(B_c \times d\) 大小的區塊,並分別量化。這個量化步驟可以融合到注意力之前的操作,例如 rotary embedding,而不額外降低速度,因為 rotary embedding 受記憶體頻寬限制。由於 FlashAttention-3 本來就是以區塊運作,我們可以對 \(S\) 的每個區塊進行縮放,以補償區塊量化,而且不增加計算成本。

p. 9

原文 SOURCE

Incoherent processing: to even out outliers, we multiply Q and K with a random orthogonal matrix M before quantizing to FP8. Since M is orthogonal, \(MM^\top=I\) and so \((QM)(KM)^\top=QK^\top\), i.e., multiplying both Q and K with M does not change the attention output. This serves to “spread out” the outliers since each entry of QM or KM is a random sum of entries of Q or K, thus reducing quantization error. In practice, we follow Chee et al. [9] and Tseng et al. [58] and choose M to be the product of random diagonal matrices of \(\pm 1\) and a Hadamard matrix, which can be multiplied in \(O(d\log d)\) instead of \(O(d^2)\), and can also be fused with the rotary embedding at no extra computation cost.

繁體中文 TRANSLATION

Incoherent processing:為了攤平離群值,我們在量化為 FP8 之前,先讓 \(Q\) 與 \(K\) 乘上一個隨機正交矩陣 \(M\)。由於 \(M\) 是正交矩陣,\(MM^\top=I\),因此 \((QM)(KM)^\top=QK^\top\);也就是說,同時讓 \(Q\) 與 \(K\) 乘上 \(M\),不會改變注意力輸出。這能「分散」離群值,因為 \(QM\) 或 \(KM\) 中的每個元素,都是 \(Q\) 或 \(K\) 元素的隨機加總,因而降低量化誤差。實務上,我們沿用 Chee 等人 [9] 與 Tseng 等人 [58] 的作法,選擇由對角元素為 \(\pm 1\) 的隨機對角矩陣與 Hadamard 矩陣相乘而成的 \(M\),使乘法成本由 \(O(d^2)\) 降為 \(O(d\log d)\),而且也能與 rotary embedding 融合,不增加額外計算成本。

4. 主要結果與證據

效能需依資料型別、mask 與序列長度分開解讀;消融支持兩項非同步設計的作用。精度結果則支持在合成離群值條件下改善 FP8 輸出誤差,尚不是端到端模型品質驗證。

p. 9

原文 SOURCE

We measure the runtime of different attention methods on an H100 80GB SXM5 GPU for different settings (without / with causal mask, head dimension 64 or 128) for FP16 inputs. We report the results in Fig. 5 and Fig. 6, showing that FlashAttention-3 is around 1.5-2.0× faster than FlashAttention-2 in the forward pass and 1.5-1.75× faster in the backward pass. Compared to a standard attention implementation, FlashAttention-3 can be up to 3-16× faster. For medium and long sequences (1k and above), FlashAttention-3 even surpasses the speed of a vendor’s library (cuDNN – closed source) that has been optimized for H100 GPUs.

繁體中文 TRANSLATION

我們在 H100 80GB SXM5 GPU 上,使用 FP16 輸入,於不同設定下量測各種注意力方法的執行時間,包括有無 causal mask,以及 head dimension 為 64 或 128。Fig. 5 與 Fig. 6 的結果顯示,FlashAttention-3 的前向運算約比 FlashAttention-2 快 1.5–2.0 倍,反向運算則快 1.5–1.75 倍。相較於標準注意力實作,FlashAttention-3 的加速可達 3–16 倍。對中長序列,也就是 1k 以上的序列,FlashAttention-3 甚至超越已針對 H100 GPU 最佳化的廠商函式庫 cuDNN;該函式庫並未開放原始碼。

Figure 5原始 PDF 第 10 頁

Attention forward speed (FP16/BF16) on H100 GPUH100 GPU 上的注意力前向速度(FP16/BF16)。

這張圖在說什麼

六個子圖比較不同 head dimension、mask 設定與序列長度下的前向吞吐量。長序列通常較能呈現 FlashAttention-3 的優勢,但短序列及不同基線的排名會改變;圖中 head dimension 256、無 mask、16k 的標示為 756 TFLOPs/s,與正文概括的最高約 740 不完全一致。

怎麼看

先選左欄無 causal mask 或右欄有 mask,再選 head dimension 64、128、256。橫軸是序列長度,縱軸 TFLOPs/s 越高越好;在相同子圖與長度下比較紫色 FlashAttention-3、橘色 FlashAttention-2 與紅色 cuDNN。OOM 表示記憶體不足,並非零吞吐量。

Figure 6原始 PDF 第 11 頁

Attention backward speed (FP16/BF16) on H100 GPUH100 GPU 上的注意力反向速度(FP16/BF16)。

這張圖在說什麼

兩個子圖提供無 causal mask、head dimension 64 與 128 的反向運算結果。FlashAttention-3 在這些展示條件下優於 FlashAttention-2 與 cuDNN,但對 cuDNN 的差距比對 FlashAttention-2 小。

怎麼看

先確認兩圖都是無 mask,再按相同序列長度比較各方法的柱高。縱軸吞吐量越高越好;反向 FLOPs 依作者慣例計為前向的 2.5 倍,因此不要直接把前向、反向柱高當成執行時間比。

p. 9

原文 SOURCE

Benchmark settings: We vary the sequence length as 512, 1k, ..., 16k, and set batch size so that the total number of tokens is 16k. We set the hidden dimension to 2048, and head dimension to be either 64, 128, or 256 (i.e., 32 heads, 16 heads, or 8 heads). 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

效能測試設定:我們將序列長度設為 512、1k、……、16k,並調整 batch size,使 token 總數保持為 16k。我們把 hidden dimension 設為 2048,head dimension 則設為 64、128 或 256,分別對應 32、16 或 8 個 heads。前向運算的 FLOPs 使用下式計算: \[4\cdot\mathrm{seqlen}^2\cdot\mathrm{head\ dimension}\cdot\mathrm{number\ of\ heads}.\] 使用 causal masking 時,將此數值除以 2,因為約只有一半的元素需要計算。反向運算的 FLOPs 則將前向 FLOPs 乘以 2.5,因為前向有兩次矩陣乘法,而反向由於重新計算而有五次矩陣乘法。

p. 9

原文 SOURCE

We ablate both the 2-stage WGMMA-softmax pipelining and warp-specialization for non-causal FP16 FlashAttention-3 with fixed parameters \(\{\mathrm{batch},\mathrm{seqlen},\mathrm{nheads},\mathrm{hdim}\}=\{4,8448,16,128\}\). The result in Table 2 confirms that our algorithmic improvements (asynchrony with warp-specialization and overlapping between GEMM and softmax) lead to significant speedup, from 570 to 661 TFLOPs.

繁體中文 TRANSLATION

我們針對無 causal mask 的 FP16 FlashAttention-3,固定參數 \(\{\mathrm{batch},\mathrm{seqlen},\mathrm{nheads},\mathrm{hdim}\}=\{4,8448,16,128\}\),分別消融兩階段 WGMMA-softmax 管線與 warp-specialization。Table 2 的結果確認,我們的演算法改進——透過 warp-specialization 實現非同步,以及讓 GEMM 與 softmax 重疊——帶來顯著加速,從 570 提升至 661 TFLOPs。

Table 2原始 PDF 第 11 頁

Pipelining ablation measurements管線設計的消融量測。
ConfigurationTimeTFLOPs/s
FlashAttention-33.538 ms661
No GEMM-Softmax Pipelining, Warp-Specialization4.021 ms582
GEMM-Softmax Pipelining, No Warp-Specialization4.105 ms570

這張表在說什麼

完整方法同時保留 warp-specialization 與 GEMM-softmax 管線,取得最低時間及最高吞吐量。兩個移除版本都較慢,支持這兩種非同步設計在該設定下的實際價值。

怎麼看

先讀第一列完整方法,再分別比較第二列移除管線、第三列移除 warp-specialization 的結果。Time 越低越好,TFLOPs/s 越高越好;三列皆為固定的非因果 FP16 設定,不能外推為 FP8 或所有序列長度的效益。

p. 10

原文 SOURCE

As there has been interest in the numerical error [21] of FlashAttention, we compare FlashAttention-2, FlashAttention-3, and a standard implementation of attention against a reference implementation in FP64. To simulate outlier features and activations in LLMs [20, 54], we generate the entries of Q, K, V with the following distribution: \[\mathcal{N}(0,1)+\mathcal{N}(0,100)\cdot\operatorname{Bernoulli}(0.001).\] That is, each entry is normally distributed with zero mean and standard deviation 1, but for 0.1% of entries we add an independent term that’s normally distributed with standard deviation 10. We then measure the root mean squared error (RMSE) in Table 3. In FP16, both FlashAttention-2 and FlashAttention-3 achieves 1.7× lower RMSE compared to the standard implementation since intermediate results (softmax) are kept in FP32. The baseline attention in FP8 uses per-tensor scaling, with matmul accumulator in FP32 and intermediate softmax results kept in FP16. Thanks to block quantization and incoherent processing, FlashAttention-3 in FP8 is 2.6× more accurate than this baseline.

繁體中文 TRANSLATION

由於研究社群關注 FlashAttention 的數值誤差 [21],我們以 FP64 的參考實作為基準,比較 FlashAttention-2、FlashAttention-3 與標準注意力實作。為了模擬 LLM 中的離群特徵與活化值 [20, 54],我們依下列分布產生 \(Q\)、\(K\)、\(V\) 的元素: \[\mathcal{N}(0,1)+\mathcal{N}(0,100)\cdot\operatorname{Bernoulli}(0.001).\] 也就是說,各元素服從平均數為 0、標準差為 1 的常態分布,但其中 0.1% 的元素會額外加上一個獨立的常態隨機項,其標準差為 10。接著,我們量測均方根誤差(RMSE),結果列於 Table 3。使用 FP16 時,FlashAttention-2 與 FlashAttention-3 相較標準實作,RMSE 均降低約 1.7 倍,因為 softmax 中間結果保留為 FP32。FP8 注意力基線採用逐張量縮放,矩陣乘法累加器使用 FP32,softmax 中間結果則保留為 FP16。受惠於區塊量化與 incoherent processing,FP8 FlashAttention-3 比此基線準確 2.6 倍。

Table 3原始 PDF 第 12 頁

Numerical error comparisons in FP16 and FP8 (e4m3).FP16 與 FP8(e4m3)的數值誤差比較。
MethodBaseline FP16FlashAttention-2 FP16FlashAttention-3 FP16
RMSE3.2e-41.9e-41.9e-4
MethodBaseline FP8FlashAttention-3 FP8No block quantNo incoherent processing
RMSE2.4e-29.1e-39.3e-32.4e-2

表格註記:原表由上下兩組不同欄數的橫向比較組成:FP16 有三個方法,FP8 有四個方法。為保留原始排列並滿足矩形資料結構,僅在 FP16 表頭與資料列尾端補空字串;這些空字串不是原始缺值。第二組 Method 表頭保留為資料列,以維持原表上下順序。

這張表在說什麼

上半部顯示兩代 FlashAttention 的 FP16 誤差一致,且低於標準基線。下半部顯示完整 FP8 方法降低 RMSE,並透過兩項移除實驗區分精度處理的影響。

怎麼看

先讀 FP16 的 RMSE 列,再讀第二個 Method 列所定義的 FP8 欄名及其下方 RMSE。所有 RMSE 越低越好,均相對 FP64 參考結果;No block quant 與 No incoherent processing 是 FP8 方法的消融,不是 FP16 結果。

p. 21

原文 SOURCE

We use following sequence lengths: 512, 1024, 2048, 4224, 8448, 16896. When sequence length \(\geq 4\mathrm{k}\), we make it also divisible by 132 (number of SMs in H100 SXM5) to avoid wave quantization.

繁體中文 TRANSLATION

我們使用以下序列長度:512、1024、2048、4224、8448、16896。當序列長度 \(\geq 4\mathrm{k}\) 時,我們也讓它能被 132 整除;132 是 H100 SXM5 的 SM 數量,這樣可避免 wave quantization。

Figure 9原始 PDF 第 22 頁

Attention forward speed (FP8) on H100 GPUH100 GPU 上的注意力前向速度(FP8)。

這張圖在說什麼

完整 FP8 結果顯示,FlashAttention-3 的优势隨 head dimension、mask 與長度改變。head dimension 64 的長序列較有優勢;128 與 256 在長序列無 mask 時接近 cuDNN,但有 mask 時仍可能落後。head dimension 256、無 mask 的最長序列達 1171 TFLOPs/s。

怎麼看

先按列選 head dimension 64、128 或 256,再按左右欄選無 mask 或有 mask。橫軸為簡化後的長度標籤,實際長序列採 4224、8448、16896;縱軸 TFLOPs/s 越高越好。比較紫色 FlashAttention-3 與紅色 cuDNN,尤其注意短序列和右欄不能概括為前者領先。

5. 限制、反向設計與負面結果

論文的限制不只在尚未驗證的大規模訓練,也包括 FP8 的負載平衡缺口與編譯器對理想管線的干預。反向運算另以專用 dQ writer 隔離跨區塊累加造成的記憶體競爭。

p. 12

原文 SOURCE

With FlashAttention-3, we have demonstrated that new programming techniques and hardware features such as asynchrony and low-precision can have a dramatic impact on the efficiency and accuracy of attention. We are able to speed up attention by 1.5-2.0× times compared to FlashAttention-2, and reduce FP8 numerical error by 2.6× compared to standard per-tensor quantization. Some limitations of our work that we hope to address in the future include: optimizing for LLM inference, integrating a persistent kernel design into the FP8 kernel, and understanding the effects of low-precision attention in large-scale training. Though we have focused on Hopper GPUs in this work, we expect that the techniques developed here will apply to other hardware accelerators. We hope that a faster and more accurate primitive such as attention will unlock new applications in long-context tasks.

繁體中文 TRANSLATION

透過 FlashAttention-3,我們證明非同步、低精度等新程式設計技術與硬體特性,能對注意力的效率及數值精度產生顯著影響。相較 FlashAttention-2,我們能讓注意力加速 1.5–2.0 倍;相較標準逐張量量化,則能將 FP8 數值誤差降低約 2.6 倍。我們希望未來處理的限制包括:針對 LLM 推論進行最佳化、將 persistent kernel 設計整合至 FP8 核心,以及了解低精度注意力對大規模訓練的影響。雖然本研究聚焦於 Hopper GPU,我們預期這些技術也能適用於其他硬體加速器。我們希望,更快速且更精確的注意力這類基礎運算,能開啟長上下文任務的新應用。

p. 18

原文 SOURCE

Similar to the forward pass § 3.1, we use warp specialization to handle asynchrony. Instead of just a simple producer-consumer pattern in the forward pass, we add one extra role of a dQ writer, since we need to accumulate the value of dQ produced by each thread block to the global value of dQ. This dQ accumulation introduces memory contention (many thread blocks writing to the same location) so having a separate warp to handle this (along with asynchrony) will avoid blocking the rest of the warps in the thread block to perform the next computation (matmul). We include the backward pass with warp specialization in Algorithm 3.

繁體中文 TRANSLATION

與 § 3.1 的前向運算相似,我們使用 warp specialization 來處理非同步。不同於前向中單純的生產者—消費者模式,我們新增 dQ writer 這個角色,因為必須把各 thread block 產生的 \(\mathrm{d}Q\) 累加到全域的 \(\mathrm{d}Q\)。這種 \(\mathrm{d}Q\) 累加會造成記憶體競爭,也就是多個 thread blocks 寫入同一位置;因此,讓獨立 warp 搭配非同步機制處理這件事,可以避免阻塞同一 thread block 的其他 warps,使它們能繼續執行下一次矩陣乘法。Algorithm 3 列出了採用 warp specialization 的反向運算。

p. 20

原文 SOURCE

Overlapping. We expected that softmax can be overlapped with (the first WGMMA + the second WGMMA). However, the compiler doesn’t cooperate in this way. SASS code shows that only the first WGMMA is overlapped with softmax, while the second WGMMA is not. It’s not clear why the compiler chooses to reorder instructions in this way. Register pressure. This algorithm requires more registers compared to the 2-stage pipelining algorithm. In theory, it needs to store an extra \(\widetilde{P}_i\) and \(scale\_o\), which is of size \(B_r\times B_c\times\operatorname{sizeof}(\mathrm{input\_data\_type})+B_r\times\operatorname{sizeof}(\mathrm{float})\). As a result, a smaller block size needs to be chosen.

繁體中文 TRANSLATION

重疊。我們原本預期 softmax 能與第一個及第二個 WGMMA 都重疊執行。然而,編譯器並未配合這種安排。SASS 程式碼顯示,只有第一個 WGMMA 與 softmax 重疊,第二個則沒有。目前不清楚編譯器為何選擇這樣重新排列指令。 暫存器壓力。相較兩階段管線,這個演算法需要更多暫存器。理論上,它必須額外儲存 \(\widetilde{P}_i\) 與 \(scale\_o\),所需大小為 \(B_r\times B_c\times\operatorname{sizeof}(\mathrm{input\_data\_type})+B_r\times\operatorname{sizeof}(\mathrm{float})\)。因此,必須選擇較小的區塊。

Figure 8原始 PDF 第 20 頁

3-Stage Pipelining三階段管線。

這張圖在說什麼

圖示三個不同迭代階段同時推進的理想設計:較後迭代的第一個 WGMMA、中間迭代的 softmax,以及較早迭代的第二個 WGMMA。實際编譯結果沒有達成圖中預期的完整重疊,因此不能將此圖視為成功實現的效能證據。

怎麼看

沿時間軸找同時對齊的三列工作,確認它們的迭代編號不同,再與 Figure 2 的兩階段安排比較。右端是管線排空階段;閱讀時應同時對照本文對編譯器排程及暫存器壓力的限制說明。