From 58e1f8d0c97365b2c016bfa2c46d6917c0502b3c Mon Sep 17 00:00:00 2001 From: maxfridbe Date: Wed, 30 Sep 2026 07:47:11 -0500 Subject: [PATCH] sycl: the speed round - warm-up captures, commit/draft overlap, vector-store dequant, XMX kernels (opt-in), profiles Measured on the B70, outputs identical before and after each change (docs/INTEL.md "Speed work"): - every window graph and the drafter's graphs captured at load (STRATA_WARM_GRAPHS=0 restores first-use capture) - the commit graph is left running while the drafter's round runs on its own queue: decode 38.3 -> 43.1 tok/s at the 2,184-token context, 46.5 -> 49.7 on a short prompt - the draft layer's batched prompt pass takes prompts under 64 rows (106 -> 16 ms on 19 tokens) - one device module per kernel: the first launch in the prompt path 245 -> 1 ms - the expert dequant writes each thread's run as one vector store: 0.085 -> 0.030 ms per expert; the 2,184-token prompt 566 -> 682 tok/s, 8,000 tokens 720 -> 841 - SWAR sign compare/subtract in the expert dots, a local-memory resident-plan kernel, a split-K fused down kernel (bit-identical to the single-token kernel, gr_parity): parity-clean, no measurable decode change XMX: oneMKL's FP16 GEMMs already run on the XMX units (30-60 TFLOP/s). Two joint_matrix kernels are in the tree, correct and opt-in because both lose to the paths they would replace on this card: xmx_gemm_iq (fused dequant + GEMM from the quantized rows; xmx_gemm_bench) and qsa_prompt_attn_xmx (the mma.sync prompt attention's port; qsa_prompt_attn_parity passes at 1e-6 of scale; STRATA_PROMPT_ATTN_XMX=1). Profiling: unitrace -q needs Intel's metrics libraries (Dockerfile.metrics) and dev.xe.observation_paranoid=0; the per-kernel table is in INTEL.md. A trap recorded there: --prefill-until with a native pack drops the prompt tail (the token loop is skipped), so a "windows for short prompts" routing was invalid and is not in this commit. --- docs/INTEL.md | 30 ++ sycl/CMakeLists.txt | 7 + sycl/include/strata/core/mtp.hpp | 9 + sycl/include/strata/core/verify.hpp | 11 +- .../strata/kernels/qsa_prompt_attn_xmx.hpp | 11 + sycl/include/strata/kernels/xmx_gemm.hpp | 11 + sycl/src/core/verify.cpp | 62 +-- sycl/src/kernels/cuda/fused_gr.dp.cpp | 84 +++-- sycl/src/kernels/cuda/iq_kernels.dp.cpp | 342 +++++++++++++---- sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp | 5 +- .../kernels/cuda/qsa_prompt_attn_xmx.dp.cpp | 357 ++++++++++++++++++ sycl/src/kernels/cuda/verify_kernels.dp.cpp | 48 ++- sycl/src/kernels/xmx_gemm_bench.cpp | 93 +++++ sycl/src/prefill/prefill.cpp | 18 +- sycl/src/program/generate.cpp | 20 +- 15 files changed, 974 insertions(+), 134 deletions(-) create mode 100644 sycl/include/strata/kernels/qsa_prompt_attn_xmx.hpp create mode 100644 sycl/include/strata/kernels/xmx_gemm.hpp create mode 100644 sycl/src/kernels/cuda/qsa_prompt_attn_xmx.dp.cpp create mode 100644 sycl/src/kernels/xmx_gemm_bench.cpp diff --git a/docs/INTEL.md b/docs/INTEL.md index 0948f1cb..e5701e80 100644 --- a/docs/INTEL.md +++ b/docs/INTEL.md @@ -229,6 +229,36 @@ the ramp, not the kernel). 38.3 tok/s decode (77% accepted on that text); the draft layer's prompt pass is now upstream's batched one (38.6 ms for 2,184 tokens, from 105 ms for 19 before it). Parity: 19 of 22, byte-exact `quantize_act` back. +**Speed work, 2026-09-30 (after the 0.1.27 merge).** What moved the numbers, measured on the B70 with the +same prompts as above (outputs identical before and after each change): + +| change | effect | +|---|---| +| every window graph and the drafter's graphs captured at load (`STRATA_WARM_GRAPHS=0`: as before) | the first request no longer pays 250-290 ms of captures | +| the commit graph left running while the drafter's round runs on its own queue (`Verifier::commit(wait=false)` + `commit_finish`) | decode 38.3 -> 43.0 tok/s at the 2,184-token context, 46.5 -> 49.8 short | +| the draft layer's batched prompt pass takes prompts under 64 rows (it fell back to per-6-token graphs) | its prompt cost on 19 tokens 106 -> 16 ms | +| one device module per kernel (`-fsycl-device-code-split=per_kernel`) | the first launch in the prompt path (the embedding gather) 245 -> 1 ms | +| the expert dequant writes each thread's run of FP16 values as one vector store (it wrote them one 2-byte store at a time) | dequant per expert 0.085 -> 0.030 ms; prompt 496 -> 575 tok/s at 2,184 tokens, 720 -> 841 at 8,000 | +| SWAR sign compare/subtract in the expert dots, a local-memory resident-plan kernel, a split-K fused down kernel (bit-identical to the single-token one) | parity-clean, no measurable decode change; kept | + +Draft policy sweep (2,184-token prompt, 128 tokens): windows of 6 (`--spec 4`) at 41.6-43.5 tok/s; `--spec 2` +33.6, `--spec 6` 35-37; `--spec-min-p` 0.3-0.7 within noise. Profiles (unitrace, `strata-sycl-dev:metrics` with +Intel's metrics libraries and `dev.xe.observation_paranoid=0`): the expert dot kernels are ALU-bound (77% XVE +active), the dense projections memory-latency bound (92-128 GB/s at 84-93% occupancy), a decode round is 80-85% +kernel time and ~5 us of launch gap per node over 2,400-2,600 nodes. + +**XMX.** oneMKL's FP16 GEMMs already run on the XMX units (30-60 TFLOP/s in `xmx_gemm_bench`); the prompt path is +bound by the dequant that feeds them, not by the products. Two joint_matrix kernels were written and are correct +but lose to the existing paths on this card, so both stay opt-in: `xmx_gemm_iq` (a fused dequant + GEMM straight +from the quantized rows, 4-5x slower than dequant + oneMKL) and `qsa_prompt_attn_xmx` (the port of the mma.sync +prompt attention; `qsa_prompt_attn_parity` passes at 1e-6 of scale, 3x slower than the FP32 fallback per chunk; +`STRATA_PROMPT_ATTN_XMX=1`). Where the prompt time goes now (2,184 / 8,000 tokens): dequant 28% / 27%, GEMMs +22% / 20%, the per-layer host grouping 9.5% / 9%, attention 7% / 14%, embeddings + PLE rows 13% / 5%. + +A trap worth knowing: with a native pack `--prefill-until N` does not feed the rest of the prompt through the +token loop (it is skipped for native packs), so the tokens after N are dropped and the model free-runs. Compare +output tokens between paths, never only timings. + **Keeping up with upstream.** A merge of upstream `main` into `b70` leaves the copies in `sycl/` behind wherever upstream touched a file they mirror. They are refreshed by re-migration, not by hand (done for 0.1.25-0.1.27, 2026-09-30): diff --git a/sycl/CMakeLists.txt b/sycl/CMakeLists.txt index 2ab04dda..682a6ed6 100644 --- a/sycl/CMakeLists.txt +++ b/sycl/CMakeLists.txt @@ -44,6 +44,10 @@ endif() # Every kernel was written for 32-lane warps (lane = tid & 31, warp-synchronous reductions). dpct pins the # sub-group size only where it saw a shuffle; the rest would get Xe2's default of 16 and race. Force 32 everywhere. list(APPEND _sycl_flags -fsycl-default-sub-group-size=32) +# One device module per kernel: the first launch of a kernel then loads only its own module. With the default +# split the first launch in the prompt path (the embedding gather) paid 245 ms for the image it shared (2026-09-30). +list(APPEND _sycl_link -fsycl-device-code-split=per_kernel) +list(APPEND _sycl_flags -fsycl-device-code-split=per_kernel) add_compile_options("$<$:${_sycl_flags}>" -fp-model=precise -Wno-unused-parameter -Wno-unused-variable -Wno-deprecated-declarations) add_link_options(${_sycl_link}) @@ -142,6 +146,7 @@ foreach(k IN LISTS _kernel_cu) list(APPEND _kernel_files src/kernels/cuda/${k}.cu) endforeach() strata_resolve(_kernels ${_kernel_files} src/kernels/ngram.cpp src/ngram/ple_reader.cpp src/platform/direct_file.cpp) +list(APPEND _kernels ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cuda/qsa_prompt_attn_xmx.dp.cpp) # port-only: the XMX prompt attention add_library(strata_kernels STATIC ${_kernels}) target_include_directories(strata_kernels PRIVATE ${STRATA_ROOT}/third_party/ggml) target_link_libraries(strata_kernels PUBLIC strata_core) @@ -188,6 +193,8 @@ if(STRATA_SYCL_PARITY) target_link_libraries(kv_hybrid_parity PRIVATE strata_kernels) add_executable(mmvq_bench ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/mmvq_bench.cpp) # dense mmvq timing target_link_libraries(mmvq_bench PRIVATE strata_kernels) + add_executable(xmx_gemm_bench ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/xmx_gemm_bench.cpp) # XMX quantized GEMM vs dequant+oneMKL + target_link_libraries(xmx_gemm_bench PRIVATE strata_kernels strata_prefill) # -qmkl for the oneMKL reference # one native expert three ways on real GGUF rows (ggml reference, CPU path, GPU native_expert_grouped): # native_expert_parity [layer ...] if(STRATA_NATIVE_EXPERTS) diff --git a/sycl/include/strata/core/mtp.hpp b/sycl/include/strata/core/mtp.hpp index 52847e1d..1426a610 100644 --- a/sycl/include/strata/core/mtp.hpp +++ b/sycl/include/strata/core/mtp.hpp @@ -25,6 +25,7 @@ #include "strata/core/session.hpp" #include +#include #include #include @@ -47,6 +48,14 @@ public: void set_prompt_len(int64_t n) { prompt_len_ = n; } /// At most this many drafts per round (below max_t - 1): a window longer than the MTP's comes from elsewhere. void set_max_drafts(int k) { max_drafts_ = k; } + /// SYCL port: capture the round, step and prompt graphs at load rather than on first use (see Verifier::warm) + bool warm(std::string& err) { + for (int T = 1; T <= max_t_; ++T) + if (!capture_round(T, err) || !capture_prefill(T, err)) return false; + for (int j = 1; j < std::min(max_t_ - 1, max_drafts_); ++j) + if (!capture_step(j, err)) return false; + return true; + } uint64_t vram_bytes() const { return vram_; } /// The draft layer's K/V state (read-only: --serve's STRATA_STATE_HASH check hashes it) const QsaState& kv_state() const { return st_; } diff --git a/sycl/include/strata/core/verify.hpp b/sycl/include/strata/core/verify.hpp index dd90e57c..ff53fe58 100644 --- a/sycl/include/strata/core/verify.hpp +++ b/sycl/include/strata/core/verify.hpp @@ -31,6 +31,7 @@ #include "strata/kernels/sampler.hpp" #include +#include #include #include @@ -108,7 +109,13 @@ public: static int64_t handoff_floats(const ModelGeometry& g) { return (int64_t) g.hc * g.n_embd + g.n_embd + g.hc; } /// Keep the first `n_keep` (1..T) tokens of the last window; advances `ss.ple_prev` by them. - bool commit(int n_keep, std::string& err); + /// `wait = false` (SYCL port, single stage only): the commit graph is launched and left running so the drafter's + /// round (its own queue, reads only the window's residuals) overlaps it; `commit_finish()` before the next run. + bool commit(int n_keep, std::string& err, bool wait = true); + bool commit_finish(std::string& err); + /// SYCL port: capture every window graph now (one per window size) instead of on first use, so the first + /// request does not pay for them (a 2,400-node graph takes tens of ms to finalize on this backend). + bool warm(std::string& err); /// Token t's residual after the last layer, (hc, n_embd) on the device, valid until the next `run`. const float* final_R(int t) const; @@ -155,6 +162,8 @@ private: void* next_user_ = nullptr; bool ple_stage() const { return lb_ <= 1 && 1 < le_; } ///< holds layer 1, where the PLE block runs bool capture_commit(std::string& err); + int pending_commit_ = 0; ///< n_keep of a launched, unfinished commit (0: none) + std::chrono::steady_clock::time_point pending_commit_t0_{}; bool record_window(int T, dpct::queue_ptr cs, std::string &err); static constexpr int kProfPer = 32; // stamps per layer bool prof_on_ = false; diff --git a/sycl/include/strata/kernels/qsa_prompt_attn_xmx.hpp b/sycl/include/strata/kernels/qsa_prompt_attn_xmx.hpp new file mode 100644 index 00000000..2536387f --- /dev/null +++ b/sycl/include/strata/kernels/qsa_prompt_attn_xmx.hpp @@ -0,0 +1,11 @@ +// SYCL port: the prompt attention (QSA, selected cells) on XMX joint_matrix - see qsa_prompt_attn_xmx.dp.cpp. +#pragma once +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include +namespace strata::kernels { +/// The same contract as qsa_prompt_attn_batch; returns false (nothing launched) when the shape, pools or device are not +/// handled, so the caller keeps its fallback. Off by default (slower than the fallback): STRATA_PROMPT_ATTN_XMX=1 enables it. +bool qsa_prompt_attn_xmx(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, + const QsaShapes& s, float* attn, int64_t n_q, void* stream); +} diff --git a/sycl/include/strata/kernels/xmx_gemm.hpp b/sycl/include/strata/kernels/xmx_gemm.hpp new file mode 100644 index 00000000..a4b31b94 --- /dev/null +++ b/sycl/include/strata/kernels/xmx_gemm.hpp @@ -0,0 +1,11 @@ +// SYCL port: XMX (joint_matrix) GEMM straight from a ggml-quantized weight matrix - see iq_kernels.dp.cpp. +#pragma once +#include +namespace strata::kernels { +/// Y[M][n_out] (FP32, row stride ldy) = X[M][K] (FP16, row stride K) . W[n_out][K]^T with W's rows quantized as ggml +/// type `ty` (18 IQ3_XXS, 20 IQ4_NL, 21 IQ3_S, 22 IQ2_S, 42 Q2_0). `up` non-null: the gate/up pair, virtual rows +/// interleaved gate/up as iq_dequant_gu_f16 lays them out (n_out = 2 * n_ff). Returns false when the shape or type is +/// not handled (the caller keeps its dequant + oneMKL path). +bool xmx_gemm_iq(int ty, const void* gate, const void* up, int64_t K, int n_out, const uint16_t* X, int M, float* Y, + int64_t ldy, void* stream); +} diff --git a/sycl/src/core/verify.cpp b/sycl/src/core/verify.cpp index ba0c9ca4..67805949 100644 --- a/sycl/src/core/verify.cpp +++ b/sycl/src/core/verify.cpp @@ -1455,9 +1455,10 @@ void Verifier::publish_plan(void* ctx) { *(volatile uint32_t*) v->h_flagA_ = v->cur_layer_ + 1; } -bool Verifier::commit(int n_keep, std::string &err) try { +bool Verifier::commit(int n_keep, std::string &err, bool wait) try { const OnDevice on_device(device_); if (n_keep < 1 || n_keep > last_t_) { err = "verify: commit count out of range"; return false; } + if (pending_commit_ != 0 && !commit_finish(err)) return false; const Clock::time_point t0 = Clock::now(); h_commit_[0] = n_keep; h_commit_[1] = n_keep - 1; @@ -1481,29 +1482,14 @@ bool Verifier::commit(int n_keep, std::string &err) try { dpct::get_error_string_dummy(le); return false; } - const dpct::err0 se = DPCT_CHECK_ERROR(cs_->wait()); - /* - DPCT1009: SYCL reports errors using exceptions and does not use error - codes. Please replace the "get_error_string_dummy(...)" with a real - error-handling function. - */ - /* - DPCT1001: The statement could not be removed. - */ - /* - DPCT1000: Error handling if-stmt was detected but could not be rewritten. - */ - if (se != 0) { - err = - std::string("verify: commit: ") + dpct::get_error_string_dummy(se); - return false; + if (!wait && next_ == nullptr) { // left running: commit_finish() collects it (the drafter overlaps it) + pending_commit_ = n_keep; + pending_commit_t0_ = t0; + return true; } - if (ple_stage()) // stages that share one session must advance it once - for (int t = 0; t < n_keep; ++t) { - ss_->ple_prev[0] = ss_->ple_prev[1]; - ss_->ple_prev[1] = last_tokens_[t]; - } - ms_commit += ms_since(t0); + pending_commit_ = n_keep; + pending_commit_t0_ = t0; + if (!commit_finish(err)) return false; return next_ == nullptr || next_->commit(n_keep, err); } catch (sycl::exception const &exc) { @@ -1512,4 +1498,34 @@ catch (sycl::exception const &exc) { std::exit(1); } +bool Verifier::warm(std::string &err) { + for (int T = 1; T <= max_t_; ++T) + if (!capture(T, err)) return false; + return true; +} + +bool Verifier::commit_finish(std::string &err) try { + if (pending_commit_ == 0) return true; + const OnDevice on_device(device_); + const int n_keep = pending_commit_; + pending_commit_ = 0; + const dpct::err0 se = DPCT_CHECK_ERROR(cs_->wait()); + if (se != 0) { + err = std::string("verify: commit: ") + dpct::get_error_string_dummy(se); + return false; + } + if (ple_stage()) // stages that share one session must advance it once + for (int t = 0; t < n_keep; ++t) { + ss_->ple_prev[0] = ss_->ple_prev[1]; + ss_->ple_prev[1] = last_tokens_[t]; + } + ms_commit += ms_since(pending_commit_t0_); + return true; +} +catch (sycl::exception const &exc) { + std::cerr << exc.what() << "Exception caught at file:" << __FILE__ + << ", line:" << __LINE__ << std::endl; + std::exit(1); +} + } // namespace strata::core diff --git a/sycl/src/kernels/cuda/fused_gr.dp.cpp b/sycl/src/kernels/cuda/fused_gr.dp.cpp index 86375f1d..27b912c6 100644 --- a/sycl/src/kernels/cuda/fused_gr.dp.cpp +++ b/sycl/src/kernels/cuda/fused_gr.dp.cpp @@ -1,5 +1,7 @@ // src/kernels/cuda/fused_gr.cu - see include/strata/kernels/fused_gr.hpp. #define DPCT_PROFILING_ENABLED +#include +#include #include #include #include "strata/sycl_queue.hpp" @@ -19,6 +21,19 @@ constexpr int D = N * HC; // 10240 constexpr int LR = 320; // hc_lr constexpr int THREADS = 256; constexpr int WARPS = THREADS / 32; +#if defined(__HIPCC__) +constexpr int TILE = 1280; // eight-token tile fits gfx1100's 64 KiB LDS limit +#else +constexpr int TILE = 2560; // xn floats per token staged at a time: 320 chunks of 8, 10 per lane +#endif +constexpr int TQ = TILE / 8 / 32; // uint4 weight chunks per lane per tile +// SYCL port: the down kernel's 41 work-groups filled 15% of the B70's threads (metrics 2026-09-30); each row's +// D = 4 tiles are split over DOWN_SPLIT work-groups that write partial sums, summed in a fixed order by the up +// kernel (deterministic, unlike atomics) before the row's nonlinearity. +#ifndef STRATA_GR_DOWN_SPLIT +#define STRATA_GR_DOWN_SPLIT (D / TILE) // 4: one tile per split (1: the unsplit order, for A/B) +#endif +constexpr int DOWN_SPLIT = STRATA_GR_DOWN_SPLIT; constexpr int DOWN_BLOCKS = LR / WARPS; // 40 blocks of 8 rows; one more for the inject rows constexpr int UP_COLS = 32; // columns d per `up` block (x 4 streams = 128 rows) constexpr int UP_BLOCKS = N / UP_COLS; // 80 @@ -134,15 +149,21 @@ auto &xn = *sycl::ext::oneapi::group_local_memory_for_overwrite( if (inject_block && (a.w_inject == nullptr || warp >= HC)) return; const uint16_t* wrow = (inject_block ? a.w_inject : a.w_down) + (size_t) row * D; const sycl::uint4 *w4 = reinterpret_cast(wrow); + // SYCL port: the multi kernel's order - per-tile partial sums for the split rows (gr_parity: bit-identical), + // the inject rows still one accumulation over the whole row (their block is not split there) float acc = 0.0f; + if (inject_block) { #pragma unroll 4 - /* - DPCT1098: The '*' expression is used instead of the __ldg call. These - two expressions do not provide the exact same functionality. Check the - generated code for potential precision and/or performance issues. - */ - for (int j = lane; j < D / 8; j += 32) acc += dot8(*(w4 + j), xn + j * 8); - acc = warp_sum(acc); + for (int j = lane; j < D / 8; j += 32) acc += dot8(*(w4 + j), xn + j * 8); + acc = warp_sum(acc); + } else { + for (int sp = 0; sp < DOWN_SPLIT; ++sp) { + float part = 0.0f; +#pragma unroll 5 + for (int j = lane + sp * (TILE / 8); j < (sp + 1) * (TILE / 8); j += 32) part += dot8(*(w4 + j), xn + j * 8); + acc += warp_sum(part); + } + } if (lane != 0) return; if (inject_block) { a.inject_out[row] = acc; @@ -218,6 +239,7 @@ struct GrMulti { FusedGrArgs a[kFusedGrMaxT]; float* xn; int T; + float* part; ///< [DOWN_SPLIT][kFusedGrMaxT][LR] partial row sums of the down kernel }; // Step 1 of `gr_down_kernel`, one block per token, same threads and reduction order: rs[t] and xn[t] to global. @@ -290,12 +312,6 @@ auto &part = for (int i = t; i < D; i += THREADS) xn[i] *= s_rs[i / N]; } -#if defined(__HIPCC__) -constexpr int TILE = 1280; // eight-token tile fits gfx1100's 64 KiB LDS limit -#else -constexpr int TILE = 2560; // xn floats per token staged at a time: 320 chunks of 8, 10 per lane -#endif -constexpr int TQ = TILE / 8 / 32; // uint4 weight chunks per lane per tile // Step 2 of `gr_down_kernel` for T tokens. One warp per row (so each lane accumulates the same chunks in the // same order as the single-token kernel); per tile the lane's 10 weight chunks are loaded BEFORE the activation @@ -311,15 +327,17 @@ __dpct_inline__ void gr_down_multi_kernel(GrMulti m, uint8_t *dpct_local) { auto tile = (float *)dpct_local; // [T][TILE] const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5; const int T = m.T; - const bool inject_block = item_ct1.get_group(2) == DOWN_BLOCKS; - const int row = inject_block ? warp : item_ct1.get_group(2) * WARPS + warp; + const int gid = (int) item_ct1.get_group(2); + const bool inject_block = gid == DOWN_BLOCKS * DOWN_SPLIT; + const int split = inject_block ? 0 : gid % DOWN_SPLIT, rb = inject_block ? 0 : gid / DOWN_SPLIT; + const int row = inject_block ? warp : rb * WARPS + warp; const bool active = !(inject_block && (m.a[0].w_inject == nullptr || warp >= HC)); const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D; const sycl::uint4 *w4 = reinterpret_cast(wrow); float acc[kFusedGrMaxT]; #pragma unroll for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f; - for (int base = 0; base < D; base += TILE) { + for (int base = inject_block ? 0 : split * TILE; base < D; base += inject_block ? TILE : TILE * DOWN_SPLIT) { sycl::uint4 wv[TQ]; if (active) { #pragma unroll @@ -378,8 +396,7 @@ __dpct_inline__ void gr_down_multi_kernel(GrMulti m, uint8_t *dpct_local) { if (inject_block) { m.a[k].inject_out[row] = s[k]; } else { - const float x = s[k] / (float) HC; - m.a[k].lo[row] = x / (1.0f + sycl::native::exp(-x)); + m.part[((size_t) split * kFusedGrMaxT + k) * LR + row] = s[k]; // the up kernel sums the splits } } } @@ -407,8 +424,16 @@ auto &lo = *sycl::ext::oneapi::group_local_memory_for_overwrite< const int T = m.T; const int d0 = item_ct1.get_group(2) * UPM_COLS; #pragma unroll - for (int i = t; i < T * LR; i += THREADS) - lo[i / LR][i % LR] = m.a[i / LR].lo[i % LR]; + for (int i = t; i < T * LR; i += THREADS) { // the down kernel's partial sums, in split order, then silu + const int k = i / LR, r = i % LR; + float x = 0.0f; +#pragma unroll + for (int sp = 0; sp < DOWN_SPLIT; ++sp) x += m.part[((size_t) sp * kFusedGrMaxT + k) * LR + r]; + x /= (float) HC; + const float v = x / (1.0f + sycl::native::exp(-x)); + lo[k][r] = v; + m.a[k].lo[r] = v; + } /* DPCT1065: Consider replacing sycl::nd_item::barrier() with sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better @@ -478,6 +503,19 @@ auto &lo = *sycl::ext::oneapi::group_local_memory_for_overwrite< } // namespace +// one partials buffer per queue (the verifier's and the drafter's launches never share a queue; within a queue the +// launches are ordered, and a graph capture records the pointer) +static float* down_partials(sycl::queue* q) { + static std::mutex mu; + static std::unordered_map bufs; + std::lock_guard lk(mu); + auto it = bufs.find(q); + if (it != bufs.end()) return it->second; + float* p = sycl::malloc_device((size_t) DOWN_SPLIT * kFusedGrMaxT * LR, *q); + bufs[q] = p; + return p; +} + void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf, int stamp_i0) { if (n_tok < 1 || n_tok > kFusedGrMaxT || xn_scratch == nullptr) { @@ -498,6 +536,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi m.xn = xn_scratch; m.T = n_tok; dpct::queue_ptr st = strata::q_of(stream); + m.part = down_partials(st); { auto exp_props = sycl::ext::oneapi::experimental::properties{ sycl::ext::oneapi::experimental::use_root_sync}; @@ -564,7 +603,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi cgh.parallel_for< dpct_kernel_name>( - sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) * + sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS * DOWN_SPLIT + 1) * sycl::range(1, 1, THREADS), sycl::range(1, 1, THREADS)), exp_props, @@ -583,6 +622,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi c.xn = xn_scratch + (size_t) c0 * D; c.T = ct; for (int k = 0; k < ct; ++k) c.a[k] = a[c0 + k]; + c.part = m.part; { auto exp_props = sycl::ext::oneapi::experimental::properties{ sycl::ext::oneapi::experimental::use_root_sync}; @@ -598,7 +638,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi cgh.parallel_for< dpct_kernel_name>( - sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 1) * + sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS * DOWN_SPLIT + 1) * sycl::range(1, 1, THREADS), sycl::range(1, 1, THREADS)), exp_props, diff --git a/sycl/src/kernels/cuda/iq_kernels.dp.cpp b/sycl/src/kernels/cuda/iq_kernels.dp.cpp index 5a30fe7b..a58d483a 100644 --- a/sycl/src/kernels/cuda/iq_kernels.dp.cpp +++ b/sycl/src/kernels/cuda/iq_kernels.dp.cpp @@ -15,6 +15,9 @@ #define GGML_COMMON_IMPL_SYCL #include "ggml-common.h" +#include +#include +#include #include #include @@ -95,6 +98,29 @@ __dpct_inline__ float vec_dot_q2_0_q8_1(const void *__restrict__ vbq, return d2 * d8 * sumi; } +// SYCL port: ggml's __vcmpne4 / __vsub4 came out of dpct as per-byte loops (extract, compare, insert, x4); on Xe the +// expert dot kernels were ALU-bound with them (77% XVE active, metrics 2026-09-30). SWAR forms of the two uses: +// swar_ne4(x): 0xFF in every byte of x that is non-zero (the sign masks: at most one bit per byte) +// swar_sub4(a, s) with s from swar_ne4: per byte a - s, i.e. a + 1 where the sign byte is set (two's complement +// of the grid value after the xor: the same bits as __vsub4(a, s) for s in {0x00, 0xFF}) +#ifndef STRATA_SWAR +#define STRATA_SWAR 1 // 1: the SWAR forms; 0: dpct's per-byte loops (A/B 2026-09-30: both correct) +#endif +#if STRATA_SWAR +__dpct_inline__ int swar_ne4(unsigned x) { + x = (x | (x >> 4)) & 0x0F0F0F0Fu; + x = (x | (x >> 2)) & 0x03030303u; + x = (x | (x >> 1)) & 0x01010101u; + return (int) (x * 0xFFu); +} +__dpct_inline__ int swar_sub4(unsigned a, unsigned s) { + return (int) (((a & 0x7F7F7F7Fu) + (s & 0x01010101u)) ^ (a & 0x80808080u)); +} +#else +__dpct_inline__ int swar_ne4(unsigned x) { return dpct::vectorized_binary(x, 0, std::not_equal_to<>()); } +__dpct_inline__ int swar_sub4(unsigned a, unsigned s) { return dpct::vectorized_binary(a, s, std::minus<>()); } +#endif + __dpct_inline__ float vec_dot_iq2_xxs_q8_1(const void *__restrict__ vbq, const block_q8_1 *__restrict__ bq8_1, const int &kbx, const int &iqs) { @@ -108,16 +134,12 @@ __dpct_inline__ float vec_dot_iq2_xxs_q8_1(const void *__restrict__ vbq, const sycl::uint2 grid_pos = ((const sycl::uint2 *)iq2xxs_grid)[aux8[k0 / 2]]; const uint32_t signs = unpack_ksigns(aux32 >> (7 * k0 / 2)); - const int signs0 = dpct::vectorized_binary( - signs & 0x08040201, 0, std::not_equal_to<>()); - const int grid0 = dpct::vectorized_binary( - grid_pos.x() ^ signs0, signs0, std::minus<>()); + const int signs0 = swar_ne4(signs & 0x08040201); + const int grid0 = swar_sub4(grid_pos.x() ^ signs0, signs0); const int u0 = get_int_b4(bq8_1[iqs / 2].qs, k0 + 0); sumi = ggml_cuda_dp4a(grid0, u0, sumi); - const int signs1 = dpct::vectorized_binary( - signs & 0x80402010, 0, std::not_equal_to<>()); - const int grid1 = dpct::vectorized_binary( - grid_pos.y() ^ signs1, signs1, std::minus<>()); + const int signs1 = swar_ne4(signs & 0x80402010); + const int grid1 = swar_sub4(grid_pos.y() ^ signs1, signs1); const int u1 = get_int_b4(bq8_1[iqs / 2].qs, k0 + 1); sumi = ggml_cuda_dp4a(grid1, u1, sumi); } @@ -144,15 +166,11 @@ __dpct_inline__ float vec_dot_iq2_xs_q8_1(const void *__restrict__ vbq, const sycl::uint2 grid_pos = ((const sycl::uint2 *)iq2xs_grid)[q2[l0 / 2] & 0x1FF]; const uint32_t signs = unpack_ksigns(q2[l0 / 2] >> 9); - const int signs0 = dpct::vectorized_binary( - signs & 0x08040201, 0, std::not_equal_to<>()); - const int grid_l = dpct::vectorized_binary( - grid_pos.x() ^ signs0, signs0, std::minus<>()); + const int signs0 = swar_ne4(signs & 0x08040201); + const int grid_l = swar_sub4(grid_pos.x() ^ signs0, signs0); const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); - const int signs1 = dpct::vectorized_binary( - signs & 0x80402010, 0, std::not_equal_to<>()); - const int grid_h = dpct::vectorized_binary( - grid_pos.y() ^ signs1, signs1, std::minus<>()); + const int signs1 = swar_ne4(signs & 0x80402010); + const int grid_h = swar_sub4(grid_pos.y() ^ signs1, signs1); const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); if (l0 < 4) { sumi0 = ggml_cuda_dp4a(grid_l, u0, sumi0); @@ -184,18 +202,12 @@ __dpct_inline__ float vec_dot_iq2_s_q8_1(const void *__restrict__ vbq, #pragma unroll for (int l0 = 0; l0 < 8; l0 += 2) { const int* grid_pos = (const int*) (iq2s_grid + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300))); - const int signs0 = dpct::vectorized_binary( - ((signs_packed_8[l0 / 2] & 0x03) << 7) | - ((signs_packed_8[l0 / 2] & 0x0C) << 21), - 0x00000000, std::not_equal_to<>()); - const int signs1 = dpct::vectorized_binary( - ((signs_packed_8[l0 / 2] & 0x30) << 3) | - ((signs_packed_8[l0 / 2] & 0xC0) << 17), - 0x00000000, std::not_equal_to<>()); - const int grid_l = dpct::vectorized_binary( - grid_pos[0] ^ signs0, signs0, std::minus<>()); - const int grid_h = dpct::vectorized_binary( - grid_pos[1] ^ signs1, signs1, std::minus<>()); + const int signs0 = swar_ne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | + ((signs_packed_8[l0 / 2] & 0x0C) << 21)); + const int signs1 = swar_ne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | + ((signs_packed_8[l0 / 2] & 0xC0) << 17)); + const int grid_l = swar_sub4(grid_pos[0] ^ signs0, signs0); + const int grid_h = swar_sub4(grid_pos[1] ^ signs1, signs1); const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); if (l0 < 4) { @@ -227,15 +239,11 @@ __dpct_inline__ float vec_dot_iq3_xxs_q8_1(const void *__restrict__ vbq, const sycl::int2 grid_pos = sycl::int2(iq3xxs_grid[q3[l0 + 0]], iq3xxs_grid[q3[l0 + 1]]); const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2)); - const int signs0 = dpct::vectorized_binary( - signs & 0x08040201, 0, std::not_equal_to<>()); - const int grid_l = dpct::vectorized_binary( - grid_pos.x() ^ signs0, signs0, std::minus<>()); + const int signs0 = swar_ne4(signs & 0x08040201); + const int grid_l = swar_sub4(grid_pos.x() ^ signs0, signs0); const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); - const int signs1 = dpct::vectorized_binary( - signs & 0x80402010, 0, std::not_equal_to<>()); - const int grid_h = dpct::vectorized_binary( - grid_pos.y() ^ signs1, signs1, std::minus<>()); + const int signs1 = swar_ne4(signs & 0x80402010); + const int grid_h = swar_sub4(grid_pos.y() ^ signs1, signs1); const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); sumi = ggml_cuda_dp4a(grid_l, u0, sumi); sumi = ggml_cuda_dp4a(grid_h, u1, sumi); @@ -264,18 +272,12 @@ __dpct_inline__ float vec_dot_iq3_s_q8_1(const void *__restrict__ vbq, const sycl::int2 grid_pos = sycl::int2(iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)], iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]); - const int signs0 = dpct::vectorized_binary( - ((signs_packed_8[l0 / 2] & 0x03) << 7) | - ((signs_packed_8[l0 / 2] & 0x0C) << 21), - 0x00000000, std::not_equal_to<>()); - const int signs1 = dpct::vectorized_binary( - ((signs_packed_8[l0 / 2] & 0x30) << 3) | - ((signs_packed_8[l0 / 2] & 0xC0) << 17), - 0x00000000, std::not_equal_to<>()); - const int grid_l = dpct::vectorized_binary( - grid_pos.x() ^ signs0, signs0, std::minus<>()); - const int grid_h = dpct::vectorized_binary( - grid_pos.y() ^ signs1, signs1, std::minus<>()); + const int signs0 = swar_ne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | + ((signs_packed_8[l0 / 2] & 0x0C) << 21)); + const int signs1 = swar_ne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | + ((signs_packed_8[l0 / 2] & 0xC0) << 17)); + const int grid_l = swar_sub4(grid_pos.x() ^ signs0, signs0); + const int grid_h = swar_sub4(grid_pos.y() ^ signs1, signs1); const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); sumi = ggml_cuda_dp4a(grid_l, u0, sumi); @@ -370,7 +372,8 @@ __dpct_inline__ float vec_dot_iq4_xs_q8_1(const void *__restrict__ vbq, // ---------------------------------------------------------------- the formats // qk = values per block, ipb = dot calls per block (qi / vdr), step = the iqs stride between calls. -template struct Fmt; +template +struct Fmt; template<> struct Fmt<16> { static constexpr int qk = 256, ipb = 8, step = 2; static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq2_xxs_q8_1(v, y, kbx, iqs); } }; template<> struct Fmt<17> { static constexpr int qk = 256, ipb = 8, step = 2; @@ -489,10 +492,10 @@ template <> struct Multi<18> { // iq3_xxs for (int l0 = 0; l0 < 8; l0 += 2) { const sycl::int2 grid_pos = sycl::int2(iq3xxs_grid[q3[l0 + 0]], iq3xxs_grid[q3[l0 + 1]]); const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2)); - const int signs0 = dpct::vectorized_binary(signs & 0x08040201, 0, std::not_equal_to<>()); - const int signs1 = dpct::vectorized_binary(signs & 0x80402010, 0, std::not_equal_to<>()); - m.w[l0 + 0] = dpct::vectorized_binary(grid_pos.x() ^ signs0, signs0, std::minus<>()); - m.w[l0 + 1] = dpct::vectorized_binary(grid_pos.y() ^ signs1, signs1, std::minus<>()); + const int signs0 = swar_ne4(signs & 0x08040201); + const int signs1 = swar_ne4(signs & 0x80402010); + m.w[l0 + 0] = swar_sub4(grid_pos.x() ^ signs0, signs0); + m.w[l0 + 1] = swar_sub4(grid_pos.y() ^ signs1, signs1); } m.a = (int) (aux32 >> 28); m.d = sycl::vec(bq3->d).convert()[0]; @@ -520,10 +523,10 @@ template <> struct Multi<22> { // iq2_s #pragma unroll for (int l0 = 0; l0 < 8; l0 += 2) { const int* grid_pos = (const int*) (iq2s_grid + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300))); - const int signs0 = dpct::vectorized_binary(((sp[l0 / 2] & 0x03) << 7) | ((sp[l0 / 2] & 0x0C) << 21), 0, std::not_equal_to<>()); - const int signs1 = dpct::vectorized_binary(((sp[l0 / 2] & 0x30) << 3) | ((sp[l0 / 2] & 0xC0) << 17), 0, std::not_equal_to<>()); - m.w[l0 + 0] = dpct::vectorized_binary(grid_pos[0] ^ signs0, signs0, std::minus<>()); - m.w[l0 + 1] = dpct::vectorized_binary(grid_pos[1] ^ signs1, signs1, std::minus<>()); + const int signs0 = swar_ne4(((sp[l0 / 2] & 0x03) << 7) | ((sp[l0 / 2] & 0x0C) << 21)); + const int signs1 = swar_ne4(((sp[l0 / 2] & 0x30) << 3) | ((sp[l0 / 2] & 0xC0) << 17)); + m.w[l0 + 0] = swar_sub4(grid_pos[0] ^ signs0, signs0); + m.w[l0 + 1] = swar_sub4(grid_pos[1] ^ signs1, signs1); } m.a = bq2->scales[iqs / 2] & 0x0F; m.b = bq2->scales[iqs / 2] >> 4; @@ -552,10 +555,10 @@ template <> struct Multi<21> { // iq3_s for (int l0 = 0; l0 < 8; l0 += 2) { const sycl::int2 grid_pos = sycl::int2(iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)], iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]); - const int signs0 = dpct::vectorized_binary(((sp[l0 / 2] & 0x03) << 7) | ((sp[l0 / 2] & 0x0C) << 21), 0, std::not_equal_to<>()); - const int signs1 = dpct::vectorized_binary(((sp[l0 / 2] & 0x30) << 3) | ((sp[l0 / 2] & 0xC0) << 17), 0, std::not_equal_to<>()); - m.w[l0 + 0] = dpct::vectorized_binary(grid_pos.x() ^ signs0, signs0, std::minus<>()); - m.w[l0 + 1] = dpct::vectorized_binary(grid_pos.y() ^ signs1, signs1, std::minus<>()); + const int signs0 = swar_ne4(((sp[l0 / 2] & 0x03) << 7) | ((sp[l0 / 2] & 0x0C) << 21)); + const int signs1 = swar_ne4(((sp[l0 / 2] & 0x30) << 3) | ((sp[l0 / 2] & 0xC0) << 17)); + m.w[l0 + 0] = swar_sub4(grid_pos.x() ^ signs0, signs0); + m.w[l0 + 1] = swar_sub4(grid_pos.y() ^ signs1, signs1); } m.a = 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F); m.d = sycl::vec(bq3->d).convert()[0]; @@ -802,6 +805,21 @@ __dpct_inline__ sycl::half cvt(float v) { .convert()[0]; } +// SYCL port: the dequant functions below wrote one 2-byte value at a time (dq_* = llama.cpp's per-thread loops); on Xe +// the FP16 expert dequant ran at ~80 GB/s of writes, 40% of the prompt path. Each thread's run of values goes out as one +// vector store instead (the offsets are multiples of the run length, so the stores are aligned). +template +__dpct_inline__ void store_run(dst_t* y, const float* v) { + if constexpr (std::is_same_v && (N == 4 || N == 8)) { + sycl::vec h; +#pragma unroll + for (int j = 0; j < N; ++j) h[j] = sycl::half(v[j]); + *reinterpret_cast*>(y) = h; + } else { +#pragma unroll + for (int j = 0; j < N; ++j) y[j] = cvt(v[j]); + } +} template inline void dq_iq2_xxs(const void *vx, int64_t ibs, dst_t *yy, int tid) { const block_iq2_xxs* x = (const block_iq2_xxs*) vx; @@ -813,9 +831,10 @@ inline void dq_iq2_xxs(const void *vx, int64_t ibs, dst_t *yy, int tid) { const uint32_t aux32 = q2[2] | (q2[3] << 16); const float d = (float) x[ibs].d * (0.5f + (aux32 >> 28)) * 0.25f; const uint8_t signs = ksigns_iq2xs[(aux32 >> 7 * il) & 127]; + float v[8]; #pragma unroll - for (int j = 0; j < 8; ++j) - y[j] = cvt(d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f)); + for (int j = 0; j < 8; ++j) v[j] = d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f); + store_run(y, v); } template inline void dq_iq2_xs(const void *vx, int64_t ibs, dst_t *yy, int tid) { @@ -826,9 +845,10 @@ inline void dq_iq2_xs(const void *vx, int64_t ibs, dst_t *yy, int tid) { const uint8_t* grid = (const uint8_t*) (iq2xs_grid + (q2[il] & 511)); const float d = (float) x[ibs].d * (0.5f + ((x[ibs].scales[ib] >> 4 * (il / 2)) & 0xf)) * 0.25f; const uint8_t signs = ksigns_iq2xs[q2[il] >> 9]; + float v[8]; #pragma unroll - for (int j = 0; j < 8; ++j) - y[j] = cvt(d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f)); + for (int j = 0; j < 8; ++j) v[j] = d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f); + store_run(y, v); } template inline void dq_iq2_s(const void *vx, int64_t ibs, dst_t *yy, int tid) { @@ -838,9 +858,10 @@ inline void dq_iq2_s(const void *vx, int64_t ibs, dst_t *yy, int tid) { const uint8_t* grid = (const uint8_t*) (iq2s_grid + (x[ibs].qs[4 * ib + il] | ((x[ibs].qh[ib] << (8 - 2 * il)) & 0x300))); const float d = (float) x[ibs].d * (0.5f + ((x[ibs].scales[ib] >> 4 * (il / 2)) & 0xf)) * 0.25f; const uint8_t signs = x[ibs].qs[QK_K / 8 + 4 * ib + il]; + float v[8]; #pragma unroll - for (int j = 0; j < 8; ++j) - y[j] = cvt(d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f)); + for (int j = 0; j < 8; ++j) v[j] = d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f); + store_run(y, v); } template inline void dq_iq3_xxs(const void *vx, int64_t ibs, dst_t *yy, int tid) { @@ -854,11 +875,13 @@ inline void dq_iq3_xxs(const void *vx, int64_t ibs, dst_t *yy, int tid) { const uint32_t aux32 = gas[0] | (gas[1] << 16); const float d = (float) x[ibs].d * (0.5f + (aux32 >> 28)) * 0.5f; const uint8_t signs = ksigns_iq2xs[(aux32 >> 7 * il) & 127]; + float v[8]; #pragma unroll for (int j = 0; j < 4; ++j) { - y[j + 0] = cvt(d * grid1[j] * (signs & kmask_iq2xs[j + 0] ? -1.f : 1.f)); - y[j + 4] = cvt(d * grid2[j] * (signs & kmask_iq2xs[j + 4] ? -1.f : 1.f)); + v[j + 0] = d * grid1[j] * (signs & kmask_iq2xs[j + 0] ? -1.f : 1.f); + v[j + 4] = d * grid2[j] * (signs & kmask_iq2xs[j + 4] ? -1.f : 1.f); } + store_run(y, v); } template inline void dq_iq3_s(const void *vx, int64_t ibs, dst_t *yy, int tid) { @@ -870,11 +893,13 @@ inline void dq_iq3_s(const void *vx, int64_t ibs, dst_t *yy, int tid) { const uint8_t* grid2 = (const uint8_t*) (iq3s_grid + (qs[2 * il + 1] | ((x[ibs].qh[ib] << (7 - 2 * il)) & 256))); const float d = (float) x[ibs].d * (1 + 2 * ((x[ibs].scales[ib / 2] >> 4 * (ib % 2)) & 0xf)); const uint8_t signs = x[ibs].signs[4 * ib + il]; + float v[8]; #pragma unroll for (int j = 0; j < 4; ++j) { - y[j + 0] = cvt(d * grid1[j] * (signs & kmask_iq2xs[j + 0] ? -1.f : 1.f)); - y[j + 4] = cvt(d * grid2[j] * (signs & kmask_iq2xs[j + 4] ? -1.f : 1.f)); + v[j + 0] = d * grid1[j] * (signs & kmask_iq2xs[j + 0] ? -1.f : 1.f); + v[j + 4] = d * grid2[j] * (signs & kmask_iq2xs[j + 4] ? -1.f : 1.f); } + store_run(y, v); } template inline void dq_iq1_m(const void *vx, int64_t ibs, dst_t *yy, int tid) { @@ -902,11 +927,14 @@ inline void dq_iq4_nl(const void *vx, int64_t ibs, dst_t *yy, int tid) { dst_t* y = yy + 32 * ib + 4 * il; const uint8_t* q4 = x[ib].qs + 4 * il; const float d = (float) x[ib].d; + float lo[4], hi[4]; #pragma unroll for (int j = 0; j < 4; ++j) { - y[j + 0] = cvt(d * kvalues_iq4nl[q4[j] & 0xf]); - y[j + 16] = cvt(d * kvalues_iq4nl[q4[j] >> 4]); + lo[j] = d * kvalues_iq4nl[q4[j] & 0xf]; + hi[j] = d * kvalues_iq4nl[q4[j] >> 4]; } + store_run(y, lo); + store_run(y + 16, hi); } // Q3_K (the Q2_0 file's token_embd): llama.cpp's dequantize_block_q3_K, its 64 threads folded onto 32 template @@ -939,11 +967,14 @@ inline void dq_iq4_xs(const void *vx, int64_t ibs, dst_t *yy, int tid) { dst_t* y = yy + 32 * ib + 4 * il; const uint8_t* q4 = x->qs + 16 * ib + 4 * il; const float d = (float) x->d * ((((x->scales_l[ib / 2] >> 4 * (ib % 2)) & 0xf) | (((x->scales_h >> 2 * ib) & 3) << 4)) - 32); + float lo[4], hi[4]; #pragma unroll for (int j = 0; j < 4; ++j) { - y[j + 0] = cvt(d * kvalues_iq4nl[q4[j] & 0xf]); - y[j + 16] = cvt(d * kvalues_iq4nl[q4[j] >> 4]); + lo[j] = d * kvalues_iq4nl[q4[j] & 0xf]; + hi[j] = d * kvalues_iq4nl[q4[j] >> 4]; } + store_run(y, lo); + store_run(y + 16, hi); } template inline void dq_q2_0(const void *vx, int64_t ibs, dst_t *yy, int tid) { @@ -951,11 +982,14 @@ inline void dq_q2_0(const void *vx, int64_t ibs, dst_t *yy, int tid) { const block_q2_0* x = (const block_q2_0*) vx + ibs * 4; const int b = tid / 8, part = tid % 8; // block 0..3, 8 values each const float d = (float) x[b].d; + float v[8]; +#pragma unroll for (int j = 0; j < 8; ++j) { const int i = part * 8 + j; const int code = (x[b].qs[i / 4] >> ((i % 4) * 2)) & 3; - yy[b * 64 + i] = cvt(d * (float) (code - 1)); + v[j] = d * (float) (code - 1); } + store_run(yy + b * 64 + part * 8, v); } template @@ -1649,4 +1683,160 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long check("native_expert_grouped/down"); } + +// ================================================================ SYCL port: XMX GEMM straight from the quantized rows +// +// The prompt path dequantizes every routed expert to FP16 (8 MB written, then read back by oneMKL) before its GEMMs: +// 39-41% of the prompt time on the B70 (2026-09-30), the GEMMs themselves another 16%. This kernel dequantizes a +// 16-feature strip of the weight matrix into local memory, packs it for the XMX B operand and multiplies it against +// every activation row with joint_matrix (16x16x16, FP16 in, FP32 out; sub-group 16 as XMX wants). The FP16 weights +// never touch global memory. +// +// Y[M][n_out] = X[M][K] . W[n_out][K]^T X FP16 row-major (lda K), Y FP32 (ldy), W quantized rows (a ggml IQ type) +// +// Gate/up: `up != nullptr`, virtual row 2r = gate row r, 2r+1 = up row r (the order iq_dequant_gu_f16 produces, which +// swiglu_interleaved expects). K must be a multiple of 256 (a QK_K block per slab) or the whole row must fit a slab +// (K = 640: 16 rows are 40 blocks, block-aligned since 16 * 640 / 256 = 40). +namespace xmx { +namespace jm = sycl::ext::oneapi::experimental::matrix; +constexpr int SG = 16; // XMX sub-group size +constexpr int NSG = 8; // sub-groups per work-group +constexpr int WG = SG * NSG; +constexpr int NT = 16; // features per work-group: one B tile +constexpr int MAXT = 4; // C tiles per sub-group -> 512 rows per chunk +constexpr int APAD = 8; // halves of padding on the staged A tile rows +struct Src { const uint8_t* gate; const uint8_t* up; int ty; int64_t per_row; }; +struct Smem { sycl::half* stage; sycl::half* packed; sycl::half* atile; float* ctile; }; + +// the block index (x[ibs] in dq_dispatch) of virtual row v's k-range [k0, k0 + 256) - rows are per_row blocks long +__dpct_inline__ const void* block_of(const Src& s, int v, int cblk, int64_t& ibs) { + if (s.up != nullptr) { ibs = (int64_t) (v >> 1) * s.per_row + cblk; return (v & 1) ? s.up : s.gate; } + ibs = (int64_t) v * s.per_row + cblk; + return s.gate; +} + +// one work-group: features [f0, f0 + 16) of the weight matrix against all M rows; slab_k halves of K per pass +void gemm_kernel(Src src, const sycl::half* X, int K, int slab_k, float* Y, int64_t ldy, int M, int n_out, Smem sm) { + auto it = sycl::ext::oneapi::this_work_item::get_nd_item<3>(); + auto sg = it.get_sub_group(); + const int sgid = (int) sg.get_group_id()[0], lane = (int) sg.get_local_id()[0], t = (int) it.get_local_id(2); + const int f0 = (int) it.get_group(2) * NT; + const int per_slab = slab_k / 256; // blocks of one row per slab (K % 256 == 0), or + const int whole = (slab_k == K) ? 1 : 0; // the whole 16-row strip as NT * K / 256 flat blocks + const int nblk = whole ? NT * K / 256 : NT * per_slab; + auto gptr = [](auto* p) { return sycl::address_space_cast(p); }; + auto lptr = [](auto* p) { return sycl::address_space_cast(p); }; + sycl::half* atile = sm.atile + (size_t) sgid * 16 * (16 + APAD); + float* ctile = sm.ctile + (size_t) sgid * 256; + for (int m_base = 0; m_base < M; m_base += MAXT * NSG * 16) { + jm::joint_matrix C[MAXT]; +#pragma unroll + for (int k = 0; k < MAXT; ++k) jm::joint_matrix_fill(sg, C[k], 0.0f); + const int tiles = std::min((M - m_base + 15) / 16, MAXT * NSG); + for (int k0 = 0; k0 < K; k0 += slab_k) { + it.barrier(sycl::access::fence_space::local_space); + // dequantize the strip's blocks of this slab into stage[NT][slab_k] (flat, row-major): 32 "threads" per + // block in dq_dispatch's terms, two calls per lane + for (int b = sgid; b < nblk; b += NSG) { + int v, kk; + if (whole) { v = (b * 256) / K; kk = (b * 256) % K; } + else { v = b / per_slab; kk = (b % per_slab) * 256; } + sycl::half* dst = sm.stage + (size_t) v * slab_k + kk; + const int row = f0 + v; + if (row < n_out) { + int64_t ibs; + const void* blk = src.gate; + if (whole) ibs = ((int64_t) f0 * K) / 256 + b; // flat blocks of the [n_out][K] matrix + else blk = block_of(src, row, k0 / 256 + b % per_slab, ibs); + dq_dispatch(src.ty, blk, ibs, dst, lane); + dq_dispatch(src.ty, blk, ibs, dst, lane + 16); + } else { + for (int i = lane; i < 256; i += SG) dst[i] = sycl::half(0.0f); + } + } + it.barrier(sycl::access::fence_space::local_space); + // pack for the XMX B operand: element (k, n) at packed[(k / 2) * (NT * 2) + n * 2 + (k & 1)] + for (int i = t; i < NT * slab_k; i += WG) { + const int n = i / slab_k, k = i - n * slab_k; + sm.packed[(k >> 1) * (NT * 2) + n * 2 + (k & 1)] = sm.stage[i]; + } + it.barrier(sycl::access::fence_space::local_space); + for (int ks = 0; ks < slab_k; ks += 16) { + jm::joint_matrix B; + jm::joint_matrix_load(sg, B, lptr(sm.packed + (ks >> 1) * (NT * 2)), NT * 2); +#pragma unroll + for (int tt = 0; tt < MAXT; ++tt) { + const int tile = sgid + tt * NSG; + if (tile >= tiles) break; + const int m0 = m_base + tile * 16; + jm::joint_matrix A; + if (m0 + 16 <= M) { + jm::joint_matrix_load(sg, A, gptr(X + (size_t) m0 * K + k0 + ks), (size_t) K); + } else { // the tail tile: valid rows staged, the rest zero + for (int i = lane; i < 16 * 16; i += SG) { + const int r = i >> 4, c = i & 15; + atile[r * (16 + APAD) + c] = (m0 + r < M) ? X[(size_t) (m0 + r) * K + k0 + ks + c] : sycl::half(0.0f); + } + sycl::group_barrier(sg); + jm::joint_matrix_load(sg, A, lptr(atile), (size_t) (16 + APAD)); + sycl::group_barrier(sg); + } + jm::joint_matrix_mad(sg, C[tt], A, B, C[tt]); + } + } + } + // the chunk's results +#pragma unroll + for (int tt = 0; tt < MAXT; ++tt) { + const int tile = sgid + tt * NSG; + if (tile >= tiles) break; + const int m0 = m_base + tile * 16; + if (m0 + 16 <= M && f0 + NT <= n_out) { + jm::joint_matrix_store(sg, C[tt], gptr(Y + (size_t) m0 * ldy + f0), (size_t) ldy, jm::layout::row_major); + } else { + jm::joint_matrix_store(sg, C[tt], lptr(ctile), (size_t) 16, jm::layout::row_major); + sycl::group_barrier(sg); + for (int i = lane; i < 256; i += SG) { + const int r = i >> 4, c = i & 15; + if (m0 + r < M && f0 + c < n_out) Y[(size_t) (m0 + r) * ldy + f0 + c] = ctile[i]; + } + sycl::group_barrier(sg); + } + } + } +} +} // namespace xmx + +bool xmx_gemm_iq(int ty, const void* gate, const void* up, int64_t K, int n_out, const uint16_t* X, int M, float* Y, + int64_t ldy, void* stream) { + if (!is_iq(ty) || ty == 16 || ty == 17 || ty == 29 || ty == 23 || ty == 11) return false; // dq_dispatch covers these; the rest untested here + if (M <= 0 || n_out <= 0 || n_out % xmx::NT != 0 || K <= 0) return false; + const bool by_block = (K % 256) == 0; + const bool whole = !by_block && ((int64_t) xmx::NT * K) % 256 == 0 && K % 16 == 0; + if (!by_block && !whole) return false; + const int slab_k = by_block ? 256 : (int) K; + if (up != nullptr && !by_block) return false; // gate/up rows are per_row blocks each + const size_t stage_halves = (size_t) xmx::NT * slab_k; + const size_t bytes = stage_halves * 2 /*stage*/ + stage_halves * 2 /*packed*/ + (size_t) xmx::NSG * 16 * (16 + xmx::APAD) * 2 + + (size_t) xmx::NSG * 256 * 4; + if (bytes > 96 * 1024) return false; + dpct::queue_ptr q = strata::q_of(stream); + xmx::Src src{(const uint8_t*) gate, (const uint8_t*) up, ty, by_block ? K / 256 : 0}; + const int groups = n_out / xmx::NT; + q->submit([&](sycl::handler& cgh) { + sycl::local_accessor slm(sycl::range<1>(bytes), cgh); + cgh.parallel_for( + sycl::nd_range<3>(sycl::range<3>(1, 1, (size_t) groups * xmx::WG), sycl::range<3>(1, 1, xmx::WG)), + [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(16)]] { + uint8_t* base = slm.get_multi_ptr().get(); + xmx::Smem sm; + sm.stage = (sycl::half*) base; + sm.packed = sm.stage + stage_halves; + sm.atile = sm.packed + stage_halves; + sm.ctile = (float*) (sm.atile + (size_t) xmx::NSG * 16 * (16 + xmx::APAD)); + xmx::gemm_kernel(src, (const sycl::half*) X, (int) K, slab_k, Y, ldy, M, n_out, sm); + }); + }); + return true; +} } // namespace strata::kernels diff --git a/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp b/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp index 1f38376b..dd9d1985 100644 --- a/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp +++ b/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp @@ -4,6 +4,7 @@ #include #include "strata/sycl_queue.hpp" #include "strata/kernels/qsa_prompt_attn.hpp" +#include "strata/kernels/qsa_prompt_attn_xmx.hpp" #include "strata/kernels/kv_q8.hpp" #include "strata/kernels/kv_q4.hpp" @@ -1186,7 +1187,9 @@ bool qsa_prompt_attn_batch(const float *q, const QsaAttnPools &pools, cc_major[dev] = major; } (void) cc_major[dev]; - return false; // SYCL: the tensor-core kernel is not ported yet; the caller takes the older kernel + // SYCL: the mma.sync kernel below is not ported; its XMX port takes the same arguments + if (qsa_prompt_attn_xmx(q, pools, ids, steps, cap, s, attn, n_q, stream)) return true; + return false; // the caller takes the older kernel } #if defined(__HIPCC__) return false; // the tensor-core kernel is compiled out on AMD (its major version is not a CUDA sm) diff --git a/sycl/src/kernels/cuda/qsa_prompt_attn_xmx.dp.cpp b/sycl/src/kernels/cuda/qsa_prompt_attn_xmx.dp.cpp new file mode 100644 index 00000000..9d3aa4df --- /dev/null +++ b/sycl/src/kernels/cuda/qsa_prompt_attn_xmx.dp.cpp @@ -0,0 +1,357 @@ +// SYCL port: the prompt attention on XMX (joint_matrix) - the port of qsa_prompt_attn.cu's tensor-core kernel. +// +// One work-group per (query position, KV head): 16 query rows (the 12 heads of the group, 4 zero rows) against the +// position's selected cells, 16 cells per chunk. Scores S = Q K^T and the update O += P V run on joint_matrix +// (FP16 x FP16 -> FP32, 16x16x16, sub-group 16); Q and P are split into hi + lo FP16 halves exactly as the CUDA kernel +// does, and the per-64-dim INT8 scales of K and V are applied outside the matrix products the same way (K's after the +// group's product, V's folded into P). The online softmax and the accumulator merge are scalar over local memory. +// KV modes: 0 FP16 K/V, 1 INT8 K/V with scales, 3 INT8 K + q4_0 V dequantized to FP16. +#include "strata/kernels/qsa_prompt_attn_xmx.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/kv_q8.hpp" +#include "strata/sycl_queue.hpp" +#include +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { +namespace jm = sycl::ext::oneapi::experimental::matrix; +constexpr int HD = 256, G = 12, CH = 16, SG = 16, NSG = 8, THREADS = SG * NSG, QS = HD + 8, PS = CH + 8; +constexpr int QK4_0 = 32; +struct q4_0_block { uint16_t d; uint8_t qs[QK4_0 / 2]; }; + +struct Smem { + sycl::half* qh; // [16][QS] + sycl::half* ql; // [16][QS] + sycl::half* kp; // packed K^T: (k/2)*(CH*2) + c*2 + (k&1), k < HD, c < CH + sycl::half* vp; // packed V: (c/2)*(HD*2) + d*2 + (c&1) + sycl::half* pv; // [4 groups][2 hi/lo][16][PS] P tiles + float* ks; // [CH][4] + float* vs; // [CH][4] + float* s; // [16][PS] scores, then probabilities + float* acc; // [16][HD] + float* tmp; // [NSG][16][16] + float* misc; // qmax[8], mrow[16], lsum[16], alpha[16], vup[4], vdown[4] + long long* row; // [CH] +}; +constexpr size_t kSmemBytes = (size_t) 2 * 16 * QS * 2 + (size_t) 2 * CH * HD * 2 + (size_t) 4 * 2 * 16 * PS * 2 + + (size_t) 2 * CH * 4 * 4 + (size_t) 16 * PS * 4 + (size_t) 16 * HD * 4 + (size_t) NSG * 256 * 4 + + (size_t) 72 * 4 + (size_t) CH * 8 + 64; + +__dpct_inline__ Smem carve(uint8_t* base) { + Smem m; + uint8_t* p = base; + auto take = [&](size_t bytes) { uint8_t* r = p; p += (bytes + 15) & ~(size_t) 15; return r; }; + m.qh = (sycl::half*) take(16 * QS * 2); + m.ql = (sycl::half*) take(16 * QS * 2); + m.kp = (sycl::half*) take((size_t) CH * HD * 2); + m.vp = (sycl::half*) take((size_t) CH * HD * 2); + m.pv = (sycl::half*) take((size_t) 4 * 2 * 16 * PS * 2); + m.ks = (float*) take(CH * 4 * 4); + m.vs = (float*) take(CH * 4 * 4); + m.s = (float*) take(16 * PS * 4); + m.acc = (float*) take((size_t) 16 * HD * 4); + m.tmp = (float*) take((size_t) NSG * 256 * 4); + m.misc = (float*) take(72 * 4); + m.row = (long long*) take(CH * 8); + return m; +} + +template +__dpct_inline__ auto lptr(T* p) { + return sycl::address_space_cast(p); +} + +__dpct_inline__ float sg_max(sycl::sub_group sg, float v) { + return sycl::reduce_over_group(sg, v, sycl::maximum()); +} + +template +void prompt_attn_xmx_kernel(const float* __restrict__ q, QsaAttnPools p, const int32_t* __restrict__ ids, + const int32_t* __restrict__ steps, int n_kv_heads, int page_size, float scale_log2, + float* __restrict__ attn, int cap, uint8_t* smem) { + auto it = sycl::ext::oneapi::this_work_item::get_nd_item<3>(); + auto sg = it.get_sub_group(); + Smem S = carve(smem); + const int qi = (int) it.get_group(2), kvh = (int) it.get_group(1); + const int n_head = n_kv_heads * G; + q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; + attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD; + ids += (size_t) qi * cap; + const int n = steps[(size_t) qi * kStepCount + kStepWidth]; + const int t = (int) it.get_local_id(2), lane = (int) sg.get_local_id()[0], sgid = (int) sg.get_group_id()[0]; + float* qmax = S.misc; + float* mrow = S.misc + 8; + float* lsum = S.misc + 24; + float* alpha = S.misc + 40; + float* vup = S.misc + 56; + float* vdown = S.misc + 60; + // q: 12 heads + 4 zero rows, scaled so its largest value sits near 2^14 (exact), split into hi + lo halves + float qm = 0.0f; + for (int i = t; i < G * HD; i += THREADS) qm = sycl::fmax(qm, sycl::fabs(q[i])); + qm = sg_max(sg, qm); + if (lane == 0) qmax[sgid] = qm; + it.barrier(sycl::access::fence_space::local_space); + qm = 0.0f; + for (int i = 0; i < NSG; ++i) qm = sycl::fmax(qm, qmax[i]); + int qe = 0; // frexp's exponent (qm < 2^qe) from the float's bits: normal numbers only, qm > 0 is + if (qm > 0.0f) qe = (int) ((sycl::bit_cast(qm) >> 23) & 0xFFu) - 126; + const float qup = sycl::ldexp(1.0f, 14 - qe), qdown = sycl::ldexp(scale_log2, qe - 14); + for (int i = t; i < 16 * HD; i += THREADS) { + const int h = i / HD, d = i % HD; + const float x = h < G ? q[(size_t) h * HD + d] * qup : 0.0f; + const sycl::half hi = sycl::half(x); + S.qh[h * QS + d] = hi; + S.ql[h * QS + d] = sycl::half(x - (float) hi); + } + for (int i = t; i < 16 * HD; i += THREADS) S.acc[i] = 0.0f; + if (t < 16) { mrow[t] = -INFINITY; lsum[t] = 0.0f; } + // the K^T tile is the same for every chunk position: B(k, c) packed by k pairs + for (int c0 = 0; c0 < n; c0 += CH) { + const int nh = sycl::min(CH, n - c0); + it.barrier(sycl::access::fence_space::local_space); // the previous chunk is done with kp, vp, s, tmp + if (t < CH) { + long long r = -1; + if (t < nh) { + const int cell = ids[c0 + t]; + const long long page = (long long) p.page_table[cell / page_size]; + r = (page * n_kv_heads + kvh) * page_size + (cell % page_size); + } + S.row[t] = r; + } + it.barrier(sycl::access::fence_space::local_space); + // K rows -> packed K^T (raw INT8 codes as halves in modes 1 and 3; the scale comes after the product) + for (int i = t; i < CH * (HD / 8); i += THREADS) { + const int c = i / (HD / 8), piece = i % (HD / 8); + const long long r = S.row[c]; + sycl::half h[8]; + if (r < 0) { + for (int j = 0; j < 8; ++j) h[j] = sycl::half(0.0f); + } else if constexpr (KV_MODE == 0) { + const sycl::vec v = *reinterpret_cast*>(p.k_pool + r * HD + piece * 8); + for (int j = 0; j < 8; ++j) h[j] = sycl::bit_cast(v[j]); + } else { + const sycl::vec v = *reinterpret_cast*>(p.k_q + r * HD + piece * 8); + for (int j = 0; j < 8; ++j) h[j] = sycl::half((float) v[j]); + } + for (int j = 0; j < 8; j += 2) { + const int k = piece * 8 + j; + sycl::half2* dst = reinterpret_cast(S.kp + (k >> 1) * (CH * 2) + c * 2); + *dst = sycl::half2(h[j], h[j + 1]); + } + } + // V rows -> packed V (pairs of cells) + if constexpr (KV_MODE == 3) { + constexpr int BLKS = HD / QK4_0; + constexpr int BYTES = BLKS * (int) sizeof(q4_0_block); + for (int i = t; i < CH * BLKS; i += THREADS) { + const int c = i / BLKS, b = i % BLKS; + const long long r = S.row[c]; + float d = 0.0f; + const q4_0_block* blk = nullptr; + if (r >= 0) { + blk = reinterpret_cast(p.v_q4 + r * BYTES) + b; + d = (float) sycl::bit_cast(blk->d); + } + for (int j = 0; j < QK4_0 / 2; ++j) { + const float lo = blk ? (float) ((int) (blk->qs[j] & 0x0F) - 8) * d : 0.0f; + const float hi = blk ? (float) ((int) (blk->qs[j] >> 4) - 8) * d : 0.0f; + const int d0 = b * QK4_0 + j, d1 = d0 + QK4_0 / 2; + S.vp[(c >> 1) * (HD * 2) + d0 * 2 + (c & 1)] = sycl::half(lo); + S.vp[(c >> 1) * (HD * 2) + d1 * 2 + (c & 1)] = sycl::half(hi); + } + } + } else { + for (int i = t; i < CH * (HD / 8); i += THREADS) { + const int c = i / (HD / 8), piece = i % (HD / 8); + const long long r = S.row[c]; + sycl::half h[8]; + if (r < 0) { + for (int j = 0; j < 8; ++j) h[j] = sycl::half(0.0f); + } else if constexpr (KV_MODE == 1) { + const sycl::vec v = *reinterpret_cast*>(p.v_q + r * HD + piece * 8); + for (int j = 0; j < 8; ++j) h[j] = sycl::half((float) v[j]); + } else { + const sycl::vec v = *reinterpret_cast*>(p.v_pool + r * HD + piece * 8); + for (int j = 0; j < 8; ++j) h[j] = sycl::bit_cast(v[j]); + } + for (int j = 0; j < 8; ++j) S.vp[(c >> 1) * (HD * 2) + (piece * 8 + j) * 2 + (c & 1)] = h[j]; + } + } + for (int i = t; i < CH * 4; i += THREADS) { + const int c = i / 4, g = i % 4; + const long long r = S.row[c]; + float a = 0.0f, b = 0.0f; + if (r >= 0) { + if constexpr (KV_MODE == 1) { + a = (float) sycl::bit_cast(p.k_scale[r * (HD / KV_Q8_GROUP) + g]); + b = (float) sycl::bit_cast(p.v_scale[r * (HD / KV_Q8_GROUP) + g]); + } else if constexpr (KV_MODE == 3) { + a = (float) sycl::bit_cast(p.k_scale[r * (HD / KV_Q8_GROUP) + g]); + b = 1.0f; + } else { + a = b = 1.0f; + } + } + S.ks[c * 4 + g] = a; + S.vs[c * 4 + g] = b; + } + it.barrier(sycl::access::fence_space::local_space); + // scores: sub-group sg takes dim group g = sg & 3 with the hi (sg < 4) or lo (sg >= 4) half of q + { + const int g = sgid & 3; + const sycl::half* qa = (sgid < 4 ? S.qh : S.ql); + jm::joint_matrix C; + jm::joint_matrix_fill(sg, C, 0.0f); + for (int kk = 0; kk < 4; ++kk) { + const int k0 = (g * 4 + kk) * 16; + jm::joint_matrix A; + jm::joint_matrix B; + jm::joint_matrix_load(sg, A, lptr(qa + k0), (size_t) QS); + jm::joint_matrix_load(sg, B, lptr(S.kp + (k0 >> 1) * (CH * 2)), (size_t) (CH * 2)); + jm::joint_matrix_mad(sg, C, A, B, C); + } + jm::joint_matrix_store(sg, C, lptr(S.tmp + sgid * 256), (size_t) 16, jm::layout::row_major); + } + it.barrier(sycl::access::fence_space::local_space); + for (int i = t; i < 16 * CH; i += THREADS) { + const int r = i / CH, c = i % CH; + float v = 0.0f; + for (int g = 0; g < 4; ++g) v += (S.tmp[g * 256 + r * 16 + c] + S.tmp[(g + 4) * 256 + r * 16 + c]) * S.ks[c * 4 + g]; + S.s[r * PS + c] = c < nh ? v * qdown : -INFINITY; + } + it.barrier(sycl::access::fence_space::local_space); + // online softmax: row t/8, 2 cells per thread, 8 lanes per row (within one sub-group) + { + constexpr int PER = CH / 8; + const int r = t >> 3, sub = t & 7; + float x[PER], mx = -INFINITY; + for (int j = 0; j < PER; ++j) { x[j] = S.s[r * PS + sub * PER + j]; mx = sycl::fmax(mx, x[j]); } + for (int o = 1; o < 8; o <<= 1) mx = sycl::fmax(mx, sycl::permute_group_by_xor(sg, mx, o)); + const float m_old = mrow[r]; + const float m_new = sycl::fmax(m_old, mx); + float sum = 0.0f; + for (int j = 0; j < PER; ++j) { + const float e = x[j] == -INFINITY ? 0.0f : sycl::exp2(x[j] - m_new); + S.s[r * PS + sub * PER + j] = e; + sum += e; + } + for (int o = 1; o < 8; o <<= 1) sum += sycl::permute_group_by_xor(sg, sum, o); + if (sub == 0) { + const float a = m_old == -INFINITY ? 0.0f : sycl::exp2(m_old - m_new); + alpha[r] = a; + lsum[r] = sycl::fma(lsum[r], a, sum); + mrow[r] = m_new; + } + } + // the V scale per dim group, folded into P relative to the chunk's largest (times 2^14, as in CUDA) + if (t < 4) { + float vmax = 0.0f; + for (int c = 0; c < CH; ++c) vmax = sycl::fmax(vmax, S.vs[c * 4 + t]); + vup[t] = vmax > 0.0f ? 16384.0f / vmax : 0.0f; + vdown[t] = vmax * (1.0f / 16384.0f); + } + it.barrier(sycl::access::fence_space::local_space); + // P tiles: pv[g][hi/lo][r][c] = s[r][c] * vs[c][g] * vup[g], split into hi + lo halves + for (int i = t; i < 4 * 16 * CH; i += THREADS) { + const int g = i / (16 * CH), rc = i % (16 * CH), r = rc / CH, c = rc % CH; + const float pw = S.s[r * PS + c] * S.vs[c * 4 + g] * vup[g]; + const sycl::half hi = sycl::half(pw); + S.pv[((g * 2 + 0) * 16 + r) * PS + c] = hi; + S.pv[((g * 2 + 1) * 16 + r) * PS + c] = sycl::half(pw - (float) hi); + } + it.barrier(sycl::access::fence_space::local_space); + // p.v: sub-group sg owns dims [32 sg, 32 sg + 32) = two B tiles of scale group sg / 2 + { + const int g = sgid >> 1; + const sycl::half* ah = S.pv + ((g * 2 + 0) * 16) * PS; + const sycl::half* al = S.pv + ((g * 2 + 1) * 16) * PS; + jm::joint_matrix Ah, Al; + jm::joint_matrix_load(sg, Ah, lptr(ah), (size_t) PS); + jm::joint_matrix_load(sg, Al, lptr(al), (size_t) PS); + const float a_vdown = vdown[g]; + for (int dt = 0; dt < 2; ++dt) { + const int d0 = sgid * 32 + dt * 16; + jm::joint_matrix B; + jm::joint_matrix_load(sg, B, lptr(S.vp + d0 * 2), (size_t) (HD * 2)); + jm::joint_matrix C; + jm::joint_matrix_fill(sg, C, 0.0f); + jm::joint_matrix_mad(sg, C, Ah, B, C); + jm::joint_matrix_mad(sg, C, Al, B, C); + jm::joint_matrix_store(sg, C, lptr(S.tmp + sgid * 256), (size_t) 16, jm::layout::row_major); + sycl::group_barrier(sg); + for (int i = lane; i < 256; i += SG) { + const int r = i >> 4, c = i & 15; + float* a = S.acc + r * HD + d0 + c; + *a = sycl::fma(*a, alpha[r], S.tmp[sgid * 256 + i] * a_vdown); + } + sycl::group_barrier(sg); + } + } + } + it.barrier(sycl::access::fence_space::local_space); + for (int i = t; i < G * HD; i += THREADS) { + const int h = i / HD, d = i % HD; + const float l = lsum[h]; + attn[(size_t) h * HD + d] = l > 0.0f ? S.acc[h * HD + d] / l : 0.0f; + } +} + +template +bool launch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, + const QsaShapes& s, float* attn, int64_t n_q, dpct::queue_ptr st) { + const float scale_log2 = 1.4426950408889634f / std::sqrt((float) HD); + for (int64_t q0 = 0; q0 < n_q; q0 += 65535) { + const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535; + const float* qq = q + q0 * s.n_head * HD; + const int32_t* idq = ids + q0 * cap; + const int32_t* stq = steps + q0 * kStepCount; + float* aq = attn + q0 * s.n_head * HD; + const int nkv = (int) s.n_head_kv, ps = (int) s.page_size, capi = (int) cap; + st->submit([&](sycl::handler& cgh) { + sycl::local_accessor slm(sycl::range<1>(kSmemBytes), cgh); + cgh.parallel_for(sycl::nd_range<3>(sycl::range<3>(1, (size_t) nkv, (size_t) nb * THREADS), sycl::range<3>(1, 1, THREADS)), + [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(16)]] { + prompt_attn_xmx_kernel(qq, pools, idq, stq, nkv, ps, scale_log2, aq, capi, + slm.get_multi_ptr().get()); + }); + }); + } + return true; +} +} // namespace + +bool qsa_prompt_attn_xmx(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, + const QsaShapes& s, float* attn, int64_t n_q, void* stream) { + // Off unless asked for: correct (qsa_prompt_attn_parity: 1e-6 of scale, like the CUDA kernel) but 3x slower than the + // FP32 fallback on the B70 (18.7 vs 5.5 ms per chunk at 32k context, 2026-09-30) - the chunk staging and packing + // dominate, not the products. Kept as the base for a tuned version (bigger chunks, vector packing). + static const bool on = std::getenv("STRATA_PROMPT_ATTN_XMX") && std::getenv("STRATA_PROMPT_ATTN_XMX")[0] == '1'; + if (!on || n_q <= 0) return false; + if (pools.k_q4 != nullptr || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !ids || !steps || + !pools.page_table) + return false; + dpct::queue_ptr st = strata::q_of(stream); + static const bool fits = [&] { + const size_t have = st->get_device().get_info(); + if (have < kSmemBytes) std::fprintf(stderr, "strata: prompt attention on XMX needs %zu bytes of local memory, the device has %zu\n", kSmemBytes, have); + return have >= kSmemBytes; + }(); + if (!fits) return false; + if (pools.k_q != nullptr && pools.v_q4 != nullptr) { + if (!pools.k_scale) return false; + return launch<3>(q, pools, ids, steps, cap, s, attn, n_q, st); + } + if (pools.k_q != nullptr) { + if (!pools.v_q || !pools.k_scale || !pools.v_scale) return false; + return launch<1>(q, pools, ids, steps, cap, s, attn, n_q, st); + } + if (!pools.k_pool || !pools.v_pool) return false; + return launch<0>(q, pools, ids, steps, cap, s, attn, n_q, st); +} +} // namespace strata::kernels diff --git a/sycl/src/kernels/cuda/verify_kernels.dp.cpp b/sycl/src/kernels/cuda/verify_kernels.dp.cpp index 402b0e2a..b556c82a 100644 --- a/sycl/src/kernels/cuda/verify_kernels.dp.cpp +++ b/sycl/src/kernels/cuda/verify_kernels.dp.cpp @@ -13,6 +13,9 @@ #include #include +#ifndef STRATA_PLAN_LOCAL +#define STRATA_PLAN_LOCAL 1 // 0: the original one-thread plan kernel (A/B) +#endif namespace strata::kernels { namespace { @@ -928,11 +931,40 @@ __dpct_inline__ void resident_plan_kernel( const int32_t *__restrict__ res, int n_expert, const uint8_t *cache_base, const unsigned long long *slot_off, long long blob, int32_t *__restrict__ pl, long long capx, uint32_t *skip, uint32_t ring) { - // one thread: at most kVerifyMaxT * 10 entries, the host's exact loop +#if STRATA_PLAN_LOCAL + // SYCL port: the host's exact loop, but over a local copy of the ids and their slots. One thread reading global + // memory for every compare (n^2 of them) took 87 us per layer on the B70 - 4% of a decode round; a work-group + // of 64 loads the n <= 60 entries once, then thread 0 groups them from local memory. + auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>(); + auto &s_ids = *sycl::ext::oneapi::group_local_memory_for_overwrite(item.get_group()); + auto &s_res = *sycl::ext::oneapi::group_local_memory_for_overwrite(item.get_group()); + auto &s_bad = *sycl::ext::oneapi::group_local_memory_for_overwrite(item.get_group()); + const int tid = (int) item.get_local_id(2); + if (tid == 0) s_bad = 0; + item.barrier(sycl::access::fence_space::local_space); + for (int i = tid; i < n && i < 64; i += 64) { + const int32_t e = ids[i]; + const bool ok = e >= 0 && e < n_expert && res[e] >= 0; + s_ids[i] = e; + s_res[i] = ok ? res[e] : -1; + if (!ok) s_bad = 1; + } + item.barrier(sycl::access::fence_space::local_space); + if (tid != 0) return; + if (s_bad || n > 64) { *skip = 0; return; } // n > 64 never happens (kVerifyMaxT * 10 = 60); refuse rather than read past +#else + // the original: one thread, the host's exact loop over global memory for (int i = 0; i < n; ++i) { const int32_t e = ids[i]; if (e < 0 || e >= n_expert || res[e] < 0) { *skip = 0; return; } } +#endif +#if !STRATA_PLAN_LOCAL +#define s_ids ids +#define S_RES(i) res[ids[i]] +#else +#define S_RES(i) s_res[i] +#endif int32_t* counts = pl; int32_t* start = pl + 4; int32_t* dst = start + capx + 1; @@ -943,17 +975,15 @@ __dpct_inline__ void resident_plan_kernel( int groups = 0, entries = 0; for (int i0 = 0; i0 < n; ++i0) { bool first = true; -#pragma unroll - for (int j = 0; j < i0; ++j) if (ids[j] == ids[i0]) { + for (int j = 0; j < i0; ++j) if (s_ids[j] == s_ids[i0]) { first = false; break; } if (!first) continue; - const int32_t slot = res[ids[i0]]; + const int32_t slot = S_RES(i0); ptr[groups] = (unsigned long long) (cache_base + (slot_off ? (size_t) slot_off[slot] : (size_t) slot * (size_t) blob)); start[groups] = entries; -#pragma unroll for (int i = i0; i < n; ++i) - if (ids[i] == ids[i0]) { + if (s_ids[i] == s_ids[i0]) { // an entry belongs to i0's group when its first occurrence is i0: the same expert id dst[entries] = i; tok[entries] = i / k; @@ -973,6 +1003,8 @@ __dpct_inline__ void resident_plan_kernel( */ sycl::atomic_fence(sycl::memory_order::acq_rel, sycl::memory_scope::device); strata::sys_store(skip, ring); +#undef s_ids +#undef S_RES } __dpct_inline__ void wait_flag_ge_or_kernel(const volatile uint32_t *flag, uint32_t value, @@ -1031,8 +1063,8 @@ void resident_plan(const int32_t* ids, int n_entries, int k, const int32_t* res_ strata::q_of(stream) ->parallel_for>( - sycl::nd_range<3>(sycl::range(1, 1, 1), sycl::range(1, 1, 1)), - exp_props, [=](sycl::nd_item<3> item_ct1) { + sycl::nd_range<3>(sycl::range(1, 1, STRATA_PLAN_LOCAL ? 64 : 1), sycl::range(1, 1, STRATA_PLAN_LOCAL ? 64 : 1)), + exp_props, [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] { resident_plan_kernel(ids, n_entries, k, res_layer, n_expert, cache_base, slot_off, blob, plan, capx, skip, ring); diff --git a/sycl/src/kernels/xmx_gemm_bench.cpp b/sycl/src/kernels/xmx_gemm_bench.cpp new file mode 100644 index 00000000..d332cd1e --- /dev/null +++ b/sycl/src/kernels/xmx_gemm_bench.cpp @@ -0,0 +1,93 @@ +// xmx_gemm_bench: the XMX quantized GEMM against dequant + oneMKL on random experts. +// xmx_gemm_bench [ty=18] [M=96] [mode=gu|down] [reps=50] +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/xmx_gemm.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +static float h2f(uint16_t h) { return (float) sycl::bit_cast(h); } +static uint16_t f2h(float f) { return sycl::bit_cast(sycl::half(f)); } +int main(int argc, char** argv) { + const int ty = argc > 1 ? std::atoi(argv[1]) : 18; + const int M = argc > 2 ? std::atoi(argv[2]) : 96; + const std::string mode = argc > 3 ? argv[3] : "gu"; + const int reps = argc > 4 ? std::atoi(argv[4]) : 50; + const bool gu = mode == "gu"; + const int64_t K = gu ? 2560 : 640, n_out = gu ? 1280 : 2560, n_ff = 640; + const int blk_elems = (ty == 20) ? 32 : (ty == 42) ? 64 : 256; + const size_t blk_bytes = strata::kernels::iq_row_bytes(ty, blk_elems); + const size_t row_bytes = strata::kernels::iq_row_bytes(ty, K); + if (row_bytes == 0) { std::printf("type %d not supported\n", ty); return 2; } + const int64_t rows_per_blob = gu ? n_ff : n_out; + std::mt19937 rng(7); + auto blob = [&]() { + std::vector b(rows_per_blob * row_bytes); + for (auto& x : b) x = (uint8_t) rng(); + for (size_t o = 0; o + 1 < b.size(); o += blk_bytes) { b[o] = 0x00; b[o + 1] = 0x3C; } // d = 1.0 in every block + return b; + }; + std::vector hg = blob(), hu = gu ? blob() : std::vector(); + std::vector hx((size_t) M * K); + std::normal_distribution nd(0.f, 1.f); + for (auto& x : hx) x = f2h(nd(rng)); + sycl::queue* q = &dpct::get_in_order_queue(); + uint8_t* dg = sycl::malloc_device(hg.size(), *q); + uint8_t* du = gu ? sycl::malloc_device(hu.size(), *q) : nullptr; + uint16_t* dx = sycl::malloc_device(hx.size(), *q); + uint16_t* dw = sycl::malloc_device((size_t) n_out * K, *q); + float* y_ref = sycl::malloc_device((size_t) M * n_out, *q); + float* y_xmx = sycl::malloc_device((size_t) M * n_out, *q); + q->memcpy(dg, hg.data(), hg.size()).wait(); + if (gu) q->memcpy(du, hu.data(), hu.size()).wait(); + q->memcpy(dx, hx.data(), hx.size() * 2).wait(); + // the reference path: the engine's dequant kernels + oneMKL (what prefill.cpp runs today) + dpct::blas::descriptor_ptr h = new dpct::blas::descriptor(); + h->set_queue(q); + auto dequant = [&]() { + if (gu) strata::kernels::iq_dequant_gu_f16(ty, dg, du, n_ff, K, dw, q); + else strata::kernels::iq_dequant_f16(ty, dg, n_out * K, dw, q); + }; + auto mkl = [&]() { + const float alpha = 1.0f, beta = 0.0f; + dpct::blas::gemm(h, oneapi::mkl::transpose::trans, oneapi::mkl::transpose::nontrans, (int) n_out, M, (int) K, &alpha, dw, + dpct::library_data_t::real_half, (int) K, dx, dpct::library_data_t::real_half, (int) K, &beta, y_ref, + dpct::library_data_t::real_float, (int) n_out, dpct::compute_type::f32); + }; + dequant(); mkl(); q->wait(); + if (!strata::kernels::xmx_gemm_iq(ty, dg, du, K, (int) n_out, dx, M, y_xmx, n_out, q)) { std::printf("xmx_gemm_iq refused\n"); return 3; } + q->wait(); + std::vector r((size_t) M * n_out), x((size_t) M * n_out); + q->memcpy(r.data(), y_ref, r.size() * 4).wait(); + q->memcpy(x.data(), y_xmx, x.size() * 4).wait(); + double maxref = 0, maxerr = 0, sumerr = 0; size_t bad = 0, nonfinite = 0; + for (size_t i = 0; i < r.size(); ++i) { + if (!std::isfinite(r[i]) || !std::isfinite(x[i])) { ++nonfinite; continue; } + maxref = std::max(maxref, (double) std::fabs(r[i])); + const double e = std::fabs((double) r[i] - x[i]); + maxerr = std::max(maxerr, e); sumerr += e; + if (e > 1e-2 * (1.0 + std::fabs(r[i]))) ++bad; + } + std::printf("ty %d %s M %d: max |ref| %.3g, max err %.3g, mean err %.3g, %zu of %zu outside 1%% (nonfinite %zu)\n", ty, + mode.c_str(), M, maxref, maxerr, sumerr / r.size(), bad, r.size(), nonfinite); + auto time = [&](auto&& fn) { + for (int i = 0; i < 3; ++i) fn(); q->wait(); + const auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < reps; ++i) fn(); + q->wait(); + return std::chrono::duration(std::chrono::steady_clock::now() - t0).count() / reps; + }; + const double t_dq = time([&] { dequant(); }), t_mkl = time([&] { mkl(); }), t_both = time([&] { dequant(); mkl(); }); + const double t_xmx = time([&] { strata::kernels::xmx_gemm_iq(ty, dg, du, K, (int) n_out, dx, M, y_xmx, n_out, q); }); + const double flop = 2.0 * M * n_out * K; + std::printf("dequant %.3f ms + mkl %.3f ms = %.3f ms (%.0f GFLOP/s on the GEMM) | xmx %.3f ms (%.0f GFLOP/s, %.2fx)\n", t_dq, + t_mkl, t_both, flop / t_mkl / 1e6, t_xmx, flop / t_xmx / 1e6, t_both / t_xmx); + return bad > r.size() / 1000 ? 1 : 0; +} diff --git a/sycl/src/prefill/prefill.cpp b/sycl/src/prefill/prefill.cpp index b9d04cb2..83da4dff 100644 --- a/sycl/src/prefill/prefill.cpp +++ b/sycl/src/prefill/prefill.cpp @@ -808,8 +808,11 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t const bool q8 = !f16_only && mmq::built() && mmq::supported(kQ8_0); const uint64_t per_row = 4 * (2 * Nn + 4 * HCN + LR + HC + Nn + 2 * KV + 1) + 2 * (Nn + 2 * HCN + LR + Nn) + 64 + (q8 ? (uint64_t) mmq::q8_bytes(g.hc, Nn) + 4 * g.hc : 0); - const int64_t B = std::min(n - r0, (int64_t) (m.region_bytes / per_row) & ~(int64_t) 63); - if (B < 64) return false; + // SYCL port: B is the batch buffers' capacity, not the row count (each batch uses nb <= B rows), so a short + // prompt gets 64-row buffers instead of the per-6-token fallback (19 tokens: 106 ms there, a few ms here) + const int64_t cap = (int64_t) (m.region_bytes / per_row) & ~(int64_t) 63; + if (cap < 64) return false; + const int64_t B = std::min(std::max(n - r0, 64), cap); uint8_t* q = m.region; auto carve = [&](size_t bytes) { void* p = q; q += (bytes + 255) & ~(size_t) 255; return p; }; float* emb = (float*) carve((size_t) B * Nn * 4); @@ -1125,6 +1128,11 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0, ++stats_.chunks; pt.mark(kPfStart, cs); const auto tsetup = Clock::now(); + auto tlap = tsetup; // STRATA_PREFILL_TIMING=1: where the host's chunk setup goes + auto lap = [&](const char* what) { + if (pt.on) { std::fprintf(stderr, "strata prefill timing: setup %s %.1f ms\n", what, ms_since(tlap)); tlap = Clock::now(); } + }; + if (pt.on) { m.cs->wait(); lap("work queued before the chunk"); } // ---- embeddings, broadcast to the four streams - or, in a later stage of a layer split, the rows the // previous stage handed on if (hand_in_ != nullptr) { @@ -1167,8 +1175,10 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0, err = "prefill: the token id upload failed"; return false; } + lap("token ids uploaded"); if (nemb) { nemb->gather_dev(m.tok_dev, T, m.emb, m.cs); + if (pt.on) { m.cs->wait(); lap("embedding gather (waited)"); } } else { const auto* codes = (const uint8_t*) wemb->data; const auto* scales = (const float*) (codes + wemb->codes_bytes); @@ -1200,6 +1210,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0, } } if (hand_in_ == nullptr) gr_broadcast(m.emb, m.R, T, m.cs); + lap("embeddings"); // ---- the PLE rows of the whole chunk, one batched SSD request (read ahead on a thread, see ple_gather) if (ple_on) { const auto tp = Clock::now(); @@ -1229,6 +1240,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0, stats_.ms_ple += ms_since(tp); } for (int64_t t = 0; t < T; ++t) { prev[0] = prev[1]; prev[1] = (int32_t) tokens[c0 + t]; } + lap("PLE rows"); // ---- the QSA step records of every position in the chunk for (int64_t t = 0; t < T; ++t) strata::kernels::qsa_step_fill(m.steps_host.data() + t * strata::kernels::kStepCount, p0 + t, s); /* @@ -1242,6 +1254,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0, int64_t qsa_index = 0, gdn_index = 0; for (int64_t l = 0; l < LB; ++l) (core::is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1; + lap("step records"); // step 3: this chunk's stream - every non-resident expert of every layer, layer by layer in id order (entry // k lands in ring slot k % ring); a copy is issued once the entry `ring` before it is consumed (its slot's // `used` event recorded), so the copy stream never waits on an event that is not queued yet @@ -1394,6 +1407,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0, if (threaded_issue) a_consumed.store(upto, std::memory_order_release); else issue_until(upto + (size_t) m.ring); }; + lap("expert stream plan"); host_setup_ms += ms_since(tsetup); bool normed = false; // F-2: the previous half's write already normed R for this half (grs, xn16) for (int64_t l = LB; l < LE; ++l) { diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index 6f89035c..e26a005c 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -5292,6 +5292,20 @@ int main(int argc, char** argv) { // plan v0.3 P6: with a native pack the first window is the last prompt token alone (it produces the first // generated token and the MTP's first cell); otherwise the token loop already did that. bool first_window = native_pack; + // SYCL port: every window graph and the drafter's graphs are captured here, once, instead of on first use in + // the loop below (STRATA_WARM_GRAPHS=0: as before). A server pays this once per process, not per request. + { + static const bool warm_on = [] { const char* v = std::getenv("STRATA_WARM_GRAPHS"); return !(v && v[0] == '0'); }(); + if (warm_on) { + const Clock::time_point tw = Clock::now(); + if (!ver.warm(err) || (use_mtp && !mtp.warm(err))) { + std::fprintf(stderr, "strata generate: warm-up capture: %s\n", err.c_str()); + return 1; + } + std::fprintf(stderr, "strata generate: window and draft graphs captured in %.0f ms\n", + std::chrono::duration(Clock::now() - tw).count()); + } + } if (use_mtp && !first_window && !mtp.draft_first(o.spec, ss.R, x, p - 1, drafts.data(), err, dprob.data(), (float) o.spec_min_p)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); @@ -5370,7 +5384,9 @@ int main(int argc, char** argv) { bool adapt_ok = true; if (!drive.d.usage.empty() && ((rounds + 1) % o.adapt_every) == 0) adapt_thr = std::thread([&] { adapt_ok = adapt(); }); - if (!ver.commit(a + 1, err)) { + // SYCL port: the commit graph is left running while the drafter's round (its own queue) runs; collected + // below, before anything reads the committed state + if (!ver.commit(a + 1, err, /*wait=*/!use_mtp)) { if (adapt_thr.joinable()) adapt_thr.join(); std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; @@ -5388,6 +5404,7 @@ int main(int argc, char** argv) { } if (eos) { if (adapt_thr.joinable()) adapt_thr.join(); + if (!ver.commit_finish(err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } total_ms += std::chrono::duration(Clock::now() - t0).count(); break; } @@ -5399,6 +5416,7 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } + if (!ver.commit_finish(err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } x = outv[(size_t) a]; p += a + 1; const double round_ms = std::chrono::duration(Clock::now() - t0).count();