Skip to content

flash-attn2: [XPU] split-KV decode, faster prefill and paged decode - #1309

Open
jiqing-feng wants to merge 32 commits into
huggingface:mainfrom
jiqing-feng:fa2-xpu-decode-splitkv
Open

jiqing-feng wants to merge 32 commits into
huggingface:mainfrom
jiqing-feng:fa2-xpu-decode-splitkv

Conversation

@jiqing-feng

@jiqing-feng jiqing-feng commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

I know a PR this large is unlikely to be reviewed line by line. It has been tested on our internal B60 and CRI machines, and I have a full test report I can share.

What's new compared to main

Results

Speedup over main (kernel time, bf16, hd128 unless noted):

B60 CRI
Prefill, contiguous (hd128 + hd256) 1.1–1.75× 2.6–3.6×
Prefill, paged (page 64, hd128) main: hangs; PR: works 4.7×
Decode, 1k–4k context 1.2–1.8× 1.25–1.5×
Decode, 32k context 2.3–6.1× 2.7–4.8×
Page size 16 / 32 main: unsupported; PR: works main: unsupported; PR: works
End-to-end (transformers continuous_batching_simple.py) 1.03× 1.06×
  • Performance is on par with vllm-xpu-kernels on both B60 and CRI.
  • All tests pass on both GPUs, no regressions.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

This PR changes source code for the following kernel(s): flash-attn2.

If you have the kernel-bot build permissions, then trigger /kernel-bot build flash-attn2 yourself. Otherwise, a maintainer will review the PR and will take an appropriate action. Thanks for your patience.

@github-actions github-actions Bot added the chore Version bumps, releases, misc maintenance label Nov 9, 2026
@jiqing-feng
jiqing-feng marked this pull request as draft November 9, 2026 08:43
Run each query of a batch with up to 16 queries (speculative decoding)
as its own split-KV decode row, with bottom-right causal masking. In a
varlen batch with longer queries (chunked prefill mixed with decode),
the generic kernel now skips the one-query batches and the split-KV
kernel handles them.
With several queries per batch the split-KV decode kernel tiled the GQA
group of a single query, so MHA and small GQA groups left most of the
8-row Q tile empty and re-read the KV once per query (up to 3x slower than
the generic kernel for MHA with 16 queries).

Add a layout that packs up to 8 queries of one Q head into the tile, with a
per-row causal / sliding-window mask, and pick the layout that needs fewer
work-groups per (batch, KV head).
Follow FlashAttention 3 PackGQA (hopper/pack_gqa.h), which is always used
when splitting KV: a work-group takes 8 consecutive rows of the
(query, Q head of the group) rows of one (batch, KV head), head fastest.
The KV of a batch is read once per 8 rows, which covers both previous
layouts (GQA group of one query; queries of one Q head) and also fills
the tile for groups of 2-7 heads with several queries.

