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: port open upstream PRs #385 #463 #453 #374 #363 #407 #413 onto 0.1.35
maxfridbefd3214f52e0a
diff --git a/docs/INTEL.md b/docs/INTEL.mdindex dcec06a14..f29eb4a68 100644--- a/docs/INTEL.md+++ b/docs/INTEL.md@@ -28,7 +28,7 @@ PCIe 3.0 x8 slot (the card trains at Gen3 x8 there; it can do Gen5 x16).Decode speed with speculative decoding depends on the text: code drafts well, prose less so (see "Speed dependson the text"). The SYCL numbers are greedy runs of the engine (as in "How to run it by hand" below, 256 new-tokens) on engine 0.1.31-sycl (2026-10-01; 0.1.32-sycl reproduces them exactly);+tokens) on engine 0.1.31-sycl (2026-10-01; 0.1.32-0.1.35-sycl reproduce them exactly);"Decode round 2" below lists what each change bought.## Setup@@ -550,6 +550,26 @@ page-locked batches of 64, and a batch's copies run while the next one is read.(0.33 -> 1.34 GB/s); a whole Coder start from the engine's launch to its first token 82 s -> 26 s, the IQ2_XS120 s -> 41 s (its 8.2 GB host mirror is ~9 s of the rest). Output identical. `STRATA_FILL_SERIAL=1` is the old fill.+**0.1.35 and seven open upstream PRs (2026-10-02).** Upstream main 0.1.33 -> 0.1.35 merged as before, then seven open+PRs ported into `sycl/` ahead of upstream (one dpct run of main + all of them, 3-way merged into only the files they+touch; `sycl/tools/merge_upstream.py`). Their header changes live in `sycl/include` until upstream merges them.++| PR | what | on the B70 |+|---|---|---|+| #385 (sergqwer) | stager: a buffer's first job of a generation waits for the previous DMA from it | race fix; same output |+| #463 (constantindjonkam) | decode waits for an adaptive swap before reading the residency table | determinism fix |+| #453 (architectds) | the drafter's batched K/V on the KV-streaming ring | 128K int8: 888 -> 895 tok/s prompt, 66.6 -> 67.0 decode |+| #374 (sergqwer) | the first chunk's PLE rows read beside layer 0 | part of the 2,184-token prompt's 784 -> 825 tok/s |+| #363 (BlueKingMuch) | the PCIe expert call: group stride, fused SwiGLU + q8_1 | IQ2_XS decode +1.7%; re-done on the port's lane kernels |+| #407 (sergqwer) | `--adapt-tuned` (opt-in) | neutral here; stays opt-in |+| #413 (BlueKingMuch) | DeltaNet recurrence per key head | bit-identical but 8% slower prompt here: off (`STRATA_GDN_KEYHEAD=1`) |++#374 needed two port fixes: its next-chunk read assumed every chunk is the full chunk length (the port's first chunk+is 256 tokens: the second chunk's rows were read from the wrong place), and its host wait on the PLE upload's event,+now inside the layer loop, deadlocked the prompt past ~4K tokens under the Level Zero v2 adapter (the stager's bug+again): the upload is marked by a polled sequence number now. #413's gate is an NVIDIA SM-count rule and its parity+test an SM-holding NVIDIA bench (not built). Outputs identical to 0.1.33 (Coder 19 / 2,184 tokens, IQ2_XS, 40K).+**Not ported yet (2026-10-01).**- Three kernels carry inline PTX (`mma.sync` tensor-core matrix ops, `ldmatrix`, `cp.async`):diff --git a/sycl/CMakeLists.txt b/sycl/CMakeLists.txtindex db55f9409..b32ad9d0e 100644--- a/sycl/CMakeLists.txt+++ b/sycl/CMakeLists.txt@@ -195,6 +195,13 @@ if(STRATA_SYCL_PARITY)add_executable(s2_expert_grouped_parity ${_src})target_link_libraries(s2_expert_grouped_parity PRIVATE strata_kernels)add_test(NAME s2_expert_grouped_parity COMMAND s2_expert_grouped_parity --selftest)+ # upstream PR #363: native_expert_grouped's group stride and fused SwiGLU + q8_1, bitwise vs the v1 launches+ strata_resolve(_src src/kernels/native_grouped_parity.cpp)+ add_executable(native_grouped_parity ${_src})+ target_link_libraries(native_grouped_parity PRIVATE strata_kernels)+ add_test(NAME native_grouped_parity COMMAND native_grouped_parity)+ # (upstream PR #413's gdn_rec_parity is an SM-holding NVIDIA bench - PTX timers, __nanosleep - not built here; the+ # key-head kernel is checked through the engine: output hashes with STRATA_GDN_KEYHEAD=1 and without)# the conversation snapshots (#216) against the engine, as upstream's STRATA_BUILD_CONVERSATION_TESTSstrata_resolve(_src src/core/conversation_snapshot_test.cpp)add_executable(conversation_snapshot_test ${_src})diff --git a/sycl/include/strata/core/verify.hpp b/sycl/include/strata/core/verify.hppindex 3b676c414..11144a648 100644--- a/sycl/include/strata/core/verify.hpp+++ b/sycl/include/strata/core/verify.hpp@@ -269,6 +269,7 @@ private:int32_t* plan_ = nullptr; // device copy of the plan blockuint8_t* staging_ = nullptr; // VRAM slots for the PCIe share of the missesstatic constexpr int64_t kStagingBlobs = 16;+ static constexpr int64_t kPcieGroupRows = 4; // the PCIe call's groups side by side (of <= 16)uint8_t* hit_xq_ = nullptr;uint8_t* nat_xq_ = nullptr; // plan v0.3 P6: q8_1 activations for a native pack's grouped expertsfloat* hit_xs_ = nullptr;diff --git a/sycl/include/strata/kernels/iq_kernels.hpp b/sycl/include/strata/kernels/iq_kernels.hppnew file mode 100644index 000000000..56c0d65e7--- /dev/null+++ b/sycl/include/strata/kernels/iq_kernels.hpp@@ -0,0 +1,77 @@+// include/strata/kernels/iq_kernels.hpp - the i-quant formats (IQ1_M, IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S,+// IQ4_NL) and Q2_0 on the GPU for the IQ2_XS / IQ3_XXS model files, and Q4_K / Q5_K / Q5_1 / Q8_0 for Unsloth's+// UD-Q4_K_XL (gate/up Q4_K or Q5_K, down Q5_1 or Q8_0, a Q8_0 embedding).+//+// The block layouts, codebook grids and dot products are llama.cpp's (ggml-common.h, ggml-cuda/vecdotq.cuh,+// ggml-cuda/dequantize.cuh; MIT, see third_party/ggml/LICENSE and VERSION.txt), so a weight means exactly what it+// means in llama.cpp. Activations are q8_1 (32 values, fp16 scale and fp16 sum), the llama.cpp CUDA contract.+#pragma once++#include <cstddef>+#include <cstdint>++namespace strata::kernels {++/// ggml type ids handled here.+bool iq_supported(int ggml_type) noexcept;+/// The token-embedding types iq_embed_rows and iq_dequant_f32 read: the i-quants above and BF16 (30).+bool embed_type_supported(int ggml_type) noexcept;+/// Bytes of one row of `n` values of `ggml_type` (n a multiple of the type's block).+size_t iq_row_bytes(int ggml_type, int64_t n) noexcept;++/// q8_1 blocks for `n_rows` rows of `n_cols` floats (n_cols a multiple of 32): y is n_rows * n_cols/32 blocks.+void quantize_q8_1_rows(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream);++/// y[c][r] = W[r] . x[c] for `ncols` columns of q8_1 activations (x stride n_in/32 blocks per column).+void iq_mmvq(int ggml_type, const void* w, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream);++/// Dequantize `n` contiguous values (n a multiple of 256) to fp16 / fp32.+void iq_dequant_f16(int ggml_type, const void* src, int64_t n, uint16_t* dst, void* stream);+void iq_dequant_f32(int ggml_type, const void* src, int64_t n, float* dst, void* stream);+/// Rows `tokens[0..n_tok)` (device ids) of a GGUF embedding table (`row_bytes` per row; the table may be mapped+/// host memory) dequantized to fp32, `n_embd` per row (a multiple of 256).+void iq_embed_rows(int ggml_type, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok,+ int64_t n_embd, float* out, void* stream);+/// One expert's gate and up matrices (n_ff rows of n_embd each) into the interleaved fp16 layout the prompt path+/// uses: row 2r = gate row r, row 2r+1 = up row r.+void iq_dequant_gu_f16(int ggml_type, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst,+ void* stream);++/// The layout of one native expert blob: [gate rows | up rows | down rows], raw GGUF blocks.+struct NativeExpertLayout {+ int gu_type = -1, d_type = -1;+ int64_t n_embd = 0, n_ff = 0;+ size_t gu_row = 0, d_row = 0; // bytes per row+ size_t up_off = 0, down_off = 0; // byte offsets inside the blob+ size_t bytes = 0; // the whole blob+};+NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff);+/// Whether `native_expert_grouped` has kernels for this gate/up and down type pair at these dimensions, and the+/// prompt path's dequantizer takes both (checked for every layer at startup, before anything is allocated).+bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept;++/// Bytes of scratch `native_expert_grouped` needs for `cap_entries` entries.+size_t native_expert_scratch_bytes(int64_t cap_entries, int64_t n_ff);++/// Grouped experts in the native format: group g's blob at device address grp_ptr[g]; its entries+/// [grp_start[g], grp_start[g+1]) read token ent_tok[e]'s q8_1 activation (n_embd/32 blocks per token in x_q8_1)+/// and write row ent_dst[e] of `out` (n_embd floats). Counts are read on the device.+/// `grid_groups` (1 .. cap_groups; 0 = cap_groups) groups run side by side, a block row each striding over the rest:+/// a call that usually has few groups or none (the verify window's PCIe share) launches less for the ones it does+/// not have. The results do not depend on it.+void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long* grp_ptr, const int32_t* grp_start,+ const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups,+ int64_t cap_entries, const void* x_q8_1, void* scratch, float* out, void* stream,+ int64_t grid_groups = 0);+/// true: `native_expert_grouped`'s launches before the group stride (STRATA_GROUPED_V1=1 at startup) - a block row+/// per possible group, SwiGLU and the q8_1 quantization as two kernels over all cap_entries. Bitwise the same results+/// (native_grouped_parity checks it); kept for A/B timing. Set before graph capture; captured graphs keep theirs.+void native_grouped_set_v1(bool v1);++/// `iq_mmvq` and `native_expert_grouped` decode each weight part once and apply it to every column / entry;+/// true selects the older kernels that decode it again per column (STRATA_OLD_IQ_MMVQ=1 at startup). Both give+/// bitwise the same results. Set before graph capture; captured graphs keep the kernels they captured.+void iq_set_old_kernels(bool old);+bool iq_old_kernels();++} // namespace strata::kernelsdiff --git a/sycl/include/strata/kernels/ngram.hpp b/sycl/include/strata/kernels/ngram.hppnew file mode 100644index 000000000..9aae9c08c--- /dev/null+++ b/sycl/include/strata/kernels/ngram.hpp@@ -0,0 +1,213 @@+// include/strata/kernels/ngram.hpp - P2.S4: the PLE n-gram hash and the per-layer token table.+//+// Two halves that share nothing but the row indices they exchange:+//+// * `ngram_rows` - the HOST hash. Sixteen row indices per token from the last three token ids, computed+// with 64-bit multiply/xor and no tensor op at all. `qwen4exp.cpp` L1092-1124, where the source says+// outright that it is host-side because "ggml has no int64 and no xor".+// * `PleTable` - the row gather. `per_layer_token_embd.weight` is IQ4_NL and is NOT IN THE PACK: it is+// 51.2e9 elements (28.8 GB) in the ORIGINAL second GGUF shard, and it is the only tensor this engine+// reads from the GGUF rather than from the canonical pack.+//+// THE HASH IS THE ONE PLACE IN THIS MODEL WHERE A WRONG BIT IS SILENTLY PLAUSIBLE. Every one of its+// properties has a rival reading that produces a valid index in range:+//+// * XOR, not sum. Two equal tokens with equal multipliers cancel to zero under XOR and double under sum.+// * `%` vocab_size, not `& (vocab_size-1)`. The vocab sizes are 20000003, 20000023, 20000033, ... - not+// powers of two, so a mask would be a different function.+// * the EOS cut propagates FORWARD: an EOS at any position replaces that position AND every older one.+// * a missing predecessor is `LLAMA_TOKEN_NULL = -1`, tested as `t < 0`. Token id 0 is a REAL token.+// * the token's OWN eos does not cut its own context - only the predecessors are examined.+//+// All of those are asserted observable in `ple_parity.cpp` rather than trusted.+#pragma once++#include <cstdint>+#include <string>++namespace strata::kernels {++// ---- geometry, every value confirmed against the artifact (docs/gguf-metadata.txt) ----+inline constexpr int NG_N_EMBD = 2560; // n_embd+inline constexpr int PLE_HEAD_DIM = 160; // qwen4exp.embedding_length_per_layer_input+inline constexpr int NGRAM_SIZE = 3; // qwen4exp.ple.ngram_size+inline constexpr int HEADS_PER_NGRAM = 8; // qwen4exp.ple.heads_per_ngram+inline constexpr int PLE_N_HEADS = (NGRAM_SIZE - 1) * HEADS_PER_NGRAM; // 16+inline constexpr int PLE_CONV_KERNEL = 4; // qwen4exp.ple.conv_kernel+inline constexpr int32_t PLE_EOS_TOKEN_ID = 248044;+inline constexpr int NG_HC = 4; // hyper_connection.count+inline constexpr int NG_HC_DIM = NG_HC * NG_N_EMBD; // 10240+inline constexpr int NG_HIST = (PLE_CONV_KERNEL - 1) * NGRAM_SIZE; // 9+inline constexpr int32_t TOKEN_NULL = -1; // LLAMA_TOKEN_NULL+inline constexpr float NG_RMS_EPS = 1e-6f;++// The table: [160, 320001536] IQ4_NL. ne0 = 160 is the FAST axis, so one row is 160 contiguous elements =+// 5 blocks of 32 at 18 bytes = 90 bytes. The head-slowest flatten then makes 16 rows exactly n_embd = 2560.+inline constexpr uint64_t PLE_TABLE_ROWS = 320001536ull;+inline constexpr int PLE_ROW_BYTES = (PLE_HEAD_DIM / 32) * 18; // 90: an IQ4_NL row+inline constexpr int PLE_ROW_BYTES_FP8 = PLE_HEAD_DIM; // 160: an F8_E4M3 row, one byte a value+inline constexpr int PLE_ROW_BYTES_MAX = PLE_ROW_BYTES_FP8;++/// The artifact's own hash constants, transcribed from `docs/gguf-dump-shard1.txt`:+///+/// layer_multipliers = [23703573157769, 20109073645365, 8052911324071]+/// head_vocab_sizes = [20000003, 20000023, ...] 16 entries, NOT an arithmetic sequence+/// head_offsets = [0, 20000003, 40000026, ...] the running sum of head_vocab_sizes+///+/// `ref/ngram.py::selftest` calls its own copies "synthetic but STRUCTURALLY REAL"; they are in fact+/// `20000003 + 10*i` for the vocab sizes, which the artifact's are not (20000003, 20000023, 20000033 - the+/// differences are 20, 10, ...). A selftest is free to use whatever constants it likes, but a PARITY test+/// against the artifact must use these, and the difference is recorded because it is exactly the kind of+/// thing that gets copied from the reference into an engine.+struct PleConsts {+ uint64_t mult[NGRAM_SIZE];+ uint64_t vocab[PLE_N_HEADS];+ uint64_t offset[PLE_N_HEADS];+};+PleConsts ple_artifact_consts();++/// `mixed_n = (ctx[0]*m[0]) ^ (ctx[1]*m[1]) ^ ... ^ (ctx[n-1]*m[n-1])` in uint64.+///+/// Exposed separately so a test can assert the XOR STRUCTURE directly rather than only its consequences.+uint64_t ngram_mixed(const int64_t* ctx, const uint64_t* mult, int n);++/// The sixteen row indices per token. `qwen4exp.cpp` L1092-1124.+///+/// tokens (n_tokens,) the ubatch's own tokens+/// prev (n_tokens, 2) predecessors OLDEST FIRST, `TOKEN_NULL` where there is none+/// out (n_tokens, 16) row indices into the PLE table+///+/// The window is built once per token and then only its PREFIXES are used, which is what makes the bigram+/// heads (0..7) and the trigram heads (8..15) agree about the recent history.+void ngram_rows(const int32_t* tokens, const int32_t* prev, int n_tokens, const PleConsts& c, uint32_t* out);++/// The IQ4_NL codebook: `{-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113}`,+/// which is `kvalues_iq4nl` from `ggml-common.h` L1121 and also the manifest's `codebooks.IQ4NL`.+///+/// There is NO `-8` in this version of ggml. Some releases of `dequantize_row_iq4_nl` subtract 8 from the+/// codebook value; at 3cf03257 they do not, and the difference would shift every one of the 51.2e9 elements.+int iq4nl_code(int code);++/// One 90-byte row -> 160 floats. The canonical rule `value = cb[code] * scale + offset` with offset 0,+/// because IQ4_NL has no min term (`has_offset` is false in the manifest).+///+/// THE NIBBLE ORDER IS SPLIT-HALF, NOT INTERLEAVED, and that is the trap here. `dequantize_row_iq4_nl` is+/// y[j] = d * kvalues[qs[j] & 0xf];+/// y[j + QK4_NL/2] = d * kvalues[qs[j] >> 4];+/// so byte j carries elements j and j+16 - NOT 2j and 2j+1, which is the natural reading and which produces+/// a perfectly plausible embedding of the wrong 160 values.+void iq4nl_dequant_row(const uint8_t* row, float* out160);++/// One FP8 row -> 160 floats: each byte an E4M3 value (the "fn" variant: no infinities, 0x7F/0xFF are NaN), times the+/// table's one scale. This is the table as Qwen3.8-Flash-Next ships it (`...ngram_embedding.shard_k`, F8_E4M3, and+/// `weight_scale`), kept byte for byte by tools/ple_fp8_pack.py; IQ4_NL is 8% off it per row.+void fp8_e4m3_dequant_row(const uint8_t* row, float scale, float* out160);++/// How the table's rows are read (plan v0.3 P2). `Direct` is the default: unbuffered 4 KiB reads from the SSD,+/// so the table never occupies RAM or the OS file cache. `Mmap` is the earlier memory-mapped path, kept as the+/// A/B arm; it returns the same bytes.+///+/// NEVER KEEP THE SHARD MAPPED WHILE READING IT DIRECT: a live section on the same file serializes the unbuffered+/// reads (311 -> 1,575 us per token, bench/results/2026-09-23-p2-ssd-direct). Direct mode drops its own mapping+/// after the header parse; nothing else in the process may hold one.+enum class PleIo { Direct, Mmap };++struct PleIoOptions {+ PleIo mode = PleIo::Direct;+ uint32_t max_inflight = 256; ///< outstanding SSD reads (decode needs 16; a prompt chunk saturates the SSD at 256)+ uint64_t cache_rows = 1u << 20; ///< bounded row cache: 1,048,576 rows x 90 B ~ 95 MB; 0 disables+ bool io_thread = true; ///< reads submitted by a worker thread, not the caller+ /// Mmap mode only (`--ple-io ram`): lock the whole mapped table in RAM at open, so no SSD read ever sits on+ /// the prompt or token path. Needs RAM for the full table. POSIX only (mlock); `locked()` reports the outcome.+ bool lock = false;+ /// Direct mode with the I/O worker only: keep the SSD awake while rows are asked for - one page of the table+ /// after this long without a read (0 = off), until `keepalive_window_s` after the last request for rows+ /// (see PleReader::set_keepalive).+ double keepalive_ms = 0;+ double keepalive_window_s = 60;+};++/// The PLE table. Held by pointer-to-impl so this header does not drag `<windows.h>` into every+/// translation unit that wants the hash.+class PleTable {+public:+ PleTable();+ ~PleTable();+ PleTable(const PleTable&) = delete;+ PleTable& operator=(const PleTable&) = delete;++ /// Open with an explicit I/O mode. The two-argument `open` below is the default (Direct).+ bool open(const std::string& gguf_path, std::string& err, const PleIoOptions& io);++ /// The split the plan asks for: `issue` as soon as the token id is known, `collect` just before layer 1+ /// needs the rows. `gather` is `issue` followed by `collect`. In Mmap mode `issue` only prefetches.+ bool issue(const uint32_t* rows16);+ bool collect(float* out2560, std::string& err);+ /// Plan v0.3 P5: the rows of `n_tokens` tokens (16 each, `rows` token-major) into `out` (2560 floats per token),+ /// as ONE reader request - page dedupe and sort across the whole batch, the reader's full queue depth. Not+ /// while a single-token `issue` is pending. The mapped mode gathers row by row.+ bool gather_batch(const uint32_t* rows, size_t n_tokens, float* out, std::string& err);++ /// Fault injection (Direct mode): every row read completes no earlier than `us` after issue.+ void set_injected_delay_us(double us);++ /// Maps the ORIGINAL second GGUF shard read-only. The tensor's data does NOT start at file offset 0:+ /// the manifest's `shard2_tensor.offset` is relative to the GGUF's DATA SECTION, and the header before it+ /// is 192 bytes. Reading at 0 would silently decode the header plus 192 bytes of shifted rows - still+ /// plausible IQ4_NL, which is why the reader takes the offset from a real GGUF parse (`GgufFile`, the+ /// project's validated reader) and checks that the tensor exactly fills the rest of the file.+ bool open(const std::string& gguf_path, std::string& err);+ void close();+ bool is_open() const;+ /// True when `PleIoOptions::lock` was asked for and mlock succeeded (false: pages only pre-touched).+ bool locked() const;+ uint64_t rows() const;+ /// "IQ4_NL" or "F8_E4M3" (a GGUF from tools/ple_fp8_pack.py: type I8, strata.ple.format = f8_e4m3).+ const char* format() const;++ /// 16 row indices -> 2560 floats. The gathered rows are flattened HEAD-SLOWEST: row h's 160 values+ /// occupy `out[h*160, (h+1)*160)`, which is what `ggml_get_rows` does and what makes the result a plain+ /// n_embd-wide vector for the block that consumes it.+ void gather(const uint32_t* rows16, float* out2560) const;++ /// One row -> 160 floats, for diagnostics and for the parity test's oracle comparison.+ void read_row(uint32_t row, float* out160) const;++ /// Bytes actually touched since `open`, for the "how often is it not ready" measurement P2.S4 asks for.+ uint64_t bytes_read() const;++ /// One line of reader statistics (Direct mode), e.g. for --stats. Empty in Mmap mode.+ std::string io_report() const;+ PleIo mode() const;++private:+ struct Impl;+ Impl* impl_ = nullptr;+};++// ================================ THE PLE GATHER'S PREFETCH, AND ITS A/B ARM ================================+//+// `gather` issues its sixteen row reads as sixteen SEPARATE page faults into a 26.8 GB mapping, which measured+// **2.10-2.61 ms per token** and is second only to the layer loop among the token's avoidable terms. The table+// is 90 B per row, so the sixteen rows are 1,440 B - 0.5 MB/s, which is latency and not bandwidth, and it is+// because the sixteen pages are taken one at a time. `PrefetchVirtualMemory` issues them in one call.+//+// **THIS SWITCH EXISTS SO THE CLAIM CAN BE MEASURED RATHER THAN ASSERTED.** Cross-build comparisons in this+// project have repeatedly turned out to be machine drift - `LAYERS` alone moves 48.9 -> 52.3 between runs of+// one binary - so the two arms are alternated inside one session. Off is `--no-ple-prefetch`.+void ple_prefetch_enable(bool on);+bool ple_prefetch_enabled();++// ---- NOTE ON `madvise(MADV_RANDOM)` ------------------------------------------------------------------+// P2.S4 asks for `madvise(MADV_RANDOM)` on the mapping, and on Linux that is exactly right: a token gathers+// 16 rows scattered over 28.8 GB, so read-ahead is pure waste and would evict useful pages.+//+// THERE IS NO LINUX, SO THERE IS NO MADV_RANDOM HERE. Windows has no equivalent of the advice - the closest+// is `FILE_FLAG_RANDOM_ACCESS` at CreateFile time, which suppresses the cache-manager's read-ahead for the+// whole handle, and `PrefetchVirtualMemory` for the positive case. `GgufFile` opens with neither, so this+// build gets the DEFAULT sequential read-ahead on a random access pattern. Saying so is the point: a+// comment claiming MADV_RANDOM here would be a comment about code that does not run. On Linux the advice+// belongs in `GgufFile::open`, which this module does not own.+// ------------------------------------------------------------------------------------------------------++} // namespace strata::kernelsdiff --git a/sycl/include/strata/prefill/kernels.hpp b/sycl/include/strata/prefill/kernels.hppnew file mode 100644index 000000000..bc4187a44--- /dev/null+++ b/sycl/include/strata/prefill/kernels.hpp@@ -0,0 +1,97 @@+// include/strata/prefill/kernels.hpp - plan v0.3 P5: the element-wise and stateful kernels of a prompt chunk.+//+// T tokens at a time, all row-major with the token as the slow index. The arithmetic mirrors the per-token native+// kernels (the decode path), batched; where a step is a recurrence in time (the GDN conv and state, the PLE conv)+// the kernel walks the chunk's tokens in order inside one launch.+#pragma once++#include "strata/kernels/kv_stream.hpp"+#include "strata/kernels/rope_scaling.hpp"++#include <cstdint>++namespace strata::prefill {++// ---- hyper-connection (n_embd 2560, hc 4, hc_lr 320)+/// xn[t, c*2560 + d] = R[t,c,d] * rsqrt(mean_d R[t,c,:]^2 + eps) * w_norm[c*2560 + d]; also its BF16 image.+/// `xn16_lo` (null: none) takes bf16(x - xn16): W.xn16 + W.xn16_lo is the product with ~16 mantissa bits of x.+void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream,+ uint16_t* xn16_lo = nullptr);+/// F-1: gr_norm without its FP32 output: the row scales rs[t*4 + c] and the BF16 image; gr_mix_r then reads R.+void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream,+ uint16_t* xn16_lo = nullptr);+/// gr_mix with xn recomputed from R, rs and w_norm exactly as gr_norm computes it (the same bits).+void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16,+ int64_t T, void* stream, uint16_t* mixed_h = nullptr, uint16_t* mixed16_lo = nullptr);+/// F-2: gr_write, then gr_norm_rs of the next half (its norm weights) over the rows just written - the same bits as+/// the two calls, without reading R back.+void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps,+ float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo = nullptr);+/// lo16[t, k] = bf16(silu(lo[t, k] / hc))+void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo = nullptr);+/// mixed[t, d] = mean_c xn[t, c, d] * sigmoid(gated[t, c, d]); FP32, BF16 and FP16 (either image may be null).+void gr_mix(const float* xn, const float* gated, float* mixed, uint16_t* mixed16, int64_t T, void* stream,+ uint16_t* mixed_h = nullptr, uint16_t* mixed16_lo = nullptr);+/// R[t, c, d] += bo[t, d] * 2 sigmoid(inj[t, c] / hc) (inj has row stride inj_ld)+void gr_write(float* R, const float* bo, const float* inj, int64_t inj_ld, int64_t T, void* stream);+/// R[t, c, :] = e[t, :] for all four streams (the embedding broadcast).+void gr_broadcast(const float* e, float* R, int64_t T, void* stream);++// ---- GDN (state 128, 16 k heads, 48 v heads, 10240 conv channels, 4 taps)+/// gate[t,h] = softplus(ab[t,h] + dt[h]) * ssm_a[h]; beta[t,h] = sigmoid(ab[t, 48 + h]) (ab: [T, 96])+void gdn_gates(const float* ab, const float* dt, const float* ssm_a, float* gate, float* beta, int64_t T, void* stream);+/// The 4-tap causal conv + SiLU over the chunk (history [C][3] in, updated to the chunk's last three inputs), then+/// the L2 norm of the q and k heads of every token. h: [T, C].+void gdn_conv(float* history, const float* qkv, const float* conv_w, float* h, int64_t T, float eps, void* stream);+/// The recurrence over the chunk, state in registers; y16[t] = rmsnorm(o) * gamma * sigmoid(z) in FP16 (what the+/// out projection reads); y is FP32 scratch.+void gdn_recurrence(float* state, const float* h, const float* gate, const float* beta, const float* z,+ const float* gamma, float eps, float* y, uint16_t* y16, int64_t T, void* stream);++// ---- MoE+/// softmax over 512, top-10 (ties to the lower id), weights renormalised over the ten (the native router).+void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t n_expert, void* stream);+/// Expert blob (Strata pack layout, Q2_0) -> BF16 matrices: gate/up interleaved [1280, 2560], down [2560, 640].+void blob_dequant(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream);+/// h16[n, r] = fp16(silu(gu[n, 2r]) * gu[n, 2r + 1]) (the interleaved expert gate/up)+void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, void* stream);+/// h16[n, r] = fp16(silu(g[n, r]) * u[n, r]) (the shared expert, gate and up separate, width 640)+void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, void* stream);+/// dst[i] = src[i] for n int32s, as a kernel: either side may be mapped host memory, and the copy never waits+/// behind the copy engine's queue (the prompt path's grouping tables, while the expert stream fills it).+void copy_i32(int32_t* dst, const int32_t* src, int64_t n, void* stream);+/// Gather rows: dst16[i, :] = x16[src[i], :] (n rows of `width` BF16).+void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int64_t n, int64_t width, void* stream);+/// bo[t, :] = shared[t, :] * sigmoid(sg[t]) + sum_k w[t, k] * D[slot[t, k], :]+void moe_combine(const float* D, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo,+ int64_t T, void* stream);++// ---- QSA helpers+/// In place: x[r, :] = x[r, :] * rsqrt(mean x^2 + eps) * w over rows of `cols` (row stride `ld`).+void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld, float eps, void* stream);+/// NEOX rotary on the first 64 dims of each head: x [T, heads, dim] at positions pos0 + t. The rope+/// scaling (rope_scaling.hpp) rides in as the process config - none is today's arithmetic exactly.+void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pos0,+ const strata::kernels::RopeScaling& scaling, void* stream);+/// q_full [T, 24, 512] (q | gate per head) -> q [T, 24, 256]+void split_q(const float* q_full, float* q, int64_t T, void* stream);+/// attn[t, h, d] *= sigmoid(q_full[t, h, 256 + d]) -> out16 (fp16 bits: the o-projection is quantized)+void gate_attn(const float* attn, const float* q_full, uint16_t* out16, int64_t T, void* stream);++/// K and V of T consecutive cells (positions pos0..pos0+T-1; K normed and rotated) into the paged pools: FP16+/// (`k_pool`/`v_pool`) or INT8 codes + FP16 scale per 64 (`k_q`...), the decode append's arithmetic.+/// K, V: [T, 2, 256].+void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const int32_t* page_table, int64_t page_size,+ uint16_t* k_pool, uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale,+ void* stream, const strata::kernels::KvHostPools* host = nullptr,+ const strata::kernels::KvHostPools* stage = nullptr);++/// fp32 -> fp16 bits and fp32 -> bf16, n elements (the two activation images of the prompt GEMMs).+void to_f16(const float* x, uint16_t* y, int64_t n, void* stream);+void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream, uint16_t* ylo = nullptr);+/// y = fp32(fp16(x)): what an FP16 store of x would read back (the FP16 indexer-key experiment)+void round_f16(const float* x, float* y, int64_t n, void* stream);+/// Expert blob -> FP16 (Q2_0 values are exact in FP16).+void blob_dequant_f16(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream);++} // namespace strata::prefilldiff --git a/sycl/src/core/verify.cpp b/sycl/src/core/verify.cppindex 6ac06f282..e114b75fa 100644--- a/sycl/src/core/verify.cpp+++ b/sycl/src/core/verify.cpp@@ -835,20 +835,21 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {const int32_t* p_start2 = pl + ptr_off + 4 * capx;float* hit_out = hit_out_ + (size_t) tb * K * N;const auto& lay = strata::kernels::cpu::expert_layout();- // plan v0.3 P6: the VRAM groups now; the PCIe groups once the copy engine has landed them in staging- auto grouped = [&](const unsigned long long* gp, const int32_t* gs, const int32_t* gn) {+ // plan v0.3 P6: the VRAM groups now; the PCIe groups once the copy engine has landed them in staging.+ // `gy`: the native launch's groups side by side (0: cap, one block row per possible group).+ auto grouped = [&](const unsigned long long* gp, const int32_t* gs, const int32_t* gn, int64_t gy) {if (lay.native) {// the layer's GGUF formats (i-quant gate/up, Q2_0 / IQ4_NL down)const auto& f = lay.fmt[(size_t) l];const NativeExpertLayout L = native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff);native_expert_grouped(L, gp, gs, gn, p_dst, p_tok, cap, cap,- nat_xq_ + (size_t) tb * (N / 32) * 36, hit_scratch_, hit_out, cs);+ nat_xq_ + (size_t) tb * (N / 32) * 36, hit_scratch_, hit_out, cs, gy);} else {moe_grouped_s2(gp, gs, gn, p_dst, p_tok, cap, cap, hit_xq_ + (size_t) tb * (N / 32) * 34,hit_xs_ + (size_t) tb * (N / 32), hit_scratch_, hit_out, cs);}};- grouped(p_ptr, p_start, p_counts);+ grouped(p_ptr, p_start, p_counts, 0);stamp(l, 20, grp);if (device_plan_) wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs);else wait_flag_ge(m_flagB_, ring, cs); // the PCIe share is in staging (DMA) or mapped@@ -859,7 +860,9 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {rebase_ptrs((unsigned long long*) p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), cs);}stamp(l, 21, grp);- grouped(p_ptr2, p_start2, p_counts + 2);+ // the PCIe share is pcie_frac of the misses: a few groups when the cache is cold, usually none (always none at+ // pcie_frac 0), so its launch is kPcieGroupRows block rows striding over the groups, not cap of them+ grouped(p_ptr2, p_start2, p_counts + 2, kPcieGroupRows);stamp(l, 22, grp);if (device_plan_) { // no CPU share when the device planned the group: its rows are zeroswait_flag_ge_or(m_flag_, ring, skip_ + grp, cs);diff --git a/sycl/src/kernels/cuda/iq_kernels.dp.cpp b/sycl/src/kernels/cuda/iq_kernels.dp.cppindex ac0714979..772316fd5 100644--- a/sycl/src/kernels/cuda/iq_kernels.dp.cpp+++ b/sycl/src/kernels/cuda/iq_kernels.dp.cpp@@ -1338,8 +1338,10 @@ __dpct_inline__ void native_gu_kernel(const int32_t *__restrict__ ent_tok, const block_q8_1 *__restrict__ xq,NativeExpertLayout L, float *__restrict__ gate, float *__restrict__ up) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();- const int g = item_ct1.get_group(1);- if (g >= *n_groups) return; // uniform over the work-group: before the barrier below is fine+ // #363: group g is computed by block row g % gridDim.y (a launch sized for fewer rows than possible groups strides);+ // a block row with no group returns before the barrier below (uniform over the work-group)+ const int ng = *n_groups;+ if ((int) item_ct1.get_group(1) >= ng) return;const void* grid = nullptr;#if STRATA_GRID_SLMif constexpr (TG == 18 || TG == 21 || TG == 22) {@@ -1361,11 +1363,13 @@ __dpct_inline__ void native_gu_kernel(if (row >= 2 * L.n_ff) return;const bool is_up = row >= L.n_ff;const int r = is_up ? row - (int) L.n_ff : row;- const uint8_t* blob = (const uint8_t*) grp_ptr[g];- const uint8_t* wr = blob + (is_up ? L.up_off : 0) + (size_t) r * L.gu_row;+ const size_t off = (is_up ? L.up_off : 0) + (size_t) r * L.gu_row;const int nb = (int) (L.n_embd / Fmt<TG>::qk), xb = (int) (L.n_embd / 32);- const int e0 = grp_start[g], e1 = grp_start[g + 1];- row_entries<TG, LN>(wr, xq, xb, ent_tok, e0, e1, nb, sub, (is_up ? up : gate) + r, (size_t) L.n_ff, grid);+ for (int g = (int) item_ct1.get_group(1); g < ng; g += (int) item_ct1.get_group_range(1)) {+ const uint8_t* wr = (const uint8_t*) grp_ptr[g] + off;+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ row_entries<TG, LN>(wr, xq, xb, ent_tok, e0, e1, nb, sub, (is_up ? up : gate) + r, (size_t) L.n_ff, grid);+ }}// native_gu_kernel with the group's entries taken GRP_NC at a time, each weight part decoded once per pass.@@ -1380,30 +1384,33 @@ __dpct_inline__ void native_gu_multi_kernel(const int32_t *__restrict__ ent_tok, const block_q8_1 *__restrict__ xq,NativeExpertLayout L, float *__restrict__ gate, float *__restrict__ up) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();- const int g = item_ct1.get_group(1);- if (g >= *n_groups) return;const int warp = item_ct1.get_local_id(2) >> 5,lane = item_ct1.get_local_id(2) & 31;const int row = item_ct1.get_group(2) * GU_ROWS + warp; // 0 .. 2*n_ffif (row >= 2 * L.n_ff) return;const bool is_up = row >= L.n_ff;const int r = is_up ? row - (int) L.n_ff : row;- const uint8_t* blob = (const uint8_t*) grp_ptr[g];- const uint8_t* wr = blob + (is_up ? L.up_off : 0) + (size_t) r * L.gu_row;+ const size_t w_off = (is_up ? L.up_off : 0) + (size_t) r * L.gu_row;const int nb = (int) (L.n_embd / Fmt<TG>::qk), xb = (int) (L.n_embd / 32);- const int e0 = grp_start[g], e1 = grp_start[g + 1];float* dst = is_up ? up : gate;- for (int e = e0; e < e1; e += GRP_NC) {- const int n = sycl::min(GRP_NC, e1 - e);- int off[GRP_NC];-#pragma unroll- for (int c = 0; c < GRP_NC; ++c)- off[c] = ent_tok[e + sycl::min(c, n - 1)] * xb;- float s[GRP_NC];- row_dot_multi<TG, GRP_NC>(wr, xq, off, n, nb, lane, s);-#pragma unroll- for (int c = 0; c < GRP_NC; ++c)- if (c < n && lane == c) dst[(size_t) (e + c) * L.n_ff + r] = s[c];+ const int ng = *n_groups;+ for (int g = item_ct1.get_group(1); g < ng;+ g +=+ item_ct1.get_group_range(1)) { // the group stride, as native_gu_kernel+ const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ for (int e = e0; e < e1; e += GRP_NC) {+ const int n = sycl::min(GRP_NC, e1 - e);+ int off[GRP_NC];+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ off[c] = ent_tok[e + sycl::min(c, n - 1)] * xb;+ float s[GRP_NC];+ row_dot_multi<TG, GRP_NC>(wr, xq, off, n, nb, lane, s);+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n && lane == c) dst[(size_t) (e + c) * L.n_ff + r] = s[c];+ }}}@@ -1426,18 +1433,17 @@ __dpct_inline__ void native_down_kernel(const int32_t *__restrict__ ent_dst, const block_q8_1 *__restrict__ hq,NativeExpertLayout L, float *__restrict__ out) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();- const int g = item_ct1.get_group(1);- if (g >= *n_groups) return;+ const int ng = *n_groups; // #363: the group stride, as native_gu_kernelconst int rib = item_ct1.get_local_id(2) / LN,sub = item_ct1.get_local_id(2) % LN;const int r = item_ct1.get_group(2) * (256 / LN) + rib;if (r >= L.n_embd) return;- const uint8_t* blob = (const uint8_t*) grp_ptr[g];- const uint8_t* wr = blob + L.down_off + (size_t) r * L.d_row;+ const size_t off = L.down_off + (size_t) r * L.d_row;const int nb = (int) (L.n_ff / Fmt<TD>::qk), hb = (int) (L.n_ff / 32);- const int e0 = grp_start[g], e1 = grp_start[g + 1];// down: entry e's activation is row e of hq (identity index), its output row is ent_dst[e]- {+ for (int g = (int) item_ct1.get_group(1); g < ng; g += (int) item_ct1.get_group_range(1)) {+ const uint8_t* wr = (const uint8_t*) grp_ptr[g] + off;+ const int e0 = grp_start[g], e1 = grp_start[g + 1];int e = e0;if constexpr (Multi<TD>::has) {for (; e + 4 <= e1; e += 4) {@@ -1471,40 +1477,37 @@ __dpct_inline__ void native_down_multi_kernel(const int32_t *__restrict__ ent_dst, const block_q8_1 *__restrict__ hq,NativeExpertLayout L, float *__restrict__ out) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();- const int g = item_ct1.get_group(1);- if (g >= *n_groups) return;const int warp = item_ct1.get_local_id(2) >> 5,lane = item_ct1.get_local_id(2) & 31;const int r = item_ct1.get_group(2) * 8 + warp;if (r >= L.n_embd) return;- const uint8_t* blob = (const uint8_t*) grp_ptr[g];- const uint8_t* wr = blob + L.down_off + (size_t) r * L.d_row;+ const size_t w_off = L.down_off + (size_t) r * L.d_row;const int nb = (int) (L.n_ff / Fmt<TD>::qk), hb = (int) (L.n_ff / 32);- const int e0 = grp_start[g], e1 = grp_start[g + 1];- for (int e = e0; e < e1; e += GRP_NC) {- const int n = sycl::min(GRP_NC, e1 - e);- int off[GRP_NC];-#pragma unroll- for (int c = 0; c < GRP_NC; ++c)- off[c] = (e + sycl::min(c, n - 1)) * hb;- float s[GRP_NC];- row_dot_multi<TD, GRP_NC>(wr, hq, off, n, nb, lane, s);-#pragma unroll- for (int c = 0; c < GRP_NC; ++c)- if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c];+ const int ng = *n_groups;+ for (int g = item_ct1.get_group(1); g < ng;+ g +=+ item_ct1.get_group_range(1)) { // the group stride, as native_gu_kernel+ const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;+ const int e0 = grp_start[g], e1 = grp_start[g + 1];+ for (int e = e0; e < e1; e += GRP_NC) {+ const int n = sycl::min(GRP_NC, e1 - e);+ int off[GRP_NC];+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ off[c] = (e + sycl::min(c, n - 1)) * hb;+ float s[GRP_NC];+ row_dot_multi<TD, GRP_NC>(wr, hq, off, n, nb, lane, s);+#pragma unroll+ for (int c = 0; c < GRP_NC; ++c)+ if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c];+ }}}// ---------------------------------------------------------------- q8_1 (quantize.cu)-__dpct_inline__ void quantize_q8_1_kernel(const float *__restrict__ x,- block_q8_1 *__restrict__ y,- long long n) {- auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();- const long long i =- (long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) +- item_ct1.get_local_id(2);- if (i >= n) return;- const float xi = x[i];+// value i of a q8_1 row set (the warp holds block i / 32, lane = i % 32)+__dpct_inline__ void q8_1_store(const float xi, block_q8_1 *__restrict__ y,+ const long long i) {float amax = sycl::fabs(xi), sum = xi;#pragma unrollfor (int o = 16; o > 0; o >>= 1) {@@ -1534,6 +1537,56 @@ __dpct_inline__ void quantize_q8_1_kernel(const float *__restrict__ x,if (iqs == 0) y[ib].ds = sycl::half2(d, sum);}+__dpct_inline__ void quantize_q8_1_kernel(const float *__restrict__ x,+ block_q8_1 *__restrict__ y,+ long long n) {+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const long long i =+ (long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) ++ item_ct1.get_local_id(2);+ if (i >= n) return;+ q8_1_store(x[i], y, i);+}++// swiglu_entries_kernel and quantize_q8_1_kernel in one pass, over the call's own entries only:+// [grp_start[0], grp_start[*n_groups]) (a call's entries are contiguous; the verify window's PCIe call starts after+// its VRAM call) instead of all cap_entries twice - nothing reads the others: the down kernel reads its groups'.+// n_ff is a multiple of 32, so a warp is one q8_1 block and the bounds are warp-uniform. The values are the two+// kernels': the SwiGLU product is rounded on its own - it must not contract into the first add of q8_1_store's block+// sum, as it could not when it went through memory (CUDA: __fmul_rn; HIP's __fmul_rn is a plain product, so there+// the product is written here under contract(off)) - then q8_1_store unchanged: the same blocks, bit for bit.+__dpct_inline__ void swiglu_q8_1_entries_kernel(+ const float *__restrict__ gate, const float *__restrict__ up,+ const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,+ int n_ff, block_q8_1 *__restrict__ hq) {+ // the product rounded on its own (no contraction into q8_1_store's block sum), as through memory in the v1 kernels+ // - HIP's form; icpx is clang too (SYCL port)+#pragma clang fp contract(off)+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();+ const long long lo = (long long)grp_start[0] * n_ff,+ hi = (long long)grp_start[*n_groups] * n_ff;+ for (long long i =+ lo ++ (long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) ++ item_ct1.get_local_id(2);+ i < hi; i += (long long)item_ct1.get_group_range(2) *+ item_ct1.get_local_range(2)) {+ const float g = gate[i];+#if defined(__HIPCC__)+ const float h = (g / (1.0f + __expf(-g))) * up[i];+#else+ /*+ DPCT1013: The rounding mode could not be specified and the generated+ code may have different accuracy than the original code. Verify the+ correctness. SYCL math built-in function rounding mode is aligned with+ OpenCL C 1.2 standard.+ */+ const float h = (g / (1.0f + sycl::native::exp(-g))) * up[i];+#endif+ q8_1_store(h, hq, i);+ }+}+// ---------------------------------------------------------------- dequant (dequantize.cuh)template <typename dst_t> __dpct_inline__ dst_t cvt(float v);template <> __dpct_inline__ float cvt<float>(float v) { return v; }@@ -2395,10 +2448,18 @@ size_t native_expert_scratch_bytes(int64_t cap, int64_t n_ff) {return 3 * ((f + 255) & ~(size_t) 255) + (((size_t) cap * (size_t) (n_ff / 32) * sizeof(block_q8_1) + 255) & ~(size_t) 255);}+namespace {+bool g_grouped_v1 = env_on("STRATA_GROUPED_V1");+} // namespace++void native_grouped_set_v1(bool v1) { g_grouped_v1 = v1; }+void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long* grp_ptr, const int32_t* grp_start,const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups,- int64_t cap_entries, const void* x_q8_1, void* scratch, float* out, void* stream) {+ int64_t cap_entries, const void* x_q8_1, void* scratch, float* out, void* stream,+ int64_t grid_groups) {if (cap_groups <= 0 || cap_entries <= 0) return;+ if (L.n_ff % 32 != 0) { std::fprintf(stderr, "native_expert_grouped: n_ff %lld\n", (long long) L.n_ff); std::exit(1); }dpct::queue_ptr s = strata::q_of(stream);const size_t f = (size_t) cap_entries * (size_t) L.n_ff * sizeof(float), fa = (f + 255) & ~(size_t) 255;float* gate = (float*) scratch;@@ -2406,8 +2467,12 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long longfloat* h = (float*) ((uint8_t*) scratch + 2 * fa);block_q8_1* hq = (block_q8_1*) ((uint8_t*) scratch + 3 * fa);const auto* X = (const block_q8_1*) x_q8_1;+ const bool v1 = g_grouped_v1;+ // #363: a verify window's PCIe call usually has no group: `grid_groups` block rows stride over the groups instead+ // of one row per possible group (the results do not depend on it)+ const int64_t gy = (v1 || grid_groups <= 0 || grid_groups > cap_groups) ? cap_groups : grid_groups;const dpct::dim3 ggu((unsigned)((2 * L.n_ff + kExpertRows - 1) / kExpertRows),- (unsigned)cap_groups);+ (unsigned)gy);switch (L.gu_type) {#define STRATA_GU(T) case T: launch_gu<T>(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;STRATA_GU_FMTS(STRATA_GU)@@ -2416,32 +2481,54 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long}check("native_expert_grouped/gu");const long long nh = (long long) cap_entries * L.n_ff;- {- auto exp_props = sycl::ext::oneapi::experimental::properties{- sycl::ext::oneapi::experimental::use_root_sync};+ if (v1) {+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};- s->parallel_for<dpct_kernel_name<class swiglu_entries_kernel_a4959c>>(- sycl::nd_range<3>(sycl::range(1, 1, (unsigned)((nh + 255) / 256)) *- sycl::range(1, 1, 256),- sycl::range(1, 1, 256)),- exp_props, [=](sycl::nd_item<3> item_ct1) {- swiglu_entries_kernel(gate, up, h, nh);- });- }- {+ s->parallel_for<+ dpct_kernel_name<class swiglu_entries_kernel_a4959c>>(+ sycl::nd_range<3>(+ sycl::range(1, 1, (unsigned)((nh + 255) / 256)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ swiglu_entries_kernel(gate, up, h, nh);+ });+ }+ {+ auto exp_props = sycl::ext::oneapi::experimental::properties{+ sycl::ext::oneapi::experimental::use_root_sync};++ s->parallel_for<+ dpct_kernel_name<class quantize_q8_1_kernel_2f9312>>(+ sycl::nd_range<3>(+ sycl::range(1, 1, (unsigned)((nh + 255) / 256)) *+ sycl::range(1, 1, 256),+ sycl::range(1, 1, 256)),+ exp_props,+ [=](sycl::nd_item<3> item_ct1)+ [[sycl::reqd_sub_group_size(32)]] {+ quantize_q8_1_kernel(h, hq, nh);+ });+ }+ } else {auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};- s->parallel_for<dpct_kernel_name<class quantize_q8_1_kernel_3fc248>>(+ s->parallel_for<+ dpct_kernel_name<class swiglu_q8_1_entries_kernel_115291>>(sycl::nd_range<3>(sycl::range(1, 1, (unsigned)((nh + 255) / 256)) *sycl::range(1, 1, 256),sycl::range(1, 1, 256)),exp_props,[=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {- quantize_q8_1_kernel(h, hq, nh);+ swiglu_q8_1_entries_kernel(gate, up, grp_start, n_groups,+ (int)L.n_ff, hq);});}- const dpct::dim3 gd((unsigned)((L.n_embd + kExpertRows - 1) / kExpertRows), (unsigned)cap_groups);+ check("native_expert_grouped/swiglu");+ const dpct::dim3 gd((unsigned)((L.n_embd + kExpertRows - 1) / kExpertRows), (unsigned)gy);switch (L.d_type) {#define STRATA_DOWN(T) case T: launch_down<T>(gd, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;STRATA_D_FMTS(STRATA_DOWN)diff --git a/sycl/src/kernels/native_grouped_parity.cpp b/sycl/src/kernels/native_grouped_parity.cppnew file mode 100644index 000000000..d20565eb2--- /dev/null+++ b/sycl/src/kernels/native_grouped_parity.cpp@@ -0,0 +1,458 @@+// src/kernels/native_grouped_parity.cpp - native_expert_grouped's group stride (grid_groups) and its fused SwiGLU ++// q8_1 pass, against the launches before them (native_grouped_set_v1: a block row per possible group, SwiGLU and the+// q8_1 quantization as two kernels over all cap_entries). Synthetic blobs, no model.+//+// build/native_grouped_parity the checks (a ctest; needs the GPU)+// build/native_grouped_parity --bench the checks, then v1/new timings of 48 calls in a graph (a window's layers)+//+// Every gate/up format with every down format; calls of 0..cap groups of 1..T entries each (an empty call is what the+// verify window's PCIe call usually is), entries from 0 and from past 0 (the PCIe call's follow the VRAM call's),+// scattered destinations, stale scratch, grid_groups 0 (= cap), 1, 2, 3, 4 and above cap: the output must be BITWISE+// equal to v1's, the rows the call must not write included (both start from the same NaN pattern).+//+// Random bytes are valid codes for every format here (every grid index is in range); only the fp16 block scales are+// set, small enough that the SwiGLU outputs keep a finite fp16 q8_1 scale.+#define DPCT_PROFILING_ENABLED+#include <sycl/sycl.hpp>+#include <dpct/dpct.hpp>+#include "strata/kernels/iq_kernels.hpp"++#include <algorithm>+#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <numeric>+#include <random>+#include <string>+#include <vector>++namespace k = strata::kernels;++namespace {++int g_fail = 0;++void ck(dpct::err0 e, const char *what) {+}++template<typename T>+T* dalloc(size_t n) {+ T* p = nullptr;+ ck(DPCT_CHECK_ERROR(p = (T *)sycl::malloc_device(+ n * sizeof(T) + 256, dpct::get_in_order_queue())),+ "malloc");+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(p, 0, n * sizeof(T) + 256).wait()),+ "memset");+ return p;+}++const char* name_of(int t) {+ switch (t) {+ case 16: return "IQ2_XXS";+ case 17: return "IQ2_XS";+ case 18: return "IQ3_XXS";+ case 20: return "IQ4_NL";+ case 21: return "IQ3_S";+ case 22: return "IQ2_S";+ case 23: return "IQ4_XS";+ case 29: return "IQ1_M";+ case 42: return "Q2_0";+ case 12: return "Q4_K";+ case 13: return "Q5_K";+ case 7: return "Q5_1";+ case 8: return "Q8_0";+ default: return "?";+ }+}+int block_values(int t) { return t == 20 || t == 7 || t == 8 ? 32 : t == 42 ? 64 : 256; }++// `rows` rows of `n` values of format t: random bytes, then a finite fp16 scale in every block+std::vector<uint8_t> random_rows(int t, int64_t rows, int64_t n, std::mt19937& rng) {+ const size_t rb = k::iq_row_bytes(t, n), bs = k::iq_row_bytes(t, block_values(t));+ std::vector<uint8_t> w((size_t) rows * rb);+ std::uniform_int_distribution<int> byte(0, 255), ex(2, 8), man(0, 1023), sgn(0, 1);+ for (auto& b : w) b = (uint8_t) byte(rng);+ for (size_t o = 0; o < w.size(); o += bs) {+ if (t == 29) {+ // IQ1_M: the fp16 scale is the top nibbles of its four scale words (bytes 48..55), the sign and the+ // exponent's top bits in the last: 0x1 / 0x2 there (0x9 / 0xA negative) keeps it in 2^-11 .. 2^-3+ const uint8_t nib = (uint8_t) ((sgn(rng) ? 0x8 : 0x0) | (1 + (byte(rng) & 1)));+ w[o + 55] = (uint8_t) ((w[o + 55] & 0x0F) | (nib << 4));+ } else { // the other formats start their block with the fp16 scale: 2^-13 .. 2^-6+ // (Q4_K / Q5_K: 2^-14 .. 2^-11, their 6-bit sub-scales multiply it by up to 63)+ const int e = (t == 12 || t == 13) ? 1 + ex(rng) % 4 : ex(rng);+ const uint16_t h = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (e << 10) | man(rng));+ std::memcpy(&w[o], &h, 2);+ if (t == 12 || t == 13 || t == 7) { // Q4_K / Q5_K: dmin, Q5_1: m - the second fp16, as small+ const int em = (t == 7) ? ex(rng) : 1 + ex(rng) % 4;+ const uint16_t m = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (em << 10) | man(rng));+ std::memcpy(&w[o + 2], &m, 2);+ }+ }+ }+ return w;+}++// one window's worth of expert calls on one format pair: blobs, T tokens' q8_1 activations, cap = T * K entries+struct Setup {+ k::NativeExpertLayout L;+ int T = 0, K = 0, cap = 0, n_blobs = 0;+ size_t slot = 0;+ uint8_t* blobs = nullptr;+ uint8_t* xq = nullptr;+ uint8_t* scr = nullptr;+ size_t scr_bytes = 0;+ float* out = nullptr;+ size_t out_floats = 0;+ unsigned long long* ptr = nullptr;+ int32_t *start = nullptr, *n = nullptr, *dst = nullptr, *tok = nullptr;++ Setup(int gu, int dt, int64_t H, int64_t FF, int tokens, int k_per_token,+ int blobs_n, std::mt19937 &rng, dpct::queue_ptr s) {+ L = k::native_expert_layout(gu, dt, H, FF);+ T = tokens; K = k_per_token; cap = T * K; n_blobs = blobs_n;+ slot = (L.bytes + 255) & ~(size_t) 255;+ blobs = dalloc<uint8_t>(slot * (size_t) n_blobs);+ for (int b = 0; b < n_blobs; ++b) {+ // gate rows | up rows (format gu, H values each) | down rows (format dt, FF values each)+ auto blob = random_rows(gu, 2 * FF, H, rng);+ const auto down = random_rows(dt, H, FF, rng);+ blob.insert(blob.end(), down.begin(), down.end());+ if (blob.size() != L.bytes) { std::fprintf(stderr, "blob %zu != %zu bytes\n", blob.size(), L.bytes); std::exit(2); }+ /*+ 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.+ */+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ blobs + slot * (size_t)b, blob.data(), blob.size()).wait()),+ "blob");+ }+ std::normal_distribution<float> nd(0.f, 1.f);+ std::vector<float> x((size_t) T * H);+ for (auto& v : x) v = nd(rng);+ float* dx = dalloc<float>(x.size());+ /*+ 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.+ */+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dx, x.data(), x.size() * 4).wait()),+ "x");+ xq = dalloc<uint8_t>((size_t) T * (H / 32) * 36);+ k::quantize_q8_1_rows(dx, T, H, xq, s);+ ck(DPCT_CHECK_ERROR(s->wait()), "quantize");+ sycl::free(dx, dpct::get_in_order_queue());+ scr_bytes = k::native_expert_scratch_bytes(cap, FF);+ scr = dalloc<uint8_t>(scr_bytes);+ out_floats = (size_t) cap * H;+ out = dalloc<float>(out_floats);+ ptr = dalloc<unsigned long long>(cap);+ start = dalloc<int32_t>(cap + 1);+ n = dalloc<int32_t>(1);+ dst = dalloc<int32_t>(cap);+ tok = dalloc<int32_t>(cap);+ }+ ~Setup() {+ sycl::free(blobs, dpct::get_in_order_queue());+ sycl::free(xq, dpct::get_in_order_queue());+ sycl::free(scr, dpct::get_in_order_queue());+ sycl::free(out, dpct::get_in_order_queue());+ sycl::free(ptr, dpct::get_in_order_queue());+ sycl::free(start, dpct::get_in_order_queue());+ sycl::free(n, dpct::get_in_order_queue());+ sycl::free(dst, dpct::get_in_order_queue());+ sycl::free(tok, dpct::get_in_order_queue());+ }+ // a plan: `groups` groups of 1..T entries from entry `base` on (as many as fit in cap)+ int plan(int groups, int base, std::mt19937& rng) {+ std::uniform_int_distribution<int> size(1, T);+ std::vector<int> sizes;+ int used = base;+ for (int g = 0; g < groups; ++g) {+ const int m = std::min(size(rng), cap - used);+ if (m <= 0) break;+ sizes.push_back(m);+ used += m;+ }+ return plan_sizes(sizes, base, rng);+ }+ // groups of these sizes from entry `base` on, each its own blob (as long as there are enough: a window's groups+ // are different experts); scattered destinations, random tokens+ int plan_sizes(const std::vector<int>& sizes, int base, std::mt19937& rng) {+ std::uniform_int_distribution<int> tk(0, T - 1);+ std::vector<int> order(n_blobs);+ std::iota(order.begin(), order.end(), 0);+ std::shuffle(order.begin(), order.end(), rng);+ std::vector<unsigned long long> p;+ std::vector<int32_t> st(1, base), tk_v, ds(cap);+ for (const int m : sizes) {+ p.push_back((unsigned long long) (blobs + slot * (size_t) order[p.size() % order.size()]));+ st.push_back(st.back() + m);+ }+ if (st.back() > cap) { std::fprintf(stderr, "plan: %d entries > cap %d\n", st.back(), cap); std::exit(2); }+ const int ng = (int) p.size();+ std::iota(ds.begin(), ds.end(), 0);+ std::shuffle(ds.begin(), ds.end(), rng); // scattered rows of `out`+ for (int e = 0; e < cap; ++e) tk_v.push_back(tk(rng));+ /*+ 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.+ */+ if (ng) ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ ptr, p.data(), p.size() * 8).wait()),+ "ptr");+ /*+ 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.+ */+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(start, st.data(),+ st.size() * 4).wait()),+ "start");+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(n, &ng, 4).wait()),+ "n");+ /*+ 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.+ */+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dst, ds.data(),+ ds.size() * 4).wait()),+ "dst");+ /*+ 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.+ */+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(tok, tk_v.data(),+ tk_v.size() * 4).wait()),+ "tok");+ return ng;+ }+ void call(int64_t grid_groups, dpct::queue_ptr s) {+ k::native_expert_grouped(L, ptr, start, n, dst, tok, cap, cap, xq, scr, out, s, grid_groups);+ }+ // `out` after one call from the NaN pattern, the scratch holding `junk` (what earlier calls left there)+ std::vector<uint32_t> result(bool v1, int64_t grid_groups, int junk,+ dpct::queue_ptr s) {+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memset(out, 0xFF, out_floats * 4)+ .wait()),+ "memset");+ ck(DPCT_CHECK_ERROR(+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(scr, junk, scr_bytes).wait()),+ "memset");+ k::native_grouped_set_v1(v1);+ call(grid_groups, s);+ k::native_grouped_set_v1(false);+ ck(DPCT_CHECK_ERROR(s->wait()), "sync");+ std::vector<uint32_t> o(out_floats);+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())+ .memcpy(o.data(), out, o.size() * 4)+ .wait()),+ "out");+ return o;+ }+};++void check(int gu, int dt, int64_t H, int64_t FF, dpct::queue_ptr s,+ std::mt19937 &rng) {+ Setup S(gu, dt, H, FF, 6, 4, 9, rng, s); // 6 tokens x 4 experts: cap 24 entries+ int calls = 0, bad = 0;+ size_t written = 0;+ for (const int base : {0, 7}) {+ for (const int groups : {0, 1, 2, 3, 5, 8, 24}) {+ const int ng = S.plan(groups, base, rng);+ const auto ref = S.result(true, 0, 0x00, s);+ size_t w = 0;+ for (const uint32_t v : ref) w += v != 0xFFFFFFFFu;+ written += w;+ for (const int64_t gy : {(int64_t) 0, (int64_t) 1, (int64_t) 2, (int64_t) 3, (int64_t) 4, (int64_t) S.cap + 3}) {+ const auto got = S.result(false, gy, (calls & 1) ? 0x7F : 0x00, s);+ ++calls;+ size_t diff = 0;+ for (size_t i = 0; i < ref.size(); ++i) diff += ref[i] != got[i];+ if (diff) {+ std::printf(" %-8s/%-7s base %d, %d groups, grid_groups %lld: %zu of %zu floats differ FAIL\n",+ name_of(gu), name_of(dt), base, ng, (long long) gy, diff, ref.size());+ ++bad;+ }+ }+ }+ }+ std::printf("%-8s/%-7s %5lld x %4lld %d calls: %s (%zu output floats written in all)\n", name_of(gu), name_of(dt),+ (long long) H, (long long) FF, calls, bad ? "FAIL" : "bitwise equal to v1", written);+ if (written == 0) { std::printf(" nothing was written: the check checked nothing FAIL\n"); ++bad; }+ g_fail += bad;+}++// ------------------------------------------------------------------------------------------------ --bench+// A window's 48 calls, one per layer, each with ITS OWN experts as the layers have: copies of the Setup's blobs in one+// arena, so the weights stream from DRAM as in the engine. (48 calls re-reading the same 28 experts - 73 MB, about an+// Ada L2 - would read part of them from L2; the engine's layers share none.)+struct Layers {+ uint8_t* arena = nullptr;+ std::vector<unsigned long long*> ptr; // per layer: its groups' blobs (device)+ Layers(Setup& S, int ng) {+ const int per = std::max(ng, 1);+ arena = dalloc<uint8_t>(S.slot * (size_t) (48 * per));+ for (int l = 0; l < 48; ++l) {+ std::vector<unsigned long long> p;+ for (int j = 0; j < per; ++j) {+ uint8_t* d = arena + S.slot * (size_t) (l * per + j);+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ d,+ S.blobs + S.slot * (size_t)((l * per + j) % S.n_blobs),+ S.L.bytes).wait()),+ "blob copy");+ p.push_back((unsigned long long) d);+ }+ unsigned long long* dp = dalloc<unsigned long long>(p.size());+ /*+ 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.+ */+ ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(+ dp, p.data(), p.size() * 8).wait()),+ "ptr");+ ptr.push_back(dp);+ }+ }+ Layers(const Layers&) = delete;+ Layers& operator=(const Layers&) = delete;+ ~Layers() {+ for (auto *p : ptr)+ DPCT_CHECK_ERROR(sycl::free(p, dpct::get_in_order_queue()));+ sycl::free(arena, dpct::get_in_order_queue());+ }+};++// the 48 calls of one variant captured in one graph+dpct::experimental::command_graph_exec_ptr+make_graph(dpct::queue_ptr s, Setup &S, const Layers &Ls, bool v1, int64_t gy) {+ k::native_grouped_set_v1(v1);+ dpct::experimental::command_graph_ptr g;+ dpct::experimental::command_graph_exec_ptr ge;+ ck(DPCT_CHECK_ERROR(dpct::experimental::begin_recording(s)), "capture");+ for (int l = 0; l < 48; ++l)+ k::native_expert_grouped(S.L, Ls.ptr[l], S.start, S.n, S.dst, S.tok, S.cap, S.cap, S.xq, S.scr, S.out, s, gy);+ ck(DPCT_CHECK_ERROR(dpct::experimental::end_recording(s, &g)), "capture");+ ck(DPCT_CHECK_ERROR(+ ge = new sycl::ext::oneapi::experimental::command_graph<+ sycl::ext::oneapi::experimental::graph_state::executable>(+ g->finalize())),+ "instantiate");+ ck(DPCT_CHECK_ERROR(delete (g)), "graph");+ k::native_grouped_set_v1(false);+ return ge;+}++// one launch of the graph: microseconds per call+float launch_us(dpct::queue_ptr s,+ dpct::experimental::command_graph_exec_ptr ge,+ dpct::event_ptr e0, dpct::event_ptr e1) {+ /*+ 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.+ */+ ck(DPCT_CHECK_ERROR(dpct::sync_barrier(e0, s)), "record");+ ck(DPCT_CHECK_ERROR(s->ext_oneapi_graph(*ge)), "launch");+ /*+ 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.+ */+ ck(DPCT_CHECK_ERROR(dpct::sync_barrier(e1, s)), "record");+ ck(DPCT_CHECK_ERROR(e1->wait_and_throw()), "bench");+ float ms = 0;+ ck(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");+ return 1e3f * ms / 48.0f;+}++float median(std::vector<float> v) {+ std::sort(v.begin(), v.end());+ return v[v.size() / 2];+}++// The two variants' launches ALTERNATE (v1-new, new-v1, ...) after a warm-up, and each reports its median: a card+// under sustained load steps its clock down after a fraction of a second (an RTX 4080 SUPER went from 80 to 89 us+// per gate/up call within one run), and whichever variant ran before the step would look faster.+constexpr int kWarmPairs = 20, kPairs = 40;++void bench(dpct::queue_ptr s, std::mt19937 &rng) {+ std::printf("\n--bench: microseconds per call, a window's 48 calls in a graph, each layer with its own experts (the\n"+ "weights stream from DRAM as in the engine); v1 / new (grid_groups): medians of %d launches each,\n"+ "alternating, after %d warm-up pairs - idle GPU assumed\n", kPairs, kWarmPairs);+ // a verify window's shape: 4 tokens x 10 experts, 2560 x 768 IQ3_S / IQ4_XS experts+ Setup S(21, 23, 2560, 768, 4, 10, 32, rng, s);+ std::vector<int> vram(16, 1);+ vram.insert(vram.end(), 12, 2); // 28 groups, 40 entries+ const struct { const char* what; std::vector<int> sizes; int64_t gy; } rows[] = {+ {"no group (the PCIe call at pcie_frac 0)", {}, 4},+ {"1 group of 2 entries (a PCIe call)", {2}, 4},+ {"28 groups, 40 entries (a VRAM call)", vram, 0},+ };+ dpct::event_ptr e0, e1;+ ck(DPCT_CHECK_ERROR(e0 = new sycl::event()), "event");+ ck(DPCT_CHECK_ERROR(e1 = new sycl::event()), "event");+ for (const auto& r : rows) {+ const int ng = S.plan_sizes(r.sizes, 0, rng);+ const Layers Ls(S, ng); // 48 x 28 experts: 3.7 GB for the VRAM call+ dpct::experimental::command_graph_exec_ptr ga = make_graph(s, S, Ls,+ true, 0),+ gb = make_graph(s, S, Ls,+ false, r.gy);+ std::vector<float> ta, tb;+ for (int i = 0; i < kWarmPairs + kPairs; ++i) {+ const bool a_first = i % 2 == 0;+ const float x = launch_us(s, a_first ? ga : gb, e0, e1), y = launch_us(s, a_first ? gb : ga, e0, e1);+ if (i < kWarmPairs) continue;+ ta.push_back(a_first ? x : y);+ tb.push_back(a_first ? y : x);+ }+ ck(DPCT_CHECK_ERROR(delete (ga)), "graph");+ ck(DPCT_CHECK_ERROR(delete (gb)), "graph");+ std::printf(" %-42s %8.2f / %8.2f us (grid_groups %lld)\n", r.what, median(ta), median(tb), (long long) r.gy);+ }+ dpct::destroy_event(e0);+ dpct::destroy_event(e1);+}++} // namespace++int main(int argc, char** argv) {+ const bool do_bench = argc > 1 && std::string(argv[1]) == "--bench";+ dpct::queue_ptr s;+ ck(DPCT_CHECK_ERROR(s = dpct::get_current_device().create_queue(true)),+ "stream");+ std::mt19937 rng(316);+ for (int gu : {16, 17, 18, 21, 22, 23, 29, 42, 12, 13, 8}) // STRATA_GU_FMTS+ for (int dt : {20, 23, 42, 7, 8}) check(gu, dt, 512, 256, s, rng); // STRATA_D_FMTS; IQ4_XS: n_ff % 256+ check(21, 20, 2560, 640, s, rng); // a model's shapes+ check(21, 23, 2560, 768, s, rng);+ if (do_bench) bench(s, rng);+ std::printf("native_grouped_parity: %d failures\n", g_fail);+ dpct::get_current_device().destroy_queue(s);+ return g_fail ? 1 : 0;+}diff --git a/sycl/src/prefill/kernels.dp.cpp b/sycl/src/prefill/kernels.dp.cppindex 29e30e35a..6c4ca8501 100644--- a/sycl/src/prefill/kernels.dp.cpp+++ b/sycl/src/prefill/kernels.dp.cpp@@ -763,9 +763,254 @@ __dpct_inline__ void gdn_rec_cols_pipe_kernel(float *__restrict__ state,#pragma unrollfor (int r = 0; r < RPG; ++r) base[r * rs] = s[r];}+#if !defined(__HIPCC__)+// The recurrence with one thread for the three value heads that share a key head (head % HK): column c of heads+// qh, qh + 16 and qh + 32, row group rg. gdn_rec_cols_pipe_kernel spends its time in shared memory, not in+// arithmetic: every thread of a warp needs the same 32 q and k values per token (the k twice), and a warp receives one+// such broadcast value per clock however wide the load. Here every q/k value a thread loads feeds three heads, and a+// token's k row goes into registers once for both of its uses. The inputs come in blocks of GDN_TB tokens, copied to+// shared memory by cp.async while the block before computes (one token ahead is shorter than a load from L2 takes),+// and the two cross-row-group sums have their own arrays, so a token needs 2 __syncthreads instead of 5: the second+// one of a token orders every read of rkv before the next token's writes, the next token's first one every read of ro+// before the writes after it. 64 blocks instead of 192. Per value head and column the same arithmetic in the same+// order: the same bits (src/prefill/gdn_rec_parity.cu checks them and times the variants: 1.41x on a 4080 Super).+// sm_80+ with 32 to 47 or 64 and more SMs (gdn_keyhead_ok); STRATA_GDN_KEYHEAD=0: gdn_rec_cols_pipe_kernel.+#if 1 // SYCL port: plain copies (no cp.async)+#define STRATA_GDN_CP_ASYNC 0 // Turing builds: plain copies (never launched there, see gdn_keyhead_ok)+#else+#define STRATA_GDN_CP_ASYNC 1+#endif+__dpct_inline__ void gdn_cp4(float *smem, const float *gmem) {+#if STRATA_GDN_CP_ASYNC+ /*+ DPCT1053: Migration of device assembly code is not supported.+ */+ asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"(+ (unsigned)__cvta_generic_to_shared(smem)),+ "l"(gmem));+#else+ *smem = *gmem;+#endif+}+__dpct_inline__ void gdn_cp16(float *smem, const float *gmem) {+#if STRATA_GDN_CP_ASYNC+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)+ asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(+ (unsigned)__cvta_generic_to_shared(smem)),+ "l"(gmem));+#else+ *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(smem))) =+ *(((uint32_t *)(uintptr_t)gmem));+ if (16 > 4)+ *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(smem)) ++ 1) = *(((uint32_t *)(uintptr_t)gmem) + 1);+ if (16 > 8)+ *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(smem)) ++ 2) = *(((uint32_t *)(uintptr_t)gmem) + 2);+ if (16 > 12)+ *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(smem)) ++ 3) = *(((uint32_t *)(uintptr_t)gmem) + 3);+#endif+#else+ *reinterpret_cast<sycl::float4*>(smem) = *reinterpret_cast<const sycl::float4*>(gmem);+#endif+}+__dpct_inline__ void gdn_cp_commit() {+#if STRATA_GDN_CP_ASYNC+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)+ asm volatile("cp.async.commit_group;\n" ::);+#else++#endif+#endif+}+__dpct_inline__ void+gdn_cp_wait_prev() { // every group but the newest has landed+#if STRATA_GDN_CP_ASYNC+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)+ asm volatile("cp.async.wait_group 1;\n" ::);+#else++#endif+#endif+}+constexpr int GDN_TB = 8, VPK = HV / HK; // tokens per staged block, value heads per key head+/*+DPCT1110: The total declared local variable size in device function+gdn_rec_kh_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_kh_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 TB = GDN_TB, NT = CB * RG, QKP = S / 4,+ VP = CB / 4; // threads, 16-byte pieces of a q/k row, of v+ auto &sq =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[2][TB][S]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &sk =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[2][TB][S]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &sv = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ float[2][TB][VPK][CB]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &sg =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[2][TB][VPK]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &sb =+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[2][TB][VPK]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &rkv = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ float[VPK][RG][CB]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ auto &ro = *sycl::ext::oneapi::group_local_memory_for_overwrite<+ float[VPK][RG][CB]>(+ sycl::ext::oneapi::this_work_item::get_work_group<3>());+ const int qh = 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;+ float s[VPK][RPG];+ const size_t rs = (size_t) HV * S;+#pragma unroll+ for (int j = 0; j < VPK; ++j) {+ const float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col;+#pragma unroll+ for (int r = 0; r < RPG; ++r) s[j][r] = base[r * rs];+ }+ const int64_t nblk = (T + TB - 1) / TB;+ auto stage = [&](int64_t k) { // tokens [k * TB, k * TB + TB) into buffer k & 1+ const int bb = (int) (k & 1);+ const int64_t t0 = k * TB;+ for (int p = tid; p < TB * 2 * QKP; p += NT) {+ const int i = p / (2 * QKP), w = p % (2 * QKP), isk = w / QKP, jj = (w % QKP) * 4;+ if (t0 + i < T)+ gdn_cp16(isk ? &sk[bb][i][jj] : &sq[bb][i][jj], h + (t0 + i) * C + (isk ? HK * S : 0) + qh * S + jj);+ }+ for (int p = tid; p < TB * VPK * VP; p += NT) {+ const int i = p / (VPK * VP), w = p % (VPK * VP), j = w / VP, jj = (w % VP) * 4;+ if (t0 + i < T)+ gdn_cp16(&sv[bb][i][j][jj], h + (t0 + i) * C + 2 * HK * S + (qh + j * HK) * S + cb * CB + jj);+ }+ for (int p = tid; p < 2 * TB * VPK; p += NT) {+ const int isb = p / (TB * VPK), w = p % (TB * VPK), i = w / VPK, j = w % VPK;+ if (t0 + i < T)+ gdn_cp4(isb ? &sb[bb][i][j] : &sg[bb][i][j], (isb ? beta : gate) + (t0 + i) * HV + qh + j * HK);+ }+ };+ if (nblk > 0) stage(0);+ gdn_cp_commit();+ for (int64_t k = 0; k < nblk; ++k) {+ // buffer (k + 1) & 1 was read by block k - 1, whose last token's second __syncthreads every thread has passed+ if (k + 1 < nblk) stage(k + 1);+ gdn_cp_commit();+ gdn_cp_wait_prev();+ /*+ 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 int bb = (int) (k & 1);+ const int n = (int) ((T - k * TB) < TB ? (T - k * TB) : TB);+ for (int i = 0; i < n; ++i) {+ const int64_t t = k * TB + i;+ float kc[RPG];+#pragma unroll+ for (int r = 0; r < RPG; ++r) kc[r] = sk[bb][i][rg * RPG + r];+ float g[VPK], kv[VPK], delta[VPK], o[VPK];+#pragma unroll+ for (int j = 0; j < VPK; ++j) {+ g[j] = sycl::native::exp(sg[bb][i][j]); kv[j] = 0.0f;+ o[j] = 0.0f;+ }+#pragma unroll+ for (int r = 0; r < RPG; ++r)+#pragma unroll+ for (int j = 0; j < VPK; ++j)+ kv[j] = sycl::fma(s[j][r], kc[r], kv[j]);+#pragma unroll+ for (int j = 0; j < VPK; ++j) rkv[j][rg][c] = kv[j];+ /*+ 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 j = 0; j < VPK; ++j) {+ const float kv_col = rkv[j][0][c] + rkv[j][1][c] + rkv[j][2][c] + rkv[j][3][c];+ delta[j] = (sv[bb][i][j][c] - g[j] * kv_col) * sb[bb][i][j];+ }+#pragma unroll+ for (int r = 0; r < RPG; ++r) {+ const float qr = sq[bb][i][rg * RPG + r];+#pragma unroll+ for (int j = 0; j < VPK; ++j) {+ s[j][r] = sycl::fma(g[j], s[j][r], kc[r] * delta[j]);+ o[j] = sycl::fma(s[j][r], (float)qr, o[j]);+ }+ }+#pragma unroll+ for (int j = 0; j < VPK; ++j) ro[j][rg][c] = o[j];+ /*+ 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 < VPK) // row group j writes head j's output+ oc_out[t * HV * S + (qh + rg * HK) * S + col] =+ (ro[rg][0][c] + ro[rg][1][c] + ro[rg][2][c] ++ ro[rg][3][c]) *+ sycl::rsqrt((float)S);+ }+ }+#pragma unroll+ for (int j = 0; j < VPK; ++j) {+ float* base = state + ((size_t) (rg * RPG) * HV + qh + j * HK) * S + col;+#pragma unroll+ for (int r = 0; r < RPG; ++r) base[r * rs] = s[j][r];+ }+}+// gdn_rec_kh_kernel where it pays: a CUDA card with cp.async (sm_80+) that holds all 64 of its blocks at once (each+// walks the whole chunk, so blocks left for a second wave would double the time), and not with 48 to 63 SMs. The+// busiest SM sets the pace: from 64 SMs up this kernel has one block per SM, below that two on some SMs (1.5 times as+// long), while the kernel before has ceil(192 / SMs); two against at most four is a draw. With the engine's grids on+// a 4080 SUPER held to fewer SMs (gdn_rec_parity --bench): 1.40-1.42x at 64 to 80 SMs, 1.02-1.04x at 48 to 63,+// 1.28-1.31x at 39 to 47, 1.53-1.57x at 32 to 38; an Ampere card gained less at 82 SMs (1.28x on a 3090 against+// 1.41x here), so 48 to 63 SMs keep the kernel before. Per call, from the current device (a layer split can mix+// cards).+bool gdn_keyhead_ok() {+ // SYCL port: upstream picks it by SM count and occupancy (NVIDIA thresholds, measured on Ada/Ampere). On Xe the+ // key-head kernel is an A/B until measured: STRATA_GDN_KEYHEAD=1 runs it, anything else keeps the kernel before.+ static const bool on = [] { const char* v = std::getenv("STRATA_GDN_KEYHEAD"); return v != nullptr && std::atoi(v) == 1; }();+ return on;+}+#endif+// the output norm over a head's 128 columns, into the FP16 copy the out projection reads (the FP32 output before the+// norm stays in its scratch buffer)__dpct_inline__ void gdn_out_norm_kernel(const float *__restrict__ z,const float *__restrict__ gamma,- float eps, float *__restrict__ y,+ float eps, const float *__restrict__ y,uint16_t *__restrict__ y16) {auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();auto &wsum = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[4]>(@@ -776,16 +1021,10 @@ auto &wsum = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[4]>(const float oc = y[at];float sp = warp_sum(oc * oc);if ((col & 31) == 0) wsum[col >> 5] = sp;- /*- 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();+ item_ct1.barrier(sycl::access::fence_space::local_space);const float ss = wsum[0] + wsum[1] + wsum[2] + wsum[3];const float v = oc * sycl::rsqrt(ss / (float)S + eps) * gamma[col] *sigm(z[t * HV * S + head * S + col]);- y[at] = v;y16[at] = hf(v);}@@ -1493,7 +1732,24 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const float});} 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)+#if !defined(__HIPCC__)+ if (pipe && gdn_keyhead_ok()) // the value heads of a key head in one thread (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_kh_kernel_c88399>>(+ sycl::nd_range<3>(sycl::range(1, 1, HK * NCB) *+ sycl::range(1, RG, CB),+ sycl::range(1, RG, CB)),+ exp_props, [=](sycl::nd_item<3> item_ct1) {+ gdn_rec_kh_kernel(state, h, gate, beta, y, T);+ });+ } else+#endif+ if (pipe) // the software-pipelined loads (same bits){auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};diff --git a/sycl/src/prefill/prefill.cpp b/sycl/src/prefill/prefill.cppindex 9aeeec065..61777fddd 100644--- a/sycl/src/prefill/prefill.cpp+++ b/sycl/src/prefill/prefill.cpp@@ -273,10 +273,11 @@ struct Stager {const int j = claim(seen);if (j < 0) { active.fetch_sub(1, std::memory_order_acq_rel); break; }const int b = j % kRing;- if (j >= kRing) {+ if (j >= kRing) // job j - kRing's DMA from this buffer is queuedwhile (issued.load(std::memory_order_acquire) <= j - kRing) std::this_thread::yield();- while (!buffer_free(b)) std::this_thread::yield();- }+ // and done (#385) - for a generation's first kRing jobs that is the previous generation's last DMA from+ // the buffer, which nothing else waits for when a chunk ends without a sync (no MTP)+ while (!buffer_free(b)) std::this_thread::yield();const Job& jb = jobs[(size_t) j];if (jb.gsrc != nullptr) {if (!jb.gsrc->read_into(jb.l, jb.e, buf[b], jb.bytes)) {@@ -416,6 +417,12 @@ struct Prefill::Impl {dpct::event_ptr ple_copied[2] ={}; // one runs; the event marks that buffer's upload donestd::vector<uint32_t> ple_rows[2];+ // SYCL port: each buffer's upload is marked by a sequence number the queue writes into page-locked memory after+ // it, polled by the host - not a host wait on `ple_copied` (a host wait on a queue's event hung the prompt path+ // under the Level Zero v2 adapter once #374 moved it inside the layer loop; see Stager::issued_one)+ uint64_t* ple_done_seq = nullptr;+ uint64_t ple_want[2] = {};+ uint64_t ple_seq = 0;float* ple_norm = nullptr;uint8_t* region = nullptr; // the attention/MoE scratch region (idle while the PLE block runs)uint64_t region_bytes = 0;@@ -489,6 +496,7 @@ void Prefill::release() {if (impl_->hand[b])sycl::free(impl_->hand[b], dpct::get_in_order_queue());if (impl_->ple_copied[b]) dpct::destroy_event(impl_->ple_copied[b]);+ if (b == 1 && impl_->ple_done_seq) { sycl::free(impl_->ple_done_seq, dpct::get_in_order_queue()); impl_->ple_done_seq = nullptr; }if (impl_->ple_emb_host[b] && impl_->ple_pageable[b].empty())sycl::free(impl_->ple_emb_host[b], dpct::get_in_order_queue());}@@ -716,6 +724,11 @@ bool Prefill::init(const core::WeightTable &wt, const core::ModelGeometry &g,if (!m.ple_copied[b] &&DPCT_CHECK_ERROR(m.ple_copied[b] = new sycl::event()) != 0)ok = false;+ if (!m.ple_done_seq) {+ m.ple_done_seq = sycl::malloc_host<uint64_t>(2, dpct::get_in_order_queue());+ if (m.ple_done_seq) m.ple_done_seq[0] = m.ple_done_seq[1] = 0;+ else ok = false;+ }m.ple_rows[b].resize(T * strata::kernels::PLE_N_HEADS);}if (ss.qsa_states[ss.qsa_primary()].kv_mode == 1) { // KV streaming: the staging pool's identity page table@@ -882,9 +895,14 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_tstd::string& err) {Impl& m = *impl_;static const bool off = [] { const char* v = std::getenv("STRATA_MTP_BATCH"); return v != nullptr && v[0] == '0'; }();+ // A ring (KV streaming: the drafter's window, page p in slot p % n_slots over a host copy) takes the same appends+ // with its own page table and host copy, as a streamed main layer does; the cells written are those the window can+ // still reach (r0 below), which the ring holds, so no two of them share a slot. STRATA_MTP_BATCH_RING=0: the+ // drafter's own pass for a ring (the A/B).+ static const bool ring_ok = [] { const char* v = std::getenv("STRATA_MTP_BATCH_RING"); return v == nullptr || v[0] != '0'; }();core::QsaState& st = mtp.kv_state_rw();- if (off || n <= 0 || m.g == nullptr || m.region == nullptr || st.kv_mode != 0 || st.kv_hybrid ||- mtp.device() != m.device)+ if (off || n <= 0 || m.g == nullptr || m.region == nullptr || (st.kv_mode != 0 && !(st.kv_mode == 2 && ring_ok)) ||+ st.kv_hybrid || mtp.device() != m.device)return false;const auto t0 = Clock::now();const core::ModelGeometry& g = *m.g;@@ -921,7 +939,10 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t// prompt gets 64-row buffers instead of the per-6-token fallback (19 tokens: 106 ms there, a few ms here)const int64_t cap = (int64_t) (m.region_bytes / per_row) & ~(int64_t) 63;if (cap < 64) return false;- const int64_t B = std::min<int64_t>(std::max<int64_t>(n - r0, 64), cap);+ int64_t B = std::min<int64_t>(std::max<int64_t>(n - r0, 64), cap);+ if (st.kv_mode == 2) // #453: a ring: one batch's cells must not share a slot (a batch can straddle one page more)+ B = std::min<int64_t>(B, ((st.n_slots - 1) * strata::kernels::qsa_real_shapes().page_size) & ~(int64_t) 63);+ if (B < 64) return false;uint8_t* q = m.region;auto carve = [&](size_t bytes) { void* p = q; q += (bytes + 255) & ~(size_t) 255; return p; };float* emb = (float*) carve((size_t) B * Nn * 4);@@ -945,7 +966,12 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_tint32_t* ident = q8 ? (int32_t*) carve((size_t) B * g.hc * 4) : nullptr;int32_t* bnd = q8 ? (int32_t*) carve(16) : nullptr;if ((uint64_t) (q - m.region) > m.region_bytes) return false;+ static const bool timing = std::getenv("STRATA_DRAFT_TIMING") != nullptr; // debug: where this pass's time goes+ if (timing) m.cs->wait();+ const auto ti0 = Clock::now();if (!mtp.idle(err)) return false; // the drafter's own stream (its graph uploads) before this writes its K/V+ const double ms_idle = ms_since(ti0);+ const auto tl0 = Clock::now();strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads;s.idx_dim = g.idx_key_dim;@@ -1046,15 +1072,19 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_treal error-handling function.*//*- 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.+ 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.*/err = std::string("prefill: the draft layer's K/V: ") +dpct::get_error_string_dummy(0);return false;}mtp.ms_prefill += ms_since(t0);+ if (timing)+ std::fprintf(stderr, "strata draft kv: %lld cells from %lld (first needed %lld), batch %lld: drafter idle %.1f ms, "+ "the batches %.1f ms, all %.1f ms\n", (long long) n, (long long) cell0, (long long) (cell0 + r0),+ (long long) B, ms_idle, ms_since(tl0), ms_since(t0));return true;}void Prefill::set_pinned_share(double share) { g_pinned_share = share; }@@ -1331,11 +1361,10 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,const float* row = embd_rows ? embd_rows[p0 + t] : nullptr;if (row) {/*- DPCT1124: cudaMemcpyAsync is migrated to asynchronous- memcpy API. While the origin API might be synchronous, it- depends on the type of operand memory, so you may need to call- wait() on event return by memcpy API to ensure synchronization- behavior.+ DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy+ API. While the origin API might be synchronous, it depends on+ the type of operand memory, so you may need to call wait() on+ event return by memcpy API to ensure synchronization behavior.*/if (DPCT_CHECK_ERROR(m.cs->memcpy(m.emb + t * N, row, (size_t)N * 4)) != 0) {@@ -1348,12 +1377,20 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,}if (hand_in_ == nullptr) gr_broadcast(m.emb, m.R, T, m.cs);lap("embeddings");- // ---- the PLE rows of the whole chunk, one batched SSD request (read ahead on a thread, see ple_gather)- if (ple_on) {+ // ---- the PLE rows of the whole chunk, one batched SSD request on a thread (see ple_gather). A later chunk's+ // were read ahead during the previous chunk; the first chunk's are read beside layer 0 - they are needed from+ // layer 1 on, and gathering them here first left the GPU idle for the whole read (~0.4 s of a 32K prompt)+ if (ple_on && !ple_next.valid())+ ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c0, b = ple_buf] {+ return ple_gather(c0, b, ple_next_err);+ });+ bool ple_pending = ple_on;+ // the chunk's rows onto the device just before layer 1 reads them, and the next chunk's gather started+ auto ple_land = [&]() -> bool {+ if (!ple_pending) return true;+ ple_pending = false;const auto tp = Clock::now();- if (!ple_next.valid()) {- if (!ple_gather(c0, ple_buf, err)) return false;- } else if (!ple_next.get()) {+ if (!ple_next.get()) {err = ple_next_err;return false;}@@ -1363,19 +1400,62 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,type of operand memory, so you may need to call wait() on eventreturn by memcpy API to ensure synchronization behavior.*/- m.cs->memcpy(m.ple_emb, m.ple_emb_host[ple_buf], (size_t)T * N * 4);- dpct::sync_barrier(m.ple_copied[ple_buf], m.cs);- if (c0 + T < n) {- m.ple_copied[ple_buf ^ 1]- ->wait_and_throw(); // the other buffer's upload (a chunk- // ago) is done+ if (DPCT_CHECK_ERROR(m.cs->memcpy(m.ple_emb,+ m.ple_emb_host[ple_buf],+ (size_t)T * N * 4)) != 0 ||+ /*+ 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.+ */+ DPCT_CHECK_ERROR((m.ple_want[ple_buf] = ++m.ple_seq,+ m.cs->fill<uint64_t>(m.ple_done_seq + ple_buf, m.ple_want[ple_buf], 1))) != 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.+ */+ /*+ 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.+ */+ err = std::string("prefill: the PLE rows' upload failed: ") ++ dpct::get_error_string_dummy(0);+ return false;+ }+ if (c0 + T < n) { // SYCL port: T, this chunk's length (the first chunk can be shorter: chunk_len)+ // the other buffer's upload (a chunk ago) is done before the SSD thread refills it+ if (DPCT_CHECK_ERROR([&] {+ while (*(volatile const uint64_t*) (m.ple_done_seq + (ple_buf ^ 1)) < m.ple_want[ple_buf ^ 1])+ std::this_thread::yield();+ }()) != 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.+ */+ /*+ 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.+ */+ err =+ std::string("prefill: the PLE rows' upload failed: ") ++ dpct::get_error_string_dummy(0);+ return false;+ }ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + T, b = ple_buf ^ 1] {return ple_gather(c1, b, ple_next_err);});}ple_buf ^= 1;stats_.ms_ple += ms_since(tp);- }+ return true;+ };for (int64_t t = 0; t < T; ++t) { prev[0] = prev[1]; prev[1] = (int32_t) tokens[c0 + t]; }lap("PLE rows");// ---- the QSA step records of every position in the chunk@@ -1562,6 +1642,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,core::progress_beat(); // the serve watchdog: a prompt chunk of 8192 tokens is still movingcore::progress_at("reading the prompt (batched): layer", l, p0); // #251: a stall names layer and chunkconst core::LayerView v(*m.wt, l);+ if (l == std::max<int64_t>(LB, 1) && !ple_land()) return false; // the PLE rows, read from layer 1 on// ---- the PLE block at layer 1, token by token (its conv reads the previous tokens' rows)if (l == 1 && ple_on && ple_batch) {// the whole chunk at once, in sub-batches carved from the idle scratch region: the key and value@@ -2333,6 +2414,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,strata::kernels::cvec_apply(m.R, l, T, D, nullptr, 0, nullptr, 0, false, m.cs);}}+ if (!ple_land()) return false; // a stage that ends before layer 1: the rows land anyway, the next gather startsif (issuer.joinable()) {issuer.join();stats_.ms_experts_host += iss_ms;@@ -2361,8 +2443,8 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,function.*//*- DPCT1010: SYCL uses exceptions to report errors and does- not use the error codes. The cudaGetLastError function call was+ DPCT1010: SYCL uses exceptions to report errors and does not+ use the error codes. The cudaGetLastError function call wasreplaced with 0. You need to rewrite this code.*/err = std::string("prefill: the layer split's hand-off: ") +@@ -2404,8 +2486,8 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,function.*//*- DPCT1010: SYCL uses exceptions to report errors and does- not use the error codes. The cudaGetLastError function call was+ DPCT1010: SYCL uses exceptions to report errors and does not+ use the error codes. The cudaGetLastError function call wasreplaced with 0. You need to rewrite this code.*/err =@@ -2456,9 +2538,9 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,real error-handling function.*//*- 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.+ 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.*/err = std::string("prefill: ") + dpct::get_error_string_dummy(0);return false;diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cppindex 75a3304f8..9f3389091 100644--- a/sycl/src/program/generate.cpp+++ b/sycl/src/program/generate.cpp@@ -239,7 +239,7 @@ struct Options {/// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM.std::string ple_io = "direct";int64_t ple_row_cache = 1 << 20; ///< bounded row cache (rows of 90 B); 0 disables- int ple_inflight = 64;+ int ple_inflight = 256; // the prompt path reads a chunk's rows at once: 64 left the SSD half idle (32K: 303 -> 189 ms)double ple_delay_us = 0; ///< fault injection: every row read completes no earlier than thisbool ple_sync_submit = false; ///< A/B arm: submit reads on the token thread, no I/O workerstd::string kv = "fp16"; ///< plan v0.3 P7: KV storage, fp16 (default) or int8 (half the VRAM)@@ -376,6 +376,11 @@ struct Options {/// Plan v0.3 P6: every `adapt_every` rounds, swap up to `adapt_swaps` of the most-routed missing experts into/// the VRAM tier in place of the least-routed resident ones (decayed counts). 0 = static residency.int adapt_every = 4;+ float adapt_decay = 0.7f; ///< the usage counts are multiplied by this after each adaptation (--adapt-decay)+ /// --adapt-tuned (STRATA_ADAPT_TUNED=1): every 2 rounds, up to 192 swaps, x0.92 - where that was measured to help+ /// (see where it is applied); explicit --adapt-* flags win+ bool adapt_tuned = false;+ bool adapt_given = false;/// Plan v0.3 P6: a draft enters the verify window only while every draft before it (and itself) has at least/// this probability under the draft layer; 0 = always --spec-1 drafts.double spec_min_p = 0.0;@@ -447,7 +452,7 @@ void usage() {" 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-inflight N outstanding SSD reads (default 256)\n"" --ple-delay-us U fault injection: each row read completes no earlier than U us\n"" --ple-sync-submit A/B arm: submit table reads on the token thread (default: an I/O thread)\n"" --kv fp16|int8 KV storage (plan v0.3 P7): int8 codes + fp16 scale per 64 values, half the\n"@@ -1193,7 +1198,9 @@ int main(int argc, char **argv) try {else if (a == "--mtp") o.mtp = next("--mtp");else if (a == "--mtp-window") o.mtp_window = std::atoll(next("--mtp-window"));else if (a == "--pcie-frac") o.pcie_frac = std::atof(next("--pcie-frac"));- else if (a == "--adapt-every") o.adapt_every = std::atoi(next("--adapt-every"));+ else if (a == "--adapt-every") { o.adapt_every = std::atoi(next("--adapt-every")); o.adapt_given = true; }+ else if (a == "--adapt-decay") { o.adapt_decay = (float) std::atof(next("--adapt-decay")); o.adapt_given = true; }+ else if (a == "--adapt-tuned") o.adapt_tuned = true;else if (a == "--spec-min-p") o.spec_min_p = std::atof(next("--spec-min-p"));else if (a == "--stop-eos") o.stop_eos = true;else if (a == "--spec-split") o.spec_split = true;@@ -1262,7 +1269,7 @@ int main(int argc, char **argv) try {if (!parse_i64_list(next("--eos-ids"), o.eos_ids, e)) { std::fprintf(stderr, "--eos-ids: %s\n", e.c_str()); return 2; }o.stop_eos = true;}- else if (a == "--adapt-swaps") o.adapt_swaps = std::atoi(next("--adapt-swaps"));+ else if (a == "--adapt-swaps") { o.adapt_swaps = std::atoi(next("--adapt-swaps")); o.adapt_given = true; }else if (a == "--expert-cache-cpu-order") o.expert_cache_cpu_order = true;else if (a == "--expert-cache-per-layer") o.expert_cache_per_layer = true;else if (a == "--no-hit-poke") o.no_hit_poke = true;@@ -2370,10 +2377,10 @@ int main(int argc, char **argv) try {st.mrope = sycl::malloc_device<int32_t>(mrope_host.size(), 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.+ 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(st.mrope, mrope_host.data(),@@ -2742,9 +2749,9 @@ int main(int argc, char **argv) try {DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()) == 0 &&DPCT_CHECK_ERROR(dpct::get_device(dev).get_device_info(p)) == 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.+ 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.*/if (!named) 0;const char *name =@@ -2764,8 +2771,8 @@ int main(int argc, char **argv) try {stderr, "strata generate: GPU %d: %s, compute capability %d.%d%s\n",dev, name,/*- DPCT1005: The SYCL device version is different from CUDA Compute- Compatibility. You may need to rewrite this code.+ DPCT1005: The SYCL device version is different from CUDA+ Compute Compatibility. You may need to rewrite this code.*/strata::cc_major_of(p.get_major_version()),strata::cc_minor_of(p.get_minor_version()),@@ -3430,8 +3437,8 @@ int main(int argc, char **argv) try {std::fprintf(stderr, "strata generate: routing-aware prefetch of the file tier on (the next layer's router)\n");} else {/*- DPCT1010: SYCL uses exceptions to report errors and does not use- the error codes. The cudaGetLastError function call was replaced+ DPCT1010: SYCL uses exceptions to report errors and does not+ use the error codes. The cudaGetLastError function call was replacedwith 0. You need to rewrite this code.*/(void)0;@@ -3662,10 +3669,11 @@ int main(int argc, char **argv) try {} else {for (int64_t c = 0; c < g.hc; ++c)/*- DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy- API. While the origin API might be synchronous, it depends on- the type of operand memory, so you may need to call wait() on- event return by memcpy API to ensure synchronization behavior.+ DPCT1124: cudaMemcpyAsync is migrated to asynchronous+ memcpy API. While the origin API might be synchronous, it+ depends on the type of operand memory, so you may need to call+ wait() on event return by memcpy API to ensure synchronization+ behavior.*/if (DPCT_CHECK_ERROR(strata::q_of(token_stream)->memcpy(ss.R + (size_t)c * g.n_embd, d_emb,@@ -3703,6 +3711,10 @@ int main(int argc, char **argv) try {}std::FILE* dump = nullptr;+ // The logits header is written WITH THE FIRST ROW, not at open: a native pack never reaches the+ // per-token dump site, and a header promising rows that were never written is worse than no file.+ int32_t hdr[2] = {0, 0};+ bool hdr_written = false;const int64_t dump_positions = (int64_t) o.tokens.size() - 1 + o.max_new;if (!o.dump_logits.empty()) {if (dump_positions > INT32_MAX || n_vocab > INT32_MAX) {@@ -3722,12 +3734,7 @@ int main(int argc, char **argv) try {// of the size gets a wrong answer that looks authoritative. `tools/logits_identical.py` caught it by// parsing the header and refusing the file.const int32_t n_rows = (int32_t) strata::program::logits_selection::row_count(dump_positions, o.logits_stride);- const int32_t hdr[2] = {(int32_t) n_vocab, n_rows};- if (std::fwrite(hdr, sizeof hdr, 1, dump) != 1) {- std::fprintf(stderr, "strata generate: cannot write logits header\n");- std::fclose(dump);- return 1;- }+ hdr[0] = n_vocab; hdr[1] = n_rows;}// ---- THE C1 ORACLE: ONE RESIDUAL SNAPSHOT PER LAYER PER POSITION, so the engine can be bisected against@@ -3957,8 +3964,8 @@ int main(int argc, char **argv) try {real error-handling function.*//*- DPCT1010: SYCL uses exceptions to report errors and does not use- the error codes. The cudaGetLastError function call was replaced+ DPCT1010: SYCL uses exceptions to report errors and does not+ use the error codes. The cudaGetLastError function call was replacedwith 0. You need to rewrite this code.*/std::fprintf(stderr,@@ -4005,9 +4012,9 @@ int main(int argc, char **argv) try {function.*//*- 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.+ 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.*/dpct::get_error_string_dummy(0));return 1;@@ -4027,9 +4034,9 @@ int main(int argc, char **argv) try {function.*//*- 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.+ 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.*/dpct::get_error_string_dummy(0));return 1;@@ -4117,10 +4124,10 @@ int main(int argc, char **argv) try {st->d_res = sycl::malloc_device<int32_t>(host_res.size(), 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.+ 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(st->d_res, host_res.data(),@@ -4315,6 +4322,28 @@ int main(int argc, char **argv) try {return 1;}}+ // --adapt-tuned: a longer memory and more frequent, larger steps for the adaptive tier, where they were measured+ // to help - a cache that holds 20-60% of the experts, with every expert outside VRAM in RAM. With fewer, a swap+ // evicts experts that are needed again; with more, nearly everything hits already; with experts on the drive, a+ // swap can read it. It pays where the CPU's share of the misses is the round's critical path (large experts).+ if (const char* v = std::getenv("STRATA_ADAPT_TUNED"); v != nullptr) o.adapt_tuned = v[0] != '0';+ if (o.adapt_tuned && !o.adapt_given && o.expert_cache > 0 && !host_res.empty()) {+ const double cover = (double) xcache.slots() / (double) (g.n_layers * g.n_expert);+ bool in_ram = !(o.mmap_experts && !o.resident_cpu_experts);+ if (o.resident_cpu_experts) // the RAM budget must hold every expert the GPU cache does not+ for (int64_t i = 0; i < g.n_layers * g.n_expert && in_ram; ++i)+ if (host_res[(size_t) i] < 0 && !src.has_resident(i / g.n_expert, i % g.n_expert)) in_ram = false;+ const bool fits = cover >= 0.2 && cover <= 0.6 && in_ram;+ if (fits) {+ o.adapt_every = 2;+ o.adapt_swaps = 192;+ o.adapt_decay = 0.92f;+ }+ std::fprintf(stderr, "strata generate: --adapt-tuned: the cache holds %.0f%% of the experts%s -> adaptive tier "+ "every %d rounds, %d swaps, x%.2f%s\n", 100.0 * cover,+ in_ram ? "" : ", some only on the drive", o.adapt_every, o.adapt_swaps, o.adapt_decay,+ fits ? "" : " (the defaults)");+ }if (o.serve) {if (o.spec < 2 || o.mtp.empty() || o.prefill_chunk <= 0 ||(graph_hits && (thits.d_res == nullptr || host_res.empty()))) {@@ -4646,16 +4675,16 @@ int main(int argc, char **argv) try {const strata::core::OnDevice on(stp->dev);stp->sp.reset();/*- 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.+ 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;}sp.reset();/*- DPCT1010: SYCL uses exceptions to report errors and does not- use the error codes. The cudaGetLastError function call was+ DPCT1010: SYCL uses exceptions to report errors and does+ not use the error codes. The cudaGetLastError function call wasreplaced with 0. You need to rewrite this code.*/(void)0;@@ -5081,10 +5110,10 @@ int main(int argc, char **argv) try {try {if (d_res != nullptr)/*- 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.+ 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::get_in_order_queue().memcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t)).wait();@@ -5193,7 +5222,7 @@ int main(int argc, char **argv) try {const strata::core::OnDevice on(st->dev);dpct::sync_barrier(st->adapt_ev, st->adapt_stream);}- for (float& v : drive.d.usage) v *= 0.7f;+ for (float& v : drive.d.usage) v *= o.adapt_decay;return true;};// stdin is read on its own thread, so a STOP line reaches a request that is still running (the client went@@ -6068,7 +6097,13 @@ int main(int argc, char **argv) try {drive.d.layers = 0;drive.d.experts = 0;drive.d.failed = false;- apply_pending(false);+ // THE WAIT IS THE FIX. A non-blocking query here left the next window's residency table to+ // depend on whether the previous round's expert copies had landed: an expert that is resident+ // runs the GPU kernel and one that is not is computed on the CPU, and the two round+ // differently enough to move a logit by ~0.26. Waiting costs the copies' remaining time on a+ // window that follows one that issued them, and buys a residency table that is a function of+ // what was actually copied - which is what makes greedy decode reproducible.+ apply_pending(true);if (hist_n > 0) {// the tails the penalties count over, ONE PER ROW: the tokens the state has consumed, the// fed-back head `x` (it joins `consumed` only after this window commits), then the drafts@@ -6634,8 +6669,8 @@ int main(int argc, char **argv) try {function.*//*- DPCT1010: SYCL uses exceptions to report errors and does not- use the error codes. The cudaGetLastError function call was+ DPCT1010: SYCL uses exceptions to report errors and does+ not use the error codes. The cudaGetLastError function call wasreplaced with 0. You need to rewrite this code.*/(long long)pos, dpct::get_error_string_dummy(0));@@ -6669,6 +6704,17 @@ int main(int argc, char **argv) try {(long long) n_vocab, (long long) pos);return 1;}+ // THE HEADER IS WRITTEN WITH THE FIRST ROW, NOT AT OPEN. A native pack leaves the per-token+ // loop at `if (native_pack) { spec_pos = pos; break; }` and never reaches this site, so a header+ // written at open promised 64 or 66 rows for a file that would contain none - and a reader that+ // trusted it reported "0 differing positions" from a file with no positions in it. Written here,+ // a run that dumps nothing leaves an empty file, which is what actually happened.+ if (emit_logits && !hdr_written && std::fwrite(hdr, sizeof hdr, 1, dump) != 1) {+ std::fprintf(stderr, "strata generate: cannot write logits header\n");+ std::fclose(dump);+ return 1;+ }+ if (emit_logits) hdr_written = true;if (emit_logits && std::fwrite(logits.data(), sizeof(float), (size_t) n_vocab, dump) != (size_t) n_vocab) {std::fprintf(stderr, "strata generate: cannot write logits at position %lld\n", (long long) pos);std::fclose(dump);@@ -6710,8 +6756,8 @@ int main(int argc, char **argv) try {function.*//*- DPCT1010: SYCL uses exceptions to report errors and does not- use the error codes. The cudaGetLastError function call was+ DPCT1010: SYCL uses exceptions to report errors and does+ not use the error codes. The cudaGetLastError function call wasreplaced with 0. You need to rewrite this code.*/dpct::get_error_string_dummy(0));@@ -6844,22 +6890,36 @@ int main(int argc, char **argv) try {std::vector<std::pair<int32_t, int32_t>> pending;dpct::event_ptr adapt_ev = nullptr;adapt_ev = new sycl::event();+ int64_t adapt_rounds = 0; // counted here: `rounds` is declared below the adapt lambdaauto apply_pending = [&](bool wait) {try {if (pending.empty()) return;+ if (wait) adapt_ev->wait_and_throw();+ // STRATA_TRACE_ADAPT: a non-blocking query means the next window reads the residency table+ // with whatever the copy has achieved. Whether the incoming experts are RESIDENT for that+ // window depends on copy latency, and a resident expert runs a different kernel than a+ // CPU-computed one - a far bigger numerical difference than a rounding wobble.+ static const bool trace_pending = std::getenv("STRATA_TRACE_ADAPT") != nullptr;if (wait) adapt_ev->wait_and_throw();else if (adapt_ev->get_info<sycl::info::event::command_execution_status>() !=- sycl::info::event_command_status::complete) return;+ sycl::info::event_command_status::complete) {+ if (trace_pending)+ std::fprintf(stderr, "strata: PENDING not landed, %zu stay non-resident this window\n",+ pending.size());+ return;+ }+ if (trace_pending)+ std::fprintf(stderr, "strata: PENDING landed, %zu experts become resident\n", pending.size());src.commit_exchanges(); // the resident RAM mode: the evicted experts take their places in RAMfor (const auto& [i, slot] : pending) host_res[(size_t) i] = slot;pending.clear();if (d_res != nullptr)/*- 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.+ 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::get_in_order_queue().memcpy(d_res, host_res.data(), host_res.size() * sizeof(int32_t)).wait();@@ -6875,7 +6935,18 @@ int main(int argc, char **argv) try {// routed clearly more often. Copies run between rounds, when the GPU is idle.auto adapt = [&]() -> bool {const Clock::time_point ta = Clock::now();- if (!pending.empty()) return true; // the previous swaps are still in flight+ ++adapt_rounds;+ // STRATA_TRACE_ADAPT: why an adapt round did or did not swap. Default off, one getenv, and it+ // reports the only thing that can make an adapt round a coin flip: whether the PREVIOUS round's+ // asynchronous expert copies had landed by the time this round started.+ static const bool trace_adapt = std::getenv("STRATA_TRACE_ADAPT") != nullptr;+ if (!pending.empty()) {+ if (trace_adapt)+ std::fprintf(stderr, "strata: ADAPT round=%lld SKIPPED, %zu swaps still in flight\n",+ (long long) adapt_rounds, pending.size());+ return true; // the previous swaps are still in flight+ }+ if (trace_adapt) std::fprintf(stderr, "strata: ADAPT round=%lld considering\n", (long long) adapt_rounds);struct Swap { float gain; int32_t layer, in, out; };std::vector<Swap> swaps;std::vector<std::pair<float, int32_t>> cand, vict;@@ -6928,7 +6999,10 @@ int main(int argc, char **argv) try {pending.emplace_back((int32_t) in, slot); // resident once the copy has landed}if (!swaps.empty()) dpct::sync_barrier(adapt_ev, adapt_stream);- for (float& v : drive.d.usage) v *= 0.7f;+ if (trace_adapt)+ std::fprintf(stderr, "strata: ADAPT round=%lld swapped %zu of %d slots, usage decayed\n",+ (long long) adapt_rounds, swaps.size(), o.adapt_swaps);+ for (float& v : drive.d.usage) v *= o.adapt_decay;swaps_total += (int64_t) swaps.size();ms_adapt += std::chrono::duration<double, std::milli>(Clock::now() - ta).count();return true;@@ -7010,7 +7084,13 @@ int main(int argc, char **argv) try {drive.d.layers = 0;drive.d.experts = 0;drive.d.failed = false;- apply_pending(false);+ // THE WAIT IS THE FIX. A non-blocking query here left the next window's residency table to+ // depend on whether the previous round's expert copies had landed: an expert that is resident+ // runs the GPU kernel and one that is not is computed on the CPU, and the two round+ // differently enough to move a logit by ~0.26. Waiting costs the copies' remaining time on a+ // window that follows one that issued them, and buys a residency table that is a function of+ // what was actually copied - which is what makes greedy decode reproducible.+ apply_pending(true);if (!ver.run(T, window.data(), p, &drive_pool_multi, &drive, outv.data(), err)) {std::fprintf(stderr, "strata generate: %s\n", err.c_str());return 1;diff --git a/sycl/tools/fixups.py b/sycl/tools/fixups.pyindex 02caddfdc..ea9dce319 100644--- a/sycl/tools/fixups.py+++ b/sycl/tools/fixups.py@@ -103,6 +103,14 @@ edit("include/strata/kernels/dp4a.hpp", lambda s: s.replace(" __nanosleep(100edit("src/kernels/cuda/fused_gr.dp.cpp", lambda s: s.replace(" cudaDeviceGetAttribute(&per_block, cudaDevAttrMaxSharedMemoryPerBlock, dev);\n"," per_block = (int) dpct::get_device(dev).get_local_mem_size(); // SYCL: the work-group local memory\n"))+# upstream PR #413 / 0.1.36+: the key-head DeltaNet kernel's cp.async helpers keep CUDA's address conversion in the+# non-NVPTX branch; the SYCL build takes the plain-copy form (upstream's own pre-sm_80 path)+def gdn_plain_copies(s):+ s = s.replace("#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP < 800\n#define STRATA_GDN_CP_ASYNC 0",+ "#if 1 // SYCL port: plain copies (no cp.async)\n#define STRATA_GDN_CP_ASYNC 0")+ return s.replace("*reinterpret_cast<float4*>(smem) = *reinterpret_cast<const float4*>(gmem);",+ "*reinterpret_cast<sycl::float4*>(smem) = *reinterpret_cast<const sycl::float4*>(gmem);")+edit("src/prefill/kernels.dp.cpp", gdn_plain_copies)edit("src/kernels/cuda/elementwise.dp.cpp", doorbell)edit("src/kernels/cuda/verify_kernels.dp.cpp", doorbell)