Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
sycl: refresh for upstream 0.1.28-0.1.29, fix the streamed-expert prompt path (stale ring pointers, stream-all hang)
maxfridbe14e0c017bbd4
diff --git a/docs/INTEL.md b/docs/INTEL.mdindex 2563426a7..bf4c1dbaf 100644--- a/docs/INTEL.md+++ b/docs/INTEL.md@@ -236,6 +236,7 @@ same prompts as above (outputs identical before and after each change):|---|---|| 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 |+| upstream 0.1.29 merged (GDN recurrence pipelining, the block-scores read, sampler) | 2,184-token prompt 765 -> 792 tok/s, decode at that context 43.1 -> 45.2 || 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 |@@ -261,28 +262,26 @@ A trap worth knowing: with a native pack `--prefill-until N` does not feed the rtoken loop (it is skipped for native packs), so the tokens after N are dropped and the model free-runs. Compareoutput tokens between paths, never only timings.-**An 80,000-token prompt (2026-09-30).** Where the time goes changes completely at this scale, and the first-attempt did not finish at all:+**An 80,000-token prompt (2026-09-30).** Where the time goes changes completely at this scale:- **The VRAM plan.** `--expert-cache auto` fills the card down to `--vram-reserve-mib` *before* the KV state(about 1 GB in INT8 at 81,920 cells) and the prompt chunk buffers (about 2 GB at `--prefill 8192`) exist. With- the 1,536 MiB default that put 30.95 of the B70's 32.6 GB in use, the driver started migrating buffers, the GPU- read 100% busy at 2,800 MHz with nothing finishing, and the rig's watchdog killed the run after 25 minutes- (one copy-engine reset, the GT recovered by itself). For long contexts pass a reserve that covers both:- `--max-context 81920 --kv int8 --vram-reserve-mib 3072 --prefill 4096` peaks at 28.8 GB. Until the auto- formula accounts for them itself, watch `vram_used_mb` on such runs. (80k ids also exceed Linux's 128 KB- single-argument limit: `--tokens-file`.)-- **Expert streaming decides the speed.** The reserve costs cache slots (10,348 of 12,288 at 3 GB), and the- prompt path streams every non-resident expert from the GGUF *once per chunk*. 2,048-token chunks: 40 chunks,- 62,942 blob reads (~125 GB), 278 s = 288 tok/s, the GPU idle 75% of the time. 4,096-token chunks: 21 chunks,- 37,678 reads, **77 s = 1,037 tok/s**, close to the 8k-token rate. The bigger chunk costs 0.5 GB more VRAM.- Twelve host copy threads instead of the default four (`STRATA_STAGER_THREADS`) take it to 75 s (1,065- tok/s): they empty the copy wait (5.6 s to 0.05 s) but the 52 s of host staging is the SSD delivering- ~70 GB of blobs, and 16 s of chunk setup remains where the GPU waits for each chunk's stream plan.-- **Compute at 80k** (of the 75 s): attention 13.9 s, QSA block selection 9.9 s (it was 0.2 s at 8k: it scans- every block of the context per query), GDN recurrence 6.1 s, the chunk setup wait 16 s, the per-layer- grouping sync 4.6 s, GEMMs 4.6 s, dequant 1.4 s. The PLE rows are no longer a cost: 1.28 M row- lookups with a 97.6% row-cache hit rate, 90 ms.+ the 1,536 MiB default that put 30.95 of the B70's 32.6 GB in use, the driver started migrating buffers and the+ run never finished. `--max-context 81920 --kv int8 --vram-reserve-mib 3072 --prefill 4096` peaks at 28.8 GB.+ (80k ids also exceed Linux's 128 KB single-argument limit: `--tokens-file`.)+- **Streamed experts.** The reserve costs cache slots (10,348 of 12,288 at 3 GB), and the prompt path streams the+ missing experts from the GGUF for every chunk. Two port bugs sat on this path and are fixed: the stream plan+ held `GgufExpertSource::blob()` pointers across ~1,900 reads of a 512-slot ring (so blobs were overwritten+ before they were copied: the 75 s / 1,065 tok/s measured first was computed partly with the wrong experts), and+ the stream-all walk hangs on this card in its first large chunk (the copy engine stops on a barrier). The stager+ threads now read the blobs themselves, and the port uses the per-layer routed-only walk (`STRATA_PREFILL_RING=8`+ upstream, the port's default; `STRATA_PREFILL_STREAM_ALL=1` restores the other for debugging).+- **Correct result: 80,000 tokens in 101 s = 790 tok/s.** GPU time: expert down GEMM 26.0 s, attention 15.4 s,+ dequant 12.7 s, QSA block selection 9.3 s (0.2 s at 8k: it scans every block of the context per query), gate/up+ GEMM 8.9 s, gather 6.1 s, the per-layer grouping sync 5.2 s, GDN recurrence 4.8 s. The PLE rows are free at this+ scale (97.6% row-cache hits).+- **Open: decode after such a prompt runs at 2-3 tok/s**, because the experts the reserve pushed out of the cache+ stay out; the prompt buffers should give their VRAM back to the cache when the prompt ends.**Keeping up with upstream.** A merge of upstream `main` into `b70` leaves the copies in `sycl/` behindwherever upstream touched a file they mirror. They are refreshed by re-migration, not by hand (done fordiff --git a/sycl/include/strata/core/gguf_expert_source.hpp b/sycl/include/strata/core/gguf_expert_source.hppindex b5c4df430..1e88fcb90 100644--- a/sycl/include/strata/core/gguf_expert_source.hpp+++ b/sycl/include/strata/core/gguf_expert_source.hpp@@ -35,6 +35,10 @@ public:void close();const uint8_t* blob(int64_t layer, int64_t expert) override;+ /// The blob gathered straight into `dst` (bytes = the layer's blob size), from any thread: no ring slot, so the+ /// prompt path's stager threads read the streamed experts themselves instead of holding ring pointers that a+ /// later blob() call overwrites (the 80k-token run of 2026-09-30 streamed ~1,900 blobs per chunk through 512 slots).+ bool read_into(int64_t layer, int64_t expert, uint8_t* dst, size_t bytes) const;int64_t reads() const override { return reads_; }private:diff --git a/sycl/include/strata/core/mtp.hpp b/sycl/include/strata/core/mtp.hppindex 1426a610a..cfd2896c1 100644--- a/sycl/include/strata/core/mtp.hpp+++ b/sycl/include/strata/core/mtp.hpp@@ -62,6 +62,9 @@ public:/// KV streaming: refill the ring of the drafter's window from its host copy for a sequence that continues at/// `upto` (a conversation-cache resume). No-op unless the drafter's K/V is a ring.void kv_restore(int64_t upto);+ /// The VRAM bind() will allocate for a native head of `head_row_bytes` per vocabulary row: the draft logits and+ /// the draft head over rt/draft_vocab.bin's subset. The expert cache is sized before bind(), so it reserves this.+ uint64_t bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const;/// The main model's embedding and head, and the verify window's final residuals (T rows, hc*n_embd each).bool bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err);diff --git a/sycl/include/strata/kernels/bf16_bits.hpp b/sycl/include/strata/kernels/bf16_bits.hppindex a315a8343..84fe011b0 100644--- a/sycl/include/strata/kernels/bf16_bits.hpp+++ b/sycl/include/strata/kernels/bf16_bits.hpp@@ -31,6 +31,12 @@namespace strata::kernels {/// Round-to-nearest-even f32 -> bf16, returned as raw bits in the LOW half of the uint16.+///+/// **A NaN IS PASSED THROUGH, QUIETED, AS `ggml_compute_fp32_to_bf16` DOES.** The rounding add alone+/// carries out of the mantissa for a NaN: 0x7FFFFFFF became 0x8000 (-0) and 0x7F800001 became 0x7F80 (+inf), so+/// a NaN upstream was masked instead of propagated. The test is on the magnitude bits, the result keeps the+/// sign and the top mantissa bits and sets the quiet bit (64 = bit 6 of the bf16). Every non-NaN input,+/// infinities included, rounds exactly as before.STRATA_BF16_HD inline uint16_t bf16_from_f32(float f) {uint32_t i;#if defined(__HIP_DEVICE_COMPILE__)@@ -38,6 +44,7 @@ STRATA_BF16_HD inline uint16_t bf16_from_f32(float f) {#elsestd::memcpy(&i, &f, 4);#endif+ if ((i & 0x7FFFFFFFu) > 0x7F800000u) return (uint16_t) ((i >> 16) | 64u);i = (i + ((i >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u;return (uint16_t) (i >> 16);}diff --git a/sycl/src/core/expert_source.cpp b/sycl/src/core/expert_source.cppindex c61737024..c2886a154 100644--- a/sycl/src/core/expert_source.cpp+++ b/sycl/src/core/expert_source.cpp@@ -836,6 +836,14 @@ void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, consd.experts += k;}+namespace {+// the verify window's per-entry tables in `expert_pool_dispatch_multi` (`kind`, `distinct`, `first_of`)+// are fixed arrays of this many entries: MAXT tokens of the model's 10 routed experts must fit, and a larger k is+// refused at run time rather than written past them.+constexpr int64_t kMaxWindowEntries = 128;+static_assert(strata::kernels::cpu::MAXT * 10 <= kMaxWindowEntries, "a verify window's entries overflow the tables");+} // namespace+void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k,float* out) {using namespace strata::kernels::cpu;@@ -846,6 +854,12 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32d.fail_layer = d.layers;return;}+ if (k < 1 || n_tok * k > kMaxWindowEntries) {+ d.failed = true;+ d.fail = "a verify window routes more entries than the expert pool's window tables hold";+ d.fail_layer = d.layers;+ return;+ }if ((int64_t) d.act_multi.size() < n_tok) d.act_multi.resize((size_t) MAXT);const ExpertLayout& lay = expert_layout();const bool native = lay.native;@@ -866,9 +880,9 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32// ---- plan v0.3 P6: the GPU's share, decided and published FIRST so the GPU starts while the CPU works.// Distinct experts in routing order; resident ones and the last pcie_num/256 of the missed ones go to the GPU.const int64_t n = n_tok * k;- int32_t kind[128]; // per entry: -1 CPU, 0 VRAM, 1 PCIe- if (d.plan != nullptr && n <= 128 && n <= d.plan->cap) {- int64_t distinct[128], first_of[128];+ int32_t kind[kMaxWindowEntries]; // per entry: -1 CPU, 0 VRAM, 1 PCIe+ if (d.plan != nullptr && n <= kMaxWindowEntries && n <= d.plan->cap) {+ int64_t distinct[kMaxWindowEntries], first_of[kMaxWindowEntries];int nd = 0, nmiss = 0;for (int64_t i = 0; i < n; ++i) {first_of[i] = i;diff --git a/sycl/src/core/gguf_expert_source.cpp b/sycl/src/core/gguf_expert_source.cppindex c6cb56b99..99c34dcf3 100644--- a/sycl/src/core/gguf_expert_source.cpp+++ b/sycl/src/core/gguf_expert_source.cpp@@ -97,4 +97,25 @@ const uint8_t* GgufExpertSource::blob(int64_t layer, int64_t expert) {return buf.data();}+bool GgufExpertSource::read_into(int64_t layer, int64_t expert, uint8_t* dst, size_t bytes) const {+ if (layer < 0 || layer >= n_layers_ || expert < 0 || expert >= n_expert_ || dst == nullptr) return false;+ const auto& lay = strata::kernels::cpu::expert_layout();+ const auto& fm = lay.fmt[(size_t) layer];+ const uint64_t blob = lay.bytes[(size_t) layer];+ if (bytes < blob) return false;+ const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off};+ const uint64_t at[3] = {0, fm.up_off, fm.down_off};+ const int fd = fds_[(size_t) layer_fd_[(size_t) layer]];+ for (int r = 0; r < 3; ++r) {+ const uint64_t src = lay.gguf_off[(size_t) (3 * layer + r)] + per[r] * (uint64_t) expert;+ uint64_t done = 0;+ while (done < per[r]) {+ const ssize_t n = ::pread(fd, dst + at[r] + done, (size_t) (per[r] - done), (off_t) (src + done));+ if (n <= 0) return false;+ done += (uint64_t) n;+ }+ }+ return true;+}+} // namespace strata::corediff --git a/sycl/src/core/mtp.cpp b/sycl/src/core/mtp.cppindex 6f0f9eee7..bdd56dea4 100644--- a/sycl/src/core/mtp.cpp+++ b/sycl/src/core/mtp.cpp@@ -374,6 +374,19 @@ catch (sycl::exception const &exc) {std::exit(1);}+uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const {+ uint64_t bytes = head_logits_ ? 0 : (uint64_t) max_t_ * (uint64_t) n_vocab * sizeof(float);+ if (dhead_ == nullptr) {+ if (FILE* f = std::fopen((rt_dir_ + "/draft_vocab.bin").c_str(), "rb")) {+ std::fseek(f, 0, SEEK_END);+ const long size = std::ftell(f);+ std::fclose(f);+ if (size >= 4 && size % 4 == 0) bytes += (uint64_t) (size / 4) * head_row_bytes + (uint64_t) size;+ }+ }+ return bytes;+}+bool MtpDrafter::bind(const WeightTable &wt, const NativeHead *head,const float *window_R, std::string &err) try {const OnDevice on_device(device_);diff --git a/sycl/src/core/native_head.cpp b/sycl/src/core/native_head.cppindex a3924b65c..d03f972c9 100644--- a/sycl/src/core/native_head.cpp+++ b/sycl/src/core/native_head.cpp@@ -7,6 +7,7 @@#include "strata/kernels/native_mmvq.hpp"#include <climits>+#include <cstdio>#include <cstring>#include <exception>@@ -155,6 +156,8 @@ const NativeEmbed* native_embed() { return g_embed; }NativeEmbed::~NativeEmbed() {if (host_) sycl::free(host_, dpct::get_in_order_queue());+ else if (dev_)+ sycl::free((void *) dev_, dpct::get_in_order_queue()); // the VRAM fallback below}bool NativeEmbed::load(const std::string &path, int64_t n_embd, int64_t n_vocab,@@ -184,17 +187,48 @@ bool NativeEmbed::load(const std::string &path, int64_t n_embd, int64_t n_vocab,*/if (DPCT_CHECK_ERROR(host_ = (void *)sycl::malloc_host(bytes_, dpct::get_in_order_queue())) != 0) {+ // Under WSL2 the driver's pinned/mapped host budget (~1 GiB) can be spent by the GPU contexts+ // themselves (three cards). The table is only gathered from, so keep it in the current device's VRAM+ // instead: it costs its size there and reads faster than over PCIe.+ /*+ DPCT1026: The call to cudaGetLastError was removed because this+ functionality is redundant in SYCL.+ */host_ = nullptr;- err = "native embedding: cannot pin " + std::to_string(bytes_ >> 20) + " MiB";- return false;- }- std::memcpy(host_, gguf.tensor_data(*t), bytes_);- void* d = nullptr;- if (DPCT_CHECK_ERROR(d = (void *)host_) != 0) {- err = "native embedding: no device alias for the mapped table";- return false;+ void* d = nullptr;+ if (DPCT_CHECK_ERROR(d = (void *)sycl::malloc_device(+ bytes_, dpct::get_in_order_queue())) !=+ 0 ||+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization+ memcpy, assuming in the original code the source host memory is+ pageable memory. If the memory is not pageable, call wait() on+ event return by memcpy API to ensure synchronization behavior.+ */+ DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(+ d, gguf.tensor_data(*t), bytes_).wait()) != 0) {+ if (d) sycl::free(d, dpct::get_in_order_queue());+ /*+ DPCT1026: The call to cudaGetLastError was removed because+ this functionality is redundant in SYCL.+ */+ err = "native embedding: cannot pin " ++ std::to_string(bytes_ >> 20) ++ " MiB, nor place it in VRAM";+ return false;+ }+ std::fprintf(stderr, "strata: native embedding: cannot pin %llu MiB, kept in VRAM instead\n",+ (unsigned long long) (bytes_ >> 20));+ dev_ = d;+ } else {+ std::memcpy(host_, gguf.tensor_data(*t), bytes_);+ void* d = nullptr;+ if (DPCT_CHECK_ERROR(d = (void *)host_) != 0) {+ err = "native embedding: no device alias for the mapped table";+ return false;+ }+ dev_ = d;}- dev_ = d;type_ = (int) t->type;n_embd_ = n_embd;n_vocab_ = n_vocab;diff --git a/sycl/src/core/verify.cpp b/sycl/src/core/verify.cppindex 678059499..78124c78d 100644--- a/sycl/src/core/verify.cpp+++ b/sycl/src/core/verify.cpp@@ -167,7 +167,8 @@ bool Verifier::init(const WeightTable &wt, const ModelGeometry &g,return false;}if (hits.d_res == nullptr || hits.cache_base == nullptr || hits.blob <= 0) {- err = "verify: needs the profile-filled VRAM expert tier (--expert-profile and --expert-cache)";+ err = "verify: needs the profile-filled VRAM expert tier (--expert-profile and --expert-cache); with "+ "--expert-cache auto, no VRAM was left for it: lower --max-context, use --kv k8v4 or images on the CPU";return false;}std::string why;diff --git a/sycl/src/kernels/cuda/dequant_bf16.dp.cpp b/sycl/src/kernels/cuda/dequant_bf16.dp.cppindex 14da1e845..3f4e68a4f 100644--- a/sycl/src/kernels/cuda/dequant_bf16.dp.cpp+++ b/sycl/src/kernels/cuda/dequant_bf16.dp.cpp@@ -22,6 +22,9 @@ __dpct_inline__ float h2f(const uint8_t *p) {}__dpct_inline__ uint16_t f2bf(float f) {uint32_t u = sycl::bit_cast<unsigned int>(f);+ // a NaN (a NaN scale in the block) stays a quiet NaN, as in ggml_compute_fp32_to_bf16 and `bf16_from_f32`:+ // the rounding add below would carry it into -0 or inf+ if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64u);u += 0x7fffu + ((u >> 16) & 1u); // round to nearest evenreturn (uint16_t) (u >> 16);}@@ -226,7 +229,7 @@ void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t coauto gpr_ct4 = gpr; \auto out_ct5 = out; \\- cgh.parallel_for<dpct_kernel_name<class dequant_kernel_c70bbf, \+ cgh.parallel_for<dpct_kernel_name<class dequant_kernel_ec9311, \dpct_kernel_scalar<TY>, T>>( \sycl::nd_range<3>(sycl::range(1, 1, grid) * \sycl::range(1, 1, 256), \diff --git a/sycl/src/kernels/cuda/kv_stream.dp.cpp b/sycl/src/kernels/cuda/kv_stream.dp.cppindex d8118d42b..c3cc23f0b 100644--- a/sycl/src/kernels/cuda/kv_stream.dp.cpp+++ b/sycl/src/kernels/cuda/kv_stream.dp.cpp@@ -330,6 +330,14 @@ void kv_stream_resolve(const KvStreamMap& m, const QsaAttnPools& slots, const Kvstd::fprintf(stderr, "kv_stream: a block's scale run must be a multiple of 16 bytes\n");std::exit(1);}+ // one sweep step looks at RT consecutive slots `(hand + thread) % n_slots`; with fewer slots than RT two+ // threads see the same slot and may both take it for two different misses. The engine never streams with fewer+ // than qsa_kv_resident_min() / page_size = 5,120 slots, so this is a guard, not a limit.+ if (m.n_slots < RT) {+ std::fprintf(stderr, "kv_stream: %lld slots is fewer than the resolve block (%d): the clock sweep would take a "+ "slot twice\n", (long long) m.n_slots, RT);+ std::exit(1);+ }/*DPCT1049: The work-group size passed to the SYCL kernel may exceed thelimit. To get the device limit, query info::device::max_work_group_size.@@ -340,7 +348,7 @@ void kv_stream_resolve(const KvStreamMap& m, const QsaAttnPools& slots, const Kvsycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class resolve_kernel_d27792>>(+ ->parallel_for<dpct_kernel_name<class resolve_kernel_148a81>>(sycl::nd_range<3>(sycl::range(1, 1, RT), sycl::range(1, 1, RT)),exp_props,[=](sycl::nd_item<3> item_ct1)@@ -359,7 +367,7 @@ void kv_stream_resolve(const KvStreamMap& m, const QsaAttnPools& slots, const Kvauto runs_of_slots_host_fmt_s_ct1 =runs_of(slots, host, fmt, s);- cgh.parallel_for<dpct_kernel_name<class copy_kernel_e47935>>(+ cgh.parallel_for<dpct_kernel_name<class copy_kernel_4bb253>>(sycl::nd_range<3>(sycl::range(1, 1, 96) *sycl::range(1, 1, 128),sycl::range(1, 1, 128)),@@ -377,7 +385,7 @@ void kv_ring_table(int32_t* page_table, int64_t n_blocks, int64_t n_slots, void*sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class ring_kernel_728502>>(+ ->parallel_for<dpct_kernel_name<class ring_kernel_f9df1d>>(sycl::nd_range<3>(sycl::range(1, 1, 64) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),diff --git a/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp b/sycl/src/kernels/cuda/qsa_decode_attn.dp.cppindex 0caac0219..39981a32c 100644--- a/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp+++ b/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp@@ -164,7 +164,9 @@ attn_chunk_kernel(const float *__restrict__ q, QsaAttnPools p,if (t < n_here) {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);+ // a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked+ // (score -FLT_MAX, weight 0) instead of being read from before the pool.+ if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);}srow[t] = r;}@@ -176,7 +178,7 @@ attn_chunk_kernel(const float *__restrict__ q, QsaAttnPools p,item_ct1.barrier();// scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions.for (int c = warp; c < CHUNK; c += WARPS) {- if (c >= n_here) {+ if (c >= n_here || srow[c] < 0) {if (lane < G) sp[lane][c] = -FLT_MAX;continue;}@@ -205,8 +207,12 @@ attn_chunk_kernel(const float *__restrict__ q, QsaAttnPools p,for (int h = warp; h < G; h += WARPS) {const float a = sp[h][lane], b = sp[h][lane + 32];const float m = warp_max(sycl::fmax(a, b));- const float ea = (lane < n_here) ? sycl::native::exp(a - m) : 0.0f;- const float eb = (lane + 32 < n_here) ? sycl::native::exp(b - m) : 0.0f;+ const float ea = (lane < n_here && srow[lane] >= 0)+ ? sycl::native::exp(a - m)+ : 0.0f;+ const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0)+ ? sycl::native::exp(b - m)+ : 0.0f;sp[h][lane] = ea;sp[h][lane + 32] = eb;const float l = warp_sum(ea + eb);@@ -223,6 +229,7 @@ attn_chunk_kernel(const float *__restrict__ q, QsaAttnPools p,#pragma unrollfor (int h = 0; h < G; ++h) acc[h] = 0.0f;for (int c = 0; c < n_here; ++c) {+ if (srow[c] < 0) continue; // masked above, weight 0float v;if constexpr (KV_MODE == 0) {v = sycl::vec<sycl::half, 1>(@@ -317,7 +324,7 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3sycl::ext::oneapi::experimental::use_root_sync};dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});- st->parallel_for<dpct_kernel_name<class attn_chunk_kernel_b8af5b,+ st->parallel_for<dpct_kernel_name<class attn_chunk_kernel_dfacfc,dpct_kernel_scalar<3>>>(sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),@@ -333,7 +340,7 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3sycl::ext::oneapi::experimental::use_root_sync};dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});- st->parallel_for<dpct_kernel_name<class attn_chunk_kernel_dfacfc,+ st->parallel_for<dpct_kernel_name<class attn_chunk_kernel_b0d448,dpct_kernel_scalar<2>>>(sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),@@ -349,7 +356,7 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3sycl::ext::oneapi::experimental::use_root_sync};dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});- st->parallel_for<dpct_kernel_name<class attn_chunk_kernel_b0d448,+ st->parallel_for<dpct_kernel_name<class attn_chunk_kernel_2ad0a4,dpct_kernel_scalar<1>>>(sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),@@ -364,7 +371,7 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3sycl::ext::oneapi::experimental::use_root_sync};dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});- st->parallel_for<dpct_kernel_name<class attn_chunk_kernel_2ad0a4,+ st->parallel_for<dpct_kernel_name<class attn_chunk_kernel_5c04f7,dpct_kernel_scalar<0>>>(sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),@@ -379,7 +386,7 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- st->parallel_for<dpct_kernel_name<class attn_merge_kernel_b5c617>>(+ st->parallel_for<dpct_kernel_name<class attn_merge_kernel_2cdaf7>>(sycl::nd_range<3>(sycl::range(1, (unsigned)n_q, (unsigned)s.n_head) *sycl::range(1, 1, HD),@@ -430,7 +437,7 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32sycl::ext::oneapi::experimental::use_root_sync};dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});- st->parallel_for<dpct_kernel_name<class attn_chunk_kernel_61a169,+ st->parallel_for<dpct_kernel_name<class attn_chunk_kernel_f262e6,dpct_kernel_scalar<3>>>(sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),@@ -446,7 +453,7 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32sycl::ext::oneapi::experimental::use_root_sync};dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});- st->parallel_for<dpct_kernel_name<class attn_chunk_kernel_f262e6,+ st->parallel_for<dpct_kernel_name<class attn_chunk_kernel_4fd923,dpct_kernel_scalar<2>>>(sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),@@ -462,7 +469,7 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32sycl::ext::oneapi::experimental::use_root_sync};dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});- st->parallel_for<dpct_kernel_name<class attn_chunk_kernel_4fd923,+ st->parallel_for<dpct_kernel_name<class attn_chunk_kernel_f6855e,dpct_kernel_scalar<1>>>(sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),@@ -477,7 +484,7 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32sycl::ext::oneapi::experimental::use_root_sync};dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});- st->parallel_for<dpct_kernel_name<class attn_chunk_kernel_f6855e,+ st->parallel_for<dpct_kernel_name<class attn_chunk_kernel_7c8e09,dpct_kernel_scalar<0>>>(sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),@@ -492,7 +499,7 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- st->parallel_for<dpct_kernel_name<class attn_merge_kernel_a9568f>>(+ st->parallel_for<dpct_kernel_name<class attn_merge_kernel_4bb902>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)s.n_head) *sycl::range(1, 1, HD),sycl::range(1, 1, HD)),diff --git a/sycl/src/kernels/cuda/qsa_select.dp.cpp b/sycl/src/kernels/cuda/qsa_select.dp.cppindex 91ef8f695..9a195a20d 100644--- a/sycl/src/kernels/cuda/qsa_select.dp.cpp+++ b/sycl/src/kernels/cuda/qsa_select.dp.cpp@@ -675,6 +675,89 @@ auto &hist =}}++// Block scores with every key block read ONCE for all of a call's queries (block_scores_kernel's grid is+// (max_blocks / 8) x nq: ~24,600 mostly-idle blocks per layer at a decode window, each key re-read per query). A fixed+// grid strides over the blocks; per (block, query) the same arithmetic in the same order as block_scores_kernel.+// qsa_block_scores takes it for every call without an active-block count and at most MQ queries: the captured decode+// window, the uncaptured decode, and prefill's pooled16 call.+constexpr int MQ = 8;+/*+DPCT1110: The total declared local variable size in device function+block_scores_multi_kernel exceeds 128 bytes and may cause high register+pressure. Consult with your hardware vendor to find the total register size+available and adjust the code, or use smaller sub-group size to avoid high+register pressure.+*/+__dpct_inline__ void block_scores_multi_kernel(+ const float *__restrict__ pooled, const float *__restrict__ dead,+ const float *__restrict__ q_idx, const int32_t *__restrict__ steps, int nq,+ int64_t max_blocks, float *__restrict__ out) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+auto &qs = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ float[MQ * IDX_HEADS * IDX_DIM]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &s_nkv =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<int64_t[MQ]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &s_nbid =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<int64_t[MQ]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+#pragma unroll+ for (int i = item_ct1.get_local_id(2); i < nq * IDX_HEADS * IDX_DIM;+ i += item_ct1.get_local_range(2)) qs[i] = q_idx[i];+ if (item_ct1.get_local_id(2) < nq) {+ s_nkv[item_ct1.get_local_id(2)] =+ steps[item_ct1.get_local_id(2) * kStepCount + kStepNKv];+ s_nbid[item_ct1.get_local_id(2)] =+ steps[item_ct1.get_local_id(2) * kStepCount + kStepNBid];+ }+ item_ct1.barrier(sycl::access::fence_space::local_space);+ int64_t top = 0;+#pragma unroll+ for (int q = 0; q < nq; ++q) top = s_nbid[q] > top ? s_nbid[q] : top;+ const int lane = item_ct1.get_local_id(2) & 31;+ const int64_t wstride = (int64_t)item_ct1.get_group_range(2) * SCORE_WARPS;+ for (int64_t b = (int64_t)item_ct1.get_group(2) * SCORE_WARPS ++ (item_ct1.get_local_id(2) >> 5);+ b <= top && b < max_blocks; b += wstride) {+ const sycl::float4 kp = *reinterpret_cast<const sycl::float4 *>(+ pooled + b * IDX_DIM + lane * 4);+ const sycl::float4 kd =+ *reinterpret_cast<const sycl::float4 *>(dead + lane * 4);+ for (int qi = 0; qi < nq; ++qi) {+ const int64_t n_bid = s_nbid[qi];+ if (b > n_bid) continue;+ const sycl::float4 k4 = (b == n_bid) ? kd : kp;+ const float* q = qs + qi * IDX_HEADS * IDX_DIM + lane * 4;+ float score = 0.0f;+#pragma unroll+ for (int h = 0; h < IDX_HEADS; ++h) {+ const sycl::float4 q4 =+ *reinterpret_cast<const sycl::float4 *>(q + h * IDX_DIM);+ float d = k4.x() * q4.x() + k4.y() * q4.y() + k4.z() * q4.z() ++ k4.w() * q4.w();+#pragma unroll+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the+ experimental feature masked sub_group function which may not be+ supported by all compilers or runtimes. You may need to adjust+ the code.+ */+ for (int o = 16; o > 0; o >>= 1) d +=+ dpct::experimental::permute_sub_group_by_xor(+ 0xffffffffu,+ sycl::ext::oneapi::this_work_item::get_sub_group(), d,+ o);+ score += d > 0.0f ? d : 0.0f;+ }+ if (lane == 0) {+ if (b == n_bid && s_nkv[qi] % R != 0) score += 1e9f;+ out[qi * max_blocks + b] = score;+ }+ }+ }+}} // namespacevoid qsa_block_scores(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq,@@ -685,6 +768,40 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idxstd::exit(1);}// a block past a query's n_bid returns at once: the grid need only reach the batch's largest n_bid (C-1)+ static const bool multi = [] { const char* v = std::getenv("STRATA_SCORES_MULTI"); return v == nullptr || std::atoi(v) != 0; }();+ if (multi && nq <= MQ && active_blocks <= 0) { // no active count: decode (captured or not) and prefill's pooled16+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<+ dpct_kernel_name<class block_scores_multi_kernel_dea7d4>>(+ sycl::nd_range<3>(sycl::range(1, 1, 256) *+ sycl::range(1, 1, SCORE_WARPS * 32),+ sycl::range(1, 1, SCORE_WARPS * 32)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ block_scores_multi_kernel(pooled, dead, q_idx,+ steps, (int)nq,+ max_blocks, scores);+ });+ }+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use the+ error codes. The cudaGetLastError function call was replaced with 0. You+ need to rewrite this code.+ */+ const dpct::err0 e = 0;+ /*+ 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.+ */++ return;+ }const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;const dpct::dim3 grid((unsigned)((reach + SCORE_WARPS - 1) / SCORE_WARPS),(unsigned)nq);@@ -693,7 +810,7 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idxsycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class block_scores_kernel_6f5935>>(+ ->parallel_for<dpct_kernel_name<class block_scores_kernel_925c9d>>(sycl::nd_range<3>(grid * sycl::range(1, 1, SCORE_WARPS * 32),sycl::range(1, 1, SCORE_WARPS * 32)),exp_props,@@ -788,7 +905,7 @@ bool qsa_block_scores_tc(const float *pooled, const float *dead,sycl::range(bytes), cgh);cgh.parallel_for<- dpct_kernel_name<class block_scores_tc_kernel_f08b24>>(+ dpct_kernel_name<class block_scores_tc_kernel_bc5f07>>(sycl::nd_range<3>(grid * sycl::range(1, 1, 128),sycl::range(1, 1, 128)),exp_props, [=](sycl::nd_item<3> item_ct1) {@@ -806,7 +923,7 @@ bool qsa_block_scores_tc(const float *pooled, const float *dead,strata::q_of(stream)->parallel_for<- dpct_kernel_name<class block_scores_tail_kernel_8303e7>>(+ dpct_kernel_name<class block_scores_tail_kernel_70dfaa>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)nq) *sycl::range(1, 1, 32),sycl::range(1, 1, 32)),@@ -849,7 +966,7 @@ void qsa_block_topk_ref(const float* scores, const int32_t* steps, int64_t nq, isycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class block_topk_kernel_409264>>(+ ->parallel_for<dpct_kernel_name<class block_topk_kernel_213104>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)nq) *sycl::range(1, 1, TOPK_T),sycl::range(1, 1, TOPK_T)),@@ -895,7 +1012,7 @@ void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64strata::q_of(stream)->parallel_for<- dpct_kernel_name<class block_topk_reg_kernel_a867d1>>(+ dpct_kernel_name<class block_topk_reg_kernel_652097>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)nq) *sycl::range(1, 1, TK_T),sycl::range(1, 1, TK_T)),diff --git a/sycl/src/kernels/cuda/s2_expert_grouped.dp.cpp b/sycl/src/kernels/cuda/s2_expert_grouped.dp.cppindex 0098de164..5b76ff016 100644--- a/sycl/src/kernels/cuda/s2_expert_grouped.dp.cpp+++ b/sycl/src/kernels/cuda/s2_expert_grouped.dp.cpp@@ -21,6 +21,7 @@#include "strata/kernels/s2_expert_grouped.hpp"#include "strata/kernels/quantize_act.hpp"+#include "strata/kernels/verify_kernels.hpp"#include <cstdio>#include <cstdlib>@@ -499,7 +500,7 @@ void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, conauto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- cs->parallel_for<dpct_kernel_name<class gu_kernel_feb5f7>>(+ cs->parallel_for<dpct_kernel_name<class gu_kernel_7c8537>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) *sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),@@ -521,7 +522,7 @@ void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, conauto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- cs->parallel_for<dpct_kernel_name<class swiglu_kernel_6bd648>>(+ cs->parallel_for<dpct_kernel_name<class swiglu_kernel_30a435>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) *sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),@@ -550,7 +551,7 @@ void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, conconst float *x_scales_nullptr_h_scales_nullptr_ct5 =x_scales != nullptr ? h_scales : nullptr;- cgh.parallel_for<dpct_kernel_name<class down_kernel_6b2ba9>>(+ cgh.parallel_for<dpct_kernel_name<class down_kernel_b856bc>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) *sycl::range(1, 1, THREADS),sycl::range(1, 1, THREADS)),@@ -666,7 +667,7 @@ void moe_hit_select(const int32_t* ids, const int32_t* res_row, int k, int n_expsycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class hit_select_kernel_62d6cd>>(+ ->parallel_for<dpct_kernel_name<class hit_select_kernel_f87f42>>(sycl::nd_range<3>(sycl::range(1, 1, 32), sycl::range(1, 1, 32)),exp_props,[=](sycl::nd_item<3> item_ct1)@@ -695,7 +696,7 @@ void moe_hit_grouped_s2_dev(const uint8_t* blob_base, const int32_t* slot_index,auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- cs->parallel_for<dpct_kernel_name<class gu_kernel_fd0f96>>(+ cs->parallel_for<dpct_kernel_name<class gu_kernel_e0f313>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)((rows + warps - 1) / warps)) *sycl::range(1, 1, THREADS),@@ -716,7 +717,7 @@ void moe_hit_grouped_s2_dev(const uint8_t* blob_base, const int32_t* slot_index,auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- cs->parallel_for<dpct_kernel_name<class swiglu_kernel_40adf2>>(+ cs->parallel_for<dpct_kernel_name<class swiglu_kernel_e17ecb>>(sycl::nd_range<3>(sycl::range(1, 1,(unsigned)((pairs + THREADS - 1) / THREADS)) *@@ -740,7 +741,7 @@ void moe_hit_grouped_s2_dev(const uint8_t* blob_base, const int32_t* slot_index,const float *x_scales_nullptr_h_scales_nullptr_ct5 =x_scales != nullptr ? h_scales : nullptr;- cgh.parallel_for<dpct_kernel_name<class down_kernel_e2a4a9>>(+ cgh.parallel_for<dpct_kernel_name<class down_kernel_bd8167>>(sycl::nd_range<3>(sycl::range(1, 1,(unsigned)((rows + warps - 1) / warps)) *@@ -769,7 +770,7 @@ void moe_hit_select_multi(const int32_t* ids, const int32_t* res_row, int n, intstrata::q_of(stream)->parallel_for<- dpct_kernel_name<class hit_select_multi_kernel_a381b5>>(+ dpct_kernel_name<class hit_select_multi_kernel_4749ea>>(sycl::nd_range<3>(sycl::range(1, 1, 128),sycl::range(1, 1, 128)),exp_props,@@ -799,7 +800,7 @@ void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_indeauto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- cs->parallel_for<dpct_kernel_name<class gu_kernel_583c8a>>(+ cs->parallel_for<dpct_kernel_name<class gu_kernel_30a25d>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)((rows + warps - 1) / warps)) *sycl::range(1, 1, THREADS),@@ -820,7 +821,7 @@ void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_indeauto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- cs->parallel_for<dpct_kernel_name<class swiglu_kernel_f4e4db>>(+ cs->parallel_for<dpct_kernel_name<class swiglu_kernel_3a6551>>(sycl::nd_range<3>(sycl::range(1, 1,(unsigned)((pairs + THREADS - 1) / THREADS)) *@@ -844,7 +845,7 @@ void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_indeconst float *x_scales_nullptr_h_scales_nullptr_ct5 =x_scales != nullptr ? h_scales : nullptr;- cgh.parallel_for<dpct_kernel_name<class down_kernel_1ae146>>(+ cgh.parallel_for<dpct_kernel_name<class down_kernel_a919b8>>(sycl::nd_range<3>(sycl::range(1, 1,(unsigned)((rows + warps - 1) / warps)) *@@ -871,6 +872,9 @@ namespace {// hit kernel's.constexpr int GU_CHUNKS = (H / 32 + 31) / 32; // 3: chunks of a gate/up row per lane (80 chunks / 32 lanes)constexpr int GMAX = 8; // entries per group (tokens routed to one expert in a window)+// a group holds one entry per token of the window routed to its expert, and the kernels below keep at+// most GMAX of them (`min(..., GMAX)`): a longer window would drop entries without a word.+static_assert(GMAX >= kVerifyMaxT, "a verify window's group can exceed GMAX entries");constexpr int GU_ROWS = 32; // gate/up rows per block: 4 per warpconstexpr int D_ROWS = 64; // down rows per block: 8 per warp@@ -1094,7 +1098,7 @@ void moe_group_resident(const int32_t* ids, int n, int k_per_tok, const uint8_t*strata::q_of(stream)->parallel_for<- dpct_kernel_name<class group_resident_kernel_937b58>>(+ dpct_kernel_name<class group_resident_kernel_5c38b8>>(sycl::nd_range<3>(sycl::range(1, 1, 128),sycl::range(1, 1, 128)),exp_props, [=](sycl::nd_item<3> item_ct1) {@@ -1121,7 +1125,7 @@ void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start,auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- cs->parallel_for<dpct_kernel_name<class gu_grouped_kernel_393d46>>(+ cs->parallel_for<dpct_kernel_name<class gu_grouped_kernel_c9eb4d>>(sycl::nd_range<3>(sycl::range(1, (unsigned)cap_groups,(unsigned)(2 * FF / GU_ROWS)) *sycl::range(1, 1, 256),@@ -1142,7 +1146,7 @@ void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start,auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- cs->parallel_for<dpct_kernel_name<class swiglu_kernel_2292bf>>(+ cs->parallel_for<dpct_kernel_name<class swiglu_kernel_5018f2>>(sycl::nd_range<3>(sycl::range(1, 1,(unsigned)((pairs + THREADS - 1) / THREADS)) *@@ -1166,7 +1170,7 @@ void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start,x_scales != nullptr ? h_scales : nullptr;cgh.parallel_for<- dpct_kernel_name<class down_grouped_kernel_f03334>>(+ dpct_kernel_name<class down_grouped_kernel_ea4417>>(sycl::nd_range<3>(sycl::range(1, (unsigned)cap_groups,(unsigned)(H / D_ROWS)) *sycl::range(1, 1, 256),@@ -1195,7 +1199,7 @@ void moe_hit_add(float* parts, const float* hit_out, const int32_t* dst, const isycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class add_hits_kernel_9d7642>>(+ ->parallel_for<dpct_kernel_name<class add_hits_kernel_50cbcb>>(sycl::nd_range<3>(grid * sycl::range(1, 1, 256),sycl::range(1, 1, 256)),exp_props, [=](sycl::nd_item<3> item_ct1) {@@ -1234,7 +1238,7 @@ void moe_hit_grouped_s2_cpu_order(const uint8_t *blob_base,auto H_ct3 = H / 32;cgh.parallel_for<- dpct_kernel_name<class activation_correction_kernel_f8a161>>(+ dpct_kernel_name<class activation_correction_kernel_ca15a9>>(sycl::nd_range<3>(sycl::range(1, 1, (H / 32 + THREADS - 1) / THREADS) *sycl::range(1, 1, THREADS),@@ -1251,7 +1255,7 @@ void moe_hit_grouped_s2_cpu_order(const uint8_t *blob_base,sycl::ext::oneapi::experimental::use_root_sync};cs->parallel_for<- dpct_kernel_name<class cpu_order_projection_kernel_ca15a9,+ dpct_kernel_name<class cpu_order_projection_kernel_6ed29b,dpct_kernel_scalar<false>>>(sycl::nd_range<3>(sycl::range(1, 1,@@ -1287,7 +1291,7 @@ void moe_hit_grouped_s2_cpu_order(const uint8_t *blob_base,auto int_n_hits_FF_ct1 = (int)n_hits * FF;cgh.parallel_for<- dpct_kernel_name<class cpu_order_swiglu_kernel_883f7b>>(+ dpct_kernel_name<class cpu_order_swiglu_kernel_4d84ce>>(sycl::nd_range<3>(sycl::range(1, 1,@@ -1308,7 +1312,7 @@ void moe_hit_grouped_s2_cpu_order(const uint8_t *blob_base,auto int_n_hits_FF_ct4 = (int)n_hits * (FF / 32);cgh.parallel_for<- dpct_kernel_name<class cpu_order_quantize_kernel_813a16>>(+ dpct_kernel_name<class cpu_order_quantize_kernel_7d1393>>(sycl::nd_range<3>(sycl::range(1, 1,(unsigned)((n_hits * (FF / 32) + THREADS - 1) /@@ -1327,7 +1331,7 @@ void moe_hit_grouped_s2_cpu_order(const uint8_t *blob_base,sycl::ext::oneapi::experimental::use_root_sync};cs->parallel_for<- dpct_kernel_name<class cpu_order_projection_kernel_7f4897,+ dpct_kernel_name<class cpu_order_projection_kernel_c67875,dpct_kernel_scalar<true>>>(sycl::nd_range<3>(sycl::range(1, 1,diff --git a/sycl/src/kernels/cuda/s_gemv.dp.cpp b/sycl/src/kernels/cuda/s_gemv.dp.cppindex 64eb51317..98b4d00cf 100644--- a/sycl/src/kernels/cuda/s_gemv.dp.cpp+++ b/sycl/src/kernels/cuda/s_gemv.dp.cpp@@ -175,17 +175,23 @@ __dpct_inline__ void s_gemv_q8_split_kernel(const int warps_per_block = (int)(item_ct1.get_local_range(2) >> 5);const long long o = (long long)item_ct1.get_group(2) * warps_per_block +(item_ct1.get_local_id(2) >> 5);- if (o >= n_out) return;const int lane = item_ct1.get_local_id(2) & 31;// THE CODEBOOK, IN SHARED MEMORY. 16 bytes, loaded once per block by the first 16 threads, instead of a// divergent constant read per element - measured at 2.12x of this whole kernel (see the note on `kIq4Nl`).+ //+ // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN, as in `s_gemv_q8k_kernel`. The return used to+ // sit above them, so whenever `n_out % 8 != 0` the last block's surplus warps left before a barrier the+ // others still waited at - undefined behaviour that every shape in the pack (a multiple of 8) happened to+ // avoid. `o` is per-WARP, so the return below keeps whole warps together and the shuffle reduction's+ // full mask stays valid.auto &s_iq4nl =*sycl::ext::oneapi::group_local_memory_for_overwrite<signed char[16]>(sycl::ext::oneapi::this_work_item::get_work_group<3>());if (item_ct1.get_local_id(2) < 16) s_iq4nl[item_ct1.get_local_id(2)] =kIq4Nl[item_ct1.get_local_id(2)];item_ct1.barrier(sycl::access::fence_space::local_space);+ if (o >= n_out) return;const long long n_groups = n_in >> group_shift;const long long codes_per_row = n_in / PER_BYTE;@@ -416,7 +422,7 @@ void s_gemv(const uint16_t *x, const uint8_t *codes, const float *scales,sycl::ext::oneapi::experimental::use_root_sync};dpct::get_in_order_queue()- .parallel_for<dpct_kernel_name<class s_gemv_kernel_2c435c,+ .parallel_for<dpct_kernel_name<class s_gemv_kernel_4f63f9,dpct_kernel_scalar<2>>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)blocks) *sycl::range(1, 1, threads),@@ -432,7 +438,7 @@ void s_gemv(const uint16_t *x, const uint8_t *codes, const float *scales,sycl::ext::oneapi::experimental::use_root_sync};dpct::get_in_order_queue()- .parallel_for<dpct_kernel_name<class s_gemv_kernel_1b4b21,+ .parallel_for<dpct_kernel_name<class s_gemv_kernel_9c529a,dpct_kernel_scalar<4>>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)blocks) *sycl::range(1, 1, threads),@@ -448,7 +454,7 @@ void s_gemv(const uint16_t *x, const uint8_t *codes, const float *scales,sycl::ext::oneapi::experimental::use_root_sync};dpct::get_in_order_queue()- .parallel_for<dpct_kernel_name<class s_gemv_kernel_c5017e,+ .parallel_for<dpct_kernel_name<class s_gemv_kernel_e40e1f,dpct_kernel_scalar<8>>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)blocks) *sycl::range(1, 1, threads),@@ -656,7 +662,7 @@ static void s_gemv_split_impl(const uint16_t *x, const uint8_t *codes,sycl::range(smem), cgh);cgh.parallel_for<dpct_kernel_name<- class s_gemv_split_kernel_51319d, dpct_kernel_scalar<2>>>(+ class s_gemv_split_kernel_8538ef, dpct_kernel_scalar<2>>>(sycl::nd_range<3>(sycl::range(1, 1, grid) *sycl::range(1, 1, threads_per_row),sycl::range(1, 1, threads_per_row)),@@ -690,7 +696,7 @@ static void s_gemv_split_impl(const uint16_t *x, const uint8_t *codes,sycl::range(smem), cgh);cgh.parallel_for<dpct_kernel_name<- class s_gemv_split_kernel_36431d, dpct_kernel_scalar<4>>>(+ class s_gemv_split_kernel_6cb7af, dpct_kernel_scalar<4>>>(sycl::nd_range<3>(sycl::range(1, 1, grid) *sycl::range(1, 1, threads_per_row),sycl::range(1, 1, threads_per_row)),@@ -724,7 +730,7 @@ static void s_gemv_split_impl(const uint16_t *x, const uint8_t *codes,sycl::range(smem), cgh);cgh.parallel_for<dpct_kernel_name<- class s_gemv_split_kernel_377b5e, dpct_kernel_scalar<8>>>(+ class s_gemv_split_kernel_63886c, dpct_kernel_scalar<8>>>(sycl::nd_range<3>(sycl::range(1, 1, grid) *sycl::range(1, 1, threads_per_row),sycl::range(1, 1, threads_per_row)),@@ -822,7 +828,7 @@ void s_gemv_q8k(const uint8_t* x_q8k, const uint8_t* codes, const float* scales,sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class s_gemv_q8k_kernel_6a05ad,+ ->parallel_for<dpct_kernel_name<class s_gemv_q8k_kernel_9b1637,dpct_kernel_scalar<4>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) *sycl::range(1, 1, threads),@@ -838,7 +844,7 @@ void s_gemv_q8k(const uint8_t* x_q8k, const uint8_t* codes, const float* scales,sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class s_gemv_q8k_kernel_c8cb93,+ ->parallel_for<dpct_kernel_name<class s_gemv_q8k_kernel_adeed5,dpct_kernel_scalar<8>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) *sycl::range(1, 1, threads),@@ -889,7 +895,7 @@ void s_gemv_q8k_split(const uint8_t* x_q8k, const uint8_t* codes, const float* ssycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class s_gemv_q8_split_kernel_c3278e,+ ->parallel_for<dpct_kernel_name<class s_gemv_q8_split_kernel_19ad26,dpct_kernel_scalar<4>,dpct_kernel_scalar<true>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) *@@ -908,7 +914,7 @@ void s_gemv_q8k_split(const uint8_t* x_q8k, const uint8_t* codes, const float* ssycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class s_gemv_q8_split_kernel_7d9a26,+ ->parallel_for<dpct_kernel_name<class s_gemv_q8_split_kernel_4da4f5,dpct_kernel_scalar<8>,dpct_kernel_scalar<true>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) *@@ -946,8 +952,10 @@ void s_gemv_q8_0_split(const uint8_t* x_q8_0, const uint8_t* codes, const float*form.group_elems);std::exit(1);}- if (form.group_elems % 4 != 0) {- std::fprintf(stderr, "s_gemv_q8_0_split: group_elems %d is not a multiple of 4\n", form.group_elems);+ // SIXTEEN, NOT FOUR: a lane-iteration takes QE = 16 consecutive elements under ONE scale (see the kernel),+ // so a group of 4 or 8 would read the wrong scale for most of them. The Q8_K launcher already said 16.+ if (form.group_elems % 16 != 0) {+ std::fprintf(stderr, "s_gemv_q8_0_split: group_elems %d is not a multiple of 16\n", form.group_elems);std::exit(1);}int group_shift = 0;@@ -964,7 +972,7 @@ void s_gemv_q8_0_split(const uint8_t* x_q8_0, const uint8_t* codes, const float*sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class s_gemv_q8_split_kernel_ee83d2,+ ->parallel_for<dpct_kernel_name<class s_gemv_q8_split_kernel_147ee4,dpct_kernel_scalar<4>,dpct_kernel_scalar<false>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) *@@ -983,7 +991,7 @@ void s_gemv_q8_0_split(const uint8_t* x_q8_0, const uint8_t* codes, const float*sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class s_gemv_q8_split_kernel_47112d,+ ->parallel_for<dpct_kernel_name<class s_gemv_q8_split_kernel_bac5c0,dpct_kernel_scalar<8>,dpct_kernel_scalar<false>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks) *diff --git a/sycl/src/kernels/cuda/sampler.dp.cpp b/sycl/src/kernels/cuda/sampler.dp.cppindex df94e4afa..e438ca877 100644--- a/sycl/src/kernels/cuda/sampler.dp.cpp+++ b/sycl/src/kernels/cuda/sampler.dp.cpp@@ -10,9 +10,14 @@// produces a valid token, so only a comparison at the distribution level can tell them apart; the parity test// does that against an independently computed distribution.//-// Both kernels put ONE BLOCK per token over the vocabulary: `sampler_greedy_kernel` is the plain argmax,-// `sampler_kernel` runs the sampled chain as `top_k` block-argmax rounds followed by the top_p / temperature /-// draw chain (its header says why the selection must be parallel and why the tie rule keeps the semantics).+// `sampler_greedy_kernel` is the plain argmax, one block per token over the vocabulary. The sampled chain has+// three implementations that pick the same token, bit for bit:+// - the SPLIT top_k (default): `sampler_split_part_kernel` cuts each row into 4,096-logit blocks over the whole+// GPU, each keeps its own top_k, and `sampler_split_merge_kernel` merges those lists and runs the tail;+// - `sampler_one_block_kernel` (`STRATA_SAMPLER_ONE_BLOCK=1`, and the fallback when the split cannot run): one+// block per token, `top_k` block-argmax rounds, each over the logits after the previous pick;+// - `sampler_kernel` (`STRATA_OLD_SAMPLER=1`), the kernel of engine 0.1.20, kept as the reference.+// The two new ones share `sampled_tail_warp` (top_p / min_p / temperature / draw on one warp).#define DPCT_PROFILING_ENABLED#include <sycl/sycl.hpp>#include <dpct/dpct.hpp>@@ -22,6 +27,9 @@#include <cmath>#include <cstdio>#include <cstdlib>+#include <cstring>+#include <mutex>+#include <vector>namespace strata::kernels {namespace {@@ -226,6 +234,11 @@ sampler_greedy_kernel(const float *__restrict__ logits, int n_vocab,/// serial scan's strict `>` keeps the first maximum it meets), so the kept sequence - both its set and its/// order - is unchanged; `top_p`'s cut reads that order in double arithmetic as before; temperature and the/// Philox draw apply after the cut. `sampler_parity` pins all of it against the host reference.+///+/// **KEPT AS THE REFERENCE, BEHIND `STRATA_OLD_SAMPLER=1`.** Two costs remain in it: the `taken`+/// sweep is O(k) per logit per round, O(k^2 x n_vocab) per row (47 M shared-memory compares at k = 20, 500 M at+/// 64), and the double-precision tail runs on all 1,024 threads where one warp suffices - GeForce issues FP64 at+/// 1/64 of FP32. The kernels after this one remove both and select the same list in the same order./*DPCT1110: The total declared local variable size in device functionsampler_kernel exceeds 128 bytes and may cause high register pressure. Consult@@ -443,6 +456,641 @@ __dpct_inline__ void sampler_kernel(const float *__restrict__ logits,if (item_ct1.get_local_id(2) == 0) out[t] = pick;}+// ---- the same list, in the same order, without the `taken` sweep ----+//+// THE SELECTION ORDER. `sampler_kernel`'s rounds rank a candidate (value, id) before (value', id') when value >+// value', or value == value' and id < id' - each thread's ascending scan keeps the first maximum it meets (strict+// `>`), and the reductions resolve a tie to the lower id. That is a strict total order (-0 and +0 compare equal and+// fall to the id, as there), so round i picks the i-th logit of the order. NaN and -inf are never picked (`s > bv`+// from -inf fails); a round that finds nothing yields the SENTINEL (-inf, n_vocab), stored as id 0.++constexpr int kSelMax = 64; // the widest top_k list, `sampler_kernel`'s KMAX+constexpr unsigned kFullMask = 0xFFFFFFFFu;++// top_k 1..64 as given; 0 ("off") and anything wider keep 64; never more than the vocabulary+__dpct_inline__ int sampled_k(int top_k, int n_vocab) {+ int k = (top_k > 0 && top_k < kSelMax) ? top_k : kSelMax;+ return k > n_vocab ? n_vocab : k;+}++// (bv, bi) <- the first of (bv, bi) and (ov, oi) in the selection order+__dpct_inline__ void take_first(float &bv, int &bi, float ov, int oi) {+ if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }+}++// The first of the warp's 32 candidates, left in EVERY lane. An XOR butterfly is exact here: "the first of two" is+// associative and commutative in a strict total order (two lanes never hold different candidates that compare+// equal - an id is in one lane at most, and two sentinels are the same pair), so every lane ends with the same pair.+__dpct_inline__ void warp_first(float &bv, int &bi) {+#pragma unroll+ for (int off = 16; off > 0; off >>= 1) {+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ const float ov = dpct::experimental::permute_sub_group_by_xor(+ kFullMask, sycl::ext::oneapi::this_work_item::get_sub_group(), bv,+ off);+ /*+ DPCT1108: '__shfl_xor_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ const int oi = dpct::experimental::permute_sub_group_by_xor(+ kFullMask, sycl::ext::oneapi::this_work_item::get_sub_group(), bi,+ off);+ take_first(bv, bi, ov, oi);+ }+}++/// **THE TAIL ON ONE WARP, WITH `sampler_kernel`'S ARITHMETIC.** `sel_ids` / `sel_logit` (shared, `k` entries) are+/// the top_k list in selection order; the 32 lanes of one warp call this and lane 0 writes `out[t]`. The old tail+/// ran on all 1,024 threads, each computing the same ~4k double `exp`s - FP64 issues at 1/64 of FP32 on GeForce.+/// Here the lanes share the `exp`s (one per entry, into `ex`) and then the quotients, and lane 0 alone runs the two+/// ORDERED sums and the two cumulative scans. Every double is the one the old chain computed: the same `exp` of+/// the same argument, the sums in the same order, `cum += e / sum` with the same correctly rounded quotient - so+/// the cut, the survivors and the pick are the same. (`n_keep == 0`, reachable only with min_p > 1, which the+/// callers clamp, read `sel_ids[-1]` in the old tail; it reads `sel_ids[0]` here.)+inline void sampled_tail_warp(const int *sel_ids, const float *sel_logit, int k,+ const SamplerParams &p, int t,+ int *__restrict__ out, double *ex) {+ const int lane =+ (int)(sycl::ext::oneapi::this_work_item::get_nd_item<3>().get_local_id(+ 2) &+ 31);+ const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f;+ int n_keep = k;+ float mx = sel_logit[0];+#pragma unroll+ for (int i = 1; i < k; ++i) mx = sycl::fmax(mx, sel_logit[i]);+ if (p.top_p < 1.0f) {+#pragma unroll+ for (int i = lane; i < k; i += 32)+ ex[i] = sycl::exp((double)sel_logit[i] - (double)mx);+ sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());+ double sum = 0.0;+ if (lane == 0)+#pragma unroll+ for (int i = 0; i < k; ++i) sum += ex[i];+ /*+ DPCT1108: '__shfl_sync' was migrated with the experimental feature+ masked sub_group function which may not be supported by all compilers or+ runtimes. You may need to adjust the code.+ */+ sum = dpct::experimental::select_from_sub_group(+ kFullMask, sycl::ext::oneapi::this_work_item::get_sub_group(), sum,+ 0);+ sycl::group_barrier(sycl::ext::oneapi::this_work_item::+ get_sub_group()); // lane 0 has read every `ex`+ // before it is overwritten+#pragma unroll+ for (int i = lane; i < k; i += 32) ex[i] = ex[i] / sum;+ sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());+ int cut = k;+ if (lane == 0) {+ double cum = 0.0;+#pragma unroll+ for (int i = 0; i < k; ++i) {+ cum += ex[i];+ if (cum >= (double) p.top_p) { cut = i + 1; break; }+ }+ }+ /*+ DPCT1108: '__shfl_sync' was migrated with the experimental feature+ masked sub_group function which may not be supported by all compilers or+ runtimes. You may need to adjust the code.+ */+ cut = dpct::experimental::select_from_sub_group(+ kFullMask, sycl::ext::oneapi::this_work_item::get_sub_group(), cut,+ 0);+ if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k;+ n_keep = cut;+ sycl::group_barrier(sycl::ext::oneapi::this_work_item::+ get_sub_group()); // `ex` is written again below+ }+ // min_p on top_p's survivors, as in `sampler_kernel` (every lane, the same float arithmetic)+ if (p.min_p > 0.0f) {+ const float thresh = sel_logit[0] + sycl::log((float)(p.min_p));+#pragma unroll+ for (int i = 0; i < n_keep; ++i)+ if (sel_logit[i] < thresh) { n_keep = i; break; }+ }+ // temperature, then one Philox draw+ float smx = sel_logit[0] * inv_t;+#pragma unroll+ for (int i = 1; i < n_keep; ++i)+ smx = sycl::fmax(smx, sel_logit[i] * inv_t);+#pragma unroll+ for (int i = lane; i < n_keep; i += 32)+ ex[i] = sycl::exp((double)(sel_logit[i] * inv_t) - (double)smx);+ sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());+ double sum = 0.0;+ if (lane == 0)+#pragma unroll+ for (int i = 0; i < n_keep; ++i) sum += ex[i];+ /*+ DPCT1108: '__shfl_sync' was migrated with the experimental feature masked+ sub_group function which may not be supported by all compilers or runtimes.+ You may need to adjust the code.+ */+ sum = dpct::experimental::select_from_sub_group(+ kFullMask, sycl::ext::oneapi::this_work_item::get_sub_group(), sum, 0);+ sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());+#pragma unroll+ for (int i = lane; i < n_keep; i += 32) ex[i] = ex[i] / sum;+ sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());+ if (lane == 0) {+ const float u = philox_uniform(p.seed, p.counter + (uint64_t) t);+ double cum = 0.0;+ int pick = sel_ids[n_keep > 0 ? n_keep - 1 : 0];+#pragma unroll+ for (int i = 0; i < n_keep; ++i) {+ cum += ex[i];+ if ((double) u < cum) { pick = sel_ids[i]; break; }+ }+ out[t] = pick;+ }+}++/// **THE ONE-BLOCK SAMPLED PATH: `sampler_kernel` WITHOUT THE `taken` SWEEP.** Round i's candidates are the logits+/// strictly AFTER round i-1's pick in the selection order, `s < prev_v || (s == prev_v && v > prev_i)`, which is+/// exactly the set `taken` left: the picks so far are the first i of the order, so what comes after the last one is+/// what has not been picked. The round is then the same block argmax with the same tie rule, so the list is the+/// same list in the same order. An empty round leaves (-inf, id 0) as before, and every round after it is empty+/// in both versions (nothing after -inf beats -inf). O(k x n_vocab) per row instead of O(k^2 x n_vocab), then warp+/// 0 runs the tail. `STRATA_SAMPLER_ONE_BLOCK=1`, and the fallback when the split path cannot run.+/*+DPCT1110: The total declared local variable size in device function+sampler_one_block_kernel exceeds 128 bytes and may cause high register pressure.+Consult with your hardware vendor to find the total register size available and+adjust the code, or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void+sampler_one_block_kernel(const float *__restrict__ logits, int n_vocab,+ const int *__restrict__ history, int history_len,+ const SamplerParams p, int *__restrict__ out,+ uint8_t *dpct_local) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int t = item_ct1.get_group(2);+ const float* l = logits + (size_t) t * n_vocab;++ // the penalty window and its membership bitmap, exactly as in `sampler_kernel`+ const int* hrow = history ? history + (size_t) t * history_len : nullptr;+ int hlen = 0;+ if (hrow) {+ hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;+ if (hlen < 0) hlen = 0;+ hrow += history_len - hlen; // the window is the TAIL+ }+ auto penal_bits = (unsigned int *)dpct_local;+ const int bits_words = (int) ((n_vocab + 31) / 32);+ const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;+ if (use_bits) {+#pragma unroll+ for (int w = item_ct1.get_local_id(2); w < bits_words;+ w += item_ct1.get_local_range(2)) penal_bits[w] = 0u;+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ item_ct1.barrier(sycl::access::fence_space::local_space);+#pragma unroll+ for (int i = item_ct1.get_local_id(2); i < hlen;+ i += item_ct1.get_local_range(2))+ if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate+ dpct::atomic_fetch_or<+ sycl::access::address_space::generic_space>(+ &penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ item_ct1.barrier(sycl::access::fence_space::local_space);+ }+ auto hit_count = [&](int v, uint8_t *dpct_local) -> int {+ if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;+ return history_count(hrow, hlen, v);+ };++ const int k = sampled_k(p.top_k, n_vocab);+ auto &sel_ids =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<int[kSelMax]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &sel_logit =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[kSelMax]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &ex =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<double[kSelMax]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &sv = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &si = *sycl::ext::oneapi::group_local_memory_for_overwrite<int[32]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const int warp = (int)(item_ct1.get_local_id(2) >> 5),+ lane = (int)(item_ct1.get_local_id(2) & 31);+ float prev_v = sycl::bit_cast<float>(+ 0x7f800000); // +inf and id -1: round 0 takes every logit+ int prev_i = -1;+ for (int i = 0; i < k; ++i) {+ float bv = sycl::bit_cast<float, int>(0xff800000); // -inf+ int best = n_vocab;+ for (int v = item_ct1.get_local_id(2); v < n_vocab;+ v += item_ct1.get_local_range(2)) {+ const float s = apply_penalties(l[v], hit_count(v, dpct_local), p);+ if ((s < prev_v || (s == prev_v && v > prev_i)) && s > bv) { bv = s; best = v; }+ }+ for (int off = 16; off > 0; off >>= 1) {+ /*+ DPCT1108: '__shfl_down_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ const float ov = dpct::experimental::shift_sub_group_left(+ 0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ bv, off);+ /*+ DPCT1108: '__shfl_down_sync' was migrated with the experimental+ feature masked sub_group function which may not be supported by all+ compilers or runtimes. You may need to adjust the code.+ */+ const int oi = dpct::experimental::shift_sub_group_left(+ 0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),+ best, off);+ if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; }+ }+ if (lane == 0) { sv[warp] = bv; si[warp] = best; }+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ item_ct1.barrier(sycl::access::fence_space::local_space);+ if (warp == 0) {+ const int nw = (int)((item_ct1.get_local_range(2) + 31) >> 5);+ float wv =+ lane < nw ? sv[lane] : sycl::bit_cast<float, int>(0xff800000);+ int wi = lane < nw ? si[lane] : n_vocab;+ for (int off = 16; off > 0; off >>= 1) {+ /*+ DPCT1108: '__shfl_down_sync' was migrated with the+ experimental feature masked sub_group function which may not be+ supported by all compilers or runtimes. You may need to adjust+ the code.+ */+ const float ov = dpct::experimental::shift_sub_group_left(+ 0xFFFFFFFFu,+ sycl::ext::oneapi::this_work_item::get_sub_group(), wv,+ off);+ /*+ DPCT1108: '__shfl_down_sync' was migrated with the+ experimental feature masked sub_group function which may not be+ supported by all compilers or runtimes. You may need to adjust+ the code.+ */+ const int oi = dpct::experimental::shift_sub_group_left(+ 0xFFFFFFFFu,+ sycl::ext::oneapi::this_work_item::get_sub_group(), wi,+ off);+ if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; }+ }+ if (lane == 0) { sel_ids[i] = (wi < n_vocab) ? wi : 0; sel_logit[i] = wv; }+ }+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ item_ct1.barrier(sycl::access::fence_space::local_space);+ // An empty round leaves (-inf, 0): nothing comes after it, as nothing was left untaken.+ prev_v = sel_logit[i];+ prev_i = sel_ids[i];+ }+ if (warp != 0) return;+ sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex);+}++// ---- THE SPLIT top_k. `sampler_kernel` and the one-block kernel keep a row on ONE SM of 170 (5090) and walk its+// 248,320 logits k times. Here a warp keeps the top_k of 1,024 logits held in registers, four warps make a block of+// 4,096 logits that merges their lists, and a row is 61 such blocks over the whole GPU; one warp per row then+// merges the 61 lists and runs the tail. Exact, because the first k of a union are within the first k of each part+// and a merge of ordered lists is ordered - the selection order being a strict total order (above).+constexpr int kSplitPerLane = 32; // logits per lane, in registers+constexpr int kSplitWarpSpan = 32 * kSplitPerLane; // 1,024 logits per warp+constexpr int kSplitWarps = 4;+constexpr int kSplitBlockSpan = kSplitWarps * kSplitWarpSpan; // 4,096 logits per block+constexpr int kSplitMaxBlocks = 64; // lists the merge holds: n_vocab <= 262,144+constexpr int kSplitMaxRows = 64; // rows per split launch (the scratch's bound)++/// Merge `nl` (<= 64) lists of `k` candidates - list L at `lists[L * stride]`, each in the selection order and+/// padded with sentinels - into their first `k`: `sink(i, value, id)` runs in every lane for i = 0..k-1 with the+/// same pair. Lane owns lists `lane` and `lane + 32`; a round takes the first of all heads and advances the list+/// it came from. An id is in one list at most (the lists cover disjoint logits), so exactly one head matches.+template <typename Sink>+__dpct_inline__ void warp_merge_lists(const sycl::int2 *lists, int nl,+ int stride, int k, int n_vocab,+ Sink &&sink) {+ const int lane =+ (int)(sycl::ext::oneapi::this_work_item::get_nd_item<3>().get_local_id(+ 2) &+ 31);+ float hv[2];+ int hi[2], pos[2];+#pragma unroll+ for (int m = 0; m < 2; ++m) {+ const int L = lane + 32 * m;+ pos[m] = 0;+ hv[m] = sycl::bit_cast<float, int>(0xff800000);+ hi[m] = n_vocab;+ if (L < nl) {+ const sycl::int2 c = lists[(size_t)L * stride];+ hi[m] = c.x();+ hv[m] = sycl::bit_cast<float>(c.y());+ }+ }+ for (int i = 0; i < k; ++i) {+ float bv = hv[0];+ int bi = hi[0];+ take_first(bv, bi, hv[1], hi[1]);+ warp_first(bv, bi);+ sink(i, bv, bi);+ if (bi < n_vocab) {+#pragma unroll+ for (int m = 0; m < 2; ++m) {+ if (hi[m] != bi) continue;+ if (++pos[m] < k) {+ const sycl::int2 c =+ lists[(size_t)(lane + 32 * m) * stride + pos[m]];+ hi[m] = c.x();+ hv[m] = sycl::bit_cast<float>(c.y());+ } else {+ hi[m] = n_vocab;+ hv[m] = sycl::bit_cast<float, int>(0xff800000);+ }+ }+ }+ }+}++/// **SPLIT STAGE 1: THE top_k OF EACH 4,096-LOGIT BLOCK.** Grid (blocks per row, rows), 128 threads. Each warp+/// loads its 1,024 penalised logits once into registers (lane + 32 j: every load is one coalesced 128-byte line)+/// and runs `k` warp-argmax rounds over them with the threshold of `sampler_one_block_kernel` - no shared memory+/// and no block barrier per round. Warp 0 then merges the four warp lists into the block's list in `cand`+/// (row-major: row t, block b, entry i at `(t * n_blocks + b) * k + i`, as (id, value bits)).+/*+DPCT1110: The total declared local variable size in device function+sampler_split_part_kernel exceeds 128 bytes and may cause high register+pressure. Consult with your hardware vendor to find the total register size+available and adjust the code, or use smaller sub-group size to avoid high+register pressure.+*/+__dpct_inline__ void+sampler_split_part_kernel(const float *__restrict__ logits, int n_vocab,+ const int *__restrict__ history, int history_len,+ const SamplerParams p, int k, int n_blocks,+ sycl::int2 *__restrict__ cand) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int t = item_ct1.get_group(1);+ const float* l = logits + (size_t) t * n_vocab;+ const int warp = (int)(item_ct1.get_local_id(2) >> 5),+ lane = (int)(item_ct1.get_local_id(2) & 31);+ const int blo = (int)item_ct1.get_group(2) * kSplitBlockSpan;++ const int* hrow = history ? history + (size_t) t * history_len : nullptr;+ int hlen = 0;+ if (hrow) {+ hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;+ if (hlen < 0) hlen = 0;+ hrow += history_len - hlen; // the window is the TAIL+ }+ // The membership bitmap of THIS BLOCK'S 4,096 logits (512 bytes, not the vocabulary's 31 KB): the same test,+ // and a hit pays the same exact count over the whole window.+ auto &bits = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ unsigned int[kSplitBlockSpan / 32]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const bool use_bits = hrow != nullptr && hlen > 0;+ if (use_bits) {+#pragma unroll+ for (int w = item_ct1.get_local_id(2); w < kSplitBlockSpan / 32;+ w += item_ct1.get_local_range(2)) bits[w] = 0u;+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ item_ct1.barrier(sycl::access::fence_space::local_space);+ for (int i = item_ct1.get_local_id(2); i < hlen;+ i += item_ct1.get_local_range(2)) {+ const int h = hrow[i];+ if (h >= 0 && h < n_vocab && h >= blo && h - blo < kSplitBlockSpan)+ dpct::atomic_fetch_or<+ sycl::access::address_space::generic_space>(+ &bits[(h - blo) >> 5], 1u << ((h - blo) & 31));+ }+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ item_ct1.barrier(sycl::access::fence_space::local_space);+ }++ // This warp's logits, penalised: `apply_penalties` with a zero count returns the logit unchanged, so only the+ // bitmap's hits go through it. Past the vocabulary: -inf, which no round picks.+ const int lo = blo + warp * kSplitWarpSpan;+ float s[kSplitPerLane];+#pragma unroll+ for (int j = 0; j < kSplitPerLane; ++j) {+ const int v = lo + 32 * j + lane;+ s[j] = v < n_vocab ? l[v] : sycl::bit_cast<float, int>(0xff800000);+ }+ if (use_bits) {+#pragma unroll+ for (int j = 0; j < kSplitPerLane; ++j) {+ const int v = lo + 32 * j + lane, b = v - blo;+ if (v < n_vocab && (bits[b >> 5] & (1u << (b & 31))))+ s[j] = apply_penalties(s[j], history_count(hrow, hlen, v), p);+ }+ }++ auto &wl = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ sycl::int2[kSplitWarps][kSelMax]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ float prev_v = sycl::bit_cast<float>(+ 0x7f800000); // +inf and id -1: round 0 takes every logit+ int prev_i = -1;+ int i = 0;+ for (; i < k; ++i) {+ // two chains (even and odd j), each walked in ascending id with a strict `>`, so each keeps its first in+ // the order; `take_first` then orders the two+ float b0 = sycl::bit_cast<float, int>(0xff800000),+ b1 = sycl::bit_cast<float, int>(0xff800000);+ int i0 = n_vocab, i1 = n_vocab;+#pragma unroll+ for (int j = 0; j < kSplitPerLane; j += 2) {+ const int v0 = lo + 32 * j + lane, v1 = v0 + 32;+ const float x0 = s[j], x1 = s[j + 1];+ if ((x0 < prev_v || (x0 == prev_v && v0 > prev_i)) && x0 > b0) { b0 = x0; i0 = v0; }+ if ((x1 < prev_v || (x1 == prev_v && v1 > prev_i)) && x1 > b1) { b1 = x1; i1 = v1; }+ }+ take_first(b0, i0, b1, i1);+ warp_first(b0, i0);+ if (i0 >= n_vocab) break; // the same in every lane: nothing left in these 1,024 logits+ if (lane == 0) wl[warp][i] = sycl::int2(i0, sycl::bit_cast<int>(b0));+ prev_v = b0;+ prev_i = i0;+ }+#pragma unroll+ for (int r = i + lane; r < k; r += 32)+ wl[warp][r] = sycl::int2(n_vocab, (int)0xff800000u); // sentinels+ item_ct1.barrier(sycl::access::fence_space::local_space);+ if (warp == 0) {+ sycl::int2 *dst =+ cand + ((size_t)t * n_blocks + item_ct1.get_group(2)) * k;+ warp_merge_lists(&wl[0][0], kSplitWarps, kSelMax, k, n_vocab, [&](int r, float v, int id) {+ if (lane == 0) dst[r] = sycl::int2(id, sycl::bit_cast<int>(v));+ });+ }+}++/// **SPLIT STAGE 2: ONE WARP PER ROW MERGES THE BLOCK LISTS, THEN RUNS THE TAIL.** The row's lists (at most 64 x+/// 64 entries, 32 KB) are copied to shared memory, merged into the row's top_k list, and `sampled_tail_warp` picks.+__dpct_inline__ void+sampler_split_merge_kernel(const sycl::int2 *__restrict__ cand, int n_blocks,+ int n_vocab, const SamplerParams p, int k,+ int *__restrict__ out) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const int t = item_ct1.get_group(2);+ const int lane = (int)item_ct1.get_local_id(2);+ auto &lists = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ sycl::int2[kSplitMaxBlocks * kSelMax]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &sel_ids =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<int[kSelMax]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &sel_logit =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[kSelMax]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &ex =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<double[kSelMax]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const sycl::int2 *src = cand + (size_t)t * n_blocks * k;+#pragma unroll+ for (int e = lane; e < n_blocks * k; e += 32) lists[e] = src[e];+ sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());+ warp_merge_lists(lists, n_blocks, k, k, n_vocab, [&](int i, float v, int id) {+ if (lane == 0) { sel_ids[i] = id < n_vocab ? id : 0; sel_logit[i] = v; }+ });+ sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());+ sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex);+}++// Which sampled path runs, read once: `STRATA_OLD_SAMPLER=1` is `sampler_kernel` (engine 0.1.20),+// `STRATA_SAMPLER_ONE_BLOCK=1` the one-block kernel; by default the split top_k wherever it applies.+enum class SampledPath { Split, OneBlock, Old };++bool env_flag(const char* name) {+ const char* e = std::getenv(name);+ return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0;+}++SampledPath sampled_path() {+ static const SampledPath path = env_flag("STRATA_OLD_SAMPLER") ? SampledPath::Old+ : env_flag("STRATA_SAMPLER_ONE_BLOCK") ? SampledPath::OneBlock+ : SampledPath::Split;+ return path;+}++// A stream being captured into a graph must not reach `split_scratch` (cudaMalloc): it+// gets the one-block kernel, which needs no memory of its own. The legacy stream cannot be captured.+bool stream_capturing(void *stream) try {+ if (stream == nullptr) return false;+ sycl::ext::oneapi::experimental::queue_state st =+ sycl::ext::oneapi::experimental::queue_state::executing;+ if (DPCT_CHECK_ERROR(+ (st = strata::q_of(stream)->ext_oneapi_get_state())) != 0) {+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use the+ error codes. The cudaGetLastError function call was replaced with 0. You+ need to rewrite this code.+ */+ (void)0;+ return true;+ }+ return st != sycl::ext::oneapi::experimental::queue_state::executing;+}+catch (sycl::exception const &exc) {+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__+ << ", line:" << __LINE__ << std::endl;+ std::exit(1);+}++// The split's block lists, one buffer per (device, stream): launches on one stream run in order, so a stream reuses+// its buffer with no sync, and two streams never share one. Grown on demand (at least doubling, up to the size of+// `kSplitMaxRows` rows at the widest vocabulary: 2 MB), never shrunk. A grown-out buffer is retired, not freed: a+// pointer handed out earlier (to another host thread on the same stream, say) may still be waiting for its launch,+// and freeing it would need a sync that proves nothing about that thread. Doubling keeps a slot's retired buffers+// smaller than its live one, so a slot holds about 4 MB at most (0.5 MB for the engine's <= 16 rows). nullptr+// when the memory cannot be had, and the caller falls back to the one-block kernel; a failed grow is remembered, so+// later calls of that size do not retry cudaMalloc each time.+sycl::int2 *split_scratch(void *stream, size_t entries) {+ struct Slot {+ int device;+ void* stream;+ sycl::int2 *ptr;+ size_t entries;+ size_t failed; // the smallest size cudaMalloc refused (0: none)+ };+ static std::mutex mu;+ static std::vector<Slot> slots;+ static std::vector<sycl::int2 *> retired;+ int device = 0;+ if (DPCT_CHECK_ERROR(device = dpct::get_current_device_id()) != 0) {+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use the+ error codes. The cudaGetLastError function call was replaced with 0. You+ need to rewrite this code.+ */+ (void)0;+ return nullptr;+ }+ std::lock_guard<std::mutex> lock(mu);+ Slot* slot = nullptr;+ for (Slot& s : slots)+ if (s.device == device && s.stream == stream) slot = &s;+ if (slot == nullptr) {+ slots.push_back({device, stream, nullptr, 0, 0});+ slot = &slots.back();+ }+ if (slot->entries >= entries) return slot->ptr;+ if (slot->failed != 0 && entries >= slot->failed) return nullptr;+ constexpr size_t kCap = (size_t) kSplitMaxRows * kSplitMaxBlocks * kSelMax;+ size_t want = 2 * slot->entries < kCap ? 2 * slot->entries : kCap;+ if (want < entries) want = entries;+ sycl::int2 *ptr = nullptr;+ if (DPCT_CHECK_ERROR(ptr = sycl::malloc_device<sycl::int2>(+ want, dpct::get_in_order_queue())) != 0) {+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use the+ error codes. The cudaGetLastError function call was replaced with 0. You+ need to rewrite this code.+ */+ (void)0;+ want = entries;+ if (DPCT_CHECK_ERROR(ptr = sycl::malloc_device<sycl::int2>(+ want, dpct::get_in_order_queue())) != 0) {+ /*+ DPCT1010: SYCL uses exceptions to report errors and does not use+ the error codes. The cudaGetLastError function call was replaced+ with 0. You need to rewrite this code.+ */+ (void)0;+ slot->failed = entries;+ return nullptr;+ }+ }+ if (slot->ptr != nullptr) retired.push_back(slot->ptr);+ slot->ptr = ptr;+ slot->entries = want;+ return ptr;+}+} // namespacevoid sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,@@ -481,7 +1129,7 @@ void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* hisycl::range(shmem), cgh);cgh.parallel_for<- dpct_kernel_name<class sampler_greedy_kernel_eacb1a>>(+ dpct_kernel_name<class sampler_greedy_kernel_5b2c3f>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n_tokens) *sycl::range(1, 1, gthreads),@@ -499,7 +1147,7 @@ void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* hi});});}- } else {+ } else if (sampled_path() == SampledPath::Old) {// The same block-per-token shape: the selection's k argmax rounds reduce inside the block. See// `sampler_kernel`'s header for what the old one-thread-per-token launch cost./*@@ -518,7 +1166,7 @@ void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* hisycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(sycl::range(shmem), cgh);- cgh.parallel_for<dpct_kernel_name<class sampler_kernel_9f529a>>(+ cgh.parallel_for<dpct_kernel_name<class sampler_kernel_ebb5aa>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n_tokens) *sycl::range(1, 1, 1024),sycl::range(1, 1, 1024)),@@ -533,6 +1181,97 @@ void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* hi.get());});});+ } else {+ // The split top_k by default: stage 1 over (61 blocks x rows) for 248,320 logits, stage 2 one warp per+ // row. The one-block kernel when asked for, or when the split cannot run: a wider vocabulary than the merge+ // holds, more than `kSplitMaxRows` rows (the engine samples at most a verify window), a stream under capture,+ // no scratch.+ const int k = sampled_k(p.top_k, n_vocab);+ const int n_blocks = (n_vocab + kSplitBlockSpan - 1) / kSplitBlockSpan;+ sycl::int2 *scratch = nullptr;+ if (sampled_path() == SampledPath::Split && n_blocks <= kSplitMaxBlocks && n_tokens <= kSplitMaxRows &&+ !stream_capturing(stream))+ // sized for 16 rows and 64 entries at least, so a verify window or a wider top_k does not regrow it+ scratch = split_scratch(stream, (size_t) (n_tokens > 16 ? n_tokens : 16) * n_blocks * kSelMax);+ if (scratch != nullptr) {+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<dpct_kernel_name<+ class sampler_split_part_kernel_cc5673>>(+ sycl::nd_range<3>(+ sycl::range(1, (unsigned)n_tokens,+ (unsigned)n_blocks) *+ sycl::range(1, 1, kSplitWarps * 32),+ sycl::range(1, 1, kSplitWarps * 32)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ sampler_split_part_kernel(+ logits, n_vocab, history, history_len, p, k,+ n_blocks, scratch);+ });+ }+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(+ strata::q_of(stream)->get_device(),+ {sycl::aspect::fp64});++ strata::q_of(stream)+ ->parallel_for<dpct_kernel_name<+ class sampler_split_merge_kernel_b17bd4>>(+ sycl::nd_range<3>(+ sycl::range(1, 1, (unsigned)n_tokens) *+ sycl::range(1, 1, 32),+ sycl::range(1, 1, 32)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ sampler_split_merge_kernel(scratch, n_blocks,+ n_vocab, p, k, out);+ });+ }+ } else {+ /*+ DPCT1049: The work-group size passed to the SYCL kernel may+ exceed the limit. To get the device limit, query+ info::device::max_work_group_size. Adjust the work-group size if+ needed.+ */+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};+ dpct::has_capability_or_fail(+ strata::q_of(stream)->get_device(),+ {sycl::aspect::fp64});++ strata::q_of(stream)+ ->submit([&](sycl::handler &cgh) {+ sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(+ sycl::range(shmem), cgh);++ cgh.parallel_for<dpct_kernel_name<+ class sampler_one_block_kernel_79fa88>>(+ sycl::nd_range<3>(+ sycl::range(1, 1, (unsigned)n_tokens) *+ sycl::range(1, 1, 1024),+ sycl::range(1, 1, 1024)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ sampler_one_block_kernel(+ logits, n_vocab, history, history_len, p,+ out,+ dpct_local_acc_ct1+ .get_multi_ptr<+ sycl::access::decorated::no>()+ .get());+ });+ });+ }}/*DPCT1010: SYCL uses exceptions to report errors and does not use thediff --git a/sycl/src/kernels/elementwise_parity.cpp b/sycl/src/kernels/elementwise_parity.cppindex 594b45980..85f7493d4 100644--- a/sycl/src/kernels/elementwise_parity.cpp+++ b/sycl/src/kernels/elementwise_parity.cpp@@ -15,6 +15,7 @@#define DPCT_PROFILING_ENABLED#include <sycl/sycl.hpp>#include <dpct/dpct.hpp>+#include "strata/kernels/dequant_bf16.hpp"#include "strata/kernels/elementwise.hpp"#include "strata/kernels/f16_bits.hpp"@@ -616,6 +617,99 @@ int main(int argc, char** argv) {if (mismatches || guards || fma_diff == 0) ++bad;}+ // ---- THE f32 -> bf16 CONVERSIONS KEEP A NaN A NaN. `f32_to_bf16_bulk` (the header's `bf16_from_f32`+ // on the device) and the prompt path's dequantizer (its own `f2bf`) against ggml_compute_fp32_to_bf16's rule;+ // before the fix 0x7FFFFFFF came back as -0 and 0x7F800001 as +inf. `bf16_bits_test` covers every f32 on+ // the host; this is the same header compiled by nvcc, plus the second copy in dequant_bf16.cu.+ {+ auto ggml_bf16 = [](uint32_t u) -> uint16_t {+ if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64);+ return (uint16_t) ((u + (0x7fffu + ((u >> 16) & 1u))) >> 16);+ };+ std::vector<uint32_t> bits = {0x7FFFFFFFu, 0xFFFFFFFFu, 0x7F800001u, 0xFF800001u, 0x7FC00000u, 0x7FBFFFFFu,+ 0x7F800000u, 0xFF800000u, 0x7F7FFFFFu, 0x00000000u, 0x80000000u, 0x3F808000u,+ 0x3F818000u, 0x00008000u, 0x7F7F8000u};+ std::mt19937 rng(13);+ while (bits.size() < 4096) bits.push_back((uint32_t) rng());+ const size_t n = bits.size();+ float* dx = nullptr;+ uint16_t* dy = nullptr;+ check(DPCT_CHECK_ERROR(dx = (float *)sycl::malloc_device(+ n * 4, dpct::get_in_order_queue())),+ "bf16 x");+ check(DPCT_CHECK_ERROR(dy = (uint16_t *)sycl::malloc_device(+ n * 2, dpct::get_in_order_queue())),+ "bf16 y");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable memory.+ If the memory is not pageable, call wait() on event return by memcpy API+ to ensure synchronization behavior.+ */+ check(DPCT_CHECK_ERROR(+ dpct::get_in_order_queue().memcpy(dx, bits.data(), n * 4).wait()),+ "bf16 cx");+ strata::kernels::f32_to_bf16_bulk(dx, dy, (int64_t) n, nullptr);+ std::vector<uint16_t> got(n);+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue()+ .memcpy(got.data(), dy, n * 2)+ .wait()),+ "bf16 cy");+ int wrong = 0;+ for (size_t i = 0; i < n; ++i) wrong += got[i] != ggml_bf16(bits[i]);++ // A Q8_0 block (type 8) whose fp16 scale is a NaN: every dequantized value is NaN * q, a NaN, and it must+ // still be one in BF16. A second block with an ordinary scale checks the finite path did not move.+ std::vector<uint8_t> blk(2 * 34, 0);+ blk[0] = 0x00; blk[1] = 0x7E; // fp16 quiet NaN+ blk[34] = 0x00; blk[35] = 0x3C; // fp16 1.0+ for (int j = 0; j < 32; ++j) {+ blk[(size_t) (2 + j)] = (uint8_t) (int8_t) (j - 16);+ blk[(size_t) (36 + j)] = (uint8_t) (int8_t) (3 * j - 50);+ }+ uint8_t* db = nullptr;+ uint16_t* dq = nullptr;+ check(DPCT_CHECK_ERROR(db = (uint8_t *)sycl::malloc_device(+ blk.size(), dpct::get_in_order_queue())),+ "q8 blk");+ check(DPCT_CHECK_ERROR(dq = (uint16_t *)sycl::malloc_device(+ 64 * 2, dpct::get_in_order_queue())),+ "q8 out");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable memory.+ If the memory is not pageable, call wait() on event return by memcpy API+ to ensure synchronization behavior.+ */+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(db, blk.data(),+ blk.size()).wait()),+ "q8 cblk");+ strata::kernels::dequant_bf16(8, db, 0, 2, 32, dq, nullptr);+ check(DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()),+ "dequant_bf16");+ std::vector<uint16_t> q(64);+ check(+ DPCT_CHECK_ERROR(+ dpct::get_in_order_queue().memcpy(q.data(), dq, 64 * 2).wait()),+ "q8 cout");+ int dq_wrong = 0;+ for (int j = 0; j < 32; ++j) {+ if (!((q[(size_t) j] & 0x7FFFu) > 0x7F80u)) ++dq_wrong; // row 0: NaN scale -> NaN+ const float v = (float) (3 * j - 50); // row 1: d = 1.0 -> the integer+ uint32_t vb;+ std::memcpy(&vb, &v, 4);+ if (q[(size_t) (32 + j)] != ggml_bf16(vb)) ++dq_wrong;+ }+ std::printf(" f32 -> bf16 (NaN kept): bulk %d of %zu differ from ggml, dequant_bf16 %d of 64 wrong\n",+ wrong, n, dq_wrong);+ if (wrong || dq_wrong) ++bad;+ sycl::free(dx, dpct::get_in_order_queue());+ sycl::free(dy, dpct::get_in_order_queue());+ sycl::free(db, dpct::get_in_order_queue());+ sycl::free(dq, dpct::get_in_order_queue());+ }+std::printf("\nelementwise: %d failures\n", bad);if (bad) return 1;if (selftest) std::printf("elementwise_parity OK\n");diff --git a/sycl/src/kernels/s_gemv_q8k_parity.cpp b/sycl/src/kernels/s_gemv_q8k_parity.cppindex 95f289421..315bab4b5 100644--- a/sycl/src/kernels/s_gemv_q8k_parity.cpp+++ b/sycl/src/kernels/s_gemv_q8k_parity.cpp@@ -69,6 +69,180 @@ struct Case {bool has_offset;};+/// THE RAGGED LAST BLOCK. The split kernels give each warp one row and a block eight warps, so with+/// `n_out % 8 != 0` the last block holds warps that have no row. Those warps used to return BEFORE the+/// codebook barrier - undefined behaviour that every real shape (a multiple of 8) avoided. Here `n_out` is+/// deliberately ragged, every row is checked against the host reference over the same bytes, and a guard+/// band past `n_out` must come back untouched: a warp without a row must neither hang the block nor write.+/// (`compute-sanitizer --tool synccheck` on this binary is the direct check of the barrier itself.)+int ragged_rows(const Case& cs, long long n_out) {+ const long long n_in = 512;+ const long long guard = 64;+ std::mt19937 rng(77 + (unsigned) n_out);+ std::normal_distribution<float> g(0.0f, 1.0f);+ std::vector<float> xf((size_t) n_in);+ for (auto& v : xf) v = g(rng);+ SForm f;+ f.code_bits = cs.bits;+ f.code_bias = cs.bias;+ f.group_elems = cs.group;+ f.codebook = cs.cb;+ f.has_offset = cs.has_offset;+ const int per_byte = 8 / cs.bits;+ std::vector<uint8_t> codes((size_t) (n_out * n_in / per_byte));+ for (auto& v : codes) v = (uint8_t) (rng() & 0xFF);+ const long long n_groups = n_in / cs.group;+ std::vector<float> scales((size_t) (n_out * n_groups)), offs((size_t) (n_out * n_groups));+ for (auto& v : scales) v = 0.01f + 0.001f * (float) (rng() % 20);+ for (auto& v : offs) v = 0.2f * g(rng);++ float* d_xf = nullptr;+ uint8_t *d_xk = nullptr, *d_x0 = nullptr, *d_codes = nullptr;+ float *d_scales = nullptr, *d_offs = nullptr, *d_y = nullptr;+ std::vector<uint8_t> xk((size_t) (n_in / 256) * 292), x0((size_t) (n_in / 32) * 34);+ check(DPCT_CHECK_ERROR(d_xf = (float *)sycl::malloc_device(+ (size_t)n_in * 4, dpct::get_in_order_queue())),+ "rxf");+ check(DPCT_CHECK_ERROR(d_xk = (uint8_t *)sycl::malloc_device(+ xk.size(), dpct::get_in_order_queue())),+ "rxk");+ check(DPCT_CHECK_ERROR(d_x0 = (uint8_t *)sycl::malloc_device(+ x0.size(), dpct::get_in_order_queue())),+ "rx0");+ check(DPCT_CHECK_ERROR(d_codes = (uint8_t *)sycl::malloc_device(+ codes.size(), dpct::get_in_order_queue())),+ "rcodes");+ check(DPCT_CHECK_ERROR(d_scales = (float *)sycl::malloc_device(+ scales.size() * 4, dpct::get_in_order_queue())),+ "rscales");+ check(DPCT_CHECK_ERROR(d_offs = (float *)sycl::malloc_device(+ offs.size() * 4, dpct::get_in_order_queue())),+ "roffs");+ check(DPCT_CHECK_ERROR(+ d_y = (float *)sycl::malloc_device((size_t)(n_out + guard) * 4,+ dpct::get_in_order_queue())),+ "ry");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in+ the original code the source host memory is pageable memory. If the memory+ is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(d_xf, xf.data(),+ (size_t)n_in * 4).wait()),+ "rcxf");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in+ the original code the source host memory is pageable memory. If the memory+ is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(+ d_codes, codes.data(), codes.size()).wait()),+ "rcc");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in+ the original code the source host memory is pageable memory. If the memory+ is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(+ d_scales, scales.data(), scales.size() * 4).wait()),+ "rcs");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in+ the original code the source host memory is pageable memory. If the memory+ is not pageable, call wait() on event return by memcpy API to ensure+ synchronization behavior.+ */+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(+ d_offs, offs.data(), offs.size() * 4).wait()),+ "rco");+ strata::kernels::quantize_q8_K(d_xf, d_xk, n_in, nullptr);+ strata::kernels::quantize_q8_0(d_xf, d_x0, n_in, nullptr);+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue()+ .memcpy(xk.data(), d_xk, xk.size())+ .wait()),+ "rcxk");+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue()+ .memcpy(x0.data(), d_x0, x0.size())+ .wait()),+ "rcx0");++ int bad = 0;+ for (int kind = 0; kind < 2; ++kind) { // 0: Q8_K activation, 1: Q8_0 activation+ std::vector<float> want((size_t) n_out);+ std::vector<double> mag((size_t) n_out); // sum |w_i a_i| per row: a row whose sum cancels near 0+ for (long long o = 0; o < n_out; ++o) { // must not turn f32 rounding into a relative failure+ double acc = 0, am = 0;+ for (long long i = 0; i < n_in; ++i) {+ double a;+ if (kind == 0) {+ a = q8k_at(xk, i);+ } else {+ const uint8_t* blk = x0.data() + (size_t) (i / 32) * 34;+ uint16_t dbits;+ std::memcpy(&dbits, blk, 2);+ a = (double) strata::kernels::f32_from_f16(dbits) * (double) ((const int8_t*) (blk + 2))[i % 32];+ }+ const double wa = weight_at(codes, scales, offs, f, n_in, o, i) * a;+ acc += wa;+ am += std::fabs(wa);+ }+ want[(size_t) o] = (float) acc;+ mag[(size_t) o] = am;+ }+ // the guard band holds a NaN pattern; any write there shows up as a changed bit+ std::vector<uint32_t> sentinel((size_t) (n_out + guard), 0x7FC0DEADu);+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable memory.+ If the memory is not pageable, call wait() on event return by memcpy API+ to ensure synchronization behavior.+ */+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(+ d_y, sentinel.data(), sentinel.size() * 4).wait()),+ "rsent");+ if (kind == 0)+ strata::kernels::s_gemv_q8k_split(d_xk, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in,+ n_out, f, nullptr);+ else+ strata::kernels::s_gemv_q8_0_split(d_x0, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in,+ n_out, f, nullptr);+ check(DPCT_CHECK_ERROR(+ dpct::get_current_device().queues_wait_and_throw()),+ "ragged split");+ std::vector<uint32_t> got_bits(sentinel.size());+ check(DPCT_CHECK_ERROR(+ dpct::get_in_order_queue()+ .memcpy(got_bits.data(), d_y, got_bits.size() * 4)+ .wait()),+ "rcy");+ double m = 0, d = 0;+ for (long long o = 0; o < n_out; ++o) {+ float v;+ std::memcpy(&v, &got_bits[(size_t) o], 4);+ m += mag[(size_t) o];+ d += std::fabs((double) want[(size_t) o] - (double) v);+ }+ long long touched = 0;+ for (long long o = n_out; o < n_out + guard; ++o) touched += got_bits[(size_t) o] != 0x7FC0DEADu;+ const double rel = d / (m > 1e-30 ? m : 1e-30);+ const bool ok = rel <= 1e-5 && touched == 0;+ std::printf(" %-28s %s n_out %3lld: rel %.3e, guard words written %lld %s\n", cs.what,+ kind == 0 ? "Q8_K" : "Q8_0", n_out, rel, touched, ok ? "ok" : "*** WRONG ***");+ if (!ok) ++bad;+ }+ sycl::free(d_xf, dpct::get_in_order_queue());+ sycl::free(d_xk, dpct::get_in_order_queue());+ sycl::free(d_x0, dpct::get_in_order_queue());+ sycl::free(d_codes, dpct::get_in_order_queue());+ sycl::free(d_scales, dpct::get_in_order_queue());+ sycl::free(d_offs, dpct::get_in_order_queue());+ sycl::free(d_y, dpct::get_in_order_queue());+ return bad;+}+} // namespaceint main(int argc, char** argv) {@@ -314,6 +488,11 @@ int main(int argc, char** argv) {sycl::free(d_y, dpct::get_in_order_queue());}+ // ---- 4. output widths that are NOT a multiple of the eight rows per block+ std::printf("\n");+ for (const Case& cs : cases)+ for (long long n_out : {1LL, 7LL, 9LL, 61LL}) bad += ragged_rows(cs, n_out);+std::printf("\ns_gemv_q8k: %d failures\n", bad);if (bad) return 1;if (selftest) std::printf("s_gemv_q8k_parity OK\n");diff --git a/sycl/src/kernels/sampler_parity.cpp b/sycl/src/kernels/sampler_parity.cppindex 0ea146080..08fef0030 100644--- a/sycl/src/kernels/sampler_parity.cpp+++ b/sycl/src/kernels/sampler_parity.cpp@@ -18,6 +18,7 @@#include <cstdio>#include <cstdlib>#include <cstring>+#include <limits>#include <random>#include <string>#include <vector>@@ -291,13 +292,256 @@ int sampled_cut(const std::vector<float>& l, const std::vector<int>& hist, constreturn cut;}+// ---- the kernel's own semantics, for the fixtures ----+//+// `sampled_reference` picks the first unpicked logit even when it is -inf or NaN; the kernels never pick either, and+// a round that finds nothing stores id 0 with a -inf logit (and later rounds treat id 0 as taken, as `sampler_kernel`+// does). The mirror below follows the kernels, so rows with -inf, NaN, +inf and more requested than finite logits+// can be pinned exactly. On rows without those it is `sampled_reference`.+struct SelList {+ std::vector<int> ids;+ std::vector<float> logit;+};++// The top_k list of `sampler_kernel` for one row: `window` is the counted history (the row's last penalty_last_n).+SelList mirror_select(const float* l, int nv, const std::vector<int>& window, const strata::kernels::SamplerParams& p,+ int k) {+ std::vector<float> s((size_t) nv);+ for (int v = 0; v < nv; ++v) {+ int c = 0;+ for (int h : window) c += h == v;+ float x = l[v];+ if (c > 0) {+ if (x <= 0.0f) x *= p.penalty_repeat; else x /= p.penalty_repeat;+ x -= (float) c * p.penalty_freq + (c > 0 ? 1.0f : 0.0f) * p.penalty_present;+ }+ s[(size_t) v] = x;+ }+ SelList out;+ std::vector<char> taken((size_t) nv, 0);+ for (int i = 0; i < k; ++i) {+ int best = nv;+ float bv = -std::numeric_limits<float>::infinity();+ for (int v = 0; v < nv; ++v)+ if (!taken[(size_t) v] && s[(size_t) v] > bv) { bv = s[(size_t) v]; best = v; }+ const int id = best < nv ? best : 0;+ taken[(size_t) id] = 1;+ out.ids.push_back(id);+ out.logit.push_back(bv);+ }+ return out;+}++// The tail of `sampler_kernel` over a list (its first `k` entries): top_p, min_p, temperature, the Philox draw.+int mirror_pick(const SelList& sel, int k, const strata::kernels::SamplerParams& p, int row) {+ int n_keep = k;+ float mx = sel.logit[0];+ for (int i = 1; i < k; ++i) mx = std::fmax(mx, sel.logit[(size_t) i]);+ if (p.top_p < 1.0f) {+ double sum = 0.0;+ for (int i = 0; i < k; ++i) sum += std::exp((double) sel.logit[(size_t) i] - (double) mx);+ double cum = 0.0;+ int cut = k;+ for (int i = 0; i < k; ++i) {+ cum += std::exp((double) sel.logit[(size_t) i] - (double) mx) / sum;+ if (cum >= (double) p.top_p) { cut = i + 1; break; }+ }+ if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k;+ n_keep = cut;+ }+ if (p.min_p > 0.0f) {+ const float thresh = sel.logit[0] + std::log(p.min_p);+ for (int i = 0; i < n_keep; ++i)+ if (sel.logit[(size_t) i] < thresh) { n_keep = i; break; }+ }+ const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f;+ auto scaled = [&](int i) { return sel.logit[(size_t) i] * inv_t; };+ float smx = scaled(0);+ for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, scaled(i));+ double sum = 0.0;+ for (int i = 0; i < n_keep; ++i) sum += std::exp((double) scaled(i) - (double) smx);+ const float u = host_philox_uniform(p.seed, p.counter + (uint64_t) row);+ double cum = 0.0;+ int pick = sel.ids[(size_t) (n_keep > 0 ? n_keep - 1 : 0)];+ for (int i = 0; i < n_keep; ++i) {+ cum += std::exp((double) scaled(i) - (double) smx) / sum;+ if ((double) u < cum) { pick = sel.ids[(size_t) i]; break; }+ }+ return pick;+}++int sampled_k(int top_k, int nv) { return std::min(nv, (top_k > 0 && top_k < 64) ? top_k : 64); }++// Rows uploaded once and sampled under many parameter sets: `sample` returns the picks of one launch on `stream`+// (nullptr: the legacy stream), -1 prefilled as in `run`.+struct DeviceRows {+ float* l = nullptr;+ int* h = nullptr;+ int* o = nullptr;+ int n_tokens = 0, nv = 0, hist_len = 0;+ DeviceRows(const std::vector<float>& logits, int n_tokens_, const std::vector<int>& hist, int hist_len_)+ : n_tokens(n_tokens_), nv((int) (logits.size() / (size_t) n_tokens_)), hist_len(hist_len_) {+ check(DPCT_CHECK_ERROR(l = sycl::malloc_device<float>(+ logits.size(), dpct::get_in_order_queue())),+ "malloc logits");+ check(+ DPCT_CHECK_ERROR(o = sycl::malloc_device<int>(+ (size_t)n_tokens, dpct::get_in_order_queue())),+ "malloc out");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable memory.+ If the memory is not pageable, call wait() on event return by memcpy API+ to ensure synchronization behavior.+ */+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(+ l, logits.data(), logits.size() * sizeof(float)).wait()),+ "copy");+ if (hist_len > 0) {+ check(+ DPCT_CHECK_ERROR(h = sycl::malloc_device<int>(+ hist.size(), dpct::get_in_order_queue())),+ "malloc hist");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable+ memory. If the memory is not pageable, call wait() on event return+ by memcpy API to ensure synchronization behavior.+ */+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(+ h, hist.data(), hist.size() * sizeof(int)).wait()),+ "copy hist");+ }+ }+ DeviceRows(const DeviceRows&) = delete;+ DeviceRows& operator=(const DeviceRows&) = delete;+ ~DeviceRows() {+ sycl::free(l, dpct::get_in_order_queue());+ sycl::free(o, dpct::get_in_order_queue());+ if (h) sycl::free(h, dpct::get_in_order_queue());+ }+ std::vector<int> sample(const strata::kernels::SamplerParams &p,+ dpct::queue_ptr stream) {+ check(DPCT_CHECK_ERROR(+ dpct::get_in_order_queue()+ .memset(o, 0xFF, (size_t)n_tokens * sizeof(int))+ .wait()),+ "fill out");+ strata::kernels::sample_tokens(l, n_tokens, nv, h, hist_len, p, o, stream);+ if (stream != &dpct::get_in_order_queue())+ check(DPCT_CHECK_ERROR(stream->wait()), "stream sync");+ std::vector<int> got((size_t) n_tokens);+ check(DPCT_CHECK_ERROR(+ dpct::get_in_order_queue()+ .memcpy(got.data(), o, got.size() * sizeof(int))+ .wait()),+ "back");+ return got;+ }+};++// The counted window of row t: the last min(penalty_last_n, hist_len) entries (none without penalties).+std::vector<int> window_of(const std::vector<int>& hist, int hist_len, int t, int last_n) {+ if (hist_len <= 0 || last_n <= 0) return {};+ const int h = std::min(last_n, hist_len);+ const int* row = hist.data() + (size_t) t * hist_len;+ return std::vector<int>(row + (hist_len - h), row + hist_len);+}++// `--bench`: the sampled path alone at the engine's vocabulary, per call, on the path the environment selects.+void bench_sampled() {+ const int NV = 248320;+ dpct::queue_ptr s = &dpct::get_in_order_queue();+ check(DPCT_CHECK_ERROR(s = dpct::get_current_device().create_queue(true)),+ "stream");+ std::mt19937 rng(20);+ std::normal_distribution<float> g(0.0f, 3.0f);+ for (int T : {1, 4, 8}) {+ std::vector<float> l((size_t) NV * T);+ for (auto& v : l) v = g(rng);+ float* d_l = nullptr;+ int* d_o = nullptr;+ check(DPCT_CHECK_ERROR(d_l = sycl::malloc_device<float>(+ l.size(), dpct::get_in_order_queue())),+ "bench logits");+ check(DPCT_CHECK_ERROR(d_o = sycl::malloc_device<int>(+ (size_t)T, dpct::get_in_order_queue())),+ "bench out");+ /*+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,+ assuming in the original code the source host memory is pageable memory.+ If the memory is not pageable, call wait() on event return by memcpy API+ to ensure synchronization behavior.+ */+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(+ d_l, l.data(), l.size() * sizeof(float)).wait()),+ "bench copy");+ for (int k : {20, 64}) {+ strata::kernels::SamplerParams p;+ p.top_k = k; p.top_p = 0.95f; p.temperature = 0.7f; p.seed = 1;+ for (int w = 0; w < 3; ++w) strata::kernels::sample_tokens(d_l, T, NV, nullptr, 0, p, d_o, s);+ check(DPCT_CHECK_ERROR(s->wait()), "bench warmup");+ dpct::event_ptr e0, e1;+ check(DPCT_CHECK_ERROR(e0 = new sycl::event()), "event");+ check(DPCT_CHECK_ERROR(e1 = new sycl::event()), "event");+ const int iters = 50;+ /*+ DPCT1024: The original code returned the error code that was+ further consumed by the program logic. This original code was+ replaced with 0. You may need to rewrite the program logic consuming+ the error code.+ */+ check(DPCT_CHECK_ERROR(dpct::sync_barrier(e0, s)), "record");+ for (int it = 0; it < iters; ++it) {+ p.counter = (uint64_t) it;+ strata::kernels::sample_tokens(d_l, T, NV, nullptr, 0, p, d_o, s);+ }+ /*+ DPCT1024: The original code returned the error code that was+ further consumed by the program logic. This original code was+ replaced with 0. You may need to rewrite the program logic consuming+ the error code.+ */+ check(DPCT_CHECK_ERROR(dpct::sync_barrier(e1, s)), "record");+ check(DPCT_CHECK_ERROR(e1->wait_and_throw()), "bench sync");+ float ms = 0.0f;+ check(DPCT_CHECK_ERROR(+ ms = (e1->get_profiling_info<+ sycl::info::event_profiling::command_end>() -+ e0->get_profiling_info<+ sycl::info::event_profiling::command_start>()) /+ 1000000.0f),+ "elapsed");+ std::printf(" bench: n_vocab %d, rows %d, top_k %2d, top_p 0.95: %8.1f us per call\n", NV, T, k,+ 1000.0 * (double) ms / iters);+ dpct::destroy_event(e0);+ dpct::destroy_event(e1);+ }+ sycl::free(d_l, dpct::get_in_order_queue());+ sycl::free(d_o, dpct::get_in_order_queue());+ }+ dpct::get_current_device().destroy_queue(s);+}+} // namespaceint main(int argc, char** argv) {- bool selftest = false;+ bool selftest = false, bench = false;for (int i = 1; i < argc; ++i) {if (std::string(argv[i]) == "--selftest") selftest = true;- else { std::fprintf(stderr, "usage: sampler_parity [--selftest]\n"); return 2; }+ else if (std::string(argv[i]) == "--bench") bench = true;+ else { std::fprintf(stderr, "usage: sampler_parity [--selftest] [--bench]\n"); return 2; }+ }+ {+ // the sampled path under test; ctest runs this binary once per path+ auto on = [](const char* n) { const char* e = std::getenv(n); return e && *e && std::strcmp(e, "0") != 0; };+ std::printf(" sampled path: %s\n", on("STRATA_OLD_SAMPLER") ? "sampler_kernel (STRATA_OLD_SAMPLER)"+ : on("STRATA_SAMPLER_ONE_BLOCK") ? "one block (STRATA_SAMPLER_ONE_BLOCK)"+ : "split top_k (default)");+ }+ if (bench) {+ bench_sampled();+ return 0;}int bad = 0;const int NV = 512, NT = 4;@@ -922,6 +1166,286 @@ int main(int argc, char** argv) {sycl::free(output, dpct::get_in_order_queue());}+ // ---- fixture 16: THE WHOLE top_k LIST, POSITION BY POSITION, UNDER TIES. A pick shows the list+ // through one draw; this reads the list itself. Every row holds a +inf logit, so the tail's arithmetic is NaN+ // (inf - inf), no cut fires and no draw lands: the chain returns its LAST kept entry, sel_ids[k - 1]. Launching+ // top_k = 1..64 then reads the list one position at a time - its set and its order. The rows make the order+ // rest on the tie rule: hundreds of logits share the top finite values, spread over every split block, warp and+ // lane; -0 and +0 tie; -inf and NaN are mixed in; a row has fewer finite logits than 64 (the sentinel id 0 must+ // come out); a penalised row lands its penalised tokens exactly on other tokens' values. Vocabularies: the+ // engine's 248,320 (a partial last split block), 100,003, 262,144 (the widest split), 262,145 (one more: the+ // one-block fallback) and 1,000.+ {+ const float inf = std::numeric_limits<float>::infinity();+ const float qnan = std::numeric_limits<float>::quiet_NaN();+ int wrong = 0, probes = 0, sentinels = 0;+ for (int nv : {248320, 100003, 262144, 262145, 1000}) {+ const int T = 4, H = 64;+ std::mt19937 rng((unsigned) (1600 + nv));+ std::normal_distribution<float> g(0.0f, 1.0f);+ std::vector<float> l((size_t) nv * T);+ for (auto& v : l) v = std::floor(g(rng) * 4.0f) / 4.0f; // quarter steps: ties everywhere+ auto spread = [&](int j) { return (int) (((int64_t) j * 7919 + 13) % nv); };+ // row 0: 20 logits at 6.25 and 300 at 6.0 over the whole row, two +inf+ float* r0 = l.data();+ for (int j = 0; j < 320; ++j) r0[spread(j)] = j < 20 ? 6.25f : 6.0f;+ r0[nv / 2] = inf;+ r0[nv - 1] = inf;+ // row 1: nothing above 0, every zero signed by its id's parity (-0 at even ids), one +inf+ float* r1 = l.data() + (size_t) nv;+ for (int v = 0; v < nv; ++v) {+ r1[v] = -std::fabs(r1[v]);+ if (r1[v] == 0.0f) r1[v] = (v & 1) ? 0.0f : -0.0f;+ }+ r1[3] = inf;+ // row 2: -inf everywhere but ten finite logits (two values), two NaN and a +inf: 11 candidates in all+ float* r2 = l.data() + (size_t) 2 * nv;+ for (int v = 0; v < nv; ++v) r2[v] = -inf;+ for (int j = 0; j < 10; ++j) r2[spread(j + 400)] = j < 5 ? 1.0f : 0.5f;+ r2[spread(500)] = qnan;+ r2[spread(501)] = qnan;+ r2[spread(502)] = inf;+ // row 3: penalties. Window ids on block and warp edges, repeats, and ids outside the vocabulary; the+ // penalised tokens sit at 9.0, which repeat 2 / freq 0.25 / present 0.5 turns into 4.0 - 0.25 x count+ // (3.75, 3.5, ...), values the quarter-step logits share.+ float* r3 = l.data() + (size_t) 3 * nv;+ std::vector<int> hist((size_t) T * H, -1);+ int* h3 = hist.data() + (size_t) 3 * H;+ const int edges[] = {0, 1023, 1024, 4095, 4096, 8191, 8192, 12345, nv / 2 + 1, nv - 2};+ int hn = 0;+ for (int e : edges)+ if (e < nv && e != nv / 2) {+ h3[hn++] = e;+ if (hn % 3 == 0) h3[hn++] = e; // counted twice+ r3[e] = 9.0f;+ }+ h3[hn++] = nv; // ignored: outside+ h3[hn++] = nv + 77;+ h3[hn++] = -5;+ for (int j = 0; j < 30; ++j) r3[spread(j + 600)] = j < 15 ? 3.75f : 3.5f;+ r3[nv / 2] = inf; // not in the window++ strata::kernels::SamplerParams base;+ base.top_p = 1.0f; base.min_p = 0.0f; base.temperature = 0.8f; base.seed = 16;+ base.penalty_last_n = H; base.penalty_repeat = 2.0f; base.penalty_freq = 0.25f;+ base.penalty_present = 0.5f;+ const int kmax = sampled_k(64, nv);+ std::vector<SelList> lists;+ for (int t = 0; t < T; ++t)+ lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, H), base, kmax));+ DeviceRows rows(l, T, hist, H);+ for (int top_k = 0; top_k <= 66; ++top_k) {+ strata::kernels::SamplerParams p = base;+ p.top_k = top_k == 65 ? 100 : top_k == 66 ? -3 : top_k; // 0, 100 and -3 mean 64+ p.top_p = (top_k & 1) ? 0.5f : 1.0f; // both tail branches (NaN: no cut)+ p.counter = (uint64_t) top_k;+ const int k = sampled_k(p.top_k, nv);+ const std::vector<int> got =+ rows.sample(p, &dpct::get_in_order_queue());+ for (int t = 0; t < T; ++t) {+ const int want = lists[(size_t) t].ids[(size_t) (k - 1)];+ sentinels += (t == 2 && k > 11);+ ++probes;+ if (got[(size_t) t] != want) {+ if (wrong < 8)+ std::printf(" n_vocab %d row %d top_k %d: position %d want id %d got %d\n", nv, t,+ p.top_k, k - 1, want, got[(size_t) t]);+ ++wrong;+ }+ }+ }+ }+ // the fixture must reach the sentinel (row 2 has 11 candidates) or it cannot see the "nothing left" rule+ std::printf(" %-34s %s (%d of %d positions differ; %d sentinel positions)\n", "top_k list under ties",+ wrong || !sentinels ? "*** WRONG ***" : "matches", wrong, probes, sentinels);+ bad += wrong + (sentinels == 0);+ }++ // ---- fixture 17: SAMPLED DRAWS UNDER TIES. The realistic chain - finite logits on half steps,+ // so dozens of tokens share each value near the top - through every stage: top_k 1 / 20 / 64, top_p 0.9 / 1,+ // min_p 0 / 0.05, a hot temperature that spreads the draws over the whole list, penalties off and on (half of+ // each window on the row's head, so they reorder it). 17 rows (the split's scratch is first sized for 16: this+ // regrows it), on the legacy stream and on a created one. Observability: some picks must be tokens that tie+ // with another kept token, or the tie rule would go untested.+ {+ const int T = 17, H = 64;+ dpct::queue_ptr cs = &dpct::get_in_order_queue();+ check(DPCT_CHECK_ERROR(+ cs = dpct::get_current_device().create_queue(true)),+ "fixture 17 stream");+ int wrong = 0, draws = 0, tied = 0;+ for (int nv : {248320, 512}) {+ std::mt19937 rng((unsigned) (1700 + nv));+ std::normal_distribution<float> g(0.0f, 1.5f);+ std::vector<float> l((size_t) nv * T);+ for (auto& v : l) v = std::floor(g(rng) * 2.0f) / 2.0f;+ if (nv == 512)+ for (auto& v : l) v = std::floor(v / 2.0f); // whole steps: a few big tie groups+ std::vector<int> hist((size_t) T * H);+ for (int t = 0; t < T; ++t) {+ const float* row = l.data() + (size_t) t * nv;+ const float mx = *std::max_element(row, row + nv);+ std::vector<int> head;+ for (int v = 0; v < nv; ++v)+ if (row[v] >= mx - 1.0f) head.push_back(v);+ for (int j = 0; j < H; ++j)+ hist[(size_t) t * H + j] = (j & 1) ? (int) (rng() % (unsigned) nv)+ : head[(size_t) (rng() % (unsigned) head.size())];+ }+ DeviceRows rows(l, T, hist, H);+ int config = 0;+ for (int pen = 0; pen < 2; ++pen) {+ strata::kernels::SamplerParams base;+ base.temperature = 2.5f; base.seed = 17;+ base.penalty_last_n = pen ? H : 0;+ base.penalty_repeat = 1.25f; base.penalty_freq = 0.25f; base.penalty_present = 0.5f;+ const int kmax = sampled_k(64, nv);+ std::vector<SelList> lists;+ for (int t = 0; t < T; ++t)+ lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, base.penalty_last_n),+ base, kmax));+ for (int top_k : {1, 20, 64})+ for (float top_p : {0.9f, 1.0f})+ for (float min_p : {0.0f, 0.05f})+ for (dpct::queue_ptr st :+ {(dpct::queue_ptr)&dpct::get_in_order_queue(),+ cs}) {+ strata::kernels::SamplerParams p = base;+ p.top_k = top_k; p.top_p = top_p; p.min_p = min_p;+ p.counter = (uint64_t) (1000 * ++config);+ const int k = sampled_k(top_k, nv);+ const std::vector<int> got = rows.sample(p, st);+ for (int t = 0; t < T; ++t) {+ const SelList& sl = lists[(size_t) t];+ const int want = mirror_pick(sl, k, p, t);+ ++draws;+ int same = 0;+ for (int i = 0; i < k; ++i) {+ if (sl.ids[(size_t) i] != want) continue;+ for (int j = 0; j < k; ++j) same += sl.logit[(size_t) j] == sl.logit[(size_t) i];+ break;+ }+ tied += same > 1;+ if (got[(size_t) t] != want) {+ if (wrong < 8)+ std::printf(" n_vocab %d row %d top_k %d top_p %.2f min_p %.2f pen %d: "+ "want %d got %d\n", nv, t, top_k, (double) top_p,+ (double) min_p, pen, want, got[(size_t) t]);+ ++wrong;+ }+ }+ }+ }+ }+ dpct::get_current_device().destroy_queue(cs);+ std::printf(" %-34s %s (%d of %d draws differ; %d picks tie with another kept token)\n",+ "sampled draws under ties", wrong || !tied ? "*** WRONG ***" : "matches", wrong, draws, tied);+ bad += wrong + (tied == 0);+ }++ // ---- fixture 18: THE DEFAULT PATH'S AUTOMATIC FALLBACKS. (a) A stream under graph capture+ // (ThreadLocal mode) gets the one-block kernel, penalty bitmap in dynamic shared memory, inside the graph: the+ // capture must succeed and the replayed graph (twice) must pick the mirror's tokens; the same stream uncaptured+ // then takes the split path (its scratch is first allocated after the capture) and picks the same. (b) More+ // rows than a split launch takes (64) fall back to one block; exactly 64 stay split.+ {+ int wrong = 0, draws = 0;+ const int H = 64;+ auto compare = [&](const char* what, const std::vector<int>& got, const std::vector<SelList>& lists, int k,+ const strata::kernels::SamplerParams& p) {+ for (size_t t = 0; t < got.size(); ++t) {+ const int want = mirror_pick(lists[t], k, p, (int) t);+ ++draws;+ if (got[t] != want) {+ if (wrong < 8) std::printf(" %s row %zu: want %d got %d\n", what, t, want, got[t]);+ ++wrong;+ }+ }+ };+ auto make = [&](int nv, int T, unsigned seed, std::vector<float>& l, std::vector<int>& hist) {+ std::mt19937 rng(seed);+ std::normal_distribution<float> g(0.0f, 1.5f);+ l.assign((size_t) nv * T, 0.0f);+ for (auto& v : l) v = std::floor(g(rng) * 2.0f) / 2.0f;+ hist.assign((size_t) T * H, 0);+ for (auto& h : hist) h = (int) (rng() % (unsigned) nv);+ };+ {+ const int nv = 248320, T = 3;+ std::vector<float> l;+ std::vector<int> hist;+ make(nv, T, 1800u, l, hist);+ strata::kernels::SamplerParams p;+ p.top_k = 20; p.top_p = 0.9f; p.temperature = 2.5f; p.seed = 18; p.counter = 77;+ p.penalty_last_n = H; p.penalty_repeat = 1.25f; p.penalty_freq = 0.25f; p.penalty_present = 0.5f;+ const int k = sampled_k(p.top_k, nv);+ std::vector<SelList> lists;+ for (int t = 0; t < T; ++t)+ lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, H), p, k));+ DeviceRows rows(l, T, hist, H);+ dpct::queue_ptr cs = &dpct::get_in_order_queue();+ check(DPCT_CHECK_ERROR(+ cs = dpct::get_current_device().create_queue(true)),+ "fixture 18 stream");+ check(DPCT_CHECK_ERROR(+ dpct::get_in_order_queue()+ .memset(rows.o, 0xFF, (size_t)T * sizeof(int))+ .wait()),+ "fixture 18 fill");+ dpct::experimental::command_graph_ptr graph = nullptr;+ dpct::experimental::command_graph_exec_ptr exec = nullptr;+ check(DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs)),+ "begin capture");+ strata::kernels::sample_tokens(rows.l, T, nv, rows.h, H, p, rows.o, cs);+ check(+ DPCT_CHECK_ERROR(dpct::experimental::end_recording(cs, &graph)),+ "end capture");+ check(DPCT_CHECK_ERROR(+ exec = new sycl::ext::oneapi::experimental::command_graph<+ sycl::ext::oneapi::experimental::graph_state::+ executable>(graph->finalize())),+ "instantiate");+ for (int replay = 0; replay < 2; ++replay) {+ check(DPCT_CHECK_ERROR(+ dpct::get_in_order_queue()+ .memset(rows.o, 0xFF, (size_t)T * sizeof(int))+ .wait()),+ "fixture 18 refill");+ check(DPCT_CHECK_ERROR(cs->ext_oneapi_graph(*exec)),+ "graph launch");+ check(DPCT_CHECK_ERROR(cs->wait()), "graph sync");+ std::vector<int> got((size_t) T);+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue()+ .memcpy(got.data(), rows.o,+ got.size() * sizeof(int))+ .wait()),+ "back");+ compare("captured graph", got, lists, k, p);+ }+ delete (exec);+ delete (graph);+ compare("same stream, uncaptured", rows.sample(p, cs), lists, k, p);+ dpct::get_current_device().destroy_queue(cs);+ }+ for (int T : {64, 70}) {+ const int nv = 512;+ std::vector<float> l;+ std::vector<int> hist;+ make(nv, T, 1810u + (unsigned) T, l, hist);+ strata::kernels::SamplerParams p;+ p.top_k = 64; p.top_p = 1.0f; p.temperature = 2.5f; p.seed = 18; p.counter = (uint64_t) T;+ const int k = sampled_k(p.top_k, nv);+ std::vector<SelList> lists;+ for (int t = 0; t < T; ++t) lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, {}, p, k));+ DeviceRows rows(l, T, hist, 0);+ compare(T > 64 ? "70 rows (one block)" : "64 rows (split)",+ rows.sample(p, &dpct::get_in_order_queue()), lists, k, p);+ }+ std::printf(" %-34s %s (%d of %d draws differ)\n", "fallbacks: graph capture, row cap",+ wrong ? "*** WRONG ***" : "matches", wrong, draws);+ bad += wrong;+ }+std::printf("\nsampler: %d failures\n", bad);if (bad) return 1;if (selftest) std::printf("sampler_parity OK\n");diff --git a/sycl/src/prefill/kernels.dp.cpp b/sycl/src/prefill/kernels.dp.cppindex 81c0523da..cfafd1f10 100644--- a/sycl/src/prefill/kernels.dp.cpp+++ b/sycl/src/prefill/kernels.dp.cpp@@ -599,6 +599,131 @@ auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(#pragma unrollfor (int r = 0; r < RPG; ++r) base[r * rs] = s[r];}+// gdn_rec_cols_kernel with the next token's inputs (q/k rows, v, gate, beta) loaded into registers while this token+// computes (software pipelining). The same arithmetic in the same order: the same bits, and the same CB-column split.+// STRATA_GDN_PIPELINE=0: gdn_rec_cols_kernel.+/*+DPCT1110: The total declared local variable size in device function+gdn_rec_cols_pipe_kernel exceeds 128 bytes and may cause high register pressure.+Consult with your hardware vendor to find the total register size available and+adjust the code, or use smaller sub-group size to avoid high register pressure.+*/+__dpct_inline__ void gdn_rec_cols_pipe_kernel(float *__restrict__ state,+ const float *__restrict__ h,+ const float *__restrict__ gate,+ const float *__restrict__ beta,+ float *__restrict__ oc_out,+ int64_t T) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ constexpr int NT = CB * RG,+ LPT = S / NT; // threads, q/k rows loaded per thread+ auto &sk = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &sq = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[S]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &red =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[RG][CB]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const int head = item_ct1.get_group(2) / NCB,+ cb = item_ct1.get_group(2) % NCB;+ const int c = item_ct1.get_local_id(2), rg = item_ct1.get_local_id(1),+ tid = rg * CB + c, col = cb * CB + c;+ const int qh = head % HK;+ float s[RPG];+ float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col;+ const size_t rs = (size_t) HV * S;+#pragma unroll+ for (int r = 0; r < RPG; ++r) s[r] = base[r * rs];+ float nq[LPT], nk[LPT], nv = 0.0f, ng = 0.0f, nb = 0.0f;+ auto fetch = [&](int64_t t) {+ const float* ht = h + t * C;+#pragma unroll+ for (int u = 0; u < LPT; ++u) { nq[u] = ht[qh * S + tid + u * NT]; nk[u] = ht[HK * S + qh * S + tid + u * NT]; }+ nv = ht[2 * HK * S + head * S + col];+ ng = gate[t * HV + head];+ nb = beta[t * HV + head];+ };+ if (T > 0) fetch(0);+ for (int64_t t = 0; t < T; ++t) {+ float cq[LPT], ck[LPT];+#pragma unroll+ for (int u = 0; u < LPT; ++u) { cq[u] = nq[u]; ck[u] = nk[u]; }+ const float cv = nv, cg = ng, cbt = nb;+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ DPCT1065: Consider replacing sycl::nd_item::barrier() with+ sycl::nd_item::barrier(sycl::access::fence_space::local_space) for+ better performance if there is no access to global memory.+ */+ item_ct1.barrier();+#pragma unroll+ for (int u = 0; u < LPT; ++u) { sq[tid + u * NT] = cq[u]; sk[tid + u * NT] = ck[u]; }+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ DPCT1065: Consider replacing sycl::nd_item::barrier() with+ sycl::nd_item::barrier(sycl::access::fence_space::local_space) for+ better performance if there is no access to global memory.+ */+ item_ct1.barrier();+ if (t + 1 < T) fetch(t + 1);+ const float g = sycl::native::exp(cg);+ float kv = 0.0f;+#pragma unroll+ for (int r = 0; r < RPG; ++r)+ kv = sycl::fma(s[r], sk[rg * RPG + r], kv);+ red[rg][c] = kv;+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ DPCT1065: Consider replacing sycl::nd_item::barrier() with+ sycl::nd_item::barrier(sycl::access::fence_space::local_space) for+ better performance if there is no access to global memory.+ */+ item_ct1.barrier();+ const float kv_col = red[0][c] + red[1][c] + red[2][c] + red[3][c];+ const float delta = (cv - g * kv_col) * cbt;+ float o = 0.0f;+#pragma unroll+ for (int r = 0; r < RPG; ++r) {+ s[r] = sycl::fma((float)g, s[r], sk[rg * RPG + r] * delta);+ o = sycl::fma(s[r], sq[rg * RPG + r], o);+ }+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ DPCT1065: Consider replacing sycl::nd_item::barrier() with+ sycl::nd_item::barrier(sycl::access::fence_space::local_space) for+ better performance if there is no access to global memory.+ */+ item_ct1.barrier();+ red[rg][c] = o;+ /*+ DPCT1118: SYCL group functions and algorithms must be encountered in+ converged control flow. You may need to adjust the code.+ */+ /*+ DPCT1065: Consider replacing sycl::nd_item::barrier() with+ sycl::nd_item::barrier(sycl::access::fence_space::local_space) for+ better performance if there is no access to global memory.+ */+ item_ct1.barrier();+ if (rg == 0) oc_out[t * HV * S + head * S + col] =+ (red[0][c] + red[1][c] + red[2][c] + red[3][c]) *+ sycl::rsqrt((float)S);+ }+#pragma unroll+ for (int r = 0; r < RPG; ++r) base[r * rs] = s[r];+}__dpct_inline__ void gdn_out_norm_kernel(const float *__restrict__ z,const float *__restrict__ gamma,float eps, float *__restrict__ y,@@ -987,7 +1112,7 @@ void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const instage ? *stage : strata::kernels::KvHostPools{};cgh.parallel_for<- dpct_kernel_name<class kv_append_kernel_c8a7c1>>(+ dpct_kernel_name<class kv_append_kernel_850222>>(sycl::nd_range<3>(sycl::range(8, 2, (unsigned)T) *sycl::range(1, 1, 64),sycl::range(1, 1, 64)),@@ -1011,7 +1136,7 @@ void to_f16(const float* x, uint16_t* y, int64_t n, void* stream) {sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class to_f16_kernel_286314>>(+ ->parallel_for<dpct_kernel_name<class to_f16_kernel_c8575f>>(sycl::nd_range<3>(sycl::range(1, 1,(unsigned)((n + 255) / 256 < 4096? (n + 255) / 256@@ -1031,7 +1156,7 @@ void round_f16(const float* x, float* y, int64_t n, void* stream) {sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class round_f16_kernel_3fea66>>(+ ->parallel_for<dpct_kernel_name<class round_f16_kernel_877aa1>>(sycl::nd_range<3>(sycl::range(1, 1,(unsigned)((n + 255) / 256 < 4096? (n + 255) / 256@@ -1051,7 +1176,7 @@ void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream) {sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class to_bf16_kernel_b87029>>(+ ->parallel_for<dpct_kernel_name<class to_bf16_kernel_44d81a>>(sycl::nd_range<3>(sycl::range(1, 1,(unsigned)((n + 255) / 256 < 4096? (n + 255) / 256@@ -1071,7 +1196,7 @@ void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_tsycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class gr_norm_kernel_7ac11f>>(+ ->parallel_for<dpct_kernel_name<class gr_norm_kernel_f38542>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(T * HC)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),@@ -1089,7 +1214,7 @@ void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint1sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class gr_norm_rs_kernel_44cb02>>(+ ->parallel_for<dpct_kernel_name<class gr_norm_rs_kernel_6c01ba>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(T * HC)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),@@ -1108,7 +1233,7 @@ void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float*sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class gr_mix_r_kernel_c2a1de>>(+ ->parallel_for<dpct_kernel_name<class gr_mix_r_kernel_a64dc1>>(sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * N)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),@@ -1127,7 +1252,7 @@ void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_lstrata::q_of(stream)->parallel_for<- dpct_kernel_name<class gr_write_norm_rs_kernel_d03793>>(+ dpct_kernel_name<class gr_write_norm_rs_kernel_85f8e9>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(T * HC)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),@@ -1149,7 +1274,7 @@ void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream) {->submit([&](sycl::handler &cgh) {auto T_LR_ct2 = T * LR;- cgh.parallel_for<dpct_kernel_name<class gr_silu_kernel_61274c>>(+ cgh.parallel_for<dpct_kernel_name<class gr_silu_kernel_f26d34>>(sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * LR)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),@@ -1167,7 +1292,7 @@ void gr_mix(const float* xn, const float* gated, float* mixed, uint16_t* mixed16sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class gr_mix_kernel_9ba6d6>>(+ ->parallel_for<dpct_kernel_name<class gr_mix_kernel_d9dd98>>(sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * N)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),@@ -1183,7 +1308,7 @@ void gr_write(float* R, const float* bo, const float* inj, int64_t inj_ld, int64sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class gr_write_kernel_24cfed>>(+ ->parallel_for<dpct_kernel_name<class gr_write_kernel_b96cec>>(sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * D)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),@@ -1199,7 +1324,7 @@ void gr_broadcast(const float* e, float* R, int64_t T, void* stream) {sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class gr_broadcast_kernel_73ae1d>>(+ ->parallel_for<dpct_kernel_name<class gr_broadcast_kernel_3dedc6>>(sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * D)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),@@ -1215,7 +1340,7 @@ void gdn_gates(const float* ab, const float* dt, const float* ssm_a, float* gatesycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class gdn_gates_kernel_850222>>(+ ->parallel_for<dpct_kernel_name<class gdn_gates_kernel_e66d35>>(sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * HV)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),@@ -1232,7 +1357,7 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, isycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class gdn_conv_kernel_8fa65c>>(+ ->parallel_for<dpct_kernel_name<class gdn_conv_kernel_df787b>>(sycl::nd_range<3>(sycl::range(1, 1, C / 128) *sycl::range(1, 1, 128),sycl::range(1, 1, 128)),@@ -1246,7 +1371,7 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, istrata::q_of(stream)->parallel_for<- dpct_kernel_name<class gdn_conv_tiled_kernel_915839>>(+ dpct_kernel_name<class gdn_conv_tiled_kernel_532f01>>(sycl::nd_range<3>(sycl::range(1,(unsigned)((T + CONV_TILE - 1) / CONV_TILE),@@ -1263,7 +1388,7 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, istrata::q_of(stream)->parallel_for<- dpct_kernel_name<class gdn_conv_hist_kernel_1d17e3>>(+ dpct_kernel_name<class gdn_conv_hist_kernel_e391a1>>(sycl::nd_range<3>(sycl::range(1, 1, C / 128) *sycl::range(1, 1, 128),sycl::range(1, 1, 128)),@@ -1277,7 +1402,7 @@ void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, isycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class gdn_l2_kernel_877aa1>>(+ ->parallel_for<dpct_kernel_name<class gdn_l2_kernel_d82250>>(sycl::nd_range<3>(sycl::range(1, (unsigned)T, 2 * HK) *sycl::range(1, 1, S),sycl::range(1, 1, S)),@@ -1302,7 +1427,7 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const floatsycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class gdn_rec_kernel_6a2bf0>>(+ ->parallel_for<dpct_kernel_name<class gdn_rec_kernel_923fed>>(sycl::nd_range<3>(sycl::range(1, 1, HV) * sycl::range(1, RG, S),sycl::range(1, RG, S)),exp_props,@@ -1312,13 +1437,28 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const floaty16, T);});} else {+ static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }();+ if (pipe) // the software-pipelined loads (same bits){auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)->parallel_for<- dpct_kernel_name<class gdn_rec_cols_kernel_64239d>>(+ dpct_kernel_name<class gdn_rec_cols_pipe_kernel_c6cea3>>(+ sycl::nd_range<3>(sycl::range(1, 1, HV * NCB) *+ sycl::range(1, RG, CB),+ sycl::range(1, RG, CB)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ gdn_rec_cols_pipe_kernel(state, h, gate, beta, y, T);+ });+ } else {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ strata::q_of(stream)+ ->parallel_for<+ dpct_kernel_name<class gdn_rec_cols_kernel_496541>>(sycl::nd_range<3>(sycl::range(1, 1, HV * NCB) *sycl::range(1, RG, CB),sycl::range(1, RG, CB)),@@ -1332,7 +1472,7 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const floatstrata::q_of(stream)->parallel_for<- dpct_kernel_name<class gdn_out_norm_kernel_237731>>(+ dpct_kernel_name<class gdn_out_norm_kernel_43e92c>>(sycl::nd_range<3>(sycl::range(1, HV, (unsigned)T) *sycl::range(1, 1, S),sycl::range(1, 1, S)),@@ -1352,7 +1492,7 @@ void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_tsycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class route_kernel_a33365,+ ->parallel_for<dpct_kernel_name<class route_kernel_4f80f3,dpct_kernel_scalar<16>>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)((T + 7) / 8)) *sycl::range(1, 1, 256),@@ -1368,7 +1508,7 @@ void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_tsycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class route_kernel_f9493d,+ ->parallel_for<dpct_kernel_name<class route_kernel_c02f30,dpct_kernel_scalar<8>>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)((T + 7) / 8)) *sycl::range(1, 1, 256),@@ -1388,7 +1528,7 @@ void blob_dequant(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* ssycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class blob_dequant_kernel_1db2df,+ ->parallel_for<dpct_kernel_name<class blob_dequant_kernel_50ffea,dpct_kernel_scalar<false>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks_for(1280LL * 640 + 2560LL * 160)) *@@ -1406,7 +1546,7 @@ void blob_dequant_f16(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, voisycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class blob_dequant_kernel_ee9bfb,+ ->parallel_for<dpct_kernel_name<class blob_dequant_kernel_cd530c,dpct_kernel_scalar<true>>>(sycl::nd_range<3>(sycl::range(1, 1, blocks_for(1280LL * 640 + 2560LL * 160)) *@@ -1425,7 +1565,7 @@ void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, void* stream)sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class swiglu_il_kernel_458d6e>>(+ ->parallel_for<dpct_kernel_name<class swiglu_il_kernel_98d495>>(sycl::nd_range<3>(sycl::range(1, 1, blocks_for(n * 640)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),@@ -1441,7 +1581,7 @@ void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, void*sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class swiglu_pair_kernel_ddbac5>>(+ ->parallel_for<dpct_kernel_name<class swiglu_pair_kernel_ab28da>>(sycl::nd_range<3>(sycl::range(1, 1, blocks_for(n * 640)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),@@ -1473,7 +1613,7 @@ void copy_i32(int32_t* dst, const int32_t* src, int64_t n, void* stream) {sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class copy_i32_kernel_7676d1>>(+ ->parallel_for<dpct_kernel_name<class copy_i32_kernel_1c95ea>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(b < 256 ? b : 256)) *sycl::range(1, 1, 256),@@ -1491,7 +1631,7 @@ void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, intsycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class gather_rows16_kernel_225b7e>>(+ ->parallel_for<dpct_kernel_name<class gather_rows16_kernel_d9d697>>(sycl::nd_range<3>(sycl::range(1, 1, blocks_for(n * (width / 8))) *sycl::range(1, 1, 256),@@ -1509,7 +1649,7 @@ void moe_combine(const float* Dm, const int32_t* slot, const float* w, const flosycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class moe_combine_kernel_d82250>>(+ ->parallel_for<dpct_kernel_name<class moe_combine_kernel_60f865>>(sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * N)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),@@ -1526,7 +1666,7 @@ void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld,sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class rms_rows_kernel_c94646>>(+ ->parallel_for<dpct_kernel_name<class rms_rows_kernel_c88408>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)rows) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),@@ -1549,7 +1689,7 @@ void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pauto strata_kernels_mrope_table_ct6 =strata::kernels::mrope_table();- cgh.parallel_for<dpct_kernel_name<class rope_kernel_dccc17>>(+ cgh.parallel_for<dpct_kernel_name<class rope_kernel_4d58b9>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(T * heads)) *sycl::range(1, 1, 32),sycl::range(1, 1, 32)),@@ -1567,7 +1707,7 @@ void split_q(const float* q_full, float* q, int64_t T, void* stream) {sycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class split_q_kernel_d499e3>>(+ ->parallel_for<dpct_kernel_name<class split_q_kernel_83c16c>>(sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * 24 * 256)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),@@ -1583,7 +1723,7 @@ void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_tsycl::ext::oneapi::experimental::use_root_sync};strata::q_of(stream)- ->parallel_for<dpct_kernel_name<class gate_attn_kernel_f391fd>>(+ ->parallel_for<dpct_kernel_name<class gate_attn_kernel_3fc329>>(sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * 24 * 256)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),diff --git a/sycl/src/prefill/prefill.cpp b/sycl/src/prefill/prefill.cppindex f7e43059c..20cd88444 100644--- a/sycl/src/prefill/prefill.cpp+++ b/sycl/src/prefill/prefill.cpp@@ -4,6 +4,7 @@#include <dpct/dpct.hpp>#include "strata/sycl_queue.hpp"#include "strata/prefill/prefill.hpp"+#include "strata/core/gguf_expert_source.hpp"#include "strata/core/mtp.hpp"#include "strata/core/progress.hpp"#include "strata/core/on_device.hpp"@@ -84,6 +85,13 @@ double g_pinned_share = 1.0;inline int ring_slots(size_t T) {const char* v = std::getenv("STRATA_PREFILL_RING");const int r = v ? std::atoi(v) : (g_pinned_share >= 0.9 ? 384 : 96);+ if (v && r == STAGE) return STAGE; // Explicit opt-in to routed-only staging, including large chunks.+ // SYCL port: routed-only staging by default. The stream-all walk (every non-resident expert of every layer, copied+ // ahead across layers) hangs on the B70 in its first large chunk - the copy engine stops on a barrier (xe resets bcs+ // on kill) - with any ring size and either issuer, while the per-layer walk streams correctly (8,000 tokens with+ // 4,051 streamed experts, 2026-09-30). STRATA_PREFILL_STREAM_ALL=1 restores it for debugging.+ static const bool stream_all_ok = [] { const char* e = std::getenv("STRATA_PREFILL_STREAM_ALL"); return e && e[0] == '1'; }();+ if (!stream_all_ok) return STAGE;const int big = r < 16 ? 16 : r > RING_MAX ? RING_MAX : r;return (int64_t) T >= STREAM_ALL_MIN ? big : STAGE;}@@ -140,7 +148,8 @@ struct Stager {// D-5: the pinned ring's depth (STRATA_STAGER_RING, default 16) - how far the host copies can run ahead of the// DMAs of the unpinned experts' blobsint kRing = 16;- struct Job { const uint8_t* src; size_t bytes; };+ // SYCL port: a job may name the expert instead of a host pointer - the thread reads it from the GGUF itself+ struct Job { const uint8_t* src; size_t bytes; int64_t layer = -1; int64_t expert = -1; const core::GgufExpertSource* gsrc = nullptr; };std::vector<uint8_t*> buf;std::vector<char> pinned;std::vector<std::vector<uint8_t>> pageable; // the fallback when no more RAM can be pinned@@ -223,7 +232,15 @@ struct Stager {while (issued.load(std::memory_order_acquire) <= j - kRing) std::this_thread::yield();dma_done[b]->wait_and_throw();}- std::memcpy(buf[b], jobs[(size_t) j].src, jobs[(size_t) j].bytes);+ if (jobs[(size_t) j].gsrc != nullptr) {+ if (!jobs[(size_t) j].gsrc->read_into(jobs[(size_t) j].layer, jobs[(size_t) j].expert, buf[b], jobs[(size_t) j].bytes)) {+ std::fprintf(stderr, "prefill: reading expert %lld of layer %lld from the GGUF failed\n",+ (long long) jobs[(size_t) j].expert, (long long) jobs[(size_t) j].layer);+ std::memset(buf[b], 0, jobs[(size_t) j].bytes);+ }+ } else {+ std::memcpy(buf[b], jobs[(size_t) j].src, jobs[(size_t) j].bytes);+ }ready[(size_t) j].store(1, std::memory_order_release);active.fetch_sub(1, std::memory_order_acq_rel);}@@ -1067,6 +1084,7 @@ struct PfTimer {bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,std::string &err) try {+ err.clear();Impl& m = *impl_;const core::OnDevice on_device(m.device);const core::ModelGeometry& g = *m.g;@@ -1273,6 +1291,8 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,std::vector<StreamEntry> seq;std::vector<size_t> seq_start;size_t issued = 0, consumed = 0;+ static const bool plan_reads = [] { const char* v = std::getenv("STRATA_GGUF_PLAN_READ"); return v && v[0] == '1'; }();+ const core::GgufExpertSource* gsrc = plan_reads ? nullptr : dynamic_cast<const core::GgufExpertSource*>(m.src);if (stream_all) {seq_start.assign((size_t) g.n_layers + 1, 0);std::vector<Stager::Job> js;@@ -1280,12 +1300,18 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,seq_start[(size_t) l] = seq.size();for (int32_t e = 0; e < m.g->n_expert; ++e) {if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;- const uint8_t* b = m.src->blob(l, e);- if (!b) { err = "prefill: expert source has no blob"; return false; }+ const uint8_t* b = nullptr;int job = -1;- if (!m.src->pinned(l, e)) {+ if (gsrc != nullptr) { // read by the stager's thread when its turn comes (see Stager::Job)job = (int) js.size();- js.push_back({b, (size_t) lay0.blob_bytes(l)});+ js.push_back({nullptr, (size_t) lay0.blob_bytes(l), l, e, gsrc});+ } else {+ b = m.src->blob(l, e);+ if (!b) { err = "prefill: expert source has no blob"; return false; }+ if (!m.src->pinned(l, e)) {+ job = (int) js.size();+ js.push_back({b, (size_t) lay0.blob_bytes(l)});+ }}seq.push_back({(int32_t) l, e, b, job});}@@ -1882,9 +1908,10 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,const int32_t e = order[j];if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;if (m.src->pinned(l, e)) continue;+ job_of[j] = (int) js.size();+ if (gsrc != nullptr) { js.push_back({nullptr, (size_t) lay.blob_bytes(l), l, e, gsrc}); continue; }const uint8_t* b = m.src->blob(l, e);if (!b) { err = "prefill: expert source has no blob"; return false; }- job_of[j] = (int) js.size();js.push_back({b, (size_t) lay.blob_bytes(l)});}m.stager->start(std::move(js));diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cppindex e26a005c9..a43090924 100644--- a/sycl/src/program/generate.cpp+++ b/sycl/src/program/generate.cpp@@ -323,8 +323,9 @@ void usage() {" --tokens-file PATH pretokenized prompt, commas or whitespace (alternative to --tokens)\n"" --ple-gguf PATH required PLE table (original second GGUF shard)\n"" --no-ple explicit diagnostic ablation of the PLE layer\n"- " --ple-io direct|mmap n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n"- " reads, the table never enters RAM or the file cache; mmap: A/B arm\n"+ " --ple-io direct|mmap|ram n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n"+ " reads, the table never enters RAM or the file cache; mmap: A/B arm;\n"+ " ram: mmap with the whole table locked in RAM at start (Linux/macOS)\n"" --ple-row-cache N bounded cache of fetched rows, 90 B each (default 1048576; 0 = off)\n"" --ple-inflight N outstanding SSD reads (default 64)\n"" --ple-delay-us U fault injection: each row read completes no earlier than U us\n"@@ -1285,11 +1286,17 @@ int main(int argc, char** argv) {return 2;}- if ((o.ple_io != "direct" && o.ple_io != "mmap") || o.ple_row_cache < 0 || o.ple_inflight < 1 ||+ if ((o.ple_io != "direct" && o.ple_io != "mmap" && o.ple_io != "ram") || o.ple_row_cache < 0 || o.ple_inflight < 1 ||o.ple_inflight > 1024 || !(o.ple_delay_us >= 0)) {std::fprintf(stderr, "strata generate: invalid --ple-io/--ple-row-cache/--ple-inflight/--ple-delay-us\n");return 2;}+#if defined(_WIN32)+ if (o.ple_io == "ram") {+ std::fprintf(stderr, "strata generate: --ple-io ram is not available on Windows (no mlock); use --ple-io mmap\n");+ return 2;+ }+#endifif (o.kv == "q4") o.kv = "q4_0";if (o.kv != "fp16" && o.kv != "int8" && o.kv != "q4_0" && o.kv != "k8v4") {std::fprintf(stderr, "strata generate: --kv must be fp16, int8, q4_0 or k8v4\n");@@ -1414,16 +1421,21 @@ int main(int argc, char** argv) {}}const bool native_pack = strata::kernels::cpu::expert_layout().native;- if (o.expert_cache_remote[0] > 0) {+ // STRATA_EARLY_REMOTE_CONTEXTS=1: create EVERY secondary context here, like CUDA1's. Under WSL2 the driver's+ // pinned/mapped host budget (dxg gpadl, ~1 GiB) is spent by CUDA0's weights and MTP before the later loop runs,+ // and a new context then fails with cudaErrorMemoryAllocation (CUDA2: "cudaSetDevice(2) failed: out of memory").+ const char* early_env = std::getenv("STRATA_EARLY_REMOTE_CONTEXTS");+ const bool early_remote = early_env && early_env[0] == '1';+ for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0 && (r == 0 || early_remote)) {// Keep CUDA1's proven startup order: initialise its context before// allocating GPU0 weights or mapping the large host expert arena.double free_gib = 0;- if (!strata::core::RemoteExperts::preflight(remote_dev[0], free_gib, err)) {+ if (!strata::core::RemoteExperts::preflight(remote_dev[r], free_gib, err)) {std::fprintf(stderr, "strata generate: %s\n", err.c_str());return 1;}std::fprintf(stderr, "strata generate: CUDA%d context ready, %.2f GiB free before expert arena registration\n",- remote_dev[0], free_gib);+ remote_dev[r], free_gib);}// plan v0.3 P6: the PCIe share of the missed experts, measured per kind of pack (the paper, finding on PCIe).// PR #44: a x8 link carries half of what the native default assumes - the GPU's SMs read that share over the@@ -1623,6 +1635,22 @@ int main(int argc, char** argv) {std::fprintf(stderr, "strata generate: session_init failed\n");return 1;}+ // **A GENERATE RUN ON A NATIVE PACK NEVER ZEROED THE SESSION STATE.** The canonical path zeroes it from+ // `put_input` at position 0 (`session_zero`, with the embedding as `R`), but a native pack breaks out of that+ // loop before the first `put_input` - it runs verify windows instead - and neither the batched prompt path+ // nor the verifier zeroes anything. `sbuf` is `cudaMalloc`'d, so the GDN recurrence, the QSA KV/indexer+ // state, the PLE history and `R` all started from whatever the allocator last held: finite on a fresh+ // allocation and overflow/NaN after reuse, which surfaced as the whole layer stack saturating and every+ // prompt decoding to the same token. `--serve` zeroes exactly this state when `resume == 0`; generate mode+ // always starts from an empty sequence, so it must too.+ // (#167) Every pack, not only a native one: a canonical pack whose prompt goes through the batched prompt path+ // (--prefill) starts at position 0 without a put_input, so it never zeroed the state either.+ strata::core::session_zero(ss, g, nullptr, main_cs);+ if (DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()) !=+ 0) {+ std::fprintf(stderr, "strata generate: zeroing the session state failed\n");+ return 1;+ }if (g.n_qsa_layers() > 0 && ss.qsa_states[0].kv_mode == 1)std::fprintf(stderr, "strata generate: KV streaming: %lld of %lld cells per QSA layer in VRAM, the K/V in ""%.2f GiB of pinned RAM\n", (long long) (ss.qsa_states[0].n_slots * 4),@@ -1677,7 +1705,9 @@ int main(int argc, char** argv) {float* ple_scratch = nullptr;if (!o.ple_gguf.empty()) {strata::kernels::PleIoOptions pio;- pio.mode = o.ple_io == "mmap" ? strata::kernels::PleIo::Mmap : strata::kernels::PleIo::Direct;+ pio.mode = o.ple_io == "mmap" || o.ple_io == "ram" ? strata::kernels::PleIo::Mmap : strata::kernels::PleIo::Direct;+ pio.lock = o.ple_io == "ram";+ const auto tpl = Clock::now();pio.max_inflight = (uint32_t) o.ple_inflight;pio.cache_rows = (uint64_t) o.ple_row_cache;pio.io_thread = !o.ple_sync_submit;@@ -1685,6 +1715,10 @@ int main(int argc, char** argv) {std::fprintf(stderr, "strata generate: %s\n", err.c_str());return 1;}+ if (pio.lock)+ std::fprintf(stderr, "strata generate: PLE table %s (--ple-io ram) in %.1f s\n",+ ple_table.locked() ? "locked in RAM" : "loaded (not locked)",+ std::chrono::duration<double>(Clock::now() - tpl).count());const strata::core::WeightRef* wk = wt.find("blk.1.ple_key.weight");const strata::core::WeightRef* wv = wt.find("blk.1.ple_value.weight");const strata::core::WeightRef* wnk = wt.find("blk.1.ple_norm_key.weight");@@ -1884,7 +1918,7 @@ int main(int argc, char** argv) {}// Create the additional contexts after MTP has secured CUDA0 memory, but// before the host arena maps its expert pages into their address spaces.- for (int r = 1; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) {+ for (int r = 1; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0 && !early_remote) {double free_gib = 0;if (!strata::core::RemoteExperts::preflight(remote_dev[r], free_gib, err)) {std::fprintf(stderr, "strata generate: %s\n", err.c_str());@@ -2187,12 +2221,20 @@ int main(int argc, char** argv) {// (with borrowing - the default with a profile - the prompt path lends cache slots instead)const bool borrow = !o.no_prefill_borrow && !o.expert_profile.empty();const int64_t prefill_mib = (o.prefill_chunk > 0 && !borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0;- const int64_t reserve = ((int64_t) o.vram_reserve_mib + prefill_mib) << 20;+ // the draft layer's head and logits are allocated when it binds, after this: 0.1.27's CJK subset made them+ // ~110-180 MiB larger, and out of the reserve they left 16 GB cards below the stall line (#199)+ const int64_t mtp_bind = (!o.mtp.empty() && native_head.loaded())+ ? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : 0;+ const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind;int64_t slots = ((int64_t) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob;if (!profile.empty()) slots = std::min<int64_t>(slots, (int64_t) profile.size());o.expert_cache = (int) std::max<int64_t>(slots, 0);- std::fprintf(stderr, "strata generate: expert cache auto: %.2f GiB free, %d MiB reserved -> %d slots\n",- (double) free_b / 1073741824.0, o.vram_reserve_mib, o.expert_cache);+ std::fprintf(stderr, "strata generate: expert cache auto: %.2f GiB free, %d MiB reserved (+%lld MiB for the "+ "draft head) -> %d slots\n",+ (double) free_b / 1073741824.0, o.vram_reserve_mib, (long long) (mtp_bind >> 20), o.expert_cache);+ if (o.expert_cache == 0) // the verify window cannot start without it (#174): say what makes room+ std::fprintf(stderr, "strata generate: no VRAM is left for the expert cache: lower --max-context, use "+ "--kv k8v4, run images on the CPU, or close other programs that use the GPU\n");} else if (multi_gpu && o.expert_cache > 0) {// a layer split's prompt path has its own buffers (it borrows no slots): an explicit cache size leaves room// for them and the reserve, or the first prompt fails with "device buffers ... do not fit"@@ -2268,6 +2310,7 @@ int main(int argc, char** argv) {// STRATA_TEST_CACHE_FAIL=N: the first N opens fail as an out-of-commit cudaMalloc does (tests the retry)int fake_fails = std::getenv("STRATA_TEST_CACHE_FAIL") ? std::atoi(std::getenv("STRATA_TEST_CACHE_FAIL")) : 0;int failed = 0;+ int zero_reads = 0;for (int attempt = 0;; ++attempt) {bool ok = false;if (fake_fails > 0) {@@ -2318,9 +2361,11 @@ int main(int argc, char** argv) {dpct::get_current_device().get_memory_info(free_b, total_b);const int64_t want = (int64_t) o.vram_reserve_mib << 20;if ((int64_t) free_b >= want - (64ll << 20)) break;- // short by (want - free); a figure of 0 only says "at least", so then give back a quarter as well+ // short by (want - free); a figure of 0 only says "at least": the first two such reads give back 1 GiB+ // each (under WDDM the free figure read before the allocation runs ~0.7 GiB high), later ones a quarterint64_t give = want - (int64_t) free_b + (64ll << 20);- if (free_b < ((size_t) 16 << 20)) give = std::max<int64_t>(give, xcache.bytes() / 4);+ if (free_b < ((size_t) 16 << 20))+ give = std::max<int64_t>(give, ++zero_reads <= 2 ? 1ll << 30 : xcache.bytes() / 4);const int64_t keep_bytes = xcache.bytes() - give;std::fprintf(stderr, "strata generate: only %lld MiB free once the slots are written (reserve %d MiB); ""shrinking the expert cache\n", (long long) (free_b >> 20), o.vram_reserve_mib);@@ -3950,6 +3995,7 @@ int main(int argc, char** argv) {~BusyScope() { strata::core::progress().busy.store(false); strata::core::progress_at("idle"); }} busy_scope;stop_req.store(false); // a STOP that arrived between requests is stale+ err.clear();const bool geni = line.rfind("GENI ", 0) == 0;if (!geni && line.rfind("GEN ", 0) != 0) {std::printf("ERR expected: GEN <max_new> <id,id,...> or GENI <max_new> <file> <id,id,...>\n");@@ -4251,6 +4297,7 @@ int main(int argc, char** argv) {};// tokens [a, b) through the windows: commit all of them, then give the draft layer their residualsauto read_windows = [&](int64_t a, int64_t b, std::string& e) -> bool {+ strata::core::progress_at("reading the prompt (verify windows), from token", a); // #217: not "batched"// every token is committed and the picks are discarded: no head sampling (see set_head_sampling)struct NoHeadSampling {strata::core::Verifier& v;@@ -4403,6 +4450,7 @@ int main(int argc, char** argv) {int64_t at = read_from;for (const int64_t to : {reread_to, root_at, turn_at, n - 1}) {if (to <= at) continue;+ err.clear();const bool win = windows_ok(at, to);if (win && !refill(err)) {std::printf("ERR refilling a lent slot failed: %s\n", err.c_str());@@ -4424,6 +4472,19 @@ int main(int argc, char** argv) {if (!stop_req.load()) {std::fprintf(stderr, "strata serve: %s\n", err.c_str());std::printf("ERR %s\n", err.c_str());+ // #224: a CUDA fault (an illegal address) poisons the context for the whole process, and+ // unwinding the destructors on it could hang until the 60 s watchdog: leave at once+ /*+ DPCT1010: SYCL uses exceptions to report errors and+ does not use the error codes. The cudaPeekAtLastError+ function call was replaced with 0. You need to rewrite+ this code.+ */+ if (0 != 0) {+ std::fflush(stdout);+ std::fflush(stderr);+ std::_Exit(1);+ }return 1;}cancelled = true; // stopped while reading the prompt: refill the lent slots below, then DONE canceldiff --git a/sycl/tools/fixups.py b/sycl/tools/fixups.pyindex 3a75c1a56..17ebf1dd9 100644--- a/sycl/tools/fixups.py+++ b/sycl/tools/fixups.py@@ -239,3 +239,9 @@ edit("src/core/remote_experts.cpp", lambda s: s.replace(edit("include/strata/core/graph.hpp", lambda s: s.replace(" std::chrono::time_point<std::chrono::steady_clock> done__ct1;", " mutable std::chrono::time_point<std::chrono::steady_clock> done__ct1;"))print("files changed:", changed)++# 0.1.29: a stream cast dpct leaves as cudaStream_t (sampler's capture check): the port's queue lookup.+for rel in all_sources():+ edit(str(rel), sub(r"\(\(cudaStream_t\)(\w+)\)->", r"strata::q_of(\1)->"))+# 0.1.29: sycl::free takes void*; NativeEmbed frees a const device pointer.+edit("src/core/native_head.cpp", lambda s: s.replace("sycl::free(dev_, dpct::get_in_order_queue())", "sycl::free((void *) dev_, dpct::get_in_order_queue())"))