transformers: compute CPU FlashSdpa P·V as a tile GEMM (~3.1×)#2319
Open
czoli1976 wants to merge 1 commit into
Open
transformers: compute CPU FlashSdpa P·V as a tile GEMM (~3.1×)#2319czoli1976 wants to merge 1 commit into
czoli1976 wants to merge 1 commit into
Conversation
The forward flash-attention's P·V step computed `head_dim` separate dot products against strided columns of V (s.row(i).dot(vblock.column(j))) -- no GEMM, and the strided column access defeats vectorization. Replace it with one contiguous tile GEMM `s.dot(&vblock)` plus the online-softmax rescale. Bit-exact vs a naive host reference (max_abs 0.0). Bench (H8/Sq512/Sk512/D64, release): 76.2 -> 24.6 ms/run = 3.1x on the whole flash_attention_gqa (the strided P·V was ~68% of the time). QK^T already used a 2-D GEMM; this brings P·V to parity. Co-Authored-By: Claude Opus 4.8 <[email protected]>
This was referenced May 30, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
The CPU
FlashSdpaOpforward pass (transformers/src/ops/flash_sdpa.rs) computed theP·Vstep ashead_dimseparate dot products against strided columns of V:vblock.column(j)is a strided view (stride =head_dim), so this is neither a GEMM nor vectorization-friendly. This replaces it with a single contiguous tile GEMM plus the online-softmax rescale:The
QK^Tstep above already used a 2-D.dot(); this just bringsP·Vto parity.Why
max_abs = 0.0vs a naivesoftmax(QKᵀ·scale)·Vreference.flash_attention_gqa— H=8, Sq=Sk=512, D=64, release build: 76.2 → 24.6 ms/run. The stridedP·Vwas ~68% of the runtime.Tests
flash_sdpa_pv_matches_naive— correctness vs naive reference (non-square, multi-head).bench_flash_sdpa_pv(#[ignore]) — the before/after A/B used for the numbers above.tract-transformerssuite green;fmt+clippyclean.🤖 Generated with Claude Code