1---2name: xe2-sdp-kernels3description: Use this skill when writing, optimizing, benchmarking, or debugging Flash Attention SDP kernels (prefill full-dense or decode full-dense) targeting Intel Xe2 (Lunar Lake/LNL, Battlemage/BMG) GPU using SYCL ESIMD. Xe2 is the GPU architecture; LNL and BMG are product names. Covers the complete optimization journey from scalar loops to DPAS, GQA layout, two-phase decode, perf testing methodology, and all hardware constraints discovered through implementation.4---56# Xe2 (Lunar Lake/LNL, Battlemage/BMG) ESIMD Flash Attention — SDP Prefill & Decode (Full Dense)78Specialized knowledge for GQA flash attention on Intel Xe2 (Lunar Lake/LNL, Battlemage/BMG).9Reference files hold detail; this file holds critical rules and workflow.1011---1213## Quick-Reference Rules (must follow every time)1415### Hardware limits16- **Max WG threads = 32** when `doubleGRF` is on. Never set nd_range WG size > 32.17- **Always compile with `doubleGRF`** — mandatory for SDP tile sizes. Do not remove.18- **Barriers**: every thread in WG must execute the same number of `barrier()` calls. Unequal counts = GPU hang (silent, infinite stall). See `references/hardware-constraints.md`.1920### Inner-loop rules21- **No `if`, no `?:`** inside the KV iteration loop body. Move all runtime conditionals to host.22- **Pre-compute loop counts on host** (e.g. causal `kvSeqOutLoopCount` based on max q-pos in WG).23- **Use `index +=` increments** — never recompute full coordinate expressions each iteration.24- **More XVE + XMX parallelism lowers frequency** — minimize XVE ops in hot loop.25- **Separate last iteration** from main loop to handle boundary masking without branches.2627### API namespace28- Use `sycl::ext::intel::experimental::esimd` for `lsc_load_2d`, `lsc_prefetch_2d`, `config_2d_mem_access`.29- Use `sycl::ext::intel::esimd::xmx::dpas` for DPAS.30- Use `sycl::ext::intel::esimd::block_load<T,N>` for 1D contiguous loads.31- See `references/lsc-memory-ops.md` for full API.3233### DPAS / VNNI34- DPAS signature: `dpas<8, 8>(acc, B_vnni, A_rowmaj)` — B first, A second.35- For S×V: softmax weights must be VNNI-packed (interleave pairs of fp16 before DPAS).36- Use `exp2()` with `attnScoreMul = (1/sqrt(HD)) * log2e` — faster than `exp()`.37- See `references/kernel-patterns.md`.3839### kv_len alignment40- **kv_len does NOT need to be chunk_size-aligned.** Use `valid_t` clamping:41 ```cpp42 int valid_t = min(sp_blk_size, max(0, kv_len - kvLogicalOffset));43 for (int t = 0; t < valid_t; t++) { ... }44 ```45- Use **ceiling** division: `chunk_num = (kv_len + chunk_size - 1) / chunk_size`.4647### GQA layout48- Q: `[q_len, headQ, HD]` — stride between tokens: `headQ * HD * sizeof(fp16)`49- K/V: `[kv_len, headKv, HD]` — stride: `headKv * HD * sizeof(fp16)`50- Decode Q: `[headQ, HD]` (single token)51- `group_size = headQ / headKv`; each kv_head serves group_size q_heads.5253### Performance testing54- **Cache-bust** (N_BUF=4) for memory-bound kernels (decode, mask_convert) — rotate buffer sets every iteration.55- **Warmup**: 5 iters minimum; 20 preferred for stable frequency.56- **Iteration count**: 100 iters minimum; 1000 for compute-bound kernels.57- **Random non-zero init** — avoid all-zero inputs (hide NaN bugs, unrealistic cache perf).58- See `references/perf-testing.md`.5960### Correctness testing61- Check **NaN count** before computing max_diff (NaN denominator silently passes threshold).62- Common NaN source: `fp32SoftMaxTemp` (softmax denominator) → 0 when all scores are -inf.63- CPU reference threshold: `thresh = (scale <= 0.1f) ? 0.1f : scale * 1.5f`.64- See `references/correctness-testing.md`.6566### Compile command67```bash68icpx <src>.cpp -o <out>.exe \69 -fsycl -fsycl-targets=spir64_gen \70 -Xs "-device bmg -options -doubleGRF" -O371```72- Do **not** use `-doubleGRF` as a top-level flag — it must be inside `-Xs "..."`.73- Spill warning `warning: ... spilled ... bytes` → reduce tile sizes.7475### SPIR-V linker errors76- Cause: runtime `if` in kernel that can be moved to host.77- Fix: `if constexpr` (template param) or dispatch multiple template instantiations from host.7879---8081## Workflow82831. **Write kernel** following inner-loop rules above.842. **Compile** — check for spill warnings. Any spill > 0 causes significant regression.853. **Correctness test** at small sizes (q=512, kv=1024). Check NaN. Check max_diff.864. **Corner cases**: q not 16-aligned, kv not chunk-aligned, kv not 8-aligned, kv < chunk_size.875. **Benchmark** at production sizes with 5 warmup + 100 iters, N_BUF=4 for BW-bound.886. **Iterate**: reduce XVE ops, verify barrier symmetry, check frequency stability.8990---9192## Assets (ready to compile)9394```bash95icpx <file>.cpp -o <file>.exe -fsycl -fsycl-targets=spir64_gen -Xs "-device bmg -options -doubleGRF" -O396```9798| Asset | Purpose | Perf |99|-------|---------|------|100| `assets/flash.attn.b.mha128.gqa.precomputed_yuchen.h` | **Production prefill** GQA, causal/non-causal template | 83–86% roofline |101| `assets/decode_sdp_gqa.h` | **Production decode** full-dense, two-phase | 65–78% roofline |102| `assets/flash.attn.b.mha128.h` | Legacy non-GQA prefill (historical reference) | ~60% roofline |103| `assets/sdp_perf_all.cpp` | **Unified perf test** — all 5 kernels, sections 1–5 | run directly |104| `assets/sdp_correctness_all.cpp` | **Unified correctness** — 86 test cases, 6 sections | run directly |105106Expected: `sdp_correctness_all.exe` → `86/86 PASSED -- ALL PASSED`107108---109110## Related Skills111112| Skill | When to use |113|-------|------------|114| `xe2-sdp-bf16` | BF16 and bf16io (hybrid) flash attention kernels — bf16 ALU limits, V conversion interleaving, mixed-precision strategies |115| `xe2-kernel-testing` | General correctness/perf testing patterns for any Xe2 ESIMD kernel |116| `sycl-esimd-build` | Compilation flags, doubleGRF, spill detection |117118---119120## Reference files121122| File | Contents |123|------|----------|124| `references/hardware-constraints.md` | Xe2/BMG GRF, L1, SLM, WG, barrier, frequency limits |125| `references/kernel-patterns.md` | DPAS tile layout, VNNI packing, online softmax, SLM ping-pong, coord patterns |126| `references/lsc-memory-ops.md` | Full LSC API: `lsc_load_2d`, `lsc_prefetch_2d`, `block_load`, `lsc_scatter`, cache hints |127| `references/perf-testing.md` | Cache-bust boilerplate, timing harness, random init, NaN check |128| `references/correctness-testing.md` | CPU reference pattern, thresholds, corner case list |129| `references/optimization-history.md` | Full story from 0.0004T scalar → 86% roofline DPAS |130| `references/code-index.md` | Per-file annotations, dispatch shapes, parameter summary |