Rows of different queries are not one 2D surface, so Q is loaded and O
stored per query surface (the GQA heads of that query), relying on the
2D block messages zero-filling / dropping rows outside the surface. With
one head per KV head the queries form a single surface. Single-query
decode keeps the previous single surface and split plan.
- Paged KV takes the vllm-xpu-kernels split count (get_num_splits plus
  the decode kernel's single-split rule) instead of the measured table.
- Single-surface Q skips the multi-surface merge, so the Q block load
  feeds the MMA directly and overlaps with the K load.
- Rows without a visible key are written by the kernels, so the split
  path allocates out / LSE without zero fills; the combine computes the
  split weights once per row (vllm ReduceSplitK).
Choose the large-surface and multi-query mainloop variants on the host and
instantiate one kernel per variant, as vllm-xpu-kernels instantiates one
decode kernel per policy. With all three variants inlined in one kernel the
paged head_dim 256 kernel spilled and ran up to 17% slower than vllm at
short KV.
… on CRI

Build a second image of the decode kernels for Xe35 (CRI) with the CRI
define so sycl-tla emits the Xe35 block loads, and select it from the
device IP version. On CRI, paged/varlen decode goes through the
xe_3 paged-decode kernel from vllm-xpu-kernels with its split-count
tuning table; FLASH_ATTN_XPU_DISABLE_VLLM_DECODE=1 keeps the split-KV
kernel.

Also fix ReduceSplitK for head dim 512.
…rrier

Add a split barrier per K block to the xe2 prefill mainloop, as in
sycl-tla's xe_fmha_fwd_mainloop and vllm's chunk_prefill mainloop.
Without it, two work-groups sharing one BMG Xe-core can produce wrong
results or hang the GPU.

With causal/local masks the K range differs between sub-groups, so
sub-groups with fewer (or no) K blocks run empty barrier rounds up to
the work-group maximum.
Port the vllm-xpu-kernels chunk-prefill kernel and dispatch to it for
contiguous and paged prefill (hd128 on BMG; hd64/128/256 on CRI).
Paged KV with page size 16/32 now works on CRI by picking a policy whose
KV tile divides the page size.

flash_attn_func and flash_attn_varlen_func call the XPU op directly when
no autograd or torch.compile is involved, which removes ~20 us of host
overhead per call.
…ls by function

Move src/prefill_vllm -> src/prefill and src/decode/vllm -> src/decode
(paged decode) and src/prefill/xe3 (Xe3 collectives shared by the xe3
prefill and the paged decode), rename the instantiation files, namespaces,
macros and env vars (FLASH_ATTN_XPU_DISABLE_{CHUNK_PREFILL,PAGED_DECODE}),
and add copyright/attribution headers to the adapted files.
…n Xe2

Port the vllm-xpu-kernels Xe2 paged decode kernel for pages of 16 or 32
rows, which the split-KV kernel does not take, and run head sizes 64 and
256 with such pages through the chunk-prefill kernel.
…el for small pages

The split-KV kernel cannot run 16/32-row pages, so the one-query batches of
a mixed batch were left uncomputed.
…code hang

CRI kernels now get 512 GRF the way vllm-xpu-kernels does it: the build
passes ocloc -cl-intel-512-GRF-per-thread for the CRI target
(build.toml `[general.xpu] cri-grf-size = 512`, kernel-builder from
jiqing-feng/kernels xpu-cri-grf-size). Kernels that need another size set
it with flash_xpu_grf::with_grf<N>() (grf_mode.hpp); bwd uses 256 where
BMG picked it before. This replaces the per-kernel grf_size /
maximum_registers properties. The XE3 paged decode and chunk prefill
kernels no longer need DPC++ >= 2026.2 and are always built (DPC++
2026.1.1 / ocloc 26.22).
scripts/check_xpu_build.py checks that every library has AOT images and
the expected GRF sizes; build.yaml runs it for XPU builds.

fp16 hd256 page-32 paged decode hung on CRI (DEVICE_LOST) on every run.
ocloc 26.22 miscompiles the XE3 paged decode kernel when it writes
O = 0 / LSE = -inf for sequences without keys; ocloc 26.40 compiles it
fine. Follow vllm:
- XE3 paged decode skips sequences without keys. With several splits
  ReduceSplitK still writes O = 0 / LSE = -inf for them; with one split
  those rows are left undefined, as in vllm. Xe2 is unchanged.
- Padded-query LSE rows (>= cu_seqlens_q[batch]) are zeroed by a
  host-side mask on the varlen paged decode path, and in the split-KV
  and chunk prefill kernels via zero_padded_lse() (lse_pad.hpp).

Both workarounds are marked TODO(ocloc>=26.40).

Tested on CRI (card 1) and BMG: pytest 1148 passed / 422 skipped /
0 failed on both, padded-LSE probe clean, no DEVICE_LOST in the fp16/bf16
hd256 page 16/32 repro matrix.
@jiqing-feng
jiqing-feng marked this pull request as ready for review November 23, 2026 05:05
- One chunk-prefill / paged-decode source for Xe2 (BMG) and Xe3P (CRI);
  per-arch differences are compile-time traits, only the mainloop is kept
  per arch (prefill/xe20, prefill/xe35).
- Shape instantiations live in flash_attn_xpu/src/instantiations/, one per
  translation unit, generated by instantiations/generate.py.
- Large paged K/V surfaces use a separate kernel instantiation on both
  architectures, selected on the host.
- Bump kernel-builder: XPU images without SPIR-V copies and stripped symbol
  tables (.so 347 MB -> 169 MB).
@jiqing-feng jiqing-feng changed the title flash-attn2: [XPU] split-KV decode kernel for seqlen_q == 1 flash-attn2: [XPU] add split-KV decode, port vllm-xpu-kernels chunk-prefill and paged-decode kernels Nov 26, 2026
@sywangyi

sywangyi commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

When the supported instantiation set changes, this script creates or overwrites the expected files but leaves obsolete files in place. It also prints the source list without checking that build.toml matches it. This can leave removed variants in the build or omit new ones. Could we add a read-only --check mode that validates generated files and the build manifest,

@jiqing-feng

Copy link
Copy Markdown
Contributor Author

When the supported instantiation set changes, this script creates or overwrites the expected files but leaves obsolete files in place. It also prints the source list without checking that build.toml matches it. This can leave removed variants in the build or omit new ones. Could we add a read-only --check mode that validates generated files and the build manifest,

Added in eb43266:

  • generate.py --check is read-only. It fails (exit 1) if a generated file is missing or out of date, if instantiations/ contains a .cpp the script does not generate, or if the instantiation entries in [kernel.flash_attn_xpu] / [kernel.flash_attn_xpu_cri] of build.toml are missing, extra, or duplicated.
  • The default mode now also deletes obsolete files and runs the same check at the end, so a stale build.toml is reported right after regenerating.

--check passes on the current tree, and regenerating produces no diff.

window_size_right, skv_causal) &&
(!skv_causal || seqlen_k >= seqlen_q))) &&
p_dropout == 0.0f && !return_softmax &&
!alibi_slopes_.has_value() && softcap == 0.0f &&

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

XPU silently ignores ALiBi and softcap. these arguments exclude the split-KV fast path, but the regular forward path does not pass them to the computation. The variable-length forward and backward paths have the same issue. Users therefore receive a successful result that does not apply the requested options. The tests currently skip these XPU combinations. Until support is implemented, the XPU entry points should explicitly reject non-default values.

if (max_seqlen_q >= 1 && p_dropout == 0.0f && !return_softmax &&
!alibi_slopes_.has_value() && softcap == 0.0f &&
!(seqused_k.has_value() && seqused_k->defined()) &&
!(leftpad_k_.has_value() && leftpad_k_->defined()) &&

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The variable-length forward path silently ignores seqused_k and leftpad_k_. At flash_api.cpp:985, providing either argument disables the specialized path, but the fallback path does not use them. If a batch’s actual KV length is shorter than the length indicated by cu_seqlens_k, or K has left padding, attention covers the wrong range. Please implement these semantics or reject the arguments as unsupported at the entry point.

@jiqing-feng

Copy link
Copy Markdown
Contributor Author

@sywangyi The XPU kernels do not implement these options, so the entry points now reject them instead of ignoring them (same as the CUDA build does when a feature is compiled out), done in f8e2850:

  • mha_fwd, mha_varlen_fwd, mha_bwd, mha_varlen_bwd: alibi_slopes and non-zero softcap raise.
  • mha_varlen_fwd: seqused_k and leftpad_k also raise.
  • mha_fwd_kvcache: non-zero softcap raises (alibi_slopes was already rejected; leftpad_k is supported there and unchanged).

The now-redundant checks on the fast paths are removed, and test_flash_attn_xpu_rejects_unsupported covers the new errors.

@jiqing-feng
jiqing-feng marked this pull request as ready for review December 1, 2026 05:22
…n the kernel

With ocloc >= 26.40 the Xe35 paged decode kernel can write O = 0 /
LSE = -inf for sequences without keys and LSE 0 for padded queries
again. This drops the host-side mask (two extra kernels, ~12 us host
time per varlen decode call).
…oads and windows

Use the SYCL-TLA multi-payload API (prepare_payloads / copy_with_multi_payloads /
prefetch_with_payloads / update_payloads) as vllm-xpu-kernels does instead of
the local xe2d_payloads.hpp, and run a causal window as a non-causal local
window with window_size_right = 0, so Causal+Local is no longer built.
… kernel

The chunk prefill Local variant now writes the LSE, so 16-bit varlen windows take it instead of the generic kernel.
Park the softmax_lse store coordinates in private memory across the K loop and
use native::recip for the epilogue row-sum reciprocal (the IEEE division from
-foffload-fp32-prec-div pushed the mainloop into spilling).
@jiqing-feng jiqing-feng changed the title flash-attn2: [XPU] add split-KV decode, port vllm-xpu-kernels chunk-prefill and paged-decode kernels flash-attn2: [XPU] split-KV decode, faster prefill and paged decode Dec 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

chore Version bumps, releases, misc maintenance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants