Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

sycl: refresh the port to upstream 0.1.31

maxfridbe90ff5da28e70
diff --git a/docs/INTEL.md b/docs/INTEL.md
index 00a63a397..0fb6d97ab 100644
--- a/docs/INTEL.md
+++ b/docs/INTEL.md
@@ -16,19 +16,19 @@ PCIe 3.0 x8 slot (the card trains at Gen3 x8 there; it can do Gen5 x16).
| | NVIDIA (Strata engine) | Intel Arc, Strata SYCL port | Intel Arc, llama.cpp |
|---|---|---|---|
-| models | all four | the Coder IQ1_M; the original IQ2_XS too (experts beyond VRAM in the host mirror: 51-61 tok/s) | the Coder (fits VRAM) |
+| models | all four | the Coder IQ1_M; the original IQ2_XS too (experts beyond VRAM in the host mirror: 58-64 tok/s) | the Coder (fits VRAM) |
| model files | the same GGUFs | the same GGUFs + a native pack | the same GGUFs |
| where the model lives | experts in RAM, hot ones on the card | every expert in VRAM (`--stream-experts`: no host copy), shard 2's lookup table read from the SSD by row | all of shard 1 on the card, shard 2 paged from disk |
| RAM needed | 32-64 GB | little (23 GB is fine) | little (23 GB is fine) |
-| decode, Coder IQ1_M | 44-51 tok/s on an RTX 5070 | **77.9 tok/s** (19-token prompt, 256 greedy tokens), **74.2** after a 2,184-token prompt, **66.1** after 128K, 54.1 after 256K; 48-72 through the API | 23-25 tok/s |
-| prompt reading | ~1,870 tok/s | **787 tok/s** at 2,184 tokens, 856 at 128K, 740 at 256K | ~150 tok/s (424 at 105K) |
+| decode, Coder IQ1_M | 44-51 tok/s on an RTX 5070 | **78.2 tok/s** (19-token prompt, 256 greedy tokens), **75.7** after a 2,184-token prompt, 59.5 after 128K, 48.7 after 256K; 48-72 through the API | 23-25 tok/s |
+| prompt reading | ~1,870 tok/s | **780 tok/s** at 2,184 tokens, 1,189 at 40K, 934 at 128K, 784 at 256K | ~150 tok/s (424 at 105K) |
| speculative decoding (MTP) | yes | yes (the base checkpoint's draft layer; 70-85% of drafts accepted on code) | no |
| images | yes | not yet | not yet |
-| context | up to 262K | 256K measured, 54 tok/s decode there (`--kv-resident`: the KV in pinned host memory, the attended window in VRAM) | 131K measured ceiling |
+| context | up to 262K | 256K measured, 49 tok/s decode there (`--kv-resident`: the KV in pinned host memory, the attended window in VRAM) | 131K measured ceiling |
Decode speed with speculative decoding depends on the text: code drafts well, prose less so (see "Speed depends
on the text"). The SYCL numbers are greedy runs of the engine (as in "How to run it by hand" below, 256 new
-tokens) on the 2026-10-01 build;
+tokens) on engine 0.1.31-sycl (2026-10-01);
"Decode round 2" below lists what each change bought.
## Setup
@@ -298,24 +298,29 @@ output tokens between paths, never only timings.
It costs ~1 s on short prompts (2,184 tokens: 610 vs 792 tok/s), so the port borrows by default only above a
32K context (`--prefill-borrow` / `--no-prefill-borrow` decide explicitly).
-**Long contexts (2026-10-01, the current build, setup's flags: `--kv-resident 32768 --vram-reserve-mib 2048
---prefill 4096`, prompt-slot borrowing on).** Same text repeated to length, then 256 greedy tokens:
+**Long contexts (2026-10-01, engine 0.1.31-sycl, setup's flags: `--kv-resident 32768 --vram-reserve-mib 2048
+--prefill 4096`, prompt-slot borrowing off - see the 0.1.31 merge below).** Same text repeated to length, then 256
+greedy tokens:
-| context | KV | prompt | decode after | peak VRAM | experts in VRAM (of 12,288) |
+| context | KV | prompt | decode after | peak VRAM | experts in the host mirror |
|---|---|---|---|---|---|
-| 128K | int8 | 856 tok/s (150 s) | **66.1 tok/s** | 29.9 GB | 12,288 |
-| 128K | q4_0 | 834 tok/s (153 s) | 62.4 tok/s | 29.7 GB | 12,288 |
-| 256K | int8 | 740 tok/s (346 s) | **54.1 tok/s** | 30.2 GB | 12,288 |
-| 256K | q4_0 | 726 tok/s (353 s) | 52.5 tok/s | 29.9 GB | 12,288 |
-| 128K | k8v4, KV in VRAM | **995 tok/s** (129 s) | 65.8 tok/s | 30.7 GB | 12,241 (47 in the host mirror) |
-| 256K | k8v4, KV in VRAM | **804 tok/s** (318 s) | 51.2 tok/s | 30.6 GB | 11,294 (994, 1.9 GB, in the host mirror) |
+| 128K | int8 | 934 tok/s (137 s) | **59.5 tok/s** | 29.7 GB | 1,040 (2.0 GB) |
+| 128K | q4_0 | 887 tok/s (144 s) | 53.4 tok/s | 29.3 GB | 1,073 |
+| 128K | k8v4, KV in VRAM | **1,026 tok/s** (125 s) | 54.4 tok/s | 29.5 GB | 1,523 (2.9 GB) |
+| 256K | int8 | 784 tok/s (327 s) | **48.7 tok/s** | 29.7 GB | 1,288 (2.5 GB) |
+| 256K | q4_0 | 763 tok/s (336 s) | 43.2 tok/s | 29.6 GB | 1,188 |
+| 256K | k8v4, KV in VRAM | 838 tok/s (305 s) | 42.3 tok/s | 29.5 GB | 2,327 (4.5 GB) |
+
+Before the merge, with borrowing (every expert in VRAM): 128K int8 856 / 66.1, 256K int8 740 / 54.1 tok/s. Without
+borrowing the prompt buffers keep their own VRAM, ~1,000-2,300 experts move to the pinned host mirror (planned item
+2) and decode pays ~10-17% for reading them over PCIe; the prompt is 4-9% faster.
KV streaming (`--kv-resident`) keeps the whole KV in pinned host memory and only the attended window in VRAM, so
-every expert stays on the card at any context; setup.py turns it on from 64K up and keeps INT8 (the faster of the
+the KV pushes no experts out; setup.py turns it on from 64K up and keeps INT8 (the faster of the
two at every size here). Without it the KV pushes experts out and decode after the prompt fell to 4-9 tok/s at
128K-256K (2026-09-30). `--kv k8v4` does not support streaming yet: setup keeps its KV in VRAM, which pushes up to
-~1,000 experts out at 256K; those come from the pinned host mirror over PCIe (planned item 2), so decode holds at
-51 tok/s (it was 3.8 before the mirror). k8v4 reads prompts fastest (no streaming copies) and works through the FP32
+more experts out; those come from the pinned host mirror over PCIe (planned item 2), so decode holds at 42 tok/s at
+256K (it was 3.8 before the mirror). k8v4 reads prompts fastest (no streaming copies) and works through the FP32
attention fallback (its dedicated prompt kernel is the XMX one below).
**XMX prompt attention v2.** 64-cell chunks, vector-packed K^T and V, hi+lo Q in one accumulator per scale group,
@@ -469,6 +474,33 @@ wherever upstream touched a file they mirror. They are refreshed by re-migration
5. A fixup whose pattern upstream changed shows up as a compile error (the PTX gate became an `#elif`
under upstream's `__HIPCC__` guard); extend the fixup, re-run it, rebuild.
+**The 0.1.31 merge (2026-10-01).** Upstream 0.1.29 -> 0.1.31 (132 commits) by the steps above: 45 migrated files
+changed for real (27 more only in dpct's kernel-name hashes), 38 conflicts resolved, verify.cpp/mtp.cpp/
+conversation_state.cpp ported by hand. A symbol audit (the port's feature identifiers counted before and after) is
+part of the procedure now: it caught a dropped mirror hook and four doorbell waits that had lost their spin bound
+(upstream renamed the loops; `fixups.py` covers both spellings). What the merge needed beyond conflicts:
+
+- **The expert kernels.** Upstream sends the i-quant experts to new multi kernels (one warp per row, 8 rows a
+ group); the port's grid is sized for its own kernels (8 lanes a row, 32 rows a group), so only a quarter of each
+ expert's rows were written and the output was end-of-text tokens. The port's kernels stay the default (they also
+ serve upstream's new Q4_K/Q5_K/Q5_1/Q8_0 experts); `STRATA_EXPERT_SPLIT=1` runs upstream's, with their grid.
+- **Prompt-slot borrowing hangs** in the first chunk of any prompt with it on (40K, 128K; GPU busy, no chunk ends)
+ since upstream's borrow rework. Off by default on SYCL (`--prefill-borrow` opts in); long prompts are faster
+ without it, decode after them ~10-17% slower (the table above). Open.
+- **Upstream's new tests found three dpct mistranslations from the first migration.** dpct writes `__fadd_rn(a, b)`
+ as `a + b` without parentheses, so `__fadd_rn(sum, c ? x : y)` became `sum + c ? x : y` (replaced, not added): in
+ the native QSA indexer's per-token pooled key (the decode path: blocks completed while generating got wrong
+ pooled keys; prompt blocks come from the batched kernel and were right), in the native QSA scores (an opt-in
+ path) and in the s2 activation rounding (every value 0; the Q2_0 s2 pack, unused here). Fixed, and `fixups.py`
+ now parenthesises. `qsa_parity`'s batch-vs-sequential test passes; decode output after long prompts changed.
+- **Upstream's new kernels against the port's on the B70** (decode tok/s, Coder 19 / 2,184-token prompts, IQ2_XS
+ 19): port defaults 78.1 / 75.7 / 58.6; `STRATA_EXPERT_SPLIT=1` 65.6-69.5 / 67.2 / 49.1 (-11 to -16%);
+ `STRATA_GR_V3=1` 73.2 / 72.4 (-4 to -6%). Both stay opt-in.
+- **Speed after the merge:** Coder 78.2 / 75.7 tok/s (as before), IQ2_XS 58.6 / 64.2 (from 50.8 / 60.6).
+- **Still failing:** `iq_multi_parity` on IQ2_XS (type 17: the port's mmvq disagrees with the reference, old and new
+ kernel alike; no model here uses it), `s2_expert_grouped_parity` (the s2 path), `kv_hybrid_parity`'s last step
+ (needs the unported tensor-core prompt kernel). `ple_parity` and `native_expert_parity` need model files.
+
**Not ported yet (2026-10-01).**
- Three kernels carry inline PTX (`mma.sync` tensor-core matrix ops, `ldmatrix`, `cp.async`):
@@ -486,12 +518,12 @@ wherever upstream touched a file they mirror. They are refreshed by re-migration
- Speculative decoding on the llama.cpp path (the GGUF carries no draft layer llama.cpp can use). The SYCL
port has it (MTP draft layer, `--mtp`).
-## Measured, 2026-10-01, Arc Pro B70, Coder IQ1_M, 32K context, INT8 KV: the SYCL port
+## Measured, 2026-10-01, Arc Pro B70, Coder IQ1_M, 32K context, INT8 KV: the SYCL port (engine 0.1.31-sycl)
| | |
|---|---|
-| decode | 77.9 tok/s on a 19-token prompt, 74.2 after a 2,184-token prompt (256 greedy tokens, MTP + suffix drafts) |
-| prompt | 787 tok/s on 2,184 tokens; 856 tok/s at 128K, 740 at 256K |
+| decode | 78.2 tok/s on a 19-token prompt, 75.7 after a 2,184-token prompt (256 greedy tokens, MTP + suffix drafts) |
+| prompt | 780 tok/s on 2,184 tokens; 934 tok/s at 128K, 784 at 256K |
| through the API | 48-72 tok/s on a ~190-token chat answer, prompt included (the first request after a start is the slower one) |
| VRAM | all 12,288 experts resident, ~1.9 GB free with everything loaded (`--vram-reserve-mib 1024`) |
| RAM | no host copy of the experts (`--stream-experts`) |
diff --git a/sycl/CMakeLists.txt b/sycl/CMakeLists.txt
index 11be21cab..c7e3697a3 100644
--- a/sycl/CMakeLists.txt
+++ b/sycl/CMakeLists.txt
@@ -10,7 +10,7 @@
#
# Device code is JIT-compiled from SPIR-V unless STRATA_SYCL_AOT names a device (bmg-g31 for the Arc Pro B70).
cmake_minimum_required(VERSION 3.24)
-project(strata_sycl VERSION 0.1.24 LANGUAGES C CXX)
+project(strata_sycl VERSION 0.1.31 LANGUAGES C CXX) # the upstream engine version this port tracks
set(STRATA_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/..)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -120,12 +120,14 @@ if(STRATA_NATIVE_EXPERTS)
endif()
add_subdirectory(${strata_llamacpp_SOURCE_DIR}/ggml ${CMAKE_BINARY_DIR}/ggml EXCLUDE_FROM_ALL)
endif()
- strata_resolve(_cpu_native src/kernels/cpu/native_expert.cpp src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/iq_avx2.cpp)
+ strata_resolve(_cpu_native src/kernels/cpu/native_expert.cpp src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/iq_avx2.cpp
+ src/kernels/cpu/kq_avx2.cpp) # 0.1.31: the Q4_K/Q5_K/Q5_1/Q8_0 expert rows
target_sources(strata_kernels_cpu PRIVATE ${_cpu_native})
target_include_directories(strata_kernels_cpu PRIVATE ${STRATA_ROOT}/third_party/ggml)
set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS
"-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma")
set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/iq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
+ set_source_files_properties(${STRATA_ROOT}/src/kernels/cpu/kq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c")
target_link_libraries(strata_kernels_cpu PUBLIC ggml-cpu ggml-base)
target_compile_definitions(strata_kernels_cpu PUBLIC STRATA_NATIVE_EXPERTS=1)
endif()
@@ -153,8 +155,10 @@ target_link_libraries(strata_kernels PUBLIC strata_core)
strata_resolve(_engine src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp
src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp
- src/core/mtp.cpp)
+ src/core/mtp.cpp src/core/conversation_snapshot.cpp src/core/conversation_state.cpp
+ src/core/conversation_memory.cpp) # 0.1.31: the conversation snapshots (#216)
add_library(strata_engine STATIC ${_engine} ${CMAKE_CURRENT_SOURCE_DIR}/src/core/gguf_expert_source.cpp)
+target_include_directories(strata_engine PRIVATE ${STRATA_ROOT}/src/core) # conversation_checked.hpp (#include "...")
target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu)
# cuBLAS -> oneMKL through dpct::blas (needs the MKL SYCL BLAS domain)
@@ -180,6 +184,23 @@ if(STRATA_SYCL_PARITY)
target_link_libraries(${p}_parity PRIVATE strata_kernels)
add_test(NAME ${p}_parity COMMAND ${p}_parity --selftest)
endforeach()
+ # 0.1.31: the IQ kernels that decode a weight part once for every column/entry, bitwise vs the per-column ones
+ # (no --selftest flag: it runs its checks by default), and the rewritten per-hit/grouped expert kernels vs the
+ # previous ones, bitwise
+ strata_resolve(_src src/kernels/iq_multi_parity.cpp)
+ add_executable(iq_multi_parity ${_src})
+ target_link_libraries(iq_multi_parity PRIVATE strata_kernels)
+ add_test(NAME iq_multi_parity COMMAND iq_multi_parity)
+ strata_resolve(_src src/kernels/s2_expert_grouped_parity.cpp)
+ 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)
+ # the conversation snapshots (#216) against the engine, as upstream's STRATA_BUILD_CONVERSATION_TESTS
+ strata_resolve(_src src/core/conversation_snapshot_test.cpp)
+ add_executable(conversation_snapshot_test ${_src})
+ target_link_libraries(conversation_snapshot_test PRIVATE strata_engine)
+ add_test(NAME conversation_snapshot_test COMMAND conversation_snapshot_test)
+ set_tests_properties(conversation_snapshot_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120)
# the prompt-attention parity takes a context length, not --selftest, and needs the tensor-core kernel (not
# ported yet: it reports "refused the pools" here). Built, not registered.
strata_resolve(_src src/kernels/qsa_prompt_attn_parity.cpp)
diff --git a/sycl/include/strata/core/coupled_draft.hpp b/sycl/include/strata/core/coupled_draft.hpp
new file mode 100644
index 000000000..78e6c9390
--- /dev/null
+++ b/sycl/include/strata/core/coupled_draft.hpp
@@ -0,0 +1,85 @@
+// include/strata/core/coupled_draft.hpp - COUPLED DRAFT SAMPLING (STRATA_SPEC_COUPLED=1, off by default).
+//
+// Under sampling the verify window samples row t of a window at position pos0 as Philox(seed, pos0 + t) over the
+// sampler chain (penalties -> top_k -> top_p -> min_p -> temperature -> inverse-CDF pick; verify.cpp run(),
+// sampler.cu), and a draft is kept only when it EQUALS that row's pick. The output is therefore a function of the
+// seed alone, whatever the drafts are: drafts only decide how many tokens a window yields.
+//
+// The MTP draft layer used to propose its ARGMAX. In coupled mode it SAMPLES instead, with the target's own chain
+// (the request's top_k / top_p / min_p / temperature and penalties over the same history) and the SAME uniform the
+// target will draw for the row that verifies the draft. When the draft's distribution is close to the target's,
+// the two inverse-CDF picks from one uniform agree far more often than an argmax agrees with a sample; the target's
+// pick - and so the text - does not change, because verification is still exact-match against the target's sample.
+//
+// THE COUNTER ARITHMETIC (all positions are sequence indices; a window's row t holds the token at pos0 + t and its
+// pick is the token at pos0 + t + 1, drawn with counter pos0 + t):
+// * MTP cell c pairs the main model's residual at position c with the token at c + 1 and predicts the token at
+// c + 2 (mtp.hpp).
+// * After a window at p with a drafts accepted, the next window starts at p' = p + a + 1 (its row 0 is the token
+// the window picked at row a). Chain step j (j = 0 ..) runs at cell p + a + j and predicts the token at
+// p + a + j + 2 = p' + j + 1: row j + 1 of the next window, VERIFIED BY ROW j's pick, counter p' + j.
+// * So a draft made at cell c is verified with counter c + 1 - whatever the window size T, the accepted count, a
+// suffix-drafter window in between (its drafts are then simply not used), or `draft_first` (cell p - 1, a = 0 for
+// a window at p). The kernel reads c from the step record the host already stages for the cell (device memory,
+// so the captured graphs replay with each round's own counter), and the seed and chain from a device copy of the
+// request's SamplerParams, refreshed at the start of every round graph.
+//
+// THE PENALTY HISTORY. The verify row j of the next window counts penalties over penalty_rows(consumed', window')
+// row j: the last h of (consumed', x', drafts 0 .. j-1), where consumed' is what the session holds after the commit
+// and x' the window's pick at row a. The drafter keeps a device RING of kCoupledHistCap + max_t slots: the host
+// stages the base (the last h of consumed' + x', -1 padded in front) in [cap - h, cap) before the round, and draft j
+// writes its token to cap + j - so draft j's window is [cap + j - h, cap + j), exactly the row the target will use.
+#pragma once
+
+#define DPCT_PROFILING_ENABLED
+#include <sycl/sycl.hpp>
+#include <dpct/dpct.hpp>
+#include "strata/kernels/sampler.hpp"
+
+#include <algorithm>
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+
+#if defined(SYCL_LANGUAGE_VERSION) || defined(__HIPCC__)
+#define STRATA_COUPLED_HD
+#else
+#define STRATA_COUPLED_HD
+#endif
+
+namespace strata::core {
+
+/// The longest penalty window the coupled drafter mirrors (serve's kPenaltyWindowCap).
+inline constexpr int kCoupledHistCap = 4096;
+
+/// STRATA_SPEC_COUPLED=1 (any value but empty or "0"): read once.
+inline bool coupled_draft_env() {
+ static const bool on = [] {
+ const char* e = std::getenv("STRATA_SPEC_COUPLED");
+ return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0;
+ }();
+ return on;
+}
+
+/// The MTP cell of chain step j after a window at `p` with `a` drafts accepted (draft() runs step j there).
+STRATA_COUPLED_HD inline int64_t coupled_draft_cell(int64_t p, int a, int j) { return p + a + j; }
+
+/// The Philox counter the verify window will draw for the row that checks the draft made at MTP cell `cell`.
+STRATA_COUPLED_HD inline uint64_t coupled_draft_counter(int64_t cell) { return (uint64_t) (cell + 1); }
+
+/// The penalty window the draft layer and the target use: min(penalty_last_n, cap), 0 when penalties are off.
+STRATA_COUPLED_HD inline int coupled_hist_len(int penalty_last_n, int cap) {
+ return penalty_last_n <= 0 ? 0 : (penalty_last_n < cap ? penalty_last_n : cap);
+}
+
+/// Where draft j's penalty window starts in the ring (base in [cap - h, cap), draft i at cap + i).
+STRATA_COUPLED_HD inline int coupled_hist_start(int cap, int j, int h) { return cap + j - h; }
+
+/// The ring's base on the host: the last `h` tokens of (tail[0..n_tail), next), -1 padded in front, into
+/// out[0..h) - row 0 of `penalty_rows` for the one-token window [next].
+inline void coupled_hist_base(const int32_t* tail, int64_t n_tail, int32_t next, int h, int32_t* out) {
+ if (h <= 0) return;
+ strata::kernels::penalty_rows(tail, n_tail, &next, 1, h, out);
+}
+
+} // namespace strata::core
diff --git a/sycl/include/strata/core/mtp.hpp b/sycl/include/strata/core/mtp.hpp
index cfd2896c1..c5726b461 100644
--- a/sycl/include/strata/core/mtp.hpp
+++ b/sycl/include/strata/core/mtp.hpp
@@ -23,6 +23,7 @@
#include <dpct/dpct.hpp>
#include "strata/core/layer.hpp"
#include "strata/core/session.hpp"
+#include "strata/kernels/sampler.hpp"
#include <cstdint>
#include <algorithm>
@@ -51,9 +52,9 @@ public:
/// SYCL port: capture the round, step and prompt graphs at load rather than on first use (see Verifier::warm)
bool warm(std::string& err) {
for (int T = 1; T <= max_t_; ++T)
- if (!capture_round(T, err) || !capture_prefill(T, err)) return false;
+ if (!capture_round(T, false, err) || !capture_prefill(T, err)) return false;
for (int j = 1; j < std::min(max_t_ - 1, max_drafts_); ++j)
- if (!capture_step(j, err)) return false;
+ if (!capture_step(j, false, err)) return false;
return true;
}
uint64_t vram_bytes() const { return vram_; }
@@ -82,6 +83,16 @@ public:
bool draft_first(int T, const float* R_row, int32_t token, int64_t cell, int32_t* drafts, std::string& err,
float* probs = nullptr, float min_p = 0.0f, int* n_drafts = nullptr);
+ /// COUPLED DRAFT SAMPLING (core/coupled_draft.hpp; STRATA_SPEC_COUPLED=1, set up by bind()): the request's
+ /// sampling. A sampled request (temperature > 0, not greedy) then drafts by SAMPLING with the target's chain and
+ /// the target's Philox draw for the verifying row, and `probs` is the draft's probability under that chain; a
+ /// greedy one keeps the argmax drafts and their graphs. A no-op when the switch is off.
+ void set_draft_sampling(const strata::kernels::SamplerParams& sp);
+ /// Coupled mode with penalties: the history the next draft() chain starts from - what the session holds after the
+ /// window's commit (`tail`) and the window's pick at its last accepted row (`next`, the next window's row 0).
+ void set_draft_history(const int32_t* tail, int64_t n_tail, int32_t next);
+ bool coupled() const { return coupled_active_; }
+
double ms_draft = 0, ms_prefill = 0;
int64_t rounds = 0;
@@ -110,9 +121,20 @@ private:
std::string &err);
bool capture_prefill(int T, std::string& err);
bool capture_prefill_dev(int T, std::string& err); ///< E-4: without the mapped staging (inputs copied on device)
- bool capture_round(int T, std::string& err);
- bool capture_step(int j, std::string& err);
+ bool capture_round(int T, bool coupled, std::string& err);
+ bool capture_step(int j, bool coupled, std::string& err);
dpct::experimental::command_graph_exec_ptr step_exec_[9] = {};
+ // coupled draft sampling: its own round/step graphs (the argmax ones stay as they were), the request's
+ // parameters and the penalty ring (mapped staging + device copies), the split scratch, token id -> subset index
+ bool setup_coupled(std::string& err);
+ dpct::experimental::command_graph_exec_ptr round_exec_c_[9] = {};
+ dpct::experimental::command_graph_exec_ptr step_exec_c_[9] = {};
+ bool coupled_ok_ = false, coupled_active_ = false;
+ bool coupled_rec_ = false; ///< record_forward: the full layer ends in the coupled sampler (draft coupled_j_)
+ int coupled_j_ = 0;
+ strata::kernels::SamplerParams *h_cparams_ = nullptr, *m_cparams_ = nullptr, *cparams_ = nullptr;
+ int32_t *h_chist_ = nullptr, *m_chist_ = nullptr, *cring_ = nullptr, *dinv_ = nullptr;
+ void* cscratch_ = nullptr;
const float* f32(const char* name) const;
const uint16_t* bf16(const char* name) const;
const void* q8(const char* name) const;
diff --git a/sycl/include/strata/core/session.hpp b/sycl/include/strata/core/session.hpp
index 633a62d5c..526dc3dff 100644
--- a/sycl/include/strata/core/session.hpp
+++ b/sycl/include/strata/core/session.hpp
@@ -45,6 +45,20 @@ struct SessionState {
float* R = nullptr; ///< alias of `block.R`, named for what it means at this level
int64_t k = 10; ///< experts per token
+
+ // **THE LAYER-RANGE CARVE (multi-GPU).** A split stage's session used to carve state for ALL 48 layers
+ // (every QSA KV pool at max_cells, every GDN recurrence) while running only its slice - the same
+ // whole-model-sized-buffer disease the QSA chunked-prefill PR cured upstream. A session now owns
+ // [layer_lo, layer_hi): `qsa_states`/`gdn_state` keep GLOBAL ordinal indexing, the arrays simply hold
+ // fewer rows, so per-layer consumers subtract `gdn_ord0`, and every old model-level `qsa_states[0]` use
+ // (the shared RoPE table, the prefill staging identity, the MTP rope borrow) reads `qsa_states[primary]`.
+ // A range with no QSA layer still carves ONE primary state so those model-level uses stay valid.
+ int64_t layer_lo = 0, layer_hi = 0; ///< resolved by `session_init` (hi = n_layers for the full range)
+ int64_t qsa_ord0 = 0; ///< global QSA ordinal of the first allocated state
+ int64_t qsa_alloc = 0; ///< allocated QSA states (>= 1 whenever the model has any)
+ int64_t gdn_ord0 = 0; ///< global GDN ordinal of `gdn_state` row 0
+ int64_t gdn_alloc = 0; ///< allocated GDN rows
+ int qsa_primary() const { return (int) qsa_ord0; }
/// The doorbell the host loop polls. Null until a caller provides one - the engine runs without it, and
/// neither `session_token` nor `session_replay` looks at it.
const Doorbell* db = nullptr;
@@ -76,9 +90,15 @@ struct SessionState {
/// Bytes for a whole session at `max_cells` of context. Every layer's state is sized at once, because P2.T10
/// requires ZERO token-path allocations - a `cudaMalloc` that happened on the first token of a longer sequence
/// would satisfy every test here and fail that one.
-uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k);
-/// Carves `base` (DEVICE memory) into `s`. Returns the bytes used.
-uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void* base, SessionState& s);
+///
+/// [layer_lo, layer_hi) carves only that range's per-layer state (a split stage runs a slice of the model);
+/// the default full range is byte-identical to the old whole-model carve. Pure arithmetic - safe to call for
+/// a candidate range before anything is allocated, which is how the layer-split search prices a placement.
+uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k, int64_t layer_lo = 0,
+ int64_t layer_hi = -1);
+/// Carves `base` (DEVICE memory) into `s`. Returns the bytes used. Same range convention as `session_bytes`.
+uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void* base, SessionState& s,
+ int64_t layer_lo = 0, int64_t layer_hi = -1);
/// Zeroes every layer's state - the residual to `R_init`, everything else to zero, so a fresh sequence starts
/// from the reference's own `zeros()`.
void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init, void* stream);
@@ -213,7 +233,8 @@ struct SessionGraphs {
/// replay re-reads every token - so the position is data, not an argument. That is the whole reason rounds
/// 211-214 moved the per-token counts into device buffers.
bool session_capture(const WeightTable& tables, const ModelGeometry& g, SessionState& s, const float* parts,
- SessionGraphs& gr, std::string& err, bool split = false);
+ SessionGraphs& gr, std::string& err, bool split = false, int64_t layer_lo = 0,
+ int64_t layer_hi = -1);
/// One token by REPLAYING the captured graphs. Identical arithmetic to `session_token`; the only difference is
/// that ~2,000 kernel launches become 48 graph launches.
diff --git a/sycl/include/strata/core/verify.hpp b/sycl/include/strata/core/verify.hpp
index ff53fe586..7d8bfb0d5 100644
--- a/sycl/include/strata/core/verify.hpp
+++ b/sycl/include/strata/core/verify.hpp
@@ -30,6 +30,7 @@
#include "strata/core/session.hpp"
#include "strata/kernels/sampler.hpp"
+#include <atomic>
#include <cstdint>
#include <chrono>
#include <string>
@@ -61,6 +62,12 @@ public:
/// The watchdog's view of the window in flight (issue #31): the layer, the GPU's sequence, the flags.
void diag(std::FILE* f) const;
+ /// #267: raise every flag the window's spin kernels wait on past any ring (UINT32_MAX), so a window the GPU
+ /// cannot finish drains instead of staying resident, then wait up to `timeout_ms` for its streams. For the
+ /// paths that give up on the engine (a timed-out window, the serve watchdog): the window then ran on whatever
+ /// the flags guarded, so this verifier refuses every later window. True when the streams finished.
+ bool release_gpu_waits(int timeout_ms);
+
/// `max_t` <= kVerifyMaxT. `head` may be null (the canonical head is then run per token).
bool init(const WeightTable& wt, const ModelGeometry& g, SessionState& ss, const VerifyHits& hits,
const NativeHead* head, int max_t, std::string& err);
@@ -117,6 +124,15 @@ public:
/// request does not pay for them (a 2,400-node graph takes tens of ms to finalize on this backend).
bool warm(std::string& err);
+ /// Measurement hook (STRATA_LOGPOS): after run(), write one line per row t of the last window's head -
+ /// "pos target logprob top top_logprob hit extra_logprob target_logprob_without_extra" - where row t is the
+ /// distribution at pos0 + t, targets[t] is the token at pos0 + t + 1, extra_logprob is the log-probability of
+ /// `extra_id` in the same row, and the last column is the target's log-probability in that row renormalized
+ /// over every token but `extra_id` (both nan when they do not apply). A layer split's earlier stage forwards
+ /// to the stage that holds the head.
+ bool window_logprobs(const int32_t* targets, int T, int64_t pos0, int32_t extra_id, std::FILE* out,
+ std::string& err);
+
/// Token t's residual after the last layer, (hc, n_embd) on the device, valid until the next `run`.
const float* final_R(int t) const;
const float* final_R_all() const { return next_ ? next_->final_R_all() : R_; }
@@ -152,6 +168,7 @@ private:
int hist_len_ = 0;
bool head_sampling_ = true; ///< set_head_sampling
int device_ = -1; ///< the device `init` ran on: run/commit switch to it (layer split)
+ std::atomic<bool> released_{false}; ///< #267: release_gpu_waits ran (maybe on the watchdog thread): no more windows
bool device_plan_ = false; ///< E-6: resident-only layers planned on the device (STRATA_VERIFY_DEVICE_PLAN)
uint32_t* skip_ = nullptr; ///< E-6: per group, the ring whose plan the device built (0: the host's)
unsigned long long* slot_off_d_ = nullptr; ///< E-6: the slot offsets on the device
diff --git a/sycl/include/strata/kernels/dp4a.hpp b/sycl/include/strata/kernels/dp4a.hpp
new file mode 100644
index 000000000..89f7ba86a
--- /dev/null
+++ b/sycl/include/strata/kernels/dp4a.hpp
@@ -0,0 +1,51 @@
+// include/strata/kernels/dp4a.hpp - the two instructions the kernels use that Pascal (sm_60) does not have.
+//
+// The engine is written for compute capability 7.5 and newer and refuses older cards at CMake configure time
+// (a Pascal build passes -DSTRATA_EXPERIMENTAL_SM60=ON). A GP100-class card is compute capability 6.0, which is
+// missing exactly two things the i-quant kernels rely on:
+//
+// * `__dp4a`, a byte-wise dot product, available from 6.1 (Pascal GP10x/GV11x). Its fallback below is
+// llama.cpp's own (`ggml/src/ggml-cuda/common.cuh`), which is the reference for the kernels in this
+// directory: they are transcribed from llama.cpp's vecdotq.cuh, and that wrapper's operands are the same
+// sites. It reinterprets the operands as SIGNED bytes and accumulates in int32, which is what `__dp4a`
+// does for these calls, so the fallback is bit-exact rather than merely close.
+// * `__nanosleep`, available from 7.0 (Volta). It only paces single-thread doorbell waits, so a loop that
+// spins without it is correct, merely busier.
+//
+// Both are compile-time selections on `__CUDA_ARCH__`, so one source tree builds for Pascal and for RTX
+// 20/30/40/50 without a #define at the call sites. A HIP build never takes either fallback: `__CUDA_ARCH__` is
+// undefined there, so `STRATA_DP4A` is `__dp4a` (which `hip_compat/intrinsics.hpp` provides) and the pause is
+// HIP's own `__nanosleep`.
+#pragma once
+
+#define DPCT_PROFILING_ENABLED
+#include <sycl/sycl.hpp>
+#include <dpct/dpct.hpp>
+#include <cstdint>
+#include <time.h>
+
+#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP < 610
+__device__ __forceinline__ int strata_dp4a(const int a, const int b, const int c) {
+ const int8_t* a8 = (const int8_t*) &a;
+ const int8_t* b8 = (const int8_t*) &b;
+ return c + a8[0] * b8[0] + a8[1] * b8[1] + a8[2] * b8[2] + a8[3] * b8[3];
+}
+#define STRATA_DP4A(a, b, c) strata_dp4a((a), (b), (c))
+#else
+#define STRATA_DP4A(a, b, c) dpct::dp4a((a), (b), (c))
+#endif
+
+/// Yield the thread while a doorbell flag is being polled. The length of the pause is a backoff hint, not a
+/// contract, and only pre-Volta CUDA has no `__nanosleep` at all.
+__dpct_inline__ void strata_spin_pause() {
+#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP < 700
+ // sm_6x: the loop spins. Every call site is a single-thread doorbell wait, so nothing else is delayed.
+#else
+ /*
+ DPCT1008: __nanosleep function is not defined in SYCL. This is a
+ hardware-specific feature. Consult with your hardware vendor to find a
+ replacement.
+ */
+ // SYCL port: no __nanosleep; the doorbell waits are bounded by strata::kSpinMax instead
+#endif
+}
diff --git a/sycl/include/strata/kernels/rope.hpp b/sycl/include/strata/kernels/rope.hpp
index be6a53bdc..34adf3059 100644
--- a/sycl/include/strata/kernels/rope.hpp
+++ b/sycl/include/strata/kernels/rope.hpp
@@ -6,6 +6,12 @@
// The cos/sin table is built on the HOST in float64 (see src/kernels/cuda/rope.cu for why) and the kernel is
// a pure rotation over it. The table depends on (n_rot, theta, position) and not on the token, so it is worth
// caching; `build_rope_table` fills `max_pos` positions of `n_rot/2` pairs each.
+//
+// ROPE SCALING RIDES IN THE TABLE, NOT IN THE KERNEL. The kernels below read cos/sin values and
+// cannot tell a scaled table from an unscaled one - with scaling on, the scaled angles (and YaRN's
+// mscale magnitude correction, folded into the same values) simply ARE the table. That is why
+// neither `rope_neox_apply` nor the indexer's pooling kernel takes any scaling argument: the config
+// enters once, here, at build time (`rope_scaling.hpp`).
#pragma once
#define DPCT_PROFILING_ENABLED
@@ -13,6 +19,8 @@
#include <dpct/dpct.hpp>
#include <cstdint>
+#include "strata/kernels/rope_scaling.hpp"
+
#if defined(SYCL_LANGUAGE_VERSION) || defined(__HIPCC__)
#define STRATA_ROPE_HD
#else
@@ -41,6 +49,12 @@ STRATA_ROPE_HD inline void rope_neox_pair(float a, float b, float c, float s, fl
void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab);
+/// The same table under the process's rope scaling (rope_scaling.hpp). For `RopeScalingType::None`
+/// this IS the five-argument builder above - the parity test holds the two to be bit-identical - and
+/// for linear/YaRN the scaled angles (YaRN's mscale included) replace them. The math is ggml's,
+/// transcribed; see the header of `rope_scaling.hpp` for what arrives from where.
+void build_rope_table(int n_rot, const RopeScaling& scaling, int max_pos, float* cos_tab, float* sin_tab);
+
// `x` and `out` are (rows, head_dim) and `pos` is (rows,) - one position per row, so a batch of heads at
// different sequence positions is one call. `cos_tab`/`sin_tab` are (max_pos, n_rot/2). `out` may equal `x`.
//
diff --git a/sycl/include/strata/kernels/rope_scaling.hpp b/sycl/include/strata/kernels/rope_scaling.hpp
new file mode 100644
index 000000000..5512e59b3
--- /dev/null
+++ b/sycl/include/strata/kernels/rope_scaling.hpp
@@ -0,0 +1,196 @@
+// include/strata/kernels/rope_scaling.hpp - rope scaling: extending the context past the trained one.
+//
+// WHAT IT IS. The artifact's RoPE is trained over `orig_ctx` positions (the artifact ships no
+// `rope.scaling` keys, so this is a pure runtime feature). Scaling re-uses positions past that by
+// rescaling the rotation angles. Three types, the llama.cpp set:
+//
+// none freq_scale 1, no correction - today's behaviour, exactly
+// linear Position Interpolation: angles shrunk by 1/factor - every position fits again, all
+// frequencies compressed uniformly
+// yarn YaRN: high-frequency pairs keep their trained angles (extrapolate), low-frequency
+// pairs are interpolated, and the pairs in between blend - plus a magnitude correction
+// `mscale` that keeps the attention temperature where training put it
+//
+// THE MATH IS GGML'S, TRANSCRIBED, NOT RE-DERIVED. `third_party/llama.cpp` is vendored and is the
+// numerical contract (the same standing `native_rope.cu` declares): ramp, correction dims, the
+// interpolation mix and the mscale formula below are line-for-line that source, with the MIT
+// attribution at each helper. The one deliberate deviation is bookkeeping: ggml's device kernel
+// speaks in even dim indices (`i0`) and halves them inside the ramp, while every Strata rope kernel
+// speaks in PAIR indices - so `rope_yarn_ramp` here takes the pair index and compares it against
+// `corr_dims` directly. Same numbers, one less division per call site.
+//
+// HOW IT REACHES THE ROPE. Two forms, one config:
+//
+// - the TABLE path (the default decode path, the indexer's pooled key) never changes its kernels:
+// scaling is baked into the cos/sin contents by `build_rope_table`, which the parity test checks
+// bit-exactly against a float64 reference;
+// - the ANALYTIC paths (`--native-rope`, the native indexer, prefill) get the resolved constants
+// as kernel arguments.
+//
+// **PROCESS CONSTANTS, SET ONCE BEFORE CAPTURE.** A CUDA graph bakes kernel ARGUMENTS at capture
+// time, so the scaling must be fixed before `session_init` captures the layers - which is exactly
+// the constraint the per-token values already respect by living in device memory (`st.pos_dev`).
+// `rope_scaling_set()` is called once from the engine's startup, after CLI and GGUF defaults meet,
+// before any graph exists. There is deliberately no way to change it mid-process: the K already in
+// the cache is stored POST-RoPE, so a mid-run change would mix two scalings in one cache.
+#pragma once
+
+#define DPCT_PROFILING_ENABLED
+#include <sycl/sycl.hpp>
+#include <dpct/dpct.hpp>
+#include <cmath>
+
+#if defined(SYCL_LANGUAGE_VERSION) || defined(__HIPCC__)
+#define STRATA_ROPE_SCALING_HD
+#else
+#define STRATA_ROPE_SCALING_HD
+#endif
+
+namespace strata::kernels {
+
+enum class RopeScalingType { None, Linear, YaRN };
+
+/// The float32 constants the ANALYTIC rotation kernels take (`rope_scaled_angle`'s arguments). The defaults are
+/// the identity: freq_scale 1, no correction, magnitude 1 - with them the helper computes `cosf(theta) * 1.0f`
+/// on `1.0f * theta`, which is exactly today's unscaled `cosf(theta)` bit for bit.
+struct RopeKernelArgs {
+ float freq_scale = 1.0f;
+ float corr_low = 0.0f;
+ float corr_high = 0.0f;
+ float ext_factor = 0.0f;
+ float attn_factor = 1.0f;
+};
+
+/// The one rope configuration, as the CLI flag family and the (future) GGUF rope keys resolve to.
+///
+/// Default-constructed this is EXACTLY today's engine: freq_scale 1, mscale 1, no correction. That
+/// identity is a regression gate, not a coincidence - the parity test compares the default's table
+/// against the pre-scaling builder bit for bit.
+struct RopeScaling {
+ RopeScalingType type = RopeScalingType::None;
+ double freq_base = 1e7; ///< `rope.freq_base` (the value pinned by `qsa_freq_base()`)
+ double factor = 1.0; ///< `--rope-scale`: how far past the trained context the run goes
+ double freq_scale_in = 0; ///< `--rope-freq-scale`: the raw ggml knob; 0 = 1/factor
+ double orig_ctx = 262144; ///< `--yarn-orig-ctx`: the context the model was trained over
+ double ext_factor = 0; ///< `--yarn-ext-factor`: correction depth; 0 = off, 1 = full YaRN
+ double attn_factor = 1.0; ///< `--yarn-attn-factor`: extra magnitude scale (ggml's attn_factor)
+ double beta_fast = 32.0; ///< `--yarn-beta-fast`
+ double beta_slow = 1.0; ///< `--yarn-beta-slow`
+
+ /// The angle shrink. ggml's `freq_scale`: 1 means "the trained angles", 1/factor squeezes
+ /// `factor` positions into the trained range.
+ double freq_scale() const {
+ if (type == RopeScalingType::None) return 1.0;
+ return freq_scale_in > 0 ? freq_scale_in : 1.0 / factor;
+ }
+
+ /// The magnitude correction. ggml's `rope_yarn` multiplies cos and sin by this; the log term
+ /// rides on `ext_factor != 0` (not on the type), exactly as that source has it. With the
+ /// default knobs YaRN factor F gives `1 + 0.1*ln(F)` - YaRN's temperature correction.
+ double mscale() const {
+ if (ext_factor == 0) return attn_factor;
+ return attn_factor * (1.0 + 0.1 * std::log(1.0 / freq_scale()));
+ }
+
+ /// The correction window, in PAIR indices: below `out[0]` pairs extrapolate (keep the trained
+ /// angles), above `out[1]` they interpolate, in between they blend. Transcribed from ggml's
+ /// `ggml_rope_yarn_corr_dims` (see the derivation comment at `rope_yarn_corr_dim` below).
+ void corr_dims(int n_rot, double out[2]) const {
+ const double start = std::floor(rope_yarn_corr_dim(n_rot, orig_ctx, beta_fast, freq_base));
+ const double end = std::ceil(rope_yarn_corr_dim(n_rot, orig_ctx, beta_slow, freq_base));
+ out[0] = start < 0 ? 0 : start;
+ out[1] = end > (double) (n_rot - 1) ? (double) (n_rot - 1) : end;
+ }
+
+ /// The analytic kernels' constants. `none` returns the identity constants WHATEVER the other knobs hold -
+ /// the table builder ignores them for `none` too, so the two rotation forms cannot disagree there, and an
+ /// unscaled run computes exactly what it computed before scaling existed. Linear/YaRN: ggml's `rope_yarn`
+ /// arguments (`attn_factor` is the raw knob; the helper applies the log term when correcting).
+ RopeKernelArgs kernel_args(int n_rot) const {
+ RopeKernelArgs a;
+ if (type == RopeScalingType::None) return a;
+ double cd[2];
+ corr_dims(n_rot, cd);
+ a.freq_scale = (float) freq_scale();
+ a.corr_low = (float) cd[0];
+ a.corr_high = (float) cd[1];
+ a.ext_factor = (float) ext_factor;
+ a.attn_factor = (float) attn_factor;
+ return a;
+ }
+
+private:
+ /// ggml/src/ggml.c: "Apparently solving `n_rot = 2pi * x * base^((2 * max_pos_emb) / n_dims)`
+ /// for x, we get `corr_dim(n_rot) = n_dims * log(max_pos_emb / (n_rot * 2pi)) / (2 * log(base))`".
+ /// float64 rather than ggml's float32: the table path computes in float64 and is held to a
+ /// bit-exact float64 reference, so its inputs are float64 too.
+ static double rope_yarn_corr_dim(int n_dims, double n_ctx_orig, double n_rot, double base) {
+ return (double) n_dims * std::log(n_ctx_orig / (n_rot * 2.0 * 3.14159265358979323846)) /
+ (2.0 * std::log(base));
+ }
+};
+
+/// The ramp between extrapolation (1) and interpolation (0).
+///
+/// ggml/src/ggml-cuda/rope.cu `rope_yarn_ramp`: `1 - clamp(y, 0, 1)` with
+/// `y = (i0 / 2 - low) / max(0.001, high - low)`. ggml passes the even dim index `i0`; this takes
+/// the pair index (ggml's `i0/2`) so Strata's pair-indexed kernels don't re-derive the mapping. The
+/// 0.001 floor on the denominator is ggml's, kept verbatim: `corr_dims` can produce low == high.
+STRATA_ROPE_SCALING_HD inline float rope_yarn_ramp(float low, float high, int pair) {
+ const float y = ((float) pair - low) / (high - low > 0.001f ? high - low : 0.001f);
+ const float clamped = y < 0.0f ? 0.0f : (y > 1.0f ? 1.0f : y);
+ return 1.0f - clamped;
+}
+
+/// The scaled angle for one pair, float32, the ANALYTIC paths' contract (pinned ggml arithmetic).
+///
+/// Takes `theta_extrap` - the position times that pair's trained `inv_freq` - and returns the angle
+/// to take cos/sin of, with ggml's mscale already folded in. `mscale_in` must be `attn_factor`
+/// (ggml's kernels receive the raw knob and apply the log term here, where it is per-pair constant;
+/// this helper keeps that shape so the native path reads against ggml line by line).
+STRATA_ROPE_SCALING_HD inline void rope_scaled_angle(float theta_extrap, float freq_scale, float corr_low,
+ float corr_high, float ext_factor, float mscale_in,
+ int pair, float& cos_out, float& sin_out) {
+ // The interpolation, always applied; the correction mixed in on top (ggml-cuda/rope.cu rope_yarn).
+ float theta = freq_scale * theta_extrap;
+ float mscale = mscale_in;
+ if (ext_factor != 0.0f) {
+ const float ramp_mix = rope_yarn_ramp(corr_low, corr_high, pair) * ext_factor;
+ theta = theta * (1.0f - ramp_mix) + theta_extrap * ramp_mix;
+ // "Get n-d magnitude scaling corrected for interpolation" - the log term only when correcting.
+ mscale *= 1.0f + 0.1f * sycl::log(1.0f / freq_scale);
+ }
+ cos_out = sycl::cos(theta) * mscale;
+ sin_out = sycl::sin(theta) * mscale;
+}
+
+/// The ONE validity rule for a resolved configuration, shared by the engine's startup check and every rotation
+/// site that takes the struct, so a bad knob cannot pass one site and trip (or silently NaN) another. Returns
+/// nullptr when the configuration is usable, else what is wrong. Every value is tested with `std::isfinite`
+/// FIRST: a NaN passes every `<`/`<=` range comparison, which is how a `--rope-scale nan` would otherwise slip
+/// through. `none` passes with any knob values - the knobs are inert there (the resolution resets them).
+inline const char* rope_scaling_invalid(const RopeScaling& s) {
+ if (!std::isfinite(s.freq_base) || s.freq_base <= 1.0) return "the frequency base must be a finite value above 1";
+ if (s.type == RopeScalingType::None) return nullptr;
+ if (!std::isfinite(s.factor) || s.factor < 1.0) return "the scaling factor must be a finite value >= 1";
+ if (!std::isfinite(s.freq_scale_in) || s.freq_scale_in < 0.0)
+ return "the frequency scale must be finite and positive (0 = 1/factor)";
+ const double fs = s.freq_scale();
+ if (!std::isfinite(fs) || fs <= 0.0) return "the resolved frequency scale must be a finite positive value";
+ if (!std::isfinite(s.orig_ctx) || s.orig_ctx < 1.0) return "the original (trained) context must be finite and > 0";
+ if (!std::isfinite(s.ext_factor) || s.ext_factor < 0.0) return "the YaRN ext factor must be finite and >= 0";
+ if (!std::isfinite(s.attn_factor) || s.attn_factor <= 0.0) return "the attention factor must be finite and > 0";
+ if (!std::isfinite(s.beta_fast) || s.beta_fast <= 0.0 || !std::isfinite(s.beta_slow) || s.beta_slow <= 0.0)
+ return "the YaRN betas must be finite and > 0";
+ if (!std::isfinite(s.mscale()) || s.mscale() <= 0.0) return "the resolved magnitude correction must be finite and > 0";
+ return nullptr;
+}
+
+/// The process's one rope configuration. Set it ONCE at startup, after the CLI and the model file
+/// have agreed on the values and BEFORE `session_init` (which builds the rope table and captures the
+/// graphs); read it at table build time and when launching the analytic kernels. Plain storage, no
+/// atomics: one writer on the startup thread, every reader after it.
+void rope_scaling_set(const RopeScaling& scaling);
+const RopeScaling& rope_scaling();
+
+} // namespace strata::kernels
diff --git a/sycl/include/strata/kernels/sampler.hpp b/sycl/include/strata/kernels/sampler.hpp
index b247f15e9..6bbc16d5a 100644
--- a/sycl/include/strata/kernels/sampler.hpp
+++ b/sycl/include/strata/kernels/sampler.hpp
@@ -43,6 +43,24 @@ struct SamplerParams {
void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
const SamplerParams& p, int* out, void* stream);
+// ---- COUPLED DRAFT SAMPLING (include/strata/core/coupled_draft.hpp, STRATA_SPEC_COUPLED=1). Device pointers
+// throughout; every per-request / per-round value comes from device memory, so the calls can be captured.
+//
+// The scratch `coupled_draft_sample` needs for `nv` logits (0: too wide for the split merge, coupled cannot run).
+size_t coupled_draft_scratch_bytes(int nv);
+// A round's inputs: `*params` <- `*mapped_params`, ring[cap - h, cap) <- mapped_hist[cap - h, cap) with h =
+// coupled_hist_len(penalty_last_n, cap). `mapped_*` are mapped host memory.
+void coupled_draft_stage(const SamplerParams* mapped_params, const int32_t* mapped_hist, SamplerParams* params,
+ int32_t* ring, int cap, void* stream);
+// Draft j of the chain from ONE row of `nv` logits (modified in place: the penalties): the target's chain with
+// `*params`, the penalty window ring[cap + j - h, cap + j), Philox counter coupled_draft_counter(step_rec[0]).
+// `sub_to_id` / `id_to_sub` map the draft head's subset to token ids and back (null: the whole vocabulary,
+// `id_vocab` ids). Writes the token id to *out_id, its probability under the final distribution to *out_prob, and
+// the id to ring[cap + j].
+void coupled_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const int32_t* id_to_sub, int id_vocab,
+ const SamplerParams* params, int32_t* ring, int cap, int j, const int32_t* step_rec,
+ void* scratch, int32_t* out_id, float* out_prob, void* stream);
+
// The penalty-history rows of a verify window, on the host: row t of `out` (T rows of `h` slots) is the last `h`
// tokens of `tail[0..n_tail)` followed by `window[0..t]`, most recent LAST, -1 in the unused front slots.
// `tail` is what the state consumed before the window, `window[0]` the fed-back token and `window[1..]` the
diff --git a/sycl/src/core/conversation_snapshot.cpp b/sycl/src/core/conversation_snapshot.cpp
new file mode 100644
index 000000000..74ea5dcfc
--- /dev/null
+++ b/sycl/src/core/conversation_snapshot.cpp
@@ -0,0 +1,289 @@
+#define DPCT_PROFILING_ENABLED
+#include <sycl/sycl.hpp>
+#include <dpct/dpct.hpp>
+#include "strata/core/conversation_snapshot.hpp"
+#include "strata/kernels/kv_q4.hpp"
+#include "conversation_checked.hpp"
+
+#include <array>
+#include <cstring>
+#include <limits>
+
+namespace strata::core {
+namespace {
+struct Layout {
+ int format;
+ int64_t cells, pooled_rows, page_size;
+ size_t data, scales, pooled, value_data, value_scales;
+};
+
+bool valid_extent(const QsaState& st, int64_t upto, std::string& error) {
+ const int64_t page = strata::kernels::qsa_real_shapes().page_size;
+ if (upto < 0 || upto > st.max_cells || upto > std::numeric_limits<int64_t>::max() - (page - 1)) {
+ error = "conversation snapshot: invalid K/V extent";
+ return false;
+ }
+ return true;
+}
+
+bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, Layout& l, std::string& error) {
+ if (!valid_extent(st, upto, error)) return false;
+ if (st.kv_hybrid && (st.kv_mode != 0 || st.kv_q4 || st.kv_int8)) {
+ error = "conversation snapshot: hybrid K8V4 requires an identity layout and distinct format flags";
+ return false;
+ }
+ const auto s = strata::kernels::qsa_real_shapes();
+ const bool int8_keys = st.kv_int8 || st.kv_hybrid;
+ if (g.n_head_kv <= 0 || g.head_dim <= 0 || g.head_dim > INT32_MAX || g.idx_key_dim <= 0 ||
+ (st.kv_q4 && g.head_dim % 32) || (int8_keys && !st.kv_q4 && g.head_dim % 64)) {
+ error = "conversation snapshot: invalid K/V geometry";
+ return false;
+ }
+ const int64_t cells = ((upto + s.page_size - 1) / s.page_size) * s.page_size;
+ const size_t per = st.kv_q4 ? (size_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim)
+ : (size_t) g.head_dim * (int8_keys ? 1 : 2);
+ // Include the moving spare row, not only completed blocks. The checkpoint
+ // restore reconstructs that row when rewinding to an earlier prefix.
+ const int64_t pooled = index && upto > 0 ? upto / s.idx_block + 1 : 0;
+ // Format 3 identifies snapshot K8V4 only; never pass it to the block movers.
+ l = {st.kv_hybrid ? 3 : qsa_kv_format(st), cells, pooled, s.page_size, 0, 0, 0, 0, 0};
+ using conversation_detail::product;
+ if (!product(l.data, {(uint64_t) cells, (uint64_t) g.n_head_kv, per}) ||
+ !product(l.scales, {(uint64_t) cells, (uint64_t) g.n_head_kv,
+ int8_keys && !st.kv_q4 ? (uint64_t) (g.head_dim / 64) * 2 : 0}) ||
+ !product(l.pooled, {(uint64_t) pooled, (uint64_t) g.idx_key_dim, sizeof(float)})) {
+ error = "conversation snapshot: K/V byte count overflow";
+ return false;
+ }
+ l.value_data = l.data;
+ l.value_scales = l.scales;
+ if (st.kv_hybrid) {
+ if (!product(l.value_data, {(uint64_t) cells, (uint64_t) g.n_head_kv,
+ (uint64_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim)})) {
+ error = "conversation snapshot: hybrid V byte count overflow";
+ return false;
+ }
+ l.value_scales = 0;
+ }
+ return true;
+}
+
+std::array<void*, 5> pools(const QsaState& st, bool resident = false) {
+ const bool host = st.kv_mode != 0 && !resident;
+ if (st.kv_hybrid) return {st.k_q, st.v_q4, st.k_scale, nullptr, st.idx_pooled};
+ if (st.kv_q4)
+ return {host ? st.host.k_q4 : st.k_q4, host ? st.host.v_q4 : st.v_q4, nullptr, nullptr, st.idx_pooled};
+ if (st.kv_int8)
+ return {host ? st.host.k_q : st.k_q, host ? st.host.v_q : st.v_q,
+ host ? st.host.k_scale : st.k_scale, host ? st.host.v_scale : st.v_scale, st.idx_pooled};
+ return {host ? st.host.k_pool : st.k_pool, host ? st.host.v_pool : st.v_pool, nullptr, nullptr, st.idx_pooled};
+}
+
+bool valid(const QsaState& st, const Layout& l, int64_t upto, std::string& error) {
+ if (upto < 0 || upto > st.max_cells || st.n_pages < 0 || l.cells / l.page_size > st.n_pages ||
+ st.kv_mode < 0 || st.kv_mode > 2 || st.n_slots <= 0 ||
+ (st.kv_mode == 0 && st.n_slots < st.n_pages) ||
+ l.pooled_rows > st.idx_pooled_rows || (st.kv_mode != 0 && !st.host.present())) {
+ error = "conversation snapshot: invalid K/V extent or missing authoritative host pool";
+ return false;
+ }
+ if (st.kv_mode == 1) {
+ const auto& m = st.map;
+ if (m.n_blocks != st.n_pages || m.n_slots != st.n_slots || !m.page_table || !m.slot_block ||
+ !m.slot_stamp || !m.slot_ref || !m.ctl || !m.miss_block || !m.miss_slot) {
+ error = "conversation snapshot: invalid streaming map";
+ return false;
+ }
+ }
+ if (st.kv_mode == 2 && (!st.page_table ||
+ (st.kv_q4 ? !st.k_q4 || !st.v_q4 : st.kv_int8 ? !st.k_q || !st.v_q || !st.k_scale || !st.v_scale
+ : !st.k_pool || !st.v_pool))) {
+ error = "conversation snapshot: invalid draft ring";
+ return false;
+ }
+ return true;
+}
+
+bool transfer(void *dst, const void *src, size_t n, std::string &error) try {
+ if (!n) return true;
+ if (!src || !dst) { error = "conversation snapshot: missing state buffer"; return false; }
+ // Default handles both device allocations and device-mapped host pool aliases.
+ const dpct::err0 e =
+ DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(dst, src, n).wait());
+ if (e == 0) return true;
+ /*
+ 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.
+ */
+ error = std::string("conversation snapshot copy: ") +
+ dpct::get_error_string_dummy(e);
+ return false;
+}
+catch (sycl::exception const &exc) {
+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__
+ << ", line:" << __LINE__ << std::endl;
+ std::exit(1);
+}
+} // namespace
+
+bool conversation_kv_capture_bytes(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,
+ int64_t upto, bool index, size_t& bytes, std::string& error) {
+ Layout l{};
+ if (!layout(st, g, upto, index, l, error) || !valid(st, l, upto, error)) return false;
+ const std::array<size_t,5> sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
+ const std::array<const ConversationBuffer*,5> buffers = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
+ bytes = 0;
+ for (size_t i = 0; i < buffers.size(); ++i) {
+ const size_t n = buffers[i]->allocation_peak(sizes[i]);
+ if (n == SIZE_MAX || !conversation_detail::add(bytes, n)) {
+ error = "conversation snapshot: segmented K/V allocation overflow";
+ return false;
+ }
+ }
+ return true;
+}
+
+size_t conversation_kv_bytes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index) {
+ size_t bytes = 0;
+ std::string error;
+ return conversation_kv_capture_bytes({}, st, g, upto, index, bytes, error) ? bytes : 0;
+}
+
+bool conversation_kv_save(ConversationKv& image, const QsaState& st, const ModelGeometry& g,
+ int64_t upto, bool index, std::string& error,
+ int64_t unchanged_tokens, size_t* reused_bytes) {
+ Layout l{};
+ if (!layout(st, g, upto, index, l, error)) return false;
+ if (!valid(st, l, upto, error)) return false;
+ if (unchanged_tokens < 0 || unchanged_tokens > upto || unchanged_tokens > image.cells) {
+ error = "conversation snapshot: invalid unchanged prefix";
+ return false;
+ }
+ const int64_t whole_cells = (unchanged_tokens / l.page_size) * l.page_size;
+ image.format = l.format;
+ image.cells = l.cells;
+ image.heads = g.n_head_kv;
+ image.head_dim = g.head_dim;
+ image.page_size = l.page_size;
+ image.pooled_rows = l.pooled_rows;
+ image.idx_dim = g.idx_key_dim;
+ const auto src = pools(st);
+ const std::array<size_t,5> sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
+ const std::array<ConversationBuffer*,5> dst = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
+ for (size_t i = 0; i < dst.size(); ++i) {
+ // Recopy the partial page and the indexer's moving spare row. Completed
+ // pages/rows strictly before the first rewritten token remain identical.
+ const size_t keep = i == 4 ? (index ? size_t(unchanged_tokens / strata::kernels::qsa_real_shapes().idx_block) * g.idx_key_dim * 4 : 0)
+ : l.cells ? (sizes[i] / size_t(l.cells)) * size_t(whole_cells) : 0;
+ if (keep > dst[i]->size()) { error = "conversation snapshot: missing reusable prefix"; return false; }
+ dst[i]->resize(sizes[i]);
+ if (!dst[i]->visit(keep, sizes[i] - keep, [&](uint8_t* p, size_t n, size_t at) {
+ return transfer(p, src[i] ? static_cast<const uint8_t*>(src[i]) + at : nullptr, n, error);
+ })) return false;
+ if (reused_bytes) *reused_bytes += keep;
+ }
+ return true;
+}
+
+bool conversation_kv_validate(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,
+ int64_t upto, bool index, std::string& error) {
+ Layout l{};
+ if (!layout(st, g, upto, index, l, error)) return false;
+ if (!valid(st, l, upto, error)) return false;
+ const std::array<size_t,5> sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
+ const std::array<const ConversationBuffer*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
+ if (image.format != l.format || image.cells != l.cells || image.heads != g.n_head_kv ||
+ image.head_dim != g.head_dim || image.page_size != l.page_size || image.pooled_rows != l.pooled_rows ||
+ image.idx_dim != g.idx_key_dim) {
+ error = "conversation snapshot: incompatible K/V geometry";
+ return false;
+ }
+ for (size_t i = 0; i < src.size(); ++i)
+ if (src[i]->size() != sizes[i]) { error = "conversation snapshot: invalid K/V payload size"; return false; }
+ const auto dst = pools(st);
+ for (size_t i = 0; i < src.size(); ++i)
+ if (sizes[i] && !dst[i]) { error = "conversation snapshot: missing target state buffer"; return false; }
+ return true;
+}
+
+bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,
+ int64_t upto, bool index, std::string& error) {
+ if (!conversation_kv_validate(image, st, g, upto, index, error)) return false;
+ const std::array<const ConversationBuffer*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
+ const auto dst = pools(st);
+ for (size_t i = 0; i < src.size(); ++i)
+ if (!src[i]->visit(0, src[i]->size(), [&](const uint8_t* p, size_t n, size_t at) {
+ return transfer(static_cast<uint8_t*>(dst[i]) + at, p, n, error);
+ })) return false;
+ // VRAM slots still contain the outgoing conversation. Resolve must refill
+ // them from the restored authoritative pools before any attention reads.
+ if (st.kv_mode == 1) strata::kernels::kv_stream_reset(st.map, nullptr);
+ if (st.kv_mode == 2 && upto > 0) {
+ auto shapes = strata::kernels::qsa_real_shapes();
+ shapes.n_head_kv = g.n_head_kv; shapes.head_dim = g.head_dim;
+ const int64_t end = (upto + shapes.page_size - 1) / shapes.page_size;
+ strata::kernels::kv_ring_restore(qsa_attn_pools(st), st.host, qsa_kv_format(st),
+ std::max<int64_t>(0, end - st.n_slots), end, st.n_slots, shapes, nullptr);
+ }
+ /*
+ DPCT1010: SYCL uses exceptions to report errors and does not use the
+ error codes. The cudaGetLastError function call was replaced with 0. You
+ need to rewrite this code.
+ */
+ const auto status = 0;
+ if (status == 0) return true;
+ /*
+ 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.
+ */
+ error = std::string("conversation snapshot residency restore: ") +
+ dpct::get_error_string_dummy(status);
+ return false;
+}
+
+bool conversation_kv_verify(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,
+ int64_t upto, bool index, uint64_t& fingerprint, std::string& error) {
+ if (!conversation_kv_validate(image, st, g, upto, index, error)) return false;
+ std::array<uint8_t, 65536> buffer;
+ uint64_t hash = 1469598103934665603ull;
+ auto compare = [&](const void* device, const uint8_t* expected, size_t bytes, bool include_hash) {
+ for (size_t offset = 0; offset < bytes;) {
+ const size_t n = std::min(buffer.size(), bytes - offset);
+ if (!transfer(buffer.data(), static_cast<const uint8_t*>(device) + offset, n, error)) return false;
+ if (std::memcmp(buffer.data(), expected + offset, n) != 0) {
+ error = "conversation snapshot: restored K/V bytes differ";
+ return false;
+ }
+ if (include_hash) for (size_t i = 0; i < n; ++i) { hash ^= buffer[i]; hash *= 1099511628211ull; }
+ offset += n;
+ }
+ return true;
+ };
+ const std::array<const ConversationBuffer*, 5> saved = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
+ const auto authoritative = pools(st);
+ for (size_t i = 0; i < saved.size(); ++i)
+ if (!saved[i]->visit(0, saved[i]->size(), [&](const uint8_t* p, size_t n, size_t at) {
+ return compare(static_cast<const uint8_t*>(authoritative[i]) + at, p, n, true);
+ })) return false;
+ if (st.kv_mode == 2 && image.cells > 0) {
+ const auto resident = pools(st, true);
+ const int64_t end = image.cells / image.page_size;
+ const int64_t begin = std::max<int64_t>(0, end - st.n_slots);
+ for (size_t i = 0; i < 4; ++i) {
+ if (saved[i]->empty()) continue;
+ const size_t page_bytes = saved[i]->size() / size_t(end);
+ for (int64_t page = begin; page < end; ++page)
+ if (!saved[i]->visit(size_t(page) * page_bytes, page_bytes,
+ [&](const uint8_t* p, size_t n, size_t at) {
+ const size_t offset = size_t(page % st.n_slots) * page_bytes + at - size_t(page) * page_bytes;
+ return compare(static_cast<const uint8_t*>(resident[i]) + offset, p, n, false);
+ })) return false;
+ }
+ }
+ fingerprint = hash;
+ return true;
+}
+
+} // namespace strata::core
diff --git a/sycl/src/core/conversation_snapshot_test.cpp b/sycl/src/core/conversation_snapshot_test.cpp
new file mode 100644
index 000000000..7544df2ab
--- /dev/null
+++ b/sycl/src/core/conversation_snapshot_test.cpp
@@ -0,0 +1,326 @@
+#define DPCT_PROFILING_ENABLED
+#include <sycl/sycl.hpp>
+#include <dpct/dpct.hpp>
+#include "strata/core/conversation_snapshot.hpp"
+#include "strata/kernels/kv_q4.hpp"
+
+#include <array>
+#include <cstdio>
+#include <cstdlib>
+#include <limits>
+#include <vector>
+
+using namespace strata::core;
+using namespace strata::kernels;
+
+namespace {
+int checks = 0;
+void check(bool ok, const char* label) {
+ ++checks;
+ if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); }
+}
+void cuda_check(dpct::err0 e) {
+ /*
+ 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.
+ */
+}
+struct Fixture {
+ ModelGeometry g;
+ QsaState state;
+ std::vector<void*> device, host;
+ std::array<void*,5> sources{};
+ std::array<size_t,5> sizes{};
+
+ template<class T> void alloc(T*& p, size_t n, bool pinned = false) {
+ if (!n) return;
+ void* raw = nullptr;
+ if (pinned) {
+ /*
+ DPCT1048: The original value cudaHostAllocMapped is not
+ meaningful in the migrated code and was removed or replaced with 0.
+ You may need to check the migrated code.
+ */
+ cuda_check(DPCT_CHECK_ERROR(raw = (void *)sycl::malloc_host(
+ n, dpct::get_in_order_queue())));
+ host.push_back(raw);
+ void* mapped = nullptr;
+ cuda_check(DPCT_CHECK_ERROR(mapped = (void *)raw));
+ p = static_cast<T*>(mapped);
+ } else {
+ cuda_check(DPCT_CHECK_ERROR(raw = (void *)sycl::malloc_device(
+ n, dpct::get_in_order_queue())));
+ device.push_back(raw); p = static_cast<T *>(raw);
+ }
+ }
+ Fixture(int fmt, int mode) {
+ auto& st = state;
+ st.kv_mode = mode; st.kv_int8 = fmt==kKvInt8; st.kv_q4 = fmt==kKvQ4; st.kv_hybrid = fmt==3;
+ st.n_pages = 24; st.n_slots = mode ? 4 : st.n_pages;
+ st.max_cells = st.n_pages * 4; st.idx_pooled_rows = mode==2 ? 2 : st.max_cells/4+2;
+ const size_t per = fmt==kKvQ4 ? kv_q4_bytes_per_head((int)g.head_dim) : g.head_dim*((st.kv_int8 || st.kv_hybrid) ? 1:2);
+ const size_t rows = st.max_cells*g.n_head_kv, slot_rows = st.n_slots*4*g.n_head_kv;
+ sizes = {rows*per, rows*per, fmt==kKvInt8 ? rows*(g.head_dim/64)*2:0,
+ fmt==kKvInt8 ? rows*(g.head_dim/64)*2:0, (size_t)st.idx_pooled_rows*g.idx_key_dim*4};
+ if (fmt==3) {
+ sizes = {rows*per, rows*kv_q4_bytes_per_head((int)g.head_dim), rows*(g.head_dim/64)*2, 0,
+ (size_t)st.idx_pooled_rows*g.idx_key_dim*4};
+ alloc(st.k_q,sizes[0]); alloc(st.v_q4,sizes[1]); alloc(st.k_scale,sizes[2]);
+ sources[0]=st.k_q; sources[1]=st.v_q4; sources[2]=st.k_scale;
+ } else if (fmt==kKvQ4) {
+ alloc(st.k_q4,slot_rows*per); alloc(st.v_q4,slot_rows*per);
+ if (mode) {alloc(st.host.k_q4,sizes[0],true); alloc(st.host.v_q4,sizes[1],true);}
+ sources[0]=mode?st.host.k_q4:st.k_q4; sources[1]=mode?st.host.v_q4:st.v_q4;
+ } else if (fmt==kKvInt8) {
+ alloc(st.k_q,slot_rows*per); alloc(st.v_q,slot_rows*per);
+ alloc(st.k_scale,slot_rows*(g.head_dim/64)*2); alloc(st.v_scale,slot_rows*(g.head_dim/64)*2);
+ if (mode) {
+ alloc(st.host.k_q,sizes[0],true); alloc(st.host.v_q,sizes[1],true);
+ alloc(st.host.k_scale,sizes[2],true); alloc(st.host.v_scale,sizes[3],true);
+ }
+ sources[0]=mode?st.host.k_q:st.k_q; sources[1]=mode?st.host.v_q:st.v_q;
+ sources[2]=mode?st.host.k_scale:st.k_scale; sources[3]=mode?st.host.v_scale:st.v_scale;
+ } else {
+ alloc(st.k_pool,slot_rows*per); alloc(st.v_pool,slot_rows*per);
+ if (mode) {alloc(st.host.k_pool,sizes[0],true); alloc(st.host.v_pool,sizes[1],true);}
+ sources[0]=mode?st.host.k_pool:st.k_pool; sources[1]=mode?st.host.v_pool:st.v_pool;
+ }
+ alloc(st.idx_pooled,sizes[4]); sources[4]=st.idx_pooled;
+ alloc(st.page_table,st.n_pages*4);
+ if (mode==1) {
+ auto& m=st.map;
+ m.page_table=st.page_table; m.n_blocks=st.n_pages; m.n_slots=st.n_slots;
+ alloc(m.slot_block,st.n_slots*4); alloc(m.slot_stamp,st.n_slots*4); alloc(m.slot_ref,st.n_slots*4);
+ alloc(m.miss_block,st.n_slots*4); alloc(m.miss_slot,st.n_slots*4); alloc(m.ctl,kKvCtlInts*4);
+ } else if (mode==2) {
+ kv_ring_table(st.page_table,st.n_pages,st.n_slots,nullptr);
+ }
+ }
+ void fill(uint8_t salt) {
+ for (size_t i=0;i<sources.size();++i) {
+ std::vector<uint8_t> data(sizes[i]);
+ for (size_t j=0;j<data.size();++j) data[j]=(uint8_t)(salt+i*31+j*7+j/257);
+ if (!data.empty()) cuda_check(DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue()
+ .memcpy(sources[i], data.data(), data.size())
+ .wait()));
+ }
+ }
+ void fill_after(uint8_t salt, int64_t first_dirty) {
+ for (size_t i=0;i<sources.size();++i) {
+ const size_t offset = i == 4 ? size_t(first_dirty/4)*g.idx_key_dim*4
+ : (sizes[i]/size_t(state.max_cells))*size_t((first_dirty/4)*4);
+ if (sizes[i] > offset)
+ cuda_check(DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue()
+ .memset(static_cast<uint8_t *>(sources[i]) + offset,
+ salt, sizes[i] - offset)
+ .wait()));
+ }
+ }
+ ~Fixture() {
+ for (void *p : device)
+ DPCT_CHECK_ERROR(sycl::free(p, dpct::get_in_order_queue()));
+ for (void *p : host) DPCT_CHECK_ERROR(free(p));
+ }
+};
+bool equal(const ConversationKv& a,const ConversationKv& b) {
+ return a.k==b.k && a.v==b.v && a.k_scale==b.k_scale && a.v_scale==b.v_scale && a.pooled==b.pooled;
+}
+
+void full_session(int fmt, int mode, int experts) {
+ Fixture main(fmt,mode), draft(fmt==3?kKvInt8:fmt,2);
+ auto& g=main.g;
+ g.n_layers=4; g.n_expert=experts;
+ g.ssm_state_size=2; g.ssm_v_heads=2; g.ssm_conv_channels=8;
+ SessionState ss;
+ ss.max_cells=96; ss.qsa_states=&main.state;
+ ss.layer_hi=g.n_layers; ss.gdn_alloc=g.n_gdn_layers(); ss.qsa_alloc=g.n_qsa_layers(); // the whole-model carve
+ std::string err;
+ ConversationStateSizes sizes;
+ check(conversation_state_sizes(g,sizes,err),"whole-session geometry sizes");
+ main.alloc(ss.gdn_state,sizes.gdn); main.alloc(ss.ple_hist,sizes.ple);
+ main.alloc(main.state.idx_tail,sizes.tail); main.alloc(main.state.idx_dead,sizes.dead);
+ main.alloc(main.state.idx_block_pos,sizes.block_pos);
+ std::vector<int32_t> ids(65);
+ for (size_t i=0;i<ids.size();++i) ids[i]=(int32_t)i+1;
+ std::vector<ConversationImageKey> images;
+ std::vector<ConversationCheckpoint> checkpoints;
+ auto fill = [&](uint8_t salt) {
+ try {
+ main.fill(salt); draft.fill(salt);
+ for (const auto& [p,n] : std::vector<std::pair<void*,size_t>>{
+ {ss.gdn_state,sizes.gdn},{ss.ple_hist,sizes.ple},{main.state.idx_tail,sizes.tail},
+ {main.state.idx_dead,sizes.dead},{main.state.idx_block_pos,sizes.block_pos}})
+ cuda_check(DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue().memset(p, salt, n).wait()));
+ // A real indexer maintains its spare pooled row as a copy of idx_dead.
+ cuda_check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
+ main.state.idx_pooled + (ids.size() / 4) * g.idx_key_dim,
+ main.state.idx_dead, sizes.dead).wait()));
+ cuda_check(DPCT_CHECK_ERROR(
+ dpct::get_current_device().queues_wait_and_throw()));
+ }
+ catch (sycl::exception const &exc) {
+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__
+ << ", line:" << __LINE__ << std::endl;
+ std::exit(1);
+ }
+ };
+ fill(13);
+ ConversationCheckpoint checkpoint;
+ checkpoint.ids.assign(ids.begin(),ids.begin()+3);
+ check(conversation_checkpoint_save(checkpoint,ss,g,err),"save complete running checkpoint");
+ checkpoint.used = 17;
+ checkpoints.push_back(std::move(checkpoint));
+ const ConversationView view{ids,images,checkpoints,true};
+ SavedConversation a,b,restored;
+ check(conversation_snapshot_save(a,view,ss,g,draft.state,err),"capture complete A");
+ check(a.checkpoints[0].used == 17,"upstream checkpoint LRU stamp survives capture");
+ fill(177);
+ check(conversation_snapshot_save(b,view,ss,g,draft.state,err),"capture complete B");
+ check(a.live.dead!=b.live.dead,"different opening-state spare keys in regression fixture");
+ auto bad=a; bad.kv.back().k.pop_back();
+ check(conversation_snapshot_restore(bad,ss,g,draft.state,err)==ConversationRestore::invalid,
+ "reject invalid late draft before any main-layer write");
+ check(conversation_snapshot_save(restored,view,ss,g,draft.state,err),"capture B after refused restore");
+ check(restored.live.gdn==b.live.gdn && restored.live.dead==b.live.dead &&
+ equal(restored.kv[0],b.kv[0]) && equal(restored.kv[1],b.kv[1]),"refusal preserves all tested state");
+ check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore complete A");
+ check(conversation_snapshot_save(restored,view,ss,g,draft.state,err),"capture restored A");
+ check(restored.live.gdn==a.live.gdn && restored.live.ple==a.live.ple && restored.live.tails==a.live.tails &&
+ restored.live.dead==a.live.dead && restored.live.block_pos==a.live.block_pos &&
+ equal(restored.kv[0],a.kv[0]) && equal(restored.kv[1],a.kv[1]),"whole-session A/B/A exactness including spare key");
+ check(ss.ple_prev[0]==64 && ss.ple_prev[1]==65,"PLE token window reconstructed");
+ for (int64_t dirty : {65, 3, 0}) {
+ check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore growth fixture base");
+ ConversationKvReuse reuse{a.kv,65,dirty};
+ const uint8_t* original = nullptr;
+ reuse.kv[0].k.visit(0,1,[&](const uint8_t* p,size_t,size_t){original=p;return true;});
+ main.fill_after(91,dirty); draft.fill_after(91,std::max<int64_t>(0,dirty-1));
+ cuda_check(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memset(ss.gdn_state, 91, sizes.gdn)
+ .wait()));
+ ids.resize(70);
+ for (size_t i=65;i<ids.size();++i) ids[i]=int32_t(i+1);
+ cuda_check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
+ main.state.idx_pooled + (ids.size() / 4) * g.idx_key_dim,
+ main.state.idx_dead, sizes.dead).wait()));
+ SavedConversation fresh,incremental;
+ check(conversation_snapshot_save(fresh,view,ss,g,draft.state,err),"full capture reference after growth or rewind");
+ size_t peak=0,reused=0;
+ check(conversation_snapshot_capture_bytes(reuse,view,ss,g,draft.state,peak,err),"admit incremental capture peak");
+ check(conversation_snapshot_save(incremental,view,ss,g,draft.state,err,std::move(reuse),&reused),"capture with retained pages");
+ check(incremental.bytes() <= peak,"incremental allocation stays within admitted bound");
+ check(incremental.live.gdn==fresh.live.gdn && incremental.live.ple==fresh.live.ple &&
+ incremental.live.dead==fresh.live.dead && equal(incremental.kv[0],fresh.kv[0]) &&
+ equal(incremental.kv[1],fresh.kv[1]),"incremental capture equals full capture after growth or rewind");
+ check((dirty>=4)==(reused>0),"only complete unchanged pages or rows are retained");
+ incremental.kv[0].k.visit(0,1,[&](const uint8_t* p,size_t,size_t){
+ check(p==original,"growth never reallocates the retained payload");return true;
+ });
+ check(conversation_snapshot_restore(incremental,ss,g,draft.state,err)==ConversationRestore::restored,"restore segmented incremental snapshot");
+ uint64_t fingerprint=0;
+ check(conversation_kv_verify(incremental.kv.back(),draft.state,g,70,false,fingerprint,err),"incremental draft authoritative and ring read-back");
+ ids.resize(65);
+ }
+ check(conversation_checkpoint_restore(a.checkpoints[0],ss,g,err),"restore early running checkpoint");
+ std::vector<uint8_t> spare(sizes.dead);
+ cuda_check(DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue()
+ .memcpy(spare.data(), main.state.idx_pooled, sizes.dead)
+ .wait()));
+ check(spare==a.checkpoints[0].dead,"checkpoint rebuilds spare row over a later completed block");
+ check(ss.ple_prev[0]==2 && ss.ple_prev[1]==3,"checkpoint PLE token window");
+}
+}
+
+int main() {
+ int devices=0;
+ if (DPCT_CHECK_ERROR(devices = dpct::device_count()) != 0 ||
+ !devices) return 77;
+ for (int fmt : std::array<int,4>{kKvF16,kKvInt8,kKvQ4,3}) for (int mode : {0,1,2}) {
+ if (fmt==3 && mode!=0) continue;
+ Fixture f(fmt,mode);
+ if (fmt==3) {
+ std::string err;
+ ConversationKv invalid;
+ for (int unsupported : {1,2}) {
+ f.state.kv_mode=unsupported;
+ check(conversation_kv_bytes(f.state,f.g,9,true)==0,"hybrid streaming/ring rejected without block-mover abort");
+ check(!conversation_kv_save(invalid,f.state,f.g,9,true,err),"hybrid streaming/ring capture fails closed");
+ }
+ f.state.kv_mode=0;
+ }
+ {
+ std::string err;
+ ConversationKv invalid;
+ for (const int64_t bad : {-1LL, 97LL, (long long) std::numeric_limits<int64_t>::max()}) {
+ check(!conversation_kv_save(invalid,f.state,f.g,bad,mode!=2,err),"reject invalid save extent before allocation");
+ check(!conversation_kv_restore(invalid,f.state,f.g,bad,mode!=2,err),"reject invalid restore extent before copying");
+ check(conversation_kv_bytes(f.state,f.g,bad,mode!=2)==0,"invalid extent cannot overflow byte estimate");
+ }
+ }
+ for (int64_t upto : {0,1,3,4,5,63,64,65,96}) {
+ const bool index=mode!=2;
+ std::string err;
+ f.fill(13);
+ ConversationKv a,b,restored;
+ cuda_check(DPCT_CHECK_ERROR(
+ dpct::get_current_device().queues_wait_and_throw()));
+ check(conversation_kv_save(a,f.state,f.g,upto,index,err),"save A");
+ check(a.bytes()==conversation_kv_bytes(f.state,f.g,upto,index),"size estimate equals snapshot payload");
+ f.fill(177);
+ check(conversation_kv_save(b,f.state,f.g,upto,index,err),"save B");
+ check(upto==0 || !equal(a,b),"fixture changes state");
+ check(conversation_kv_restore(a,f.state,f.g,upto,index,err),"restore A over B");
+ cuda_check(DPCT_CHECK_ERROR(
+ dpct::get_current_device().queues_wait_and_throw()));
+ check(conversation_kv_save(restored,f.state,f.g,upto,index,err),"read back restored A");
+ check(equal(a,restored),"A/B/A byte-exact K/V and indexer state");
+ uint64_t fingerprint = 0;
+ check(conversation_kv_verify(a,f.state,f.g,upto,index,fingerprint,err),"verify restored authoritative and resident bytes without rewriting them");
+ if (mode==1) {
+ std::vector<int32_t> table((size_t)f.state.n_pages);
+ cuda_check(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memcpy(table.data(),
+ f.state.page_table,
+ table.size() * 4)
+ .wait()));
+ check(std::all_of(table.begin(),table.end(),[](int32_t x){return x==-1;}),"stale VRAM pages invalidated");
+ }
+ if (mode==2 && upto>0) {
+ const auto s=qsa_real_shapes();
+ const int64_t b1=(upto+s.page_size-1)/s.page_size,b0=std::max<int64_t>(0,b1-f.state.n_slots);
+ const size_t block=kv_block_bytes(s,fmt)/2;
+ // Codes and scales are separate in INT8; check code bytes here.
+ const size_t code_block=fmt==kKvInt8 ? s.page_size*s.n_head_kv*s.head_dim : block;
+ const void* slots=fmt==kKvQ4?(void*)f.state.k_q4:fmt==kKvInt8?(void*)f.state.k_q:(void*)f.state.k_pool;
+ std::vector<uint8_t> got(code_block);
+ for (int64_t page=b0;page<b1;++page) {
+ cuda_check(DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue()
+ .memcpy(got.data(),
+ (const uint8_t *)slots +
+ (page % f.state.n_slots) * code_block,
+ code_block)
+ .wait()));
+ std::vector<uint8_t> expected(code_block);
+ check(a.k.read(expected.data(), page*code_block, code_block),"read segmented expected draft page");
+ check(got == expected,"draft ring contains restored pages");
+ }
+ }
+ auto bad=a; bad.head_dim++;
+ check(!conversation_kv_restore(bad,f.state,f.g,upto,index,err),"reject incompatible geometry");
+ if (!a.k.empty()) {
+ bad=a; bad.k.pop_back();
+ check(!conversation_kv_restore(bad,f.state,f.g,upto,index,err),"reject malformed payload");
+ }
+ }
+ }
+ for (int fmt : {kKvF16,kKvInt8,kKvQ4}) for (int mode : {0,1}) for (int experts : {256,512})
+ full_session(fmt,mode,experts);
+ for (int experts : {256,512}) full_session(3,0,experts);
+ std::printf("conversation_snapshot_test: %d checks passed\n",checks);
+}
diff --git a/sycl/src/core/conversation_state.cpp b/sycl/src/core/conversation_state.cpp
new file mode 100644
index 000000000..584fc3ab2
--- /dev/null
+++ b/sycl/src/core/conversation_state.cpp
@@ -0,0 +1,316 @@
+// sycl/src/core/conversation_state.cpp - SYCL port of src/core/conversation_state.cpp (two CUDA calls, by hand).
+#include <sycl/sycl.hpp>
+#include <dpct/dpct.hpp>
+#include "strata/core/conversation_snapshot.hpp"
+#include "conversation_checked.hpp"
+
+#include <algorithm>
+#include <array>
+#include <limits>
+
+namespace strata::core {
+namespace {
+using conversation_detail::add;
+using conversation_detail::product;
+
+std::array<int64_t, 18> geometry_key(const ModelGeometry& g) {
+ return {g.n_embd, g.n_layers, g.qsa_interval, g.ssm_state_size, g.ssm_k_heads,
+ g.ssm_v_heads, g.ssm_d_conv, g.ssm_conv_channels, g.ssm_value_dim,
+ g.n_head, g.n_head_kv, g.head_dim, g.idx_q_heads, g.idx_key_dim,
+ g.hc, g.hc_lr, g.n_expert, g.n_ff};
+}
+
+bool fail(std::string& error, const char* message) {
+ error = std::string("conversation snapshot: ") + message;
+ return false;
+}
+
+// SYCL port (hand-ported: no CUDA header is included here, so dpct never saw this file): the device-wide sync and
+// the any-direction copy as SYCL queue operations; errors arrive as exceptions instead of status codes.
+bool sync(std::string& error) {
+ try {
+ dpct::get_current_device().queues_wait_and_throw();
+ return true;
+ } catch (sycl::exception const& e) {
+ error = std::string("conversation snapshot synchronize: ") + e.what();
+ return false;
+ }
+}
+
+bool copy(void* dst, const void* src, size_t bytes, std::string& error) {
+ if (!bytes) return true;
+ if (!dst || !src) return fail(error, "missing running-state buffer");
+ try {
+ dpct::get_in_order_queue().memcpy(dst, src, bytes).wait();
+ return true;
+ } catch (sycl::exception const& e) {
+ error = std::string("conversation snapshot running-state copy: ") + e.what();
+ return false;
+ }
+}
+
+// The session's carve (#216): `qsa_states` keeps global ordinals and holds the owned ones
+// [qsa_ord0, qsa_ord0 + qsa_alloc); `gdn_state` holds `gdn_alloc` rows. A whole-model session owns every layer.
+size_t owned_qsa(const SessionState& ss) { return (size_t) std::max<int64_t>(ss.qsa_alloc, 0); }
+const QsaState& owned(const SessionState& ss, size_t j) { return ss.qsa_states[(size_t) ss.qsa_ord0 + j]; }
+
+bool image_keys(const std::vector<ConversationImageKey>& images, size_t tokens) {
+ int64_t previous = -1;
+ for (const auto& image : images) {
+ if (image.start <= previous || image.start < 0 || (uint64_t) image.start >= tokens) return false;
+ previous = image.start;
+ }
+ return true;
+}
+
+bool checkpoint_targets(const SessionState& ss, const ModelGeometry& g, size_t tokens,
+ ConversationStateSizes& z, std::string& error) {
+ if (!conversation_session_sizes(g, ss, z, error)) return false;
+ if (ss.max_cells < 0 || tokens > (uint64_t) ss.max_cells || (z.gdn && !ss.gdn_state) ||
+ (owned_qsa(ss) && !ss.qsa_states)) return fail(error, "invalid session running-state targets");
+ for (size_t j = 0; j < owned_qsa(ss); ++j) {
+ const auto& st = owned(ss, j);
+ const auto block = strata::kernels::qsa_real_shapes().idx_block;
+ size_t pooled_bytes = 0;
+ if (!st.idx_tail || !st.idx_dead || !st.idx_block_pos || !st.idx_pooled ||
+ st.max_cells < 0 || tokens > (uint64_t) st.max_cells ||
+ (tokens && tokens / (uint64_t) block >= (uint64_t) std::max<int64_t>(0, st.idx_pooled_rows)) ||
+ !product(pooled_bytes, {tokens / (uint64_t) block + 1, (uint64_t) g.idx_key_dim, sizeof(float)}))
+ return fail(error, "invalid indexer running-state target");
+ }
+ return true;
+}
+
+bool view_validate(const ConversationView& view, const SessionState& ss,
+ const ModelGeometry& g, std::string& error) {
+ ConversationStateSizes z;
+ if (!checkpoint_targets(ss, g, view.ids.size(), z, error)) return false;
+ if (view.ids.empty() || !image_keys(view.images, view.ids.size()) ||
+ std::any_of(view.ids.begin(), view.ids.end(), [](int32_t id) { return id < 0; }))
+ return fail(error, "invalid live token/image metadata");
+ for (const auto& c : view.checkpoints) {
+ if (!c.stage_parts.empty() || c.ids.empty() || c.ids.size() > view.ids.size() ||
+ !std::equal(c.ids.begin(), c.ids.end(), view.ids.begin()))
+ return fail(error, "checkpoint is not a live token prefix");
+ if (!conversation_checkpoint_validate(c, ss, g, error)) return false;
+ size_t image = 0;
+ for (const auto& key : view.images) {
+ if ((uint64_t) key.start >= c.ids.size()) break;
+ if (image >= c.imgs.size() || !(c.imgs[image++] == key))
+ return fail(error, "checkpoint image identity differs");
+ }
+ if (image != c.imgs.size()) return fail(error, "checkpoint image prefix differs");
+ }
+ return true;
+}
+
+bool metadata_bytes(const ConversationCheckpoint& c, size_t& total) {
+ size_t ids = 0, images = 0;
+ if (!product(ids, {c.ids.size(), sizeof(int32_t)}) ||
+ !product(images, {c.imgs.size(), sizeof(ConversationImageKey)})) return false;
+ for (size_t n : {ids, images, c.gdn.size(), c.ple.size(), c.tails.size(), c.dead.size(), c.block_pos.size()})
+ if (!add(total, n)) return false;
+ return true;
+}
+} // namespace
+
+bool conversation_state_sizes(const ModelGeometry& g, ConversationStateSizes& z, std::string& error) {
+ z = {};
+ const auto key = geometry_key(g);
+ for (size_t i = 0; i < key.size(); ++i)
+ if (key[i] < 0 || (i != 1 && key[i] == 0)) return fail(error, "invalid model geometry");
+ size_t recurrence = 0, convolution = 0;
+ if (!product(recurrence, {(uint64_t) g.ssm_state_size, (uint64_t) g.ssm_v_heads, (uint64_t) g.ssm_state_size}) ||
+ !product(convolution, {(uint64_t) g.ssm_conv_channels, (uint64_t) (g.ssm_d_conv - 1)}) ||
+ !add(recurrence, convolution) ||
+ !product(z.gdn, {(uint64_t) g.n_gdn_layers(), recurrence, sizeof(float)}) ||
+ !product(z.ple, {strata::kernels::NG_HIST, strata::kernels::NG_HC_DIM, sizeof(float)}) ||
+ !product(z.tail, {(uint64_t) (strata::kernels::qsa_real_shapes().idx_block - 1),
+ (uint64_t) g.idx_key_dim, sizeof(float)}) ||
+ !product(z.dead, {(uint64_t) g.idx_key_dim, sizeof(float)}))
+ return fail(error, "running-state byte count overflow");
+ z.block_pos = sizeof(int32_t);
+ size_t total = 0;
+ if (!product(total, {(uint64_t) g.n_qsa_layers(), z.tail}) ||
+ !product(total, {(uint64_t) g.n_qsa_layers(), z.dead}) ||
+ !product(total, {(uint64_t) g.n_qsa_layers(), z.block_pos}))
+ return fail(error, "indexer byte count overflow");
+ return true;
+}
+
+bool conversation_session_sizes(const ModelGeometry& g, const SessionState& ss, ConversationStateSizes& z,
+ std::string& error) {
+ if (!conversation_state_sizes(g, z, error)) return false;
+ const int64_t n_gdn = g.n_gdn_layers(), n_qsa = g.n_qsa_layers();
+ if (ss.gdn_alloc < 0 || ss.gdn_alloc > n_gdn || ss.qsa_ord0 < 0 || ss.qsa_alloc < 0 ||
+ ss.qsa_ord0 > n_qsa || ss.qsa_alloc > n_qsa - ss.qsa_ord0)
+ return fail(error, "invalid session layer carve");
+ // z.gdn is n_gdn whole rows; the session holds gdn_alloc of them (all of them for the default full range)
+ z.gdn = n_gdn > 0 ? z.gdn / (size_t) n_gdn * (size_t) ss.gdn_alloc : 0;
+ return true;
+}
+
+bool conversation_checkpoint_validate(const ConversationCheckpoint& c, const SessionState& ss,
+ const ModelGeometry& g, std::string& error) {
+ ConversationStateSizes z;
+ if (!checkpoint_targets(ss, g, c.ids.size(), z, error)) return false;
+ const size_t layers = owned_qsa(ss);
+ if (c.gdn.size() != z.gdn || c.ple.size() != (ss.ple_hist ? z.ple : 0) ||
+ c.tails.size() != layers * z.tail || c.dead.size() != layers * z.dead ||
+ c.block_pos.size() != layers * z.block_pos || !image_keys(c.imgs, c.ids.size()))
+ return fail(error, "invalid checkpoint running-state payload");
+ return true;
+}
+
+bool conversation_checkpoint_save(ConversationCheckpoint& c, const SessionState& ss,
+ const ModelGeometry& g, std::string& error) {
+ ConversationStateSizes z;
+ if (!checkpoint_targets(ss, g, c.ids.size(), z, error)) return false;
+ const size_t layers = owned_qsa(ss);
+ c.gdn.resize(z.gdn); c.ple.resize(ss.ple_hist ? z.ple : 0);
+ c.tails.resize(layers * z.tail); c.dead.resize(layers * z.dead); c.block_pos.resize(layers * z.block_pos);
+ if (!copy(c.gdn.data(), ss.gdn_state, c.gdn.size(), error) ||
+ !copy(c.ple.data(), ss.ple_hist, c.ple.size(), error)) return false;
+ for (size_t j = 0; j < layers; ++j) {
+ const auto& st = owned(ss, j);
+ if (!copy(c.tails.data() + j * z.tail, st.idx_tail, z.tail, error) ||
+ !copy(c.dead.data() + j * z.dead, st.idx_dead, z.dead, error) ||
+ !copy(c.block_pos.data() + j * z.block_pos, st.idx_block_pos, z.block_pos, error)) return false;
+ }
+ return true;
+}
+
+bool conversation_checkpoint_restore(const ConversationCheckpoint& c, SessionState& ss,
+ const ModelGeometry& g, std::string& error) {
+ if (!conversation_checkpoint_validate(c, ss, g, error)) return false;
+ ConversationStateSizes z;
+ if (!conversation_session_sizes(g, ss, z, error)) return false;
+ if (!copy(ss.gdn_state, c.gdn.data(), c.gdn.size(), error) ||
+ !copy(ss.ple_hist, c.ple.data(), c.ple.size(), error)) return false;
+ for (size_t j = 0; j < owned_qsa(ss); ++j) {
+ const auto& st = owned(ss, j);
+ if (!copy(st.idx_tail, c.tails.data() + j * z.tail, z.tail, error) ||
+ !copy(st.idx_dead, c.dead.data() + j * z.dead, z.dead, error) ||
+ !copy(st.idx_block_pos, c.block_pos.data() + j * z.block_pos, z.block_pos, error)) return false;
+ if (!c.ids.empty()) {
+ const size_t row = c.ids.size() / strata::kernels::qsa_real_shapes().idx_block;
+ if (!copy(st.idx_pooled + row * g.idx_key_dim, c.dead.data() + j * z.dead, z.dead, error)) return false;
+ }
+ }
+ const size_t tokens = c.ids.size();
+ ss.ple_prev[0] = tokens >= 2 ? c.ids[tokens - 2] : -1;
+ ss.ple_prev[1] = tokens >= 1 ? c.ids[tokens - 1] : -1;
+ return sync(error);
+}
+
+bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& ss,
+ const ModelGeometry& g, const QsaState& draft, size_t& bytes, std::string& error) {
+ bytes = 0;
+ if (!view_validate(view, ss, g, error)) return false;
+ ConversationStateSizes z;
+ if (!conversation_session_sizes(g, ss, z, error)) return false;
+ size_t ids = 0, images = 0, checkpoints = 0, layers = 0, tails = 0, dead = 0, positions = 0;
+ const auto qsa = (uint64_t) owned_qsa(ss);
+ if (!product(ids, {view.ids.size(), sizeof(int32_t)}) ||
+ !product(images, {view.images.size(), sizeof(ConversationImageKey)}) ||
+ !product(checkpoints, {view.checkpoints.size(), sizeof(ConversationCheckpoint)}) ||
+ !product(layers, {qsa + 1, sizeof(ConversationKv)}) ||
+ !product(tails, {qsa, z.tail}) || !product(dead, {qsa, z.dead}) ||
+ !product(positions, {qsa, z.block_pos})) return fail(error, "snapshot metadata byte count overflow");
+ for (size_t n : {ids, images, checkpoints, layers, tails, dead, positions, z.gdn, ss.ple_hist ? z.ple : 0})
+ if (!add(bytes, n)) return fail(error, "snapshot byte count overflow");
+ for (const auto& c : view.checkpoints)
+ if (!metadata_bytes(c, bytes)) return fail(error, "checkpoint byte count overflow");
+ const int64_t upto = (int64_t) view.ids.size(); // view_validate bounds this by signed max_cells
+ for (uint64_t i = 0; i <= qsa; ++i) {
+ const auto& st = i == qsa ? draft : owned(ss, (size_t) i);
+ const size_t n = conversation_kv_bytes(st, g, upto, i != qsa);
+ if (!n || !add(bytes, n)) return fail(error, "invalid or overflowing K/V byte estimate");
+ }
+ return true;
+}
+
+bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view,
+ const SessionState& ss, const ModelGeometry& g,
+ const QsaState& draft, size_t& bytes, std::string& error) {
+ if (!conversation_snapshot_bytes(view, ss, g, draft, bytes, error)) return false;
+ if (reuse.kv.empty()) return true;
+ const size_t layers = owned_qsa(ss) + 1;
+ if (reuse.kv.size() != layers || reuse.unchanged_tokens < 0 ||
+ reuse.unchanged_tokens > reuse.captured_tokens || reuse.unchanged_tokens > int64_t(view.ids.size()))
+ return fail(error, "invalid retained K/V prefix");
+ for (size_t i = 0; i < layers; ++i) {
+ const bool index = i + 1 != layers;
+ const auto& st = index ? owned(ss, i) : draft;
+ if (!conversation_kv_validate(reuse.kv[i], st, g, reuse.captured_tokens, index, error)) return false;
+ const size_t fresh = conversation_kv_bytes(st, g, int64_t(view.ids.size()), index);
+ size_t retained = 0;
+ if (!conversation_kv_capture_bytes(reuse.kv[i], st, g, int64_t(view.ids.size()), index, retained, error)) return false;
+ bytes -= fresh;
+ if (!add(bytes, retained)) return fail(error, "retained K/V allocation overflow");
+ }
+ size_t directory = 0;
+ if (!product(directory, {reuse.kv.capacity() - layers, sizeof(ConversationKv)}) || !add(bytes, directory))
+ return fail(error, "retained K/V directory overflow");
+ return true;
+}
+
+bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view,
+ const SessionState& ss, const ModelGeometry& g,
+ const QsaState& draft, std::string& error,
+ ConversationKvReuse reuse, size_t* reused_bytes) {
+ size_t estimate = 0;
+ if (!conversation_snapshot_capture_bytes(reuse, view, ss, g, draft, estimate, error) || !sync(error)) return false;
+ // Build into a new object so a failure cannot publish a partial snapshot.
+ SavedConversation captured;
+ captured.geometry = geometry_key(g);
+ captured.layer_lo = ss.layer_lo; captured.layer_hi = ss.layer_hi;
+ captured.live.ids = view.ids; captured.live.imgs = view.images;
+ captured.cvec = view.cvec; captured.checkpoints = view.checkpoints;
+ const int64_t unchanged = reuse.kv.empty() ? 0 : reuse.unchanged_tokens;
+ captured.kv = std::move(reuse.kv);
+ const size_t layers = owned_qsa(ss);
+ captured.kv.resize(layers + 1);
+ if (!conversation_checkpoint_save(captured.live, ss, g, error)) return false;
+ const int64_t upto = (int64_t) view.ids.size();
+ for (size_t j = 0; j < layers; ++j)
+ if (!conversation_kv_save(captured.kv[j], owned(ss, j), g, upto, true, error,
+ unchanged, reused_bytes)) return false;
+ // The draft's final cell may not have been computed when the output cap was
+ // reached. Refresh that page even when the main prefix continued unchanged.
+ if (!conversation_kv_save(captured.kv.back(), draft, g, upto, false, error,
+ std::max<int64_t>(0, unchanged - 1), reused_bytes)) return false;
+ image = std::move(captured);
+ return true;
+}
+
+bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& ss,
+ const ModelGeometry& g, const QsaState& draft, std::string& error) {
+ if (!image.live.stage_parts.empty()) return fail(error, "layer-split parking is not supported");
+ if (image.geometry != geometry_key(g)) return fail(error, "incompatible runtime geometry");
+ // an image holds exactly one carve's running state and K/V: same layer range or nothing
+ if (image.layer_lo != ss.layer_lo || image.layer_hi != ss.layer_hi)
+ return fail(error, "snapshot from another session layer range");
+ const ConversationView view{image.live.ids, image.live.imgs, image.checkpoints, image.cvec};
+ if (!view_validate(view, ss, g, error) || !conversation_checkpoint_validate(image.live, ss, g, error)) return false;
+ const size_t layers = owned_qsa(ss);
+ if (image.kv.size() != layers + 1) return fail(error, "invalid K/V layer count");
+ const int64_t upto = (int64_t) image.live.ids.size();
+ for (size_t j = 0; j < layers; ++j)
+ if (!conversation_kv_validate(image.kv[j], owned(ss, j), g, upto, true, error)) return false;
+ return conversation_kv_validate(image.kv.back(), draft, g, upto, false, error);
+}
+
+ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& ss,
+ const ModelGeometry& g, const QsaState& draft, std::string& error) {
+ if (!conversation_snapshot_validate(image, ss, g, draft, error)) return ConversationRestore::invalid;
+ if (!sync(error)) return ConversationRestore::transfer_failed;
+ const int64_t upto = (int64_t) image.live.ids.size();
+ for (size_t j = 0; j < owned_qsa(ss); ++j)
+ if (!conversation_kv_restore(image.kv[j], owned(ss, j), g, upto, true, error))
+ return ConversationRestore::transfer_failed;
+ if (!conversation_kv_restore(image.kv.back(), draft, g, upto, false, error) ||
+ !conversation_checkpoint_restore(image.live, ss, g, error)) return ConversationRestore::transfer_failed;
+ return ConversationRestore::restored;
+}
+} // namespace strata::core
diff --git a/sycl/src/core/device.dp.cpp b/sycl/src/core/device.dp.cpp
index d72b556a5..5804ed88c 100644
--- a/sycl/src/core/device.dp.cpp
+++ b/sycl/src/core/device.dp.cpp
@@ -41,14 +41,80 @@ __dpct_inline__ void poison_kernel(float *p, uint64_t n_floats) {
if (i < n_floats) p[i] = sycl::bit_cast<float>(0x7fc00000);
}
+#if defined(STRATA_USE_HIP)
+#if !defined(STRATA_HIP_ARCHS)
+#error "STRATA_HIP_ARCHS (the compiled HIP architectures) is set by cmake/hip_backend.cmake"
+#endif
+// "gfx1201:sramecc-:xnack-" -> "gfx1201"
+std::string base_arch(const char* gcn_arch_name) {
+ std::string arch(gcn_arch_name);
+ const size_t colon = arch.find(':');
+ if (colon != std::string::npos) arch.resize(colon);
+ return arch;
+}
+
+bool compiled_for(const std::string& arch) {
+ const std::string list = STRATA_HIP_ARCHS;
+ size_t a = 0;
+ while (a <= list.size()) {
+ size_t b = list.find(',', a);
+ if (b == std::string::npos) b = list.size();
+ if (!arch.empty() && list.compare(a, b - a, arch) == 0 && b - a == arch.size()) return true;
+ a = b + 1;
+ }
+ return false;
+}
+
+std::string arch_problem(const cudaDeviceProp& p, int ordinal) {
+ const std::string arch = base_arch(p.gcnArchName);
+ const std::string card = "GPU " + std::to_string(ordinal) + " (" + p.name + ", " + arch + ")";
+ if (!compiled_for(arch)) {
+ return card + " is not an architecture this Strata engine was compiled for (" + STRATA_HIP_ARCHS +
+ "); compile it for this card (./setup.sh --backend hip, or -DCMAKE_HIP_ARCHITECTURES=" + arch +
+ ", docs/AMD_HIP.md) or choose another GPU with HIP_VISIBLE_DEVICES";
+ }
+ if (p.warpSize != 32) {
+ return card + " runs wave" + std::to_string(p.warpSize) + "; Strata's HIP kernels need wave32";
+ }
+ return "";
+}
+#endif
+
} // namespace
+const char* compiled_gpu_archs() {
+#if defined(STRATA_USE_HIP)
+ return STRATA_HIP_ARCHS;
+#else
+ return "";
+#endif
+}
+
+std::string gpu_arch_problem(int ordinal) {
+#if defined(STRATA_USE_HIP)
+ int count = 0;
+ if (cudaGetDeviceCount(&count) != cudaSuccess || ordinal < 0 || ordinal >= count) {
+ cudaGetLastError();
+ return "";
+ }
+ cudaDeviceProp p{};
+ if (cudaGetDeviceProperties(&p, ordinal) != cudaSuccess) {
+ cudaGetLastError();
+ return "";
+ }
+ return arch_problem(p, ordinal);
+#else
+ (void) ordinal;
+ return "";
+#endif
+}
+
DeviceInfo device_info(int ordinal) {
int count = 0;
check(DPCT_CHECK_ERROR(count = dpct::device_count()), "cudaGetDeviceCount");
if (count == 0) {
#if defined(STRATA_USE_HIP)
- throw CudaError("no HIP device is present; this backend targets gfx1100 wave32", -1);
+ throw CudaError(std::string("no HIP device is present; this engine was compiled for ") + STRATA_HIP_ARCHS, -1);
#else
throw CudaError("no CUDA device is present; Strata needs an NVIDIA GPU (RTX 20 series or newer)", -1);
#endif
@@ -113,16 +179,23 @@ DeviceInfo device_info(int ordinal) {
// fp32-FMA fallback below sm_80, the tensor-core prompt kernels refuse and fall back). Compiling for a
// supported arch is enforced by CMake; RUNNING on an older card is caught here, because a binary can be carried
// to a machine with an older card and would otherwise silently take whatever path the driver chose. The HIP
- // backend is validated on gfx1100 (wave32) only.
+ // backend checks the card against the architectures the binary was compiled for (and wave32).
#if defined(STRATA_USE_HIP)
- if (std::strncmp(p.gcnArchName, "gfx1100", 7) != 0 || p.warpSize != 32) {
- throw CudaError("HIP backend requires validated gfx1100 wave32 hardware", -1);
- }
+ d.arch = base_arch(p.gcnArchName);
+ if (const std::string why = arch_problem(p, ordinal); !why.empty()) throw CudaError(why, -1);
+#else
+ // #236: the experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON: Pascal sm_60, Volta sm_70) runs on the cards it
+ // was built for - refusing them below 7.5 there made the flag useless; the release engine keeps 7.5
+#if defined(STRATA_EXPERIMENTAL_SM60)
+ constexpr int kMinCc = 60;
+ const char* const kNeed = "6.0 or newer (this is the experimental Pascal / Volta build)";
#else
- if (d.cc_major * 10 + d.cc_minor < 75) {
+ constexpr int kMinCc = 75;
+ const char* const kNeed = "7.5 or newer (RTX 20 / 30 / 40 / 50 series)";
+#endif
+ if (d.cc_major * 10 + d.cc_minor < kMinCc) {
throw CudaError("device " + d.name + " reports compute capability " + std::to_string(d.cc_major) +
- "." + std::to_string(d.cc_minor) +
- "; Strata needs compute capability 7.5 or newer (RTX 20 / 30 / 40 / 50 series)",
+ "." + std::to_string(d.cc_minor) + "; Strata needs compute capability " + kNeed,
-1);
}
#endif
diff --git a/sycl/src/core/expert_source.cpp b/sycl/src/core/expert_source.cpp
index c2886a154..efab717c9 100644
--- a/sycl/src/core/expert_source.cpp
+++ b/sycl/src/core/expert_source.cpp
@@ -6,11 +6,14 @@
#include "strata/core/expert_source.hpp"
#include "strata/core/remote_experts.hpp"
#include "strata/kernels/cpu/expert_layout.hpp"
+#include "strata/artifact/gguf_reader.hpp"
#include "strata/core/pinned.hpp"
+#include "strata/platform/memory.hpp"
#include "strata/kernels/elementwise.hpp"
#include "strata/kernels/quantize_act.hpp"
#include "strata/kernels/s2_expert_grouped.hpp"
+#include "strata/kernels/cpu/kq_avx2.hpp"
#include <algorithm>
#include <atomic>
@@ -22,6 +25,9 @@
#include <filesystem>
#include <sstream>
#include <limits>
+#include <map>
+#include <memory>
+#include <mutex>
#include <thread>
#include <utility>
#include <vector>
@@ -39,6 +45,15 @@
#include <unistd.h>
#endif
+// a 64-bit seek (as in pinned.cu): the 32-bit `fseek` wraps past 4 GiB, and the spelling differs per platform
+#ifndef STRATA_FSEEK64
+#ifdef _WIN32
+#define STRATA_FSEEK64(f, o) _fseeki64((f), (long long) (o), SEEK_SET)
+#else
+#define STRATA_FSEEK64(f, o) fseeko((f), (off_t) (o), SEEK_SET)
+#endif
+#endif
+
namespace strata::core {
namespace detail {
@@ -138,10 +153,33 @@ const uint8_t* cache_complement_blob_or_fallback(
return mapped_fallback;
}
+int64_t choose_resident_keep_from(const std::vector<uint64_t>& slot_bytes, uint64_t base_bytes, uint64_t budget,
+ int64_t lend_from) {
+ if (base_bytes > budget) return -1;
+ const int64_t slots = (int64_t) slot_bytes.size();
+ if (lend_from < 0 || lend_from > slots) lend_from = slots; // no lend region: only the experts no slot holds
+ int64_t keep = slots;
+ uint64_t bytes = base_bytes;
+ while (keep > lend_from) {
+ const uint64_t b = slot_bytes[(size_t) keep - 1];
+ if (b > budget - bytes) break;
+ bytes += b;
+ --keep;
+ }
+ return keep;
+}
+
+bool exchange_cache_complement(std::vector<uint64_t>& offsets, size_t in, size_t out) {
+ if (in == out || in >= offsets.size() || out >= offsets.size() || offsets[in] == kNoCacheComplement ||
+ offsets[out] != kNoCacheComplement) return false;
+ offsets[out] = offsets[in];
+ offsets[in] = kNoCacheComplement;
+ return true;
+}
+
} // namespace detail
namespace {
-constexpr uint64_t kPinnedMemoryHeadroom = 8ull << 30;
#if defined(__linux__)
bool read_cgroup_memory_stat(const std::filesystem::path& path, uint64_t current,
@@ -324,6 +362,16 @@ bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64
}
}
const std::string path = pack_dir + "/experts.bin";
+ if (layout.native && !gguf_.empty() && !std::filesystem::exists(path)) {
+ // CS-T: no experts.bin - the model's GGUF shards, read in place
+ blobs_ = (int64_t) blob_count;
+ n_layers_ = n_layers;
+ n_expert_ = n_expert;
+ layer_offsets_ = std::move(layer_offsets);
+ layer_blob_bytes_ = std::move(layer_blob_bytes);
+ if (!open_gguf(err)) { close(); return false; }
+ return true;
+ }
#if defined(_WIN32)
// UTF-8 -> UTF-16: the pack may live under a path with non-ASCII characters, and `CreateFileA` would
@@ -412,17 +460,83 @@ bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64
void FileExpertSource::close() {
if (complement_arena_ != nullptr) {
- if (complement_pinned_)(void) DPCT_CHECK_ERROR(
+ if (complement_pinned_ && !complement_partial_)(void) DPCT_CHECK_ERROR(
sycl::free(complement_arena_, dpct::get_in_order_queue()));
- else std::free(complement_arena_);
+ else {
+ /*
+ DPCT1027: The call to cudaHostUnregister was replaced with 0
+ because SYCL currently does not support registering of existing host
+ memory for use by device. Use USM to allocate memory for use by host
+ and device.
+ */
+ if (complement_partial_)(void) 0;
+ if (complement_locked_ > 0)
+ strata::platform::unlock_resident((uint8_t*) complement_arena_ + complement_lock_off_, complement_locked_);
+ std::free(complement_arena_);
+ }
}
+ if (xstage_ != nullptr) {
+ if (xstage_pinned_)(void)
+ DPCT_CHECK_ERROR(sycl::free(xstage_, dpct::get_in_order_queue()));
+ else std::free(xstage_);
+ }
+ xstage_ = nullptr;
+ xstage_pinned_ = false;
+ xstage_cap_ = 0;
+ xstage_blob_ = 0;
+ override_.clear();
+ staged_.clear();
+ exchanges_ = 0;
+ file_reads_.store(0);
complement_arena_ = nullptr;
complement_host_ = nullptr;
complement_device_ = nullptr;
complement_bytes_ = 0;
complement_offsets_.clear();
complement_pinned_ = false;
+ complement_partial_ = false;
+ complement_pin_limit_ = 0;
+ complement_lock_off_ = 0;
complement_ready_ = false;
+ complement_locked_ = 0;
+ complement_lent_slots_ = 0;
+ if (!maps_.empty()) {
+ for (Map& m : maps_) {
+#if defined(_WIN32)
+ if (m.base != nullptr) UnmapViewOfFile((LPCVOID) m.base);
+ if (m.mapping != nullptr) CloseHandle((HANDLE) m.mapping);
+ if (m.file != nullptr) CloseHandle((HANDLE) m.file);
+#else
+ if (m.base != nullptr) munmap((void*) m.base, (size_t) m.bytes);
+ if (m.fd >= 0) ::close(m.fd);
+#endif
+ }
+ maps_.clear();
+ base_ = nullptr; // one of the views above
+ }
+ role_ptr_.clear();
+ role_bytes_.clear();
+ {
+ std::lock_guard<std::mutex> lk(stage_mu_);
+ stage_buf_.clear();
+ stage_key_.clear();
+ stage_epoch_.clear();
+ stage_used_.clear();
+ stage_busy_.clear();
+ stage_of_.clear();
+ stage_blob_ = 0;
+ stage_seq_ = 0;
+ epoch_ = 0;
+ last_layer_ = -1;
+ stage_grew_ = false;
+ }
+ ram_reads_.store(0);
+ warm_stamp_.reset();
+ warm_hits_.store(0);
+ warm_count_.store(0);
+ file_read_bytes_.store(0);
+ file_blob_bytes_.store(0);
+ file_us_.store(0);
#if defined(_WIN32)
if (base_ != nullptr) UnmapViewOfFile((LPCVOID) base_);
if (mapping_ != nullptr) CloseHandle((HANDLE) mapping_);
@@ -444,7 +558,430 @@ void FileExpertSource::close() {
reads_ = 0;
}
+
+bool ExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) {
+ const uint8_t* b = blob(layer, expert);
+ if (b == nullptr || dst == nullptr) return false;
+ std::memcpy(dst, b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(layer));
+ return true;
+}
+
+// ================================ CS-T: THE GGUF SHARDS IN PLACE ================================
+//
+// A native pack without experts.bin: every file native_experts.txt names is mapped (MapViewOfFile / mmap, no
+// flag - the same retention argument as experts.bin above), and an expert's blob [gate rows | up rows | down rows]
+// is three slices of three tensors, possibly in two shards (UD-Q4_K_XL's layer 11). Nothing is read at open; a
+// blob is assembled when it is asked for (`blob`, into a small pool of buffers) or copied where it is needed
+// (`copy_blob`: the RAM copy, the prompt path's pinned stager buffers).
+bool FileExpertSource::open_gguf(std::string& err) {
+ const auto& lay = strata::kernels::cpu::expert_layout();
+ if (!check_experts_gguf(gguf_, lay, err)) { err = "FileExpertSource: " + err; return false; }
+ const size_t cut = gguf_.find_last_of("/\\");
+ const std::string dir = cut == std::string::npos ? std::string() : gguf_.substr(0, cut + 1);
+ std::map<std::string, size_t> index;
+ role_ptr_.assign((size_t) (3 * n_layers_), nullptr);
+ role_bytes_.assign((size_t) (3 * n_layers_), 0);
+ for (int64_t l = 0; l < n_layers_; ++l) {
+ const auto& fm = lay.fmt[(size_t) l];
+ const uint64_t per[3] = {fm.up_off, fm.up_off, lay.bytes[(size_t) l] - fm.down_off};
+ for (int r = 0; r < 3; ++r) {
+ const size_t i = (size_t) (3 * l + r);
+ const std::string path = lay.gguf_file.size() > i && !lay.gguf_file[i].empty() ? dir + lay.gguf_file[i]
+ : gguf_;
+ auto it = index.find(path);
+ if (it == index.end()) {
+ Map m;
+#if defined(_WIN32)
+ const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
+ std::vector<wchar_t> wpath((size_t) (wide > 0 ? wide : 1));
+ if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide);
+ HANDLE f = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
+ FILE_ATTRIBUTE_NORMAL, nullptr);
+ LARGE_INTEGER sz{};
+ if (f == INVALID_HANDLE_VALUE || !GetFileSizeEx(f, &sz)) {
+ if (f != INVALID_HANDLE_VALUE) CloseHandle(f);
+ err = "FileExpertSource: cannot open " + path;
+ return false;
+ }
+ HANDLE mh = CreateFileMappingW(f, nullptr, PAGE_READONLY, 0, 0, nullptr);
+ void* view = mh != nullptr ? MapViewOfFile(mh, FILE_MAP_READ, 0, 0, 0) : nullptr;
+ if (view == nullptr) {
+ if (mh != nullptr) CloseHandle(mh);
+ CloseHandle(f);
+ err = "FileExpertSource: cannot map " + path;
+ return false;
+ }
+ m.file = f;
+ m.mapping = mh;
+ m.bytes = (uint64_t) sz.QuadPart;
+ m.base = (const uint8_t*) view;
+#else
+ const int fd = ::open(path.c_str(), O_RDONLY);
+ struct stat st{};
+ if (fd < 0 || fstat(fd, &st) != 0 || st.st_size <= 0) {
+ if (fd >= 0) ::close(fd);
+ err = "FileExpertSource: cannot open " + path;
+ return false;
+ }
+ void* view = mmap(nullptr, (size_t) st.st_size, PROT_READ, MAP_SHARED, fd, 0);
+ if (view == MAP_FAILED) { ::close(fd); err = "FileExpertSource: cannot map " + path; return false; }
+ m.fd = fd;
+ m.bytes = (uint64_t) st.st_size;
+ m.base = (const uint8_t*) view;
+#endif
+ maps_.push_back(m);
+ it = index.emplace(path, maps_.size() - 1).first;
+ }
+ const Map& m = maps_[it->second];
+ const uint64_t at = lay.gguf_off[i], bytes = per[r] * (uint64_t) n_expert_;
+ if (at > m.bytes || bytes > m.bytes - at) { // check_experts_gguf proved it; the mapping must agree
+ err = "FileExpertSource: an expert span runs past the end of " + path;
+ return false;
+ }
+ role_ptr_[i] = m.base + (size_t) at;
+ role_bytes_[i] = per[r];
+ }
+ }
+ base_ = maps_.front().base; // "opened"; mapped_blob answers nullptr in this mode
+ warm_stamp_.reset(new std::atomic<uint32_t>[(size_t) (n_layers_ * n_expert_)]());
+ for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b);
+ return true;
+}
+
+bool FileExpertSource::copy_from_files(int64_t layer, int64_t expert, uint8_t* dst) const {
+ if (dst == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false;
+ if (!role_ptr_.empty()) {
+ uint64_t at = 0;
+ for (int r = 0; r < 3; ++r) {
+ const size_t i = (size_t) (3 * layer + r);
+ const uint64_t per = role_bytes_[i];
+ std::memcpy(dst + at, role_ptr_[i] + (size_t) ((uint64_t) expert * per), (size_t) per);
+ at += per;
+ }
+ return true;
+ }
+ const uint8_t* b = mapped_blob(layer, expert);
+ if (b == nullptr) return false;
+ std::memcpy(dst, b, (size_t) layer_blob_bytes_[(size_t) layer]);
+ return true;
+}
+
+// A blob assembled from the three role slices. The buffer of a (layer, expert) is reused for another only once
+// its blob has not been asked for during `kStageAge` layers (begin_layer) or 256 assemblies, whichever comes
+// first, and never while it is being filled: the pool computes a layer's misses before it starts the next, and a
+// fill (the GPU cache at startup, an adaptive swap, a helper GPU) copies the blob right away.
+//
+// `claim_stage` finds or reserves the buffer of `key` (stage_mu_ held): true when the blob is already there (or
+// being filled by another thread - the caller then waits), false when the caller must fill buffer `v`.
+bool FileExpertSource::claim_stage(int64_t key, size_t& v, bool& fill) {
+ constexpr uint64_t kStageSeq = 256;
+ const uint64_t seq = ++stage_seq_;
+ auto it = stage_of_.find(key);
+ fill = false;
+ if (it != stage_of_.end()) {
+ v = it->second;
+ stage_epoch_[v] = epoch_;
+ stage_used_[v] = seq;
+ return true;
+ }
+ v = stage_buf_.size();
+ uint64_t oldest = std::numeric_limits<uint64_t>::max();
+ for (size_t i = 0; i < stage_buf_.size(); ++i)
+ if (!stage_busy_[i] && (stage_epoch_[i] + kStageAge <= epoch_ || stage_used_[i] + kStageSeq <= seq) &&
+ stage_used_[i] < oldest) {
+ oldest = stage_used_[i];
+ v = i;
+ }
+ if (v == stage_buf_.size()) {
+ stage_buf_.emplace_back(new (std::nothrow) uint8_t[(size_t) stage_blob_]);
+ if (!stage_buf_.back()) { stage_buf_.pop_back(); return false; }
+ stage_key_.push_back(-1);
+ stage_epoch_.push_back(0);
+ stage_used_.push_back(0);
+ stage_busy_.push_back(0);
+ if (stage_buf_.size() == 512 && !stage_grew_) {
+ stage_grew_ = true;
+ std::fprintf(stderr, "FileExpertSource: %zu blobs assembled from the GGUF are in use at once (%.2f GiB)\n",
+ stage_buf_.size(), (double) stage_buf_.size() * (double) stage_blob_ / 1073741824.0);
+ }
+ } else {
+ stage_of_.erase(stage_key_[v]);
+ }
+ stage_key_[v] = key;
+ stage_epoch_[v] = epoch_;
+ stage_used_[v] = seq;
+ stage_busy_[v] = 1;
+ stage_of_[key] = v;
+ fill = true;
+ return false;
+}
+
+// Fills buffer `v` (reserved by claim_stage) outside the lock, then publishes it.
+bool FileExpertSource::fill_stage(size_t v, int64_t layer, int64_t expert, uint8_t* dst) {
+ const auto t0 = std::chrono::steady_clock::now();
+ const bool ok = copy_from_files(layer, expert, dst);
+ const double us = std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count();
+ file_us_.fetch_add((uint64_t) us, std::memory_order_relaxed);
+ if (ok) {
+ file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
+ file_blob_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
+ }
+ {
+ std::lock_guard<std::mutex> lk(stage_mu_);
+ stage_busy_[v] = 0;
+ if (!ok) {
+ stage_of_.erase(stage_key_[v]);
+ stage_key_[v] = -1;
+ }
+ }
+ stage_cv_.notify_all();
+ return ok;
+}
+
+const uint8_t* FileExpertSource::staged_blob(int64_t layer, int64_t expert) {
+ const int64_t key = layer * n_expert_ + expert;
+ size_t v = 0;
+ bool fill = false;
+ uint8_t* dst = nullptr;
+ {
+ std::unique_lock<std::mutex> lk(stage_mu_);
+ const bool have = claim_stage(key, v, fill);
+ if (!have && !fill) return nullptr;
+ dst = stage_buf_[v].get();
+ if (have) {
+ // another thread (a prefetch, the adaptive tier) is filling it: wait for that
+ stage_cv_.wait(lk, [&] { return !stage_busy_[v] || stage_key_[v] != key; });
+ if (stage_key_[v] != key) return nullptr; // its fill failed
+ return dst;
+ }
+ }
+ return fill_stage(v, layer, expert, dst) ? dst : nullptr;
+}
+
+void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n) {
+ if (role_ptr_.empty() || n <= 0 || layer < 0 || layer >= n_layers_) return;
+ struct Fill { size_t v; int64_t e; uint8_t* dst; };
+ std::vector<Fill> todo;
+ {
+ std::lock_guard<std::mutex> lk(stage_mu_);
+ for (int64_t i = 0; i < n; ++i) {
+ const int64_t e = experts[i];
+ if (e < 0 || e >= n_expert_) continue;
+ const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e;
+ if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement)
+ continue; // in the RAM copy
+ if (!override_.empty() && override_[index] != nullptr) continue;
+ size_t v = 0;
+ bool fill = false;
+ if (!claim_stage(layer * n_expert_ + e, v, fill) && fill) {
+ todo.push_back({v, e, stage_buf_[v].get()});
+ if (warm_stamp_) {
+ const uint32_t s = warm_stamp_[index].load(std::memory_order_relaxed);
+ if (s != 0 && (uint64_t) s + 3 >= epoch_ + 1) warm_hits_.fetch_add(1, std::memory_order_relaxed);
+ }
+ }
+ }
+ }
+ if (todo.empty()) return;
+#if defined(_WIN32)
+ // One PrefetchVirtualMemory call for every slice about to be copied: the memory manager reads them in large
+ // requests, all queued at once, where the copies' page faults would read a few clusters each. The copies below
+ // then find the pages resident (or in flight). STRATA_FETCH_PVM=0 is the A/B arm.
+ {
+ using Pvm = BOOL(WINAPI*)(HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
+ static const Pvm pvm = [] {
+ const char* v = std::getenv("STRATA_FETCH_PVM");
+ if (v != nullptr && std::atoi(v) == 0) return (Pvm) nullptr;
+ return (Pvm) (void*) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "PrefetchVirtualMemory");
+ }();
+ if (pvm != nullptr) {
+ std::vector<WIN32_MEMORY_RANGE_ENTRY> ranges;
+ ranges.reserve(todo.size() * 3);
+ for (const Fill& f : todo)
+ for (int r = 0; r < 3; ++r) {
+ const size_t i = (size_t) (3 * layer + r);
+ ranges.push_back({(PVOID) (role_ptr_[i] + (size_t) ((uint64_t) f.e * role_bytes_[i])),
+ (SIZE_T) role_bytes_[i]});
+ }
+ (void) pvm(GetCurrentProcess(), (ULONG_PTR) ranges.size(), ranges.data(), 0);
+ }
+ }
+#endif
+ // the page faults of a mapped read are one outstanding request each: several threads keep the SSD's queue full
+ std::atomic<size_t> next{0};
+ auto work = [&] {
+ for (size_t i; (i = next.fetch_add(1)) < todo.size();)
+ (void) fill_stage(todo[i].v, layer, todo[i].e, todo[i].dst);
+ };
+ const size_t nt = std::min<size_t>(todo.size(), (size_t) fetch_threads_);
+ std::vector<std::thread> th;
+ for (size_t t = 1; t < nt; ++t) th.emplace_back(work);
+ work();
+ for (auto& t : th) t.join();
+}
+
+
+void FileExpertSource::warm(int64_t layer, const int64_t* experts, int64_t n) {
+ if (role_ptr_.empty() || n <= 0 || layer < 0 || layer >= n_layers_) return;
+ uint32_t stamp;
+ {
+ std::lock_guard<std::mutex> lk(stage_mu_);
+ stamp = (uint32_t) epoch_ + 1;
+ }
+#if defined(_WIN32)
+ using Pvm = BOOL(WINAPI*)(HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
+ static const Pvm pvm = (Pvm) (void*) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "PrefetchVirtualMemory");
+ std::vector<WIN32_MEMORY_RANGE_ENTRY> ranges;
+#endif
+ for (int64_t j = 0; j < n; ++j) {
+ const int64_t e = experts[j];
+ if (e < 0 || e >= n_expert_) continue;
+ const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e;
+ if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement)
+ continue; // in the RAM copy
+ if (warm_stamp_) warm_stamp_[index].store(stamp, std::memory_order_relaxed);
+ warm_count_.fetch_add(1, std::memory_order_relaxed);
+ for (int r = 0; r < 3; ++r) {
+ const size_t i = (size_t) (3 * layer + r);
+ const uint8_t* p = role_ptr_[i] + (size_t) ((uint64_t) e * role_bytes_[i]);
+#if defined(_WIN32)
+ ranges.push_back({(PVOID) p, (SIZE_T) role_bytes_[i]});
+#else
+ const uintptr_t pg = 4096, a = (uintptr_t) p & ~(pg - 1);
+ (void) madvise((void*) a, (size_t) ((uintptr_t) p + role_bytes_[i] - a), MADV_WILLNEED);
+#endif
+ }
+ }
+#if defined(_WIN32)
+ if (pvm != nullptr && !ranges.empty()) (void) pvm(GetCurrentProcess(), (ULONG_PTR) ranges.size(), ranges.data(), 0);
+#endif
+}
+
+RouterLookahead::~RouterLookahead() {
+ {
+ std::lock_guard<std::mutex> lk(mu_);
+ quit_ = true;
+ }
+ cv_.notify_all();
+ if (thread_.joinable()) thread_.join();
+}
+
+bool RouterLookahead::start(std::vector<std::vector<uint16_t>> routers, int64_t n_embd, int64_t n_expert, int k,
+ ExpertSource* src, std::string& err) {
+ if (src == nullptr || !src->warms()) { err = "RouterLookahead: the expert source does not warm"; return false; }
+ if (n_embd % 8 != 0) { err = "RouterLookahead: n_embd is not a multiple of 8"; return false; }
+ for (const auto& r : routers)
+ if (r.size() != (size_t) (n_embd * n_expert)) { err = "RouterLookahead: a router of another shape"; return false; }
+ routers_ = std::move(routers);
+ n_embd_ = n_embd;
+ n_expert_ = n_expert;
+ k_ = k < 1 ? 1 : k > (int) n_expert ? (int) n_expert : k;
+ src_ = src;
+ x_.assign((size_t) (8 * n_embd), 0.f);
+ thread_ = std::thread([this] { run(); });
+ return true;
+}
+
+void RouterLookahead::submit(int64_t layer, const float* x, int64_t n_tok, const int32_t* host_res) {
+ if (layer + 1 >= (int64_t) routers_.size() || n_tok <= 0 || x == nullptr) return;
+ {
+ std::lock_guard<std::mutex> lk(mu_);
+ if (busy_ || pending_) { skipped_.fetch_add(1, std::memory_order_relaxed); return; }
+ n_tok_ = std::min<int64_t>(n_tok, 8);
+ std::memcpy(x_.data(), x, (size_t) (n_tok_ * n_embd_) * sizeof(float));
+ layer_ = layer + 1;
+ host_res_ = host_res;
+ pending_ = true;
+ }
+ cv_.notify_one();
+}
+
+void RouterLookahead::run() {
+ std::vector<float> logits((size_t) (8 * n_expert_));
+ std::vector<int32_t> order((size_t) n_expert_);
+ std::vector<int64_t> want;
+ for (;;) {
+ int64_t layer, nt;
+ const int32_t* host_res;
+ {
+ std::unique_lock<std::mutex> lk(mu_);
+ cv_.wait(lk, [&] { return quit_ || pending_; });
+ if (quit_) return;
+ pending_ = false;
+ busy_ = true;
+ layer = layer_;
+ nt = n_tok_;
+ host_res = host_res_;
+ }
+ const auto t0 = std::chrono::steady_clock::now();
+ want.clear();
+ strata::kernels::cpu::bf16_rows_dot_multi(routers_[(size_t) layer].data(), (int) n_expert_, (int) n_embd_,
+ x_.data(), (int) nt, logits.data());
+ for (int64_t t = 0; t < nt; ++t) {
+ const float* lt = logits.data() + (size_t) (t * n_expert_);
+ for (int64_t e = 0; e < n_expert_; ++e) order[(size_t) e] = (int32_t) e;
+ std::partial_sort(order.begin(), order.begin() + k_, order.end(),
+ [&](int32_t a, int32_t b) { return lt[(size_t) a] > lt[(size_t) b]; });
+ for (int j = 0; j < k_; ++j) {
+ const int64_t e = order[(size_t) j];
+ if (host_res != nullptr && host_res[(size_t) (layer * n_expert_ + e)] >= 0) continue; // on the GPU
+ if (std::find(want.begin(), want.end(), e) == want.end()) want.push_back(e);
+ }
+ }
+ src_->warm(layer, want.data(), (int64_t) want.size());
+ predicted_.fetch_add((int64_t) want.size(), std::memory_order_relaxed);
+ busy_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
+ std::memory_order_relaxed);
+ {
+ std::lock_guard<std::mutex> lk(mu_);
+ busy_ = false;
+ }
+ }
+}
+
+void FileExpertSource::begin_layer(int64_t layer, const int32_t* ids, int64_t k) {
+ (void) ids;
+ (void) k;
+ if (role_ptr_.empty()) return;
+ std::lock_guard<std::mutex> lk(stage_mu_);
+ if (layer != last_layer_) {
+ ++epoch_;
+ last_layer_ = layer;
+ }
+}
+
+bool FileExpertSource::transient(int64_t layer, int64_t expert) const {
+ if (role_ptr_.empty() || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false;
+ const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
+ if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement)
+ return false;
+ return override_.empty() || override_[index] == nullptr;
+}
+
+bool FileExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) {
+ if (base_ == nullptr || dst == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_)
+ return false;
+ const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
+ const uint64_t bytes = layer_blob_bytes_[(size_t) layer];
+ if (complement_ready_) {
+ const uint8_t* held =
+ detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr);
+ if (held == nullptr && !override_.empty()) held = override_[index];
+ if (held != nullptr) {
+ std::memcpy(dst, held, (size_t) bytes);
+ return true;
+ }
+ }
+ const auto t0 = std::chrono::steady_clock::now();
+ if (!copy_from_files(layer, expert, dst)) return false;
+ file_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
+ std::memory_order_relaxed);
+ file_read_bytes_.fetch_add(bytes, std::memory_order_relaxed);
+ return true;
+}
+
const uint8_t* FileExpertSource::mapped_blob(int64_t layer, int64_t expert) const {
+ if (!role_ptr_.empty()) return nullptr; // the GGUF in place: no contiguous blob in any file
if (base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return nullptr;
const size_t i = (size_t) layer;
if (i >= layer_offsets_.size() || i >= layer_blob_bytes_.size()) return nullptr;
@@ -460,7 +997,9 @@ const uint8_t* FileExpertSource::mapped_blob(int64_t layer, int64_t expert) cons
bool FileExpertSource::pin_cache_complement(
const ExpertCache &cache, std::string &err, bool pin,
- const std::vector<std::pair<int32_t, int32_t>> &additional_gpu_pairs) try {
+ const std::vector<std::pair<int32_t, int32_t>> &additional_gpu_pairs,
+ int64_t lend_from_slot, uint64_t headroom_bytes, uint64_t budget_bytes,
+ const std::vector<std::pair<int32_t, int32_t>> *rank) try {
err.clear();
if (base_ == nullptr) { err = "FileExpertSource: open the mapped experts before pinning a complement"; return false; }
if (complement_ready_) { err = "FileExpertSource: the cache complement is already pinned"; return false; }
@@ -495,186 +1034,383 @@ bool FileExpertSource::pin_cache_complement(
return false;
}
+ // The GPU cache's experts, and the bytes each slot's expert takes here (for the lend region below).
+ const int64_t n_slots = cache.slots();
std::vector<std::pair<int32_t, int32_t>> primary_gpu_pairs;
+ std::vector<int32_t> pair_slot;
+ std::vector<uint64_t> slot_bytes((size_t) std::max<int64_t>(n_slots, 0), 0);
primary_gpu_pairs.reserve((size_t) cache.resident());
+ pair_slot.reserve((size_t) cache.resident());
for (int64_t layer = 0; layer < n_layers_; ++layer) {
for (int64_t expert = 0; expert < n_expert_; ++expert) {
- if (cache.slot_of(layer, expert) != kNotResident)
- primary_gpu_pairs.emplace_back((int32_t) layer, (int32_t) expert);
+ const int32_t slot = cache.slot_of(layer, expert);
+ if (slot == kNotResident) continue;
+ primary_gpu_pairs.emplace_back((int32_t) layer, (int32_t) expert);
+ pair_slot.push_back(slot);
+ if (slot >= 0 && slot < n_slots) slot_bytes[(size_t) slot] = layer_blob_bytes_[(size_t) layer];
}
}
std::vector<uint64_t> offsets;
uint64_t bytes = 0;
if (!detail::make_cache_complement_plan(n_layers_, n_expert_, layer_blob_bytes_, primary_gpu_pairs,
additional_gpu_pairs, offsets, bytes, err)) return false;
+ if (budget_bytes > 0) {
+ // CS-T: a RAM budget. The complement's experts in `rank` order (the expert profile, hottest first) while
+ // they fit, the rest left on the mapped files; clamped to what the RAM has room for.
+ uint64_t physical = 0;
+ if (!available_memory_bytes(physical)) {
+ err = "FileExpertSource: cannot determine available RAM for --resident-budget-gib";
+ return false;
+ }
+ const uint64_t room = physical > headroom_bytes ? physical - headroom_bytes : 0;
+ if (budget_bytes > room) {
+ std::fprintf(stderr, "FileExpertSource: --resident-budget-gib %.2f is more than the RAM has room for "
+ "(%.2f GiB available minus %.0f GiB headroom): %.2f GiB\n",
+ (double) budget_bytes / 1073741824.0, (double) physical / 1073741824.0,
+ (double) headroom_bytes / 1073741824.0, (double) room / 1073741824.0);
+ budget_bytes = room;
+ }
+ std::vector<uint64_t> ranked(offsets.size(), kNoComplement);
+ uint64_t at = 0;
+ int64_t held = 0;
+ if (rank != nullptr)
+ for (const auto& pr : *rank) {
+ if (pr.first < 0 || pr.second < 0 || pr.first >= n_layers_ || pr.second >= n_expert_) continue;
+ const size_t i = (size_t) pr.first * (size_t) n_expert_ + (size_t) pr.second;
+ if (offsets[i] == kNoComplement || ranked[i] != kNoComplement) continue; // on a GPU, or twice
+ const uint64_t b = layer_blob_bytes_[(size_t) pr.first];
+ if (b > budget_bytes - at) continue;
+ ranked[i] = at;
+ at += b;
+ ++held;
+ }
+ std::fprintf(stderr, "FileExpertSource: RAM budget %.2f GiB: %lld of the %.2f GiB of experts the GPU cache does "
+ "not hold, by profile rank; the rest are read from the files\n",
+ (double) budget_bytes / 1073741824.0, (long long) held, (double) bytes / 1073741824.0);
+ offsets.swap(ranked);
+ bytes = at;
+ lend_from_slot = -1;
+ }
- if (bytes > 0) {
+ const bool lend = lend_from_slot >= 0 && lend_from_slot < n_slots && additional_gpu_pairs.empty();
+ uint64_t budget = std::numeric_limits<uint64_t>::max();
+ if (bytes > 0 || lend) {
uint64_t physical = 0;
if (!available_memory_bytes(physical)) {
err = "FileExpertSource: cannot determine available RAM for the resident-memory safety check";
return false;
}
- if (physical <= kPinnedMemoryHeadroom || bytes > physical - kPinnedMemoryHeadroom) {
- char message[256];
+ budget = physical > headroom_bytes ? physical - headroom_bytes : 0;
+ if (bytes > budget) {
+ char message[320];
std::snprintf(message, sizeof message,
- "FileExpertSource: resident complement %.2f GiB exceeds available RAM minus the 8 GiB safety headroom",
- (double) bytes / 1073741824.0);
+ "FileExpertSource: resident complement %.2f GiB exceeds available RAM (%.2f GiB) minus the "
+ "%.0f GiB safety headroom",
+ (double) bytes / 1073741824.0, (double) physical / 1073741824.0,
+ (double) headroom_bytes / 1073741824.0);
err = message;
return false;
}
}
+ // The prompt path's lend region: its slots' experts are streamed from here during a prompt and copied back into
+ // their slots after it, so the ones that fit are kept here too (from the last slot down: a short prompt lends
+ // only the last few). The rest keep the mapped-file fallback.
+ int64_t keep_from = n_slots;
+ if (lend) {
+ keep_from = detail::choose_resident_keep_from(slot_bytes, bytes, budget, lend_from_slot);
+ if (keep_from < 0) keep_from = n_slots;
+ if (keep_from < n_slots) {
+ std::vector<std::pair<int32_t, int32_t>> core;
+ core.reserve(primary_gpu_pairs.size());
+ for (size_t i = 0; i < primary_gpu_pairs.size(); ++i)
+ if (pair_slot[i] < keep_from) core.push_back(primary_gpu_pairs[i]);
+ if (!detail::make_cache_complement_plan(n_layers_, n_expert_, layer_blob_bytes_, core,
+ additional_gpu_pairs, offsets, bytes, err)) return false;
+ }
+ }
void* arena = nullptr;
const uint8_t* host = nullptr;
const uint8_t* device = nullptr;
+ bool pinned_ok = false;
+ uint64_t locked = 0;
+ uint64_t partial_pin = 0; ///< CS-T: a registered prefix of a locked arena
+ uint64_t lock_off = 0; ///< where the working-set lock starts (after the registered prefix)
+ std::string note;
+ auto release = [&]() {
+ try {
+ if (arena == nullptr) return;
+ if (pinned_ok)(void)
+ DPCT_CHECK_ERROR(sycl::free(arena, dpct::get_in_order_queue()));
+ else {
+ /*
+ DPCT1027: The call to cudaHostUnregister was replaced with 0
+ because SYCL currently does not support registering of existing host
+ memory for use by device. Use USM to allocate memory for use by host
+ and device.
+ */
+ if (partial_pin > 0)(void) 0;
+ if (locked > 0) strata::platform::unlock_resident((uint8_t*) arena + lock_off, locked);
+ std::free(arena);
+ }
+ arena = nullptr;
+ }
+ catch (sycl::exception const &exc) {
+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__
+ << ", line:" << __LINE__ << std::endl;
+ std::exit(1);
+ }
+ };
if (bytes > 0) {
std::fprintf(stderr, "FileExpertSource: allocating %.2f GiB %s cache complement\n",
- (double) bytes / 1073741824.0, pin ? "mapped pinned" : "pageable resident");
+ (double) bytes / 1073741824.0, pin ? "page-locked" : "pageable resident");
std::fflush(stderr);
if (pin) {
const dpct::err0 allocated = DPCT_CHECK_ERROR(
arena = (void *)sycl::malloc_host((size_t)bytes,
dpct::get_in_order_queue()));
- /*
- DPCT1000: Error handling if-stmt was detected but could not be
- rewritten.
- */
- if (allocated != 0) {
- /*
- DPCT1001: The statement could not be removed.
- */
- err = std::string("FileExpertSource: mapped pinned complement "
- "allocation failed: ") +
- /*
- 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.
- */
- dpct::get_error_string_dummy(allocated);
- std::fprintf(stderr, "%s\n", err.c_str());
- std::fflush(stderr);
+ if (allocated == 0) {
+ void* alias = nullptr;
+ const dpct::err0 aliased =
+ DPCT_CHECK_ERROR(alias = (void *)arena);
+ if (aliased == 0 && alias != nullptr) {
+ device = (const uint8_t*) alias;
+ pinned_ok = true;
+ note = "page-locked and mapped";
+ } else {
+ /*
+ 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.
+ */
+ note = std::string("no device alias (") +
+ dpct::get_error_string_dummy(aliased) + ")";
+ /*
+ 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;
+ (void)DPCT_CHECK_ERROR(
+ sycl::free(arena, dpct::get_in_order_queue()));
+ arena = nullptr;
+ }
+ } else {
+ // Refused (the driver's page-locked limit): the same bytes in ordinary memory, locked in the working
+ // set instead, as the arena does - resident either way, only copied by the CPU instead of by DMA.
/*
- 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.
+ 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.
*/
- (void)0;
- return false;
- }
- host = (const uint8_t*) arena;
- void* alias = nullptr;
- const dpct::err0 aliased = DPCT_CHECK_ERROR(alias = (void *)arena);
- if (aliased != 0 || alias == nullptr) {
- err = std::string("FileExpertSource: mapped pinned complement "
- "device alias failed: ") +
- /*
- 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.
- */
- dpct::get_error_string_dummy(aliased);
- std::fprintf(stderr, "%s\n", err.c_str());
- std::fflush(stderr);
+ note = std::string("page-locking refused (") +
+ dpct::get_error_string_dummy(allocated) + ")";
/*
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;
- (void)DPCT_CHECK_ERROR(
- sycl::free(arena, dpct::get_in_order_queue()));
- return false;
+ arena = nullptr;
}
- device = (const uint8_t*) alias;
- } else {
+ }
+ if (arena == nullptr) {
arena = std::malloc((size_t) bytes);
if (arena == nullptr) {
err = "FileExpertSource: pageable resident complement allocation failed";
return false;
}
- host = (const uint8_t*) arena;
+ if (pin) {
+ // CS-T, a RAM budget: its bytes are in profile order, hottest first, so the driver is asked to
+ // register the largest prefix it takes (from the cap down in 2 GiB steps). Those experts can be
+ // read by the GPU over PCIe (--pcie-frac) and copied by DMA; only the rest is locked in the working
+ // set (the registered prefix is page-locked by the driver already - locking it twice made the next
+ // device allocation fail).
+ // opt-in (STRATA_PARTIAL_PIN=1): on the RTX 5070 PC the GPU's PCIe share of the misses measured no
+ // faster than the CPU computing them (7.30 / 7.44 tok/s with 24 / 16 GiB registered against 7.05-7.74
+ // unpinned at a 40 GiB budget), and registering adds startup time and driver memory pressure
+ static const bool partial_on = [] {
+ const char* v = std::getenv("STRATA_PARTIAL_PIN");
+ return v != nullptr && std::atoi(v) != 0;
+ }();
+ // at most STRATA_PARTIAL_PIN_GIB (default 24): registering 30 GiB of a 40 GiB arena left the driver
+ // unable to page-lock the prompt path's small buffers afterwards (RTX 5070, WDDM)
+ static const uint64_t pin_cap = [] {
+ const char* v = std::getenv("STRATA_PARTIAL_PIN_GIB");
+ return (uint64_t) ((v != nullptr && std::atof(v) > 0 ? std::atof(v) : 24.0) * 1073741824.0);
+ }();
+ if (budget_bytes > 0 && partial_on) {
+ const uint64_t step = 2ull << 30;
+ for (uint64_t want = std::min(bytes, pin_cap); want >= step; want = want > step ? want - step : 0) {
+ // cut at an expert boundary: a blob that started inside the registered range and ran past it
+ // would be taken as page-locked by a cudaMemcpyAsync and refused ("adaptive refill failed")
+ uint64_t w = want;
+ for (size_t i = 0; i < offsets.size(); ++i) {
+ if (offsets[i] == kNoComplement) continue;
+ const uint64_t b = layer_blob_bytes_[i / (size_t) n_expert_];
+ if (offsets[i] < want && offsets[i] + b > want) { w = offsets[i]; break; }
+ }
+ if (w == 0) break;
+ /*
+ DPCT1027: The call to cudaHostRegister was replaced
+ with 0 because SYCL currently does not support
+ registering of existing host memory for use by device.
+ Use USM to allocate memory for use by host and device.
+ */
+ if (0 == 0) {
+ void* alias = nullptr;
+ if (DPCT_CHECK_ERROR(alias = (void *)arena) == 0 &&
+ alias != nullptr) {
+ device = (const uint8_t*) alias;
+ partial_pin = w;
+ } else {
+ /*
+ 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;
+ /*
+ DPCT1027: The call to cudaHostUnregister was
+ replaced with 0 because SYCL currently does not
+ support registering of existing host memory for
+ use by device. Use USM to allocate memory for
+ use by host and device.
+ */
+ (void)0;
+ }
+ break;
+ }
+ /*
+ 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;
+ if (want <= step) break;
+ }
+ char msg[160];
+ std::snprintf(msg, sizeof msg, "%.2f GiB of it registered for the GPU (the hottest)",
+ (double) partial_pin / 1073741824.0);
+ note += std::string("; ") + msg;
+ }
+ lock_off = partial_pin;
+ const strata::platform::LockResult lr =
+ strata::platform::lock_resident((uint8_t*) arena + lock_off, bytes - lock_off);
+ locked = lr.locked_bytes;
+ note += (note.empty() ? "" : "; ") + lr.note;
+ }
}
+ host = (const uint8_t*) arena;
}
- uint64_t copied = 0;
- for (int64_t layer = 0; layer < n_layers_; ++layer) {
- const uint64_t blob_bytes = layer_blob_bytes_[(size_t) layer];
- for (int64_t expert = 0; expert < n_expert_; ++expert) {
- const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
- const uint64_t offset = offsets[index];
- if (offset == kNoComplement) continue;
- const uint8_t* source = mapped_blob(layer, expert);
- if (source == nullptr || offset > bytes || blob_bytes > bytes - offset) {
- err = "FileExpertSource: invalid blob bounds while building the cache complement";
- if (arena != nullptr) {
- if (pin)(void) DPCT_CHECK_ERROR(
- sycl::free(arena, dpct::get_in_order_queue()));
- else std::free(arena);
+ // Copied layer by layer on a few threads: the page faults of the mapped file are the cost, and they overlap.
+#if !defined(_WIN32)
+ const long page_size = sysconf(_SC_PAGESIZE);
+ if (page_size <= 0) {
+ err = "FileExpertSource: cannot determine page size for mapped-page release";
+ release();
+ return false;
+ }
+#endif
+ std::atomic<int64_t> next_layer{0}, layers_done{0};
+ std::atomic<uint64_t> copied{0};
+ std::atomic<bool> failed{false};
+ std::mutex fail_mu;
+ std::string fail_msg;
+ auto fail = [&](const std::string& m) {
+ std::lock_guard<std::mutex> lock(fail_mu);
+ if (fail_msg.empty()) fail_msg = m;
+ failed.store(true);
+ };
+ auto worker = [&]() {
+ for (;;) {
+ const int64_t layer = next_layer.fetch_add(1);
+ if (layer >= n_layers_ || failed.load()) return;
+ const uint64_t blob_bytes = layer_blob_bytes_[(size_t) layer];
+ for (int64_t expert = 0; expert < n_expert_; ++expert) {
+ const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
+ const uint64_t offset = offsets[index];
+ if (offset == kNoComplement) continue;
+ if (offset > bytes || blob_bytes > bytes - offset ||
+ !copy_from_files(layer, expert, (uint8_t*) host + (size_t) offset)) {
+ fail("FileExpertSource: invalid blob bounds while building the cache complement");
+ return;
}
- return false;
+ copied.fetch_add(blob_bytes);
}
- std::memcpy((uint8_t*) host + (size_t) offset, source, (size_t) blob_bytes);
- copied += blob_bytes;
- }
#if !defined(_WIN32)
- const uint64_t layer_offset = layer_offsets_[(size_t) layer];
- const uint64_t layer_bytes = blob_bytes * (uint64_t) n_expert_;
- const uint64_t layer_end = layer_offset + layer_bytes;
- const long page_bytes = sysconf(_SC_PAGESIZE);
- if (page_bytes <= 0) {
- err = "FileExpertSource: cannot determine page size for mapped-page release";
- if (arena != nullptr) {
- if (pin)(void) DPCT_CHECK_ERROR(
- sycl::free(arena, dpct::get_in_order_queue()));
- else std::free(arena);
+ if (role_ptr_.empty()) { // experts.bin; the GGUF in place leaves its pages to the OS
+ const uint64_t layer_offset = layer_offsets_[(size_t) layer];
+ const uint64_t layer_bytes = blob_bytes * (uint64_t) n_expert_;
+ const uint64_t layer_end = layer_offset + layer_bytes;
+ const uint64_t page = (uint64_t) page_size;
+ const uint64_t advice_start = layer_offset - layer_offset % page;
+ const uint64_t end_remainder = layer_end % page;
+ const uint64_t extra = end_remainder == 0 ? 0 : page - end_remainder;
+ const uint64_t advice_end = extra > mapped_bytes_ - layer_end ? mapped_bytes_ : layer_end + extra;
+ if (advice_end > advice_start &&
+ madvise((void*) (base_ + (size_t) advice_start), (size_t) (advice_end - advice_start), MADV_DONTNEED) != 0) {
+ fail("FileExpertSource: madvise could not release mapped expert layer " + std::to_string(layer));
+ return;
}
- return false;
- }
- const uint64_t page = (uint64_t) page_bytes;
- const uint64_t advice_start = layer_offset - layer_offset % page;
- const uint64_t end_remainder = layer_end % page;
- const uint64_t extra = end_remainder == 0 ? 0 : page - end_remainder;
- const uint64_t advice_end = extra > mapped_bytes_ - layer_end ? mapped_bytes_ : layer_end + extra;
- if (advice_end > advice_start &&
- madvise((void*) (base_ + (size_t) advice_start), (size_t) (advice_end - advice_start), MADV_DONTNEED) != 0) {
- err = "FileExpertSource: madvise could not release mapped expert layer " + std::to_string(layer);
- if (arena != nullptr) {
- if (pin)(void) DPCT_CHECK_ERROR(
- sycl::free(arena, dpct::get_in_order_queue()));
- else std::free(arena);
+ if (posix_fadvise(fd_, (off_t) layer_offset, (off_t) layer_bytes, POSIX_FADV_DONTNEED) != 0) {
+ fail("FileExpertSource: posix_fadvise could not release expert layer " + std::to_string(layer));
+ return;
}
- return false;
- }
- const int advice = posix_fadvise(fd_, (off_t) layer_offset, (off_t) layer_bytes, POSIX_FADV_DONTNEED);
- if (advice != 0) {
- err = "FileExpertSource: posix_fadvise could not release expert layer " + std::to_string(layer);
- if (arena != nullptr) {
- if (pin)(void) DPCT_CHECK_ERROR(
- sycl::free(arena, dpct::get_in_order_queue()));
- else std::free(arena);
}
- return false;
- }
#endif
- if ((layer + 1) % 8 == 0 || layer + 1 == n_layers_) {
- std::fprintf(stderr, "FileExpertSource: copied cache complement through layer %lld/%lld (%.2f GiB)\n",
- (long long) (layer + 1), (long long) n_layers_, (double) copied / 1073741824.0);
- std::fflush(stderr);
+ const int64_t done = layers_done.fetch_add(1) + 1;
+ if (done % 8 == 0 || done == n_layers_)
+ std::fprintf(stderr, "FileExpertSource: copied cache complement through layer %lld/%lld (%.2f GiB)\n",
+ (long long) done, (long long) n_layers_, (double) copied.load() / 1073741824.0);
}
+ };
+ {
+ const int threads = (int) std::max<int64_t>(1, std::min<int64_t>(6, n_layers_));
+ std::vector<std::thread> pool;
+ for (int i = 1; i < threads; ++i) pool.emplace_back(worker);
+ worker();
+ for (auto& t : pool) t.join();
}
+ std::fflush(stderr);
+ if (failed.load()) {
+ err = fail_msg;
+ release();
+ return false;
+ }
+#if defined(_WIN32)
+ // The mapped pages this process touched (the GPU cache's fill and this copy) leave its working set for the
+ // standby list: VirtualUnlock on pages that are not locked does exactly that (it then reports ERROR_NOT_LOCKED).
+ if (maps_.empty()) (void) VirtualUnlock((LPVOID) base_, (SIZE_T) mapped_bytes_);
+ for (const Map& m : maps_) (void) VirtualUnlock((LPVOID) m.base, (SIZE_T) m.bytes);
+#endif
complement_arena_ = arena;
complement_host_ = host;
complement_device_ = device;
complement_bytes_ = bytes;
complement_offsets_ = std::move(offsets);
- complement_pinned_ = pin && bytes > 0;
+ complement_pinned_ = (pinned_ok || partial_pin > 0) && bytes > 0;
+ complement_pin_limit_ = pinned_ok ? bytes : partial_pin;
+ complement_partial_ = !pinned_ok && partial_pin > 0;
+ complement_locked_ = locked;
+ complement_lock_off_ = lock_off;
+ complement_lent_slots_ = lend ? n_slots - keep_from : 0;
complement_ready_ = true;
- std::fprintf(stderr, "FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB\n",
- complement_pinned_ ? "mapped pinned" : "pageable resident",
- (double) resident_bytes() / 1073741824.0, (double) pinned_bytes() / 1073741824.0);
+ std::fprintf(stderr, "FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB%s%s\n",
+ complement_pinned_ ? "mapped pinned" : pin ? "locked resident" : "pageable resident",
+ (double) resident_bytes() / 1073741824.0, (double) pinned_bytes() / 1073741824.0,
+ note.empty() ? "" : "; ", note.c_str());
+ if (lend)
+ std::fprintf(stderr, "FileExpertSource: %lld of the prompt path's %lld lendable slots keep their experts in RAM "
+ "too%s\n", (long long) complement_lent_slots_, (long long) (n_slots - lend_from_slot),
+ complement_lent_slots_ < n_slots - lend_from_slot
+ ? " (the others are read from the file when lent: not enough RAM for them)" : "");
if (!additional_gpu_pairs.empty()) {
std::fprintf(stderr, "FileExpertSource: %zu verified additional-GPU experts remain on the mmap fallback\n",
additional_gpu_pairs.size());
@@ -688,13 +1424,119 @@ catch (sycl::exception const &exc) {
std::exit(1);
}
+bool FileExpertSource::has_resident(int64_t layer, int64_t expert) const {
+ if (!complement_ready_ || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false;
+ const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
+ return index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement;
+}
+
+bool FileExpertSource::reserve_exchanges(int64_t n, std::string &err) try {
+ err.clear();
+ if (n <= xstage_cap_) return true;
+ if (!staged_.empty()) { err = "FileExpertSource: exchange buffers are in use"; return false; }
+ uint64_t blob = 0;
+ for (const uint64_t b : layer_blob_bytes_) blob = std::max(blob, b);
+ if (blob == 0 || n <= 0) { err = "FileExpertSource: no expert geometry for the exchange buffers"; return false; }
+ if (xstage_ != nullptr) {
+ if (xstage_pinned_)(void)
+ DPCT_CHECK_ERROR(sycl::free(xstage_, dpct::get_in_order_queue()));
+ else std::free(xstage_);
+ xstage_ = nullptr;
+ xstage_cap_ = 0;
+ }
+ const size_t total = (size_t) n * (size_t) blob;
+ void* p = nullptr;
+ /*
+ DPCT1048: The original value cudaHostAllocDefault is not meaningful in
+ the migrated code and was removed or replaced with 0. You may need to check
+ the migrated code.
+ */
+ if (DPCT_CHECK_ERROR(p = (void *)sycl::malloc_host(
+ total, dpct::get_in_order_queue())) == 0 &&
+ p != nullptr) {
+ xstage_pinned_ = true;
+ } else {
+ /*
+ 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;
+ p = std::malloc(total);
+ xstage_pinned_ = false;
+ if (p == nullptr) { err = "FileExpertSource: cannot allocate the exchange buffers"; return false; }
+ }
+ xstage_ = (uint8_t*) p;
+ xstage_cap_ = n;
+ xstage_blob_ = blob;
+ return true;
+}
+catch (sycl::exception const &exc) {
+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__
+ << ", line:" << __LINE__ << std::endl;
+ std::exit(1);
+}
+
+uint8_t* FileExpertSource::exchange_buffer(int64_t q) const {
+ if (xstage_ == nullptr || q < 0 || q >= xstage_cap_) return nullptr;
+ return xstage_ + (size_t) q * (size_t) xstage_blob_;
+}
+
+bool FileExpertSource::stage_exchange(int64_t layer, int64_t in, int64_t out, int64_t q) {
+ if (!has_resident(layer, in) || has_resident(layer, out) || exchange_buffer(q) == nullptr) return false;
+ const size_t i_in = (size_t) layer * (size_t) n_expert_ + (size_t) in;
+ const size_t i_out = (size_t) layer * (size_t) n_expert_ + (size_t) out;
+ if (override_.empty()) override_.assign((size_t) blobs_, nullptr);
+ if (override_[i_out] != nullptr) return false;
+ for (const Exchange& x : staged_)
+ if (x.in == i_in || x.q == q) return false;
+ override_[i_out] = exchange_buffer(q);
+ staged_.push_back({i_in, i_out, q, layer_blob_bytes_[(size_t) layer]});
+ return true;
+}
+
+int64_t FileExpertSource::commit_exchanges() {
+ int64_t n = 0;
+ for (const Exchange& x : staged_) {
+ const uint8_t* src = override_[x.out];
+ const uint64_t at = complement_offsets_[x.in];
+ if (src != nullptr && at != kNoComplement && at <= complement_bytes_ && x.bytes <= complement_bytes_ - at &&
+ complement_host_ != nullptr) {
+ std::memcpy((uint8_t*) complement_host_ + (size_t) at, src, (size_t) x.bytes);
+ if (detail::exchange_cache_complement(complement_offsets_, x.in, x.out)) ++n;
+ }
+ override_[x.out] = nullptr;
+ }
+ staged_.clear();
+ exchanges_ += n;
+ return n;
+}
+
const uint8_t* FileExpertSource::blob(int64_t layer, int64_t expert) {
if (base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return nullptr;
const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
- const uint8_t* mapped_fallback = mapped_blob(layer, expert);
- const uint8_t* result = complement_ready_
- ? detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, mapped_fallback)
- : mapped_fallback;
+ const uint8_t* result = nullptr;
+ bool from_files = true;
+ if (complement_ready_) {
+ result = detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr);
+ if (result != nullptr) {
+ ram_reads_.fetch_add(1, std::memory_order_relaxed);
+ from_files = false;
+ } else if (!override_.empty() && override_[index] != nullptr) {
+ result = override_[index];
+ from_files = false;
+ }
+ }
+ if (from_files) {
+ if (!role_ptr_.empty()) {
+ result = staged_blob(layer, expert); // counts its bytes
+ } else {
+ result = mapped_blob(layer, expert);
+ if (result != nullptr)
+ file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
+ }
+ if (complement_ready_ && result != nullptr) file_reads_.fetch_add(1, std::memory_order_relaxed);
+ }
if (result != nullptr) ++reads_;
return result;
}
@@ -703,7 +1545,10 @@ bool FileExpertSource::pinned(int64_t layer, int64_t expert) const {
if (!complement_ready_ || !complement_pinned_ || complement_host_ == nullptr || layer < 0 || expert < 0 ||
layer >= n_layers_ || expert >= n_expert_) return false;
const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
- return index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement;
+ if (index >= complement_offsets_.size() || complement_offsets_[index] == kNoComplement) return false;
+ // a partial pin (CS-T): only the registered prefix
+ return !complement_partial_ ||
+ complement_offsets_[index] + layer_blob_bytes_[(size_t) layer] <= complement_pin_limit_;
}
const uint8_t* FileExpertSource::device_alias(int64_t layer, int64_t expert) const {
@@ -712,6 +1557,12 @@ const uint8_t* FileExpertSource::device_alias(int64_t layer, int64_t expert) con
return complement_device_ + (size_t) complement_offsets_[index];
}
+bool FileExpertSource::pcie_layer(int64_t layer) const {
+ if (complement_ready_ && complement_pinned_ && complement_device_ != nullptr)
+ return layer >= 0 && layer < n_layers_;
+ return device_alias(layer, 0) != nullptr;
+}
+
// ================================ THE ADAPTER ================================
void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, const float* weights, int64_t n_embd,
@@ -854,6 +1705,7 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
d.fail_layer = d.layers;
return;
}
+ if (d.lookahead != nullptr) d.lookahead->submit(d.layers, x_f, n_tok, d.host_res); // CS-T: warm layer + 1
if (k < 1 || n_tok * k > kMaxWindowEntries) {
d.failed = true;
d.fail = "a verify window routes more entries than the expert pool's window tables hold";
@@ -894,7 +1746,7 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
if (e >= 0 && e < d.n_expert && d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] < 0) ++nmiss;
}
}
- const bool pcie_ok = d.pcie_num > 0 && d.src->device_alias(d.layers, 0) != nullptr;
+ const bool pcie_ok = d.pcie_num > 0 && d.src->pcie_layer(d.layers);
const int m = pcie_ok ? (nmiss * d.pcie_num) >> 8 : 0;
int miss_rank = 0, groups = 0, entries = 0, fetches = 0;
GpuPlanSink& P = *d.plan;
@@ -913,8 +1765,8 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
: (size_t) slot * (size_t) d.cache_blob));
} else {
if (miss_rank >= nmiss - m && fetches < P.staging_cap && fetches < 64) {
- const uint8_t* src = d.src->blob(d.layers, e);
- if (src != nullptr && d.src->pinned(d.layers, e)) {
+ const uint8_t* src = d.src->pinned(d.layers, e) ? d.src->blob(d.layers, e) : nullptr;
+ if (src != nullptr) {
kd = 1;
dma_src[fetches] = src;
pcie_i0[fetches] = i0;
@@ -986,6 +1838,15 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
else
for (int64_t t = 0; t < n_tok; ++t) act_quant_q8_1(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]);
const auto c2 = std::chrono::steady_clock::now();
+ { // CS-T: the experts the CPU computes, fetched together (the GGUF in place reads them on several threads)
+ static thread_local std::vector<int64_t> miss;
+ miss.clear();
+ for (int64_t i = 0; i < n_tok * k; ++i)
+ if (kind[i] < 0 && ids[i] >= 0 && ids[i] < d.n_expert &&
+ std::find(miss.begin(), miss.end(), (int64_t) ids[i]) == miss.end())
+ miss.push_back(ids[i]);
+ d.src->prefetch(d.layers, miss.data(), (int64_t) miss.size());
+ }
int njobs = 0;
for (int64_t t = 0; t < n_tok; ++t)
for (int64_t j = 0; j < k; ++j) {
@@ -1189,9 +2050,180 @@ catch (sycl::exception const &exc) {
// ================================ THE RESIDENT ARENA (R2.1) ================================
-// Plan v0.3 P6: the arena from the model's shard 1. Each layer's gate, up and down tensors hold the 512 experts
-// one after another; they are read in chunks and each expert's slice lands at its place in the blob
-// [gate rows | up rows | down rows] - the layout tools/iq_pack.py would have written to experts.bin.
+namespace {
+
+void hash_u64(uint64_t& h, uint64_t v) {
+ h = fnv1a64((const uint8_t*) &v, sizeof v, h);
+}
+
+void hash_text(uint64_t& h, const std::string& s) {
+ h = fnv1a64((const uint8_t*) s.data(), (uint64_t) s.size(), h);
+}
+
+bool hash_small_file(const std::filesystem::path& path, uint64_t& h, std::string& err) {
+ hash_text(h, path.filename().string());
+ std::ifstream f(path, std::ios::binary);
+ if (!f) {
+ hash_u64(h, 0);
+ return true;
+ }
+ hash_u64(h, 1);
+ std::vector<uint8_t> buf(64u << 10);
+ for (;;) {
+ f.read((char*) buf.data(), (std::streamsize) buf.size());
+ const std::streamsize n = f.gcount();
+ if (n > 0) h = fnv1a64(buf.data(), (uint64_t) n, h);
+ if (f.eof()) break;
+ if (!f) {
+ err = "ArenaExpertSource: cannot hash pack metadata " + path.string();
+ return false;
+ }
+ }
+ return true;
+}
+
+bool hash_sampled_file(const std::filesystem::path& path, uint64_t& h, std::string& err) {
+ std::ifstream f(path, std::ios::binary | std::ios::ate);
+ if (!f) {
+ err = "ArenaExpertSource: cannot sample pack source " + path.string();
+ return false;
+ }
+ const std::streamoff end = f.tellg();
+ if (end < 0) {
+ err = "ArenaExpertSource: cannot size pack source " + path.string();
+ return false;
+ }
+ const uint64_t bytes = (uint64_t) end;
+ hash_text(h, path.filename().string());
+ hash_u64(h, bytes);
+ constexpr uint64_t sample = 64u << 10;
+ const uint64_t starts[3] = {0, bytes / 2, bytes > sample ? bytes - sample : 0};
+ std::vector<uint8_t> buf((size_t) std::min<uint64_t>(sample, bytes));
+ for (uint64_t off : starts) {
+ if (buf.empty()) break;
+ const uint64_t at = std::min<uint64_t>(off, bytes - (uint64_t) buf.size());
+ f.clear();
+ f.seekg((std::streamoff) at);
+ f.read((char*) buf.data(), (std::streamsize) buf.size());
+ if ((size_t) f.gcount() != buf.size()) {
+ err = "ArenaExpertSource: short read while hashing pack source " + path.string();
+ return false;
+ }
+ hash_u64(h, at);
+ h = fnv1a64(buf.data(), (uint64_t) buf.size(), h);
+ }
+ return true;
+}
+
+bool shared_arena_pack_hash(const std::string& pack_dir, const std::string& experts_path,
+ const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay,
+ uint64_t& out, std::string& err) {
+ uint64_t h = 1469598103934665603ull;
+ hash_text(h, "strata-shared-expert-arena-pack-v1");
+ hash_u64(h, (uint64_t) lay.n_layers);
+ hash_u64(h, (uint64_t) lay.n_expert);
+ hash_u64(h, lay.total);
+ hash_u64(h, lay.max_blob);
+ hash_u64(h, lay.native ? 1 : 0);
+
+ const std::filesystem::path pack(pack_dir);
+ for (const char* name : {"manifest.json", "index.txt", "native_experts.txt"}) {
+ if (!hash_small_file(pack / name, h, err)) return false;
+ }
+
+ if (std::filesystem::exists(experts_path)) {
+ if (!hash_sampled_file(experts_path, h, err)) return false;
+ } else if (!gguf.empty()) {
+ // Native packs may read experts straight from one or more GGUF shards. Sample every distinct source
+ // file named by native_experts.txt; this keeps the fingerprint cheap while still tying it to the model
+ // bytes rather than only to an equal-size layout.
+ const std::filesystem::path first(gguf);
+ std::vector<std::filesystem::path> sources{first};
+ for (const std::string& name : lay.gguf_file) {
+ if (name.empty()) continue;
+ const std::filesystem::path p = first.parent_path() / name;
+ if (std::find(sources.begin(), sources.end(), p) == sources.end()) sources.push_back(p);
+ }
+ for (const auto& p : sources) {
+ if (!hash_sampled_file(p, h, err)) return false;
+ }
+ }
+
+ out = h == 0 ? 1 : h;
+ return true;
+}
+
+} // namespace
+
+namespace {
+/// The GGUF file that holds role `r` (0 gate, 1 up, 2 down) of layer `l`: a name beside the --native shard
+/// (native_experts.txt v3 per layer, v4 per role), or the --native shard itself.
+std::string expert_gguf_file(const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay, int64_t l, int r) {
+ const size_t i = (size_t) (3 * l + r);
+ if (lay.gguf_file.size() <= i || lay.gguf_file[i].empty()) return gguf;
+ const size_t cut = gguf.find_last_of("/\\");
+ return (cut == std::string::npos ? std::string() : gguf.substr(0, cut + 1)) + lay.gguf_file[i];
+}
+} // namespace
+
+bool check_experts_gguf(const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay, std::string& err) {
+ static const char* roles[3] = {"gate", "up", "down"};
+ if (lay.gguf_off.size() != (size_t) (3 * lay.n_layers)) {
+ err = "native_experts.txt has no GGUF offsets (a pack older than v2): repack it with tools/iq_pack.py";
+ return false;
+ }
+ try {
+ std::map<std::string, std::unique_ptr<strata::GgufFile>> files;
+ for (int64_t l = 0; l < lay.n_layers; ++l) {
+ const auto& fm = lay.fmt[(size_t) l];
+ const uint64_t blob = lay.bytes[(size_t) l];
+ const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off};
+ for (int r = 0; r < 3; ++r) {
+ const std::string path = expert_gguf_file(gguf, lay, l, r);
+ auto& f = files[path];
+ if (!f) f = std::make_unique<strata::GgufFile>(path);
+ const std::string name = "blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight";
+ const strata::TensorInfo* t = f->find(name);
+ const uint64_t want_type = (uint64_t) (r < 2 ? fm.gu_type : fm.d_type);
+ // GGUF order: dim 0 is the row (the input), dim 1 the rows, dim 2 the experts
+ const uint64_t cols = (uint64_t) (r < 2 ? fm.n_embd : fm.n_ff);
+ const uint64_t rows = (uint64_t) (r < 2 ? fm.n_ff : fm.n_embd);
+ const uint64_t bytes = per[r] * (uint64_t) lay.n_expert;
+ const uint64_t payload = f->file_size() - f->data_start();
+ std::string why;
+ if (t == nullptr) why = "is not in it";
+ else if (t->type != want_type)
+ why = std::string("is ") + t->type_name() + ", the pack says type " + std::to_string(want_type);
+ else if (t->shape.size() != 3 || t->shape[0] != cols || t->shape[1] != rows ||
+ t->shape[2] != (uint64_t) lay.n_expert)
+ why = "is not [" + std::to_string(cols) + ", " + std::to_string(rows) + ", " +
+ std::to_string(lay.n_expert) + "]";
+ else if (strata::tensor_payload_bytes(*t) != bytes)
+ why = "is not " + std::to_string(per[r]) + " B per expert";
+ else if (f->data_start() + t->offset != lay.gguf_off[(size_t) (3 * l + r)])
+ why = "starts at byte " + std::to_string(f->data_start() + t->offset) + ", the pack says " +
+ std::to_string(lay.gguf_off[(size_t) (3 * l + r)]);
+ else if (t->offset > payload || bytes > payload - t->offset)
+ why = "runs past the end of the file (a truncated shard?)";
+ if (!why.empty()) {
+ err = "the pack's native_experts.txt does not match the model: " + name + " in " + path + " " +
+ why + " - repack with tools/iq_pack.py from this model's shards";
+ return false;
+ }
+ }
+ }
+ return true;
+ } catch (const std::exception& e) {
+ err = std::string("native experts from the GGUF: ") + e.what();
+ return false;
+ }
+}
+
+// Plan v0.3 P6: the arena from the model's GGUF shards. Each layer's gate, up and down tensors hold the 512
+// experts one after another; they are read in chunks and each expert's slice lands at its place in the blob
+// [gate rows | up rows | down rows] - the layout tools/iq_pack.py would have written to experts.bin. Each role
+// is read from its own file (native_experts.txt v4: a shard boundary can fall inside a layer; per role as in
+// #255, gopinath87607). The caller checks the spans first (check_experts_gguf).
LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata::kernels::cpu::ExpertLayout& lay,
int threads) {
LoadStats st;
@@ -1199,42 +2231,42 @@ LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata:
const auto t0 = std::chrono::steady_clock::now();
std::atomic<int64_t> next{0};
std::atomic<bool> bad{false};
- // a layer's experts may sit in another shard of the model (native_experts.txt v3): a name beside `gguf`
- const size_t cut = gguf.find_last_of("/\\");
- const std::string dir = cut == std::string::npos ? std::string() : gguf.substr(0, cut + 1);
- auto file_of = [&](int64_t l) -> std::string {
- if (lay.gguf_file.empty() || lay.gguf_file[(size_t) l].empty()) return gguf;
- return dir + lay.gguf_file[(size_t) l];
- };
auto worker = [&]() {
- std::ifstream f;
+ // #230: `fread` on a `FILE*`, as load_experts_ranges (#89): MSVC's `std::ifstream::read` splits a request
+ // into 4095-byte freads, which took this path to 0.02 GiB/s on a Windows install without experts.bin.
+ // The guard closes the handle on every return.
+ struct Closer {
+ FILE* f = nullptr;
+ ~Closer() { if (f != nullptr) std::fclose(f); }
+ } file;
std::string open_name;
std::vector<uint8_t> buf;
for (;;) {
const int64_t l = next.fetch_add(1);
if (l >= lay.n_layers || bad) break;
- const std::string name = file_of(l);
- if (name != open_name) {
- f.close();
- f.clear();
- f.open(name, std::ios::binary);
- if (!f) { bad = true; return; }
- open_name = name;
- }
const auto& fm = lay.fmt[(size_t) l];
const uint64_t blob = lay.bytes[(size_t) l];
const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off};
const uint64_t at[3] = {0, fm.up_off, fm.down_off};
for (int r = 0; r < 3; ++r) {
+ // the handle is kept while consecutive roles share a file (every layer of a v3 pack)
+ const std::string name = expert_gguf_file(gguf, lay, l, r);
+ if (name != open_name) {
+ if (file.f != nullptr) std::fclose(file.f);
+ file.f = std::fopen(name.c_str(), "rb");
+ if (file.f == nullptr) { bad = true; return; }
+ open_name = name;
+ }
+ FILE* const f = file.f;
const uint64_t src = lay.gguf_off[(size_t) (3 * l + r)];
const uint64_t total = per[r] * (uint64_t) lay.n_expert;
const uint64_t chunk = per[r] * 16; // 16 experts per read
buf.resize((size_t) chunk);
for (uint64_t done = 0; done < total; done += chunk) {
const uint64_t n = std::min<uint64_t>(chunk, total - done);
- f.seekg((std::streamoff) (src + done));
- f.read((char*) buf.data(), (std::streamsize) n);
- if ((uint64_t) f.gcount() != n) { bad = true; return; }
+ // 64-bit seek: a shard is tens of GB
+ if (STRATA_FSEEK64(f, src + done) != 0) { bad = true; return; }
+ if (std::fread(buf.data(), 1, (size_t) n, f) != (size_t) n) { bad = true; return; }
for (uint64_t k = 0; k < n / per[r]; ++k) {
const uint64_t e = done / per[r] + k;
std::memcpy(dst + lay.blob_offset(l, (int64_t) e) + at[r], buf.data() + k * per[r], (size_t) per[r]);
@@ -1262,7 +2294,8 @@ ArenaExpertSource::~ArenaExpertSource() { close(); }
bool ArenaExpertSource::open(const std::string &pack_dir, int64_t n_layers,
int64_t n_expert, int threads, std::string &err,
- uint64_t max_pinned_bytes) try {
+ uint64_t max_pinned_bytes,
+ const std::string &shared_arena_file) try {
close();
const std::string path = pack_dir + "/experts.bin";
// plan v0.3 P6: the layout (canonical, or a native pack's per-layer blobs) was loaded by the driver
@@ -1278,7 +2311,12 @@ bool ArenaExpertSource::open(const std::string &pack_dir, int64_t n_layers,
const bool from_gguf = !std::ifstream(path, std::ios::binary) && lay.native && !lay.gguf_off.empty() && !gguf_.empty();
// SIZE CHECK BEFORE THE ALLOCATION, not after. A wrong pack should name the two numbers rather than spend
// 34 GB and a minute of loading first.
- if (!from_gguf) {
+ if (from_gguf) {
+ // every (file, offset) of native_experts.txt must be the tensor it claims, of the pack's type and
+ // dimensions and inside its file - before the allocation, so a pack of another model or a truncated
+ // shard is a message rather than an arena of plausible wrong experts
+ if (!check_experts_gguf(gguf_, lay, err)) { err = "ArenaExpertSource: " + err; return false; }
+ } else {
std::ifstream f(path, std::ios::binary | std::ios::ate);
if (!f) { err = "ArenaExpertSource: cannot open " + path; return false; }
const uint64_t got = (uint64_t) f.tellg();
@@ -1294,6 +2332,10 @@ bool ArenaExpertSource::open(const std::string &pack_dir, int64_t n_layers,
}
}
+ uint64_t pack_hash = 0;
+ if (!shared_arena_file.empty() &&
+ !shared_arena_pack_hash(pack_dir, path, gguf_, lay, pack_hash, err)) return false;
+
// one layer per registration slice, so no expert straddles two registrations. The arena is one blob
// longer than the file: a copy of a whole VRAM slot (the largest blob) may then start at any expert.
std::vector<uint64_t> bounds, loff, lbytes;
@@ -1303,10 +2345,14 @@ bool ArenaExpertSource::open(const std::string &pack_dir, int64_t n_layers,
lbytes.push_back(lay.blob_bytes(l) * (uint64_t) n_expert);
}
bounds.push_back(want);
- PinnedArena* a = new PinnedArena(want + (uint64_t) blob, bounds, max_pinned_bytes);
+ PinnedArena* a = new PinnedArena(want + (uint64_t) blob, bounds, max_pinned_bytes,
+ shared_arena_file, pack_hash);
if (!a->valid()) {
+ const std::string why = a->note;
delete a;
- err = "ArenaExpertSource: the arena could not be reserved (" + std::to_string(want) + " B)";
+ err = "ArenaExpertSource: the arena could not be reserved (" +
+ std::to_string(want + (uint64_t) blob) + " B)" +
+ (why.empty() ? std::string{} : ": " + why);
return false;
}
const LoadStats st = from_gguf ? load_experts_gguf(gguf_, a->data(), lay, threads)
diff --git a/sycl/src/core/layer.cpp b/sycl/src/core/layer.cpp
index f80a85737..0ac8fb1e7 100644
--- a/sycl/src/core/layer.cpp
+++ b/sycl/src/core/layer.cpp
@@ -741,9 +741,10 @@ uint64_t qsa_state_init(const ModelGeometry &g, int64_t max_cells, void *base,
// THE ROPE TABLE IS BUILT ON THE HOST IN FLOAT64 and uploaded once, because the reference computes its
// frequencies in float64 and reproducing that on device means double-precision `pow`/`cos` that need not
// agree with the host's libm. A table shorter than the sequence would have the rotation read past it.
+ // The process's rope scaling (none by default) is INSIDE the table - the rotation kernels cannot tell.
if (share_rope == nullptr) {
std::vector<float> hc((size_t) max_cells * (s.n_rot / 2)), hs((size_t) max_cells * (s.n_rot / 2));
- strata::kernels::build_rope_table((int) s.n_rot, strata::kernels::qsa_freq_base(), (int) max_cells,
+ strata::kernels::build_rope_table((int) s.n_rot, strata::kernels::rope_scaling(), (int) max_cells,
hc.data(), hs.data());
dpct::get_in_order_queue()
.memcpy(st.cos_tab, hc.data(), hc.size() * 4)
@@ -977,7 +978,7 @@ const auto normalize_rotate = [&](float* data, const WeightRef* norm, int rows,
try {
if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, RMS_EPS, stream);
else rms_norm_weighted(data, (const float*) norm->data, rows, cols, RMS_EPS, stream);
- if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, (float) qsa_freq_base(), st.pos_dev, stream);
+ if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), st.pos_dev, stream);
else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, st.pos_dev, stream);
return true;
} catch (const std::exception& error) {
@@ -1047,7 +1048,7 @@ if (st.kv_hybrid) {
} else if (st.kv_int8) kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); else kv_append_step(st.k_pool, st.v_pool, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); { const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim; const uint64_t base = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 2 * nvk + 8; if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.k_pool, base, nvk / 2, stream); if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.v_pool, base + nvk / 2, nvk / 2, stream); dump_slot(dump, g, layer, b.vcur, base + nvk, nvk, stream); dump_slot(dump, g, layer, b.kcur, base + 2 * nvk, nvk, stream); } { const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; if (native_qsa_indexer_enabled()) {
try {
native_qsa_indexer_append(b.idx_raw, st.step + kStepPos, pos_base,
- (const float*) w_ikn->data, RMS_EPS, ib, s, st.max_cells, (float) qsa_freq_base(), stream);
+ (const float*) w_ikn->data, RMS_EPS, ib, s, st.max_cells, rope_scaling(), stream);
} catch (const std::exception& error) { err = v.name("native_indexer") + ": " + error.what(); return false; }
} else indexer_key_append(b.idx_raw, st.pos_dev, pos_base, (const float*) w_ikn->data, RMS_EPS, ib, s,
st.cos_tab, st.sin_tab, stream); }
diff --git a/sycl/src/core/mtp.cpp b/sycl/src/core/mtp.cpp
index bdd56dea4..4e9a013c0 100644
--- a/sycl/src/core/mtp.cpp
+++ b/sycl/src/core/mtp.cpp
@@ -2,6 +2,7 @@
#include <sycl/sycl.hpp>
#include <dpct/dpct.hpp>
#include "strata/core/mtp.hpp"
+#include "strata/core/coupled_draft.hpp"
#include "strata/core/on_device.hpp"
#include "strata/core/native_head.hpp"
@@ -119,6 +120,14 @@ MtpDrafter::~MtpDrafter() {
if (pf_dev_) sycl::free(pf_dev_, dpct::get_in_order_queue());
for (auto &e : round_exec_) if (e) delete (e);
for (auto &e : step_exec_) if (e) delete (e);
+ for (auto &e : round_exec_c_) if (e) delete (e);
+ for (auto &e : step_exec_c_) if (e) delete (e);
+ if (cparams_) sycl::free(cparams_, dpct::get_in_order_queue());
+ if (cring_) sycl::free(cring_, dpct::get_in_order_queue());
+ if (dinv_) sycl::free(dinv_, dpct::get_in_order_queue());
+ if (cscratch_) sycl::free(cscratch_, dpct::get_in_order_queue());
+ if (h_cparams_) sycl::free(h_cparams_, dpct::get_in_order_queue());
+ if (h_chist_) sycl::free(h_chist_, dpct::get_in_order_queue());
if (cs_) dpct::get_current_device().destroy_queue(cs_);
if (dense_) sycl::free(dense_, dpct::get_in_order_queue());
if (experts_) sycl::free(experts_, dpct::get_in_order_queue());
@@ -248,7 +257,7 @@ bool MtpDrafter::load(const std::string &rt_dir, const ModelGeometry &g,
// ---- the layer's own K/V (dense attention: no indexer state is read)
const strata::kernels::QsaShapes s = shapes_of(g);
- const int64_t max_cells = ss.qsa_states[0].max_cells;
+ const int64_t max_cells = ss.qsa_states[ss.qsa_primary()].max_cells;
// KV streaming: the drafter only reads its last `window` cells, so with streaming on its K/V is a ring of the
// window (plus the cells a round writes ahead of its queries) over a host copy, refilled on a resume. The host copy
// is pinned after the expert arena has pinned what it could: if it does not fit, the K/V stays whole in VRAM.
@@ -264,7 +273,7 @@ bool MtpDrafter::load(const std::string &rt_dir, const ModelGeometry &g,
sb, dpct::get_in_order_queue())) != 0) {
err = "mtp: the K/V state does not fit"; return false;
}
- if (qsa_state_init(g, max_cells, state_arena_, st_, &ss.qsa_states[0], ring) == 0) {
+ if (qsa_state_init(g, max_cells, state_arena_, st_, &ss.qsa_states[ss.qsa_primary()], ring) == 0) {
if (st_.kv_mode == 0) { err = "mtp: state init failed"; return false; }
std::fprintf(stderr, "strata mtp: no pinned RAM left for the draft layer's K/V copy; keeping it in VRAM\n");
/*
@@ -279,7 +288,7 @@ bool MtpDrafter::load(const std::string &rt_dir, const ModelGeometry &g,
sb, dpct::get_in_order_queue())) != 0) {
err = "mtp: the K/V state does not fit"; return false;
}
- if (qsa_state_init(g, max_cells, state_arena_, st_, &ss.qsa_states[0], ring) == 0) { err = "mtp: state init failed"; return false; }
+ if (qsa_state_init(g, max_cells, state_arena_, st_, &ss.qsa_states[ss.qsa_primary()], ring) == 0) { err = "mtp: state init failed"; return false; }
}
qsa_set_kv_int8(kv_int8_was);
qsa_set_kv_hybrid(kv_hybrid_was);
@@ -384,9 +393,71 @@ uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const
if (size >= 4 && size % 4 == 0) bytes += (uint64_t) (size / 4) * head_row_bytes + (uint64_t) size;
}
}
+ // coupled draft sampling (STRATA_SPEC_COUPLED=1 only): an upper bound - the id -> subset map, the penalty ring,
+ // the split scratch (64 lists of 64 entries at most) and the parameters
+ if (coupled_draft_env() && cparams_ == nullptr)
+ bytes += (uint64_t) n_vocab * 4 + (uint64_t) (kCoupledHistCap + max_t_) * 4 + 64ull * 64ull * 8ull + 4096;
return bytes;
}
+bool MtpDrafter::setup_coupled(std::string& err) try {
+ const int64_t nv = dhead_ != nullptr ? n_dvocab_ : n_vocab_;
+ const size_t scratch = strata::kernels::coupled_draft_scratch_bytes((int) nv);
+ if (scratch == 0) {
+ std::fprintf(stderr, "strata mtp: STRATA_SPEC_COUPLED: %lld draft logits are too wide for the coupled sampler; "
+ "argmax drafts\n", (long long) nv);
+ return true;
+ }
+ sycl::queue& q = dpct::get_in_order_queue();
+ const size_t ring = (size_t) (kCoupledHistCap + max_t_) * sizeof(int32_t);
+ cparams_ = sycl::malloc_device<strata::kernels::SamplerParams>(1, q);
+ cring_ = (int32_t*) sycl::malloc_device(ring, q);
+ cscratch_ = sycl::malloc_device(scratch, q);
+ if (cparams_ == nullptr || cring_ == nullptr || cscratch_ == nullptr ||
+ !mapped(sizeof(strata::kernels::SamplerParams), (void**) &h_cparams_, (void**) &m_cparams_) ||
+ !mapped((size_t) kCoupledHistCap * sizeof(int32_t), (void**) &h_chist_, (void**) &m_chist_)) {
+ err = "mtp: the coupled draft sampler's buffers do not fit";
+ return false;
+ }
+ q.memset(cring_, 0xff, ring).wait(); // -1: no token
+ std::fill(h_chist_, h_chist_ + kCoupledHistCap, -1);
+ vram_ += sizeof(strata::kernels::SamplerParams) + ring + scratch;
+ if (dhead_ != nullptr) { // token id -> subset index (-1: not in the draft head), for the penalties
+ std::vector<int32_t> sub((size_t) n_dvocab_), inv((size_t) n_vocab_, -1);
+ q.memcpy(sub.data(), dvocab_, sub.size() * sizeof(int32_t)).wait();
+ for (size_t i = 0; i < sub.size(); ++i)
+ if (sub[i] >= 0 && sub[i] < n_vocab_ && inv[(size_t) sub[i]] < 0) inv[(size_t) sub[i]] = (int32_t) i;
+ dinv_ = (int32_t*) sycl::malloc_device(inv.size() * sizeof(int32_t), q);
+ if (dinv_ == nullptr) {
+ err = "mtp: the coupled draft sampler's token map does not fit";
+ return false;
+ }
+ q.memcpy(dinv_, inv.data(), inv.size() * sizeof(int32_t)).wait();
+ vram_ += inv.size() * sizeof(int32_t);
+ }
+ dpct::get_current_device().queues_wait_and_throw();
+ coupled_ok_ = true;
+ std::fprintf(stderr, "strata mtp: coupled draft sampling on (STRATA_SPEC_COUPLED): sampled requests draft with the "
+ "target's chain and Philox draw over %lld tokens\n", (long long) nv);
+ return true;
+} catch (sycl::exception const& e) {
+ err = std::string("mtp: coupled setup: ") + e.what();
+ return false;
+}
+
+void MtpDrafter::set_draft_sampling(const strata::kernels::SamplerParams& sp) {
+ coupled_active_ = coupled_ok_ && !sp.greedy && sp.temperature > 0.0f;
+ if (!coupled_active_) return;
+ *h_cparams_ = sp; // read by the next round graph (after the previous one has synced)
+ std::fill(h_chist_, h_chist_ + kCoupledHistCap, -1);
+}
+
+void MtpDrafter::set_draft_history(const int32_t* tail, int64_t n_tail, int32_t next) {
+ if (!coupled_active_) return;
+ const int h = coupled_hist_len(h_cparams_->penalty_last_n, kCoupledHistCap);
+ coupled_hist_base(tail, n_tail, next, h, h_chist_ + (kCoupledHistCap - h));
+}
+
bool MtpDrafter::bind(const WeightTable &wt, const NativeHead *head,
const float *window_R, std::string &err) try {
const OnDevice on_device(device_);
@@ -429,6 +500,7 @@ bool MtpDrafter::bind(const WeightTable &wt, const NativeHead *head,
(double) (n_dvocab_ * row_bytes) / 1048576.0);
}
}
+ if (coupled_draft_env() && cparams_ == nullptr && !setup_coupled(err)) return false;
return true;
}
catch (sycl::exception const &exc) {
@@ -492,7 +564,7 @@ bool MtpDrafter::record_forward(int T, int step_row0, dpct::queue_ptr cs,
// ---- attention: K/V into the layer's own cache, then (full) dense attention over every cell
auto norm_rope = [&](float* data, const float* gamma, int rows, int cols, const int32_t* p) {
native_qsa_rms_norm_weighted(data, gamma, data, cols, rows, EPS, cs);
- if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, (float) qsa_freq_base(), p, cs);
+ if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), p, cs);
else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st_.cos_tab, st_.sin_tab, p, cs);
};
native_quantize_q8_1(mixed_, xq_, (int) N, T, cs);
@@ -593,6 +665,13 @@ bool MtpDrafter::record_forward(int T, int step_row0, dpct::queue_ptr cs,
const bool sub = dhead_ != nullptr;
const int64_t nv = sub ? n_dvocab_ : n_vocab_;
native_mmvq(head_->type(), sub ? dhead_ : head_->weights(), xq_, head_logits_, (int) N, (int) nv, T, cs);
+ if (coupled_rec_) {
+ // coupled draft sampling: the target's chain and Philox draw for the row that will verify this draft
+ // (counter = this cell + 1, from its step record), penalties over the ring; T == 1 (full layer)
+ coupled_draft_sample(head_logits_, (int) nv, sub ? dvocab_ : nullptr, sub ? dinv_ : nullptr, (int) n_vocab_,
+ cparams_, cring_, kCoupledHistCap, coupled_j_, step, cscratch_, out_ids_, probs_, cs);
+ return true;
+ }
SamplerParams sp;
sp.greedy = true;
sp.temperature = 0.0f;
@@ -680,14 +759,17 @@ catch (sycl::exception const &exc) {
std::exit(1);
}
-bool MtpDrafter::capture_round(int T, std::string &err) try {
- if (round_exec_[T]) return true;
+bool MtpDrafter::capture_round(int T, bool coupled, std::string &err) try {
+ dpct::experimental::command_graph_exec_ptr& exec = coupled ? round_exec_c_[T] : round_exec_[T];
+ if (exec) return true;
using namespace strata::kernels;
const int64_t HCN = g_->hc * g_->n_embd;
if (DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs_)) != 0) {
err = "mtp: begin capture"; return false;
}
bool ok = true;
+ // coupled: the request's chain and the penalty history's base, for this round's drafts
+ if (coupled) coupled_draft_stage(m_cparams_, m_chist_, cparams_, cring_, kCoupledHistCap, cs_);
copy_i32_from_mapped(tok_, m_tok_, T, cs_);
copy_i32_from_mapped(step_, m_step_, (int64_t) 2 * T * 4, cs_);
copy_i32_from_mapped(pos_, m_pos_, (int64_t) 2 * T * g_->n_head, cs_);
@@ -702,10 +784,13 @@ bool MtpDrafter::capture_round(int T, std::string &err) try {
if (ok) {
copy_i32_from_mapped(step_ + ra * 4, m_step_ + ra * 4, 4, cs_);
copy_i32_from_mapped(pos_ + ra * g_->n_head, m_pos_ + ra * g_->n_head, g_->n_head, cs_);
+ coupled_rec_ = coupled;
+ coupled_j_ = 0;
ok = record_forward(1, ra, cs_, err);
+ coupled_rec_ = false;
}
if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, 0, cs_, probs_, m_prob_);
- return finish_capture(cs_, ok, round_exec_[T], "round", err);
+ return finish_capture(cs_, ok, exec, coupled ? "round (coupled)" : "round", err);
}
catch (sycl::exception const &exc) {
std::cerr << exc.what() << "Exception caught at file:" << __FILE__
@@ -715,8 +800,9 @@ catch (sycl::exception const &exc) {
// Chain step j (1..max_t-2): one row at the cell staged in step row `max_t + j - 1`, from the previous step's
// residual and token (left in Rin_[0] / tok_[0] by mtp_select); draft j and its probability to the mapped outputs.
-bool MtpDrafter::capture_step(int j, std::string &err) try {
- if (step_exec_[j]) return true;
+bool MtpDrafter::capture_step(int j, bool coupled, std::string &err) try {
+ dpct::experimental::command_graph_exec_ptr& exec = coupled ? step_exec_c_[j] : step_exec_[j];
+ if (exec) return true;
using namespace strata::kernels;
const int64_t HCN = g_->hc * g_->n_embd;
const int row = max_t_ + j - 1;
@@ -725,9 +811,12 @@ bool MtpDrafter::capture_step(int j, std::string &err) try {
}
copy_i32_from_mapped(step_ + row * 4, m_step_ + row * 4, 4, cs_);
copy_i32_from_mapped(pos_ + row * g_->n_head, m_pos_ + row * g_->n_head, g_->n_head, cs_);
+ coupled_rec_ = coupled;
+ coupled_j_ = j;
bool ok = record_forward(1, row, cs_, err);
+ coupled_rec_ = false;
if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, j, cs_, probs_, m_prob_);
- return finish_capture(cs_, ok, step_exec_[j], "step", err);
+ return finish_capture(cs_, ok, exec, coupled ? "step (coupled)" : "step", err);
}
catch (sycl::exception const &exc) {
std::cerr << exc.what() << "Exception caught at file:" << __FILE__
@@ -923,7 +1012,8 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t*
float* probs, float min_p, int* n_drafts) {
const OnDevice on_device(device_);
if (T < 1 || T > max_t_ || a < 0 || a >= T) { err = "mtp: draft arguments out of range"; return false; }
- if (!capture_round(T, err)) return false;
+ const bool cp = coupled_active_; // coupled draft sampling for this request: its own graphs
+ if (!capture_round(T, cp, err)) return false;
const Clock::time_point t0 = Clock::now();
const int64_t NH = g_->n_head;
auto put = [&](int row, int64_t cell) {
@@ -937,11 +1027,11 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t*
h_tok_[t] = tokens[t];
put(t, p + t);
}
- put(2 * max_t_ - 1, p + a);
+ put(2 * max_t_ - 1, coupled_draft_cell(p, a, 0)); // p + a: draft 0's cell
h_row_[0] = a;
h_row_[1] = 0;
std::atomic_thread_fence(std::memory_order_seq_cst);
- if (DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*round_exec_[T])) != 0 ||
+ if (DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*(cp ? round_exec_c_[T] : round_exec_[T]))) != 0 ||
DPCT_CHECK_ERROR(cs_->wait()) != 0) {
/*
DPCT1009: SYCL reports errors using exceptions and does not use error
@@ -962,10 +1052,10 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t*
int n = 1;
// the chain continues while the last draft is likely enough to be verified
for (int j = 1; j < std::min(max_t_ - 1, max_drafts_) && pj >= min_p; ++j) {
- if (!capture_step(j, err)) return false;
- put(max_t_ + j - 1, p + a + j);
+ if (!capture_step(j, cp, err)) return false;
+ put(max_t_ + j - 1, coupled_draft_cell(p, a, j)); // p + a + j; coupled: drawn at counter cell + 1
std::atomic_thread_fence(std::memory_order_seq_cst);
- if (DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*step_exec_[j])) != 0 ||
+ if (DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*(cp ? step_exec_c_[j] : step_exec_[j]))) != 0 ||
DPCT_CHECK_ERROR(cs_->wait()) != 0) {
/*
DPCT1009: SYCL reports errors using exceptions and does not use
diff --git a/sycl/src/core/native_dense.cpp b/sycl/src/core/native_dense.cpp
index 1d7da7142..7b0ff4a31 100644
--- a/sycl/src/core/native_dense.cpp
+++ b/sycl/src/core/native_dense.cpp
@@ -18,9 +18,10 @@ namespace {
bool eligible(const strata::TensorInfo& tensor, bool include_ple_key) {
const auto& name = tensor.name;
if (name.rfind("blk.", 0) != 0) return false;
- // Match the native PLE kernel: Q2_0, IQ3_XXS and IQ4_XS. Other keys retain the packed BF16 fallback.
+ // Match the native PLE kernel: Q2_0, IQ3_XXS, IQ4_XS and Q8_0 (UD-Q4_K_XL). Other keys retain the packed BF16
+ // fallback.
if (name == "blk.1.ple_key.weight")
- return include_ple_key && (tensor.type == 42 || tensor.type == 18 || tensor.type == 23);
+ return include_ple_key && (tensor.type == 42 || tensor.type == 18 || tensor.type == 23 || tensor.type == 8);
static const char* suffixes[] = {".attn_qkv.weight", ".attn_gate.weight", ".ssm_out.weight",
".attn_q.weight", ".attn_k.weight", ".attn_v.weight", ".attn_output.weight",
".ffn_gate_shexp.weight", ".ffn_up_shexp.weight", ".ffn_down_shexp.weight"};
diff --git a/sycl/src/core/native_head.cpp b/sycl/src/core/native_head.cpp
index d03f972c9..3ebfe6389 100644
--- a/sycl/src/core/native_head.cpp
+++ b/sycl/src/core/native_head.cpp
@@ -18,23 +18,22 @@ NativeHead::~NativeHead() {
if (weights_) sycl::free(weights_, dpct::get_in_order_queue());
}
-bool NativeHead::load(const std::string &path, int64_t n_in, int64_t n_out,
- std::string &err) try {
+bool NativeHead::load(const std::vector<std::string> &shards, int64_t n_in,
+ int64_t n_out, std::string &err) try {
if (loaded()) { err = "native head is already loaded"; return false; }
if (n_in <= 0 || n_out <= 0 || n_in > INT_MAX || n_out > INT_MAX || n_in % 256) {
err = "native head requires positive int32 dimensions and whole 256-value rows";
return false;
}
try {
- strata::GgufFile gguf(path);
- err = strata::check_architecture(gguf);
+ // The architecture is the metadata shard's; output.weight comes from whichever shard holds it (shard 2
+ // of Unsloth's UD-Q4_K_XL, whose shard 1 holds no tensor). GgufModel refuses a duplicate across shards.
+ const strata::GgufModel model(shards);
+ err = strata::check_architecture(model.meta());
if (!err.empty()) return false;
- const strata::TensorInfo* tensor = nullptr;
- for (const auto& candidate : gguf.tensors()) {
- if (candidate.name != "output.weight") continue;
- if (tensor) { err = "native head: duplicate output.weight"; return false; }
- tensor = &candidate;
- }
+ size_t at = 0;
+ const strata::TensorInfo* tensor = model.find("output.weight", &at);
+ const strata::GgufFile& gguf = model.shard(at);
if (!tensor || !strata::kernels::native_mmvq_supported((int) tensor->type) || tensor->shape.size() != 2 ||
tensor->shape[0] != (uint64_t) n_in || tensor->shape[1] != (uint64_t) n_out) {
err = "native head: expected a natively supported output.weight with the canonical head dimensions";
@@ -160,13 +159,15 @@ NativeEmbed::~NativeEmbed() {
sycl::free((void *) dev_, dpct::get_in_order_queue()); // the VRAM fallback below
}
-bool NativeEmbed::load(const std::string &path, int64_t n_embd, int64_t n_vocab,
- std::string &err) try {
+bool NativeEmbed::load(const std::vector<std::string> &shards, int64_t n_embd,
+ int64_t n_vocab, std::string &err) try {
try {
- strata::GgufFile gguf(path);
- const strata::TensorInfo* t = nullptr;
- for (const auto& c : gguf.tensors())
- if (c.name == "token_embd.weight") t = &c;
+ const strata::GgufModel model(shards);
+ err = strata::check_architecture(model.meta());
+ if (!err.empty()) { err = "native embedding: " + err; return false; }
+ size_t at = 0;
+ const strata::TensorInfo* t = model.find("token_embd.weight", &at);
+ const strata::GgufFile& gguf = model.shard(at);
if (!t || t->shape.size() != 2 || t->shape[0] != (uint64_t) n_embd || t->shape[1] != (uint64_t) n_vocab ||
!strata::kernels::iq_supported((int) t->type) || n_embd % 256) {
err = "native embedding: token_embd.weight is absent, of another shape, or of a type without a GPU "
@@ -175,6 +176,13 @@ bool NativeEmbed::load(const std::string &path, int64_t n_embd, int64_t n_vocab,
}
row_ = strata::kernels::iq_row_bytes((int) t->type, n_embd);
bytes_ = (uint64_t) row_ * (uint64_t) n_vocab;
+ // the table is copied out of the mapping below: a truncated shard must be an error, not a read past EOF
+ if (!model.in_bounds(*t, at) || strata::tensor_payload_bytes(*t) != bytes_) {
+ err = "native embedding: token_embd.weight's payload is truncated or not " + std::to_string(bytes_) +
+ " B (" + gguf.path() + ")";
+ bytes_ = 0;
+ return false;
+ }
/*
DPCT1048: The original value cudaHostAllocMapped is not meaningful in
the migrated code and was removed or replaced with 0. You may need to
diff --git a/sycl/src/core/pinned.dp.cpp b/sycl/src/core/pinned.dp.cpp
index 5b5d33da1..517163788 100644
--- a/sycl/src/core/pinned.dp.cpp
+++ b/sycl/src/core/pinned.dp.cpp
@@ -6,6 +6,7 @@
#include "strata/platform/memory.hpp"
#include <atomic>
+#include <cerrno>
#include <cstdlib>
#include <cstdio>
#include <cstring>
@@ -24,7 +25,10 @@
#ifdef _WIN32
#include <windows.h>
#else
+#include <fcntl.h>
#include <sys/mman.h>
+#include <sys/stat.h>
+#include <unistd.h>
#include <linux/mman.h>
#ifndef MAP_HUGE_2MB
#define MAP_HUGE_2MB (21 << 26)
@@ -35,9 +39,32 @@ namespace strata::core {
namespace {
+constexpr uint64_t kSharedArenaHeaderBytes = 4096;
+constexpr char kSharedArenaMagic[16] = "STRATA-ARENA-V1";
+
+struct SharedArenaHeader {
+ char magic[16];
+ uint32_t version;
+ uint32_t header_bytes;
+ uint64_t arena_bytes;
+ uint64_t pack_hash;
+ uint64_t reserved[4];
+};
+static_assert(sizeof(SharedArenaHeader) <= kSharedArenaHeaderBytes);
+
// A 2 MB-aligned reservation. Large pages first, then the largest alignment the OS will give us for free.
-void* reserve(uint64_t bytes, PageBacking& got, std::string& note) {
+// A non-empty shared_file instead maps one file whose first 4 KiB identify the pack and whose remaining bytes
+// are the resident arena. This shared-file layout is intended for tmpfs (/dev/shm); hugetlbfs would need
+// hugepage-aligned file size and arena offset rather than the 4 KiB header layout used here.
+void* reserve(uint64_t bytes, PageBacking& got, std::string& note, const std::string& shared_file,
+ uint64_t shared_pack_hash, void*& mapping_base, uint64_t& mapping_bytes) {
+ mapping_base = nullptr;
+ mapping_bytes = 0;
#ifdef _WIN32
+ if (!shared_file.empty()) {
+ note = "shared-file arena backing is not implemented on Windows";
+ return nullptr;
+ }
// MEM_LARGE_PAGES needs SeLockMemoryPrivilege. Having it assigned to the account is not enough: the
// PROCESS must enable it in its own token (AdjustTokenPrivileges) before VirtualAlloc, or the call fails.
// An account without the assignment, or a failure to enable, leaves the process as it was: VirtualAlloc
@@ -85,6 +112,94 @@ void* reserve(uint64_t bytes, PageBacking& got, std::string& note) {
got = PageBacking::NormalPages;
return p;
#else
+ if (!shared_file.empty()) {
+ if (shared_pack_hash == 0) {
+ note = "shared arena requires a nonzero pack hash";
+ return nullptr;
+ }
+ if (bytes > UINT64_MAX - kSharedArenaHeaderBytes) {
+ note = "shared arena size overflows its header";
+ return nullptr;
+ }
+ const uint64_t file_bytes = kSharedArenaHeaderBytes + bytes;
+ const int fd = open(shared_file.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600);
+ if (fd < 0) {
+ note = "cannot open shared arena " + shared_file + ": " + std::strerror(errno);
+ return nullptr;
+ }
+ struct stat st{};
+ if (fstat(fd, &st) != 0) {
+ const int e = errno;
+ close(fd);
+ note = "cannot stat shared arena " + shared_file + ": " + std::strerror(e);
+ return nullptr;
+ }
+
+ const bool fresh = st.st_size == 0;
+ if (fresh) {
+ if (ftruncate(fd, (off_t) file_bytes) != 0) {
+ const int e = errno;
+ close(fd);
+ note = "cannot size shared arena " + shared_file + ": " + std::strerror(e);
+ return nullptr;
+ }
+ SharedArenaHeader hdr{};
+ std::memcpy(hdr.magic, kSharedArenaMagic, sizeof hdr.magic);
+ hdr.version = 1;
+ hdr.header_bytes = (uint32_t) kSharedArenaHeaderBytes;
+ hdr.arena_bytes = bytes;
+ hdr.pack_hash = shared_pack_hash;
+ const ssize_t written = pwrite(fd, &hdr, sizeof hdr, 0);
+ if (written != (ssize_t) sizeof hdr) {
+ const int e = errno;
+ close(fd);
+ note = "cannot write shared arena header " + shared_file + ": " +
+ (written < 0 ? std::string(std::strerror(e)) : std::string("short write"));
+ return nullptr;
+ }
+ } else {
+ if (st.st_size < 0 || (uint64_t) st.st_size != file_bytes) {
+ close(fd);
+ note = "shared arena " + shared_file + " is " +
+ std::to_string((unsigned long long) st.st_size) + " B, expected " +
+ std::to_string((unsigned long long) file_bytes) + " B including its header";
+ return nullptr;
+ }
+ SharedArenaHeader hdr{};
+ const ssize_t got_header = pread(fd, &hdr, sizeof hdr, 0);
+ if (got_header != (ssize_t) sizeof hdr ||
+ std::memcmp(hdr.magic, kSharedArenaMagic, sizeof hdr.magic) != 0 ||
+ hdr.version != 1 || hdr.header_bytes != kSharedArenaHeaderBytes || hdr.arena_bytes != bytes) {
+ close(fd);
+ note = "shared arena " + shared_file + " has an incompatible or missing header";
+ return nullptr;
+ }
+ if (hdr.pack_hash != shared_pack_hash) {
+ close(fd);
+ char b[256];
+ std::snprintf(b, sizeof b,
+ "shared arena %s was written for pack hash %016llx, expected %016llx",
+ shared_file.c_str(), (unsigned long long) hdr.pack_hash,
+ (unsigned long long) shared_pack_hash);
+ note = b;
+ return nullptr;
+ }
+ }
+
+ void* map = mmap(nullptr, (size_t) file_bytes, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
+ const int e = errno;
+ close(fd);
+ if (map == MAP_FAILED) {
+ note = "cannot map shared arena " + shared_file + ": " + std::strerror(e);
+ return nullptr;
+ }
+ mapping_base = map;
+ mapping_bytes = file_bytes;
+ got = PageBacking::NormalPages;
+ note = "MAP_SHARED file " + shared_file + " (pack hash checked)";
+ return (uint8_t*) map + kSharedArenaHeaderBytes;
+ }
+
void* p = mmap(nullptr, bytes, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_HUGE_2MB, -1, 0);
if (p != MAP_FAILED) {
@@ -129,6 +244,47 @@ rewrite this code.
bool clear_error() {(void)0; return true; }
} // namespace
+int arena_pin_cap_gib() {
+ const char* e = std::getenv("STRATA_ARENA_PIN_GIB");
+ if (e == nullptr || *e == '\0') return -1;
+ if (std::string(e) == "auto") return -2; // #243: the Windows shared-memory budget sets the sliced pin's cap
+ const int v = std::atoi(e);
+ return v < 0 ? -1 : v;
+}
+
+namespace {
+#ifdef _WIN32
+// #243: how much of the arena the sliced registration may pin on Windows when the whole arena was refused.
+// Page-locked memory the GPU maps is charged to its shared (non-local) WDDM segment; pinned slice by slice until
+// the driver refused one (28 GiB of a 63 GB PC), that segment was left full and every later cudaMalloc failed
+// "out of memory". 4 GiB of the budget stay free for what the engine allocates after the arena; without the DXGI
+// numbers, RAM/2 - 8 GiB (the budget is about half the RAM). False: no limit could be worked out.
+bool sliced_pin_limit(uint64_t& limit, std::string& why) {
+ constexpr uint64_t GiB = 1ull << 30;
+ char buf[256];
+ int dev = 0;
+ cudaDeviceProp p{};
+ uint64_t budget = 0, usage = 0;
+ std::string err = "no CUDA device properties";
+ if (cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess &&
+ strata::platform::gpu_shared_memory_budget(p.luid, budget, usage, err)) {
+ limit = budget > usage + 4 * GiB ? budget - usage - 4 * GiB : 0;
+ std::snprintf(buf, sizeof buf, "the GPU's shared-memory budget %.1f GiB - %.1f GiB in use - 4 GiB",
+ (double) budget / GiB, (double) usage / GiB);
+ why = buf;
+ return true;
+ }
+ (void) cudaGetLastError();
+ const uint64_t ram = strata::platform::total_physical_memory();
+ if (ram == 0) return false;
+ limit = ram / 2 > 8 * GiB ? ram / 2 - 8 * GiB : 0;
+ std::snprintf(buf, sizeof buf, "%s: RAM/2 - 8 GiB of %.1f GiB", err.c_str(), (double) ram / GiB);
+ why = buf;
+ return true;
+}
+#endif
+} // namespace
+
namespace {
std::vector<uint64_t> uniform_bounds(uint64_t bytes, uint64_t slice) {
std::vector<uint64_t> b;
@@ -144,15 +300,29 @@ PinnedArena::PinnedArena(uint64_t bytes, uint64_t slice) : PinnedArena(bytes, un
}
PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t> &bounds,
- uint64_t max_pinned_bytes) try
+ uint64_t max_pinned_bytes,
+ const std::string &shared_file,
+ uint64_t shared_pack_hash) try
: capacity(bytes) {
if (bytes == 0) return;
- base = reserve(bytes, backing, note);
+ base = reserve(bytes, backing, note, shared_file, shared_pack_hash, mapping_base, mapping_bytes);
+ if (base != nullptr && mapping_base == nullptr) {
+ mapping_base = base;
+ mapping_bytes = bytes;
+ }
// Register with CUDA BEFORE any page is touched: cudaHostRegister pins what is resident now, and a region
// that has already been faulted in page by page is far more expensive to register and may fail outright.
if (base) {
- const bool capped = max_pinned_bytes > 0 && max_pinned_bytes < bytes && bounds.size() >= 2;
+ // #243: STRATA_ARENA_PIN_GIB=N caps the registration from the start where the caller set no cap
+ const int env_gib = arena_pin_cap_gib();
+ uint64_t cap = max_pinned_bytes;
+ std::string cap_why = "by the engine (multi-GPU under WDDM, or remote experts)";
+ if (cap == 0 && env_gib > 0) {
+ cap = (uint64_t) env_gib << 30;
+ cap_why = "by STRATA_ARENA_PIN_GIB";
+ }
+ const bool capped = cap > 0 && cap < bytes && bounds.size() >= 2;
const dpct::err0 e =
capped ? 0 :
/*
@@ -169,9 +339,18 @@ PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t> &bounds,
// Plan v0.3 P5: the whole range is refused, so pin it slice by slice from the start. The rest stays
// resident through the working-set lock below. (P6: slices may differ in size, one per layer.)
slice_bytes = 1; // sliced; the uniform constructor records the size
+ bool limited = capped;
+ uint64_t limit = cap;
+ std::string limit_why;
+#ifdef _WIN32
+ // #243 (opt-in, STRATA_ARENA_PIN_GIB=auto): not up to the driver's refusal but below the shared-memory
+ // budget, for a PC where the full sliced pin leaves WDDM refusing later allocations. Not the default: a
+ // 64 GB PC pins 30 GiB past that budget without trouble, and capping it at 26 cost ~20% prompt speed.
+ if (!capped && env_gib == -2) limited = sliced_pin_limit(limit, limit_why);
+#endif
for (size_t i = 0; i + 1 < bounds.size(); ++i) {
const uint64_t off = bounds[i], n = bounds[i + 1] - bounds[i];
- if (capped && (off > max_pinned_bytes || n > max_pinned_bytes - off)) break;
+ if (limited && (off > limit || n > limit - off)) break;
/*
DPCT1027: The call to cudaHostRegister was replaced with 0
because SYCL currently does not support registering of existing
@@ -191,19 +370,26 @@ PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t> &bounds,
registered_bytes = off + n;
++registered_slices;
}
+ char gib[32];
+ std::snprintf(gib, sizeof gib, "%.1f", (double) limit / (double) (1ull << 30));
note =
- (capped ? "cudaHostRegister limited to " +
- std::to_string(max_pinned_bytes >> 30) +
- " GiB for CUDA1; "
- :
- /*
- 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.
- */
+ (capped
+ ? "cudaHostRegister limited to " +
+ std::to_string(cap >> 30) + " GiB " + cap_why + "; "
+ :
+ /*
+ 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.
+ */
"cudaHostRegister of the whole arena FAILED (" +
- std::string(dpct::get_error_string_dummy(e)) + "); ") +
+ std::string(dpct::get_error_string_dummy(e)) + "); " +
+ (limited ? "slices capped at " + std::string(gib) +
+ " GiB (" + limit_why +
+ "; STRATA_ARENA_PIN_GIB=auto; N sets a "
+ "cap; #243); "
+ : std::string())) +
std::to_string(registered_slices) + " slices pinned (" +
std::to_string(registered_bytes >> 30) + " GiB); " + note;
if (registered_bytes < bytes) {
@@ -281,8 +467,10 @@ PinnedArena::~PinnedArena() {
device.
*/
}
- release(base, capacity);
+ release(mapping_base ? mapping_base : base, mapping_bytes ? mapping_bytes : capacity);
base = nullptr;
+ mapping_base = nullptr;
+ mapping_bytes = 0;
}
}
diff --git a/sycl/src/core/session.cpp b/sycl/src/core/session.cpp
index 1b3bd7405..c4e7cf86d 100644
--- a/sycl/src/core/session.cpp
+++ b/sycl/src/core/session.cpp
@@ -52,13 +52,20 @@ static uint64_t ple_hist_bytes() {
return (uint64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM * sizeof(float);
}
-uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k) {
+uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k, int64_t layer_lo, int64_t layer_hi) {
+ if (layer_hi < 0 || layer_hi > g.n_layers) layer_hi = g.n_layers;
+ if (layer_lo < 0) layer_lo = 0;
+ // QSA layers are `l % interval == interval-1`, so exactly `bound / interval` of them live below `bound`
+ const int64_t I = std::max<int64_t>(g.qsa_interval, 1);
+ const int64_t q_lo = layer_lo / I, q_hi = layer_hi / I;
+ const int64_t q_n = std::max<int64_t>(q_hi - q_lo, g.n_qsa_layers() > 0 ? 1 : 0);
+ const int64_t gdn_n = std::max<int64_t>((layer_hi - layer_lo) - std::max<int64_t>(q_hi - q_lo, 0), 0);
uint64_t n = 0;
n += gdn_buffers_bytes(g);
- n += (uint64_t) g.n_gdn_layers() * gdn_state_floats(g) * 4;
+ n += (uint64_t) gdn_n * gdn_state_floats(g) * 4;
// One QSA state carries the RoPE table; the others borrow it (P7: 64 MiB per layer at 262K).
if (g.n_qsa_layers() > 0)
- n += qsa_state_bytes(g, max_cells, true) + (uint64_t) (g.n_qsa_layers() - 1) * qsa_state_bytes(g, max_cells, false);
+ n += qsa_state_bytes(g, max_cells, true) + (uint64_t) (q_n - 1) * qsa_state_bytes(g, max_cells, false);
n += qsa_buffers_bytes(g, max_cells);
n += moe_buffers_bytes(g, k);
n += block_buffers_bytes(g);
@@ -66,7 +73,10 @@ uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k) {
return align_up(n, SESSION_STATE_ALIGN) + 4096;
}
-uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void* base, SessionState& s) {
+uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void* base, SessionState& s,
+ int64_t layer_lo, int64_t layer_hi) {
+ if (layer_hi < 0 || layer_hi > g.n_layers) layer_hi = g.n_layers;
+ if (layer_lo < 0) layer_lo = 0;
uint8_t* p = (uint8_t*) base;
uint64_t used = 0;
auto take = [&](uint64_t bytes) {
@@ -77,24 +87,34 @@ uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void
s.max_cells = max_cells;
s.k = k;
+ s.layer_lo = layer_lo;
+ s.layer_hi = layer_hi;
+ const int64_t I = std::max<int64_t>(g.qsa_interval, 1);
+ const int64_t q_n_range = layer_hi / I - layer_lo / I;
+ s.qsa_ord0 = layer_lo / I;
+ s.qsa_alloc = std::max<int64_t>(q_n_range, g.n_qsa_layers() > 0 ? 1 : 0);
+ s.gdn_ord0 = layer_lo - layer_lo / I;
+ s.gdn_alloc = std::max<int64_t>((layer_hi - layer_lo) - q_n_range, 0);
gdn_buffers_init(g, take(gdn_buffers_bytes(g)), s.gdn);
- s.gdn_state = (float*) take((uint64_t) g.n_gdn_layers() * gdn_state_floats(g) * 4);
+ s.gdn_state = (float*) take((uint64_t) s.gdn_alloc * gdn_state_floats(g) * 4);
- // the 12 QSA states are separate allocations carved from one arena, because `QsaState` is a struct of
+ // the QSA states are separate allocations carved from one arena, because `QsaState` is a struct of
// pointers and `qsa_state_init` writes them - a contiguous array would need the arena to be laid out the
- // same way, which is a coupling with nothing to gain.
+ // same way, which is a coupling with nothing to gain. Only the range's ordinals are initialized; the
+ // rest stay value-initialized nulls. The FIRST ALLOCATED one (the session's primary, ordinal qsa_ord0)
+ // owns the RoPE table that the others - and the prefill staging identity, and the MTP drafter - borrow.
const uint64_t first = qsa_state_bytes(g, max_cells, true), rest = qsa_state_bytes(g, max_cells, false);
- s.qsa_state_arena = take(g.n_qsa_layers() > 0 ? first + (uint64_t) (g.n_qsa_layers() - 1) * rest : 0);
- s.qsa_states = new QsaState[(size_t) g.n_qsa_layers()];
+ s.qsa_state_arena = take(g.n_qsa_layers() > 0 ? first + (uint64_t) (s.qsa_alloc - 1) * rest : 0);
+ s.qsa_states = new QsaState[(size_t) g.n_qsa_layers()]();
s.qsa_buf_arena = take(qsa_buffers_bytes(g, max_cells));
uint8_t* qp = (uint8_t*) s.qsa_state_arena;
// a layer whose pinned RAM could not be had (KV streaming's host copy) is half-built: going on would have the
// attention read null host pointers at the first request ("illegal memory access"), so the session fails here
- for (int64_t i = 0; i < g.n_qsa_layers(); ++i)
- if (qsa_state_init(g, max_cells, qp + (i == 0 ? 0 : first + (uint64_t) (i - 1) * rest), s.qsa_states[i],
- i == 0 ? nullptr : &s.qsa_states[0]) == 0)
+ for (int64_t j = 0; j < s.qsa_alloc; ++j)
+ if (qsa_state_init(g, max_cells, qp + (j == 0 ? 0 : first + (uint64_t) (j - 1) * rest),
+ s.qsa_states[s.qsa_ord0 + j], j == 0 ? nullptr : &s.qsa_states[s.qsa_ord0]) == 0)
return 0;
qsa_buffers_init(g, max_cells, s.qsa_buf_arena, s.qsa_bufs);
@@ -126,11 +146,10 @@ void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init,
} else {
cs->memset(s.block.R, 0, (size_t)g.hc * g.n_embd * 4);
}
- // every GDN layer's recurrence and conv history
- cs->memset(s.gdn_state, 0,
- (size_t)g.n_gdn_layers() * gdn_state_floats(g) * 4);
- // and every QSA layer's cache and indexer
- for (int64_t i = 0; i < g.n_qsa_layers(); ++i) qsa_state_zero(s.qsa_states[i], g, stream);
+ // every owned GDN layer's recurrence and conv history
+ cs->memset(s.gdn_state, 0, (size_t)s.gdn_alloc * gdn_state_floats(g) * 4);
+ // and every owned QSA layer's cache and indexer
+ for (int64_t j = 0; j < s.qsa_alloc; ++j) qsa_state_zero(s.qsa_states[s.qsa_ord0 + j], g, stream);
// **AND THE PLE'S CONV HISTORY AND TOKEN WINDOW.** A sequence that started with a warm history would
// convolve over rows belonging to a different sequence - the conv reads NG_HIST previous NORMALIZED rows,
// so a stale one is a real contribution and not a zero. The token window resets to `NG_HIST`-many nulls
@@ -148,7 +167,7 @@ void gdn_point_at(const ModelGeometry& g, int64_t layer, SessionState& s) {
if (is_qsa_layer(g, layer)) return;
int64_t gdn_index = 0;
for (int64_t l = 0; l < layer; ++l) if (!is_qsa_layer(g, l)) ++gdn_index;
- s.gdn.state = s.gdn_state + (size_t) gdn_index * gdn_state_floats(g);
+ s.gdn.state = s.gdn_state + (size_t) (gdn_index - s.gdn_ord0) * gdn_state_floats(g);
s.gdn.conv_state = s.gdn.state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
}
@@ -161,42 +180,46 @@ void stage_token(const ModelGeometry& g, int64_t pos, int32_t pos_base, SessionS
sh.head_dim = g.head_dim;
sh.idx_n_head = g.idx_q_heads;
sh.idx_dim = g.idx_key_dim;
- for (int64_t i = 0; i < g.n_qsa_layers(); ++i) {
- QsaState& q = s.qsa_states[i];
+ for (int64_t j = 0; j < s.qsa_alloc; ++j) {
+ QsaState& q = s.qsa_states[s.qsa_ord0 + j];
qsa_step_fill(q.host_step, pos, sh);
for (int64_t h = 0; h < g.n_head; ++h) q.host_pos[h] = (int32_t) (pos_base + pos);
}
}
bool session_capture(const WeightTable& tables, const ModelGeometry& g, SessionState& s, const float* parts,
- SessionGraphs& gr, std::string& err, bool split) {
+ SessionGraphs& gr, std::string& err, bool split, int64_t layer_lo, int64_t layer_hi) {
if (gr.captured) return true;
+ if (layer_hi < 0 || layer_hi > g.n_layers) layer_hi = g.n_layers;
+ if (layer_lo < 0) layer_lo = 0;
gr.execs =
- new dpct::experimental::command_graph_exec_ptr[(size_t)g.n_layers];
+ new dpct::experimental::command_graph_exec_ptr[(size_t)g.n_layers]();
gr.posts =
- new dpct::experimental::command_graph_exec_ptr[(size_t)g.n_layers];
+ new dpct::experimental::command_graph_exec_ptr[(size_t)g.n_layers]();
for (int64_t i = 0; i < g.n_layers; ++i) gr.posts[i] = nullptr;
if (split) {
gr.preA =
- new dpct::experimental::command_graph_exec_ptr[(size_t)g.n_layers];
+ new dpct::experimental::command_graph_exec_ptr[(size_t)
+ g.n_layers]();
gr.preB =
- new dpct::experimental::command_graph_exec_ptr[(size_t)g.n_layers];
+ new dpct::experimental::command_graph_exec_ptr[(size_t)
+ g.n_layers]();
for (int64_t i = 0; i < g.n_layers; ++i) { gr.preA[i] = nullptr; gr.preB[i] = nullptr; }
for (int k = 0; k < 5; ++k) {
gr.preP[k] =
- new dpct::experimental::command_graph_exec_ptr[(size_t)
- g.n_layers];
+ new dpct::experimental::command_graph_exec_ptr[(size_t)g
+ .n_layers]();
for (int64_t i = 0; i < g.n_layers; ++i) gr.preP[k][i] = nullptr;
}
}
gr.split_captured = split;
gr.n = 0;
- int64_t qsa_index = 0;
- for (int64_t l = 0; l < g.n_layers; ++l) {
+ int64_t qsa_index = s.qsa_ord0;
+ for (int64_t l = layer_lo; l < layer_hi; ++l) {
gdn_point_at(g, l, s);
const bool qsa = is_qsa_layer(g, l);
- QsaState& qst = qsa ? s.qsa_states[qsa_index] : s.qsa_states[0];
+ QsaState& qst = qsa ? s.qsa_states[qsa_index] : s.qsa_states[s.qsa_primary()];
// **TWO GRAPHS PER LAYER, SPLIT AT THE ROUTER.** `pre` ends with the doorbell rung; the host then runs
// the CPU pool on what it published; `post` combines those experts with THIS layer's weights. Capturing
@@ -1340,8 +1363,8 @@ bool session_run_token(const ModelGeometry &g, int64_t pos, int32_t pos_base,
err = "session_run_token: layer " + std::to_string(l) +
" never rang (" +
/*
- DPCT1009: SYCL reports errors using exceptions and
- does not use error codes. Please replace the
+ 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.
*/
diff --git a/sycl/src/core/verify.cpp b/sycl/src/core/verify.cpp
index 5e8f933de..1fdb4e07b 100644
--- a/sycl/src/core/verify.cpp
+++ b/sycl/src/core/verify.cpp
@@ -41,6 +41,7 @@
#include <atomic>
#include <map>
#include <string>
+#include <thread>
#include <vector>
#include <chrono>
#include <cmath>
@@ -119,13 +120,65 @@ std::atomic<const Verifier*> g_diag_verifier{nullptr};
void diag_active_verifier(std::FILE* f) {
if (const Verifier* v = g_diag_verifier.load()) v->diag(f);
}
+// #267: every live verifier (a layer split has one per stage), for the release before the engine ends
+constexpr int kLiveMax = 16;
+std::atomic<Verifier*> g_live[kLiveMax];
+void release_live_verifiers(std::FILE* f) {
+ for (auto& slot : g_live)
+ if (Verifier* v = slot.load()) {
+ const Clock::time_point t0 = Clock::now();
+ const bool done = v->release_gpu_waits(5000);
+ if (f != nullptr)
+ std::fprintf(f, "strata: released the verify window's GPU waits (#267): the GPU %s\n",
+ done ? ("finished in " + std::to_string((long long) ms_since(t0)) + " ms").c_str()
+ : "did not finish within 5 s");
+ }
+ if (f != nullptr) std::fflush(f);
+}
+std::string released_note(bool drained) {
+ return drained ? "; its GPU waits were released and the GPU finished (#267)"
+ : "; its GPU waits were released but the GPU did not finish within 5 s (#267)";
+}
+// #267 test hook: STRATA_TEST_VERIFY_STALL=N withholds the last layer's flag in the N-th window (1-based), so the
+// GPU spins on a flag nobody raises - the bounded window wait and the release are then what ends it. Unset: never.
+const int64_t g_test_stall = [] {
+ const char* e = std::getenv("STRATA_TEST_VERIFY_STALL");
+ return e != nullptr ? (int64_t) std::atoll(e) : (int64_t) 0;
+}();
} // namespace
+bool Verifier::release_gpu_waits(int timeout_ms) try {
+ released_.store(true);
+ // the words the spin kernels read (wait_flag_ge, wait_flag_ge_or) are mapped host memory, so a store here
+ // reaches them with no API call; UINT32_MAX is past every ring. (E-6's skip words are device memory, but
+ // wait_flag_ge_or also returns on its flag.) A host function raising flag B later only raises.
+ for (uint32_t* p : {h_flag_, h_flagA_, h_flagB_})
+ if (p != nullptr) *(volatile uint32_t*) p = UINT32_MAX;
+ std::atomic_thread_fence(std::memory_order_seq_cst);
+ _mm_sfence();
+ const OnDevice on_device(device_);
+ const Clock::time_point t0 = Clock::now();
+ // SYCL port: no cudaStreamQuery; a queue with nothing left to run reports ext_oneapi_empty()
+ for (dpct::queue_ptr q : {cs_, copy_}) {
+ if (q == nullptr) continue;
+ while (!q->ext_oneapi_empty()) {
+ if (ms_since(t0) > timeout_ms) return false;
+ std::this_thread::sleep_for(std::chrono::milliseconds(1));
+ }
+ }
+ return true;
+} catch (...) {
+ return false; // the runtime may already be tearing down (the watchdog's path ends the engine)
+}
+
void Verifier::diag(std::FILE* f) const {
auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; };
- std::fprintf(f, " verify window: %d tokens at position %lld, host at layer step %u; the GPU rang %u; flags: "
- "served %u, plan (A) %u, copies (B) %u\n", last_t_, (long long) last_pos0_, cur_layer_ + 1,
- rd(h_seq_), rd(h_flag_), rd(h_flagA_), rd(h_flagB_));
+ // #251: outside a verify stage these are the LAST window's numbers (it finished), not the stalled work's
+ const char* where = progress().where.load();
+ const bool current = where != nullptr && std::strncmp(where, "verify window", 13) == 0;
+ std::fprintf(f, " verify window%s: %d tokens at position %lld, host at layer step %u; the GPU rang %u; flags: "
+ "served %u, plan (A) %u, copies (B) %u\n", current ? "" : " (last window, not the current stage)",
+ last_t_, (long long) last_pos0_, cur_layer_ + 1, rd(h_seq_), rd(h_flag_), rd(h_flagA_), rd(h_flagB_));
}
Verifier::~Verifier() try {
@@ -133,6 +186,10 @@ Verifier::~Verifier() try {
// that throws aborts the process (exit 139); the waits and frees below are best-effort then.
const Verifier* self = this;
g_diag_verifier.compare_exchange_strong(self, nullptr);
+ for (auto& slot : g_live) {
+ Verifier* me = this;
+ slot.compare_exchange_strong(me, nullptr);
+ }
if (cs_) cs_->wait();
for (auto& e : exec_)
if (e) delete (e);
@@ -155,6 +212,11 @@ bool Verifier::init(const WeightTable &wt, const ModelGeometry &g,
const NativeHead *head, int max_t, std::string &err) try {
g_diag_verifier.store(this);
diag_verify_fn().store(&diag_active_verifier);
+ for (auto& slot : g_live) {
+ Verifier* none = nullptr;
+ if (slot.load() == this || slot.compare_exchange_strong(none, this)) break;
+ }
+ release_gpu_fn().store(&release_live_verifiers);
device_ = dpct::get_current_device_id(); // a layer split's stage on another
// GPU: its streams, graphs and
// buffers live there
@@ -197,7 +259,7 @@ bool Verifier::init(const WeightTable &wt, const ModelGeometry &g,
const strata::kernels::QsaShapes s = shapes_of(g);
cap_ = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);
- max_blocks_ = ss.qsa_states[0].max_cells / s.idx_block + 2;
+ max_blocks_ = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2;
attn_scratch_floats_ = (int64_t) strata::kernels::qsa_decode_attn_scratch_floats(cap_, s);
const uint64_t T = (uint64_t) max_t, N = (uint64_t) g.n_embd, HC = (uint64_t) g.hc, K = (uint64_t) ss.k;
@@ -526,7 +588,7 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {
!native_of(wout, v.name("ssm_out.weight"), err))
return false;
const int64_t gi = gdn_idx[(size_t) l];
- float* state = ss.gdn_state + (size_t) gi * gdn_floats;
+ float* state = ss.gdn_state + (size_t) (gi - ss.gdn_ord0) * gdn_floats;
float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
float* qkv = qkv_L_ + (size_t) gi * MT * C;
float* hb = h_L_ + (size_t) gi * MT * C;
@@ -565,7 +627,7 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {
auto norm_rope = [&](float* data, const WeightRef* norm, int rows, int cols, const int32_t* pos) {
if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, EPS, cs);
else rms_norm_weighted(data, (const float*) norm->data, rows, cols, EPS, cs);
- if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, (float) qsa_freq_base(), pos, cs);
+ if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), pos, cs);
else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, pos, cs);
};
float* idx_raw = idx_raw_L_ + (size_t) qi * MT * ID;
@@ -610,7 +672,7 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {
for (int t = tb; t < te; ++t)
native_qsa_indexer_append(idx_raw + t * ID, step_ + t * kStepCount + kStepPos, 0,
(const float*) wikn->data, EPS, ib, s, st.max_cells,
- (float) qsa_freq_base(), cs);
+ rope_scaling(), cs);
stamp(l, 9, grp);
native_mmvq(wq->native_type, wq->native_data, xq_, qfull_ + tb * NH * 2 * HD, (int) N, (int) (NH * 2 * HD),
n, cs);
@@ -1040,7 +1102,7 @@ bool Verifier::capture_commit(std::string &err) try {
if (!is_qsa_layer(g, l)) {
const WeightRef* wnm = need(v, "ssm_norm.weight", err);
if (!wnm) { ok = false; break; }
- float* state = ss.gdn_state + (size_t) gdn_index * gdn_floats;
+ float* state = ss.gdn_state + (size_t) (gdn_index - ss.gdn_ord0) * gdn_floats;
float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
const float* qkv = qkv_L_ + (size_t) gdn_index * MT * C;
gdn_conv_commit(conv, qkv, (int) C, commit_, cs_);
@@ -1057,7 +1119,7 @@ bool Verifier::capture_commit(std::string &err) try {
for (int64_t t = 0; t < MT; ++t)
native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + t) * ID, commit_ + 2 + t, 0,
(const float*) wikn->data, EPS, ib, s, st.max_cells,
- (float) qsa_freq_base(), cs_);
+ rope_scaling(), cs_);
++qsa_index;
}
}
@@ -1104,7 +1166,8 @@ bool Verifier::run(int T, const int32_t *tokens, int64_t pos0, PoolMultiFn pool,
if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; }
const ModelGeometry& g = *g_;
SessionState& ss = *ss_;
- if (pos0 + T > ss.qsa_states[0].max_cells) { err = "verify: the window runs past the context"; return false; }
+ if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }
+ if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; }
if (!capture(T, err) || !capture_commit(err)) return false;
VDBG("captured; staging\n");
const Clock::time_point t0 = Clock::now();
@@ -1171,7 +1234,9 @@ bool Verifier::run(int T, const int32_t *tokens, int64_t pos0, PoolMultiFn pool,
// so waiting on them per layer fails. STRATA_VERIFY_NO_HOST=1 waits for the whole window instead. Only for
// an all-resident cache: a missed expert would leave the GPU waiting for a plan that never comes.
static const bool no_host = std::getenv("STRATA_VERIFY_NO_HOST") != nullptr;
- for (int64_t k = 0; !no_host && k < (le_ - lb_) * G; ++k) {
+ const int64_t steps = (le_ - lb_) * G;
+ const bool test_stall = g_test_stall > 0 && windows + 1 == g_test_stall; // #267 test hook (off: false)
+ for (int64_t k = 0; !no_host && k < steps; ++k) {
const int64_t l = lb_ + k / G;
const int grp = (int) (k % G);
const uint32_t want = (uint32_t) (k + 1);
@@ -1203,7 +1268,11 @@ bool Verifier::run(int T, const int32_t *tokens, int64_t pos0, PoolMultiFn pool,
return false;
}
}
- if (now - a > std::chrono::seconds(20)) { err = "verify: timed out at layer " + std::to_string(l); return false; }
+ if (now - a > std::chrono::seconds(20)) {
+ // #267: the caller ends the engine; no spin kernel may outlive it
+ err = "verify: timed out at layer " + std::to_string(l) + released_note(release_gpu_waits(5000));
+ return false;
+ }
}
const Clock::time_point b = Clock::now();
VDBG("layer %lld rang\n", (long long) l);
@@ -1228,11 +1297,14 @@ bool Verifier::run(int T, const int32_t *tokens, int64_t pos0, PoolMultiFn pool,
*(volatile uint32_t*) h_flagA_ = want;
raise_flag(h_flagB_, want);
}
- *flag = want;
+ if (!(test_stall && k + 1 == steps)) *flag = want;
ms_wait += std::chrono::duration<double, std::milli>(b - a).count();
ms_pool += ms_since(b);
}
progress_at("verify window: waiting for the GPU to finish the window (flags A/B/M raised)", (int64_t) T);
+ // #267: a window the GPU never finishes (a spin kernel that never sees its flag) holds the host here; the stall
+ // watchdog then releases every verifier's GPU waits (release_live_verifiers) before it ends the engine, so no
+ // spin kernel outlives the process. The wait itself stays a blocking sync (a polling wait cost decode upstream).
const dpct::err0 se = DPCT_CHECK_ERROR(cs_->wait());
if (std::getenv("STRATA_VERIFY_DEBUG") != nullptr) {
const Clock::time_point t_done = Clock::now();
@@ -1460,6 +1532,47 @@ void Verifier::publish_plan(void* ctx) {
*(volatile uint32_t*) v->h_flagA_ = v->cur_layer_ + 1;
}
+bool Verifier::window_logprobs(const int32_t* targets, int T, int64_t pos0, int32_t extra_id, std::FILE* out,
+ std::string& err) try {
+ if (next_ != nullptr) return next_->window_logprobs(targets, T, pos0, extra_id, out, err);
+ const OnDevice on_device(device_);
+ if (head_logits_ == nullptr || n_vocab_ <= 0 || T <= 0 || targets == nullptr || out == nullptr) {
+ err = "window_logprobs: no head logits for this window";
+ return false;
+ }
+ // run() synchronized cs_ before returning, so the head of this window is complete
+ std::vector<float> h((size_t) T * (size_t) n_vocab_);
+ cs_->memcpy(h.data(), head_logits_, h.size() * sizeof(float)).wait();
+ for (int t = 0; t < T; ++t) {
+ const float* row = h.data() + (size_t) t * (size_t) n_vocab_;
+ const int32_t tgt = targets[t];
+ if (tgt < 0 || (int64_t) tgt >= n_vocab_) continue;
+ int64_t top = 0;
+ for (int64_t v = 1; v < n_vocab_; ++v)
+ if (row[v] > row[top]) top = v;
+ const double maxv = row[top];
+ const bool has_extra = extra_id >= 0 && (int64_t) extra_id < n_vocab_;
+ double sum = 0.0, sum_without = 0.0; // the second skips extra_id: no cancellation when it holds ~all mass
+ for (int64_t v = 0; v < n_vocab_; ++v) {
+ const double e = std::exp((double) row[v] - maxv);
+ sum += e;
+ if (v != (int64_t) extra_id) sum_without += e;
+ }
+ const double lse = maxv + std::log(sum);
+ const double extra = has_extra ? (double) row[extra_id] - lse : NAN;
+ const double without = has_extra && tgt != extra_id && sum_without > 0.0
+ ? (double) row[tgt] - (maxv + std::log(sum_without)) : NAN;
+ std::fprintf(out, "%lld\t%d\t%.9f\t%lld\t%.9f\t%d\t%.9f\t%.9f\n", (long long) (pos0 + t), (int) tgt,
+ (double) row[tgt] - lse, (long long) top, maxv - lse, (int) (top == (int64_t) tgt), extra,
+ without);
+ }
+ std::fflush(out);
+ return true;
+} catch (sycl::exception const& e) {
+ err = std::string("window_logprobs: ") + e.what();
+ return false;
+}
+
bool Verifier::commit(int n_keep, std::string &err, bool wait) try {
const OnDevice on_device(device_);
if (n_keep < 1 || n_keep > last_t_) { err = "verify: commit count out of range"; return false; }
diff --git a/sycl/src/kernels/cuda/elementwise.dp.cpp b/sycl/src/kernels/cuda/elementwise.dp.cpp
index 731c6fbd1..ea4de6bd0 100644
--- a/sycl/src/kernels/cuda/elementwise.dp.cpp
+++ b/sycl/src/kernels/cuda/elementwise.dp.cpp
@@ -5,6 +5,7 @@
#include "strata/sycl_queue.hpp"
#include "strata/sycl_doorbell.hpp"
#include "strata/kernels/elementwise.hpp"
+#include "strata/kernels/dp4a.hpp"
#include "strata/kernels/bf16_bits.hpp"
#include "strata/kernels/f16_bits.hpp"
@@ -12,7 +13,6 @@
#include <cmath>
#include <cstdio>
#include <cstdlib>
-#include <time.h>
namespace strata::kernels {
namespace {
@@ -363,6 +363,10 @@ void silu_inplace(float* x, int64_t n, void* stream) {
/// the write was not ordered into host-visible memory, so no amount of reading it would show it, and the driver
/// call was flushing the whole pipeline enough to make it appear. A 10-22 us driver call per iteration is a
/// very expensive substitute for one fence instruction.
+///
+/// **THE STORE IS VOLATILE**, like `doorbell_publish_kernel`'s. On RDNA4 (gfx1201) a plain store to mapped pinned
+/// memory stays in the GPU's L2 until the stream is synchronized - the host never saw the ring (tests/hip/handoff:
+/// 0 of 100 rings seen without a sync; volatile, a system-scope atomic store or a fence after the store: 100 of 100).
__dpct_inline__ void doorbell_ring_kernel(uint32_t *seq) {
/*
DPCT1078: Consider replacing memory_order::acq_rel with
@@ -376,12 +380,7 @@ __dpct_inline__ void doorbell_ring_kernel(uint32_t *seq) {
__dpct_inline__ void doorbell_wait_kernel(const volatile uint32_t *flag,
const volatile uint32_t *seq) {
const uint32_t want = strata::sys_load(seq);
- /*
- DPCT1008: __nanosleep function is not defined in SYCL. This is a
- hardware-specific feature. Consult with your hardware vendor to find a
- replacement.
- */
- for (uint32_t spin = 0; spin < strata::kSpinMax && strata::sys_load(flag) != want; ++spin) {}
+ for (uint32_t spin = 0; spin < strata::kSpinMax && strata::sys_load(flag) != want; ++spin) strata_spin_pause();
/*
DPCT1078: Consider replacing memory_order::acq_rel with
memory_order::seq_cst for correctness if strong memory order restrictions
diff --git a/sycl/src/kernels/cuda/fused_gr.dp.cpp b/sycl/src/kernels/cuda/fused_gr.dp.cpp
index 5e17d4df8..3421c8398 100644
--- a/sycl/src/kernels/cuda/fused_gr.dp.cpp
+++ b/sycl/src/kernels/cuda/fused_gr.dp.cpp
@@ -373,8 +373,17 @@ bool gr_norm_split() { // default; STRATA_GR_NORM_SPLIT=0: one work-group per
}
// Step 2 of `gr_down_kernel` for T tokens. One warp per row (so each lane accumulates the same chunks in the
-// same order as the single-token kernel); per tile the lane's 10 weight chunks are loaded BEFORE the activation
+// same order as the single-token kernel); per tile the lane's weight chunks are loaded BEFORE the activation
// tile is staged, so the DRAM and L2 traffic are in flight together.
+//
+// TILEV = xn floats per token staged at a time. The tile only changes the staging granularity: the lane's chunk
+// order (lane + 32*q within the tile, tiles ascending) is strictly increasing for either value, so the results are
+// bitwise identical to `gr_down_kernel` for both. 2560 stages 320 chunks of 8 per tile (10 per lane); cards whose
+// opt-in below 8 * 2560 * 4 B slices the tokens - sm_75 (64 KiB) carries 6 tokens of it - run TILEV 1280 instead,
+// which fits all eight tokens in one 40 KiB launch and stages 160 chunks of 8 (5 per lane, half the registers held
+// for the weight prefetch); smaller tiles raise how many blocks share an SM (the 41-block grid), e.g. three blocks
+// of four tokens instead of one on sm_75.
+template <int TILEV>
/*
DPCT1110: The total declared local variable size in device function
gr_down_multi_kernel exceeds 128 bytes and may cause high register pressure.
@@ -383,7 +392,8 @@ adjust the code, or use smaller sub-group size to avoid high register pressure.
*/
__dpct_inline__ void gr_down_multi_kernel(GrMulti m, uint8_t *dpct_local) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
- auto tile = (float *)dpct_local; // [T][TILE]
+ constexpr int TQ = TILEV / 8 / 32; // uint4 weight chunks per lane per tile
+ auto tile = (float *)dpct_local; // [T][TILEV]
const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
const int T = m.T;
const int gid = (int) item_ct1.get_group(2);
@@ -396,7 +406,7 @@ __dpct_inline__ void gr_down_multi_kernel(GrMulti m, uint8_t *dpct_local) {
float acc[kFusedGrMaxT];
#pragma unroll
for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f;
- for (int base = inject_block ? 0 : split * TILE; base < D; base += inject_block ? TILE : TILE * DOWN_SPLIT) {
+ for (int base = inject_block ? 0 : split * TILEV; base < D; base += inject_block ? TILEV : TILEV * DOWN_SPLIT) {
sycl::uint4 wv[TQ];
if (active) {
#pragma unroll
@@ -421,8 +431,8 @@ __dpct_inline__ void gr_down_multi_kernel(GrMulti m, uint8_t *dpct_local) {
item_ct1.barrier(); // the previous tile is consumed
const sycl::float4 *src4 = reinterpret_cast<const sycl::float4 *>(m.xn);
sycl::float4 *tile4 = reinterpret_cast<sycl::float4 *>(tile);
- for (int i = t; i < T * (TILE / 4); i += THREADS) {
- const int k = i / (TILE / 4), off = i - k * (TILE / 4);
+ for (int i = t; i < T * (TILEV / 4); i += THREADS) {
+ const int k = i / (TILEV / 4), off = i - k * (TILEV / 4);
tile4[i] = src4[((size_t) k * D + base) / 4 + off];
}
/*
@@ -441,7 +451,7 @@ __dpct_inline__ void gr_down_multi_kernel(GrMulti m, uint8_t *dpct_local) {
const int j = lane + 32 * q;
#pragma unroll
for (int k = 0; k < kFusedGrMaxT; ++k)
- if (k < T) acc[k] += dot8(wv[q], tile + k * TILE + j * 8);
+ if (k < T) acc[k] += dot8(wv[q], tile + k * TILEV + j * 8);
}
}
if (!active) return;
@@ -682,6 +692,266 @@ auto &lo = *sycl::ext::oneapi::group_local_memory_for_overwrite<
}
}
+
+// ================================ hc read v3 (opt-in: STRATA_GR_V3=1) - two kernels, stream-split ================
+// The norm kernel runs on only T blocks (~16 us of pure latency per call) and `down` on 41 blocks (~280 GB/s).
+// v3: `down` is split over (row group, stream[, column half]) = 164 or 328 blocks; each block stages its slice of
+// R' * w_norm for the T tokens, reduces that slice's sum of squares itself, and writes UNSCALED partial dots. The
+// rms scale is per stream, so w_down . xn = sum_c rs[c] * (w_down[:, c] . (R'[c] * w_norm[c])) - `up` applies it
+// in its prologue (lo, inject, rs). Same maths, ANOTHER SUMMATION ORDER: not bitwise the default kernels, hence
+// opt-in. Dynamic shared memory is T * (N / S) floats: S (1 or 2 column halves) is the smallest that fits the
+// card's opt-in limit at kFusedGrMaxT tokens (Ampere 99 KB: S = 1; Turing / HIP 64 KB: S = 2); a card where
+// neither fits keeps the default kernels.
+constexpr int PR = LR + HC; // partial rows per (token, stream): 320 down + 4 inject
+constexpr int TQ3 = N / 8 / 32; // uint4 weight chunks per lane in one stream's slice (10)
+
+template <int S>
+/*
+DPCT1110: The total declared local variable size in device function
+gr_down_v3_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 gr_down_v3_kernel(GrMulti m, float *__restrict__ part,
+ float *__restrict__ ssg,
+ uint8_t *dpct_local) {
+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
+ auto xs = (float *)dpct_local; // [T][N / S]
+ constexpr int R2 = 1; // down rows per warp
+ auto &red = *sycl::ext::oneapi::group_local_memory_for_overwrite<
+ float[WARPS][kFusedGrMaxT]>(
+ sycl::ext::oneapi::this_work_item::get_work_group<3>());
+ const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
+ const int T = m.T;
+ // S = 2: each stream's 2560 columns in two halves (blockIdx.y = stream * S + half): twice the blocks
+ constexpr int SL = N / S, TQS = SL / 8 / 32;
+ const int rg = item_ct1.get_group(2), c = item_ct1.get_group(1) / S,
+ h = item_ct1.get_group(1) - (item_ct1.get_group(1) / S) * S;
+ constexpr int NDB = LR / (WARPS * R2); // down row blocks per stream; block NDB = the inject rows
+ const bool inject_block = rg == NDB;
+ // warp w owns rows row0 + w * R2 + r (r < R2); the inject block: warps 0-3, one row each
+ const int row0 = inject_block ? warp : (rg * WARPS + warp) * R2;
+ const int nrows = inject_block ? ((m.a[0].w_inject != nullptr && warp < HC) ? 1 : 0) : R2;
+ const bool active = nrows > 0;
+ const uint16_t* wbase = inject_block ? m.a[0].w_inject : m.a[0].w_down;
+ sycl::uint4 wv[R2][TQS];
+#pragma unroll
+ for (int r = 0; r < R2; ++r) {
+ if (r >= nrows) break;
+ const sycl::uint4 *w4 = reinterpret_cast<const sycl::uint4 *>(
+ wbase + (size_t)(row0 + r) * D + (size_t)c * N + (size_t)h * SL);
+#pragma unroll
+ /*
+ DPCT1098: The '*' expression is used instead of the __ldg call.
+ These two expressions do not provide the exact same functionality. Check
+ the generated code for potential precision and/or performance issues.
+ */
+ for (int q = 0; q < TQS; ++q) wv[r][q] = *(w4 + lane + 32 * q);
+ }
+ float ssp[kFusedGrMaxT];
+#pragma unroll
+ for (int k = 0; k < kFusedGrMaxT; ++k) {
+ ssp[k] = 0.0f;
+ if (k >= T) continue;
+ const FusedGrArgs& a = m.a[k];
+ const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f;
+ const sycl::float4 *R4 = reinterpret_cast<const sycl::float4 *>(
+ a.R + (size_t)c * N + (size_t)h * SL);
+ const sycl::float4 *G4 = reinterpret_cast<const sycl::float4 *>(
+ a.w_norm + (size_t)c * N + (size_t)h * SL);
+ const sycl::float4 *B4 =
+ reinterpret_cast<const sycl::float4 *>(a.bo_prev + (size_t)h * SL);
+ sycl::float4 *X4 =
+ reinterpret_cast<sycl::float4 *>(xs + (size_t)k * SL);
+ for (int i = t; i < SL / 4; i += THREADS) {
+ sycl::float4 r = R4[i];
+ if (a.apply) {
+ const sycl::float4 b = B4[i];
+ r.x() = sycl::fma((float)(b.x()), (float)gw, r.x());
+ r.y() = sycl::fma((float)(b.y()), (float)gw, r.y());
+ r.z() = sycl::fma((float)(b.z()), (float)gw, r.z());
+ r.w() = sycl::fma((float)(b.w()), (float)gw, r.w());
+ }
+ const sycl::float4 g = G4[i];
+ ssp[k] +=
+ r.x() * r.x() + r.y() * r.y() + r.z() * r.z() + r.w() * r.w();
+ X4[i] = sycl::float4(r.x() * g.x(), r.y() * g.y(), r.z() * g.z(),
+ r.w() * g.w());
+ }
+ }
+#pragma unroll
+ for (int k = 0; k < kFusedGrMaxT; ++k) {
+ if (k >= T) break;
+ const float v = warp_sum(ssp[k]);
+ if (lane == 0) red[warp][k] = v;
+ }
+ /*
+ DPCT1065: Consider replacing sycl::nd_item::barrier() with
+ sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
+ performance if there is no access to global memory.
+ */
+ item_ct1.barrier();
+ if (rg == 0 && t < T) {
+ float sum = 0.0f;
+#pragma unroll
+ for (int w = 0; w < WARPS; ++w) sum += red[w][t];
+ ssg[(t * HC + c) * S + h] = sum;
+ }
+ if (!active) return;
+#pragma unroll
+ for (int r = 0; r < R2; ++r) {
+ if (r >= nrows) break;
+ float acc[kFusedGrMaxT];
+#pragma unroll
+ for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f;
+#pragma unroll
+ for (int q = 0; q < TQS; ++q) {
+ const int j = lane + 32 * q;
+#pragma unroll
+ for (int k = 0; k < kFusedGrMaxT; ++k)
+ if (k < T) acc[k] += dot8(wv[r][q], xs + (size_t) k * SL + j * 8);
+ }
+ const int prow = inject_block ? LR + warp : row0 + r;
+#pragma unroll
+ for (int k = 0; k < kFusedGrMaxT; ++k) {
+ if (k >= T) break;
+ const float v = warp_sum(acc[k]);
+ if (lane == 0) part[(((size_t) k * HC + c) * S + h) * PR + prow] = v;
+ }
+ }
+}
+
+template <int S>
+/*
+DPCT1110: The total declared local variable size in device function
+gr_up_v3_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 gr_up_v3_kernel(GrMulti m, const float *__restrict__ part,
+ const float *__restrict__ ssg) {
+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
+auto &lo = *sycl::ext::oneapi::group_local_memory_for_overwrite<
+ float[kFusedGrMaxT][LR]>(
+ sycl::ext::oneapi::this_work_item::get_work_group<3>());
+ auto &rsS = *sycl::ext::oneapi::group_local_memory_for_overwrite<
+ float[kFusedGrMaxT][HC]>(
+ sycl::ext::oneapi::this_work_item::get_work_group<3>());
+ auto &g = *sycl::ext::oneapi::group_local_memory_for_overwrite<
+ float[kFusedGrMaxT][HC][UPM_COLS]>(
+ sycl::ext::oneapi::this_work_item::get_work_group<3>());
+ const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
+ const int T = m.T;
+ const int d0 = item_ct1.get_group(2) * UPM_COLS;
+ constexpr int RPW = HC * UPM_COLS / WARPS; // 8 rows per warp
+ if (t < T * HC) {
+ const int k = t / HC, c = t - k * HC;
+ float ss = 0.0f;
+#pragma unroll
+ for (int h = 0; h < S; ++h) ss += ssg[t * S + h];
+ const float r = sycl::rsqrt(ss / (float)N + m.a[k].eps);
+ rsS[k][c] = r;
+ if (item_ct1.get_group(2) == 0) m.a[k].rs[c] = r;
+ }
+ /*
+ 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();
+ for (int i = t; i < T * LR; i += THREADS) {
+ const int k = i / LR, r = i - k * LR;
+ float sum = 0.0f;
+#pragma unroll
+ for (int c = 0; c < HC; ++c) {
+ float p = 0.0f;
+#pragma unroll
+ for (int h = 0; h < S; ++h) p += part[(((size_t) k * HC + c) * S + h) * PR + r];
+ sum = sycl::fma(rsS[k][c], p, sum);
+ }
+ const float x = sum / (float) HC;
+ lo[k][r] = x / (1.0f + sycl::native::exp(-x));
+ }
+ if (item_ct1.get_group(2) == 0 && t < T * HC) {
+ const int k = t / HC, cc = t - k * HC;
+ if (m.a[k].w_inject != nullptr) {
+ float sum = 0.0f;
+#pragma unroll
+ for (int c = 0; c < HC; ++c) {
+ float p = 0.0f;
+#pragma unroll
+ for (int h = 0; h < S; ++h) p += part[(((size_t) k * HC + c) * S + h) * PR + LR + cc];
+ sum = sycl::fma(rsS[k][c], p, sum);
+ }
+ m.a[k].inject_out[cc] = sum;
+ }
+ }
+ /*
+ 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 q = 0; q < RPW; ++q) {
+ const int r = warp + q * WARPS;
+ const int c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd;
+ const sycl::uint4 *w4 =
+ reinterpret_cast<const sycl::uint4 *>(m.a[0].w_up + (size_t)i * LR);
+ /*
+ DPCT1098: The '*' expression is used instead of the __ldg call.
+ These two expressions do not provide the exact same functionality. Check
+ the generated code for potential precision and/or performance issues.
+ */
+ const sycl::uint4 wa = *(w4 + lane);
+ /*
+ DPCT1098: The '*' expression is used instead of the __ldg call.
+ These two expressions do not provide the exact same functionality. Check
+ the generated code for potential precision and/or performance issues.
+ */
+ const sycl::uint4 wb =
+ lane < LR / 8 - 32 ? *(w4 + 32 + lane) : sycl::uint4(0, 0, 0, 0);
+ float rv = 0.0f, wn = 0.0f, bo = 0.0f, ip = 0.0f;
+ bool apply = false;
+ if (lane < T) {
+ const FusedGrArgs& a = m.a[lane];
+ rv = a.R[i];
+ wn = a.w_norm[i];
+ apply = a.apply;
+ if (apply) { bo = a.bo_prev[d0 + dd]; ip = a.inj_prev[c]; }
+ }
+ float mine = 0.0f;
+#pragma unroll
+ for (int k = 0; k < kFusedGrMaxT; ++k) {
+ if (k >= T) break;
+ float acc = dot8(wa, lo[k] + lane * 8);
+ if (lane < LR / 8 - 32) acc += dot8(wb, lo[k] + (32 + lane) * 8);
+ acc = warp_sum(acc);
+ if (lane == k) mine = acc;
+ }
+ if (lane < T) {
+ if (apply) {
+ rv = sycl::fma(bo, 2.0f * sigmoidf_(ip / (float)HC), rv);
+ m.a[lane].R_out[i] = rv;
+ }
+ const float x = rv * wn * rsS[lane][c];
+ g[lane][c][dd] = x * sigmoidf_(mine);
+ }
+ }
+ /*
+ 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();
+ for (int i = t; i < T * UPM_COLS; i += THREADS) {
+ const int k = i / UPM_COLS, col = i - k * UPM_COLS;
+ float sum = 0.0f;
+#pragma unroll
+ for (int c = 0; c < HC; ++c) sum += g[k][c][col];
+ m.a[k].mixed[d0 + col] = sum / (float) HC;
+ }
+}
} // namespace
// one partials buffer per queue (the verifier's and the drafter's launches never share a queue; within a queue the
@@ -717,6 +987,139 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi
m.xn = xn_scratch;
m.T = n_tok;
dpct::queue_ptr st = strata::q_of(stream);
+ // STRATA_GR_V3=1: the two-kernel read above (another summation order - opt-in)
+ static const bool v3 = [] { const char* v = std::getenv("STRATA_GR_V3"); return v != nullptr && std::atoi(v) != 0; }();
+ static int split3[64] = {}; // per device: 0 = not decided yet, 1 / 2 = column halves S, -1 = does not fit
+ int dev3 = 0;
+ if (v3) {
+ dev3 = dpct::get_current_device_id();
+ if (dev3 >= 0 && dev3 < 64 && split3[dev3] == 0) {
+ int optin = 0;
+ // SYCL port: the device's local memory is the limit (no per-kernel opt-in to raise)
+ optin = (int) dpct::get_device(dev3).get_local_mem_size();
+ const int limit = optin > 0 ? optin : 48 * 1024;
+ const int need1 = (int) (kFusedGrMaxT * N * sizeof(float)), need2 = need1 / 2;
+ int split = -1;
+ if (need1 <= limit &&
+ /*
+ DPCT1027: The call to cudaFuncSetAttribute was replaced with
+ 0 because SYCL currently does not support corresponding setting.
+ */
+ 0 == 0)
+ split = 1;
+ else if (need2 <= limit &&
+ /*
+ DPCT1027: The call to cudaFuncSetAttribute was replaced
+ with 0 because SYCL currently does not support
+ corresponding setting.
+ */
+ 0 == 0)
+ split = 2;
+ /*
+ DPCT1026: The call to cudaGetLastError was removed because this
+ functionality is redundant in SYCL.
+ */
+; // drop any error the attempts left behind
+ split3[dev3] = split;
+ }
+ }
+ const int split = v3 && dev3 >= 0 && dev3 < 64 ? split3[dev3] : -1;
+ if (split > 0) { // 2 kernels; scratch = partials + sums of squares
+ float* part = xn_scratch;
+ float* ssg = xn_scratch + (size_t) n_tok * HC * 2 * PR; // room for S = 2
+ /*
+ DPCT1083: The size of local memory in the migrated code may be
+ different from the original code. Check that the allocated memory size
+ in the migrated code is correct.
+ */
+ const size_t sm = (size_t)n_tok * (N / split) * sizeof(float);
+ if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, stream);
+ if (split == 2) {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+
+ st->submit([&](sycl::handler &cgh) {
+ sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
+ sycl::range(sm), cgh);
+
+ cgh.parallel_for<dpct_kernel_name<
+ class gr_down_v3_kernel_c14ff7, dpct_kernel_scalar<2>>>(
+ sycl::nd_range<3>(sycl::range(1, HC * 2, LR / WARPS + 1) *
+ sycl::range(1, 1, THREADS),
+ sycl::range(1, 1, THREADS)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(
+ 32)]] {
+ gr_down_v3_kernel<2>(
+ m, part, ssg,
+ dpct_local_acc_ct1
+ .get_multi_ptr<sycl::access::decorated::no>()
+ .get());
+ });
+ });
+ } else {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+
+ st->submit([&](sycl::handler &cgh) {
+ sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
+ sycl::range(sm), cgh);
+
+ cgh.parallel_for<dpct_kernel_name<
+ class gr_down_v3_kernel_88bc89, dpct_kernel_scalar<1>>>(
+ sycl::nd_range<3>(sycl::range(1, HC, LR / WARPS + 1) *
+ sycl::range(1, 1, THREADS),
+ sycl::range(1, 1, THREADS)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(
+ 32)]] {
+ gr_down_v3_kernel<1>(
+ m, part, ssg,
+ dpct_local_acc_ct1
+ .get_multi_ptr<sycl::access::decorated::no>()
+ .get());
+ });
+ });
+ }
+ if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, stream);
+ if (split == 2) {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+
+ st->parallel_for<dpct_kernel_name<class gr_up_v3_kernel_6e945c,
+ dpct_kernel_scalar<2>>>(
+ sycl::nd_range<3>(sycl::range(1, 1, UPM_BLOCKS) *
+ sycl::range(1, 1, THREADS),
+ sycl::range(1, 1, THREADS)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1)
+ [[sycl::reqd_sub_group_size(32)]] {
+ gr_up_v3_kernel<2>(m, part, ssg);
+ });
+ } else {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+
+ st->parallel_for<dpct_kernel_name<class gr_up_v3_kernel_716779,
+ dpct_kernel_scalar<1>>>(
+ sycl::nd_range<3>(sycl::range(1, 1, UPM_BLOCKS) *
+ sycl::range(1, 1, THREADS),
+ sycl::range(1, 1, THREADS)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1)
+ [[sycl::reqd_sub_group_size(32)]] {
+ gr_up_v3_kernel<1>(m, part, ssg);
+ });
+ }
+ /*
+ DPCT1010: SYCL uses exceptions to report errors and does not use the
+ error codes. The cudaGetLastError function call was replaced with 0. You
+ need to rewrite this code.
+ */
+ const dpct::err0 e3 = 0;
+
+ return;
+ }
m.part = down_partials(st);
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
@@ -737,38 +1140,17 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi
});
}
if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, stream);
- // the shared-memory opt-in is a per-DEVICE setting: once per device, not once per process (a layer split
- // runs this kernel on two cards)
+ // the local-memory capacity is a per-DEVICE property: once per device (a layer split runs this on two cards).
+ // SYCL port: upstream picks TILEV 1280 on sm_75 and takes the per-block limit below sm_70 (CUDA compute
+ // capabilities, cudaFuncSetAttribute opt-ins); here the tile is the port's TILE and the device's local memory is
+ // the only limit. The tiled kernel is the fallback (STRATA_GR_DOWN_SLICED=0 STRATA_GR_DOWN_DIRECT=0); the
+ // default is the sliced kernel below.
static bool attr[64] = {};
- static int chunk[64] = {}; // Turing port: tokens the down kernel may carry in one launch on this card
+ static int chunk[64] = {}; // tokens the tiled down kernel may carry in one launch on this card
int dev = 0;
dev = dpct::get_current_device_id();
if (dev >= 0 && dev < 64 && !attr[dev]) {
- // at most what the card allows (Turing: 64 KB - enough for windows of up to 6 tokens)
- int optin = 0;
- /*
- DPCT1019: local_mem_size in SYCL is not a complete equivalent of
- cudaDevAttrMaxSharedMemoryPerBlockOptin in CUDA. You may need to adjust
- the code.
- */
- optin = dpct::get_device(dev).get_local_mem_size();
- int want = (int) (kFusedGrMaxT * TILE * sizeof(float));
- if (optin > 0 && want > optin) want = optin;
- /*
- DPCT1026: The call to cudaFuncSetAttribute was removed because SYCL
- currently does not support corresponding setting.
- */
- /*
- DPCT1026: The call to cudaGetLastError was removed because this
- functionality is redundant in SYCL.
- */
-; // drop any error the attempt left behind
- // Turing port: the down kernel stages n_tok*TILE floats of dynamic shared memory - 80 KB at the full
- // 8 tokens. A card whose opt-in is below that (Turing: 64 KB, so 7+ tokens fail to launch as
- // "invalid argument") processes the tokens in slices that fit; a card that reports no opt-in gets what
- // fits the 48 KB default (4 tokens of the CUDA tile; all 8 of HIP's smaller tile). The down kernel's
- // outputs (lo, inject_out) are strictly per-token, so the chunk boundaries are safe, and the up kernel
- // below still sees every token of the batch in one launch.
+ const int optin = (int) dpct::get_device(dev).get_local_mem_size();
const int capacity = (optin > 0 ? optin : 48 * 1024) / (int) (TILE * sizeof(float));
chunk[dev] = capacity < 1 ? 1 : (capacity > kFusedGrMaxT ? kFusedGrMaxT : capacity);
attr[dev] = true;
@@ -797,25 +1179,18 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi
} else if (chunk_tok >= n_tok) {
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
-
st->submit([&](sycl::handler &cgh) {
- /*
- DPCT1083: The size of local memory in the migrated code may
- be different from the original code. Check that the allocated
- memory size in the migrated code is correct.
- */
sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
sycl::range((size_t)n_tok * TILE * sizeof(float)), cgh);
-
cgh.parallel_for<
- dpct_kernel_name<class gr_down_multi_kernel_7f5820>>(
+ dpct_kernel_name<class gr_down_multi_kernel_7f5820, dpct_kernel_scalar<TILE>>>(
sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS * DOWN_SPLIT + 1) *
sycl::range(1, 1, THREADS),
sycl::range(1, 1, THREADS)),
exp_props,
[=](sycl::nd_item<3> item_ct1)
[[sycl::reqd_sub_group_size(32)]] {
- gr_down_multi_kernel(
+ gr_down_multi_kernel<TILE>(
m, dpct_local_acc_ct1
.get_multi_ptr<sycl::access::decorated::no>()
.get());
@@ -829,35 +1204,25 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi
c.T = ct;
for (int k = 0; k < ct; ++k) c.a[k] = a[c0 + k];
c.part = m.part;
- {
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- st->submit([&](sycl::handler &cgh) {
- /*
- DPCT1083: The size of local memory in the migrated code
- may be different from the original code. Check that the
- allocated memory size in the migrated code is correct.
- */
- sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
- sycl::range((size_t)ct * TILE * sizeof(float)), cgh);
-
- cgh.parallel_for<
- dpct_kernel_name<class gr_down_multi_kernel_88cb86>>(
- sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS * DOWN_SPLIT + 1) *
- sycl::range(1, 1, THREADS),
- sycl::range(1, 1, THREADS)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- gr_down_multi_kernel(
- c, dpct_local_acc_ct1
- .get_multi_ptr<
- sycl::access::decorated::no>()
- .get());
- });
- });
- }
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+ st->submit([&](sycl::handler &cgh) {
+ sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
+ sycl::range((size_t)ct * TILE * sizeof(float)), cgh);
+ cgh.parallel_for<
+ dpct_kernel_name<class gr_down_multi_kernel_88cb86, dpct_kernel_scalar<TILE>>>(
+ sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS * DOWN_SPLIT + 1) *
+ sycl::range(1, 1, THREADS),
+ sycl::range(1, 1, THREADS)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1)
+ [[sycl::reqd_sub_group_size(32)]] {
+ gr_down_multi_kernel<TILE>(
+ c, dpct_local_acc_ct1
+ .get_multi_ptr<sycl::access::decorated::no>()
+ .get());
+ });
+ });
}
}
if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, stream);
@@ -894,6 +1259,23 @@ void fused_gr_read(const FusedGrArgs& a, void* stream) {
std::exit(1);
}
dpct::queue_ptr st = strata::q_of(stream);
+ // SYCL port: the multi-token read's sliced down kernel and per-(token, stream) norm sum in their own orders, so a
+ // window's token would differ in its last bits from this kernel's. The header promises "every token's outputs
+ // are bitwise fused_gr_read(a[t])" (gr_parity checks it): with those paths on, the single read IS the multi read
+ // of one token (each token's sums run in the same order whatever the window size).
+ if (gr_down_sliced() || gr_norm_split() || gr_down_direct()) {
+ static std::mutex mu;
+ static std::unordered_map<sycl::queue*, float*> xn;
+ float* scratch;
+ {
+ std::lock_guard<std::mutex> lk(mu);
+ float*& p = xn[st];
+ if (!p) p = sycl::malloc_device<float>((size_t) D, *st);
+ scratch = p;
+ }
+ fused_gr_read_multi(&a, 1, scratch, stream);
+ return;
+ }
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
diff --git a/sycl/src/kernels/cuda/iq_kernels.dp.cpp b/sycl/src/kernels/cuda/iq_kernels.dp.cpp
index 535fbb319..375517367 100644
--- a/sycl/src/kernels/cuda/iq_kernels.dp.cpp
+++ b/sycl/src/kernels/cuda/iq_kernels.dp.cpp
@@ -10,6 +10,7 @@
#include "strata/sycl_math.hpp"
#include "strata/sycl_queue.hpp"
#include "strata/kernels/iq_kernels.hpp"
+#include "strata/kernels/dp4a.hpp"
#define GGML_COMMON_DECL_SYCL
#define GGML_COMMON_IMPL_SYCL
@@ -71,7 +72,7 @@ __dpct_inline__ sycl::int2 get_int_from_table_16(const int &q4,
return sycl::int2(dpct::byte_level_permute(tmp[0], tmp[1], 0x6420),
dpct::byte_level_permute(tmp[0], tmp[1], 0x7531));
}
-#define ggml_cuda_dp4a(a, b, c) strata::dp4a((a), (b), (c))
+#define ggml_cuda_dp4a(a, b, c) strata::dp4a((a), (b), (c)) // SYCL port: the one dp4a (strata/sycl_math.hpp)
// ---------------------------------------------------------------- the dot products (vecdotq.cuh)
__dpct_inline__ float vec_dot_q2_0_q8_1(const void *__restrict__ vbq,
@@ -341,7 +342,7 @@ __dpct_inline__ uint32_t iq4nl_lut4(uint32_t q4) { // four nibbles -> four kva
}
return r;
}
-__dpct_inline__ sycl::int2 iq4nl_pair(int aux) { // = get_int_from_table_16(aux, kvalues_iq4nl)
+__dpct_inline__ sycl::int2 iq4nl_pair(int aux) { // = get_int_from_table_16(aux)
return sycl::int2((int) iq4nl_lut4((uint32_t) aux & 0x0f0f0f0fu), (int) iq4nl_lut4(((uint32_t) aux >> 4) & 0x0f0f0f0fu));
}
__dpct_inline__ sycl::int2 load8_a2(const uint8_t* p) { // 8 bytes at a 2-byte-aligned address, as two ints
@@ -420,6 +421,170 @@ __dpct_inline__ float vec_dot_iq4_xs_q8_1(const void *__restrict__ vbq,
return d * sumi;
}
+// ---------------------------------------------------------------- Unsloth's UD-Q4_K_XL experts
+// Q4_K / Q5_K gate/up and Q5_1 / Q8_0 down: llama.cpp's vec_dot_*_q8_1 (vecdotq.cuh, VDR 2 each), transcribed; the
+// Q5_1 min term is the one departure (below). Via eddoursul/Strata 8029fa9 (iq_dot.cuh) and #255 (Q8_0,
+// gopinath87607), which agree with llama.cpp and with each other.
+constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q8_0 = 2;
+
+__dpct_inline__ float vec_dot_q4_K_q8_1_impl_vmmq(
+ const int *__restrict__ v, const int *__restrict__ u,
+ const uint8_t *__restrict__ sc, const uint8_t *__restrict__ m,
+ const sycl::half2 &dm4, const float *__restrict__ d8) {
+ float sumf_d = 0.0f;
+ float sumf_m = 0.0f;
+#pragma unroll
+ for (int i = 0; i < QR4_K; ++i) {
+ const int v0i = (v[0] >> (4 * i)) & 0x0F0F0F0F;
+ const int v1i = (v[1] >> (4 * i)) & 0x0F0F0F0F;
+ const int dot1 = ggml_cuda_dp4a(v1i, u[2 * i + 1], ggml_cuda_dp4a(v0i, u[2 * i + 0], 0));
+ const int dot2 = ggml_cuda_dp4a(0x01010101, u[2 * i + 1], ggml_cuda_dp4a(0x01010101, u[2 * i + 0], 0));
+ sumf_d += d8[i] * (dot1 * sc[i]);
+ sumf_m += d8[i] * (dot2 * m[i]); // the min times the sum of the QUANTIZED activations
+ }
+ const sycl::float2 dm4f =
+ dm4.template convert<float, sycl::rounding_mode::automatic>();
+ return dm4f.x() * sumf_d - dm4f.y() * sumf_m;
+}
+__dpct_inline__ float vec_dot_q5_K_q8_1_impl_vmmq(
+ const int *__restrict__ vl, const int *__restrict__ vh,
+ const int *__restrict__ u, const uint8_t *__restrict__ sc,
+ const uint8_t *__restrict__ m, const sycl::half2 &dm5,
+ const float *__restrict__ d8) {
+ float sumf_d = 0.0f;
+ float sumf_m = 0.0f;
+#pragma unroll
+ for (int i = 0; i < QR5_K; ++i) {
+ const int vl0i = (vl[0] >> (4 * i)) & 0x0F0F0F0F;
+ const int vl1i = (vl[1] >> (4 * i)) & 0x0F0F0F0F;
+ const int vh0i = ((vh[0] >> i) << 4) & 0x10101010;
+ const int vh1i = ((vh[1] >> i) << 4) & 0x10101010;
+ const int v0i = vl0i | vh0i;
+ const int v1i = vl1i | vh1i;
+ const int dot1 = ggml_cuda_dp4a(v0i, u[2 * i + 0], ggml_cuda_dp4a(v1i, u[2 * i + 1], 0));
+ const int dot2 = ggml_cuda_dp4a(0x01010101, u[2 * i + 0], ggml_cuda_dp4a(0x01010101, u[2 * i + 1], 0));
+ sumf_d += d8[i] * (dot1 * sc[i]);
+ sumf_m += d8[i] * (dot2 * m[i]);
+ }
+ const sycl::float2 dm5f =
+ dm5.template convert<float, sycl::rounding_mode::automatic>();
+ return dm5f.x() * sumf_d - dm5f.y() * sumf_m;
+}
+// the 6-bit scales and mins of the 32-value group pair bq8_offset / 2, branchless (llama.cpp; shared by Q4_K, Q5_K)
+__dpct_inline__ void k_scale_min(const uint8_t *scales8, int bq8_offset,
+ uint16_t aux[2]) {
+ const uint16_t* scales = (const uint16_t*) scales8;
+ const int j = bq8_offset / 2;
+ const int jm = j & 1;
+ const uint32_t s0 = scales[jm + 0];
+ const uint32_t s2 = scales[jm + 2];
+ const uint32_t s4 = scales[jm + 4];
+ const uint32_t hi = (uint32_t) -(int32_t) (j >= 2);
+ aux[0] = (uint16_t) (((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi));
+ aux[1] = (uint16_t) (((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi));
+}
+__dpct_inline__ float vec_dot_q4_K_q8_1(const void *__restrict__ vbq,
+ const block_q8_1 *__restrict__ bq8_1,
+ const int &kbx, const int &iqs) {
+ const block_q4_K* bq4_K = (const block_q4_K*) vbq + kbx;
+ int v[2];
+ int u[2 * QR4_K];
+ float d8[QR4_K];
+ const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2));
+ const int* q4 = (const int*) (bq4_K->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
+ v[0] = q4[0];
+ v[1] = q4[4];
+ uint16_t aux[2];
+ k_scale_min(bq4_K->scales, bq8_offset, aux);
+ const uint8_t* sc = (const uint8_t*) aux;
+ const uint8_t* m = sc + 2;
+#pragma unroll
+ for (int i = 0; i < QR4_K; ++i) {
+ const block_q8_1* bq8i = bq8_1 + bq8_offset + i;
+ d8[i] = bq8i->ds[0];
+ const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);
+ u[2 * i + 0] = q8[0];
+ u[2 * i + 1] = q8[4];
+ }
+ return vec_dot_q4_K_q8_1_impl_vmmq(v, u, sc, m, bq4_K->dm, d8);
+}
+__dpct_inline__ float vec_dot_q5_K_q8_1(const void *__restrict__ vbq,
+ const block_q8_1 *__restrict__ bq8_1,
+ const int &kbx, const int &iqs) {
+ const block_q5_K* bq5_K = (const block_q5_K*) vbq + kbx;
+ int vl[2];
+ int vh[2];
+ int u[2 * QR5_K];
+ float d8[QR5_K];
+ const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2));
+ const int* ql = (const int*) (bq5_K->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
+ const int* qh = (const int*) (bq5_K->qh + 4 * ((iqs / 2) % 4));
+ vl[0] = ql[0];
+ vl[1] = ql[4];
+ vh[0] = qh[0] >> bq8_offset;
+ vh[1] = qh[4] >> bq8_offset;
+ uint16_t aux[2];
+ k_scale_min(bq5_K->scales, bq8_offset, aux);
+ const uint8_t* sc = (const uint8_t*) aux;
+ const uint8_t* m = sc + 2;
+#pragma unroll
+ for (int i = 0; i < QR5_K; ++i) {
+ const block_q8_1* bq8i = bq8_1 + bq8_offset + i;
+ d8[i] = bq8i->ds[0];
+ const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);
+ u[2 * i + 0] = q8[0];
+ u[2 * i + 1] = q8[4];
+ }
+ return vec_dot_q5_K_q8_1_impl_vmmq(vl, vh, u, sc, m, bq5_K->dm, d8);
+}
+// Q5_1: llama.cpp's integer chain, but the min term multiplies the sum of the QUANTIZED activations (dp4a with
+// 0x01010101, times d8) instead of the q8_1 block's `ds.y`, which our quantizer (like llama.cpp's) fills with the sum
+// of the ORIGINAL activations. That is ggml-cpu's convention (its q8_1 `s` is d * sum(q)) and the one the K-quant
+// mins above use; the scaled and the min term then see the same activation (eddoursul/Strata measured 1.1-1.2%
+// against 1.9% relative error per expert). Result: sumi * (d5 * d8) + sumu * (m5 * d8).
+__dpct_inline__ float vec_dot_q5_1_q8_1(const void *__restrict__ vbq,
+ const block_q8_1 *__restrict__ bq8_1,
+ const int &kbx, const int &iqs) {
+ const block_q5_1* bq5_1 = (const block_q5_1*) vbq + kbx;
+ int sumi = 0, sumu = 0;
+#pragma unroll
+ for (int i = 0; i < VDR_Q5_1; ++i) {
+ const int vl = get_int_b4(bq5_1->qs, iqs + i);
+ const int vh = get_int_b4(bq5_1->qh, 0) >> (4 * (iqs + i));
+ const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_1);
+ int vi0 = (vl >> 0) & 0x0F0F0F0F;
+ vi0 |= (vh << 4) & 0x00000010;
+ vi0 |= (vh << 11) & 0x00001000;
+ vi0 |= (vh << 18) & 0x00100000;
+ vi0 |= (vh << 25) & 0x10000000;
+ sumi = ggml_cuda_dp4a(vi0, u0, sumi);
+ int vi1 = (vl >> 4) & 0x0F0F0F0F;
+ vi1 |= (vh >> 12) & 0x00000010;
+ vi1 |= (vh >> 5) & 0x00001000;
+ vi1 |= (vh << 2) & 0x00100000;
+ vi1 |= (vh << 9) & 0x10000000;
+ sumi = ggml_cuda_dp4a(vi1, u1, sumi);
+ sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu));
+ }
+ const sycl::float2 dm5 =
+ (bq5_1->dm).template convert<float, sycl::rounding_mode::automatic>();
+ const float d8 = bq8_1->ds[0];
+ return sumi * (dm5.x() * d8) + sumu * (dm5.y() * d8);
+}
+__dpct_inline__ float vec_dot_q8_0_q8_1(const void *__restrict__ vbq,
+ const block_q8_1 *__restrict__ bq8_1,
+ const int &kbx, const int &iqs) {
+ const block_q8_0* bq8_0 = (const block_q8_0*) vbq + kbx;
+ int sumi = 0;
+#pragma unroll
+ for (int i = 0; i < VDR_Q8_0; ++i)
+ sumi = ggml_cuda_dp4a(get_int_b2(bq8_0->qs, iqs + i), get_int_b4(bq8_1->qs, iqs + i), sumi);
+ const float d8_0 = sycl::vec<sycl::half, 1>(bq8_0->d)
+ .convert<float, sycl::rounding_mode::automatic>()[0],
+ d8_1 = bq8_1->ds[0];
+ return d8_0 * d8_1 * ((float) sumi);
+}
+
// ---------------------------------------------------------------- the formats
// qk = values per block, ipb = dot calls per block (qi / vdr), step = the iqs stride between calls.
template<int TY>
@@ -442,6 +607,20 @@ template<> struct Fmt<29> { static constexpr int qk = 256, ipb = 8, step = 1;
static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq1_m_q8_1(v, y, kbx, iqs); } };
template<> struct Fmt<42> { static constexpr int qk = 64, ipb = 2, step = 1;
static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q2_0_q8_1(v, y, kbx, iqs); } };
+template<> struct Fmt<12> { static constexpr int qk = 256, ipb = QI4_K / VDR_Q4_K, step = VDR_Q4_K;
+ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_K_q8_1(v, y, kbx, iqs); } };
+template<> struct Fmt<13> { static constexpr int qk = 256, ipb = QI5_K / VDR_Q5_K, step = VDR_Q5_K;
+ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_K_q8_1(v, y, kbx, iqs); } };
+template<> struct Fmt<7> { static constexpr int qk = 32, ipb = QI5_1 / VDR_Q5_1, step = VDR_Q5_1;
+ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_1_q8_1(v, y, kbx, iqs); } };
+template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0, step = VDR_Q8_0;
+ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q8_0_q8_1(v, y, kbx, iqs); } };
+
+// The formats of each role, one list each so a type cannot be in one switch and missing from another. Every
+// entry is a kernel template for each CUDA architecture of the build, hence two lists rather than one.
+#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(8)
+#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(8)
+#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(8)
__dpct_inline__ float warp_sum(float v) {
#pragma unroll
@@ -519,6 +698,398 @@ mmvq_kernel(const uint8_t *__restrict__ w, size_t row_bytes,
}
}
+// ---------------------------------------------------------------- decode once, apply to every column
+// The kernels above call Fmt<TY>::dot once per (call, column): each column re-reads the weight words and redoes
+// the grid lookups and sign unpacking. Here each dot is split, as native_mmvq.cu's multi-column traits are, into
+// `load` (everything that depends only on the weight: the signed grid words, the integer scales, the fp16 block
+// scale as a float) and `apply` (the activation loads, the dp4a chain in the same order, the same integer scale
+// step and the same float expression). `apply(load(...))` does the dot's integer and float operations in the same
+// order on the same values, so a column of the kernels below is BITWISE equal to the same column of mmvq_kernel /
+// native_gu_kernel / native_down_kernel (iq_multi_parity checks it; STRATA_OLD_IQ_MMVQ=1 keeps the old kernels).
+template<int TY> struct Split;
+// Formats with a Split below take the decode-once kernels; the others (Q4_K, Q5_K, Q5_1, Q8_0: UD-Q4_K_XL) the
+// per-entry ones, which call Fmt<TY>::dot per column exactly as before #242 (the launchers test kSplit at compile
+// time, so the multi kernels are never instantiated for a type without a Split).
+template<int TY> inline constexpr bool kSplit = false;
+template<> inline constexpr bool kSplit<16> = true;
+template<> struct Split<16> { // IQ2_XXS
+ struct W { int g[8]; int ls; float dw; };
+ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
+ const block_iq2_xxs* bq2 = (const block_iq2_xxs*) vbq + kbx;
+ const int q2 = get_int_b2(bq2->qs, iqs);
+ const uint8_t* aux8 = (const uint8_t*) &q2;
+ const uint32_t aux32 = get_int_b2(bq2->qs, iqs + 1);
+ W r;
+#pragma unroll
+ for (int k0 = 0; k0 < 8; k0 += 2) {
+ const sycl::uint2 grid_pos =
+ ((const sycl::uint2 *)iq2xxs_grid)[aux8[k0 / 2]];
+ const uint32_t signs = unpack_ksigns(aux32 >> (7 * k0 / 2));
+ const int signs0 = dpct::vectorized_binary<sycl::uchar4>(
+ signs & 0x08040201, 0, std::not_equal_to<>());
+ r.g[k0 + 0] = dpct::vectorized_binary<sycl::uchar4>(
+ grid_pos.x() ^ signs0, signs0, std::minus<>());
+ const int signs1 = dpct::vectorized_binary<sycl::uchar4>(
+ signs & 0x80402010, 0, std::not_equal_to<>());
+ r.g[k0 + 1] = dpct::vectorized_binary<sycl::uchar4>(
+ grid_pos.y() ^ signs1, signs1, std::minus<>());
+ }
+ r.ls = aux32 >> 27 | 1;
+ r.dw = sycl::vec<sycl::half, 1>(bq2->d)
+ .convert<float, sycl::rounding_mode::automatic>()[0];
+ return r;
+ }
+ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
+ int sumi = 0;
+#pragma unroll
+ for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi);
+ sumi = sumi * r.ls / 8;
+ const float d = r.dw * bq8_1[iqs / 2].ds[0];
+ return d * sumi;
+ }
+};
+// IQ2_XS and IQ2_S share the apply: two half sums, two 4-bit scales
+struct SplitLs2 {
+ struct W { int g[8]; int ls0, ls1; float dw; };
+ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
+ int sumi0 = 0, sumi1 = 0;
+#pragma unroll
+ for (int j = 0; j < 4; ++j) sumi0 = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi0);
+#pragma unroll
+ for (int j = 4; j < 8; ++j) sumi1 = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi1);
+ const int sumi = (sumi0 * r.ls0 + sumi1 * r.ls1 + (sumi0 + sumi1) / 2) / 4;
+ const float d = r.dw * bq8_1[iqs / 2].ds[0];
+ return d * sumi;
+ }
+};
+template<> inline constexpr bool kSplit<17> = true;
+template<> struct Split<17> : SplitLs2 { // IQ2_XS
+ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
+ const block_iq2_xs* bq2 = (const block_iq2_xs*) vbq + kbx;
+ const sycl::int2 q2_packed = sycl::int2(get_int_b2(bq2->qs, iqs + 0),
+ get_int_b2(bq2->qs, iqs + 1));
+ const uint16_t* q2 = (const uint16_t*) &q2_packed;
+ W r;
+ r.ls0 = bq2->scales[iqs / 2] & 0x0F;
+ r.ls1 = bq2->scales[iqs / 2] >> 4;
+#pragma unroll
+ for (int l0 = 0; l0 < 8; l0 += 2) {
+ const sycl::uint2 grid_pos =
+ ((const sycl::uint2 *)iq2xs_grid)[q2[l0 / 2] & 0x1FF];
+ const uint32_t signs = unpack_ksigns(q2[l0 / 2] >> 9);
+ const int signs0 = dpct::vectorized_binary<sycl::uchar4>(
+ signs & 0x08040201, 0, std::not_equal_to<>());
+ r.g[l0 + 0] = dpct::vectorized_binary<sycl::uchar4>(
+ grid_pos.x() ^ signs0, signs0, std::minus<>());
+ const int signs1 = dpct::vectorized_binary<sycl::uchar4>(
+ signs & 0x80402010, 0, std::not_equal_to<>());
+ r.g[l0 + 1] = dpct::vectorized_binary<sycl::uchar4>(
+ grid_pos.y() ^ signs1, signs1, std::minus<>());
+ }
+ r.dw = sycl::vec<sycl::half, 1>(bq2->d)
+ .convert<float, sycl::rounding_mode::automatic>()[0];
+ return r;
+ }
+};
+template<> inline constexpr bool kSplit<22> = true;
+template<> struct Split<22> : SplitLs2 { // IQ2_S
+ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
+ const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx;
+ const int qs_packed = get_int_b2(bq2->qs, iqs / 2);
+ const uint8_t* qs = (const uint8_t*) &qs_packed;
+ const int qh = bq2->qh[iqs / 2];
+ const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2);
+ const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
+ W r;
+ r.ls0 = bq2->scales[iqs / 2] & 0x0F;
+ r.ls1 = bq2->scales[iqs / 2] >> 4;
+#pragma unroll
+ for (int l0 = 0; l0 < 8; l0 += 2) {
+ const int* grid_pos = (const int*) (iq2s_grid + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300)));
+ const int signs0 = dpct::vectorized_binary<sycl::uchar4>(
+ ((signs_packed_8[l0 / 2] & 0x03) << 7) |
+ ((signs_packed_8[l0 / 2] & 0x0C) << 21),
+ 0x00000000, std::not_equal_to<>());
+ const int signs1 = dpct::vectorized_binary<sycl::uchar4>(
+ ((signs_packed_8[l0 / 2] & 0x30) << 3) |
+ ((signs_packed_8[l0 / 2] & 0xC0) << 17),
+ 0x00000000, std::not_equal_to<>());
+ r.g[l0 + 0] = dpct::vectorized_binary<sycl::uchar4>(
+ grid_pos[0] ^ signs0, signs0, std::minus<>());
+ r.g[l0 + 1] = dpct::vectorized_binary<sycl::uchar4>(
+ grid_pos[1] ^ signs1, signs1, std::minus<>());
+ }
+ r.dw = sycl::vec<sycl::half, 1>(bq2->d)
+ .convert<float, sycl::rounding_mode::automatic>()[0];
+ return r;
+ }
+};
+template<> inline constexpr bool kSplit<18> = true;
+template<> struct Split<18> { // IQ3_XXS
+ struct W { int g[8]; int ls; float dw; };
+ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
+ const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx;
+ const sycl::int2 q3_packed =
+ sycl::int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1));
+ const uint8_t* q3 = (const uint8_t*) &q3_packed;
+ const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2);
+ W r;
+#pragma unroll
+ for (int l0 = 0; l0 < 8; l0 += 2) {
+ const sycl::int2 grid_pos =
+ sycl::int2(iq3xxs_grid[q3[l0 + 0]], iq3xxs_grid[q3[l0 + 1]]);
+ const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2));
+ const int signs0 = dpct::vectorized_binary<sycl::uchar4>(
+ signs & 0x08040201, 0, std::not_equal_to<>());
+ r.g[l0 + 0] = dpct::vectorized_binary<sycl::uchar4>(
+ grid_pos.x() ^ signs0, signs0, std::minus<>());
+ const int signs1 = dpct::vectorized_binary<sycl::uchar4>(
+ signs & 0x80402010, 0, std::not_equal_to<>());
+ r.g[l0 + 1] = dpct::vectorized_binary<sycl::uchar4>(
+ grid_pos.y() ^ signs1, signs1, std::minus<>());
+ }
+ r.ls = aux32 >> 28;
+ r.dw = sycl::vec<sycl::half, 1>(bq3->d)
+ .convert<float, sycl::rounding_mode::automatic>()[0];
+ return r;
+ }
+ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
+ int sumi = 0;
+#pragma unroll
+ for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi);
+ sumi = (r.ls * sumi + sumi / 2) / 2;
+ const float d = r.dw * bq8_1[iqs / 2].ds[0];
+ return d * sumi;
+ }
+};
+template<> inline constexpr bool kSplit<21> = true;
+template<> struct Split<21> { // IQ3_S
+ struct W { int g[8]; int ls; float dw; };
+ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
+ const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;
+ const sycl::int2 qs_packed = sycl::int2(get_int_b2(bq3->qs, iqs + 0),
+ get_int_b2(bq3->qs, iqs + 1));
+ const uint8_t* qs = (const uint8_t*) &qs_packed;
+ const int qh = bq3->qh[iqs / 2];
+ const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);
+ const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
+ W r;
+#pragma unroll
+ for (int l0 = 0; l0 < 8; l0 += 2) {
+ const sycl::int2 grid_pos =
+ sycl::int2(iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],
+ iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);
+ const int signs0 = dpct::vectorized_binary<sycl::uchar4>(
+ ((signs_packed_8[l0 / 2] & 0x03) << 7) |
+ ((signs_packed_8[l0 / 2] & 0x0C) << 21),
+ 0x00000000, std::not_equal_to<>());
+ const int signs1 = dpct::vectorized_binary<sycl::uchar4>(
+ ((signs_packed_8[l0 / 2] & 0x30) << 3) |
+ ((signs_packed_8[l0 / 2] & 0xC0) << 17),
+ 0x00000000, std::not_equal_to<>());
+ r.g[l0 + 0] = dpct::vectorized_binary<sycl::uchar4>(
+ grid_pos.x() ^ signs0, signs0, std::minus<>());
+ r.g[l0 + 1] = dpct::vectorized_binary<sycl::uchar4>(
+ grid_pos.y() ^ signs1, signs1, std::minus<>());
+ }
+ r.ls = 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);
+ r.dw = sycl::vec<sycl::half, 1>(bq3->d)
+ .convert<float, sycl::rounding_mode::automatic>()[0];
+ return r;
+ }
+ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
+ int sumi = 0;
+#pragma unroll
+ for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi);
+ sumi *= r.ls;
+ const float d = r.dw * bq8_1[iqs / 2].ds[0];
+ return d * sumi;
+ }
+};
+template<> inline constexpr bool kSplit<29> = true;
+template<> struct Split<29> { // IQ1_M
+ struct W { int g[8]; float delta[4]; int sc0, sc1; float dw; };
+ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
+ const block_iq1_m* bq1 = (const block_iq1_m*) vbq + kbx;
+ const int qs_packed = get_int_b4(bq1->qs, iqs);
+ const uint8_t* qs = (const uint8_t*) &qs_packed;
+ W r;
+#pragma unroll
+ for (int l0 = 0; l0 < 8; l0 += 2) {
+ const int qhl = bq1->qh[2 * iqs + l0 / 4] >> (4 * ((l0 / 2) % 2));
+ const int grid = iq1s_grid_gpu[qs[l0 / 2] | ((qhl & 0x07) << 8)];
+ r.g[l0 + 0] = (grid >> 0) & 0x0F0F0F0F;
+ r.g[l0 + 1] = (grid >> 4) & 0x0F0F0F0F;
+ r.delta[l0 / 2] = -1.0f + IQ1M_DELTA - (qhl & 0x08) * (2.0f * IQ1M_DELTA / 0x08);
+ }
+ const uint16_t* sc = (const uint16_t*) bq1->scales;
+ iq1m_scale_t scale;
+ scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00F0) | ((sc[2] >> 4) & 0x0F00) | (sc[3] & 0xF000);
+ r.dw = sycl::vec<sycl::half, 1>(scale.f16)
+ .convert<float, sycl::rounding_mode::automatic>()[0];
+ const int tmp = sc[iqs / 2] >> (6 * (iqs % 2));
+ r.sc0 = 2 * ((tmp >> 0) & 0x07) + 1;
+ r.sc1 = 2 * ((tmp >> 3) & 0x07) + 1;
+ return r;
+ }
+ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
+ int sumi[2] = {0, 0};
+ float sumf[2] = {0.0f, 0.0f};
+#pragma unroll
+ for (int l0 = 0; l0 < 8; l0 += 2) {
+ const int u0 = get_int_b4(bq8_1[iqs].qs, l0 + 0);
+ const int u1 = get_int_b4(bq8_1[iqs].qs, l0 + 1);
+ sumi[l0 / 4] = ggml_cuda_dp4a(r.g[l0 + 0], u0, sumi[l0 / 4]);
+ sumi[l0 / 4] = ggml_cuda_dp4a(r.g[l0 + 1], u1, sumi[l0 / 4]);
+ int sumy = 0;
+ sumy = ggml_cuda_dp4a(u0, 0x01010101, sumy);
+ sumy = ggml_cuda_dp4a(u1, 0x01010101, sumy);
+ sumf[l0 / 4] += r.delta[l0 / 2] * sumy;
+ }
+ const float d = r.dw * bq8_1[iqs].ds[0];
+ return d * ((sumi[0] + sumf[0]) * r.sc0 + (sumi[1] + sumf[1]) * r.sc1);
+ }
+};
+template<> inline constexpr bool kSplit<20> = true;
+template<> struct Split<20> { // IQ4_NL
+ struct W { sycl::int2 v[2]; float dw; };
+ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
+ const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx;
+ W r;
+#pragma unroll
+ for (int l = 0; l < 2; ++l) r.v[l] = iq4nl_pair(get_int_b2(bq4->qs, iqs + l)); // SYCL port: = get_int_from_table_16(q)
+ r.dw = sycl::vec<sycl::half, 1>(bq4->d)
+ .convert<float, sycl::rounding_mode::automatic>()[0];
+ return r;
+ }
+ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
+ const int* q8 = (const int*) bq8_1->qs + iqs;
+ int sumi = 0;
+#pragma unroll
+ for (int l = 0; l < 2; ++l) {
+ sumi = ggml_cuda_dp4a(r.v[l].x(), q8[l + 0], sumi);
+ sumi = ggml_cuda_dp4a(r.v[l].y(), q8[l + 4], sumi);
+ }
+ const float d = r.dw * bq8_1->ds[0];
+ return d * sumi;
+ }
+};
+template<> inline constexpr bool kSplit<23> = true;
+template<> struct Split<23> { // IQ4_XS
+ struct W { sycl::int2 v[4]; int ls; float dw; };
+ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
+ const block_iq4_xs* bq4 = (const block_iq4_xs*) vbq + kbx;
+ W r;
+#pragma unroll
+ for (int j = 0; j < 4; ++j) r.v[j] = iq4nl_pair(get_int_b4(bq4->qs, iqs + j)); // SYCL port: = get_int_from_table_16(q)
+ r.ls = ((bq4->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0F) | (((bq4->scales_h >> (iqs / 2)) & 0x03) << 4);
+ r.dw = sycl::vec<sycl::half, 1>(bq4->d)
+ .convert<float, sycl::rounding_mode::automatic>()[0];
+ return r;
+ }
+ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
+ int sumi = 0;
+#pragma unroll
+ for (int j = 0; j < 4; ++j) {
+ const int u0 = get_int_b4(bq8_1[iqs / 4].qs, j + 0);
+ const int u1 = get_int_b4(bq8_1[iqs / 4].qs, j + 4);
+ sumi = ggml_cuda_dp4a(r.v[j].x(), u0, sumi);
+ sumi = ggml_cuda_dp4a(r.v[j].y(), u1, sumi);
+ }
+ sumi *= r.ls - 32;
+ const float d = r.dw * bq8_1[iqs / 4].ds[0];
+ return d * sumi;
+ }
+};
+template<> inline constexpr bool kSplit<42> = true;
+template<> struct Split<42> { // Q2_0
+ struct W { int qx[4], qy[4]; float d2; };
+ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
+ const block_q2_0* bq2_0 = (const block_q2_0*) vbq + kbx;
+ W r;
+ r.d2 = bq2_0->d;
+ const int16_t* qs = (const int16_t*) bq2_0->qs + iqs * 4;
+#pragma unroll
+ for (int j = 0; j < 4; ++j) {
+ const int q = qs[j];
+ const int qe =
+ dpct::byte_level_permute(0x020100FF, 0x020100FF, q >> 0);
+ const int qo =
+ dpct::byte_level_permute(0x020100FF, 0x020100FF, q >> 2);
+ r.qx[j] = dpct::byte_level_permute(qe, qo, 0x5140);
+ r.qy[j] = dpct::byte_level_permute(qe, qo, 0x7362);
+ }
+ return r;
+ }
+ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
+ const block_q8_1* bq8_1_chunk = bq8_1 + iqs;
+ int sumi = 0;
+#pragma unroll
+ for (int j = 0; j < 4; ++j) {
+ const int u = get_int_b4(bq8_1_chunk->qs, j * 2 + 0);
+ const int v = get_int_b4(bq8_1_chunk->qs, j * 2 + 1);
+ sumi = ggml_cuda_dp4a(u, r.qx[j], sumi);
+ sumi = ggml_cuda_dp4a(v, r.qy[j], sumi);
+ }
+ const float d8 = bq8_1_chunk->ds[0];
+ return r.d2 * d8 * sumi;
+ }
+};
+
+// One row against the n <= NC activations x + off[0..n) (n >= 1, warp-uniform; offsets in q8_1 blocks, 32-bit to
+// spare registers), the whole warp. Per activation this is row_dot: the same calls k, lane-strided the same way,
+// summed in the same order, then the same warp_sum. Only the weight side moves out of the per-activation loop.
+template <int TY, int NC>
+__dpct_inline__ void row_dot_multi(const uint8_t *row, const block_q8_1 *x,
+ const int (&off)[NC], int n, int nb,
+ int lane, float (&s)[NC]) {
+ using F = Fmt<TY>;
+ using S = Split<TY>;
+#pragma unroll
+ for (int c = 0; c < NC; ++c) s[c] = 0.0f;
+ for (int k = lane; k < nb * F::ipb; k += 32) {
+ const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
+ /*
+ DPCT1084: The function call "Split::load" has multiple migration
+ results in different template instantiations that could not be unified.
+ You may need to adjust the code.
+ */
+ const typename S::W w = S::load(row, kbx, iqs);
+#pragma unroll
+ for (int c = 0; c < NC; ++c)
+ if (c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
+ }
+#pragma unroll
+ for (int c = 0; c < NC; ++c)
+ if (c < n) s[c] = warp_sum(s[c]);
+}
+
+// mmvq_kernel with the columns taken NC at a time. After warp_sum every lane holds the same sum, so lane c stores
+// column c.
+template <int TY, int NC>
+__dpct_inline__ void
+mmvq_multi_kernel(const uint8_t *__restrict__ w, size_t row_bytes,
+ const block_q8_1 *__restrict__ x, float *__restrict__ y,
+ int n_in, int n_out, int ncols) {
+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
+ const int row = item_ct1.get_group(2) * 4 + item_ct1.get_local_id(1);
+ if (row >= n_out) return;
+ const int lane = item_ct1.get_local_id(2);
+ const int nb = n_in / Fmt<TY>::qk, xb = n_in / 32;
+ const uint8_t* wr = w + (size_t) row * row_bytes;
+ for (int c0 = 0; c0 < ncols; c0 += NC) {
+ const int n = sycl::min(NC, ncols - c0);
+ int off[NC];
+#pragma unroll
+ for (int c = 0; c < NC; ++c) off[c] = (c0 + sycl::min(c, n - 1)) * xb;
+ float s[NC];
+ row_dot_multi<TY, NC>(wr, x, off, n, nb, lane, s);
+#pragma unroll
+ for (int c = 0; c < NC; ++c)
+ if (c < n && lane == c) y[(size_t) (c0 + c) * n_out + row] = s[c];
+ }
+}
+
// ---------------------------------------------------------------- grouped native experts
// ---------------------------------------------------------------- SYCL port: multi-entry dots
@@ -758,7 +1329,7 @@ __dpct_inline__ void row_entries(const uint8_t* wr, const block_q8_1* x, int x_s
constexpr int GU_ROWS = 8; // rows per block (one warp each)
-template <int TG>
+template <int TG, int LN = kExpertLanes>
__dpct_inline__ void native_gu_kernel(
const unsigned long long *__restrict__ grp_ptr,
const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
@@ -782,9 +1353,36 @@ __dpct_inline__ void native_gu_kernel(
grid = &sg[0];
}
#endif
- const int rib = item_ct1.get_local_id(2) / kExpertLanes,
- sub = item_ct1.get_local_id(2) % kExpertLanes;
- const int row = item_ct1.get_group(2) * kExpertRows + rib; // 0 .. 2*n_ff
+ const int rib = item_ct1.get_local_id(2) / LN,
+ sub = item_ct1.get_local_id(2) % LN;
+ const int row = item_ct1.get_group(2) * (256 / LN) + rib; // 0 .. 2*n_ff
+ 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 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);
+}
+
+// native_gu_kernel with the group's entries taken GRP_NC at a time, each weight part decoded once per pass.
+// A group has at most one entry per token of the window (kVerifyMaxT = 8; setup writes --spec 4, and a split window
+// has halves of <= 4), so 4 takes such windows in one pass; 8 would take ~64-80 registers against ~48 (ptxas -v).
+constexpr int GRP_NC = 4;
+
+template <int TG>
+__dpct_inline__ void native_gu_multi_kernel(
+ const unsigned long long *__restrict__ grp_ptr,
+ const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
+ 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_ff
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;
@@ -792,7 +1390,19 @@ __dpct_inline__ void native_gu_kernel(
const uint8_t* wr = blob + (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, kExpertLanes>(wr, xq, xb, ent_tok, e0, e1, nb, sub, (is_up ? up : gate) + r, (size_t) L.n_ff, grid);
+ 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];
+ }
}
__dpct_inline__ void swiglu_entries_kernel(const float *__restrict__ gate,
@@ -807,7 +1417,7 @@ __dpct_inline__ void swiglu_entries_kernel(const float *__restrict__ gate,
h[i] = (g / (1.0f + sycl::native::exp(-g))) * up[i];
}
-template <int TD>
+template <int TD, int LN = kExpertLanes>
__dpct_inline__ void native_down_kernel(
const unsigned long long *__restrict__ grp_ptr,
const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
@@ -816,9 +1426,9 @@ __dpct_inline__ void native_down_kernel(
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 rib = item_ct1.get_local_id(2) / kExpertLanes,
- sub = item_ct1.get_local_id(2) % kExpertLanes;
- const int r = item_ct1.get_group(2) * kExpertRows + rib;
+ const 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;
@@ -831,7 +1441,7 @@ __dpct_inline__ void native_down_kernel(
for (; e + 4 <= e1; e += 4) {
const block_q8_1* xs[4] = {hq + (size_t) e * hb, hq + (size_t) (e + 1) * hb, hq + (size_t) (e + 2) * hb, hq + (size_t) (e + 3) * hb};
float o[4];
- row_dot_multi<TD, kExpertLanes, 4>(wr, xs, nb, sub, o);
+ row_dot_multi<TD, LN, 4>(wr, xs, nb, sub, o);
if (sub == 0)
#pragma unroll
for (int i = 0; i < 4; ++i) out[(size_t) ent_dst[e + i] * L.n_embd + r] = o[i];
@@ -839,18 +1449,50 @@ __dpct_inline__ void native_down_kernel(
if (e + 2 <= e1) {
const block_q8_1* xs[2] = {hq + (size_t) e * hb, hq + (size_t) (e + 1) * hb};
float o[2];
- row_dot_multi<TD, kExpertLanes, 2>(wr, xs, nb, sub, o);
+ row_dot_multi<TD, LN, 2>(wr, xs, nb, sub, o);
if (sub == 0) { out[(size_t) ent_dst[e] * L.n_embd + r] = o[0]; out[(size_t) ent_dst[e + 1] * L.n_embd + r] = o[1]; }
e += 2;
}
}
for (; e < e1; ++e) {
- const float v = row_dot_lanes<TD, kExpertLanes>(wr, hq + (size_t) e * hb, nb, sub);
+ const float v = row_dot_lanes<TD, LN>(wr, hq + (size_t) e * hb, nb, sub);
if (sub == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = v;
}
}
}
+// native_down_kernel with the entries taken GRP_NC at a time
+template <int TD>
+__dpct_inline__ void native_down_multi_kernel(
+ const unsigned long long *__restrict__ grp_ptr,
+ const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
+ 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 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];
+ }
+}
+
// ---------------------------------------------------------------- q8_1 (quantize.cu)
__dpct_inline__ void quantize_q8_1_kernel(const float *__restrict__ x,
block_q8_1 *__restrict__ y,
@@ -1089,6 +1731,92 @@ inline void dq_q2_0(const void *vx, int64_t ibs, dst_t *yy, int tid) {
store_run<dst_t, 8>(yy + b * 64 + part * 8, v);
}
+// llama.cpp's dequantize_q4_K / dequantize_q5_K (dequantize.cuh; q5_K's 64 threads folded onto 32) and the 32-value
+// blocks of Q5_1 / Q8_0, 8 of them per 256-value "superblock" (thread tid writes 8 values of block tid % 8).
+__dpct_inline__ void get_scale_min_k4(int j, const uint8_t *q, uint8_t &d,
+ uint8_t &m) {
+ if (j < 4) {
+ d = q[j] & 63; m = q[j + 4] & 63;
+ } else {
+ d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4);
+ m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4);
+ }
+}
+template <typename dst_t>
+inline void dq_q4_k(const void *vx, int64_t ibs, dst_t *yy, int tid) {
+ const block_q4_K* x = (const block_q4_K*) vx;
+ const int64_t il = tid / 8, ir = tid % 8, is = 2 * il;
+ const int n = 4;
+ dst_t* y = yy + 64 * il + n * ir;
+ const float dall = x[ibs].dm[0];
+ const float dmin = x[ibs].dm[1];
+ const uint8_t* q = x[ibs].qs + 32 * il + n * ir;
+ uint8_t sc, m;
+ get_scale_min_k4((int) is + 0, x[ibs].scales, sc, m);
+ const float d1 = dall * sc, m1 = dmin * m;
+ get_scale_min_k4((int) is + 1, x[ibs].scales, sc, m);
+ const float d2 = dall * sc, m2 = dmin * m;
+#pragma unroll
+ for (int l = 0; l < n; ++l) {
+ y[l + 0] = cvt<dst_t>(d1 * (q[l] & 0xF) - m1);
+ y[l + 32] = cvt<dst_t>(d2 * (q[l] >> 4) - m2);
+ }
+}
+template <typename dst_t>
+inline void dq_q5_k(const void *vx, int64_t ibs, dst_t *yy, int tid) {
+ const block_q5_K* x = (const block_q5_K*) vx;
+ for (int tt = tid; tt < 64; tt += 32) {
+ const int il = tt / 16, ir = tt % 16, is = 2 * il;
+ dst_t* y = yy + 64 * il + 2 * ir;
+ const float dall = x[ibs].dm[0];
+ const float dmin = x[ibs].dm[1];
+ const uint8_t* ql = x[ibs].qs + 32 * il + 2 * ir;
+ const uint8_t* qh = x[ibs].qh + 2 * ir;
+ uint8_t sc, m;
+ get_scale_min_k4(is + 0, x[ibs].scales, sc, m);
+ const float d1 = dall * sc, m1 = dmin * m;
+ get_scale_min_k4(is + 1, x[ibs].scales, sc, m);
+ const float d2 = dall * sc, m2 = dmin * m;
+ uint8_t hm = (uint8_t) (1 << (2 * il));
+ y[0] = cvt<dst_t>(d1 * ((ql[0] & 0xF) + (qh[0] & hm ? 16 : 0)) - m1);
+ y[1] = cvt<dst_t>(d1 * ((ql[1] & 0xF) + (qh[1] & hm ? 16 : 0)) - m1);
+ hm <<= 1;
+ y[32] = cvt<dst_t>(d2 * ((ql[0] >> 4) + (qh[0] & hm ? 16 : 0)) - m2);
+ y[33] = cvt<dst_t>(d2 * ((ql[1] >> 4) + (qh[1] & hm ? 16 : 0)) - m2);
+ }
+}
+template <typename dst_t>
+inline void dq_q5_1(const void *vx, int64_t ibs, dst_t *yy, int tid) {
+ const block_q5_1* x = (const block_q5_1*) vx + ibs * (QK_K / QK5_1);
+ const int ib = tid % 8, il = tid / 8;
+ const sycl::float2 dm =
+ (x[ib].dm).template convert<float, sycl::rounding_mode::automatic>();
+ uint32_t qh;
+ memcpy(&qh, x[ib].qh, sizeof(qh));
+ dst_t* y = yy + 32 * ib;
+ for (int j = 0; j < 4; ++j) {
+ const int iqs = 4 * il + j; // llama.cpp's dequantize_q5_1 for value pairs iqs, iqs + 16
+ const int xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10;
+ const int xh_1 = ((qh >> (iqs + 12))) & 0x10;
+ y[iqs] =
+ cvt<dst_t>((float)((x[ib].qs[iqs] & 0xf) | xh_0) * dm.x() + dm.y());
+ y[iqs + 16] =
+ cvt<dst_t>((float)((x[ib].qs[iqs] >> 4) | xh_1) * dm.x() + dm.y());
+ }
+}
+template <typename dst_t>
+inline void dq_q8_0(const void *vx, int64_t ibs, dst_t *yy, int tid) {
+ const block_q8_0* x = (const block_q8_0*) vx + ibs * (QK_K / QK8_0);
+ const int ib = tid % 8, il = tid / 8;
+ const float d = sycl::vec<sycl::half, 1>(x[ib].d)
+ .convert<float, sycl::rounding_mode::automatic>()[0];
+ dst_t* y = yy + 32 * ib + 8 * il;
+#pragma unroll
+ for (int j = 0; j < 8; ++j)
+ y[j] = cvt<dst_t>((float)x[ib].qs[8 * il + j] * d);
+}
+
+// Every type below must also be in is_iq(): the host entry points refuse the others, so the default is unreachable.
template <typename dst_t>
__dpct_inline__ void
dq_dispatch(int ty, const void *vx, int64_t ibs, dst_t *y, int tid) {
@@ -1106,6 +1834,10 @@ dq_dispatch(int ty, const void *vx, int64_t ibs, dst_t *y, int tid) {
case 23: dq_iq4_xs(vx, ibs, y, tid); break;
case 11: dq_q3_k(vx, ibs, y, tid); break;
case 42: dq_q2_0(vx, ibs, y, tid); break;
+ case 12: dq_q4_k(vx, ibs, y, tid); break;
+ case 13: dq_q5_k(vx, ibs, y, tid); break;
+ case 7: dq_q5_1(vx, ibs, y, tid); break;
+ case 8: dq_q8_0(vx, ibs, y, tid); break;
default: break;
}
}
@@ -1131,246 +1863,365 @@ __dpct_inline__ void dequant_gu_kernel(
item_ct1.get_local_id(2));
}
-bool is_iq(int t) { return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11; }
-
-} // namespace
-
-bool iq_supported(int t) noexcept { return is_iq(t); }
-
-size_t iq_row_bytes(int t, int64_t n) noexcept {
+// the types dq_dispatch dequantizes
+bool is_iq(int t) {
+ return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11 ||
+ t == 12 || t == 13 || t == 7 || t == 8;
+}
+// values per block of the types the grouped expert kernels take (0 = none)
+int gu_qk(int t) {
switch (t) {
- case 16: return (size_t) (n / 256) * sizeof(block_iq2_xxs);
- case 17: return (size_t) (n / 256) * sizeof(block_iq2_xs);
- case 18: return (size_t) (n / 256) * sizeof(block_iq3_xxs);
- case 20: return (size_t) (n / 32) * sizeof(block_iq4_nl);
- case 21: return (size_t) (n / 256) * sizeof(block_iq3_s);
- case 22: return (size_t) (n / 256) * sizeof(block_iq2_s);
- case 29: return (size_t) (n / 256) * sizeof(block_iq1_m);
- case 23: return (size_t) (n / 256) * sizeof(block_iq4_xs);
- case 11: return (size_t) (n / 256) * sizeof(block_q3_K);
- case 42: return (size_t) (n / 64) * sizeof(block_q2_0);
+#define STRATA_QK(T) case T: return Fmt<T>::qk;
+ STRATA_GU_FMTS(STRATA_QK)
+#undef STRATA_QK
default: return 0;
}
}
-
-void quantize_q8_1_rows(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream) {
- const long long n = (long long) n_rows * n_cols;
- if (n <= 0) return;
- {
- 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 quantize_q8_1_kernel_a566ca>>(
- sycl::nd_range<3>(
- sycl::range(1, 1, (unsigned)((n + 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(x, (block_q8_1 *)y, n);
- });
+int d_qk(int t) {
+ switch (t) {
+#define STRATA_QK(T) case T: return Fmt<T>::qk;
+ STRATA_D_FMTS(STRATA_QK)
+#undef STRATA_QK
+ default: return 0;
}
- check("quantize_q8_1_rows");
}
-void iq_mmvq(int t, const void* w, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {
+bool env_on(const char* name) {
+ const char* v = std::getenv(name);
+ return v != nullptr && v[0] != '\0' && v[0] != '0';
+}
+// STRATA_OLD_IQ_MMVQ=1 keeps the per-column kernels (bitwise equal to the new ones; kept for A/B timing)
+bool g_old_kernels = env_on("STRATA_OLD_IQ_MMVQ");
+// SYCL port (0.1.31 merge): upstream sends the split formats (the i-quants) to native_gu/down_multi_kernel, one warp
+// per row, 8 rows a group. On the B70 the port's grouped kernels (8 lanes a row, 32 rows a group, the multi-entry
+// dots with aligned loads and the IQ4 codebook in registers) are the measured ones, so they stay the default for
+// every format; STRATA_EXPERT_SPLIT=1 takes upstream's multi kernels, launched with their own grid (GU_ROWS rows).
+bool g_split_multi = env_on("STRATA_EXPERT_SPLIT");
+
+template <int TY>
+void launch_mmvq(const uint8_t *W, size_t rb, const block_q8_1 *X, float *y,
+ int n_in, int n_out, int ncols, dpct::queue_ptr s) {
const dpct::dim3 grid((unsigned)((n_out + 3) / 4)), block(32, 4);
- const size_t rb = iq_row_bytes(t, n_in);
- dpct::queue_ptr s = strata::q_of(stream);
- const auto* W = (const uint8_t*) w;
- const auto* X = (const block_q8_1*) x_q8_1;
- switch (t) {
- /*
- DPCT1049: The work-group size passed to the SYCL kernel may exceed
- the limit. To get the device limit, query
- info::device::max_work_group_size. Adjust the work-group size if needed.
- */
- case 16: {
+ /*
+ DPCT1049: The work-group size passed to the SYCL kernel may exceed the
+ limit. To get the device limit, query info::device::max_work_group_size.
+ Adjust the work-group size if needed.
+ */
+ if constexpr (!kSplit<TY>) {
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
s->submit([&](sycl::handler &cgh) {
- cgh.parallel_for<dpct_kernel_name<class mmvq_kernel_2769e1,
- dpct_kernel_scalar<16>>>(
+ cgh.parallel_for<dpct_kernel_name<class mmvq_kernel_87549a,
+ dpct_kernel_scalar<TY>>>(
sycl::nd_range<3>(grid * block, block), exp_props,
[=](sycl::nd_item<3> item_ct1)
[[sycl::reqd_sub_group_size(32)]] {
- mmvq_kernel<16>(W, rb, X, y, n_in, n_out, ncols);
+ mmvq_kernel<TY>(W, rb, X, y, n_in, n_out, ncols);
});
});
- } break;
- /*
- DPCT1049: The work-group size passed to the SYCL kernel may exceed
- the limit. To get the device limit, query
- info::device::max_work_group_size. Adjust the work-group size if needed.
- */
- case 17: {
+ }
+ /*
+ DPCT1049: The work-group size passed to the SYCL kernel may exceed the
+ limit. To get the device limit, query info::device::max_work_group_size.
+ Adjust the work-group size if needed.
+ */
+ else if (g_old_kernels) {
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
s->submit([&](sycl::handler &cgh) {
- cgh.parallel_for<dpct_kernel_name<class mmvq_kernel_4ee329,
- dpct_kernel_scalar<17>>>(
+ cgh.parallel_for<dpct_kernel_name<class mmvq_kernel_f617b1,
+ dpct_kernel_scalar<TY>>>(
sycl::nd_range<3>(grid * block, block), exp_props,
[=](sycl::nd_item<3> item_ct1)
[[sycl::reqd_sub_group_size(32)]] {
- mmvq_kernel<17>(W, rb, X, y, n_in, n_out, ncols);
+ mmvq_kernel<TY>(W, rb, X, y, n_in, n_out, ncols);
});
});
- } break;
- /*
- DPCT1049: The work-group size passed to the SYCL kernel may exceed
- the limit. To get the device limit, query
- info::device::max_work_group_size. Adjust the work-group size if needed.
- */
- case 18: {
+ }
+ /*
+ DPCT1049: The work-group size passed to the SYCL kernel may exceed the
+ limit. To get the device limit, query info::device::max_work_group_size.
+ Adjust the work-group size if needed.
+ */
+ else if (ncols <= 1) {
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
s->submit([&](sycl::handler &cgh) {
- cgh.parallel_for<dpct_kernel_name<class mmvq_kernel_34dcfe,
- dpct_kernel_scalar<18>>>(
+ cgh.parallel_for<dpct_kernel_name<class mmvq_multi_kernel_77d6d0,
+ dpct_kernel_scalar<TY>,
+ dpct_kernel_scalar<1>>>(
sycl::nd_range<3>(grid * block, block), exp_props,
[=](sycl::nd_item<3> item_ct1)
[[sycl::reqd_sub_group_size(32)]] {
- mmvq_kernel<18>(W, rb, X, y, n_in, n_out, ncols);
+ mmvq_multi_kernel<TY, 1>(W, rb, X, y, n_in, n_out,
+ ncols);
});
});
- } break;
- /*
- DPCT1049: The work-group size passed to the SYCL kernel may exceed
- the limit. To get the device limit, query
- info::device::max_work_group_size. Adjust the work-group size if needed.
- */
- case 20: {
+ }
+ /*
+ DPCT1049: The work-group size passed to the SYCL kernel may exceed the
+ limit. To get the device limit, query info::device::max_work_group_size.
+ Adjust the work-group size if needed.
+ */
+ else if (ncols == 2) {
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
s->submit([&](sycl::handler &cgh) {
- cgh.parallel_for<dpct_kernel_name<class mmvq_kernel_dfe57c,
- dpct_kernel_scalar<20>>>(
+ cgh.parallel_for<dpct_kernel_name<class mmvq_multi_kernel_7ba01c,
+ dpct_kernel_scalar<TY>,
+ dpct_kernel_scalar<2>>>(
sycl::nd_range<3>(grid * block, block), exp_props,
[=](sycl::nd_item<3> item_ct1)
[[sycl::reqd_sub_group_size(32)]] {
- mmvq_kernel<20>(W, rb, X, y, n_in, n_out, ncols);
+ mmvq_multi_kernel<TY, 2>(W, rb, X, y, n_in, n_out,
+ ncols);
});
});
- } break;
- /*
- DPCT1049: The work-group size passed to the SYCL kernel may exceed
- the limit. To get the device limit, query
- info::device::max_work_group_size. Adjust the work-group size if needed.
- */
- case 21: {
+ }
+ /*
+ DPCT1049: The work-group size passed to the SYCL kernel may exceed the
+ limit. To get the device limit, query info::device::max_work_group_size.
+ Adjust the work-group size if needed.
+ */
+ else if (ncols <= 4) {
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
s->submit([&](sycl::handler &cgh) {
- cgh.parallel_for<dpct_kernel_name<class mmvq_kernel_9d8f61,
- dpct_kernel_scalar<21>>>(
+ cgh.parallel_for<dpct_kernel_name<class mmvq_multi_kernel_6fd6d9,
+ dpct_kernel_scalar<TY>,
+ dpct_kernel_scalar<4>>>(
sycl::nd_range<3>(grid * block, block), exp_props,
[=](sycl::nd_item<3> item_ct1)
[[sycl::reqd_sub_group_size(32)]] {
- mmvq_kernel<21>(W, rb, X, y, n_in, n_out, ncols);
+ mmvq_multi_kernel<TY, 4>(W, rb, X, y, n_in, n_out,
+ ncols);
});
});
- } break;
- /*
- DPCT1049: The work-group size passed to the SYCL kernel may exceed
- the limit. To get the device limit, query
- info::device::max_work_group_size. Adjust the work-group size if needed.
- */
- case 22: {
+ }
+ /*
+ DPCT1049: The work-group size passed to the SYCL kernel may exceed the
+ limit. To get the device limit, query info::device::max_work_group_size.
+ Adjust the work-group size if needed.
+ */
+ else {
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
s->submit([&](sycl::handler &cgh) {
- cgh.parallel_for<dpct_kernel_name<class mmvq_kernel_979367,
- dpct_kernel_scalar<22>>>(
+ cgh.parallel_for<dpct_kernel_name<class mmvq_multi_kernel_6e0f6e,
+ dpct_kernel_scalar<TY>,
+ dpct_kernel_scalar<8>>>(
sycl::nd_range<3>(grid * block, block), exp_props,
[=](sycl::nd_item<3> item_ct1)
[[sycl::reqd_sub_group_size(32)]] {
- mmvq_kernel<22>(W, rb, X, y, n_in, n_out, ncols);
+ mmvq_multi_kernel<TY, 8>(W, rb, X, y, n_in, n_out,
+ ncols);
});
});
- } break;
- /*
- DPCT1049: The work-group size passed to the SYCL kernel may exceed
- the limit. To get the device limit, query
- info::device::max_work_group_size. Adjust the work-group size if needed.
- */
- case 23: {
+ } // 8 at a time past 8
+}
+
+// SYCL port: lanes per row of the port's grouped expert kernels at run time (STRATA_GU_LANES / STRATA_DOWN_LANES:
+// 4, 8, 16 or 32; default STRATA_EXPERT_LANES), 256 / lanes rows per work-group. Gate/up rows are 80 dot calls
+// (2560 wide), the IQ4_NL down rows 40 (640 wide), so the best split can differ by role.
+inline int lanes_env(const char* name) {
+ const char* v = std::getenv(name);
+ const int n = v ? std::atoi(v) : kExpertLanes;
+ return n == 4 || n == 8 || n == 16 || n == 32 ? n : kExpertLanes;
+}
+inline int gu_lanes() { static const int v = lanes_env("STRATA_GU_LANES"); return v; }
+inline int down_lanes() { static const int v = lanes_env("STRATA_DOWN_LANES"); return v; }
+template <int TG, int LN>
+void launch_gu_port(unsigned groups, dpct::queue_ptr s, const unsigned long long *grp_ptr, const int32_t *grp_start,
+ const int32_t *n_groups, const int32_t *ent_tok, const block_q8_1 *X,
+ const NativeExpertLayout &L, float *gate, float *up) {
+ constexpr int ROWS = 256 / LN;
+ const unsigned gx = (unsigned) ((2 * L.n_ff + ROWS - 1) / ROWS);
+ auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
+ s->parallel_for<dpct_kernel_name<class native_gu_port, dpct_kernel_scalar<TG>, dpct_kernel_scalar<LN>>>(
+ sycl::nd_range<3>(sycl::range<3>(1, groups, (size_t) gx * 256), sycl::range<3>(1, 1, 256)), exp_props,
+ [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
+ native_gu_kernel<TG, LN>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
+ });
+}
+template <int TG>
+void launch_gu_lanes(dpct::dim3 grid, dpct::queue_ptr s, const unsigned long long *grp_ptr, const int32_t *grp_start,
+ const int32_t *n_groups, const int32_t *ent_tok, const block_q8_1 *X,
+ const NativeExpertLayout &L, float *gate, float *up) {
+ switch (gu_lanes()) {
+ case 4: launch_gu_port<TG, 4>(grid.y, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
+ case 16: launch_gu_port<TG, 16>(grid.y, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
+ case 32: launch_gu_port<TG, 32>(grid.y, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
+ default: launch_gu_port<TG, 8>(grid.y, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
+ }
+}
+template <int TD, int LN>
+void launch_down_port(unsigned groups, dpct::queue_ptr s, const unsigned long long *grp_ptr, const int32_t *grp_start,
+ const int32_t *n_groups, const int32_t *ent_dst, const block_q8_1 *hq,
+ const NativeExpertLayout &L, float *out) {
+ constexpr int ROWS = 256 / LN;
+ const unsigned gx = (unsigned) ((L.n_embd + ROWS - 1) / ROWS);
+ auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
+ s->parallel_for<dpct_kernel_name<class native_down_port, dpct_kernel_scalar<TD>, dpct_kernel_scalar<LN>>>(
+ sycl::nd_range<3>(sycl::range<3>(1, groups, (size_t) gx * 256), sycl::range<3>(1, 1, 256)), exp_props,
+ [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
+ native_down_kernel<TD, LN>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
+ });
+}
+template <int TD>
+void launch_down_lanes(dpct::dim3 grid, dpct::queue_ptr s, const unsigned long long *grp_ptr, const int32_t *grp_start,
+ const int32_t *n_groups, const int32_t *ent_dst, const block_q8_1 *hq,
+ const NativeExpertLayout &L, float *out) {
+ switch (down_lanes()) {
+ case 4: launch_down_port<TD, 4>(grid.y, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
+ case 16: launch_down_port<TD, 16>(grid.y, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
+ case 32: launch_down_port<TD, 32>(grid.y, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
+ default: launch_down_port<TD, 8>(grid.y, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
+ }
+}
+
+template <int TG>
+void launch_gu(dpct::dim3 grid, dpct::queue_ptr s,
+ const unsigned long long *grp_ptr, const int32_t *grp_start,
+ const int32_t *n_groups, const int32_t *ent_tok,
+ const block_q8_1 *X, const NativeExpertLayout &L, float *gate,
+ float *up) {
+ if constexpr (!kSplit<TG>) {
+
+ launch_gu_lanes<TG>(grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
+ } else if (g_old_kernels || !g_split_multi) {
+
+ launch_gu_lanes<TG>(grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
+ } else {
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
s->submit([&](sycl::handler &cgh) {
- cgh.parallel_for<dpct_kernel_name<class mmvq_kernel_15e579,
- dpct_kernel_scalar<23>>>(
- sycl::nd_range<3>(grid * block, block), exp_props,
+ cgh.parallel_for<dpct_kernel_name<
+ class native_gu_multi_kernel_37f479, dpct_kernel_scalar<TG>>>(
+ sycl::nd_range<3>(dpct::dim3((unsigned) ((2 * L.n_ff + GU_ROWS - 1) / GU_ROWS), grid.y) * sycl::range(1, 1, 256),
+ sycl::range(1, 1, 256)),
+ exp_props,
[=](sycl::nd_item<3> item_ct1)
[[sycl::reqd_sub_group_size(32)]] {
- mmvq_kernel<23>(W, rb, X, y, n_in, n_out, ncols);
+ native_gu_multi_kernel<TG>(grp_ptr, grp_start, n_groups,
+ ent_tok, X, L, gate, up);
});
});
- } break;
- /*
- DPCT1049: The work-group size passed to the SYCL kernel may exceed
- the limit. To get the device limit, query
- info::device::max_work_group_size. Adjust the work-group size if needed.
- */
- case 29: {
+ }
+}
+
+template <int TD>
+void launch_down(dpct::dim3 grid, dpct::queue_ptr s,
+ const unsigned long long *grp_ptr, const int32_t *grp_start,
+ const int32_t *n_groups, const int32_t *ent_dst,
+ const block_q8_1 *hq, const NativeExpertLayout &L,
+ float *out) {
+ if constexpr (!kSplit<TD>) {
+
+ launch_down_lanes<TD>(grid, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
+ } else if (g_old_kernels || !g_split_multi) {
+
+ launch_down_lanes<TD>(grid, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
+ } else {
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
s->submit([&](sycl::handler &cgh) {
- cgh.parallel_for<dpct_kernel_name<class mmvq_kernel_bc4076,
- dpct_kernel_scalar<29>>>(
- sycl::nd_range<3>(grid * block, block), exp_props,
+ cgh.parallel_for<dpct_kernel_name<
+ class native_down_multi_kernel_490cef, dpct_kernel_scalar<TD>>>(
+ sycl::nd_range<3>(dpct::dim3((unsigned) ((L.n_embd + GU_ROWS - 1) / GU_ROWS), grid.y) * sycl::range(1, 1, 256),
+ sycl::range(1, 1, 256)),
+ exp_props,
[=](sycl::nd_item<3> item_ct1)
[[sycl::reqd_sub_group_size(32)]] {
- mmvq_kernel<29>(W, rb, X, y, n_in, n_out, ncols);
+ native_down_multi_kernel<TD>(grp_ptr, grp_start,
+ n_groups, ent_dst, hq, L,
+ out);
});
});
- } break;
- /*
- DPCT1049: The work-group size passed to the SYCL kernel may exceed
- the limit. To get the device limit, query
- info::device::max_work_group_size. Adjust the work-group size if needed.
- */
- case 42: {
+ }
+}
+
+} // namespace
+
+void iq_set_old_kernels(bool old) { g_old_kernels = old; }
+bool iq_old_kernels() { return g_old_kernels; }
+
+bool iq_supported(int t) noexcept { return is_iq(t); }
+size_t iq_row_bytes(int t, int64_t n) noexcept {
+ switch (t) {
+ case 16: return (size_t) (n / 256) * sizeof(block_iq2_xxs);
+ case 17: return (size_t) (n / 256) * sizeof(block_iq2_xs);
+ case 18: return (size_t) (n / 256) * sizeof(block_iq3_xxs);
+ case 20: return (size_t) (n / 32) * sizeof(block_iq4_nl);
+ case 21: return (size_t) (n / 256) * sizeof(block_iq3_s);
+ case 22: return (size_t) (n / 256) * sizeof(block_iq2_s);
+ case 29: return (size_t) (n / 256) * sizeof(block_iq1_m);
+ case 23: return (size_t) (n / 256) * sizeof(block_iq4_xs);
+ case 11: return (size_t) (n / 256) * sizeof(block_q3_K);
+ case 42: return (size_t) (n / 64) * sizeof(block_q2_0);
+ case 12: return (size_t) (n / 256) * sizeof(block_q4_K);
+ case 13: return (size_t) (n / 256) * sizeof(block_q5_K);
+ case 7: return (size_t) (n / 32) * sizeof(block_q5_1);
+ case 8: return (size_t) (n / 32) * sizeof(block_q8_0);
+ default: return 0;
+ }
+}
+
+void quantize_q8_1_rows(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream) {
+ const long long n = (long long) n_rows * n_cols;
+ if (n <= 0) return;
+ {
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
- s->submit([&](sycl::handler &cgh) {
-
- cgh.parallel_for<dpct_kernel_name<class mmvq_kernel_2c3d4c,
- dpct_kernel_scalar<42>>>(
- sycl::nd_range<3>(grid * block, block), exp_props,
+ strata::q_of(stream)
+ ->parallel_for<dpct_kernel_name<class quantize_q8_1_kernel_9d62b4>>(
+ sycl::nd_range<3>(
+ sycl::range(1, 1, (unsigned)((n + 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)]] {
- mmvq_kernel<42>(W, rb, X, y, n_in, n_out, ncols);
+ quantize_q8_1_kernel(x, (block_q8_1 *)y, n);
});
- });
- } break;
+ }
+ check("quantize_q8_1_rows");
+}
+
+void iq_mmvq(int t, const void* w, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {
+ const size_t rb = iq_row_bytes(t, n_in);
+ dpct::queue_ptr s = strata::q_of(stream);
+ const auto* W = (const uint8_t*) w;
+ const auto* X = (const block_q8_1*) x_q8_1;
+ switch (t) {
+#define STRATA_MMVQ(T) case T: launch_mmvq<T>(W, rb, X, y, n_in, n_out, ncols, s); break;
+ STRATA_MMVQ_FMTS(STRATA_MMVQ)
+#undef STRATA_MMVQ
default: std::fprintf(stderr, "iq_mmvq: type %d is not supported\n", t); std::exit(1);
}
check("iq_mmvq");
@@ -1475,6 +2326,8 @@ void iq_dequant_f32(int t, const void* src, int64_t n, float* dst, void* stream)
}
void iq_dequant_gu_f16(int t, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst, void* stream) {
+ // checked like the other entry points: an unknown type used to leave `dst` unwritten, a wrong prompt and no error
+ if (n_embd % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_gu_f16: type %d / %lld\n", t, (long long) n_embd); std::exit(1); }
const int64_t per_row = n_embd / 256;
{
@@ -1502,6 +2355,12 @@ void iq_dequant_gu_f16(int t, const void* gate, const void* up, int64_t n_ff, in
check("iq_dequant_gu_f16");
}
+bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept {
+ const int qg = gu_qk(gu_type), qd = d_qk(d_type);
+ return qg > 0 && qd > 0 && is_iq(gu_type) && is_iq(d_type) && n_embd % qg == 0 && n_ff % qd == 0 &&
+ n_embd % 256 == 0 && (n_ff * n_embd) % 256 == 0;
+}
+
NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) {
NativeExpertLayout L;
L.gu_type = gu_type;
@@ -1535,158 +2394,9 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long
const dpct::dim3 ggu((unsigned)((2 * L.n_ff + kExpertRows - 1) / kExpertRows),
(unsigned)cap_groups);
switch (L.gu_type) {
- case 16: {
-
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- s->submit([&](sycl::handler &cgh) {
-
- cgh.parallel_for<dpct_kernel_name<class native_gu_kernel_472f9a,
- dpct_kernel_scalar<16>>>(
- sycl::nd_range<3>(ggu * sycl::range(1, 1, 256),
- sycl::range(1, 1, 256)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- native_gu_kernel<16>(grp_ptr, grp_start, n_groups,
- ent_tok, X, L, gate, up);
- });
- });
- } break;
- case 17: {
-
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- s->submit([&](sycl::handler &cgh) {
-
- cgh.parallel_for<dpct_kernel_name<class native_gu_kernel_3af217,
- dpct_kernel_scalar<17>>>(
- sycl::nd_range<3>(ggu * sycl::range(1, 1, 256),
- sycl::range(1, 1, 256)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- native_gu_kernel<17>(grp_ptr, grp_start, n_groups,
- ent_tok, X, L, gate, up);
- });
- });
- } break;
- case 18: {
-
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- s->submit([&](sycl::handler &cgh) {
-
- cgh.parallel_for<dpct_kernel_name<class native_gu_kernel_17c573,
- dpct_kernel_scalar<18>>>(
- sycl::nd_range<3>(ggu * sycl::range(1, 1, 256),
- sycl::range(1, 1, 256)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- native_gu_kernel<18>(grp_ptr, grp_start, n_groups,
- ent_tok, X, L, gate, up);
- });
- });
- } break;
- case 21: {
-
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- s->submit([&](sycl::handler &cgh) {
-
- cgh.parallel_for<dpct_kernel_name<class native_gu_kernel_1f1e65,
- dpct_kernel_scalar<21>>>(
- sycl::nd_range<3>(ggu * sycl::range(1, 1, 256),
- sycl::range(1, 1, 256)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- native_gu_kernel<21>(grp_ptr, grp_start, n_groups,
- ent_tok, X, L, gate, up);
- });
- });
- } break;
- case 22: {
-
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- s->submit([&](sycl::handler &cgh) {
-
- cgh.parallel_for<dpct_kernel_name<class native_gu_kernel_5b900c,
- dpct_kernel_scalar<22>>>(
- sycl::nd_range<3>(ggu * sycl::range(1, 1, 256),
- sycl::range(1, 1, 256)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- native_gu_kernel<22>(grp_ptr, grp_start, n_groups,
- ent_tok, X, L, gate, up);
- });
- });
- } break;
- case 23: {
-
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- s->submit([&](sycl::handler &cgh) {
-
- cgh.parallel_for<dpct_kernel_name<class native_gu_kernel_ca9850,
- dpct_kernel_scalar<23>>>(
- sycl::nd_range<3>(ggu * sycl::range(1, 1, 256),
- sycl::range(1, 1, 256)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- native_gu_kernel<23>(grp_ptr, grp_start, n_groups,
- ent_tok, X, L, gate, up);
- });
- });
- } break;
- case 29: {
-
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- s->submit([&](sycl::handler &cgh) {
-
- cgh.parallel_for<dpct_kernel_name<class native_gu_kernel_5ad3a4,
- dpct_kernel_scalar<29>>>(
- sycl::nd_range<3>(ggu * sycl::range(1, 1, 256),
- sycl::range(1, 1, 256)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- native_gu_kernel<29>(grp_ptr, grp_start, n_groups,
- ent_tok, X, L, gate, up);
- });
- });
- } break;
- case 42: {
-
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- s->submit([&](sycl::handler &cgh) {
-
- cgh.parallel_for<dpct_kernel_name<class native_gu_kernel_331601,
- dpct_kernel_scalar<42>>>(
- sycl::nd_range<3>(ggu * sycl::range(1, 1, 256),
- sycl::range(1, 1, 256)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- native_gu_kernel<42>(grp_ptr, grp_start, n_groups,
- ent_tok, X, L, gate, up);
- });
- });
- } break;
+#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)
+#undef STRATA_GU
default: std::fprintf(stderr, "native_expert_grouped: gate/up type %d\n", L.gu_type); std::exit(1);
}
check("native_expert_grouped/gu");
@@ -1718,63 +2428,9 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long
}
const dpct::dim3 gd((unsigned)((L.n_embd + kExpertRows - 1) / kExpertRows), (unsigned)cap_groups);
switch (L.d_type) {
- case 20: {
-
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- s->submit([&](sycl::handler &cgh) {
-
- cgh.parallel_for<dpct_kernel_name<class native_down_kernel_f2a0ef,
- dpct_kernel_scalar<20>>>(
- sycl::nd_range<3>(gd * sycl::range(1, 1, 256),
- sycl::range(1, 1, 256)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- native_down_kernel<20>(grp_ptr, grp_start, n_groups,
- ent_dst, hq, L, out);
- });
- });
- } break;
- case 23: {
-
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- s->submit([&](sycl::handler &cgh) {
-
- cgh.parallel_for<dpct_kernel_name<class native_down_kernel_cf19c8,
- dpct_kernel_scalar<23>>>(
- sycl::nd_range<3>(gd * sycl::range(1, 1, 256),
- sycl::range(1, 1, 256)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- native_down_kernel<23>(grp_ptr, grp_start, n_groups,
- ent_dst, hq, L, out);
- });
- });
- } break;
- case 42: {
-
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- s->submit([&](sycl::handler &cgh) {
-
- cgh.parallel_for<dpct_kernel_name<class native_down_kernel_57a5b9,
- dpct_kernel_scalar<42>>>(
- sycl::nd_range<3>(gd * sycl::range(1, 1, 256),
- sycl::range(1, 1, 256)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- native_down_kernel<42>(grp_ptr, grp_start, n_groups,
- ent_dst, hq, L, out);
- });
- });
- } break;
+#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)
+#undef STRATA_DOWN
default: std::fprintf(stderr, "native_expert_grouped: down type %d\n", L.d_type); std::exit(1);
}
check("native_expert_grouped/down");
diff --git a/sycl/src/kernels/cuda/native_flash_attn.dp.cpp b/sycl/src/kernels/cuda/native_flash_attn.dp.cpp
index 4b2d29512..33e19c894 100644
--- a/sycl/src/kernels/cuda/native_flash_attn.dp.cpp
+++ b/sycl/src/kernels/cuda/native_flash_attn.dp.cpp
@@ -262,17 +262,17 @@ attend(const float *__restrict__ q, const sycl::half *__restrict__ k,
#pragma unroll
for (int i = 0; i < 16; ++i) {
/*
- 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.
+ 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.
*/
vkq[i].x() = vkq[i].x() * rescale;
/*
- 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.
+ 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.
*/
vkq[i].y() = vkq[i].y() * rescale;
}
diff --git a/sycl/src/kernels/cuda/native_gr_postops.dp.cpp b/sycl/src/kernels/cuda/native_gr_postops.dp.cpp
index 436af20f3..48d9be425 100644
--- a/sycl/src/kernels/cuda/native_gr_postops.dp.cpp
+++ b/sycl/src/kernels/cuda/native_gr_postops.dp.cpp
@@ -74,25 +74,25 @@ pre_gated(const float *__restrict__ xn, float *__restrict__ gate,
const std::size_t i = std::size_t(c) * n_embd + d;
const float x = xn[i], w = sigmoid(gate[i]);
/*
- 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.
+ 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 product = x * w;
gate[i] = product;
/*
- 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.
+ 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.
*/
if constexpr (Fused) sum = sycl::fma(x, w, sum);
/*
- 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.
+ 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.
*/
else sum = c == 0 ? product : sum + product;
}
diff --git a/sycl/src/kernels/cuda/native_mmvq.dp.cpp b/sycl/src/kernels/cuda/native_mmvq.dp.cpp
index 406711222..177fa97d0 100644
--- a/sycl/src/kernels/cuda/native_mmvq.dp.cpp
+++ b/sycl/src/kernels/cuda/native_mmvq.dp.cpp
@@ -29,6 +29,7 @@
#include "strata/sycl_math.hpp"
#include "strata/sycl_queue.hpp"
#include "strata/kernels/native_mmvq.hpp"
+#include "strata/kernels/dp4a.hpp"
#include "strata/kernels/iq_kernels.hpp"
#include <cstdint>
@@ -211,10 +212,8 @@ q5_q8_dot_impl(const int *__restrict__ vl, const int *__restrict__ vh,
const int vh1i = ((vh[1] >> i) << 4) & 0x10101010;
const int v0i = vl0i | vh0i;
const int v1i = vl1i | vh1i;
- const int dot1 =
- strata::dp4a(v0i, u[2 * i], strata::dp4a(v1i, u[2 * i + 1], 0));
- const int dot2 = strata::dp4a(0x01010101, u[2 * i],
- strata::dp4a(0x01010101, u[2 * i + 1], 0));
+ const int dot1 = STRATA_DP4A(v0i, u[2 * i], STRATA_DP4A(v1i, u[2 * i + 1], 0));
+ const int dot2 = STRATA_DP4A(0x01010101, u[2 * i], STRATA_DP4A(0x01010101, u[2 * i + 1], 0));
sumf_d += d8[i] * (dot1 * sc[i]);
sumf_m += d8[i] * (dot2 * m[i]);
}
@@ -224,10 +223,10 @@ q5_q8_dot_impl(const int *__restrict__ vl, const int *__restrict__ vh,
}
/*
-DPCT1110: The total declared local variable size in device function
-q5_q8_dot 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.
+DPCT1110: The total declared local variable size in device function q5_q8_dot
+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__ float q5_q8_dot(const Q5KBlock *__restrict__ bq5,
const Q81Block *__restrict__ bq8, int iqs) {
@@ -342,8 +341,8 @@ __dpct_inline__ float q2_q8_dot(const Q20Block *__restrict__ w,
const int qo = dpct::byte_level_permute(0x020100ff, 0x020100ff, q >> 2);
const int qx = dpct::byte_level_permute(qe, qo, 0x5140);
const int qy = dpct::byte_level_permute(qe, qo, 0x7362);
- sumi = strata::dp4a(u, qx, sumi);
- sumi = strata::dp4a(v, qy, sumi);
+ sumi = STRATA_DP4A(u, qx, sumi);
+ sumi = STRATA_DP4A(v, qy, sumi);
}
const float d8 = chunk->ds[0];
return d2 * d8 * sumi;
@@ -430,7 +429,7 @@ __dpct_inline__ float q3_q8_dot_impl(int vl, int vh, const int *__restrict__ u,
const int vih = ((vh >> i) << 2) & 0x04040404;
const int vi =
dpct::vectorized_binary<sycl::char4>(vil, vih, dpct::sub_sat());
- sumf += d8[i] * (strata::dp4a(vi, u[i], 0) * sc);
+ sumf += d8[i] * (STRATA_DP4A(vi, u[i], 0) * sc);
}
return d3 * sumf;
}
@@ -541,8 +540,8 @@ __dpct_inline__ float iq4_xs_q8_dot(const IQ4XSBlock *__restrict__ w,
const sycl::int2 v = iq4_table_lookup(aux_q4, iq4nl_values);
const int u0 = reinterpret_cast<const int*>(x[iqs / 4].qs)[j];
const int u1 = reinterpret_cast<const int*>(x[iqs / 4].qs)[j + 4];
- sumi = strata::dp4a(v.x(), u0, sumi);
- sumi = strata::dp4a(v.y(), u1, sumi);
+ sumi = STRATA_DP4A(v.x(), u0, sumi);
+ sumi = STRATA_DP4A(v.y(), u1, sumi);
}
const int ls = ((w->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0f) |
(((w->scales_h >> (iqs / 2)) & 0x03) << 4);
@@ -616,10 +615,8 @@ q4_q8_dot_impl(const int *__restrict__ v, const int *__restrict__ u,
for (int i = 0; i < 2; ++i) {
const int v0i = (v[0] >> (4 * i)) & 0x0f0f0f0f;
const int v1i = (v[1] >> (4 * i)) & 0x0f0f0f0f;
- const int dot1 =
- strata::dp4a(v1i, u[2 * i + 1], strata::dp4a(v0i, u[2 * i], 0));
- const int dot2 = strata::dp4a(0x01010101, u[2 * i + 1],
- strata::dp4a(0x01010101, u[2 * i], 0));
+ const int dot1 = STRATA_DP4A(v1i, u[2 * i + 1], STRATA_DP4A(v0i, u[2 * i], 0));
+ const int dot2 = STRATA_DP4A(0x01010101, u[2 * i + 1], STRATA_DP4A(0x01010101, u[2 * i], 0));
sumf_d += d8[i] * (dot1 * sc[i]);
sumf_m += d8[i] * (dot2 * m[i]);
}
@@ -731,7 +728,7 @@ __dpct_inline__ float q6_q8_dot_impl(int vl, int vh, const int *__restrict__ u,
const int vih = ((vh >> (4 * i)) << 4) & 0x30303030;
const int vi = dpct::vectorized_binary<sycl::char4>(
vil | vih, 0x20202020, dpct::sub_sat());
- sumf += d8[i] * (strata::dp4a(vi, u[i], 0) * sc);
+ sumf += d8[i] * (STRATA_DP4A(vi, u[i], 0) * sc);
}
return d * sumf;
}
@@ -817,10 +814,8 @@ __dpct_inline__ float small_q8_dot(const Q40Block *__restrict__ w,
const int v = load_int_b2(w->qs, iqs + i);
const int vi0 = (v >> 0) & 0x0f0f0f0f;
const int vi1 = (v >> 4) & 0x0f0f0f0f;
- sumi = strata::dp4a(vi0, reinterpret_cast<const int *>(x->qs)[iqs + i],
- sumi);
- sumi = strata::dp4a(
- vi1, reinterpret_cast<const int *>(x->qs)[iqs + i + 4], sumi);
+ sumi = STRATA_DP4A(vi0, reinterpret_cast<const int*>(x->qs)[iqs + i], sumi);
+ sumi = STRATA_DP4A(vi1, reinterpret_cast<const int*>(x->qs)[iqs + i + 4], sumi);
}
const sycl::float2 ds =
(x->ds).template convert<float, sycl::rounding_mode::automatic>();
@@ -841,15 +836,13 @@ __dpct_inline__ float small_q8_dot(const Q50Block *__restrict__ w,
vi0 |= (vh << 11) & 0x00001000;
vi0 |= (vh << 18) & 0x00100000;
vi0 |= (vh << 25) & 0x10000000;
- sumi = strata::dp4a(vi0, reinterpret_cast<const int *>(x->qs)[iqs + i],
- sumi);
+ sumi = STRATA_DP4A(vi0, reinterpret_cast<const int*>(x->qs)[iqs + i], sumi);
int vi1 = (vl >> 4) & 0x0f0f0f0f;
vi1 |= (vh >> 12) & 0x00000010;
vi1 |= (vh >> 5) & 0x00001000;
vi1 |= (vh << 2) & 0x00100000;
vi1 |= (vh << 9) & 0x10000000;
- sumi = strata::dp4a(
- vi1, reinterpret_cast<const int *>(x->qs)[iqs + i + 4], sumi);
+ sumi = STRATA_DP4A(vi1, reinterpret_cast<const int*>(x->qs)[iqs + i + 4], sumi);
}
const sycl::float2 ds =
(x->ds).template convert<float, sycl::rounding_mode::automatic>();
@@ -865,7 +858,7 @@ __dpct_inline__ float small_q8_dot(const Q80Block *__restrict__ w,
for (int i = 0; i < 2; ++i) {
const int v = load_int_b2(w->qs, iqs + i);
const int u = reinterpret_cast<const int*>(x->qs)[iqs + i];
- sumi = strata::dp4a(v, u, sumi);
+ sumi = STRATA_DP4A(v, u, sumi);
}
const float d0 = w->d;
const float d1 = x->ds[0];
@@ -881,8 +874,8 @@ __dpct_inline__ float small_q8_dot(const IQ4NLBlock *__restrict__ w,
for (int i = 0; i < 2; ++i) {
const sycl::int2 v =
iq4_table_lookup(load_int_b2(w->qs, iqs + i), iq4nl_values);
- sumi = strata::dp4a(v.x(), q8[i], sumi);
- sumi = strata::dp4a(v.y(), q8[i + 4], sumi);
+ sumi = STRATA_DP4A(v.x(), q8[i], sumi);
+ sumi = STRATA_DP4A(v.y(), q8[i + 4], sumi);
}
const float d = sycl::vec<sycl::half, 1>(w->d)
.convert<float, sycl::rounding_mode::automatic>()[0] *
@@ -1065,8 +1058,8 @@ struct Q20Traits {
int sumi = 0;
#pragma unroll
for (int j = 0; j < 4; ++j) {
- sumi = strata::dp4a(q8[j * 2], r.qx[j], sumi);
- sumi = strata::dp4a(q8[j * 2 + 1], r.qy[j], sumi);
+ sumi = STRATA_DP4A(q8[j * 2], r.qx[j], sumi);
+ sumi = STRATA_DP4A(q8[j * 2 + 1], r.qy[j], sumi);
}
const float d8 = chunk->ds[0];
return r.d2 * d8 * sumi;
@@ -1171,8 +1164,8 @@ struct IQ4XSTraits {
for (int j = 0; j < 4; ++j) {
const int u0 = reinterpret_cast<const int*>(x[iqs / 4].qs)[j];
const int u1 = reinterpret_cast<const int*>(x[iqs / 4].qs)[j + 4];
- sumi = strata::dp4a(r.v[j].x(), u0, sumi);
- sumi = strata::dp4a(r.v[j].y(), u1, sumi);
+ sumi = STRATA_DP4A(r.v[j].x(), u0, sumi);
+ sumi = STRATA_DP4A(r.v[j].y(), u1, sumi);
}
sumi *= r.ls - 32;
const float d = r.dw * x[iqs / 4].ds[0];
diff --git a/sycl/src/kernels/cuda/native_qsa_indexer.dp.cpp b/sycl/src/kernels/cuda/native_qsa_indexer.dp.cpp
index c216b8d5e..3c3c062c0 100644
--- a/sycl/src/kernels/cuda/native_qsa_indexer.dp.cpp
+++ b/sycl/src/kernels/cuda/native_qsa_indexer.dp.cpp
@@ -48,12 +48,15 @@ inline float warp_sum(float x) {
offset);
return x;
}
-__dpct_inline__ void
-append(const float *__restrict__ raw, const int32_t *__restrict__ pos_dev,
- int pos_base, const float *__restrict__ gamma, float epsilon,
- float *__restrict__ tail, float *__restrict__ dead,
- float *__restrict__ pooled, int32_t *__restrict__ block_pos,
- int max_cells, float theta_scale, const int32_t *__restrict__ mtab) {
+__dpct_inline__ void append(const float *__restrict__ raw,
+ const int32_t *__restrict__ pos_dev, int pos_base,
+ const float *__restrict__ gamma, float epsilon,
+ float *__restrict__ tail, float *__restrict__ dead,
+ float *__restrict__ pooled,
+ int32_t *__restrict__ block_pos, int max_cells,
+ float theta_scale, float freq_scale, float corr_low,
+ float corr_high, float ext_factor, float mscale,
+ const int32_t *__restrict__ mtab) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
const int pos = *pos_dev, d = item_ct1.get_local_id(2);
if (pos < 0 || pos >= max_cells) return;
@@ -87,7 +90,7 @@ append(const float *__restrict__ raw, const int32_t *__restrict__ pos_dev,
Verify the correctness. SYCL math built-in function rounding mode is
aligned with OpenCL C 1.2 standard.
*/
- sum = sum + pos == 0 || j == R - 1 ? incoming : tail[j * D + d];
+ sum = sum + (pos == 0 || j == R - 1 ? incoming : tail[j * D + d]);
/*
DPCT1013: The rounding mode could not be specified and the generated
code may have different accuracy than the original code. Verify the
@@ -123,9 +126,13 @@ append(const float *__restrict__ raw, const int32_t *__restrict__ pos_dev,
float y = values[d];
if (d < ROT) {
const int pair = d % (ROT / 2);
- const float theta = (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) *
- dpct::pow(theta_scale, float(pair));
- const float c = sycl::cos((float)theta), s = sycl::sin((float)theta);
+ // The spare (pos == 0) keeps its zero angle; under YaRN the mscale magnitude still rides in
+ // through cos(0) - which is exactly what the queries are scaled by, so the top-k is unmoved.
+ const float theta_extrap =
+ (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) *
+ dpct::pow(theta_scale, float(pair));
+ float c, s;
+ rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s);
const float a = values[pair], z = values[pair + ROT / 2];
y = d < ROT / 2 ? a * c - z * s : a * s + z * c;
}
@@ -140,14 +147,21 @@ append(const float *__restrict__ raw, const int32_t *__restrict__ pos_dev,
// (cell >= p0) or the tail the previous batch left (cell < p0). Only the batch's last completed block writes the
// spare after it (every earlier one's is overwritten by the next block in order).
__dpct_inline__ float pooled_value(const float *values, int d, int rope_pos,
- float theta_scale, const int32_t *mtab,
- bool zero_pos) {
+ float theta_scale, float freq_scale,
+ float corr_low, float corr_high,
+ float ext_factor, float mscale,
+ const int32_t *mtab, bool zero_pos) {
float y = values[d];
if (d < ROT) {
const int pair = d % (ROT / 2);
- const float theta = (zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair)) *
- dpct::pow(theta_scale, float(pair));
- const float c = sycl::cos((float)theta), s = sycl::sin((float)theta);
+ // The same rotation the single append applies, rope_scaling.hpp's helper shared: under none this is
+ // today's cosf/sinf; under linear/YaRN the pooled keys move with the cache's K, and the spare's zero
+ // angle carries the mscale magnitude through cos(0) exactly as the single append's does.
+ const float theta_extrap =
+ (zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair)) *
+ dpct::pow(theta_scale, float(pair));
+ float c, s;
+ rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s);
const float a = values[pair], z = values[pair + ROT / 2];
y = d < ROT / 2 ? a * c - z * s : a * s + z * c;
}
@@ -169,11 +183,12 @@ __dpct_inline__ float norm_scale(float mean, float *partials, int d) {
return square_sum;
}
// cell 0 of a sequence: the spare (every gather index names cell 0), written to pooled[0] and dead
-__dpct_inline__ void append_first(const float *__restrict__ raw,
- const float *__restrict__ gamma,
- float epsilon, float *__restrict__ dead,
- float *__restrict__ pooled, float theta_scale,
- const int32_t *__restrict__ mtab) {
+__dpct_inline__ void
+append_first(const float *__restrict__ raw, const float *__restrict__ gamma,
+ float epsilon, float *__restrict__ dead,
+ float *__restrict__ pooled, float theta_scale, float freq_scale,
+ float corr_low, float corr_high, float ext_factor, float mscale,
+ const int32_t *__restrict__ mtab) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
const int d = item_ct1.get_local_id(2);
auto &values =
@@ -217,7 +232,8 @@ __dpct_inline__ void append_first(const float *__restrict__ raw,
*/
item_ct1.barrier(sycl::access::fence_space::local_space);
if (d >= D) return;
- const float y = pooled_value(values, d, 0, theta_scale, mtab, true);
+ const float y = pooled_value(values, d, 0, theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale,
+ mtab, true);
pooled[d] = y;
dead[d] = y;
}
@@ -227,6 +243,8 @@ append_blocks(const float *__restrict__ raw, int64_t n, int64_t p0,
const float *__restrict__ tail, const float *__restrict__ dead,
float *__restrict__ pooled, int32_t *__restrict__ block_pos,
int64_t first_block, int64_t last_block, float theta_scale,
+ float freq_scale, float corr_low, float corr_high,
+ float ext_factor, float mscale,
const int32_t *__restrict__ mtab) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
const int64_t b = first_block + item_ct1.get_group(2);
@@ -273,7 +291,8 @@ append_blocks(const float *__restrict__ raw, int64_t n, int64_t p0,
item_ct1.barrier(sycl::access::fence_space::local_space);
if (d >= D) return;
const int rope_pos = pos_base + R * (int) b;
- pooled[std::size_t(b) * D + d] = pooled_value(values, d, rope_pos, theta_scale, mtab, false);
+ pooled[std::size_t(b) * D + d] = pooled_value(values, d, rope_pos, theta_scale, freq_scale, corr_low, corr_high,
+ ext_factor, mscale, mtab, false);
if (b == last_block) {
pooled[std::size_t(b + 1) * D + d] = dead[d];
if (d == 0) *block_pos = rope_pos;
@@ -310,25 +329,26 @@ void native_qsa_indexer_set_enabled(bool value) { enabled.store(value, std::memo
bool native_qsa_indexer_enabled() { return enabled.load(std::memory_order_relaxed); }
void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_device, int32_t pos_base,
const float* gamma, float epsilon, const QsaIndexerBuffers& b,
- const QsaShapes& s, int64_t max_cells, float freq_base, void* stream) {
+ const QsaShapes& s, int64_t max_cells, const RopeScaling& scaling, void* stream) {
if (!stream || s.idx_dim != D || s.idx_block != R || s.n_rot != ROT ||
max_cells < 1 || max_cells > INT32_MAX || pos_base < 0 || pos_base % R ||
int64_t(pos_base) + max_cells > INT32_MAX || !std::isfinite(epsilon) || epsilon <= 0.0f ||
- !std::isfinite(freq_base) || freq_base <= 1.0f)
- throw std::invalid_argument("native QSA indexer requires fixed geometry, aligned position base, positive capacity/epsilon, valid frequency and explicit stream");
+ rope_scaling_invalid(scaling) != nullptr)
+ throw std::invalid_argument("native QSA indexer requires fixed geometry, aligned position base, positive capacity/epsilon, valid frequency/scaling and explicit stream");
const Span spans[] = {{raw,D*4},{relative_pos_device,4},{gamma,D*4},{b.tail,(R-1)*D*4},
{b.dead,D*4},{b.pooled,std::size_t(max_cells/R+1)*D*4},{b.block_pos,4}};
for (const auto& span : spans) validate(span);
for (int i = 0; i < 7; ++i) for (int j = i + 1; j < 7; ++j)
if (overlaps(spans[i], spans[j])) throw std::invalid_argument("native QSA indexer buffers overlap");
- const float theta_scale = powf(freq_base, -2.0f / ROT);
+ const float theta_scale = powf((float) scaling.freq_base, -2.0f / ROT);
+ const RopeKernelArgs k = scaling.kernel_args(ROT); // none: the identity constants
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
((sycl::queue *)(strata::q_of(stream)))
->submit([&](sycl::handler &cgh) {
- auto mrope_table_ct11 = mrope_table();
+ auto mrope_table_ct16 = mrope_table();
cgh.parallel_for<dpct_kernel_name<class append_182f95>>(
sycl::nd_range<3>(sycl::range(1, 1, THREADS),
@@ -339,7 +359,9 @@ void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_dev
append(raw, relative_pos_device, pos_base, gamma,
epsilon, b.tail, b.dead, b.pooled,
b.block_pos, int(max_cells), theta_scale,
- mrope_table_ct11);
+ k.freq_scale, k.corr_low, k.corr_high,
+ k.ext_factor, k.attn_factor,
+ mrope_table_ct16);
});
});
}
@@ -366,13 +388,15 @@ void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_dev
}
void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, int32_t pos_base, const float* gamma,
float epsilon, const QsaIndexerBuffers& b, const QsaShapes& s, int64_t max_cells,
- float freq_base, void* stream) {
+ const RopeScaling& scaling, void* stream) {
if (n <= 0) return;
if (!stream || s.idx_dim != D || s.idx_block != R || s.n_rot != ROT || p0 < 0 || p0 + n > max_cells ||
max_cells > INT32_MAX || pos_base < 0 || pos_base % R || int64_t(pos_base) + max_cells > INT32_MAX ||
- !std::isfinite(epsilon) || epsilon <= 0.0f || !std::isfinite(freq_base) || freq_base <= 1.0f)
- throw std::invalid_argument("native QSA indexer (batch): bad geometry, positions or parameters");
- const float theta_scale = powf(freq_base, -2.0f / ROT);
+ !std::isfinite(epsilon) || epsilon <= 0.0f || rope_scaling_invalid(scaling) != nullptr)
+ throw std::invalid_argument("native QSA indexer (batch): bad geometry, positions, parameters or scaling");
+ const float theta_scale = powf((float) scaling.freq_base, -2.0f / ROT);
+ const RopeKernelArgs k = scaling.kernel_args(ROT); // none: the identity constants
+ const float fsf = k.freq_scale, cl = k.corr_low, ch = k.corr_high, ef = k.ext_factor, ms = k.attn_factor;
const dpct::queue_ptr st = strata::q_of(stream);
const int32_t* mtab = mrope_table();
if (p0 == 0) {
@@ -385,7 +409,7 @@ void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, in
exp_props,
[=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
append_first(raw, gamma, epsilon, b.dead, b.pooled, theta_scale,
- mtab);
+ fsf, cl, ch, ef, ms, mtab);
});
}
// completed blocks: those whose last cell (4b+3) lies in [p0, p0 + n)
@@ -404,7 +428,7 @@ void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, in
[=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
append_blocks(raw, n, p0, pos_base, gamma, epsilon, b.tail,
b.dead, b.pooled, b.block_pos, first, hi,
- theta_scale, mtab);
+ theta_scale, fsf, cl, ch, ef, ms, mtab);
});
}
{
diff --git a/sycl/src/kernels/cuda/native_qsa_score.dp.cpp b/sycl/src/kernels/cuda/native_qsa_score.dp.cpp
index fe57d98af..a45806800 100644
--- a/sycl/src/kernels/cuda/native_qsa_score.dp.cpp
+++ b/sycl/src/kernels/cuda/native_qsa_score.dp.cpp
@@ -106,7 +106,7 @@ __dpct_inline__ void score_kernel(const float *__restrict__ pooled,
}
float sum=(((h[0] + h[1]) + h[2]) + h[3]);
if(bias)sum=(sum + bias[row]);
- sum=(sum + row==full&&n%R?1e9f:0.0f);
+ sum=(sum + (row==full&&n%R?1e9f:0.0f));
for(int i=row*R;i<n&&i<(row+1)*R;++i)cells[i]=sum;
#else
auto &shared = *sycl::ext::oneapi::group_local_memory_for_overwrite<
@@ -208,7 +208,7 @@ __dpct_inline__ void score_kernel(const float *__restrict__ pooled,
correctness. SYCL math built-in function rounding mode is aligned with
OpenCL C 1.2 standard.
*/
- sum = sum + row == full && n % R ? 1e9f : 0.0f;
+ sum = sum + (row == full && n % R ? 1e9f : 0.0f);
// The live causal mask is +0. Invalid/padded cells are never exported.
/*
DPCT1013: The rounding mode could not be specified and the generated
@@ -252,7 +252,7 @@ __global__ void scalar_score_kernel(
sum=(sum + head_score[2]);
sum=(sum + head_score[3]);
if(bias)sum=(sum + bias[row]);
- sum=(sum + row==full&&n%R?1e9f:0.0f);
+ sum=(sum + (row==full&&n%R?1e9f:0.0f));
sum=(sum + 0.0f);
for(int i=row*R;i<n&&i<(row+1)*R;++i)cells[i]=sum;
}
diff --git a/sycl/src/kernels/cuda/native_rope.dp.cpp b/sycl/src/kernels/cuda/native_rope.dp.cpp
index fa30f027e..6dfe25684 100644
--- a/sycl/src/kernels/cuda/native_rope.dp.cpp
+++ b/sycl/src/kernels/cuda/native_rope.dp.cpp
@@ -42,7 +42,9 @@ bool overlaps(const void* a, size_t an, const void* b, size_t bn) {
return x <= y ? y - x < an : x - y < bn;
}
__dpct_inline__ void apply(const float *x, float *out, int rows, int width,
- int n_rot, float theta_scale, const int *positions,
+ int n_rot, float theta_scale, float freq_scale,
+ float corr_low, float corr_high, float ext_factor,
+ float mscale, const int *positions,
const int32_t *mtab) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
const int row = item_ct1.get_group(1);
@@ -57,9 +59,10 @@ __dpct_inline__ void apply(const float *x, float *out, int rows, int width,
}
return;
}
- const float theta = mrope_pos(mtab, positions[row], pair) *
- dpct::pow(theta_scale, float(pair));
- const float c = sycl::cos((float)theta), s = sycl::sin((float)theta);
+ const float theta_extrap = mrope_pos(mtab, positions[row], pair) *
+ dpct::pow(theta_scale, float(pair));
+ float c, s;
+ rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s);
const float a = x[start + pair], b = x[start + pair + n_rot / 2];
out[start + pair] = a * c - b * s;
out[start + pair + n_rot / 2] = a * s + b * c;
@@ -86,13 +89,13 @@ const int32_t* mrope_table() { return mrope_tab[mrope_dev()].load(std::memory_or
void native_rope_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }
bool native_rope_enabled() { return enabled.load(std::memory_order_relaxed); }
void native_rope_apply(const float* x, float* out, int rows, int head_dim,
- int n_rot, float freq_base, const int* positions, void* stream) {
+ int n_rot, const RopeScaling& scaling, const int* positions, void* stream) {
if (!x || !out || !positions || !stream || rows < 1 || rows > 65535 ||
(head_dim != 128 && head_dim != 256) || n_rot != 64 ||
- !std::isfinite(freq_base) || freq_base <= 1.0f ||
+ rope_scaling_invalid(scaling) != nullptr ||
reinterpret_cast<uintptr_t>(x) % 4 || reinterpret_cast<uintptr_t>(out) % 4 ||
reinterpret_cast<uintptr_t>(positions) % 4) {
- throw std::invalid_argument("native RoPE requires aligned F32 rows, width 128/256, rotation 64, valid base and explicit stream");
+ throw std::invalid_argument("native RoPE requires aligned F32 rows, width 128/256, rotation 64, valid base/scaling and explicit stream");
}
const size_t bytes = size_t(rows) * head_dim * sizeof(float);
if ((x != out && overlaps(x, bytes, out, bytes)) ||
@@ -101,14 +104,15 @@ void native_rope_apply(const float* x, float* out, int rows, int head_dim,
throw std::invalid_argument("native RoPE buffers partially overlap");
}
// Match pinned host-side float powf before device fast powf/trigonometry.
- const float theta_scale = powf(freq_base, -2.0f / n_rot);
+ const float theta_scale = powf((float) scaling.freq_base, -2.0f / n_rot);
+ const RopeKernelArgs k = scaling.kernel_args(n_rot); // none: the identity constants
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
((sycl::queue *)(strata::q_of(stream)))
->submit([&](sycl::handler &cgh) {
- auto mrope_table_ct7 = mrope_table();
+ auto mrope_table_ct12 = mrope_table();
cgh.parallel_for<dpct_kernel_name<class apply_b955ef>>(
sycl::nd_range<3>(
@@ -117,7 +121,9 @@ void native_rope_apply(const float* x, float* out, int rows, int head_dim,
sycl::range(1, 1, 128)),
exp_props, [=](sycl::nd_item<3> item_ct1) {
apply(x, out, rows, head_dim, n_rot, theta_scale,
- positions, mrope_table_ct7);
+ k.freq_scale, k.corr_low, k.corr_high,
+ k.ext_factor, k.attn_factor, positions,
+ mrope_table_ct12);
});
});
}
diff --git a/sycl/src/kernels/cuda/ple.dp.cpp b/sycl/src/kernels/cuda/ple.dp.cpp
index a6c06b876..1d430071c 100644
--- a/sycl/src/kernels/cuda/ple.dp.cpp
+++ b/sycl/src/kernels/cuda/ple.dp.cpp
@@ -337,8 +337,9 @@ void ple_block(const float* emb, const float* hidden, const float* hist_rows, co
const bool native_key = w.key_native_data != nullptr && w.key_bf16 == nullptr;
if (native_key && (!emb || !hidden || !hist_rows || !out.result || !scratch || !stream ||
!w.key_native_q8_1 ||
- (w.key_native_type != 42 && w.key_native_type != 18 && w.key_native_type != 23)))
- throw std::invalid_argument("ple_block: native key requires Q2_0, IQ3_XXS or IQ4_XS weights, input/output, private scratch and explicit stream");
+ (w.key_native_type != 42 && w.key_native_type != 18 && w.key_native_type != 23 &&
+ w.key_native_type != 8)))
+ throw std::invalid_argument("ple_block: native key requires Q2_0, IQ3_XXS, IQ4_XS or Q8_0 weights, input/output, private scratch and explicit stream");
if (emb == nullptr || hidden == nullptr || hist_rows == nullptr || out.result == nullptr) return;
const int n_embd = NG_N_EMBD, hc = NG_HC, hc_dim = NG_HC_DIM;
static_assert(NG_N_EMBD == 2560 && NG_HC_DIM == 10240, "native PLE key geometry changed");
diff --git a/sycl/src/kernels/cuda/qsa.dp.cpp b/sycl/src/kernels/cuda/qsa.dp.cpp
index 09ccaff8c..c5df718b5 100644
--- a/sycl/src/kernels/cuda/qsa.dp.cpp
+++ b/sycl/src/kernels/cuda/qsa.dp.cpp
@@ -218,10 +218,18 @@ __dpct_inline__ void indexer_key_append_kernel(
OpenCL C 1.2 standard.
*/
const double inv = 1.0 / sycl::sqrt(ss / (double)idx_dim + (double)eps);
- dead[d] = (float) (p * inv * (double) w_k_norm[d]);
- // rope at position 0 is the identity here (cos = 1, sin = 0 exactly), so no rotation is applied and
- // the parity test asserts the value is bit-exact - which is what makes skipping it legitimate.
- pooled[d] = dead[d];
+ float y = (float) (p * inv * (double) w_k_norm[d]);
+ // The spare rotates at position 0 - ALWAYS row 0 of the table, whatever `pos_base` is, as the native
+ // indexer's spare does. At angle 0 the sine is exactly 0 in every scaling (sin(0) * mscale), so the
+ // pair rotation reduces to `v * cos_tab[pair]` with no partner element to read (and no barrier).
+ // Unscaled, row 0 is exactly (1, 0) and `v * 1.0f` is `v` bit for bit - today's value, which the
+ // parity test holds bit-exact. Under YaRN row 0 is (mscale, 0): the rotated dims carry the magnitude
+ // correction exactly like every other pooled row and like the native kernel's spare (the unrotated
+ // dims pass through, as in the rotation of the completed blocks below). Skipping the rotation here,
+ // as this kernel once did, left `dead` and `pooled[0]` the only unscaled keys of a scaled cache.
+ if (d < n_rot) y *= cos_tab[d % (n_rot / 2)];
+ dead[d] = y;
+ pooled[d] = y;
}
if (slot != r - 1) return;
diff --git a/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp b/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp
index dd9d19852..65e05f045 100644
--- a/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp
+++ b/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp
@@ -26,8 +26,9 @@ constexpr int CH = D1_CH; // cells per chunk
constexpr int THREADS = 128; // 4 warps: scores by cell (8 each), p.v by dimension (64 each = one int8 scale group)
constexpr int QS = HD + 8; // q row stride in halves (bank-conflict-free fragment loads)
-// The MMA and cp.async below need sm_80. Builds for older cards (the experimental sm_75 one) compile them to a trap;
-// qsa_prompt_attn_batch refuses such a device at run time, so the old kernel runs there.
+// The MMA below needs sm_75 or newer (Turing runs it as two k=8 steps); cp.async needs sm_80. Builds for pre-sm_75
+// cards compile the MMA to a trap; qsa_prompt_attn_batch refuses such a device at run time, so the old kernel runs
+// there. Turing compiles cp_async16 to a trap as well and takes the v1 kernel instead of launch_i8.
#if defined(__HIPCC__) // AMD: no mma.sync / cp.async; the host keeps the old kernel (below)
#define STRATA_PA_SM80 0
#elif 0 // SYCL: inline PTX (mma/ldmatrix/cp.async) - the XMX port is pending; see tools/fixups.py
@@ -36,9 +37,23 @@ constexpr int QS = HD + 8; // q row stride in halves (bank-conflict-free
#define STRATA_PA_SM80 0
#endif
+// m16n8k16 with f16 inputs needs sm_80. Turing (sm_75) has m16n8k8 with the SAME A/B/C register mapping, so the
+// k=16 step is two k=8 steps on the fragments as they are already laid out: a[0]/a[1] are rows gid/gid+8 at k columns
+// 2*tig..2*tig+1 (b[0]'s k rows), a[2]/a[3] the same rows at k columns 2*tig+8..2*tig+9 (b[1]'s k rows). The
+// products then add into the same FP32 C registers in the order hi-part-0, hi-part-1, which is the order the k16
+// instruction accumulates in as well - but the sum now rounds twice, so the two paths do not agree bit for bit.
__dpct_inline__ void mma16816(float *c, const uint32_t *a, const uint32_t *b) {
-#if !STRATA_PA_SM80
- /* unreachable on SYCL: the launcher refuses this device */
+#if !STRATA_PA_SM80 && \
+ (defined(__HIPCC__) || !defined(DPCT_COMPATIBILITY_TEMP) || \
+ DPCT_COMPATIBILITY_TEMP < 750)
+ /* unreachable on SYCL: the launcher refuses this device */ // AMD and pre-Turing builds: no mma.sync (the host keeps the old kernel there)
+#elif 0 // SYCL: Turing's m16n8k8 PTX (unreachable: the launcher refuses this device)
+ asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n"
+ : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
+ : "r"(a[0]), "r"(a[1]), "r"(b[0]));
+ asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n"
+ : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
+ : "r"(a[2]), "r"(a[3]), "r"(b[1]));
#else
#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 "
@@ -1163,7 +1178,10 @@ bool qsa_prompt_attn_batch(const float *q, const QsaAttnPools &pools,
int64_t cap, const QsaShapes &s, float *attn,
int64_t n_q, void *stream) try {
if (n_q <= 0) return true;
- { // sm_80 or newer (the MMA and cp.async above); an older card keeps the old kernel
+ bool turing = false; // per call, from the CURRENT device (a layer split can mix Turing with newer cards)
+ { // sm_75 or newer: the MMA above compiles for both. sm_80+ runs the cp.async kernel (launch_i8); Turing has
+ // no cp.async, so it runs the v1 kernel (launch<1>, same accuracy, another summation order). An older card
+ // keeps the old kernel.
static int cc_major[64] = {};
int dev = 0;
/*
@@ -1187,7 +1205,8 @@ bool qsa_prompt_attn_batch(const float *q, const QsaAttnPools &pools,
cc_major[dev] = major;
}
(void) cc_major[dev];
- // SYCL: the mma.sync kernel below is not ported; its XMX port takes the same arguments
+ // SYCL: the mma.sync kernel below is not ported (upstream's Turing/sm_80 split - `turing` - does not
+ // apply); its XMX port takes the same arguments
if (qsa_prompt_attn_xmx(q, pools, ids, steps, cap, s, attn, n_q, stream)) return true;
return false; // the caller takes the older kernel
}
@@ -1205,9 +1224,10 @@ bool qsa_prompt_attn_batch(const float *q, const QsaAttnPools &pools,
if (pools.k_q != nullptr) {
if (!pools.v_q || !pools.k_scale || !pools.v_scale) return false;
// STRATA_PROMPT_ATTN_V1=1 (debug): the first version, same accuracy, another summation order - the control
- // for how far the model amplifies an FP32-level change
+ // for how far the model amplifies an FP32-level change. Turing always takes it: v2's cp.async does not
+ // exist before sm_80.
static const bool v1 = std::getenv("STRATA_PROMPT_ATTN_V1") != nullptr;
- if (v1) return launch<1>(q, pools, ids, steps, cap, s, attn, n_q, st);
+ if (v1 || turing) return launch<1>(q, pools, ids, steps, cap, s, attn, n_q, st);
return launch_i8(q, pools, ids, steps, cap, s, attn, n_q, st);
}
if (!pools.k_pool || !pools.v_pool) return false;
diff --git a/sycl/src/kernels/cuda/rope.dp.cpp b/sycl/src/kernels/cuda/rope.dp.cpp
index b11777b96..bfe7ecf97 100644
--- a/sycl/src/kernels/cuda/rope.dp.cpp
+++ b/sycl/src/kernels/cuda/rope.dp.cpp
@@ -20,6 +20,11 @@
// Building the table once on the host and passing it in makes the TABLE exactly the reference's values and
// leaves the kernel a pure rotation, so each half can be checked tightly instead of both halves sharing one
// loose tolerance. The engine wants a cached table anyway: it is per (n_rot, theta, position), not per token.
+//
+// THE SCALED TABLE IS THE SAME IDEA WITH MORE MATH IN THE HOST LOOP. Linear rescales the angle by
+// `freq_scale`; YaRN blends extrapolation and interpolation along the pairs (ggml's `rope_yarn`) and folds
+// the mscale magnitude correction into the same cos/sin values. All of it float64, in the reference's
+// order, so `rope_parity` can hold every variant to a bit-exact float64 transcription of the same spec.
#define DPCT_PROFILING_ENABLED
#include <sycl/sycl.hpp>
#include <dpct/dpct.hpp>
@@ -33,6 +38,15 @@
namespace strata::kernels {
+namespace {
+// The process's rope config (rope_scaling.hpp). One writer - the engine's startup thread, before
+// session_init builds any table or captures any graph - and readers after it.
+RopeScaling g_rope_scaling;
+} // namespace
+
+void rope_scaling_set(const RopeScaling& scaling) { g_rope_scaling = scaling; }
+const RopeScaling& rope_scaling() { return g_rope_scaling; }
+
void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab) {
const int half = n_rot / 2;
for (int p = 0; p < max_pos; ++p) {
@@ -46,6 +60,33 @@ void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, floa
}
}
+void build_rope_table(int n_rot, const RopeScaling& sc, int max_pos, float* cos_tab, float* sin_tab) {
+ if (sc.type == RopeScalingType::None) {
+ build_rope_table(n_rot, sc.freq_base, max_pos, cos_tab, sin_tab); // the original loop, verbatim
+ return;
+ }
+ const int half = n_rot / 2;
+ const double fs = sc.freq_scale();
+ const double ms = sc.mscale();
+ double cd[2];
+ sc.corr_dims(n_rot, cd);
+ const bool correct = sc.ext_factor != 0; // ggml: the correction rides on ext_factor, not the type
+ for (int p = 0; p < max_pos; ++p) {
+ for (int i = 0; i < half; ++i) {
+ const double inv = std::pow(sc.freq_base, -2.0 * (double) i / (double) n_rot);
+ const double extrap = (double) p * inv; // the trained angle, ggml's theta_extrap
+ const double interp = fs * extrap; // ggml's theta_interp
+ double ang = interp;
+ if (correct) {
+ const double ramp = (double) rope_yarn_ramp((float) cd[0], (float) cd[1], i) * sc.ext_factor;
+ ang = interp * (1.0 - ramp) + extrap * ramp;
+ }
+ cos_tab[(size_t) p * half + i] = (float) (std::cos(ang) * ms);
+ sin_tab[(size_t) p * half + i] = (float) (std::sin(ang) * ms);
+ }
+ }
+}
+
namespace {
// ONE THREAD PER ROW, not per (row, pair). The first version had one thread per pair and did the tail copy
diff --git a/sycl/src/kernels/cuda/s2_expert_grouped.dp.cpp b/sycl/src/kernels/cuda/s2_expert_grouped.dp.cpp
index 5b76ff016..ff8bd9094 100644
--- a/sycl/src/kernels/cuda/s2_expert_grouped.dp.cpp
+++ b/sycl/src/kernels/cuda/s2_expert_grouped.dp.cpp
@@ -19,10 +19,13 @@
#include "strata/sycl_math.hpp"
#include "strata/sycl_queue.hpp"
#include "strata/kernels/s2_expert_grouped.hpp"
+#include "strata/kernels/dp4a.hpp"
#include "strata/kernels/quantize_act.hpp"
#include "strata/kernels/verify_kernels.hpp"
+#include <atomic>
+#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
@@ -224,6 +227,214 @@ down_kernel(const uint8_t *__restrict__ blob_base,
if (lane == 0) out[(size_t) dst_index[h] * H + r] = s;
}
+// ---- THE SAME INTEGERS FROM FEWER INSTRUCTIONS. `STRATA_OLD_GROUPED=1` keeps the kernels above.
+//
+// **INSIDE A CHUNK, WHICH CODE MEETS WHICH ACTIVATION IN A `dp4a` WORD IS FREE.** `s = sum_e code_e * x_e` and
+// `hx = sum_e x_e` are exact integer sums (|s| <= 32 * 3 * 128), so any grouping of the 32 products into words
+// gives the same two integers. The grouping used here costs no transposition of the codes: `(w >> 2f) & 0x03030303`
+// holds field `f` of each of a code word's four bytes - elements `4b + f`, plus 16 for the second word - so it is
+// the ACTIVATIONS that are regrouped, once per chunk, into
+//
+// X[4h + f] = { x[16h + f], x[16h + 4 + f], x[16h + 8 + f], x[16h + 12 + f] }
+//
+// a 4x4 byte transpose of each half of the chunk, eight `__byte_perm`. The kernels above spend seven integer
+// operations per code BYTE and a second `dp4a` chain for `hx` on every row; here a code word costs seven for 16
+// elements and `hx` is summed once per chunk. `s`, `hx` and the float expression `dw * dx * (float) (s - hx)` are
+// unchanged, so every output is bitwise the previous kernels' - `s2_expert_grouped_parity` checks exactly that.
+
+// fp16 at an even address, one 16-bit load (`f16_at` reads it as two bytes); same value.
+__dpct_inline__ float f16_ld(const uint8_t *p) {
+ return sycl::vec<sycl::half, 1>(sycl::bit_cast<sycl::half, unsigned short>(
+ *(const unsigned short *)p))
+ .convert<float, sycl::rounding_mode::automatic>()[0];
+}
+
+// A chunk's two code words as the eight `dp4a` operands that pair with `X[0..7]`: `m[4h + f]` byte `b` is the
+// code of element `16h + 4b + f`.
+__dpct_inline__ void expand_codes(sycl::uint2 cb, int m[8]) {
+ const unsigned M = 0x03030303u;
+ m[0] = (int)(cb.x() & M);
+ m[1] = (int)((cb.x() >> 2) & M);
+ m[2] = (int)((cb.x() >> 4) & M);
+ m[3] = (int)((cb.x() >> 6) & M);
+ m[4] = (int)(cb.y() & M);
+ m[5] = (int)((cb.y() >> 2) & M);
+ m[6] = (int)((cb.y() >> 4) & M);
+ m[7] = (int)((cb.y() >> 6) & M);
+}
+
+// The 32 int8 of the `block_q8_0` at `xb` regrouped into `X[0..7]` (see above), and their sum `hx`.
+//
+// **NINE ALIGNED WORD LOADS INSTEAD OF 32 BYTE LOADS.** The caller guarantees a 4-byte aligned activation row, so
+// chunk `c`'s int8 start at `34c + 2`, i.e. 0 bytes (odd `c`) or 2 bytes (even `c`) into an aligned word; the
+// words are read aligned and funnel-shifted into place. The ninth word is read only in the 2-byte case, and then
+// it lies inside block `c + 1` of the same row: both row lengths (80 and 20 chunks) are even, so an even chunk is
+// never a row's last.
+__dpct_inline__ int load_x_chunk(const uint8_t *__restrict__ xb, int X[8]) {
+ const uint8_t* q = xb + 2;
+ const int off = (int) ((uintptr_t) q & 3);
+ const unsigned* p = (const unsigned*) (q - off);
+ const unsigned sh = (unsigned) off * 8;
+ unsigned v[9];
+#pragma unroll
+ /*
+ DPCT1098: The '*' expression is used instead of the __ldg call. These
+ two expressions do not provide the exact same functionality. Check the
+ generated code for potential precision and/or performance issues.
+ */
+ for (int j = 0; j < 8; ++j) v[j] = *(p + j);
+ /*
+ DPCT1098: The '*' expression is used instead of the __ldg call. These
+ two expressions do not provide the exact same functionality. Check the
+ generated code for potential precision and/or performance issues.
+ */
+ v[8] = off != 0 ? *(p + 8) : 0u;
+ unsigned n[8];
+ int hx = 0;
+#pragma unroll
+ for (int j = 0; j < 8; ++j) {
+ // natural word j: x[4j .. 4j+3]; a 64-bit shift (sh is 0, 8, 16 or 24) rather than __funnelshift_r, so the same
+ // source needs no CUDA-only intrinsic.
+ n[j] = (unsigned) ((((unsigned long long) v[j + 1] << 32) | v[j]) >> sh);
+ hx = strata::dp4a(0x01010101, (int) n[j], hx);
+ }
+#pragma unroll
+ for (int h = 0; h < 2; ++h) {
+ const unsigned t0 = dpct::byte_level_permute(n[4 * h], n[4 * h + 1],
+ 0x5140); // a0 b0 a1 b1
+ const unsigned t1 = dpct::byte_level_permute(n[4 * h], n[4 * h + 1],
+ 0x7362); // a2 b2 a3 b3
+ const unsigned t2 = dpct::byte_level_permute(n[4 * h + 2], n[4 * h + 3],
+ 0x5140); // c0 d0 c1 d1
+ const unsigned t3 = dpct::byte_level_permute(n[4 * h + 2], n[4 * h + 3],
+ 0x7362); // c2 d2 c3 d3
+ X[4 * h + 0] =
+ (int)dpct::byte_level_permute(t0, t2, 0x5410); // a0 b0 c0 d0
+ X[4 * h + 1] =
+ (int)dpct::byte_level_permute(t0, t2, 0x7632); // a1 b1 c1 d1
+ X[4 * h + 2] =
+ (int)dpct::byte_level_permute(t1, t3, 0x5410); // a2 b2 c2 d2
+ X[4 * h + 3] =
+ (int)dpct::byte_level_permute(t1, t3, 0x7632); // a3 b3 c3 d3
+ }
+ return hx;
+}
+
+// `s` for one chunk: the eight expanded code words against the eight regrouped activation words.
+__dpct_inline__ int chunk_s(const int m[8], const int X[8]) {
+ int s = 0;
+#pragma unroll
+ for (int j = 0; j < 8; ++j) s = strata::dp4a(m[j], X[j], s);
+ return s;
+}
+
+/// `gu_kernel`, new: ONE WARP PER (gate, up) PAIR - row-slots `2r` and `2r + 1`, adjacent in the blob - so each
+/// activation chunk is loaded and regrouped once for both rows. Per row, the lane's chunks, their order, the float
+/// expression and the shuffle reduction are `row_dot_s2_q8`'s; the outputs land where `gu_kernel` puts them.
+/*
+DPCT1110: The total declared local variable size in device function
+gu_pair_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
+gu_pair_kernel(const uint8_t *__restrict__ blob_base,
+ const int32_t *__restrict__ slot_index, long long blob_bytes,
+ const uint8_t *__restrict__ x_q8_0,
+ const float *__restrict__ x_scales, float *__restrict__ gate_up,
+ int n_hits, const int32_t *__restrict__ d_count,
+ const int32_t *__restrict__ dst_index, int tok_div) {
+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
+ const int warps_per_block = (int)(item_ct1.get_local_range(2) >> 5);
+ const long long pair = (long long)item_ct1.get_group(2) * warps_per_block +
+ (item_ct1.get_local_id(2) >> 5);
+ const long long total = (long long) n_hits * FF;
+ if (pair >= total) return;
+ const int h = (int) (pair / FF);
+ if (d_count != nullptr && h >= *d_count) return;
+ const int r = (int) (pair % FF);
+ const int lane = item_ct1.get_local_id(2) & 31;
+
+ const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes;
+ if (tok_div > 0) {
+ const int tok = dst_index[h] / tok_div;
+ x_q8_0 += (size_t) tok * (size_t) (H / 32) * 34;
+ if (x_scales != nullptr) x_scales += (size_t) tok * (size_t) (H / 32);
+ }
+ const uint8_t* codes = blob + (size_t) (2 * r) * ROW_GU; // gate row; the up row follows it
+ const uint8_t* scales = blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2;
+ float acc_g = 0.0f, acc_u = 0.0f;
+ for (int c = lane; c < H / 32; c += 32) {
+ const uint8_t* xb = x_q8_0 + (size_t) c * 34;
+ const float dx = x_scales ? x_scales[c] : f16_ld(xb);
+ int X[8], m[8];
+ const int hx = load_x_chunk(xb, X);
+ expand_codes(*(const sycl::uint2 *)(codes + (size_t)c * 8), m);
+ const float dw_g = f16_ld(scales + (size_t) (c >> 1) * 2);
+ acc_g += dw_g * dx * (float) (chunk_s(m, X) - hx);
+ expand_codes(*(const sycl::uint2 *)(codes + ROW_GU + (size_t)c * 8), m);
+ const float dw_u = f16_ld(scales + SC_GU * 2 + (size_t) (c >> 1) * 2);
+ acc_u += dw_u * dx * (float) (chunk_s(m, X) - hx);
+ }
+ const float sg = warp_sum(acc_g);
+ const float su = warp_sum(acc_u);
+ if (lane != 0) return;
+ gate_up[(size_t) h * FF + (size_t) r] = sg; // gate-major, as in `gu_kernel`
+ gate_up[(size_t) n_hits * FF + (size_t) h * FF + (size_t) r] = su;
+}
+
+/// `down_kernel`, new: ONE WARP PER PAIR OF ROWS `r, r + 1` of one hit, the intermediate's chunk loaded once for both.
+/*
+DPCT1110: The total declared local variable size in device function
+down_pair_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 down_pair_kernel(const uint8_t *__restrict__ blob_base,
+ const int32_t *__restrict__ slot_index,
+ const int32_t *__restrict__ dst_index,
+ long long blob_bytes,
+ const uint8_t *__restrict__ h_q8_0,
+ const float *__restrict__ h_scales,
+ float *__restrict__ out, int n_hits,
+ const int32_t *__restrict__ d_count) {
+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
+ const int warps_per_block = (int)(item_ct1.get_local_range(2) >> 5);
+ const long long pair = (long long)item_ct1.get_group(2) * warps_per_block +
+ (item_ct1.get_local_id(2) >> 5);
+ const long long total = (long long) n_hits * (H / 2);
+ if (pair >= total) return;
+ const int h = (int) (pair / (H / 2));
+ if (d_count != nullptr && h >= *d_count) return;
+ const int r = 2 * (int) (pair % (H / 2));
+ const int lane = item_ct1.get_local_id(2) & 31;
+
+ const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes;
+ const uint8_t* xrow = h_q8_0 + (size_t) h * (size_t) (FF / 32) * 34;
+ const float* xs = h_scales ? h_scales + (size_t) h * (size_t) (FF / 32) : nullptr;
+ const uint8_t* codes = blob + O_D_CODES + (size_t) r * ROW_D;
+ const uint8_t* scales = blob + O_D_SCALES + (size_t) r * SC_D * 2;
+ float acc0 = 0.0f, acc1 = 0.0f;
+ for (int c = lane; c < FF / 32; c += 32) {
+ const uint8_t* xb = xrow + (size_t) c * 34;
+ const float dx = xs ? xs[c] : f16_ld(xb);
+ int X[8], m[8];
+ const int hx = load_x_chunk(xb, X);
+ expand_codes(*(const sycl::uint2 *)(codes + (size_t)c * 8), m);
+ const float dw0 = f16_ld(scales + (size_t) (c >> 1) * 2);
+ acc0 += dw0 * dx * (float) (chunk_s(m, X) - hx);
+ expand_codes(*(const sycl::uint2 *)(codes + ROW_D + (size_t)c * 8), m);
+ const float dw1 = f16_ld(scales + SC_D * 2 + (size_t) (c >> 1) * 2);
+ acc1 += dw1 * dx * (float) (chunk_s(m, X) - hx);
+ }
+ const float s0 = warp_sum(acc0);
+ const float s1 = warp_sum(acc1);
+ if (lane != 0) return;
+ const size_t o = (size_t) dst_index[h] * H + (size_t) r;
+ out[o] = s0;
+ out[o + 1] = s1;
+}
+
// The CPU subtracts the weight bias after its eight FMA accumulators have been reduced. Moving the
// subtraction into each integer dot, as the legacy kernel does, changes rounding even with equal scales.
__dpct_inline__ void activation_correction_kernel(const uint8_t *q8,
@@ -436,7 +647,7 @@ __dpct_inline__ void cpu_order_quantize_kernel(const float *x, uint8_t *blocks,
Verify the correctness. SYCL math built-in function rounding mode is
aligned with OpenCL C 1.2 standard.
*/
- int v = (int)t + t >= 0.0f ? 0.5f : -0.5f;
+ int v = (int) (t + (t >= 0.0f ? 0.5f : -0.5f)); // SYCL port: dpct dropped the parentheses (it rounded every value to 0)
v = v < -127 ? -127 : (v > 127 ? 127 : v);
out[2 + j] = (uint8_t) (int8_t) v;
sum += v;
@@ -466,8 +677,154 @@ void check(const char* who, void* stream) {
(void) stream;
}
+// The previous kernels stay selectable for A/B - `STRATA_OLD_GROUPED=1` in the environment, or
+// `moe_grouped_select_old` (the parity test runs both in one process). The environment is read once, on first use;
+// the choice is made at each launch, so a captured graph keeps the kernels it was captured with.
+std::atomic<int> g_select_old{-1};
+// Which kernels the last launch of an entry point used: 1 = new, 0 = previous, -1 = none since the last query.
+std::atomic<int> g_last_path{-1};
+
+bool old_kernels() {
+ const int s = g_select_old.load(std::memory_order_relaxed);
+ if (s >= 0) return s != 0;
+ static const bool env = [] {
+ const char* e = std::getenv("STRATA_OLD_GROUPED");
+ return e != nullptr && e[0] == '1';
+ }();
+ return env;
+}
+
+// `STRATA_GROUPED_PAIR_MIN_HITS=N`: the per-hit path keeps the previous one-warp-per-row kernels below N hits of
+// capacity. The new per-hit kernels launch half the warps (two rows each), so one hit's gate/up is 80 blocks - fewer
+// than an RTX 5090's SMs - and whether that costs time at one to three hits is what `--bench` measures. Bitwise
+// the same either way; default 0 (always the new kernels). Ignored while `moe_grouped_select_old` forces a choice.
+long long pair_min_hits() {
+ if (g_select_old.load(std::memory_order_relaxed) >= 0) return 0;
+ static const long long n = [] {
+ const char* e = std::getenv("STRATA_GROUPED_PAIR_MIN_HITS");
+ return e != nullptr ? std::atoll(e) : 0LL;
+ }();
+ return n;
+}
+
+// The new kernels read the activations as aligned words (`load_x_chunk`), so they need 4-byte aligned activation
+// rows - the input's and the intermediate's in `scratch`; the per-hit ones also read a blob's codes as uint2, which
+// needs an 8-byte aligned arena and slot size (the grouped kernels above already did). Anything else keeps the
+// previous kernels rather than issuing a misaligned load.
+bool new_grouped(const void* x_q8_0, const void* scratch) {
+ const bool fast = !old_kernels() && ((uintptr_t) x_q8_0 & 3) == 0 && ((uintptr_t) scratch & 3) == 0;
+ g_last_path.store(fast ? 1 : 0, std::memory_order_relaxed);
+ return fast;
+}
+
+bool new_hit(const void* blob_base, long long blob_bytes, const void* x_q8_0, const void* scratch, long long cap) {
+ const bool fast = new_grouped(x_q8_0, scratch) && ((uintptr_t) blob_base & 7) == 0 && (blob_bytes & 7) == 0 &&
+ cap >= pair_min_hits();
+ g_last_path.store(fast ? 1 : 0, std::memory_order_relaxed);
+ return fast;
+}
+
+// The per-hit path's two projections, previous or new kernels (one warp per row, or per pair of rows).
+void launch_hit_gu(bool fast, const uint8_t *blob_base,
+ const int32_t *slot_index, long long blob_bytes,
+ const uint8_t *x_q8_0, const float *x_scales, float *gate_up,
+ long long cap, const int32_t *d_count,
+ const int32_t *dst_index, int tok_div, dpct::queue_ptr cs) {
+ const int warps = THREADS / 32;
+ if (fast) {
+ const long long pairs = cap * (long long) FF;
+ {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+
+ cs->parallel_for<dpct_kernel_name<class gu_pair_kernel_787004>>(
+ sycl::nd_range<3>(
+ sycl::range(1, 1, (unsigned)((pairs + warps - 1) / warps)) *
+ sycl::range(1, 1, THREADS),
+ sycl::range(1, 1, THREADS)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1)
+ [[sycl::reqd_sub_group_size(32)]] {
+ gu_pair_kernel(blob_base, slot_index, blob_bytes,
+ x_q8_0, x_scales, gate_up, (int)cap,
+ d_count, dst_index, tok_div);
+ });
+ }
+ } else {
+ const long long rows = cap * 2LL * FF;
+ {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+
+ cs->parallel_for<dpct_kernel_name<class gu_kernel_55bc52>>(
+ sycl::nd_range<3>(
+ sycl::range(1, 1, (unsigned)((rows + warps - 1) / warps)) *
+ sycl::range(1, 1, THREADS),
+ sycl::range(1, 1, THREADS)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1)
+ [[sycl::reqd_sub_group_size(32)]] {
+ gu_kernel(blob_base, slot_index, blob_bytes, x_q8_0,
+ x_scales, gate_up, (int)cap, d_count,
+ dst_index, tok_div);
+ });
+ }
+ }
+}
+
+void launch_hit_down(bool fast, const uint8_t *blob_base,
+ const int32_t *slot_index, const int32_t *dst_index,
+ long long blob_bytes, const uint8_t *h_q8_0,
+ const float *h_scales, float *out, long long cap,
+ const int32_t *d_count, dpct::queue_ptr cs) {
+ const int warps = THREADS / 32;
+ if (fast) {
+ const long long pairs = cap * (long long) (H / 2);
+ {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+
+ cs->parallel_for<dpct_kernel_name<class down_pair_kernel_7d15d9>>(
+ sycl::nd_range<3>(
+ sycl::range(1, 1, (unsigned)((pairs + warps - 1) / warps)) *
+ sycl::range(1, 1, THREADS),
+ sycl::range(1, 1, THREADS)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1)
+ [[sycl::reqd_sub_group_size(32)]] {
+ down_pair_kernel(blob_base, slot_index, dst_index,
+ blob_bytes, h_q8_0, h_scales, out,
+ (int)cap, d_count);
+ });
+ }
+ } else {
+ const long long rows = cap * (long long) H;
+ {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+
+ cs->parallel_for<dpct_kernel_name<class down_kernel_b3587f>>(
+ sycl::nd_range<3>(
+ sycl::range(1, 1, (unsigned)((rows + warps - 1) / warps)) *
+ sycl::range(1, 1, THREADS),
+ sycl::range(1, 1, THREADS)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1)
+ [[sycl::reqd_sub_group_size(32)]] {
+ down_kernel(blob_base, slot_index, dst_index,
+ blob_bytes, h_q8_0, h_scales, out, (int)cap,
+ d_count);
+ });
+ }
+ }
+}
+
} // namespace
+void moe_grouped_select_old(int old) { g_select_old.store(old < 0 ? -1 : (old != 0 ? 1 : 0)); }
+
+int moe_grouped_last_path() { return g_last_path.exchange(-1, std::memory_order_relaxed); }
+
uint64_t moe_hit_grouped_scratch_bytes(int64_t n_hits, int64_t n_embd, int64_t n_ff) {
if (n_hits <= 0) return 0;
const uint64_t gu = (uint64_t) n_hits * (uint64_t) (2 * n_ff) * 4;
@@ -484,7 +841,7 @@ void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, con
void* stream, const float* x_scales) {
if (n_hits <= 0) return;
dpct::queue_ptr cs = strata::q_of(stream);
- const int warps = THREADS / 32;
+ const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, n_hits);
const uint64_t gu_bytes = ((uint64_t) n_hits * (uint64_t) (2 * FF) * 4 + 15) & ~15ull;
const uint64_t q8_bytes = ((uint64_t) n_hits * (uint64_t) (FF / 32) * 34 + 15) & ~15ull;
@@ -494,24 +851,8 @@ void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, con
// 1. gate + up, one launch for every row of every hit.
{
- const long long rows = n_hits * 2LL * FF;
- const unsigned blocks = (unsigned) ((rows + warps - 1) / warps);
- {
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- cs->parallel_for<dpct_kernel_name<class gu_kernel_7c8537>>(
- sycl::nd_range<3>(sycl::range(1, 1, blocks) *
- sycl::range(1, 1, THREADS),
- sycl::range(1, 1, THREADS)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- gu_kernel(blob_base, slot_index, blob_bytes, x_q8_0,
- x_scales, gate_up, (int)n_hits, nullptr,
- nullptr, 0);
- });
- }
+ launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, n_hits, nullptr, nullptr,
+ 0, cs);
check("moe_hit_grouped_s2/gu", stream);
}
// 2. silu(gate) * up.
@@ -541,30 +882,8 @@ void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, con
else quantize_q8_0(gate_up, h_q8_0, n_hits * (int64_t) FF, stream);
// 4. down.
{
- const long long rows = n_hits * (long long) H;
- const unsigned blocks = (unsigned) ((rows + warps - 1) / warps);
- {
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- cs->submit([&](sycl::handler &cgh) {
- const float *x_scales_nullptr_h_scales_nullptr_ct5 =
- x_scales != nullptr ? h_scales : nullptr;
-
- cgh.parallel_for<dpct_kernel_name<class down_kernel_b856bc>>(
- sycl::nd_range<3>(sycl::range(1, 1, blocks) *
- sycl::range(1, 1, THREADS),
- sycl::range(1, 1, THREADS)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- down_kernel(blob_base, slot_index, dst_index,
- blob_bytes, h_q8_0,
- x_scales_nullptr_h_scales_nullptr_ct5,
- out, (int)n_hits, nullptr);
- });
- });
- }
+ launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0,
+ x_scales != nullptr ? h_scales : nullptr, out, n_hits, nullptr, cs);
check("moe_hit_grouped_s2/down", stream);
}
}
@@ -684,31 +1003,15 @@ void moe_hit_grouped_s2_dev(const uint8_t* blob_base, const int32_t* slot_index,
void* scratch, float* out, void* stream, const float* x_scales) {
if (cap <= 0) return;
dpct::queue_ptr cs = strata::q_of(stream);
- const int warps = THREADS / 32;
+ const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, cap);
const uint64_t gu_bytes = ((uint64_t) cap * (uint64_t) (2 * FF) * 4 + 15) & ~15ull;
const uint64_t q8_bytes = ((uint64_t) cap * (uint64_t) (FF / 32) * 34 + 15) & ~15ull;
float* gate_up = (float*) scratch;
uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes;
float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes);
{
- const long long rows = cap * 2LL * FF;
- {
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- cs->parallel_for<dpct_kernel_name<class gu_kernel_e0f313>>(
- sycl::nd_range<3>(
- sycl::range(1, 1, (unsigned)((rows + warps - 1) / warps)) *
- sycl::range(1, 1, THREADS),
- sycl::range(1, 1, THREADS)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- gu_kernel(blob_base, slot_index, blob_bytes, x_q8_0,
- x_scales, gate_up, (int)cap, d_count, nullptr,
- 0);
- });
- }
+ launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, cap, d_count, nullptr, 0,
+ cs);
check("moe_hit_grouped_s2_dev/gu", stream);
}
{
@@ -732,31 +1035,8 @@ void moe_hit_grouped_s2_dev(const uint8_t* blob_base, const int32_t* slot_index,
if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream);
else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream);
{
- const long long rows = cap * (long long) H;
- {
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- cs->submit([&](sycl::handler &cgh) {
- const float *x_scales_nullptr_h_scales_nullptr_ct5 =
- x_scales != nullptr ? h_scales : nullptr;
-
- cgh.parallel_for<dpct_kernel_name<class down_kernel_bd8167>>(
- sycl::nd_range<3>(
- sycl::range(1, 1,
- (unsigned)((rows + warps - 1) / warps)) *
- sycl::range(1, 1, THREADS),
- sycl::range(1, 1, THREADS)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- down_kernel(blob_base, slot_index, dst_index,
- blob_bytes, h_q8_0,
- x_scales_nullptr_h_scales_nullptr_ct5,
- out, (int)cap, d_count);
- });
- });
- }
+ launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0,
+ x_scales != nullptr ? h_scales : nullptr, out, cap, d_count, cs);
check("moe_hit_grouped_s2_dev/down", stream);
}
}
@@ -788,31 +1068,15 @@ void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_inde
const float* x_scales, int k_per_token, void* scratch, float* out, void* stream) {
if (cap <= 0) return;
dpct::queue_ptr cs = strata::q_of(stream);
- const int warps = THREADS / 32;
+ const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, cap);
const uint64_t gu_bytes = ((uint64_t) cap * (uint64_t) (2 * FF) * 4 + 15) & ~15ull;
const uint64_t q8_bytes = ((uint64_t) cap * (uint64_t) (FF / 32) * 34 + 15) & ~15ull;
float* gate_up = (float*) scratch;
uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes;
float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes);
{
- const long long rows = cap * 2LL * FF;
- {
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- cs->parallel_for<dpct_kernel_name<class gu_kernel_30a25d>>(
- sycl::nd_range<3>(
- sycl::range(1, 1, (unsigned)((rows + warps - 1) / warps)) *
- sycl::range(1, 1, THREADS),
- sycl::range(1, 1, THREADS)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- gu_kernel(blob_base, slot_index, blob_bytes, x_q8_0,
- x_scales, gate_up, (int)cap, d_count,
- dst_index, k_per_token);
- });
- }
+ launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, cap, d_count, dst_index,
+ k_per_token, cs);
check("moe_hit_grouped_s2_multi/gu", stream);
}
{
@@ -836,31 +1100,8 @@ void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_inde
if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream);
else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream);
{
- const long long rows = cap * (long long) H;
- {
- auto exp_props = sycl::ext::oneapi::experimental::properties{
- sycl::ext::oneapi::experimental::use_root_sync};
-
- cs->submit([&](sycl::handler &cgh) {
- const float *x_scales_nullptr_h_scales_nullptr_ct5 =
- x_scales != nullptr ? h_scales : nullptr;
-
- cgh.parallel_for<dpct_kernel_name<class down_kernel_a919b8>>(
- sycl::nd_range<3>(
- sycl::range(1, 1,
- (unsigned)((rows + warps - 1) / warps)) *
- sycl::range(1, 1, THREADS),
- sycl::range(1, 1, THREADS)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- down_kernel(blob_base, slot_index, dst_index,
- blob_bytes, h_q8_0,
- x_scales_nullptr_h_scales_nullptr_ct5,
- out, (int)cap, d_count);
- });
- });
- }
+ launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0,
+ x_scales != nullptr ? h_scales : nullptr, out, cap, d_count, cs);
check("moe_hit_grouped_s2_multi/down", stream);
}
}
@@ -1022,6 +1263,183 @@ auto &hs_q =
}
}
}
+
+// ---- The grouped kernels with the staged activations laid out for the reads.
+//
+// **THE LAYOUT ABOVE IS AN 8-WAY BANK CONFLICT.** `xs_q[k][c * 8 + j]` puts lane `L`'s word `j` at `8L + j`, so
+// lanes `L, L + 4, L + 8, ...` share a bank on every one of the chunk's eight reads; and `chunk_dot` recomputes
+// `hx`, which depends on the entry alone, for every row. Here the staging writes, once per (entry, chunk):
+//
+// xs_w[j][k * NC + c] word j of the regrouped chunk (`load_x_chunk`), so lanes read consecutive words
+// xs_dh[k * NC + c] (dx, hx) - one 64-bit read per chunk instead of a float and eight `dp4a`
+//
+// Word-major, the staging writes are consecutive as well (the flat index `i` IS `k * NC + c`), so neither side
+// conflicts and no padding is needed. Each warp takes its rows TWO at a time (adjacent rows: gate `r` and up `r`,
+// or down rows `r, r + 1`), so every shared read serves both; the codes of both are expanded once per row, not
+// once per entry. Per (row, entry) the lane's chunks, their order, the float expression and the shuffle
+// reduction are the kernels' above, so every output is bitwise theirs.
+
+// Stages chunk `i = k * NC + c` of a group: its regrouped words at `xs_w[j * STRIDE + i]` and (dx, hx) at `xs_dh[i]`.
+template <int STRIDE>
+__dpct_inline__ void stage_chunk(const uint8_t *__restrict__ xb, float dx,
+ int *xs_w, sycl::int2 *xs_dh, int i) {
+ int X[8];
+ const int hx = load_x_chunk(xb, X);
+#pragma unroll
+ for (int j = 0; j < 8; ++j) xs_w[j * STRIDE + i] = X[j];
+ xs_dh[i] = sycl::int2(sycl::bit_cast<int>(dx), hx);
+}
+
+/*
+DPCT1110: The total declared local variable size in device function
+gu_grouped_t_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 gu_grouped_t_kernel(
+ const unsigned long long *__restrict__ grp_ptr,
+ const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
+ const int32_t *__restrict__ ent_tok, const uint8_t *__restrict__ x_q8_0,
+ const float *__restrict__ x_scales, float *__restrict__ gate_up,
+ int cap_entries) {
+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
+ constexpr int NC = H / 32;
+ auto &xs_w = *sycl::ext::oneapi::group_local_memory_for_overwrite<
+ int[8 * GMAX * NC]>(
+ sycl::ext::oneapi::this_work_item::get_work_group<
+ 3>()); // 20 KB: word j of entry k's chunk c at [j][k * NC + c]
+ auto &xs_dh = *sycl::ext::oneapi::group_local_memory_for_overwrite<
+ sycl::int2[GMAX * NC]>(
+ sycl::ext::oneapi::this_work_item::get_work_group<3>()); // 5 KB: (dx as
+ // bits, hx)
+ const int g = item_ct1.get_group(1);
+ if (g >= *n_groups) return;
+ const int e0 = grp_start[g], ne = sycl::min(grp_start[g + 1] - e0, GMAX);
+ const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
+ for (int i = t; i < ne * NC; i += item_ct1.get_local_range(2)) {
+ const int k = i / NC, c = i - k * NC;
+ const int tok = ent_tok[e0 + k];
+ const uint8_t* xb = x_q8_0 + (size_t) tok * (size_t) NC * 34 + (size_t) c * 34;
+ const float dx = x_scales ? x_scales[(size_t) tok * NC + c] : f16_ld(xb);
+ stage_chunk<GMAX * NC>(xb, dx, xs_w, xs_dh, i);
+ }
+ item_ct1.barrier(sycl::access::fence_space::local_space);
+ const uint8_t* blob = (const uint8_t*) grp_ptr[g];
+ const int row0 = item_ct1.get_group(2) *
+ GU_ROWS; // even: a pair is always (gate r, up r)
+ for (int pp = warp; pp < GU_ROWS / 2; pp += 8) {
+ const int i = row0 + 2 * pp;
+ const uint8_t* codes = blob + (size_t) i * ROW_GU;
+ const uint8_t* scales = blob + O_GU_SCALES + (size_t) i * SC_GU * 2;
+ int m0[GU_CHUNKS][8], m1[GU_CHUNKS][8];
+ float dw0[GU_CHUNKS], dw1[GU_CHUNKS];
+#pragma unroll
+ for (int q = 0; q < GU_CHUNKS; ++q) {
+ const int c = lane + 32 * q;
+ if (c < NC) {
+ expand_codes(*(const sycl::uint2 *)(codes + (size_t)c * 8),
+ m0[q]);
+ expand_codes(
+ *(const sycl::uint2 *)(codes + ROW_GU + (size_t)c * 8),
+ m1[q]);
+ dw0[q] = f16_ld(scales + (size_t) (c >> 1) * 2);
+ dw1[q] = f16_ld(scales + SC_GU * 2 + (size_t) (c >> 1) * 2);
+ }
+ }
+ for (int k = 0; k < ne; ++k) {
+ float acc0 = 0.0f, acc1 = 0.0f;
+#pragma unroll
+ for (int q = 0; q < GU_CHUNKS; ++q) {
+ const int c = lane + 32 * q;
+ if (c >= NC) break;
+ const int at = k * NC + c;
+ int X[8];
+#pragma unroll
+ for (int j = 0; j < 8; ++j) X[j] = xs_w[j * (GMAX * NC) + at];
+ const sycl::int2 dh = xs_dh[at];
+ const float dx = sycl::bit_cast<float>(dh.x());
+ acc0 += dw0[q] * dx * (float)(chunk_s(m0[q], X) - dh.y());
+ acc1 += dw1[q] * dx * (float)(chunk_s(m1[q], X) - dh.y());
+ }
+ const float s0 = warp_sum(acc0);
+ const float s1 = warp_sum(acc1);
+ if (lane == 0) {
+ const int e = e0 + k, r = i >> 1;
+ gate_up[(size_t) e * FF + (size_t) r] = s0;
+ gate_up[(size_t) cap_entries * FF + (size_t) e * FF + (size_t) r] = s1;
+ }
+ }
+ }
+}
+
+/*
+DPCT1110: The total declared local variable size in device function
+down_grouped_t_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 down_grouped_t_kernel(
+ const unsigned long long *__restrict__ grp_ptr,
+ const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
+ const int32_t *__restrict__ ent_dst, const uint8_t *__restrict__ h_q8_0,
+ const float *__restrict__ h_scales, float *__restrict__ out) {
+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
+ constexpr int NC = FF / 32;
+ auto &hs_w = *sycl::ext::oneapi::group_local_memory_for_overwrite<
+ int[8 * GMAX * NC]>(
+ sycl::ext::oneapi::this_work_item::get_work_group<3>());
+ auto &hs_dh = *sycl::ext::oneapi::group_local_memory_for_overwrite<
+ sycl::int2[GMAX * NC]>(
+ sycl::ext::oneapi::this_work_item::get_work_group<3>());
+ const int g = item_ct1.get_group(1);
+ if (g >= *n_groups) return;
+ const int e0 = grp_start[g], ne = sycl::min(grp_start[g + 1] - e0, GMAX);
+ const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
+ for (int i = t; i < ne * NC; i += item_ct1.get_local_range(2)) {
+ const int k = i / NC, c = i - k * NC;
+ const uint8_t* xb = h_q8_0 + (size_t) (e0 + k) * (size_t) NC * 34 + (size_t) c * 34;
+ const float dx = h_scales ? h_scales[(size_t) (e0 + k) * NC + c] : f16_ld(xb);
+ stage_chunk<GMAX * NC>(xb, dx, hs_w, hs_dh, i);
+ }
+ item_ct1.barrier(sycl::access::fence_space::local_space);
+ const uint8_t* blob = (const uint8_t*) grp_ptr[g];
+ const int row0 = item_ct1.get_group(2) * D_ROWS;
+ for (int pp = warp; pp < D_ROWS / 2; pp += 8) {
+ const int r = row0 + 2 * pp;
+ const uint8_t* codes = blob + O_D_CODES + (size_t) r * ROW_D;
+ const uint8_t* scales = blob + O_D_SCALES + (size_t) r * SC_D * 2;
+ const int c = lane; // lanes 0..19 hold one chunk each, as above
+ int m0[8], m1[8];
+ float dw0 = 0.0f, dw1 = 0.0f;
+ if (c < NC) {
+ expand_codes(*(const sycl::uint2 *)(codes + (size_t)c * 8), m0);
+ expand_codes(*(const sycl::uint2 *)(codes + ROW_D + (size_t)c * 8),
+ m1);
+ dw0 = f16_ld(scales + (size_t) (c >> 1) * 2);
+ dw1 = f16_ld(scales + SC_D * 2 + (size_t) (c >> 1) * 2);
+ }
+ for (int k = 0; k < ne; ++k) {
+ float acc0 = 0.0f, acc1 = 0.0f;
+ if (c < NC) {
+ const int at = k * NC + c;
+ int X[8];
+#pragma unroll
+ for (int j = 0; j < 8; ++j) X[j] = hs_w[j * (GMAX * NC) + at];
+ const sycl::int2 dh = hs_dh[at];
+ const float dx = sycl::bit_cast<float>(dh.x());
+ acc0 += dw0 * dx * (float)(chunk_s(m0, X) - dh.y());
+ acc1 += dw1 * dx * (float)(chunk_s(m1, X) - dh.y());
+ }
+ const float s0 = warp_sum(acc0);
+ const float s1 = warp_sum(acc1);
+ if (lane == 0) {
+ const size_t o = (size_t) ent_dst[e0 + k] * H + (size_t) r;
+ out[o] = s0;
+ out[o + 1] = s1;
+ }
+ }
+ }
+}
} // namespace
namespace {
@@ -1120,15 +1538,32 @@ void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start,
float* gate_up = (float*) scratch;
uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes;
float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes);
+ const bool fast = new_grouped(x_q8_0, scratch);
{
+ const dpct::dim3 grid((unsigned)(2 * FF / GU_ROWS),
+ (unsigned)cap_groups);
+ if (fast)
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
+ cs->parallel_for<
+ dpct_kernel_name<class gu_grouped_t_kernel_998f94>>(
+ sycl::nd_range<3>(grid * sycl::range(1, 1, 256),
+ sycl::range(1, 1, 256)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1)
+ [[sycl::reqd_sub_group_size(32)]] {
+ gu_grouped_t_kernel(grp_ptr, grp_start, n_groups,
+ ent_tok, x_q8_0, x_scales, gate_up,
+ (int)cap_entries);
+ });
+ } else {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+
cs->parallel_for<dpct_kernel_name<class gu_grouped_kernel_c9eb4d>>(
- sycl::nd_range<3>(sycl::range(1, (unsigned)cap_groups,
- (unsigned)(2 * FF / GU_ROWS)) *
- sycl::range(1, 1, 256),
+ sycl::nd_range<3>(grid * sycl::range(1, 1, 256),
sycl::range(1, 1, 256)),
exp_props,
[=](sycl::nd_item<3> item_ct1)
@@ -1161,28 +1596,37 @@ void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start,
if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap_entries * (int64_t) FF, stream);
else quantize_q8_0(gate_up, h_q8_0, cap_entries * (int64_t) FF, stream);
{
+ const dpct::dim3 grid((unsigned)(H / D_ROWS), (unsigned)cap_groups);
+ const float* hs = x_scales != nullptr ? h_scales : nullptr;
+ if (fast)
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
- cs->submit([&](sycl::handler &cgh) {
- const float *x_scales_nullptr_h_scales_nullptr_ct5 =
- x_scales != nullptr ? h_scales : nullptr;
-
- cgh.parallel_for<
- dpct_kernel_name<class down_grouped_kernel_ea4417>>(
- sycl::nd_range<3>(sycl::range(1, (unsigned)cap_groups,
- (unsigned)(H / D_ROWS)) *
- sycl::range(1, 1, 256),
- sycl::range(1, 1, 256)),
- exp_props,
- [=](sycl::nd_item<3> item_ct1)
- [[sycl::reqd_sub_group_size(32)]] {
- down_grouped_kernel(
- grp_ptr, grp_start, n_groups, ent_dst, h_q8_0,
- x_scales_nullptr_h_scales_nullptr_ct5, out);
- });
- });
+ cs->parallel_for<
+ dpct_kernel_name<class down_grouped_t_kernel_12b16d>>(
+ sycl::nd_range<3>(grid * sycl::range(1, 1, 256),
+ sycl::range(1, 1, 256)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1)
+ [[sycl::reqd_sub_group_size(32)]] {
+ down_grouped_t_kernel(grp_ptr, grp_start, n_groups,
+ ent_dst, h_q8_0, hs, out);
+ });
+ } else {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+
+ cs->parallel_for<
+ dpct_kernel_name<class down_grouped_kernel_ea4417>>(
+ sycl::nd_range<3>(grid * sycl::range(1, 1, 256),
+ sycl::range(1, 1, 256)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1)
+ [[sycl::reqd_sub_group_size(32)]] {
+ down_grouped_kernel(grp_ptr, grp_start, n_groups,
+ ent_dst, h_q8_0, hs, out);
+ });
}
check("moe_grouped_s2/down", stream);
}
diff --git a/sycl/src/kernels/cuda/sampler.dp.cpp b/sycl/src/kernels/cuda/sampler.dp.cpp
index e438ca877..5727fd394 100644
--- a/sycl/src/kernels/cuda/sampler.dp.cpp
+++ b/sycl/src/kernels/cuda/sampler.dp.cpp
@@ -23,6 +23,7 @@
#include <dpct/dpct.hpp>
#include "strata/sycl_queue.hpp"
#include "strata/kernels/sampler.hpp"
+#include "strata/core/coupled_draft.hpp"
#include <cmath>
#include <cstdio>
@@ -512,9 +513,13 @@ __dpct_inline__ void warp_first(float &bv, int &bi) {
/// the same argument, the sums in the same order, `cum += e / sum` with the same correctly rounded quotient - so
/// the cut, the survivors and the pick are the same. (`n_keep == 0`, reachable only with min_p > 1, which the
/// callers clamp, read `sel_ids[-1]` in the old tail; it reads `sel_ids[0]` here.)
+/// kProb (the coupled draft only): lane 0 also writes the pick's probability under the final distribution to
+/// `*prob_out`. The sampler's own calls take kProb = false, whose code is the tail above, unchanged.
+template <bool kProb = false>
inline void sampled_tail_warp(const int *sel_ids, const float *sel_logit, int k,
const SamplerParams &p, int t,
- int *__restrict__ out, double *ex) {
+ int *__restrict__ out, double *ex,
+ float *prob_out = nullptr) {
const int lane =
(int)(sycl::ext::oneapi::this_work_item::get_nd_item<3>().get_local_id(
2) &
@@ -590,9 +595,9 @@ inline void sampled_tail_warp(const int *sel_ids, const float *sel_logit, int k,
#pragma unroll
for (int i = 0; i < n_keep; ++i) sum += ex[i];
/*
- DPCT1108: '__shfl_sync' was migrated with the experimental feature masked
- sub_group function which may not be supported by all compilers or runtimes.
- You may need to adjust the code.
+ DPCT1108: '__shfl_sync' was migrated with the experimental feature
+ masked sub_group function which may not be supported by all compilers or
+ runtimes. You may need to adjust the code.
*/
sum = dpct::experimental::select_from_sub_group(
kFullMask, sycl::ext::oneapi::this_work_item::get_sub_group(), sum, 0);
@@ -603,13 +608,15 @@ inline void sampled_tail_warp(const int *sel_ids, const float *sel_logit, int k,
if (lane == 0) {
const float u = philox_uniform(p.seed, p.counter + (uint64_t) t);
double cum = 0.0;
- int pick = sel_ids[n_keep > 0 ? n_keep - 1 : 0];
+ int pi = n_keep > 0 ? n_keep - 1 : 0;
+ int pick = sel_ids[pi];
#pragma unroll
for (int i = 0; i < n_keep; ++i) {
cum += ex[i];
- if ((double) u < cum) { pick = sel_ids[i]; break; }
+ if ((double) u < cum) { pick = sel_ids[i]; pi = i; break; }
}
out[t] = pick;
+ if constexpr (kProb) *prob_out = n_keep > 0 ? (float) ex[pi] : 1.0f;
}
}
@@ -981,6 +988,122 @@ sampler_split_merge_kernel(const sycl::int2 *__restrict__ cand, int n_blocks,
sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex);
}
+// ---- COUPLED DRAFT SAMPLING (include/strata/core/coupled_draft.hpp): the MTP draft layer samples its draft with the
+// target's chain and the target's Philox draw. Everything that varies per request or per round - the chain's
+// parameters, the seed, the counter (from the cell's step record), the penalty history - is read from DEVICE memory:
+// these kernels are captured into the drafter's round/step graphs. One row, `nv` logits: the draft head's
+// vocabulary subset (rt/draft_vocab.bin) or the whole vocabulary; `sub_to_id` maps a subset index to its token id.
+
+/// The round's inputs: the request's SamplerParams and the history base (the last h slots before `cap`), from
+/// mapped host memory into the device copies the chain's kernels read.
+__dpct_inline__ void coupled_stage_kernel(const SamplerParams *__restrict__ mp,
+ const int *__restrict__ mh,
+ SamplerParams *__restrict__ dp,
+ int *__restrict__ ring, int cap) {
+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
+ const volatile int *s = (const volatile int *)mp;
+ int* d = (int*) dp;
+#pragma unroll
+ for (int i = item_ct1.get_local_id(2);
+ i < (int)(sizeof(SamplerParams) / sizeof(int));
+ i += item_ct1.get_local_range(2)) d[i] = s[i];
+ const int h = strata::core::coupled_hist_len(((const volatile SamplerParams*) mp)->penalty_last_n, cap);
+ const volatile int* vh = (const volatile int*) mh;
+#pragma unroll
+ for (int i = cap - h + (int)item_ct1.get_local_id(2); i < cap;
+ i += item_ct1.get_local_range(2)) ring[i] = vh[i];
+}
+
+/// The penalties, applied in place to the draft logits before the selection - the target applies the same
+/// `apply_penalties` to the same token with the same count over the same window before its own. Draft j's window
+/// is the ring's [cap + j - h, cap + j): the base plus drafts 0 .. j-1. A history token outside the draft head's
+/// subset has no logit here. Each distinct token is penalised once: the entry whose `atomicOr` sets its bit does it.
+__dpct_inline__ void coupled_penalize_kernel(
+ float *__restrict__ logits, int nv, const int *__restrict__ id_to_sub,
+ int id_vocab, const SamplerParams *__restrict__ dp,
+ const int *__restrict__ ring, int cap, int j, uint8_t *dpct_local) {
+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
+ const SamplerParams p = *dp;
+ const int h = strata::core::coupled_hist_len(p.penalty_last_n, cap);
+ if (h <= 0) return;
+ const int* hrow = ring + strata::core::coupled_hist_start(cap, j, h);
+ auto seen = (unsigned int *)dpct_local;
+ const int words = (nv + 31) / 32;
+#pragma unroll
+ for (int w = item_ct1.get_local_id(2); w < words;
+ w += item_ct1.get_local_range(2)) seen[w] = 0u;
+ /*
+ 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();
+ for (int i = item_ct1.get_local_id(2); i < h;
+ i += item_ct1.get_local_range(2)) {
+ const int v = hrow[i];
+ if (v < 0 || v >= id_vocab) continue;
+ const int s = id_to_sub != nullptr ? id_to_sub[v] : v;
+ if (s < 0 || s >= nv) continue;
+ const unsigned bit = 1u << (s & 31);
+ if (dpct::atomic_fetch_or<sycl::access::address_space::generic_space>(
+ &seen[s >> 5], bit) &
+ bit) continue;
+ logits[s] = apply_penalties(logits[s], history_count(hrow, h, v), p);
+ }
+}
+
+/// The merge of `sampler_split_merge_kernel` (lists of `kpart` entries, the request's top_k taken from them), then
+/// `sampled_tail_warp` with the counter of the row that will verify this draft. Lane 0 maps the pick to its token
+/// id, writes it and its probability, and appends it to the ring for the next draft's penalty window.
+__dpct_inline__ void coupled_merge_kernel(
+ const sycl::int2 *__restrict__ cand, int n_blocks, int nv, int kpart,
+ const SamplerParams *__restrict__ dp, const int *__restrict__ step_rec,
+ const int *__restrict__ sub_to_id, int *__restrict__ ring, int cap, int j,
+ int *__restrict__ out_id, float *__restrict__ out_prob) {
+ const int lane =
+ (int)sycl::ext::oneapi::this_work_item::get_nd_item<3>().get_local_id(
+ 2);
+ SamplerParams p = *dp;
+ p.counter = strata::core::coupled_draft_counter((int64_t) step_rec[0]);
+ const int k = sampled_k(p.top_k, nv); // <= kpart: the first k of a union lie in the first k of each list
+ auto &lists = *sycl::ext::oneapi::group_local_memory_for_overwrite<
+ sycl::int2[kSplitMaxBlocks * kSelMax]>(
+ sycl::ext::oneapi::this_work_item::get_work_group<3>());
+ auto &sel_ids =
+ *sycl::ext::oneapi::group_local_memory_for_overwrite<int[kSelMax]>(
+ sycl::ext::oneapi::this_work_item::get_work_group<3>());
+ auto &sel_logit =
+ *sycl::ext::oneapi::group_local_memory_for_overwrite<float[kSelMax]>(
+ sycl::ext::oneapi::this_work_item::get_work_group<3>());
+ auto &ex =
+ *sycl::ext::oneapi::group_local_memory_for_overwrite<double[kSelMax]>(
+ sycl::ext::oneapi::this_work_item::get_work_group<3>());
+ auto &pick = *sycl::ext::oneapi::group_local_memory_for_overwrite<int[1]>(
+ sycl::ext::oneapi::this_work_item::get_work_group<3>());
+ auto &prob = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[1]>(
+ sycl::ext::oneapi::this_work_item::get_work_group<3>());
+#pragma unroll
+ for (int e = lane; e < n_blocks * kpart; e += 32) lists[e] = cand[e];
+ sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
+ warp_merge_lists(lists, n_blocks, kpart, k, nv, [&](int i, float v, int id) {
+ if (lane == 0) { sel_ids[i] = id < nv ? id : 0; sel_logit[i] = v; }
+ });
+ sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
+ if (p.greedy || p.temperature <= 0.0f) { // never launched for greedy requests; the argmax, defensively
+ if (lane == 0) { pick[0] = sel_ids[0]; prob[0] = 1.0f; }
+ } else {
+ sampled_tail_warp<true>(sel_ids, sel_logit, k, p, 0, pick, ex, prob);
+ }
+ sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
+ if (lane == 0) {
+ const int s = pick[0];
+ const int id = sub_to_id != nullptr ? sub_to_id[s] : s;
+ *out_id = id;
+ *out_prob = prob[0];
+ ring[cap + j] = id;
+ }
+}
+
// Which sampled path runs, read once: `STRATA_OLD_SAMPLER=1` is `sampler_kernel` (engine 0.1.20),
// `STRATA_SAMPLER_ONE_BLOCK=1` the one-block kernel; by default the split top_k wherever it applies.
enum class SampledPath { Split, OneBlock, Old };
@@ -1283,4 +1406,118 @@ void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* hi
if (stream == nullptr) dpct::get_current_device().queues_wait_and_throw();
}
+namespace {
+int coupled_blocks(int nv) { return (nv + kSplitBlockSpan - 1) / kSplitBlockSpan; }
+int coupled_kpart(int nv) { return nv < kSelMax ? nv : kSelMax; }
+void coupled_check(const char* what) {
+ /*
+ DPCT1010: SYCL uses exceptions to report errors and does not use the
+ error codes. The cudaGetLastError function call was replaced with 0. You
+ need to rewrite this code.
+ */
+ const dpct::err0 e = 0;
+}
+} // namespace
+
+size_t coupled_draft_scratch_bytes(int nv) {
+ if (nv <= 0 || coupled_blocks(nv) > kSplitMaxBlocks) return 0;
+ return (size_t)coupled_blocks(nv) * (size_t)kSelMax * sizeof(sycl::int2);
+}
+
+void coupled_draft_stage(const SamplerParams* mapped_params, const int32_t* mapped_hist, SamplerParams* params,
+ int32_t* ring, int cap, void* stream) {
+ {
+ 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 coupled_stage_kernel_113245>>(
+ sycl::nd_range<3>(sycl::range(1, 1, 256),
+ sycl::range(1, 1, 256)),
+ exp_props, [=](sycl::nd_item<3> item_ct1) {
+ coupled_stage_kernel(mapped_params, mapped_hist, params,
+ ring, cap);
+ });
+ }
+ coupled_check("coupled_draft_stage");
+}
+
+void coupled_draft_sample(float* logits, int nv, const int32_t* sub_to_id, const int32_t* id_to_sub, int id_vocab,
+ const SamplerParams* params, int32_t* ring, int cap, int j, const int32_t* step_rec,
+ void* scratch, int32_t* out_id, float* out_prob, void* stream) {
+ const dpct::queue_ptr s = strata::q_of(stream);
+ const int n_blocks = coupled_blocks(nv), kpart = coupled_kpart(nv);
+ if (nv <= 0 || n_blocks > kSplitMaxBlocks || scratch == nullptr) {
+ std::fprintf(stderr, "coupled_draft_sample: %d logits need scratch and at most %d blocks\n", nv, kSplitMaxBlocks);
+ std::exit(1);
+ }
+ /*
+ DPCT1049: The work-group size passed to the SYCL kernel may exceed the
+ limit. To get the device limit, query info::device::max_work_group_size.
+ Adjust the work-group size if needed.
+ */
+ {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+
+ s->submit([&](sycl::handler &cgh) {
+ /*
+ DPCT1083: The size of local memory in the migrated code may be
+ different from the original code. Check that the allocated memory
+ size in the migrated code is correct.
+ */
+ sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
+ sycl::range((unsigned)((nv + 31) / 32) * sizeof(unsigned)),
+ cgh);
+
+ cgh.parallel_for<
+ dpct_kernel_name<class coupled_penalize_kernel_6ca8a2>>(
+ sycl::nd_range<3>(sycl::range(1, 1, 1024),
+ sycl::range(1, 1, 1024)),
+ exp_props, [=](sycl::nd_item<3> item_ct1) {
+ coupled_penalize_kernel(
+ logits, nv, id_to_sub, id_vocab, params, ring, cap, j,
+ dpct_local_acc_ct1
+ .get_multi_ptr<sycl::access::decorated::no>()
+ .get());
+ });
+ });
+ }
+ coupled_check("coupled_penalize");
+ // the selection of the split sampler, unchanged: every 4,096-logit block's first `kpart` (the widest list,
+ // since the request's top_k is only known on the device), penalties already applied above
+ {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+
+ s->parallel_for<
+ dpct_kernel_name<class sampler_split_part_kernel_cc5674>>(
+ sycl::nd_range<3>(sycl::range(1, 1u, (unsigned)n_blocks) *
+ sycl::range(1, 1, kSplitWarps * 32),
+ sycl::range(1, 1, kSplitWarps * 32)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
+ sampler_split_part_kernel(logits, nv, nullptr, 0,
+ SamplerParams{}, kpart, n_blocks,
+ (sycl::int2 *)scratch);
+ });
+ }
+ coupled_check("coupled_draft split part");
+ {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+ dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp64});
+
+ s->parallel_for<dpct_kernel_name<class coupled_merge_kernel_1fbeb1>>(
+ sycl::nd_range<3>(sycl::range(1, 1, 32), sycl::range(1, 1, 32)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
+ coupled_merge_kernel((const sycl::int2 *)scratch, n_blocks, nv,
+ kpart, params, step_rec, sub_to_id, ring,
+ cap, j, out_id, out_prob);
+ });
+ }
+ coupled_check("coupled_draft merge");
+}
+
} // namespace strata::kernels
diff --git a/sycl/src/kernels/cuda/verify_kernels.dp.cpp b/sycl/src/kernels/cuda/verify_kernels.dp.cpp
index 25f05990e..7b9178e18 100644
--- a/sycl/src/kernels/cuda/verify_kernels.dp.cpp
+++ b/sycl/src/kernels/cuda/verify_kernels.dp.cpp
@@ -9,10 +9,10 @@
#include "strata/sycl_doorbell.hpp"
#include "strata/kernels/verify_kernels.hpp"
#include "strata/kernels/resident_plan_mirror.hpp"
+#include "strata/kernels/dp4a.hpp"
#include <cstdio>
#include <cstdlib>
-#include <time.h>
#ifndef STRATA_PLAN_LOCAL
#define STRATA_PLAN_LOCAL 1 // 0: the original one-thread plan kernel (A/B)
@@ -911,12 +911,7 @@ void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const
namespace {
__dpct_inline__ void wait_flag_ge_kernel(const volatile uint32_t *flag,
uint32_t value) {
- /*
- DPCT1008: __nanosleep function is not defined in SYCL. This is a
- hardware-specific feature. Consult with your hardware vendor to find a
- replacement.
- */
- for (uint32_t spin = 0; spin < strata::kSpinMax && strata::sys_load(flag) < value; ++spin) {}
+ for (uint32_t spin = 0; spin < strata::kSpinMax && strata::sys_load(flag) < value; ++spin) strata_spin_pause();
/*
DPCT1078: Consider replacing memory_order::acq_rel with
memory_order::seq_cst for correctness if strong memory order restrictions
@@ -1076,12 +1071,7 @@ __dpct_inline__ void wait_flag_ge_or_kernel(const volatile uint32_t *flag,
uint32_t value,
const volatile uint32_t *skip) {
if (strata::sys_load(skip) == value) return;
- /*
- DPCT1008: __nanosleep function is not defined in SYCL. This is a
- hardware-specific feature. Consult with your hardware vendor to find a
- replacement.
- */
- for (uint32_t spin = 0; spin < strata::kSpinMax && strata::sys_load(flag) < value; ++spin) {}
+ for (uint32_t spin = 0; spin < strata::kSpinMax && strata::sys_load(flag) < value; ++spin) strata_spin_pause();
/*
DPCT1078: Consider replacing memory_order::acq_rel with
memory_order::seq_cst for correctness if strong memory order restrictions
@@ -1288,7 +1278,7 @@ namespace {
__dpct_inline__ void gpu_stamp_kernel(unsigned long long *buf, int i) {
unsigned long long t;
#if defined(__HIPCC__)
- t = wall_clock64() * 10ull; // gfx11: a constant 100 MHz counter, in ns
+ t = wall_clock64() * 10ull; // gfx11 / gfx12: a constant 100 MHz counter, in ns
#else
/*
DPCT1053: Migration of device assembly code is not supported.
diff --git a/sycl/src/kernels/iq_multi_parity.cpp b/sycl/src/kernels/iq_multi_parity.cpp
new file mode 100644
index 000000000..0e9e4426b
--- /dev/null
+++ b/sycl/src/kernels/iq_multi_parity.cpp
@@ -0,0 +1,480 @@
+// src/kernels/iq_multi_parity.cpp - the IQ kernels that decode each weight part once for every
+// column / entry, against the older kernels that decode it again per column. Synthetic blocks, no model.
+//
+// build/iq_multi_parity the checks (a ctest; needs the GPU)
+// build/iq_multi_parity --bench the checks, then old/new timings of both paths
+//
+// (1) iq_mmvq, every format it takes, ncols 1..8 and 11 (the > 8 split): the new output must be BITWISE equal to
+// the old one (iq_set_old_kernels), and within float rounding of a double reference built from the GPU's own
+// dequantizer (validated against gguf-py by iq_parity) and the dequantized q8_1 activations - a gross-error
+// guard, not the contract.
+// (2) native_expert_grouped, every gate/up format with the down formats: groups of 0..11 entries (more than a pass
+// of GRP_NC), unused grid rows (cap_groups > groups), scattered destinations; bitwise, new vs old, the rows it
+// must not write included.
+//
+// Random bytes are valid codes for every format here (all grid indices are in range); only the fp16 block scales
+// are set, small enough that the grouped path's SwiGLU output keeps a finite fp16 q8_1 scale.
+#define DPCT_PROFILING_ENABLED
+#include <sycl/sycl.hpp>
+#include <dpct/dpct.hpp>
+#include "strata/kernels/f16_bits.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 *w) {
+}
+
+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_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";
+ default: return "?";
+ }
+}
+int block_values(int t) { return t == 20 ? 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, 3);
+ 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 the four scale words (bytes 48..55); nibble 3 carries the
+ // sign and the exponent's top bits: 0x1 / 0x2 (or 0x9 / 0xA) keeps it in 2^-11 .. 2^-3
+ const uint8_t nib = (uint8_t) ((sgn(rng) == 0 ? 0x8 : 0x0) | (1 + (byte(rng) & 1)));
+ w[o + 55] = (uint8_t) ((w[o + 55] & 0x0F) | (nib << 4));
+ } else {
+ const uint16_t h = (uint16_t) ((sgn(rng) == 0 ? 0x8000 : 0) | (ex(rng) << 10) | man(rng)); // 2^-13 .. 2^-6
+ std::memcpy(&w[o], &h, 2);
+ }
+ }
+ return w;
+}
+
+std::vector<float> random_x(size_t n, std::mt19937& rng) {
+ std::normal_distribution<float> nd(0.f, 1.f);
+ std::vector<float> x(n);
+ for (auto& v : x) v = nd(rng);
+ return x;
+}
+
+// q8_1 blocks (fp16 scale, fp16 sum, 32 int8) back to floats
+std::vector<double> dequant_q8_1(const std::vector<uint8_t>& q, size_t n) {
+ std::vector<double> v(n);
+ for (size_t b = 0; b < n / 32; ++b) {
+ uint16_t dh;
+ std::memcpy(&dh, &q[b * 36], 2);
+ const double d = k::f32_from_f16(dh);
+ for (int i = 0; i < 32; ++i) v[b * 32 + i] = d * (int8_t) q[b * 36 + 4 + i];
+ }
+ return v;
+}
+
+// ------------------------------------------------------------------------------------------------ (1) iq_mmvq
+void check_mmvq(int t, int n_in, int n_out, dpct::queue_ptr s,
+ std::mt19937 &rng) {
+ const auto w = random_rows(t, n_out, n_in, rng);
+ uint8_t* dw = dalloc<uint8_t>(w.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_in_order_queue().memcpy(dw, w.data(), w.size()).wait()),
+ "w");
+ // the double reference's weights: the GPU dequantizer (iq_parity checks it against gguf-py)
+ float* dwf = dalloc<float>((size_t) n_out * n_in);
+ k::iq_dequant_f32(t, dw, (int64_t) n_out * n_in, dwf, s);
+ std::vector<float> wf((size_t) n_out * n_in);
+ ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memcpy(wf.data(), dwf, wf.size() * 4)
+ .wait()),
+ "wf");
+ const int max_cols = 11;
+ const auto x = random_x((size_t) max_cols * n_in, 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_in_order_queue().memcpy(dx, x.data(), x.size() * 4).wait()),
+ "x");
+ const size_t xq_bytes = (size_t) max_cols * (n_in / 32) * 36;
+ uint8_t* dxq = dalloc<uint8_t>(xq_bytes);
+ k::quantize_q8_1_rows(dx, max_cols, n_in, dxq, s);
+ std::vector<uint8_t> xq(xq_bytes);
+ ck(DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue().memcpy(xq.data(), dxq, xq_bytes).wait()),
+ "xq");
+ const auto xd = dequant_q8_1(xq, (size_t) max_cols * n_in);
+ float* dy_old = dalloc<float>((size_t) max_cols * n_out);
+ float* dy_new = dalloc<float>((size_t) max_cols * n_out);
+ std::vector<float> y_old((size_t) max_cols * n_out), y_new(y_old.size());
+ const int cols[] = {1, 2, 3, 4, 5, 6, 7, 8, 11};
+ int bad = 0;
+ double worst = 0.0;
+ for (int nc : cols) {
+ ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memset(dy_old, 0xFF, y_old.size() * 4)
+ .wait()),
+ "memset");
+ ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memset(dy_new, 0xFF, y_new.size() * 4)
+ .wait()),
+ "memset");
+ k::iq_set_old_kernels(true);
+ k::iq_mmvq(t, dw, dxq, dy_old, n_in, n_out, nc, s);
+ k::iq_set_old_kernels(false);
+ k::iq_mmvq(t, dw, dxq, dy_new, n_in, n_out, nc, s);
+ ck(DPCT_CHECK_ERROR(s->wait()), "sync");
+ ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memcpy(y_old.data(), dy_old, y_old.size() * 4)
+ .wait()),
+ "y_old");
+ ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memcpy(y_new.data(), dy_new, y_new.size() * 4)
+ .wait()),
+ "y_new");
+ size_t diff = 0;
+ for (size_t i = 0; i < y_old.size(); ++i) diff += std::memcmp(&y_old[i], &y_new[i], 4) != 0;
+ double num = 0, den = 0;
+ bool finite = true;
+ for (int c = 0; c < nc; ++c)
+ for (int r = 0; r < n_out; ++r) {
+ double acc = 0;
+ for (int i = 0; i < n_in; ++i) acc += (double) wf[(size_t) r * n_in + i] * xd[(size_t) c * n_in + i];
+ const float g = y_new[(size_t) c * n_out + r];
+ finite = finite && std::isfinite(g);
+ num += std::fabs(g - acc);
+ den += std::fabs(acc);
+ }
+ const double rel = num / (den + 1e-30);
+ worst = std::max(worst, rel);
+ if (diff != 0 || !finite || !(rel < 1e-2)) {
+ std::printf(" %-8s %5d x %5d ncols %2d: %zu outputs differ from the old kernel, ref rel %.2e%s FAIL\n",
+ name_of(t), n_out, n_in, nc, diff, rel, finite ? "" : ", non-finite");
+ ++bad;
+ }
+ }
+ std::printf("%-8s type %2d %5d x %5d iq_mmvq ncols 1..8, 11: %s (ref rel <= %.2e)\n", name_of(t), t, n_out, n_in,
+ bad ? "FAIL" : "bitwise equal to the old kernel", worst);
+ g_fail += bad;
+ sycl::free(dw, dpct::get_in_order_queue());
+ sycl::free(dwf, dpct::get_in_order_queue());
+ sycl::free(dx, dpct::get_in_order_queue());
+ sycl::free(dxq, dpct::get_in_order_queue());
+ sycl::free(dy_old, dpct::get_in_order_queue());
+ sycl::free(dy_new, dpct::get_in_order_queue());
+}
+
+// ---------------------------------------------------------------------------------- (2) native_expert_grouped
+struct Grouped {
+ k::NativeExpertLayout L;
+ int n_groups = 0, n_ent = 0, cap_groups = 0, cap_ent = 0, n_tok = 0;
+ std::vector<uint8_t*> blobs;
+ unsigned long long* dptr = nullptr;
+ int32_t *dstart = nullptr, *dn = nullptr, *ddst = nullptr, *dtok = nullptr;
+ float* dx = nullptr;
+ uint8_t *dxq = nullptr, *dscr = nullptr;
+ float* dout = nullptr;
+ size_t out_floats = 0;
+
+ Grouped(int gu, int dt, int64_t H, int64_t FF, const std::vector<int>& counts, int tokens, std::mt19937& rng) {
+ L = k::native_expert_layout(gu, dt, H, FF);
+ n_groups = (int) counts.size();
+ cap_groups = n_groups + 2; // the extra grid rows must exit
+ n_tok = tokens;
+ std::vector<int32_t> start(1, 0), tok, dst;
+ for (int c : counts) start.push_back(start.back() + c);
+ n_ent = start.back();
+ cap_ent = n_ent + 3;
+ std::uniform_int_distribution<int> tk(0, tokens - 1);
+ for (int e = 0; e < n_ent; ++e) tok.push_back(tk(rng));
+ dst.resize(n_ent);
+ std::iota(dst.begin(), dst.end(), 0);
+ std::shuffle(dst.begin(), dst.end(), rng);
+ std::vector<unsigned long long> ptr;
+ for (int g = 0; g < n_groups; ++g) {
+ // one blob per group: gate rows | up rows (format gu, H values) | down rows (format dt, FF values)
+ auto b = random_rows(gu, 2 * FF, H, rng);
+ const auto d = random_rows(dt, H, FF, rng);
+ b.insert(b.end(), d.begin(), d.end());
+ if (b.size() != L.bytes) { std::fprintf(stderr, "blob size %zu != %zu\n", b.size(), L.bytes); std::exit(2); }
+ uint8_t* db = dalloc<uint8_t>(b.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_in_order_queue().memcpy(db, b.data(), b.size()).wait()),
+ "blob");
+ blobs.push_back(db);
+ ptr.push_back((unsigned long long) db);
+ }
+ dptr = dalloc<unsigned long long>(cap_groups);
+ dstart = dalloc<int32_t>(cap_groups + 1);
+ dn = dalloc<int32_t>(1);
+ ddst = dalloc<int32_t>(cap_ent);
+ dtok = dalloc<int32_t>(cap_ent);
+ /*
+ 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_in_order_queue().memcpy(dptr, ptr.data(),
+ ptr.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_in_order_queue().memcpy(
+ dstart, start.data(), start.size() * 4).wait()),
+ "start");
+ ck(DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue().memcpy(dn, &n_groups, 4).wait()),
+ "n");
+ if (n_ent) {
+ /*
+ 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_in_order_queue().memcpy(
+ ddst, dst.data(), dst.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_in_order_queue().memcpy(
+ dtok, tok.data(), tok.size() * 4).wait()),
+ "tok");
+ }
+ const auto x = random_x((size_t) tokens * H, rng);
+ 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_in_order_queue().memcpy(dx, x.data(), x.size() * 4).wait()),
+ "x");
+ dxq = dalloc<uint8_t>((size_t) tokens * (H / 32) * 36);
+ dscr = dalloc<uint8_t>(k::native_expert_scratch_bytes(cap_ent, FF));
+ out_floats = (size_t) cap_ent * H;
+ dout = dalloc<float>(out_floats);
+ }
+ ~Grouped() {
+ for (auto *b : blobs)
+ DPCT_CHECK_ERROR(sycl::free(b, dpct::get_in_order_queue()));
+ sycl::free(dptr, dpct::get_in_order_queue());
+ sycl::free(dstart, dpct::get_in_order_queue());
+ sycl::free(dn, dpct::get_in_order_queue());
+ sycl::free(ddst, dpct::get_in_order_queue());
+ sycl::free(dtok, dpct::get_in_order_queue());
+ sycl::free(dx, dpct::get_in_order_queue());
+ sycl::free(dxq, dpct::get_in_order_queue());
+ sycl::free(dscr, dpct::get_in_order_queue());
+ sycl::free(dout, dpct::get_in_order_queue());
+ }
+ void run(bool old, dpct::queue_ptr s) {
+ k::iq_set_old_kernels(old);
+ k::quantize_q8_1_rows(dx, n_tok, L.n_embd, dxq, s);
+ k::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, cap_groups, cap_ent, dxq, dscr, dout, s);
+ k::iq_set_old_kernels(false);
+ }
+ std::vector<float> result(bool old, dpct::queue_ptr s) {
+ ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memset(dout, 0xFF, out_floats * 4)
+ .wait()),
+ "memset"); // NaN rows: must stay NaN where nothing writes
+ ck(DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue()
+ .memset(dscr, 0,
+ k::native_expert_scratch_bytes(cap_ent, L.n_ff))
+ .wait()),
+ "memset");
+ run(old, s);
+ ck(DPCT_CHECK_ERROR(s->wait()), "sync");
+ std::vector<float> o(out_floats);
+ ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memcpy(o.data(), dout, o.size() * 4)
+ .wait()),
+ "out");
+ return o;
+ }
+};
+
+void check_grouped(int gu, int dt, int64_t H, int64_t FF, dpct::queue_ptr s,
+ std::mt19937 &rng) {
+ // 0..11 entries per group: one pass, a partial pass, two passes and three passes of GRP_NC = 4
+ Grouped G(gu, dt, H, FF, {1, 3, 4, 5, 0, 8, 2, 11, 1}, 8, rng);
+ const auto a = G.result(true, s), b = G.result(false, s);
+ size_t diff = 0, written = 0;
+ bool finite = true;
+ for (size_t i = 0; i < a.size(); ++i) {
+ diff += std::memcmp(&a[i], &b[i], 4) != 0;
+ if (i < (size_t) G.n_ent * H) { ++written; finite = finite && std::isfinite(b[i]); }
+ }
+ const bool ok = diff == 0 && finite;
+ std::printf("%-8s/%-7s %5lld x %4lld native_expert_grouped, %d groups, %d entries: %s\n", name_of(gu),
+ name_of(dt), (long long) H, (long long) FF, G.n_groups, G.n_ent,
+ ok ? "bitwise equal to the old kernels" : "FAIL");
+ if (!ok) {
+ std::printf(" %zu of %zu floats differ%s\n", diff, a.size(), finite ? "" : ", non-finite outputs");
+ ++g_fail;
+ }
+}
+
+// ------------------------------------------------------------------------------------------------ --bench
+float time_ms(dpct::queue_ptr s, int it, const auto &fn) {
+ dpct::event_ptr e0, e1;
+ e0 = new sycl::event();
+ e1 = new sycl::event();
+ fn();
+ dpct::sync_barrier(e0, s);
+ for (int i = 0; i < it; ++i) fn();
+ dpct::sync_barrier(e1, s);
+ ck(DPCT_CHECK_ERROR(e1->wait_and_throw()), "bench");
+ float ms = 0;
+ ms =
+ (e1->get_profiling_info<sycl::info::event_profiling::command_end>() -
+ e0->get_profiling_info<sycl::info::event_profiling::command_start>()) /
+ 1000000.0f;
+ dpct::destroy_event(e0);
+ dpct::destroy_event(e1);
+ return ms / it;
+}
+
+void bench(dpct::queue_ptr s, std::mt19937 &rng) {
+ std::printf("\n--bench: microseconds per call, old (per-column decode) / new (decode once), idle GPU assumed\n");
+ const int n_in = 2560, n_out = 8192, it = 200;
+ for (int t : {16, 17, 18, 21, 22, 29}) {
+ const auto w = random_rows(t, n_out, n_in, rng);
+ uint8_t* dw = dalloc<uint8_t>(w.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_in_order_queue().memcpy(dw, w.data(), w.size()).wait()),
+ "w");
+ const auto x = random_x((size_t) 8 * n_in, 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_in_order_queue().memcpy(dx, x.data(), x.size() * 4).wait()),
+ "x");
+ uint8_t* dxq = dalloc<uint8_t>((size_t) 8 * (n_in / 32) * 36);
+ k::quantize_q8_1_rows(dx, 8, n_in, dxq, s);
+ float* dy = dalloc<float>((size_t) 8 * n_out);
+ std::printf("%-8s iq_mmvq %d x %d:", name_of(t), n_out, n_in);
+ for (int nc = 1; nc <= 8; ++nc) {
+ float us[2];
+ for (int old = 1; old >= 0; --old) {
+ k::iq_set_old_kernels(old != 0);
+ us[old] = 1e3f * time_ms(s, it, [&] { k::iq_mmvq(t, dw, dxq, dy, n_in, n_out, nc, s); });
+ }
+ std::printf(" %d: %.1f/%.1f", nc, us[1], us[0]);
+ }
+ std::printf("\n");
+ k::iq_set_old_kernels(false);
+ sycl::free(dw, dpct::get_in_order_queue());
+ sycl::free(dx, dpct::get_in_order_queue());
+ sycl::free(dxq, dpct::get_in_order_queue());
+ sycl::free(dy, dpct::get_in_order_queue());
+ }
+ // the verify window's shape: 2560 x 640 experts, 16 groups of m entries each
+ for (int gu : {16, 17, 18, 21, 22, 29}) {
+ std::printf("%-8s/Q2_0 grouped, 16 groups of m entries:", name_of(gu));
+ for (int m : {1, 2, 3, 4, 8}) {
+ Grouped G(gu, 42, 2560, 640, std::vector<int>(16, m), 8, rng);
+ float us[2];
+ for (int old = 1; old >= 0; --old)
+ us[old] = 1e3f * time_ms(s, 50, [&] { G.run(old != 0, s); });
+ std::printf(" m=%d: %.1f/%.1f", m, us[1], us[0]);
+ }
+ std::printf("\n");
+ }
+}
+
+} // 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(18);
+ for (int t : {16, 17, 18, 20, 21, 22, 23, 29, 42}) {
+ check_mmvq(t, 2560, 67, s, rng); // the model's n_embd; 67 rows: a partial block of 4 rows
+ check_mmvq(t, 1024, 5, s, rng);
+ }
+ for (int gu : {16, 17, 18, 21, 22, 23, 29, 42}) {
+ for (int dt : {20, 42}) check_grouped(gu, dt, 2560, 640, s, rng); // the model's shape
+ check_grouped(gu, 23, 1024, 512, s, rng); // IQ4_XS down needs n_ff % 256 == 0
+ }
+ if (do_bench) bench(s, rng);
+ std::printf("iq_multi_parity: %d failures\n", g_fail);
+ dpct::get_current_device().destroy_queue(s);
+ return g_fail ? 1 : 0;
+}
diff --git a/sycl/src/kernels/iq_parity.cpp b/sycl/src/kernels/iq_parity.cpp
index 9adfcb577..25c83b3c1 100644
--- a/sycl/src/kernels/iq_parity.cpp
+++ b/sycl/src/kernels/iq_parity.cpp
@@ -1,9 +1,17 @@
-// src/kernels/iq_parity.cpp - plan v0.3 P6: the i-quant kernels against gguf-py on real rows.
+// src/kernels/iq_parity.cpp - plan v0.3 P6: the i-quant kernels against gguf-py on generated rows.
//
-// python tools/iq_fixture.py --out logs/iq_fixture && build/iq_parity logs/iq_fixture
+// python tools/iq_fixture.py --out <dir> && build/iq_parity <dir>
//
-// Dequant must match gguf-py's values to fp32 rounding; the MMVQ dot (q8_1 activations) must match the float
-// matrix-vector product within the activation rounding (a few 1e-3 relative).
+// The fixtures are GENERATED (deterministic; TODO 24) - tools/iq_fixture.py writes each type's raw block
+// bytes and the gguf-py dequantized reference (Q2_0, this repository's type 42, is dequantized by
+// tools/gguf_writer.py's codec instead - gguf-py has no such type). Dependencies: python3 with numpy and
+// the vendored gguf-py that setup downloads (the pinned llama.cpp zip; third_party/ is gitignored).
+//
+// What is compared, and how: the dequant parity is a MEASURED relative error (sum|got-ref| / sum|ref|) -
+// bitwise equality is not claimed and not required; on the generated fixtures it measures 0.00e+00. The
+// MMVQ dot (q8_1 activations) must match the float matrix-vector product over that reference within the
+// activation rounding (a few 1e-3 relative), for 1 to 8 columns, every column of a multi-column call bitwise
+// equal to a one-column call on it.
#define DPCT_PROFILING_ENABLED
#include <sycl/sycl.hpp>
#include <dpct/dpct.hpp>
@@ -12,6 +20,7 @@
#include <cmath>
#include <cstdio>
+#include <cstring>
#include <random>
#include <string>
#include <vector>
@@ -19,13 +28,22 @@
int main(int argc, char** argv) {
const std::string dir = argc > 1 ? argv[1] : "logs/iq_fixture";
const char* names[] = {"IQ2_XXS", "IQ2_XS", "IQ2_S", "IQ3_XXS", "IQ3_S", "IQ1_M", "IQ4_NL", "IQ4_XS", "Q2_0", "Q3_K"};
- int failures = 0;
+ int failures = 0, missing = 0;
dpct::queue_ptr s;
s = dpct::get_current_device().create_queue(true);
for (const char* nm : names) {
std::FILE* f = std::fopen((dir + "/" + nm + ".bin").c_str(), "rb");
std::FILE* g = std::fopen((dir + "/" + nm + ".f32").c_str(), "rb");
- if (!f || !g) { std::printf("%-8s missing fixture\n", nm); ++failures; continue; }
+ if (!f || !g) {
+ std::printf("%-8s missing fixture: %s/%s.bin or %s/%s.f32 - generate the fixtures first with "
+ "python tools/iq_fixture.py --out %s (deterministic; see the tool's --help)\n",
+ nm, dir.c_str(), nm, dir.c_str(), nm, dir.c_str());
+ if (f) std::fclose(f);
+ if (g) std::fclose(g);
+ ++failures;
+ ++missing;
+ continue;
+ }
int hdr[3];
std::fread(hdr, 4, 3, f);
const int type = hdr[0], rows = hdr[1], cols = hdr[2];
@@ -59,19 +77,21 @@ int main(int argc, char** argv) {
for (size_t i = 0; i < ref.size(); ++i) { num += std::fabs(got[i] - ref[i]); den += std::fabs(ref[i]); }
dq_err = num / (den + 1e-30);
}
- // the dot, two columns
+ // the dot, ncols 1..8: each column of an ncols call bitwise equal to a one-column call on it (the
+ // exact multi-column layout, the default), all of them within the activation rounding of the float product
+ const int MC = 8;
std::mt19937 rng(7);
std::normal_distribution<float> nd(0.f, 1.f);
- std::vector<float> x((size_t) 2 * cols);
+ std::vector<float> x((size_t) MC * cols);
for (auto& v : x) v = nd(rng);
float* dx = nullptr;
void* xq = nullptr;
float* dy = nullptr;
dx = (float *)sycl::malloc_device(x.size() * 4,
dpct::get_in_order_queue());
- xq = (void *)sycl::malloc_device((size_t)2 * cols / 32 * 36,
+ xq = (void *)sycl::malloc_device((size_t)MC * cols / 32 * 36,
dpct::get_in_order_queue());
- dy = (float *)sycl::malloc_device((size_t)2 * rows * 4,
+ dy = (float *)sycl::malloc_device((size_t)MC * rows * 4,
dpct::get_in_order_queue());
/*
DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
@@ -80,15 +100,32 @@ int main(int argc, char** argv) {
to ensure synchronization behavior.
*/
dpct::get_in_order_queue().memcpy(dx, x.data(), x.size() * 4).wait();
- strata::kernels::quantize_q8_1_rows(dx, 2, cols, xq, s);
+ strata::kernels::quantize_q8_1_rows(dx, MC, cols, xq, s);
+ std::vector<float> y((size_t) MC * rows), yn(y.size());
+ int multi_bad = 0;
try {
- strata::kernels::native_mmvq(type, dw, xq, dy, cols, rows, 2, s);
+ for (int c = 0; c < MC; ++c)
+ strata::kernels::native_mmvq(type, dw, (const uint8_t*) xq + (size_t) c * cols / 32 * 36,
+ dy + (size_t) c * rows, cols, rows, 1, s);
+ s->wait();
+ dpct::get_in_order_queue()
+ .memcpy(y.data(), dy, y.size() * 4)
+ .wait();
+ for (int nc = 2; nc <= MC; ++nc) {
+ strata::kernels::native_mmvq(type, dw, xq, dy, cols, rows, nc, s);
+ s->wait();
+ dpct::get_in_order_queue()
+ .memcpy(yn.data(), dy, yn.size() * 4)
+ .wait();
+ if (strata::kernels::native_mmvq_multi_exact() &&
+ std::memcmp(yn.data(), y.data(), (size_t) nc * rows * 4) != 0) {
+ std::printf("%-8s mmvq ncols %d: not bitwise equal to the one-column calls\n", nm, nc);
+ ++multi_bad;
+ }
+ }
} catch (const std::exception& e) { std::printf("%-8s mmvq: %s\n", nm, e.what()); ++failures; continue; }
- std::vector<float> y((size_t) 2 * rows);
- s->wait();
- dpct::get_in_order_queue().memcpy(y.data(), dy, y.size() * 4).wait();
double num = 0, den = 0;
- for (int c = 0; c < 2; ++c)
+ for (int c = 0; c < MC; ++c)
for (int r = 0; r < rows; ++r) {
double acc = 0;
for (int k = 0; k < cols; ++k) acc += (double) ref[(size_t) r * cols + k] * x[(size_t) c * cols + k];
@@ -96,9 +133,9 @@ int main(int argc, char** argv) {
den += std::fabs(acc);
}
const double mm_err = num / (den + 1e-30);
- const bool ok = dq_err < 1e-6 && mm_err < 2e-2;
- std::printf("%-8s type %2d %4d x %5d dequant rel %.2e mmvq rel %.2e %s\n", nm, type, rows, cols, dq_err, mm_err,
- ok ? "ok" : "FAIL");
+ const bool ok = dq_err < 1e-6 && mm_err < 2e-2 && multi_bad == 0;
+ std::printf("%-8s type %2d %4d x %5d dequant rel %.2e mmvq rel %.2e (ncols 1..%d) %s\n", nm, type, rows, cols,
+ dq_err, mm_err, MC, ok ? "ok" : "FAIL");
if (!ok) ++failures;
sycl::free(dw, dpct::get_in_order_queue());
sycl::free(dq, dpct::get_in_order_queue());
@@ -107,5 +144,10 @@ int main(int argc, char** argv) {
sycl::free(dy, dpct::get_in_order_queue());
}
std::printf("iq_parity: %d failures\n", failures);
+ // no fixture at all: the generator was skipped (no numpy / vendored gguf-py) - a skip (3), not a failure
+ if (missing == (int) (sizeof names / sizeof names[0])) {
+ std::printf("iq_parity: no fixtures in %s - skipped\n", dir.c_str());
+ return 3;
+ }
return failures ? 1 : 0;
}
diff --git a/sycl/src/kernels/ple_parity.cpp b/sycl/src/kernels/ple_parity.cpp
index 5679df58a..10cfefaf3 100644
--- a/sycl/src/kernels/ple_parity.cpp
+++ b/sycl/src/kernels/ple_parity.cpp
@@ -209,9 +209,9 @@ int history_advance_regression() {
float* history = history_storage + guard;
float* norm = norm_storage + guard;
/*
- 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
+ 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_in_order_queue().memcpy(
@@ -764,54 +764,54 @@ int main(int argc, char** argv) {
hcd * 4, dpct::get_in_order_queue())),
"cr");
/*
- 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
+ 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_in_order_queue().memcpy(d_nk, cap.w_nk.data(), hcd * 4).wait()),
"cnk");
/*
- 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
+ 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_in_order_queue().memcpy(d_nq, cap.w_nq.data(), hcd * 4).wait()),
"cnq");
/*
- 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
+ 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_in_order_queue().memcpy(d_nc, cap.w_nc.data(), hcd * 4).wait()),
"cnc");
/*
- 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
+ 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_in_order_queue().memcpy(
d_kc, key_codes.data(), key_codes.size()).wait()),
"ckc");
/*
- 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
+ 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_in_order_queue().memcpy(
d_vb, value_bf16.data(), value_bf16.size() * 2).wait()),
"cvb");
/*
- 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
+ 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_in_order_queue().memcpy(
@@ -831,9 +831,9 @@ int main(int argc, char** argv) {
key_scales.size() * 4, dpct::get_in_order_queue())),
"ks");
/*
- 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
+ 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_in_order_queue().memcpy(
@@ -1203,10 +1203,10 @@ int main(int argc, char** argv) {
std::vector<float> projected(hcd), normalized(hcd), actual_key(hcd), actual_result(hcd), replay(hcd);
for (int p = 0; p < std::min(cap.nt, 2); ++p) {
/*
- 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.
*/
ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
d_emb, cap.emb.data() + (size_t)p * nd, nd * 4).wait()),
diff --git a/sycl/src/kernels/qsa_parity.cpp b/sycl/src/kernels/qsa_parity.cpp
index efbb202a2..9aaf02cbd 100644
--- a/sycl/src/kernels/qsa_parity.cpp
+++ b/sycl/src/kernels/qsa_parity.cpp
@@ -50,6 +50,7 @@
#include <sycl/sycl.hpp>
#include <dpct/dpct.hpp>
#include "strata/kernels/qsa.hpp"
+#include "strata/kernels/native_qsa_indexer.hpp"
#include "strata/kernels/f16_bits.hpp"
#include "strata/kernels/rope.hpp"
@@ -1452,6 +1453,230 @@ int main(int argc, char** argv) {
check(DPCT_CHECK_ERROR(delete (g2)), "gd");
}
+ // ================= the NATIVE indexer's batched append vs the sequential one =================
+ // The prefill path appends a chunk in one native_qsa_indexer_append_batch call, the decode path appends
+ // token by token - and one cache must never be able to tell which path filled it (rope_scaling.hpp's
+ // one-rotation rule). So the batch's whole end state must be BIT-IDENTICAL to the sequential appends',
+ // under all three scaling configs: none (today's rotation), linear 2 (pure angle shrink, no correction)
+ // and yarn 2 (corr-dims ramp and the mscale magnitude) - both kernels must take the same RopeScaling.
+ // "Bit-identical" is asserted on the bit representations (memcmp of the state words): float != would
+ // pass a NaN-payload or -0.0 flip that the claim does not cover. Eight cells: exactly two completed
+ // blocks, so the paths' end states agree on block_pos too (a mid-block chunk end leaves the sequential
+ // path pointing at the open block's base and the batch at the last completed one's - upstream C-2's own
+ // semantics, the same for every scaling; see native_qsa_indexer.hpp's block_pos contract).
+ {
+ std::printf("\n-- the native indexer's batched append vs the sequential one\n");
+ const int64_t NB = 8; // exactly two complete blocks of r=4
+ const int32_t BASE = 100; // positions 100..107, not cell indices 0..7
+ const int64_t MC = 1024; // the capacity both sides validate against
+ using RST = strata::kernels::RopeScalingType;
+ struct Variant { const char* name; RST type; double factor; double ext; };
+ const Variant variants[] = {{"none", RST::None, 1.0, 0.0},
+ {"linear 2", RST::Linear, 2.0, 0.0},
+ {"yarn 2", RST::YaRN, 2.0, 1.0}};
+ std::vector<float> raws((size_t) NB * IDXD);
+ for (int64_t t = 0; t < NB; ++t)
+ for (int64_t d = 0; d < IDXD; ++d)
+ raws[(size_t) t * IDXD + d] = (float) (gauss(rng) * std::pow(4.0, (double) (t % 4)));
+ dpct::queue_ptr cs = &dpct::get_in_order_queue();
+ check(DPCT_CHECK_ERROR(
+ cs = dpct::get_current_device().create_queue(true)),
+ "cs");
+ std::vector<float> none_pooled;
+ for (const Variant& var : variants) {
+ strata::kernels::RopeScaling sc;
+ sc.type = var.type;
+ sc.factor = var.factor;
+ sc.ext_factor = var.ext;
+ const size_t prows = (size_t) (MC / R + 1) * IDXD, trows = (size_t) (R - 1) * IDXD;
+ Dev<float> pooledA(prows), deadA(IDXD), tailA(trows), pooledB(prows), deadB(IDXD), tailB(trows);
+ Dev<int32_t> bposA(1), bposB(1), dpos(1);
+ for (Dev<float>* dp : {&pooledA, &deadA, &tailA, &pooledB, &deadB, &tailB})
+ check(
+ DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue()
+ .memset(dp->p, 0,
+ dp == &pooledA || dp == &pooledB ? prows * 4
+ : dp == &deadA || dp == &deadB ? IDXD * 4
+ : trows * 4)
+ .wait()),
+ "zero");
+ check(DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue().memset(bposA.p, 0, 4).wait()),
+ "zero");
+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memset(bposB.p, 0, 4)
+ .wait()),
+ "zero");
+ Dev<float> draw((size_t) IDXD), drawAll;
+ drawAll.put(raws);
+ strata::kernels::QsaIndexerBuffers bufsA{tailA.p, deadA.p, pooledA.p, bposA.p};
+ strata::kernels::QsaIndexerBuffers bufsB{tailB.p, deadB.p, pooledB.p, bposB.p};
+ for (int64_t t = 0; t < NB; ++t) { // the sequential side: one cell, its device position
+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memcpy(draw.p,
+ &raws[(size_t)t * IDXD],
+ (size_t)IDXD * 4)
+ .wait()),
+ "raw");
+ const int32_t tp = (int32_t) t;
+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memcpy(dpos.p, &tp, 4)
+ .wait()),
+ "pos");
+ strata::kernels::native_qsa_indexer_append(draw.p, dpos.p, BASE, dw_kn.p, EPS, bufsA, S, MC, sc, cs);
+ // SYCL port: cudaMemcpy on the legacy stream waited for this append before the next copy refilled
+ // `draw`; a default-queue copy does not wait for work on `cs`, so without this the next cell's raw
+ // keys could overwrite this one before the kernel reads them
+ check(DPCT_CHECK_ERROR(cs->wait()), "append");
+ }
+ strata::kernels::native_qsa_indexer_append_batch(drawAll.p, NB, 0, BASE, dw_kn.p, EPS, bufsB, S, MC, sc, cs);
+ check(DPCT_CHECK_ERROR(cs->wait()), "sync");
+ const std::vector<float> pa = pooledA.get(prows), pb = pooledB.get(prows);
+ const std::vector<float> da = deadA.get((size_t) IDXD), db = deadB.get((size_t) IDXD);
+ const std::vector<float> ta = tailA.get(trows), tbb = tailB.get(trows);
+ const std::vector<int32_t> ba = bposA.get(1), bb = bposB.get(1);
+ long long bad = 0;
+ for (size_t i = 0; i < pa.size(); ++i) bad += std::memcmp(&pa[i], &pb[i], 4) != 0;
+ for (size_t i = 0; i < da.size(); ++i) bad += std::memcmp(&da[i], &db[i], 4) != 0;
+ for (size_t i = 0; i < ta.size(); ++i) bad += std::memcmp(&ta[i], &tbb[i], 4) != 0;
+ bad += std::memcmp(&ba[0], &bb[0], 4) != 0;
+ std::printf(" %-44s %s (%lld of %zu state words differ)\n",
+ (std::string("batch vs sequential, ") + var.name).c_str(),
+ bad ? "*** WRONG ***" : "bit-identical", bad, pa.size() + da.size() + ta.size() + 1);
+ if (bad) ++g_bad;
+ if (var.type == RST::None) none_pooled = pa;
+ else {
+ int moved = 0;
+ for (size_t i = 0; i < pa.size(); ++i) moved += std::memcmp(&pa[i], &none_pooled[i], 4) != 0;
+ std::printf(" %-44s %d of %zu pooled words differ from the none baseline\n",
+ (std::string("the scaling is visible, ") + var.name).c_str(), moved, pa.size());
+ if (!moved) { std::printf(" *** the batched append ignored its scaling ***\n"); ++g_bad; }
+ }
+ }
+ check(DPCT_CHECK_ERROR(dpct::get_current_device().destroy_queue(cs)),
+ "csd");
+ }
+
+ // ================= the spare (position 0) under rope scaling: the table indexer vs the native one =========
+ // The spare key (`dead`, and `pooled[0]` until the first block completes) rotates at angle 0. Its sine is
+ // 0 in every scaling, so the rotation is `v * cos_tab[0][pair]`: exactly `v` unscaled (row 0 is (1, 0), the
+ // bit-exact value section 2 asserts), `v * mscale` under YaRN - the magnitude every other pooled row and
+ // the native kernel's spare carry. The table kernel used to skip the rotation at position 0, which left
+ // the spare the one unscaled key of a scaled cache. Asserted per variant: the table spare is BIT-EXACTLY
+ // the unscaled spare times row 0 on the rotated dims and the unscaled spare past them; `pooled[0]` equals
+ // `dead`; the native spare carries the same factor (to f32 rounding: its mscale is formed in float); and
+ // under YaRN the factor is observable (row 0 is not 1).
+ {
+ std::printf("\n-- the spare key (position 0) under rope scaling: table indexer vs native indexer\n");
+ using RST = strata::kernels::RopeScalingType;
+ struct Variant { const char* name; RST type; double factor; double ext; };
+ const Variant variants[] = {{"none", RST::None, 1.0, 0.0},
+ {"linear 2", RST::Linear, 2.0, 0.0},
+ {"yarn 2", RST::YaRN, 2.0, 1.0}};
+ const int64_t MC = 64, HALF = S.n_rot / 2, NROT = S.n_rot;
+ std::vector<float> raw0((size_t) IDXD);
+ for (int64_t d = 0; d < IDXD; ++d) raw0[(size_t) d] = rnd(3.0);
+ Dev<float> draw0;
+ draw0.put(raw0);
+ Dev<int32_t> dpos0(1);
+ const int32_t zero = 0;
+ check(DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue().memcpy(dpos0.p, &zero, 4).wait()),
+ "pos0");
+ dpct::queue_ptr cs = &dpct::get_in_order_queue();
+ check(DPCT_CHECK_ERROR(
+ cs = dpct::get_current_device().create_queue(true)),
+ "cs");
+ const size_t prows = (size_t) (MC / R + 1) * IDXD, trows = (size_t) (R - 1) * IDXD;
+ // one cell at position 0 through either kernel; returns (dead, pooled[0])
+ auto spare = [&](bool native, const strata::kernels::RopeScaling &sc,
+ std::vector<float> &dead,
+ std::vector<float> &pooled0) {
+ try {
+ Dev<float> pooled(prows), dd((size_t)IDXD), tail(trows);
+ Dev<int32_t> bpos(1);
+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memset(pooled.p, 0, prows * 4)
+ .wait()),
+ "zero");
+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memset(dd.p, 0, (size_t)IDXD * 4)
+ .wait()),
+ "zero");
+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memset(tail.p, 0, trows * 4)
+ .wait()),
+ "zero");
+ check(DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue().memset(bpos.p, 0, 4).wait()),
+ "zero");
+ strata::kernels::QsaIndexerBuffers bufs{tail.p, dd.p, pooled.p, bpos.p};
+ if (native) {
+ strata::kernels::native_qsa_indexer_append(draw0.p, dpos0.p, 0, dw_kn.p, EPS, bufs, S, MC, sc, cs);
+ } else {
+ std::vector<float> tc((size_t) (MC * HALF)), ts(tc.size());
+ strata::kernels::build_rope_table((int) NROT, sc, (int) MC, tc.data(), ts.data());
+ Dev<float> dc, dsn;
+ dc.put(tc);
+ dsn.put(ts);
+ strata::kernels::indexer_key_append(draw0.p, dpos0.p, 0, dw_kn.p, EPS, bufs, S, dc.p, dsn.p, cs);
+ }
+ check(DPCT_CHECK_ERROR(cs->wait()), "sync");
+ dead = dd.get((size_t) IDXD);
+ pooled0 = pooled.get((size_t) IDXD);
+ }
+ catch (sycl::exception const &exc) {
+ std::cerr << exc.what()
+ << "Exception caught at file:" << __FILE__
+ << ", line:" << __LINE__ << std::endl;
+ std::exit(1);
+ }
+ };
+ std::vector<float> t_none, t_none_p, n_none, n_none_p;
+ for (const Variant& var : variants) {
+ strata::kernels::RopeScaling sc;
+ sc.type = var.type;
+ sc.factor = var.factor;
+ sc.ext_factor = var.ext;
+ std::vector<float> row0c((size_t) (MC * HALF)), row0s(row0c.size());
+ strata::kernels::build_rope_table((int) NROT, sc, (int) MC, row0c.data(), row0s.data());
+ std::vector<float> td, tp, nd, np;
+ spare(false, sc, td, tp);
+ spare(true, sc, nd, np);
+ if (var.type == RST::None) { t_none = td; t_none_p = tp; n_none = nd; n_none_p = np; }
+ long long tbad = 0, pbad = 0, sin_bad = 0;
+ double nworst = 0;
+ for (int64_t i = 0; i < HALF; ++i) sin_bad += row0s[(size_t) i] != 0.0f;
+ for (int64_t d = 0; d < IDXD; ++d) {
+ const float c0 = d < NROT ? row0c[(size_t) (d % HALF)] : 1.0f;
+ const float want = d < NROT ? t_none[(size_t) d] * c0 : t_none[(size_t) d];
+ tbad += std::memcmp(&td[(size_t) d], &want, 4) != 0;
+ pbad += std::memcmp(&tp[(size_t) d], &td[(size_t) d], 4) != 0;
+ const double nwant = (double) n_none[(size_t) d] * (double) c0;
+ const double den = std::max(std::fabs(nwant), 1e-6);
+ nworst = std::max(nworst, std::fabs((double) nd[(size_t) d] - nwant) / den);
+ }
+ require(std::string(" ") + var.name + ": row 0 of the table is (c, 0)", sin_bad == 0,
+ std::to_string(sin_bad) + " nonzero sines");
+ require(std::string(" ") + var.name + ": the table spare is the unscaled spare times row 0, BIT-EXACT",
+ tbad == 0, std::to_string(tbad) + " of " + std::to_string(IDXD) + " wrong");
+ require(std::string(" ") + var.name + ": the table's pooled[0] is its spare", pbad == 0,
+ std::to_string(pbad) + " wrong");
+ require(std::string(" ") + var.name + ": the native spare carries the same row-0 factor", nworst <= 4e-7,
+ "worst relative " + std::to_string(nworst));
+ if (var.type == RST::YaRN) {
+ int moved = 0;
+ for (int64_t d = 0; d < NROT; ++d) moved += std::memcmp(&td[(size_t) d], &t_none[(size_t) d], 4) != 0;
+ require(" yarn 2: the magnitude correction is observable on the table spare",
+ row0c[0] != 1.0f && moved > NROT / 2,
+ "row0 cos " + std::to_string(row0c[0]) + ", " + std::to_string(moved) + " dims moved");
+ }
+ }
+ check(DPCT_CHECK_ERROR(dpct::get_current_device().destroy_queue(cs)),
+ "csd");
+ }
+
std::printf("\nqsa: %d failures\n", g_bad);
if (g_bad) return 1;
if (selftest) std::printf("qsa_parity OK\n");
diff --git a/sycl/src/kernels/qsa_prompt_attn_parity.cpp b/sycl/src/kernels/qsa_prompt_attn_parity.cpp
index 645f21f87..42d634d93 100644
--- a/sycl/src/kernels/qsa_prompt_attn_parity.cpp
+++ b/sycl/src/kernels/qsa_prompt_attn_parity.cpp
@@ -39,9 +39,9 @@ template <typename T> T* up(const std::vector<T>& h) {
dpct::get_in_order_queue())),
"malloc");
/*
- 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
+ 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_in_order_queue().memcpy(
diff --git a/sycl/src/kernels/rope_parity.cpp b/sycl/src/kernels/rope_parity.cpp
index ccb1df640..bec5af5a6 100644
--- a/sycl/src/kernels/rope_parity.cpp
+++ b/sycl/src/kernels/rope_parity.cpp
@@ -12,10 +12,23 @@
// A single end-to-end comparison would have had to carry one loose tolerance for both, and the interesting
// failure - the NEOX pairing being wrong - is a PERMUTATION that a loose tolerance over all 256 dims would
// happily accept.
+//
+// Check 4 extends the same discipline to the SCALED tables (rope scaling: none/linear/YaRN). The rotation
+// kernel cannot see scaling - it lives in the table contents - so each variant's TABLE is held to a float64
+// transcription of ggml's `rope_yarn` spec (the ramp helper is shared, the `rope_neox_pair` convention), and
+// the two properties a tolerance could never fake get their own structural checks: at position 0 every pair's
+// angle is 0, so YaRN's mscale stands naked in cos_tab[0], and at a far position the first pair must match
+// EXTRAPOLATION while the last matches INTERPOLATION. An observability assertion closes it: if the scaled
+// and unscaled tables were indistinguishable, every green number above would be vacuous.
+//
+// Check 5 holds the TWO PATHS together: the table path's float64 host trig and the native path's float32
+// fast-math device trig must answer to the same `RopeScaling`, yarn and none alike, so one cache never
+// mixes two rotations.
#define DPCT_PROFILING_ENABLED
#include <sycl/sycl.hpp>
#include <dpct/dpct.hpp>
#include "strata/kernels/rope.hpp"
+#include "strata/kernels/native_rope.hpp"
#include <cmath>
#include <cstdio>
@@ -107,36 +120,36 @@ int main(int argc, char** argv) {
pos.size(), dpct::get_in_order_queue())),
"malloc pos");
/*
- 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
+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
+ in the original code the source host memory is pageable memory. If the
+ memory is not pageable, call wait() on event return by memcpy API to ensure
synchronization behavior.
*/
check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
d_x, x.data(), x.size() * sizeof(float)).wait()),
"copy x");
/*
- 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
+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
+ in the original code the source host memory is pageable memory. If the
+ memory is not pageable, call wait() on event return by memcpy API to ensure
synchronization behavior.
*/
check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
d_cos, hcos.data(), hcos.size() * sizeof(float)).wait()),
"copy cos");
/*
- 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
+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
+ in the original code the source host memory is pageable memory. If the
+ memory is not pageable, call wait() on event return by memcpy API to ensure
synchronization behavior.
*/
check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
d_sin, hsin.data(), hsin.size() * sizeof(float)).wait()),
"copy sin");
/*
- 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
+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
+ in the original code the source host memory is pageable memory. If the
+ memory is not pageable, call wait() on event return by memcpy API to ensure
synchronization behavior.
*/
check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
@@ -222,6 +235,378 @@ int main(int argc, char** argv) {
if (!(neox_moved && !adjacent_moved)) ++bad;
}
+ // ---- 4. THE SCALED TABLES (rope_scaling.hpp). Scaling lives in the table contents, so each variant is
+ // a table check: a float64 transcription of the ggml spec, bit-exact after the float32 cast, plus the
+ // structural and observability checks the tolerances cannot cover.
+ {
+ // 4a. type None IS the five-argument builder above - bit for bit.
+ std::vector<float> nc((size_t) max_pos * half), ns((size_t) max_pos * half);
+ strata::kernels::RopeScaling none;
+ none.freq_base = theta;
+ strata::kernels::build_rope_table(n_rot, none, max_pos, nc.data(), ns.data());
+ const long long none_bad =
+ (long long) (std::memcmp(nc.data(), hcos.data(), nc.size() * 4) != 0) +
+ (long long) (std::memcmp(ns.data(), hsin.data(), ns.size() * 4) != 0);
+ std::printf(" scaled table, None vs unscaled builder %s\n", none_bad ? "*** WRONG ***" : "bit-identical");
+ bad += (int) none_bad;
+
+ // 4b. LINEAR, factor 4: `ang = p * inv / 4` in float64. The factor is a power of two on purpose -
+ // dividing by it is exact, so no multiplication-order rounding can sneak between spec and builder.
+ strata::kernels::RopeScaling lin;
+ lin.type = strata::kernels::RopeScalingType::Linear;
+ lin.freq_base = theta;
+ lin.factor = 4.0;
+ std::vector<float> lc((size_t) max_pos * half), ls((size_t) max_pos * half);
+ strata::kernels::build_rope_table(n_rot, lin, max_pos, lc.data(), ls.data());
+ long long lin_bad = 0;
+ for (int p = 0; p < max_pos; ++p) {
+ for (int i = 0; i < half; ++i) {
+ const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot);
+ const double ang = (double) p * inv / 4.0;
+ const float rc = (float) std::cos(ang), rs = (float) std::sin(ang);
+ if (std::memcmp(&rc, &lc[(size_t) p * half + i], 4) != 0) ++lin_bad;
+ if (std::memcmp(&rs, &ls[(size_t) p * half + i], 4) != 0) ++lin_bad;
+ }
+ }
+ std::printf(" scaled table, linear factor 4 %s (%lld of %d entries differ)\n",
+ lin_bad ? "*** WRONG ***" : "bit-exact", lin_bad, max_pos * half * 2);
+ bad += (int) lin_bad;
+
+ // 4c. THE INTERPOLATION CLAIM ITSELF: linear(4) at position p is `none` at p/4 - the same table row,
+ // bit for bit, at every position divisible by the factor.
+ std::vector<float> wc((size_t) 4 * max_pos * half), ws((size_t) 4 * max_pos * half);
+ strata::kernels::build_rope_table(n_rot, lin, 4 * max_pos, wc.data(), ws.data());
+ long long equiv_bad = 0;
+ for (int p = 0; p < 4 * max_pos; p += 4) {
+ for (int i = 0; i < half; ++i) {
+ if (std::memcmp(&wc[(size_t) p * half + i], &hcos[(size_t) (p / 4) * half + i], 4) != 0) ++equiv_bad;
+ if (std::memcmp(&ws[(size_t) p * half + i], &hsin[(size_t) (p / 4) * half + i], 4) != 0) ++equiv_bad;
+ }
+ }
+ std::printf(" linear(4) @ p == none @ p/4 %s (%lld of %d rows differ)\n",
+ equiv_bad ? "*** WRONG ***" : "bit-identical", equiv_bad, max_pos);
+ bad += (int) equiv_bad;
+
+ // 4d. YARN vs a float64 transcription of ggml's rope_yarn (factor 4, the default correction knobs).
+ // The ramp helper is shared with the builder (the rope_neox_pair convention: one definition, not two
+ // transcriptions of it); the interpolation mix and the mscale formula are written here from the ggml
+ // source lines, which is the spec being tested.
+ strata::kernels::RopeScaling yarn;
+ yarn.type = strata::kernels::RopeScalingType::YaRN;
+ yarn.freq_base = theta;
+ yarn.factor = 4.0;
+ yarn.ext_factor = 1.0;
+ std::vector<float> yc((size_t) max_pos * half), ys((size_t) max_pos * half);
+ strata::kernels::build_rope_table(n_rot, yarn, max_pos, yc.data(), ys.data());
+ const double fs = yarn.freq_scale(); // 0.25
+ const double ms = yarn.mscale(); // attn_factor * (1 + 0.1*ln(4))
+ double cd[2];
+ yarn.corr_dims(n_rot, cd);
+ long long yarn_bad = 0;
+ for (int p = 0; p < max_pos; ++p) {
+ for (int i = 0; i < half; ++i) {
+ const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot);
+ const double extrap = (double) p * inv;
+ const double interp = fs * extrap;
+ const double ramp = (double) strata::kernels::rope_yarn_ramp((float) cd[0], (float) cd[1], i) *
+ yarn.ext_factor;
+ const double ang = interp * (1.0 - ramp) + extrap * ramp;
+ const float rc = (float) (std::cos(ang) * ms), rs = (float) (std::sin(ang) * ms);
+ if (std::memcmp(&rc, &yc[(size_t) p * half + i], 4) != 0) ++yarn_bad;
+ if (std::memcmp(&rs, &ys[(size_t) p * half + i], 4) != 0) ++yarn_bad;
+ }
+ }
+ std::printf(" scaled table, yarn factor 4 %s (%lld of %d entries differ)\n",
+ yarn_bad ? "*** WRONG ***" : "bit-exact", yarn_bad, max_pos * half * 2);
+ bad += (int) yarn_bad;
+
+ // 4e. THE STRUCTURE a tolerance cannot fake. At position 0 every pair's angle is 0, so YaRN's whole
+ // magnitude correction stands naked: cos_tab[0] == mscale. At the far end of the table the first
+ // pair (the highest trained frequency) must match EXTRAPOLATION and the last INTERPOLATION. The two
+ // halves need different observables: at the first pair cos separates the hypotheses outright, but at
+ // the last they differ by ~4 microradians here, invisible to cos near 1 - sin sees it, because near
+ // zero sin IS the angle. That asymmetry is the YaRN design: interpolation happens where angles are
+ // small. Both hypotheses go through the same mix formula the builder uses, so the bit comparison is
+ // spec against spec, not shortcut against implementation.
+ {
+ const float msv = (float) ms;
+ const bool zero_ok = std::memcmp(&msv, &yc[0], 4) == 0 && ys[0] == 0.0f;
+ const int far = max_pos - 1;
+ const double inv_f = 1.0; // pair 0: theta ** 0
+ const double extrap_f = (double) far * inv_f, interp_f = fs * extrap_f;
+ const double inv_l = std::pow(theta, -2.0 * (double) (half - 1) / (double) n_rot);
+ const double extrap_l = (double) far * inv_l, interp_l = fs * extrap_l;
+ const float ef = (float) (std::cos(interp_f * (1.0 - 1.0) + extrap_f * 1.0) * ms);
+ const float itf = (float) (std::cos(interp_f * (1.0 - 0.0) + extrap_f * 0.0) * ms);
+ const float sl_e = (float) (std::sin(interp_l * (1.0 - 1.0) + extrap_l * 1.0) * ms);
+ const float sl_i = (float) (std::sin(interp_l * (1.0 - 0.0) + extrap_l * 0.0) * ms);
+ const float got_f = yc[(size_t) far * half], got_l = ys[(size_t) far * half + (half - 1)];
+ const bool first_extrapolates = std::memcmp(&got_f, &ef, 4) == 0;
+ const bool last_interpolates = std::memcmp(&got_l, &sl_i, 4) == 0;
+ const bool distinguishable = std::fabs((double) ef - (double) itf) > 1e-3 &&
+ std::fabs((double) sl_e - (double) sl_i) > 1e-8;
+ std::printf(" yarn structure: cos_tab[0]==mscale %.4f, first pair extrapolates, last interpolates "
+ "%s\n", (double) msv,
+ zero_ok && first_extrapolates && last_interpolates && distinguishable
+ ? "confirmed"
+ : "*** WRONG ***");
+ if (!(zero_ok && first_extrapolates && last_interpolates && distinguishable)) ++bad;
+ }
+
+ // 4f. THE OBSERVABILITY assertion: the fixtures must SEE scaling. If the builder ignored its config,
+ // linear(2) would equal `none` everywhere and 4b-4e would be green on a broken builder.
+ {
+ strata::kernels::RopeScaling lin2;
+ lin2.type = strata::kernels::RopeScalingType::Linear;
+ lin2.freq_base = theta;
+ lin2.factor = 2.0;
+ std::vector<float> l2c((size_t) 101 * half), l2s((size_t) 101 * half);
+ strata::kernels::build_rope_table(n_rot, lin2, 101, l2c.data(), l2s.data());
+ const float c_none = (float) std::cos(100.0); // pair 0, position 100, unscaled: ang = 100
+ const float c_lin = l2c[(size_t) 100 * half]; // pair 0, position 100, linear(2): ang = 50
+ const bool sees = std::fabs((double) c_none - (double) c_lin) > 1e-3;
+ std::printf(" observability: none vs linear(2) at position 100 %s (|%.4f - %.4f|)\n",
+ sees ? "visible" : "*** VACUUM ***", (double) c_none, (double) c_lin);
+ if (!sees) ++bad;
+ }
+
+ // 4g. THE ROTATION under a scaled table. The kernel is table-agnostic and must not know or care:
+ // the host reference is the same rope_neox_pair walk as check 2, over the YaRN table.
+ std::vector<float> ref2(x.size());
+ for (int r = 0; r < rows; ++r) {
+ const float* xr = &x[(size_t) r * head_dim];
+ float* orow = &ref2[(size_t) r * head_dim];
+ for (int d = 0; d < head_dim; ++d) orow[d] = xr[d];
+ for (int i = 0; i < half; ++i) {
+ float c = yc[(size_t) pos[(size_t) r] * half + i], s = ys[(size_t) pos[(size_t) r] * half + i];
+ strata::kernels::rope_neox_pair(xr[i], xr[half + i], c, s, orow[i], orow[half + i]);
+ }
+ }
+ /*
+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
+ assuming in the original code the source host memory is pageable memory.
+ If the memory is not pageable, call wait() on event return by memcpy API
+ to ensure synchronization behavior.
+ */
+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
+ d_x, x.data(), x.size() * sizeof(float)).wait()),
+ "copy x");
+ /*
+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
+ assuming in the original code the source host memory is pageable memory.
+ If the memory is not pageable, call wait() on event return by memcpy API
+ to ensure synchronization behavior.
+ */
+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
+ d_cos, yc.data(), yc.size() * sizeof(float)).wait()),
+ "copy ycos");
+ /*
+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
+ assuming in the original code the source host memory is pageable memory.
+ If the memory is not pageable, call wait() on event return by memcpy API
+ to ensure synchronization behavior.
+ */
+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
+ d_sin, ys.data(), ys.size() * sizeof(float)).wait()),
+ "copy ysin");
+ /*
+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
+ assuming in the original code the source host memory is pageable memory.
+ If the memory is not pageable, call wait() on event return by memcpy API
+ to ensure synchronization behavior.
+ */
+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
+ d_pos, pos.data(), pos.size() * sizeof(int)).wait()),
+ "copy pos");
+ strata::kernels::rope_neox_apply(d_x, d_out, rows, head_dim, n_rot, d_cos, d_sin, d_pos, nullptr);
+ std::vector<float> got2(ref2.size());
+ check(DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue()
+ .memcpy(got2.data(), d_out, got2.size() * sizeof(float))
+ .wait()),
+ "back");
+ long long rot2_bad = 0;
+ double worst2 = 0.0;
+ for (size_t i = 0; i < ref2.size(); ++i) {
+ const double a = ref2[i], b = got2[i];
+ const double rel = std::fabs(a - b) / row_scale[i / (size_t) head_dim];
+ worst2 = std::max(worst2, rel);
+ if (!(rel <= 1e-6)) ++rot2_bad;
+ }
+ std::printf(" rope rotation over the yarn table %s (%lld of %zu over 1e-6, worst rel %.3e)\n",
+ rot2_bad ? "*** WRONG ***" : "agrees", rot2_bad, ref2.size(), worst2);
+ bad += (int) rot2_bad;
+ }
+
+ // ---- 5. THE TWO PATHS MUST AGREE. The table path (the default) computes cos/sin on the host in float64;
+ // the native path (`--native-rope`) computes the same angles on device in float32 under `--use_fast_math`.
+ // They answer to ONE config - `RopeScaling` - and a disagreement between them would put differently-rotated
+ // K into the cache depending on which path ran. The tolerance is NOT the 1e-6 of checks 2/4g: the device
+ // side takes fast-math trig at angles up to ~2048 rad, where the fp32 range reduction alone is worth ~1e-4,
+ // so the bar is the row-magnitude-relative 3e-3 and the test keeps the positions where that holds. (The
+ // engine's default is the table path precisely because float64 host trig has no such floor.)
+ {
+ const int npos = 2048;
+ strata::kernels::RopeScaling yarn;
+ yarn.type = strata::kernels::RopeScalingType::YaRN;
+ yarn.factor = 2.0;
+ yarn.ext_factor = 1.0;
+ std::vector<float> sc((size_t) npos * half), ss((size_t) npos * half);
+ strata::kernels::build_rope_table(n_rot, yarn, npos, sc.data(), ss.data());
+ std::mt19937 rng2(23);
+ std::normal_distribution<float> gauss2(0.0f, 1.0f);
+ const int nrows = 24 * 16; // 16 positions spread over the table's range
+ std::vector<float> x2((size_t) nrows * head_dim);
+ for (auto& v : x2) v = gauss2(rng2);
+ std::vector<int> pos2((size_t) nrows);
+ for (int r = 0; r < nrows; ++r) pos2[(size_t) r] = (r * 127) % npos;
+
+ float *d_x2 = nullptr, *d_t2 = nullptr, *d_n2 = nullptr, *d_c2 = nullptr, *d_s2 = nullptr;
+ int* d_p2 = nullptr;
+ check(DPCT_CHECK_ERROR(d_x2 = sycl::malloc_device<float>(
+ x2.size(), dpct::get_in_order_queue())),
+ "malloc x2");
+ check(DPCT_CHECK_ERROR(d_t2 = sycl::malloc_device<float>(
+ x2.size(), dpct::get_in_order_queue())),
+ "malloc t2");
+ check(DPCT_CHECK_ERROR(d_n2 = sycl::malloc_device<float>(
+ x2.size(), dpct::get_in_order_queue())),
+ "malloc n2");
+ check(DPCT_CHECK_ERROR(d_c2 = sycl::malloc_device<float>(
+ sc.size(), dpct::get_in_order_queue())),
+ "malloc c2");
+ check(DPCT_CHECK_ERROR(d_s2 = sycl::malloc_device<float>(
+ ss.size(), dpct::get_in_order_queue())),
+ "malloc s2");
+ check(DPCT_CHECK_ERROR(d_p2 = sycl::malloc_device<int>(
+ pos2.size(), dpct::get_in_order_queue())),
+ "malloc p2");
+ /*
+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
+ assuming in the original code the source host memory is pageable memory.
+ If the memory is not pageable, call wait() on event return by memcpy API
+ to ensure synchronization behavior.
+ */
+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
+ d_x2, x2.data(), x2.size() * sizeof(float)).wait()),
+ "copy x2");
+ /*
+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
+ assuming in the original code the source host memory is pageable memory.
+ If the memory is not pageable, call wait() on event return by memcpy API
+ to ensure synchronization behavior.
+ */
+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
+ d_c2, sc.data(), sc.size() * sizeof(float)).wait()),
+ "copy c2");
+ /*
+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
+ assuming in the original code the source host memory is pageable memory.
+ If the memory is not pageable, call wait() on event return by memcpy API
+ to ensure synchronization behavior.
+ */
+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
+ d_s2, ss.data(), ss.size() * sizeof(float)).wait()),
+ "copy s2");
+ /*
+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
+ assuming in the original code the source host memory is pageable memory.
+ If the memory is not pageable, call wait() on event return by memcpy API
+ to ensure synchronization behavior.
+ */
+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
+ d_p2, pos2.data(), pos2.size() * sizeof(int)).wait()),
+ "copy p2");
+ // The native path demands an explicit stream - a null one is refused by validation, not defaulted.
+ dpct::queue_ptr cs5 = &dpct::get_in_order_queue();
+ check(DPCT_CHECK_ERROR(
+ cs5 = dpct::get_current_device().create_queue(true)),
+ "stream5");
+ strata::kernels::rope_neox_apply(d_x2, d_t2, nrows, head_dim, n_rot, d_c2, d_s2, d_p2, nullptr);
+ strata::kernels::native_rope_apply(d_x2, d_n2, nrows, head_dim, n_rot, yarn, d_p2, cs5);
+ check(DPCT_CHECK_ERROR(cs5->wait()), "sync5");
+ std::vector<float> got_t(x2.size()), got_n(x2.size());
+ check(DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue()
+ .memcpy(got_t.data(), d_t2, got_t.size() * sizeof(float))
+ .wait()),
+ "back t2");
+ check(DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue()
+ .memcpy(got_n.data(), d_n2, got_n.size() * sizeof(float))
+ .wait()),
+ "back n2");
+ long long agree_bad = 0;
+ double worst = 0.0;
+ for (int r = 0; r < nrows; ++r) {
+ double m = 0;
+ for (int d = 0; d < head_dim; ++d) m = std::max(m, (double) std::fabs(x2[(size_t) r * head_dim + d]));
+ const double scale = m > 1e-30 ? m : 1e-30;
+ for (int d = 0; d < head_dim; ++d) {
+ const double rel = std::fabs((double) got_t[(size_t) r * head_dim + d] -
+ (double) got_n[(size_t) r * head_dim + d]) / scale;
+ worst = std::max(worst, rel);
+ if (!(rel <= 3e-3)) ++agree_bad;
+ }
+ }
+ std::printf(" native path vs table path, yarn factor 2 %s (%lld of %d over 3e-3, worst rel %.3e)\n",
+ agree_bad ? "*** WRONG ***" : "agrees", agree_bad, nrows * head_dim, worst);
+ bad += (int) agree_bad;
+
+ // and the None config: the native path against the UNSCALED table - the identity this feature must
+ // not disturb.
+ strata::kernels::RopeScaling none5; // all defaults: type None, freq_scale 1, mscale 1
+ strata::kernels::native_rope_apply(d_x2, d_n2, nrows, head_dim, n_rot, none5, d_p2, cs5);
+ check(DPCT_CHECK_ERROR(cs5->wait()), "sync5b");
+ check(DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue()
+ .memcpy(got_n.data(), d_n2, got_n.size() * sizeof(float))
+ .wait()),
+ "back n2b");
+ std::vector<float> nc5((size_t) npos * half), ns5((size_t) npos * half);
+ strata::kernels::build_rope_table(n_rot, none5, npos, nc5.data(), ns5.data());
+ /*
+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
+ assuming in the original code the source host memory is pageable memory.
+ If the memory is not pageable, call wait() on event return by memcpy API
+ to ensure synchronization behavior.
+ */
+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
+ d_c2, nc5.data(), nc5.size() * sizeof(float)).wait()),
+ "copy c2b");
+ /*
+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
+ assuming in the original code the source host memory is pageable memory.
+ If the memory is not pageable, call wait() on event return by memcpy API
+ to ensure synchronization behavior.
+ */
+ check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
+ d_s2, ns5.data(), ns5.size() * sizeof(float)).wait()),
+ "copy s2b");
+ strata::kernels::rope_neox_apply(d_x2, d_t2, nrows, head_dim, n_rot, d_c2, d_s2, d_p2, nullptr);
+ check(DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue()
+ .memcpy(got_t.data(), d_t2, got_t.size() * sizeof(float))
+ .wait()),
+ "back t2b");
+ long long none_bad5 = 0;
+ double worst5 = 0.0;
+ for (int r = 0; r < nrows; ++r) {
+ double m = 0;
+ for (int d = 0; d < head_dim; ++d) m = std::max(m, (double) std::fabs(x2[(size_t) r * head_dim + d]));
+ const double scale = m > 1e-30 ? m : 1e-30;
+ for (int d = 0; d < head_dim; ++d) {
+ const double rel = std::fabs((double) got_t[(size_t) r * head_dim + d] -
+ (double) got_n[(size_t) r * head_dim + d]) / scale;
+ worst5 = std::max(worst5, rel);
+ if (!(rel <= 3e-3)) ++none_bad5;
+ }
+ }
+ std::printf(" native path vs table path, none %s (%lld of %d over 3e-3, worst rel %.3e)\n",
+ none_bad5 ? "*** WRONG ***" : "agrees", none_bad5, nrows * head_dim, worst5);
+ bad += (int) none_bad5;
+ }
+
std::printf("\nrope: %d failures\n", bad);
if (bad) return 1;
if (selftest) std::printf("rope_parity OK\n");
diff --git a/sycl/src/kernels/s2_expert_grouped_parity.cpp b/sycl/src/kernels/s2_expert_grouped_parity.cpp
new file mode 100644
index 000000000..2d53dcfc3
--- /dev/null
+++ b/sycl/src/kernels/s2_expert_grouped_parity.cpp
@@ -0,0 +1,790 @@
+// src/kernels/s2_expert_grouped_parity.cpp - the rewritten expert kernels against the previous ones,
+// BITWISE (GPU, synthetic, no model).
+//
+// build/s2_expert_grouped_parity the checks below; exit 1 on any difference
+// build/s2_expert_grouped_parity --bench previous vs new kernel timings on engine-like shapes
+//
+// Random Q2_0 expert blobs (random codes, fp16 scales in a realistic range) and random Q8_0 activations. Every entry
+// point of `s2_expert_grouped.hpp` that gained a new kernel runs twice from identical inputs and sentinel-filled
+// outputs - `moe_grouped_select_old(1)`, then `(0)` - and the two runs are compared byte for byte:
+// 1. `moe_hit_grouped_s2` per hit, host count; with fp32 activation scales and with the blocks' fp16 `d`
+// 2. `moe_hit_grouped_s2_dev` device count below the capacity (the rows past it must stay untouched)
+// 3. `moe_hit_grouped_s2_multi` verify window: each hit reads its own token's activation row
+// 4. `moe_grouped_s2` host-built groups of 1..8 entries, one of them a mapped HOST blob (the PCIe
+// share), and more group capacity than groups
+// 5. `moe_group_resident` + `moe_grouped_s2` the MTP layer's shape, with and without fp32 scales
+// 6. an activation row that is only 2-byte aligned: the new path must fall back to the previous kernels
+// 7. a slot stride that is not a multiple of 8 (BLOB + 4), and 8. an arena 4 bytes past an aligned address: the
+// per-hit path must fall back as well (its codes are read as uint2)
+// Every run asks `moe_grouped_last_path` which kernels it launched, so a new path that silently declined cannot pass
+// as "the previous kernels against themselves": forced new must report the new kernels, and 6-8 the previous ones.
+// (A misaligned scratch is not exercised: the previous kernels store floats there, so it is not a legal input.)
+// The output AND the scratch (gate/up, the quantized intermediate and its scales) are compared, so a failure names
+// the projection. Bitwise equality with the previous kernels is the contract; on top of it a double-precision
+// host reference of every up row and every down row checks that the fixture computes an expert at all - two
+// kernels agreeing on garbage would otherwise pass.
+#define DPCT_PROFILING_ENABLED
+#include <sycl/sycl.hpp>
+#include <dpct/dpct.hpp>
+#include "strata/kernels/f16_bits.hpp"
+#include "strata/kernels/s2_expert_grouped.hpp"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <functional>
+#include <numeric>
+#include <random>
+#include <string>
+#include <vector>
+
+namespace k = strata::kernels;
+
+namespace {
+// The blob geometry, `cpu/expert.hpp`'s (restated as in the kernel).
+constexpr int H = 2560, FF = 640, NCH_GU = H / 32, NCH_D = FF / 32;
+constexpr size_t ROW_GU = H / 4, ROW_D = FF / 4, SC_GU = H / 64, SC_D = FF / 64;
+constexpr size_t O_D_CODES = 2ull * FF * ROW_GU;
+constexpr size_t O_GU_SCALES = O_D_CODES + (size_t) H * ROW_D;
+constexpr size_t O_D_SCALES = O_GU_SCALES + 2ull * FF * SC_GU * 2;
+constexpr size_t BLOB = O_D_SCALES + (size_t) H * SC_D * 2;
+static_assert(BLOB == 1382400, "the Q2_0 expert blob is 1,382,400 bytes");
+constexpr size_t XROW = (size_t) NCH_GU * 34; // one token's activation row of block_q8_0
+
+int g_fail = 0;
+
+void ck(dpct::err0 e, const char *w) {
+ /*
+ 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.
+ */
+}
+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_in_order_queue().memset(p, 0, n * sizeof(T) + 256).wait()),
+ "memset");
+ return p;
+}
+template <typename T> void up(T* d, const std::vector<T>& h) {
+ /*
+ 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_in_order_queue().memcpy(
+ d, h.data(), h.size() * sizeof(T)).wait()),
+ "h2d");
+}
+template <typename T> std::vector<T> down(const T* d, size_t n) {
+ std::vector<T> h(n);
+ ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memcpy(h.data(), d, n * sizeof(T))
+ .wait()),
+ "d2h");
+ return h;
+}
+
+float f16f(const uint8_t* p) { return k::f32_from_f16((uint16_t) (p[0] | (p[1] << 8))); }
+void put16(uint8_t* p, float f) {
+ const uint16_t h = k::f16_from_f32(f);
+ p[0] = (uint8_t) h;
+ p[1] = (uint8_t) (h >> 8);
+}
+
+// Random codes; fp16 scales of either sign in [1e-3, 3e-2] (a real pack's range, so no overflow downstream).
+void fill_blob(uint8_t* b, std::mt19937& rng) {
+ for (size_t i = 0; i < O_GU_SCALES; ++i) b[i] = (uint8_t) rng();
+ std::uniform_real_distribution<float> mag(1e-3f, 3e-2f);
+ for (size_t i = O_GU_SCALES; i < BLOB; i += 2) put16(b + i, (rng() & 1 ? -1.0f : 1.0f) * mag(rng));
+}
+
+// `n_tok` activation rows: per 32-chunk an fp16 `d` then 32 int8 in [-127, 127] (what `quantize_q8_0` writes),
+// plus the fp32 scales `quantize_q8_0_scaled` would pass alongside. Some chunks are saturated on purpose.
+void fill_x(std::vector<uint8_t>& x, std::vector<float>& xs, int n_tok, std::mt19937& rng) {
+ x.assign((size_t) n_tok * XROW, 0);
+ xs.assign((size_t) n_tok * NCH_GU, 0.0f);
+ std::uniform_real_distribution<float> sc(2e-3f, 5e-2f);
+ for (size_t c = 0; c < (size_t) n_tok * NCH_GU; ++c) {
+ uint8_t* b = x.data() + c * 34;
+ xs[c] = sc(rng);
+ put16(b, xs[c]);
+ const int mode = (int) (rng() % 16);
+ for (int j = 0; j < 32; ++j) {
+ const int v = mode == 0 ? 127 : mode == 1 ? -127 : (int) (rng() % 255) - 127;
+ b[2 + j] = (uint8_t) (int8_t) v;
+ }
+ }
+}
+
+// Double-precision reference of one row against one activation row: sum_c dw * dx * sum_e (code_e - 1) * x_e.
+// `mag` receives sum |term|, the scale the tolerance is relative to.
+double row_ref(const uint8_t* codes, const uint8_t* scales, const uint8_t* xrow, const float* xs, int n_chunks,
+ double* mag) {
+ double acc = 0.0, a = 0.0;
+ for (int c = 0; c < n_chunks; ++c) {
+ const uint8_t* xb = xrow + (size_t) c * 34;
+ const double dx = xs ? (double) xs[c] : (double) f16f(xb);
+ const double dw = (double) f16f(scales + (size_t) (c >> 1) * 2);
+ int s = 0;
+ for (int e = 0; e < 32; ++e) {
+ const int code = (codes[(size_t) c * 8 + e / 4] >> (2 * (e % 4))) & 3;
+ s += (code - 1) * (int) (int8_t) xb[2 + e];
+ }
+ const double t = dw * dx * (double) s;
+ acc += t;
+ a += std::fabs(t);
+ }
+ *mag = a;
+ return acc;
+}
+
+bool close_to(float got, double ref, double mag) {
+ return std::isfinite(got) && std::fabs((double) got - ref) <= 4e-5 * mag + 1e-30;
+}
+
+struct Scratch {
+ void* p = nullptr;
+ uint64_t bytes = 0;
+ int64_t cap = 0;
+ uint64_t gu_bytes() const { return ((uint64_t) cap * 2 * FF * 4 + 15) & ~15ull; }
+ uint64_t q8_bytes() const { return ((uint64_t) cap * NCH_D * 34 + 15) & ~15ull; }
+};
+
+// One entry point, run with the previous kernels then with the new ones from identical sentinel-filled buffers;
+// every differing float of the output and byte of the scratch is counted. `keep` receives the new run.
+struct Run {
+ std::vector<float> out;
+ std::vector<uint8_t> scratch;
+};
+
+bool twice(const char* name, float* d_out, size_t out_floats, const Scratch& s,
+ const std::function<void()>& call, Run* keep, bool expect_new = true) {
+ Run r[2];
+ for (int old = 1; old >= 0; --old) {
+ ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memset(d_out, 0xA5, out_floats * 4)
+ .wait()),
+ "sentinel out");
+ ck(DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue().memset(s.p, 0x5A, s.bytes).wait()),
+ "sentinel scratch");
+ k::moe_grouped_select_old(old);
+ (void) k::moe_grouped_last_path(); // clear
+ call();
+ const int path = k::moe_grouped_last_path();
+ const int want = old ? 0 : (expect_new ? 1 : 0);
+ if (path != want) {
+ std::printf(" %-44s forced %s: launched %s kernels, expected %s\n", name, old ? "previous" : "new",
+ path == 1 ? "the new" : path == 0 ? "the previous" : "no", want ? "the new" : "the previous");
+ ++g_fail;
+ }
+ /*
+ 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.
+ */
+ ck(0, name);
+ ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
+ name);
+ Run& x = r[old ? 0 : 1];
+ x.out = down(d_out, out_floats);
+ x.scratch = down((const uint8_t*) s.p, (size_t) s.bytes);
+ }
+ k::moe_grouped_select_old(-1);
+ const uint64_t gu = s.gu_bytes(), q8 = s.q8_bytes();
+ size_t diff_out = 0, diff_gu = 0, diff_q8 = 0, diff_hs = 0;
+ for (size_t i = 0; i < out_floats; ++i)
+ diff_out += std::memcmp(&r[0].out[i], &r[1].out[i], 4) != 0;
+ for (size_t i = 0; i < (size_t) s.bytes; ++i) {
+ if (r[0].scratch[i] == r[1].scratch[i]) continue;
+ if (i < gu) ++diff_gu;
+ else if (i < gu + q8) ++diff_q8;
+ else ++diff_hs;
+ }
+ const bool ok = diff_out + diff_gu + diff_q8 + diff_hs == 0;
+ std::printf(" %-44s %s", name, ok ? "bitwise identical" : "DIFFERS");
+ if (!ok)
+ std::printf(" (out %zu floats, gate/up %zu B, intermediate %zu B, its scales %zu B)", diff_out, diff_gu,
+ diff_q8, diff_hs);
+ std::printf("\n");
+ if (!ok) ++g_fail;
+ if (keep) *keep = std::move(r[1]);
+ return ok;
+}
+
+// The host reference on a finished run: every up row (the second half of gate/up, which the swiglu leaves alone)
+// against the activation row it read, and every written down row against the intermediate the run produced.
+struct Entry {
+ const uint8_t* blob; // host copy of the entry's blob
+ int tok; // activation row it reads
+ int dst; // output row it writes
+};
+void reference(const char* name, const Run& r, const Scratch& s, const std::vector<Entry>& ent,
+ const std::vector<uint8_t>& x, const std::vector<float>* xs) {
+ const float* gu = (const float*) r.scratch.data();
+ const uint8_t* hq = r.scratch.data() + s.gu_bytes();
+ const float* hs = (const float*) (r.scratch.data() + s.gu_bytes() + s.q8_bytes());
+ long checked = 0, bad = 0;
+ double worst = 0.0;
+ for (size_t e = 0; e < ent.size(); ++e) {
+ const uint8_t* b = ent[e].blob;
+ const uint8_t* xrow = x.data() + (size_t) ent[e].tok * XROW;
+ const float* xsr = xs ? xs->data() + (size_t) ent[e].tok * NCH_GU : nullptr;
+ for (int rr = 0; rr < FF; rr += 7) { // up row rr = row-slot 2rr + 1
+ double mag;
+ const double ref = row_ref(b + (size_t) (2 * rr + 1) * ROW_GU, b + O_GU_SCALES + (size_t) (2 * rr + 1) * SC_GU * 2,
+ xrow, xsr, NCH_GU, &mag);
+ const float got = gu[(size_t) s.cap * FF + e * FF + (size_t) rr];
+ ++checked;
+ if (!close_to(got, ref, mag)) ++bad;
+ if (mag > 0) worst = std::max(worst, std::fabs((double) got - ref) / mag);
+ }
+ const uint8_t* hrow = hq + e * (size_t) NCH_D * 34;
+ const float* hsr = xs ? hs + e * (size_t) NCH_D : nullptr;
+ for (int rr = 0; rr < H; rr += 13) {
+ double mag;
+ const double ref = row_ref(b + O_D_CODES + (size_t) rr * ROW_D, b + O_D_SCALES + (size_t) rr * SC_D * 2,
+ hrow, hsr, NCH_D, &mag);
+ const float got = r.out[(size_t) ent[e].dst * H + (size_t) rr];
+ ++checked;
+ if (!close_to(got, ref, mag)) ++bad;
+ if (mag > 0) worst = std::max(worst, std::fabs((double) got - ref) / mag);
+ }
+ }
+ std::printf(" %-44s host reference: %ld rows, %ld outside tolerance, worst %.2e of sum|term|\n", name, checked,
+ bad, worst);
+ if (bad || checked == 0) ++g_fail;
+}
+
+struct Fixture {
+ int nb = 0;
+ std::vector<uint8_t> h; // nb blobs
+ uint8_t* d = nullptr;
+ const uint8_t* hb(int i) const { return h.data() + (size_t) i * BLOB; }
+};
+
+Fixture make_blobs(int nb, std::mt19937& rng) {
+ Fixture f;
+ f.nb = nb;
+ f.h.resize((size_t) nb * BLOB);
+ for (int i = 0; i < nb; ++i) fill_blob(f.h.data() + (size_t) i * BLOB, rng);
+ f.d = dalloc<uint8_t>((size_t) nb * BLOB);
+ up(f.d, f.h);
+ return f;
+}
+
+Scratch make_scratch(int64_t cap) {
+ Scratch s;
+ s.cap = cap;
+ s.bytes = k::moe_hit_grouped_scratch_bytes(cap, H, FF);
+ s.p = dalloc<uint8_t>(s.bytes);
+ return s;
+}
+
+// ---------------------------------------------------------------- the checks
+void check_all() {
+ std::mt19937 rng(20260928);
+ const Fixture fx = make_blobs(12, rng);
+ constexpr int K = 10;
+
+ // Activations for up to 8 tokens, device copies with and without the fp32 scales.
+ std::vector<uint8_t> x;
+ std::vector<float> xs;
+ fill_x(x, xs, 8, rng);
+ uint8_t* d_x = dalloc<uint8_t>(x.size());
+ float* d_xs = dalloc<float>(xs.size());
+ up(d_x, x);
+ up(d_xs, xs);
+
+ // ---- 1. moe_hit_grouped_s2: 9 hits of 10 routed rows, slots and destinations shuffled
+ {
+ const int n_hits = 9;
+ std::vector<int32_t> slot(n_hits), dst(K);
+ for (int i = 0; i < n_hits; ++i) slot[i] = (int32_t) ((i * 5 + 3) % fx.nb);
+ std::iota(dst.begin(), dst.end(), 0);
+ std::shuffle(dst.begin(), dst.end(), rng);
+ dst.resize(n_hits);
+ int32_t* d_slot = dalloc<int32_t>(n_hits);
+ int32_t* d_dst = dalloc<int32_t>(n_hits);
+ up(d_slot, slot);
+ up(d_dst, dst);
+ const Scratch s = make_scratch(n_hits);
+ float* d_out = dalloc<float>((size_t) K * H);
+ std::vector<Entry> ent;
+ for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]});
+ for (int scaled = 1; scaled >= 0; --scaled) {
+ Run r;
+ const std::string name = std::string("moe_hit_grouped_s2") + (scaled ? " (fp32 scales)" : " (fp16 d)");
+ twice(name.c_str(), d_out, (size_t) K * H, s, [&] {
+ k::moe_hit_grouped_s2(fx.d, d_slot, d_dst, n_hits, (int64_t) BLOB, d_x, s.p, d_out, nullptr,
+ scaled ? d_xs : nullptr);
+ }, &r);
+ reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr);
+ }
+ }
+
+ // ---- 2. moe_hit_grouped_s2_dev: capacity 10, device count 7
+ {
+ const int cap = 10, count = 7;
+ std::vector<int32_t> slot(cap), dst(cap);
+ for (int i = 0; i < cap; ++i) slot[i] = (int32_t) ((i * 7 + 1) % fx.nb);
+ std::iota(dst.begin(), dst.end(), 0);
+ std::shuffle(dst.begin(), dst.end(), rng);
+ int32_t* d_slot = dalloc<int32_t>(cap);
+ int32_t* d_dst = dalloc<int32_t>(cap);
+ int32_t* d_count = dalloc<int32_t>(1);
+ up(d_slot, slot);
+ up(d_dst, dst);
+ up(d_count, std::vector<int32_t>{count});
+ const Scratch s = make_scratch(cap);
+ float* d_out = dalloc<float>((size_t) K * H);
+ std::vector<Entry> ent;
+ for (int i = 0; i < count; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]});
+ Run r;
+ twice("moe_hit_grouped_s2_dev (count 7 of 10)", d_out, (size_t) K * H, s, [&] {
+ k::moe_hit_grouped_s2_dev(fx.d, d_slot, d_dst, d_count, cap, (int64_t) BLOB, d_x, s.p, d_out, nullptr,
+ d_xs);
+ }, &r);
+ reference("moe_hit_grouped_s2_dev (count 7 of 10)", r, s, ent, x, &xs);
+ // the rows of the hits past the count keep the sentinel
+ long touched = 0;
+ for (int i = count; i < cap; ++i)
+ for (int c = 0; c < H; ++c) {
+ uint32_t v;
+ std::memcpy(&v, &r.out[(size_t) dst[i] * H + c], 4);
+ touched += v != 0xA5A5A5A5u;
+ }
+ std::printf(" %-44s rows past the count written: %ld\n", "moe_hit_grouped_s2_dev (count 7 of 10)", touched);
+ if (touched) ++g_fail;
+ }
+
+ // ---- 3. moe_hit_grouped_s2_multi: 4 tokens x 10 routed entries, 29 hits
+ {
+ const int T = 4, n = T * K, count = 29;
+ std::vector<int32_t> ent_ids(n);
+ std::iota(ent_ids.begin(), ent_ids.end(), 0);
+ std::shuffle(ent_ids.begin(), ent_ids.end(), rng);
+ std::vector<int32_t> slot(n), dst(n);
+ for (int i = 0; i < n; ++i) {
+ dst[i] = ent_ids[i];
+ slot[i] = (int32_t) (rng() % fx.nb);
+ }
+ std::sort(dst.begin(), dst.begin() + count); // hit order is routing order, as `moe_hit_select_multi` makes it
+ int32_t* d_slot = dalloc<int32_t>(n);
+ int32_t* d_dst = dalloc<int32_t>(n);
+ int32_t* d_count = dalloc<int32_t>(1);
+ up(d_slot, slot);
+ up(d_dst, dst);
+ up(d_count, std::vector<int32_t>{count});
+ const Scratch s = make_scratch(n);
+ float* d_out = dalloc<float>((size_t) n * H);
+ std::vector<Entry> ent;
+ for (int i = 0; i < count; ++i) ent.push_back({fx.hb(slot[i]), dst[i] / K, dst[i]});
+ Run r;
+ twice("moe_hit_grouped_s2_multi (4 tokens, 29 hits)", d_out, (size_t) n * H, s, [&] {
+ k::moe_hit_grouped_s2_multi(fx.d, d_slot, d_dst, d_count, n, (int64_t) BLOB, d_x, d_xs, K, s.p, d_out,
+ nullptr);
+ }, &r);
+ reference("moe_hit_grouped_s2_multi (4 tokens, 29 hits)", r, s, ent, x, &xs);
+ }
+
+ // ---- 4. moe_grouped_s2: 8 tokens x 10 entries in groups of 1..8, one group on a mapped host blob
+ {
+ const int T = 8, n = T * K;
+ uint8_t* h_host = nullptr;
+ uint8_t* d_host = nullptr;
+ /*
+ DPCT1048: The original value cudaHostAllocMapped is not meaningful in
+ the migrated code and was removed or replaced with 0. You may need to
+ check the migrated code.
+ */
+ ck(DPCT_CHECK_ERROR(h_host = (uint8_t *)sycl::malloc_host(
+ BLOB, dpct::get_in_order_queue())),
+ "host blob");
+ std::memcpy(h_host, fx.hb(fx.nb - 1), BLOB);
+ ck(DPCT_CHECK_ERROR(*(void **)&d_host = (uint8_t *)h_host),
+ "host blob ptr");
+ // group sizes: 8, 1, 5, 2, 7, 3, 1, 6, 4, ... up to n entries
+ const int sizes[] = {8, 1, 5, 2, 7, 3, 1, 6, 4, 8, 1, 2, 3, 4, 5, 6, 7, 1, 1, 5};
+ std::vector<int32_t> order(n); // the output rows, in group order
+ std::iota(order.begin(), order.end(), 0);
+ std::shuffle(order.begin(), order.end(), rng);
+ std::vector<unsigned long long> gptr;
+ std::vector<int32_t> gstart{0}, edst, etok;
+ std::vector<Entry> ent;
+ int at = 0, gi = 0;
+ while (at < n) {
+ const int sz = std::min(sizes[gi % 20], n - at);
+ const bool host = gi == 3;
+ const int b = gi % (fx.nb - 1);
+ gptr.push_back((unsigned long long) (host ? d_host : fx.d + (size_t) b * BLOB));
+ for (int j = 0; j < sz; ++j, ++at) {
+ edst.push_back(order[at]);
+ etok.push_back(order[at] / K);
+ ent.push_back({host ? h_host : fx.hb(b), order[at] / K, order[at]});
+ }
+ gstart.push_back(at);
+ ++gi;
+ }
+ const int n_groups = gi, cap_groups = n_groups + 3;
+ gstart.resize((size_t) cap_groups + 1, at);
+ gptr.resize((size_t) cap_groups, gptr[0]);
+ unsigned long long* d_gptr = dalloc<unsigned long long>(gptr.size());
+ int32_t* d_gstart = dalloc<int32_t>(gstart.size());
+ int32_t* d_ng = dalloc<int32_t>(1);
+ int32_t* d_edst = dalloc<int32_t>(n);
+ int32_t* d_etok = dalloc<int32_t>(n);
+ up(d_gptr, gptr);
+ up(d_gstart, gstart);
+ up(d_ng, std::vector<int32_t>{n_groups});
+ up(d_edst, edst);
+ up(d_etok, etok);
+ const Scratch s = make_scratch(n);
+ float* d_out = dalloc<float>((size_t) n * H);
+ for (int scaled = 1; scaled >= 0; --scaled) {
+ Run r;
+ const std::string name = std::string("moe_grouped_s2 (") + std::to_string(n_groups) + " groups" +
+ (scaled ? ", fp32 scales)" : ", fp16 d)");
+ twice(name.c_str(), d_out, (size_t) n * H, s, [&] {
+ k::moe_grouped_s2(d_gptr, d_gstart, d_ng, d_edst, d_etok, cap_groups, n, d_x, scaled ? d_xs : nullptr,
+ s.p, d_out, nullptr);
+ }, &r);
+ reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr);
+ }
+ ck(DPCT_CHECK_ERROR(sycl::free(h_host, dpct::get_in_order_queue())),
+ "free host blob");
+ }
+
+ // ---- 5. moe_group_resident + moe_grouped_s2: the MTP layer (experts resident at base + id * BLOB)
+ {
+ const int T = 5, n = T * K;
+ std::vector<int32_t> ids(n);
+ for (int t = 0; t < T; ++t) { // distinct within a token, shared across tokens
+ std::vector<int32_t> pick(fx.nb);
+ std::iota(pick.begin(), pick.end(), 0);
+ std::shuffle(pick.begin(), pick.end(), rng);
+ for (int j = 0; j < K; ++j) ids[(size_t) t * K + j] = pick[j];
+ }
+ int32_t* d_ids = dalloc<int32_t>(n);
+ up(d_ids, ids);
+ unsigned long long* d_gptr = dalloc<unsigned long long>(n);
+ int32_t* d_gstart = dalloc<int32_t>(n + 1);
+ int32_t* d_counts = dalloc<int32_t>(2);
+ int32_t* d_edst = dalloc<int32_t>(n);
+ int32_t* d_etok = dalloc<int32_t>(n);
+ k::moe_group_resident(d_ids, n, K, fx.d, (int64_t) BLOB, d_gptr, d_gstart, d_counts, d_edst, d_etok, nullptr);
+ ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
+ "group_resident");
+ const std::vector<int32_t> edst = down(d_edst, n), etok = down(d_etok, n);
+ std::vector<Entry> ent(n); // entry e: dst = routing index, blob = its expert
+ for (int e = 0; e < n; ++e) ent[e] = {fx.hb(ids[(size_t) edst[e]]), etok[e], edst[e]};
+ const Scratch s = make_scratch(n);
+ float* d_out = dalloc<float>((size_t) n * H);
+ for (int scaled = 1; scaled >= 0; --scaled) {
+ Run r;
+ const std::string name = std::string("moe_group_resident + moe_grouped_s2") + (scaled ? " (fp32)" : " (fp16)");
+ twice(name.c_str(), d_out, (size_t) n * H, s, [&] {
+ k::moe_grouped_s2(d_gptr, d_gstart, d_counts, d_edst, d_etok, n, n, d_x, scaled ? d_xs : nullptr, s.p,
+ d_out, nullptr);
+ }, &r);
+ reference(name.c_str(), r, s, ent, x, scaled ? &xs : nullptr);
+ }
+ }
+
+ // ---- 6. a 2-byte aligned activation row: the new path must decline and the previous kernels run
+ {
+ uint8_t* d_x2 = dalloc<uint8_t>(x.size() + 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_in_order_queue().memcpy(d_x2 + 2, x.data(), XROW).wait()),
+ "x2");
+ const int n_hits = 3;
+ std::vector<int32_t> slot{2, 5, 7}, dst{4, 0, 9};
+ int32_t* d_slot = dalloc<int32_t>(n_hits);
+ int32_t* d_dst = dalloc<int32_t>(n_hits);
+ up(d_slot, slot);
+ up(d_dst, dst);
+ const Scratch s = make_scratch(n_hits);
+ float* d_out = dalloc<float>((size_t) K * H);
+ std::vector<Entry> ent;
+ for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]});
+ Run r;
+ twice("moe_hit_grouped_s2 (2-byte aligned x)", d_out, (size_t) K * H, s, [&] {
+ k::moe_hit_grouped_s2(fx.d, d_slot, d_dst, n_hits, (int64_t) BLOB, d_x2 + 2, s.p, d_out, nullptr, d_xs);
+ }, &r, /*expect_new=*/false);
+ reference("moe_hit_grouped_s2 (2-byte aligned x)", r, s, ent, x, &xs);
+ }
+
+ // ---- 7. slots BLOB + 4 bytes apart, and 8. an arena at an address that is 4 mod 8: per-hit fallback
+ {
+ constexpr size_t STRIDE = BLOB + 4;
+ static_assert(STRIDE % 8 != 0, "the stride must defeat the uint2 code loads");
+ const int nb = 8;
+ uint8_t* d_arena = dalloc<uint8_t>((size_t) nb * STRIDE + 8);
+ const int n_hits = 4;
+ std::vector<int32_t> slot{6, 1, 3, 0}, dst{2, 7, 5, 8};
+ int32_t* d_slot = dalloc<int32_t>(n_hits);
+ int32_t* d_dst = dalloc<int32_t>(n_hits);
+ up(d_slot, slot);
+ up(d_dst, dst);
+ const Scratch s = make_scratch(n_hits);
+ float* d_out = dalloc<float>((size_t) K * H);
+ std::vector<Entry> ent;
+ for (int i = 0; i < n_hits; ++i) ent.push_back({fx.hb(slot[i]), 0, dst[i]});
+ // One allocation for both layouts: the BLOB + 4 strided copies first, then the same blobs BLOB apart from
+ // `d_arena + 4` over them.
+ for (int i = 0; i < nb; ++i)
+ /*
+ 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_in_order_queue().memcpy(
+ d_arena + (size_t)i * STRIDE, fx.hb(i), BLOB).wait()),
+ "arena");
+ {
+ Run r;
+ twice("moe_hit_grouped_s2 (slot stride BLOB + 4)", d_out, (size_t) K * H, s, [&] {
+ k::moe_hit_grouped_s2(d_arena, d_slot, d_dst, n_hits, (int64_t) STRIDE, d_x, s.p, d_out, nullptr,
+ d_xs);
+ }, &r, /*expect_new=*/false);
+ reference("moe_hit_grouped_s2 (slot stride BLOB + 4)", r, s, ent, x, &xs);
+ }
+ for (int i = 0; i < nb; ++i)
+ /*
+ 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_in_order_queue().memcpy(
+ d_arena + 4 + (size_t)i * BLOB, fx.hb(i), BLOB).wait()),
+ "arena");
+ {
+ Run r;
+ twice("moe_hit_grouped_s2 (arena 4 mod 8)", d_out, (size_t) K * H, s, [&] {
+ k::moe_hit_grouped_s2(d_arena + 4, d_slot, d_dst, n_hits, (int64_t) BLOB, d_x, s.p, d_out, nullptr,
+ d_xs);
+ }, &r, /*expect_new=*/false);
+ reference("moe_hit_grouped_s2 (arena 4 mod 8)", r, s, ent, x, &xs);
+ }
+ }
+}
+
+// ---------------------------------------------------------------- --bench
+// Engine-like shapes with the blobs cycled through a set larger than the L2, so each call reads its codes from
+// DRAM as the engine's do. Reports microseconds per call and the codes' effective bandwidth.
+void bench() {
+ int dev = 0;
+ dpct::device_info prop{};
+ ck(DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()), "dev");
+ ck(DPCT_CHECK_ERROR(dpct::get_device(dev).get_device_info(prop)), "props");
+ /*
+ DPCT1051: SYCL does not support a device property functionally
+ compatible with l2CacheSize. It was migrated to global_mem_cache_size. You
+ may need to adjust the value of global_mem_cache_size for the specific
+ device.
+ */
+ const int nb = std::max(
+ 48, (int)(3ull * (size_t)prop.get_global_mem_cache_size() / BLOB) + 8);
+ /*
+ DPCT1051: SYCL does not support a device property functionally
+ compatible with l2CacheSize. It was migrated to global_mem_cache_size. You
+ may need to adjust the value of global_mem_cache_size for the specific
+ device.
+ */
+ std::printf("bench: %s, L2 %d MB, %d blobs (%.0f MB) cycled\n",
+ prop.get_name(), prop.get_global_mem_cache_size() >> 20, nb,
+ nb * (double)BLOB / 1e6);
+ std::mt19937 rng(7);
+ Fixture fx;
+ fx.nb = nb;
+ fx.d = dalloc<uint8_t>((size_t) nb * BLOB);
+ {
+ std::vector<uint8_t> b(BLOB);
+ for (int i = 0; i < nb; ++i) {
+ fill_blob(b.data(), 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.
+ */
+ ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
+ fx.d + (size_t)i * BLOB, b.data(), BLOB).wait()),
+ "blob");
+ }
+ }
+ std::vector<uint8_t> x;
+ std::vector<float> xs;
+ fill_x(x, xs, 8, rng);
+ uint8_t* d_x = dalloc<uint8_t>(x.size());
+ float* d_xs = dalloc<float>(xs.size());
+ up(d_x, x);
+ up(d_xs, xs);
+ constexpr int K = 10, ITERS = 200, SETS = 16;
+ dpct::event_ptr e0, e1;
+ ck(DPCT_CHECK_ERROR(e0 = new sycl::event()), "ev");
+ ck(DPCT_CHECK_ERROR(e1 = new sycl::event()), "ev");
+ auto time = [&](const std::function<void(int)> &call) {
+ try {
+ call(0);
+ ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
+ "warm");
+ /*
+ 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)), "rec");
+ for (int i = 0; i < ITERS; ++i) call(i % SETS);
+ /*
+ 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)), "rec");
+ ck(DPCT_CHECK_ERROR(e1->wait_and_throw()), "sync");
+ 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 1000.0 * ms / ITERS;
+ }
+ catch (sycl::exception const &exc) {
+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__
+ << ", line:" << __LINE__ << std::endl;
+ std::exit(1);
+ }
+ };
+ auto ab = [&](const char* name, double blobs_per_call, const std::function<void(int)>& call) {
+ double us[2];
+ for (int old = 1; old >= 0; --old) {
+ k::moe_grouped_select_old(old);
+ us[old ? 0 : 1] = time(call);
+ }
+ k::moe_grouped_select_old(-1);
+ const double gb = blobs_per_call * (double) BLOB / 1e3; // bytes / us = MB/s ... / 1e3 -> GB/s
+ std::printf(" %-40s previous %8.1f us (%6.0f GB/s) new %8.1f us (%6.0f GB/s) x%.2f\n", name, us[0],
+ gb / us[0], us[1], gb / us[1], us[0] / us[1]);
+ };
+
+ // per-hit path, decode: 9 hits of 10 (5090-like residency), 5 of 10, and the low-residency 1-3 hits, where the
+ // new kernels' grid (80 gate/up blocks per hit) is below one block per SM - see `STRATA_GROUPED_PAIR_MIN_HITS`
+ for (const int n_hits : {9, 5, 3, 2, 1}) {
+ std::vector<int32_t> slots((size_t) SETS * n_hits), dst(K);
+ for (auto& v : slots) v = (int32_t) (rng() % nb);
+ std::iota(dst.begin(), dst.end(), 0);
+ int32_t* d_slots = dalloc<int32_t>(slots.size());
+ int32_t* d_dst = dalloc<int32_t>(K);
+ up(d_slots, slots);
+ up(d_dst, dst);
+ const Scratch s = make_scratch(n_hits);
+ float* d_out = dalloc<float>((size_t) K * H);
+ const std::string name = "moe_hit_grouped_s2, " + std::to_string(n_hits) + " hits";
+ ab(name.c_str(), n_hits, [&](int set) {
+ k::moe_hit_grouped_s2(fx.d, d_slots + (size_t) set * n_hits, d_dst, n_hits, (int64_t) BLOB, d_x, s.p,
+ d_out, nullptr, d_xs);
+ });
+ }
+ // grouped path, verify window: T tokens x 10, routed with `share` = the chance an entry reuses an expert already
+ // routed by an earlier token of the window
+ struct Shape { int T; double share; const char* what; };
+ for (const Shape sh : {Shape{4, 0.0, "4 tokens, no sharing"}, Shape{4, 0.3, "4 tokens, 30% shared"},
+ Shape{8, 0.3, "8 tokens, 30% shared"}, Shape{8, 1.0, "8 tokens, all shared (ne 8)"}}) {
+ const int n = sh.T * K;
+ std::vector<unsigned long long> gptr((size_t) SETS * n);
+ std::vector<int32_t> gstart((size_t) SETS * (n + 1)), ng(SETS), edst((size_t) SETS * n), etok((size_t) SETS * n);
+ double groups = 0;
+ std::uniform_real_distribution<double> u(0, 1);
+ for (int set = 0; set < SETS; ++set) {
+ std::vector<std::vector<int>> g; // per group: routing indices
+ std::vector<int> gexp; // per group: blob
+ for (int t = 0; t < sh.T; ++t) {
+ std::vector<char> used(g.size(), 0);
+ for (int j = 0; j < K; ++j) {
+ int pick = -1;
+ if (t > 0 && u(rng) < sh.share)
+ for (size_t q = 0; q < g.size(); ++q)
+ if (!used[q] && (int) g[q].size() < 8) { pick = (int) q; break; }
+ if (pick < 0) {
+ pick = (int) g.size();
+ g.emplace_back();
+ gexp.push_back((int) (rng() % nb));
+ used.push_back(0);
+ }
+ used[(size_t) pick] = 1;
+ g[(size_t) pick].push_back(t * K + j);
+ }
+ }
+ int at = 0;
+ for (size_t q = 0; q < g.size(); ++q) {
+ gptr[(size_t) set * n + q] = (unsigned long long) (fx.d + (size_t) gexp[q] * BLOB);
+ gstart[(size_t) set * (n + 1) + q] = at;
+ for (int e : g[q]) {
+ edst[(size_t) set * n + at] = e;
+ etok[(size_t) set * n + at] = e / K;
+ ++at;
+ }
+ }
+ for (size_t q = g.size(); q <= (size_t) n; ++q) gstart[(size_t) set * (n + 1) + q] = at;
+ ng[set] = (int32_t) g.size();
+ groups += (double) g.size() / SETS;
+ }
+ unsigned long long* d_gptr = dalloc<unsigned long long>(gptr.size());
+ int32_t* d_gstart = dalloc<int32_t>(gstart.size());
+ int32_t* d_ng = dalloc<int32_t>(SETS);
+ int32_t* d_edst = dalloc<int32_t>(edst.size());
+ int32_t* d_etok = dalloc<int32_t>(etok.size());
+ up(d_gptr, gptr);
+ up(d_gstart, gstart);
+ up(d_ng, ng);
+ up(d_edst, edst);
+ up(d_etok, etok);
+ const Scratch s = make_scratch(n);
+ float* d_out = dalloc<float>((size_t) n * H);
+ char name[96];
+ std::snprintf(name, sizeof name, "moe_grouped_s2, %s (%.0f groups)", sh.what, groups);
+ ab(name, groups, [&](int set) {
+ k::moe_grouped_s2(d_gptr + (size_t) set * n, d_gstart + (size_t) set * (n + 1), d_ng + set,
+ d_edst + (size_t) set * n, d_etok + (size_t) set * n, n, n, d_x, d_xs, s.p, d_out,
+ nullptr);
+ });
+ }
+}
+} // namespace
+
+int main(int argc, char** argv) {
+ bool do_bench = false;
+ for (int i = 1; i < argc; ++i) {
+ if (std::strcmp(argv[i], "--bench") == 0) do_bench = true;
+ else if (std::strcmp(argv[i], "--selftest") != 0) {
+ std::fprintf(stderr, "usage: s2_expert_grouped_parity [--selftest] [--bench]\n");
+ return 2;
+ }
+ }
+ std::printf("s2_expert_grouped_parity: new expert kernels vs the previous ones, bitwise\n");
+ check_all();
+ if (do_bench) bench();
+ std::printf("s2_expert_grouped_parity: %d failures\n%s\n", g_fail, g_fail ? "FAIL" : "PASS");
+ return g_fail ? 1 : 0;
+}
diff --git a/sycl/src/prefill/gemm.dp.cpp b/sycl/src/prefill/gemm.dp.cpp
index 3a683a7a8..50d8541a5 100644
--- a/sycl/src/prefill/gemm.dp.cpp
+++ b/sycl/src/prefill/gemm.dp.cpp
@@ -45,6 +45,13 @@ void ck(int s, const char *what) {
}
}
+// A setup call whose failure the engine survives (the handle keeps its defaults), as before #240 - but said.
+void note(int s, const char *what) {
+ if (s != 0) std::fprintf(
+ stderr, "prefill gemm: %s: cuBLAS status %d (continuing)\n", what,
+ (int)s);
+}
+
#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
struct HipLtCallKey {
strata::prefill::hipblaslt::InputType type;
@@ -289,19 +296,24 @@ bool Gemm::init_external(void *stream, uint16_t *scratch, int64_t scratch_elems,
void *workspace, size_t ws_bytes,
std::string &err) try {
dpct::blas::descriptor_ptr h = nullptr;
- if (DPCT_CHECK_ERROR(h = new dpct::blas::descriptor()) != 0) {
- err = "prefill gemm: cublasCreate failed"; return false;
+ if (const int s = DPCT_CHECK_ERROR(h = new dpct::blas::descriptor());
+ s != 0) {
+ err = "prefill gemm: cublasCreate: cuBLAS status " + std::to_string((int) s);
+ return false;
}
handle_ = h;
stream_ = stream;
external_ = true;
- h->set_queue(strata::q_of(stream));
+ note(DPCT_CHECK_ERROR(h->set_queue(strata::q_of(stream))),
+ "cublasSetStream");
workspace_ = workspace;
/*
- DPCT1026: The call to cublasSetWorkspace was removed because this
- functionality is redundant in SYCL.
+ DPCT1027: The call to cublasSetWorkspace was replaced with 0 because
+ this functionality is redundant in SYCL.
*/
- h->set_math_mode(dpct::blas::math_mode::mm_default);
+ note(0, "cublasSetWorkspace");
+ note(DPCT_CHECK_ERROR(h->set_math_mode(dpct::blas::math_mode::mm_default)),
+ "cublasSetMathMode");
scratch_ = scratch;
scratch_elems_ = scratch_elems;
#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
@@ -333,33 +345,72 @@ void Gemm::rebind(uint16_t* scratch, int64_t scratch_elems, void* workspace, siz
}
bool Gemm::init(void *stream, int64_t scratch_elems, std::string &err) try {
+ // #240: every failure names the call and the real status, so "no VRAM" can be told from a broken install
dpct::blas::descriptor_ptr h = nullptr;
- if (DPCT_CHECK_ERROR(h = new dpct::blas::descriptor()) != 0) {
- err = "prefill gemm: cublasCreate failed"; return false;
+ if (const int s = DPCT_CHECK_ERROR(h = new dpct::blas::descriptor());
+ s != 0) {
+ err = "prefill gemm: cublasCreate: cuBLAS status " + std::to_string((int) s);
+ return false;
}
handle_ = h;
stream_ = stream;
- h->set_queue(strata::q_of(stream));
+ note(DPCT_CHECK_ERROR(h->set_queue(strata::q_of(stream))),
+ "cublasSetStream");
// A fixed workspace so the handle never allocates on the way (and graphs could capture it later).
const size_t ws = 32u << 20;
- if (DPCT_CHECK_ERROR(workspace_ = (void *)sycl::malloc_device(
- ws, dpct::get_in_order_queue())) != 0) {
- err = "prefill gemm: workspace"; return false;
+ /*
+ DPCT1000: Error handling if-stmt was detected but could not be
+ rewritten.
+ */
+ if (const dpct::err0 e =
+ DPCT_CHECK_ERROR(workspace_ = (void *)sycl::malloc_device(
+ ws, dpct::get_in_order_queue()));
+ e != 0) {
+ /*
+ DPCT1009: SYCL reports errors using exceptions and does not use
+ error codes. Please replace the "get_error_string_dummy(...)" with a
+ real error-handling function.
+ */
+ /*
+ DPCT1001: The statement could not be removed.
+ */
+ err = std::string("prefill gemm: workspace of 32 MiB: ") +
+ dpct::get_error_string_dummy(e);
+ return false;
}
/*
- DPCT1026: The call to cublasSetWorkspace was removed because this
- functionality is redundant in SYCL.
+ DPCT1027: The call to cublasSetWorkspace was replaced with 0 because
+ this functionality is redundant in SYCL.
*/
- h->set_math_mode(dpct::blas::math_mode::mm_default);
+ note(0, "cublasSetWorkspace");
+ note(DPCT_CHECK_ERROR(h->set_math_mode(dpct::blas::math_mode::mm_default)),
+ "cublasSetMathMode");
#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
hipblaslt_state_ = create_hipblaslt_state(workspace_, ws).release();
#endif
- if (scratch_elems > 0 &&
- DPCT_CHECK_ERROR(
- scratch_ = (uint16_t *)sycl::malloc_device(
- (size_t)scratch_elems * 2, dpct::get_in_order_queue())) != 0) {
- err = "prefill gemm: dequant scratch of " + std::to_string(scratch_elems * 2 >> 20) + " MiB";
- return false;
+ if (scratch_elems > 0) {
+ /*
+ DPCT1000: Error handling if-stmt was detected but could not be
+ rewritten.
+ */
+ if (const dpct::err0 e = DPCT_CHECK_ERROR(
+ scratch_ = (uint16_t *)sycl::malloc_device(
+ (size_t)scratch_elems * 2, dpct::get_in_order_queue()));
+ e != 0) {
+ /*
+ DPCT1001: The statement could not be removed.
+ */
+ err = "prefill gemm: dequant scratch of " +
+ std::to_string(scratch_elems * 2 >> 20) + " MiB: " +
+ /*
+ 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.
+ */
+ dpct::get_error_string_dummy(e);
+ return false;
+ }
}
scratch_elems_ = scratch_elems;
return true;
diff --git a/sycl/src/prefill/kernels.dp.cpp b/sycl/src/prefill/kernels.dp.cpp
index cfafd1f10..88adbd50d 100644
--- a/sycl/src/prefill/kernels.dp.cpp
+++ b/sycl/src/prefill/kernels.dp.cpp
@@ -942,17 +942,21 @@ auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
}
__dpct_inline__ void rope_kernel(float *__restrict__ x, int64_t heads,
int64_t dim, int64_t ld, int64_t pos0,
- float theta_scale,
+ float theta_scale, float freq_scale,
+ float corr_low, float corr_high,
+ float ext_factor, float mscale,
const int32_t *__restrict__ mtab) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
const int64_t row = item_ct1.get_group(2); // t * heads + h
const int pair = item_ct1.get_local_id(2); // 0..31
const int64_t t = row / heads, h = row % heads;
float* p = x + t * ld + h * dim;
- const float theta =
+ const float theta_extrap =
(float)strata::kernels::mrope_pos(mtab, (int)(pos0 + t), pair) *
dpct::pow(theta_scale, (float)pair);
- const float c = sycl::cos((float)theta), s = sycl::sin((float)theta);
+ float c, s;
+ strata::kernels::rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale,
+ pair, c, s);
const float a = p[pair], b = p[pair + 32];
p[pair] = a * c - b * s;
p[pair + 32] = a * s + b * c;
@@ -1678,15 +1682,23 @@ void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld,
}
check("rms_rows");
}
-void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, float freq_base, void* stream) {
- const float theta_scale = powf(freq_base, -2.0f / 64.0f);
+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) {
+ // The engine validates the resolved config at startup with the same rule (generate.cpp), so this only
+ // fires for a caller that bypassed it; the prompt path has no error return here, so it stops the process.
+ if (const char* why = strata::kernels::rope_scaling_invalid(scaling)) {
+ std::fprintf(stderr, "prefill rope: invalid rope scaling: %s\n", why);
+ std::exit(1);
+ }
+ const float theta_scale = powf((float) scaling.freq_base, -2.0f / 64.0f);
+ const strata::kernels::RopeKernelArgs k = scaling.kernel_args(64); // none: the identity constants
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
strata::q_of(stream)
->submit([&](sycl::handler &cgh) {
- auto strata_kernels_mrope_table_ct6 =
+ auto strata_kernels_mrope_table_ct11 =
strata::kernels::mrope_table();
cgh.parallel_for<dpct_kernel_name<class rope_kernel_4d58b9>>(
@@ -1695,7 +1707,9 @@ void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t p
sycl::range(1, 1, 32)),
exp_props, [=](sycl::nd_item<3> item_ct1) {
rope_kernel(x, heads, dim, ld, pos0, theta_scale,
- strata_kernels_mrope_table_ct6);
+ k.freq_scale, k.corr_low, k.corr_high,
+ k.ext_factor, k.attn_factor,
+ strata_kernels_mrope_table_ct11);
});
});
}
diff --git a/sycl/src/prefill/prefill.cpp b/sycl/src/prefill/prefill.cpp
index 348167925..6fa9ae0db 100644
--- a/sycl/src/prefill/prefill.cpp
+++ b/sycl/src/prefill/prefill.cpp
@@ -71,12 +71,19 @@ constexpr int64_t N = 2560, HC = 4, D = N * HC, LR = 320, K = 10, NE = 512;
constexpr int64_t C = 10240, ZV = 6144, HV = 48;
// plan v0.3 P6: staging holds the largest blob of the pack (a native pack's blobs differ per layer)
inline int64_t MAXBLOB() { return (int64_t) strata::kernels::cpu::expert_layout().max_blob; }
-constexpr int STAGE = 8; // host->device expert staging ring (chunks below STREAM_ALL_MIN)
+constexpr int STAGE = 8; // host->device expert staging ring (chunks below stream_all_min())
// Step 3: from this chunk size on, every non-resident expert of every layer streams in a fixed order through a
// RING_MAX-slot ring (nearly all 512 are routed at such a chunk), so the copy engine keeps working through the
// attention halves instead of waiting for each layer's routing.
constexpr int RING_MAX = 512; // the arrays; the ring itself is ring_slots()
-constexpr int64_t STREAM_ALL_MIN = 2048;
+// The chunk size from which every expert streams: 1024 since 0.1.30 (was 2048). Measured on the 5070, Q2_0 / IQ2_XS,
+// fixed cache: 1,500-token prompts 621 -> 785 / 612 -> 735 tok/s, 2,000 727 -> 934 / 712 -> 892, 4,000 (its last
+// chunk) 779 -> 912 / 766 -> 844, the same output. Below ~1,000 tokens the output changed on Q2_0 (a smaller chunk
+// takes other kernels), so 1024 is the floor. STRATA_PREFILL_STREAM_MIN overrides (A/B).
+inline int64_t stream_all_min() {
+ static const int64_t v = [] { const char* e = std::getenv("STRATA_PREFILL_STREAM_MIN"); return e ? (int64_t) std::atoll(e) : (int64_t) 1024; }();
+ return v;
+}
double g_pinned_share = 1.0;
// The streamed ring: 384 slots when (nearly) every streamed expert is DMA'd from pinned RAM - measured on Q2_0,
// 8192-token chunks: 96 slots 1153 tok/s, 384 1294 (the next layer's experts arrive during its attention half) -
@@ -93,7 +100,7 @@ inline int ring_slots(size_t T) {
static const bool stream_all_ok = [] { const char* e = std::getenv("STRATA_PREFILL_STREAM_ALL"); return e && e[0] == '1'; }();
if (!stream_all_ok) return STAGE;
const int big = r < 16 ? 16 : r > RING_MAX ? RING_MAX : r;
- return (int64_t) T >= STREAM_ALL_MIN ? big : STAGE;
+ return (int64_t) T >= stream_all_min() ? big : STAGE;
}
constexpr int DQ = 2; // dequantized-expert ring (FP16 gate/up + down)
@@ -149,7 +156,12 @@ struct Stager {
// DMAs of the unpinned experts' blobs
int kRing = 16;
// SYCL port: a job may name the expert instead of a host pointer - the thread reads it from the GGUF itself
- struct Job { const uint8_t* src; size_t bytes; int64_t layer = -1; int64_t expert = -1; const core::GgufExpertSource* gsrc = nullptr; };
+ // (`gsrc`). `from` set: the blob is copied by the source itself (CS-T: a GGUF read in place assembles it from its
+ // three role slices; a pointer to it would not live as long as the queue)
+ struct Job {
+ const uint8_t* src; size_t bytes; core::ExpertSource* from = nullptr; int32_t l = 0, e = 0;
+ const core::GgufExpertSource* gsrc = nullptr;
+ };
std::vector<uint8_t*> buf;
std::vector<char> pinned;
std::vector<std::vector<uint8_t>> pageable; // the fallback when no more RAM can be pinned
@@ -232,14 +244,17 @@ struct Stager {
while (issued.load(std::memory_order_acquire) <= j - kRing) std::this_thread::yield();
dma_done[b]->wait_and_throw();
}
- if (jobs[(size_t) j].gsrc != nullptr) {
- if (!jobs[(size_t) j].gsrc->read_into(jobs[(size_t) j].layer, jobs[(size_t) j].expert, buf[b], jobs[(size_t) j].bytes)) {
- std::fprintf(stderr, "prefill: reading expert %lld of layer %lld from the GGUF failed\n",
- (long long) jobs[(size_t) j].expert, (long long) jobs[(size_t) j].layer);
- std::memset(buf[b], 0, jobs[(size_t) j].bytes);
+ const Job& jb = jobs[(size_t) j];
+ if (jb.gsrc != nullptr) {
+ if (!jb.gsrc->read_into(jb.l, jb.e, buf[b], jb.bytes)) {
+ std::fprintf(stderr, "prefill: reading expert %d of layer %d from the GGUF failed\n", jb.e, jb.l);
+ std::memset(buf[b], 0, jb.bytes);
}
- } else {
- std::memcpy(buf[b], jobs[(size_t) j].src, jobs[(size_t) j].bytes);
+ } else if (jb.from == nullptr) {
+ std::memcpy(buf[b], jb.src, jb.bytes);
+ } else if (!jb.from->copy_blob(jb.l, jb.e, buf[b])) {
+ std::fprintf(stderr, "prefill: the expert source could not copy expert %d of layer %d\n", jb.e, jb.l);
+ std::abort();
}
ready[(size_t) j].store(1, std::memory_order_release);
active.fetch_sub(1, std::memory_order_acq_rel);
@@ -379,7 +394,7 @@ namespace {
bool stage_own() { static const bool v = std::getenv("STRATA_KV_STAGE_OWN") != nullptr; return v; }
void take_stage(Alloc& o_borrowed, const core::SessionState& ss, const strata::kernels::QsaShapes& s,
strata::kernels::KvHostPools& st, bool& ok) {
- const core::QsaState& q0 = ss.qsa_states[0];
+ const core::QsaState& q0 = ss.qsa_states[ss.qsa_primary()];
if (q0.kv_mode != 1) return;
if (stage_own() && o_borrowed.count_only) return;
Alloc own;
@@ -409,7 +424,15 @@ strata::kernels::QsaAttnPools pools_of(const strata::kernels::KvHostPools& h, co
} // namespace
Prefill::Prefill() : impl_(new Impl) {}
-Prefill::~Prefill() {
+Prefill::~Prefill() { release(); }
+
+void Prefill::reset() {
+ release();
+ impl_.reset(new Impl);
+ stats_ = PrefillStats{};
+}
+
+void Prefill::release() {
if (!impl_) return;
if (impl_->cs) impl_->cs->wait();
if (impl_->copy) impl_->copy->wait();
@@ -540,10 +563,24 @@ bool Prefill::init(const core::WeightTable &wt, const core::ModelGeometry &g,
return false;
}
if (m.tok_dev == nullptr) {
- if (DPCT_CHECK_ERROR(m.tok_dev = sycl::malloc_device<int32_t>(
- (size_t)chunk, dpct::get_in_order_queue())) !=
- 0) {
- err = "prefill: the token id buffer";
+ /*
+ DPCT1000: Error handling if-stmt was detected but could not be
+ rewritten.
+ */
+ if (const dpct::err0 e = DPCT_CHECK_ERROR(
+ m.tok_dev = sycl::malloc_device<int32_t>(
+ (size_t)chunk, dpct::get_in_order_queue()));
+ e != 0) {
+ /*
+ DPCT1009: SYCL reports errors using exceptions and does not use
+ error codes. Please replace the "get_error_string_dummy(...)" with a
+ real error-handling function.
+ */
+ /*
+ DPCT1001: The statement could not be removed.
+ */
+ err = std::string("prefill: the token id buffer (") +
+ dpct::get_error_string_dummy(e) + ")";
return false;
}
m.owned.push_back(m.tok_dev);
@@ -628,8 +665,8 @@ bool Prefill::init(const core::WeightTable &wt, const core::ModelGeometry &g,
ok = false;
m.ple_rows[b].resize(T * strata::kernels::PLE_N_HEADS);
}
- if (ss.qsa_states[0].kv_mode == 1) { // KV streaming: the staging pool's identity page table
- const int64_t pages = ss.qsa_states[0].n_pages;
+ if (ss.qsa_states[ss.qsa_primary()].kv_mode == 1) { // KV streaming: the staging pool's identity page table
+ const int64_t pages = ss.qsa_states[ss.qsa_primary()].n_pages;
std::vector<int32_t> ident((size_t) pages);
for (int64_t i = 0; i < pages; ++i) ident[(size_t) i] = (int32_t) i;
if (DPCT_CHECK_ERROR(
@@ -690,7 +727,7 @@ bool Prefill::carve(size_t T, void* alloc) {
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;
m.cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);
- m.max_blocks = ss.qsa_states[0].max_cells / s.idx_block + 2;
+ m.max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2;
{
// one region for the attention half's and the MoE half's scratch (see gdn_set_bytes)
const uint64_t region = std::max({gdn_set_bytes(T), qsa_set_bytes(T, m.cap, m.max_blocks, m.sel_batch,
@@ -935,7 +972,7 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t
proj(mixed, mixed_h, w_k, Kc, nb, KV, Nn, 0);
proj(mixed, mixed_h, w_v, Vc, nb, KV, Nn, 0);
rms_rows(Kc, w_kn, nb * g.n_head_kv, g.head_dim, g.head_dim, EPS, m.cs);
- rope(Kc, nb, g.n_head_kv, g.head_dim, KV, c0, (float) strata::kernels::qsa_freq_base(), m.cs);
+ rope(Kc, nb, g.n_head_kv, g.head_dim, KV, c0, strata::kernels::rope_scaling(), m.cs);
if (st.kv_q4) {
strata::kernels::fwht256_inplace_cuda(Kc, nb * g.n_head_kv, m.cs);
strata::kernels::fwht256_inplace_cuda(Vc, nb * g.n_head_kv, m.cs);
@@ -982,7 +1019,7 @@ uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::Session
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;
const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);
- const int64_t max_blocks = ss.qsa_states[0].max_cells / s.idx_block + 2;
+ const int64_t max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2;
o.take<uint8_t>((size_t) std::max({gdn_set_bytes(T), qsa_set_bytes(T, cap, max_blocks, 256, 32, s),
moe_set_bytes(T, g.n_expert)}), ok);
for (int i = 0; i < DQ; ++i) { o.take<uint16_t>(1280 * 2560, ok); o.take<uint16_t>(2560 * 640, ok); }
@@ -1152,6 +1189,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
if (should_stop && should_stop()) { err = "cancelled"; return false; }
if (std::getenv("STRATA_TRACE")) { std::fprintf(stderr, "strata trace: prompt chunk %lld of %lld\n", (long long) c0, (long long) n); std::fflush(stderr); }
const int64_t T = chunk_len(c0), p0 = pos0 + c0;
+ core::progress_at("reading the prompt (batched): preparing the chunk from token", p0); // #251
++stats_.chunks;
pt.mark(kPfStart, cs);
const auto tsetup = Clock::now();
@@ -1286,7 +1324,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
// k lands in ring slot k % ring); a copy is issued once the entry `ring` before it is consumed (its slot's
// `used` event recorded), so the copy stream never waits on an event that is not queued yet
const strata::kernels::cpu::ExpertLayout& lay0 = strata::kernels::cpu::expert_layout();
- const bool stream_all = m.ring > STAGE && T >= STREAM_ALL_MIN && m.src != nullptr;
+ const bool stream_all = m.ring > STAGE && T >= stream_all_min() && m.src != nullptr;
struct StreamEntry { int32_t l, e; const uint8_t* blob; int job; };
std::vector<StreamEntry> seq;
std::vector<size_t> seq_start;
@@ -1304,7 +1342,10 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
int job = -1;
if (gsrc != nullptr) { // read by the stager's thread when its turn comes (see Stager::Job)
job = (int) js.size();
- js.push_back({nullptr, (size_t) lay0.blob_bytes(l), l, e, gsrc});
+ js.push_back({nullptr, (size_t) lay0.blob_bytes(l), nullptr, (int32_t) l, e, gsrc});
+ } else if (m.src->transient(l, e)) { // CS-T: copied by the source into the stager's buffer
+ job = (int) js.size();
+ js.push_back({nullptr, (size_t) lay0.blob_bytes(l), m.src, (int32_t) l, e});
} else {
b = m.src->blob(l, e);
if (!b) { err = "prefill: expert source has no blob"; return false; }
@@ -1447,6 +1488,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
bool normed = false; // F-2: the previous half's write already normed R for this half (grs, xn16)
for (int64_t l = LB; l < LE; ++l) {
core::progress_beat(); // the serve watchdog: a prompt chunk of 8192 tokens is still moving
+ core::progress_at("reading the prompt (batched): layer", l, p0); // #251: a stall names layer and chunk
const core::LayerView v(*m.wt, l);
// ---- the PLE block at layer 1, token by token (its conv reads the previous tokens' rows)
if (l == 1 && ple_on && ple_batch) {
@@ -1528,7 +1570,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
*wsa = need(v, "ssm_a", err);
if (!wqkv || !wg || !wo || !wa || !wb || !wc || !wnm || !wdt || !wsa) return false;
pt.mark(kPfGdn, cs);
- float* state = ss.gdn_state + (size_t) gdn_index * gdn_floats;
+ float* state = ss.gdn_state + (size_t) (gdn_index - ss.gdn_ord0) * gdn_floats;
float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
if (!native_proj(m.gemm, wqkv, m.mixed_h, m.qkv, T, v.name("attn_qkv.weight"), err)) return false;
if (!native_proj(m.gemm, wg, m.mixed_h, m.z, T, v.name("attn_gate.weight"), err)) return false;
@@ -1560,7 +1602,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err)) return false;
if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err)) return false;
rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs);
- rope(m.Kc, T, 2, 256, 512, p0, (float) strata::kernels::qsa_freq_base(), m.cs);
+ rope(m.Kc, T, 2, 256, 512, p0, strata::kernels::rope_scaling(), m.cs);
// KV streaming: this layer's cells [0, p0) come in from the host copy to the staging pool, and the
// chunk's cells go to the host copy, the staging pool, and the VRAM slots of resident blocks
const bool staged = st.kv_mode == 1;
@@ -1590,10 +1632,10 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
}
split_q(m.Qf, m.q, T, m.cs);
rms_rows(m.q, (const float*) wqn->data, T * 24, 256, 256, EPS, m.cs);
- rope(m.q, T, 24, 256, 6144, p0, (float) strata::kernels::qsa_freq_base(), m.cs);
+ rope(m.q, T, 24, 256, 6144, p0, strata::kernels::rope_scaling(), m.cs);
if (st.kv_q4) strata::kernels::fwht256_inplace_cuda(m.q, T * 24, m.cs);
rms_rows(m.q_idx, (const float*) wiqn->data, T * 4, 128, 128, EPS, m.cs);
- rope(m.q_idx, T, 4, 128, 512, p0, (float) strata::kernels::qsa_freq_base(), m.cs);
+ rope(m.q_idx, T, 4, 128, 512, p0, strata::kernels::rope_scaling(), m.cs);
// the indexer appends, token by token; then scores + selection for many queries at once:
// a query reads completed blocks (final once completed) and `dead` for its own tail block
const strata::kernels::QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};
@@ -1605,13 +1647,13 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
if (!per_token) {
strata::kernels::native_qsa_indexer_append_batch(m.idx_raw, T, p0, 0, (const float*) wikn->data,
EPS, ib, s, st.max_cells,
- (float) strata::kernels::qsa_freq_base(), m.cs);
+ strata::kernels::rope_scaling(), m.cs);
}
for (int64_t t = 0; per_token && t < T; ++t) {
const int32_t* step_t = m.steps_dev + t * strata::kernels::kStepCount;
strata::kernels::native_qsa_indexer_append(m.idx_raw + t * 128, step_t + strata::kernels::kStepPos, 0,
(const float*) wikn->data, EPS, ib, s, st.max_cells,
- (float) strata::kernels::qsa_freq_base(), m.cs);
+ strata::kernels::rope_scaling(), m.cs);
}
} catch (const std::exception& e) { err = std::string("prefill indexer: ") + e.what(); return false; }
pt.mark(kPfQsaSel, cs);
@@ -1928,7 +1970,14 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;
if (m.src->pinned(l, e)) continue;
job_of[j] = (int) js.size();
- if (gsrc != nullptr) { js.push_back({nullptr, (size_t) lay.blob_bytes(l), l, e, gsrc}); continue; }
+ if (gsrc != nullptr) {
+ js.push_back({nullptr, (size_t) lay.blob_bytes(l), nullptr, (int32_t) l, e, gsrc});
+ continue;
+ }
+ if (m.src->transient(l, e)) { // CS-T: copied by the source
+ js.push_back({nullptr, (size_t) lay.blob_bytes(l), m.src, (int32_t) l, e});
+ continue;
+ }
const uint8_t* b = m.src->blob(l, e);
if (!b) { err = "prefill: expert source has no blob"; return false; }
js.push_back({b, (size_t) lay.blob_bytes(l)});
@@ -1944,9 +1993,10 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
const int sl = stage_next;
stage_next = (stage_next + 1) % STAGE;
const auto th = Clock::now();
- const uint8_t* b = m.src->blob(l, e);
- if (!b) { err = "prefill: expert source has no blob"; return false; }
- if (m.src->pinned(l, e)) {
+ const bool pinned = m.src->pinned(l, e); // pinned: never transient
+ const uint8_t* b = pinned ? m.src->blob(l, e) : nullptr;
+ if (pinned && !b) { err = "prefill: expert source has no blob"; return false; }
+ if (pinned) {
// DMA straight from the page-locked arena: the copy stream only waits for the slot
if (m.stage_live[sl])(m.copy)
->ext_oneapi_submit_barrier({*m.used[sl]});
@@ -2188,6 +2238,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
stats_.experts_dma += iss_dma;
}
stats_.tokens += T;
+ core::progress_at("reading the prompt (batched): finishing the chunk from token", p0);
pt.mark(kPfStart, cs);
if (next_ != nullptr) {
// the rows to the host buffer the next stage read two chunks ago (it has finished: waited below)
@@ -2352,7 +2403,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
std::vector<uint8_t> b((size_t) gdn_floats * 4);
std::string line;
char h[8];
- for (int64_t i = 0; i < g.n_gdn_layers(); ++i) {
+ for (int64_t i = 0; i < ss.gdn_alloc; ++i) {
dpct::get_in_order_queue()
.memcpy(b.data(), ss.gdn_state + (size_t)i * gdn_floats,
b.size())
diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp
index 34a605989..d7c835c42 100644
--- a/sycl/src/program/generate.cpp
+++ b/sycl/src/program/generate.cpp
@@ -18,10 +18,14 @@
#include <sycl/sycl.hpp>
#include <dpct/dpct.hpp>
#include "strata/sycl_queue.hpp"
+#include "strata/core/device.hpp"
#include "strata/core/expert_cache.hpp"
+#include "strata/core/conversation_snapshot.hpp"
+#include "strata/core/conversation_memory.hpp"
#include "strata/core/expert_source.hpp"
#include "strata/core/gguf_expert_source.hpp"
#include "strata/kernels/resident_plan_mirror.hpp"
+#include "strata/core/pinned.hpp"
#include "strata/core/remote_experts.hpp"
#include "strata/core/on_device.hpp"
#include "strata/core/layer.hpp"
@@ -32,6 +36,7 @@
#include "strata/kernels/cpu/pool.hpp"
#include "strata/kernels/cpu/expert_layout.hpp"
#include "strata/kernels/ngram.hpp"
+#include "strata/kernels/iq_kernels.hpp"
#include "strata/kernels/s2_expert_grouped.hpp"
#include "strata/kernels/sampler.hpp"
#include "strata/kernels/verify_kernels.hpp"
@@ -79,6 +84,8 @@
#include <deque>
#include <map>
#include <mutex>
+#include <optional>
+#include <new>
#include <charconv>
#include <cmath>
#include <limits>
@@ -93,6 +100,18 @@
#include <vector>
namespace {
+// Windows' WDDM driver model: native Windows, or WSL2 (its GPU goes through /dev/dxg to the Windows driver). There,
+// pinning a large arena into two CUDA contexts leaves WDDM refusing every later allocation (the 5080 + 3090 rig);
+// a Linux driver has no such limit (#253: the 8 GiB cap cost a 4090 + 3060 split 3x of its prompt speed).
+bool under_wddm() {
+#ifdef _WIN32
+ return true;
+#else
+ static const bool dxg = std::filesystem::exists("/dev/dxg");
+ return dxg;
+#endif
+}
+
// perf-review D-4: the lent slots are refilled with queued copies and one wait; STRATA_REFILL_BLOCKING=1 waits on each
bool refill_blocking() {
static const bool v = std::getenv("STRATA_REFILL_BLOCKING") != nullptr;
@@ -101,6 +120,58 @@ bool refill_blocking() {
using Clock = std::chrono::steady_clock;
+// The resident RAM mode and the adaptive tier. A swap copies `in` (held in RAM) into the slot of `out` (held only
+// by that slot). Before the slot is overwritten, `out`'s bytes are copied back from it into an exchange buffer, so
+// the CPU computes `out` from RAM while the swap is in flight; when the swap has landed, `commit_exchanges` moves
+// them into `in`'s place in RAM. The RAM copy then again holds exactly the experts no core slot does, and no swap
+// reads the file. Swaps that need no exchange (`out` in the lend region is held in RAM already; or `in` is not) go
+// on as before; ones beyond the buffers' room wait for a later round. Runs on the adaptive tier's thread while the
+// GPU commits and drafts: the copies back are on its stream, and waited for before the refills are queued.
+template <class Swap>
+bool resident_stage_swaps(strata::core::FileExpertSource &src,
+ strata::core::ExpertCache &cache,
+ const std::vector<int32_t> &host_res,
+ int64_t n_expert, std::vector<Swap> &swaps,
+ dpct::queue_ptr stream) try {
+ if (!src.complement_ready() || swaps.empty()) return true;
+ struct Staged { int32_t layer, in, out; int64_t q; };
+ std::vector<Staged> staged;
+ std::vector<Swap> kept;
+ kept.reserve(swaps.size());
+ for (const Swap& s : swaps) {
+ if (!src.has_resident(s.layer, s.in) || src.has_resident(s.layer, s.out)) { kept.push_back(s); continue; }
+ const int64_t q = (int64_t) staged.size();
+ if (q >= src.exchange_capacity()) continue;
+ const int32_t slot = host_res[(size_t) s.layer * (size_t) n_expert + (size_t) s.out];
+ if (slot < 0) continue;
+ /*
+ 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(stream->memcpy(
+ src.exchange_buffer(q), cache.device_slot(slot),
+ (size_t)strata::kernels::cpu::expert_layout().blob_bytes(
+ s.layer))) != 0)
+ return false;
+ staged.push_back({s.layer, s.in, s.out, q});
+ kept.push_back(s);
+ }
+ if (!staged.empty()) {
+ if (DPCT_CHECK_ERROR(stream->wait()) != 0) return false;
+ for (const Staged& x : staged)
+ if (!src.stage_exchange(x.layer, x.in, x.out, x.q)) return false;
+ }
+ swaps.swap(kept);
+ return true;
+}
+catch (sycl::exception const &exc) {
+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__
+ << ", line:" << __LINE__ << std::endl;
+ std::exit(1);
+}
+
struct Options {
std::string pack = "pack/full";
std::vector<int64_t> tokens; // the prompt, PRE-TOKENIZED
@@ -133,12 +204,29 @@ struct Options {
bool native_flash_attn_short = false; // diagnostic pinned attention, context <=256
bool native_qsa_indexer = false; // pinned F16 key cache and F32 pooling
bool native_qsa = false; // pinned F32 QSA norms and gate
+ /// THE CONTEXT EXTENSION (rope scaling, rope_scaling.hpp). These knobs resolve to ONE process config,
+ /// set once before `session_init` builds the rope table and the graphs capture the kernels. There is
+ /// deliberately no per-request form: K sits in the cache POST-RoPE, so one cache must never mix two
+ /// scalings. Precedence: an EXPLICIT flag over the model file's rope keys over the struct defaults -
+ /// `none` and `1` are explicit values (the opt-outs), the absent flag is not.
+ std::string rope_scaling; ///< --rope-scaling none|linear|yarn (llama.cpp's names); empty = the flag is absent
+ double rope_scale = 0; ///< --rope-scale F: the extension factor; 0 = the flag is absent (the model file's, else 1 = off)
+ double rope_freq_base = 0; ///< --rope-freq-base N: 0 = the model's (1e7)
+ double rope_freq_scale = 0; ///< --rope-freq-scale F: the raw ggml knob; 0 = 1/--rope-scale
+ double yarn_orig_ctx = 0; ///< --yarn-orig-ctx N: 0 = the model's, else 262144
+ double yarn_ext_factor = -1.0; ///< --yarn-ext-factor F: <0 = auto (1 for yarn, 0 otherwise)
+ double yarn_attn_factor = 1.0; ///< --yarn-attn-factor F
+ double yarn_beta_fast = 32.0; ///< --yarn-beta-fast F
+ double yarn_beta_slow = 1.0; ///< --yarn-beta-slow F
bool native_rope = false; // pinned text-only CUDA rotary arithmetic
bool native_ple_postops = false; // pinned PLE postprojection arithmetic
bool native_router = false; // pinned fused 512-expert top-10 router
bool cpu_oracle_q8_0 = false; // pinned x86 activation scales/codes at both expert stages
std::string native_head_gguf; // native output.weight experiment; same model shard as the pack
std::vector<std::string> native_dense_gguf; // repeat for native GDN/QSA projection shards
+ /// Every shard of --native's model (strata::gguf_split_paths: the metadata shard first; a missing shard is an
+ /// error) and of --native-head-gguf's (the same list unless that names another model).
+ std::vector<std::string> native_shards, native_head_shards;
/// Plan v0.3 P1: the whole native arithmetic set as ONE switch (model shard 1). It enables exactly the
/// combination recorded in bench/results/2026-09-23-attention-ple plus the native indexer, and never the
/// <=256-token attention adapter. It becomes the default once P0 shows it is not slower.
@@ -186,8 +274,19 @@ struct Options {
/// is reserved for a host thread that has nothing to do while the drain runs.
bool no_host_worker = false;
bool mmap_experts = false; ///< R2.1: opt OUT of the resident arena, back to MapViewOfFile
+ std::string shared_expert_arena; ///< Linux: optional file backing for the resident arena shared by processes
bool resident_cpu_experts = false; ///< mmap-backed static-cache misses copied into ordinary RAM
bool stream_experts = false; ///< SYCL port: no host arena; blobs read from the GGUF on demand (all experts in VRAM)
+ /// `--resident-experts` (the low-RAM PC's resident mode, chosen by setup): `--resident-cpu-experts` with the copy
+ /// page-locked when the driver allows (else locked in the working set), 4 GiB of RAM headroom, and plain mmap
+ /// (with a warning) when even the experts no slot holds do not fit.
+ bool resident_pin = false;
+ uint64_t resident_headroom = 8ull << 30;
+ bool resident_soft = false;
+ /// CS-T `--resident-budget-gib N`: the resident mode with a RAM budget - the N GiB of experts the GPU cache does
+ /// not hold that the expert profile ranks hottest are copied into RAM, the rest are read from the files in place
+ /// (the GGUF shards when the pack has no experts.bin). 0 = the whole complement (--resident-experts).
+ uint64_t resident_budget = 0;
/// R4: slots of VRAM-resident experts. **0 = off, and off is the default.**
/// **THE COMMENT THAT USED TO BE HERE WAS FALSE AND ROUND 328 MEASURED IT.** It said "the cache has no
/// consumer yet - `moe_hit_grouped_s2` does not exist - so switching it on costs the fill traffic and
@@ -278,6 +377,10 @@ struct Options {
/// the later stages' devices "D1,D2,.." (default: the next visible GPUs; "0" with one K: both stages on this
/// GPU, sharing everything - the bit-exact A/B of the hand-off)
std::string split_device;
+ /// --split-skip-if-fits (opt-in; the server passes it for a config's "split_skip_if_fits"): with
+ /// --layer-split auto, run on CUDA0 alone when it holds every profiled expert pair plus the whole session (KV),
+ /// the drafter and the reserve - a split then only adds hand-offs (two RDNA4 cards: 1,384 vs 1,794 tok/s at 4K)
+ bool split_skip_if_fits = false;
/// Plan v0.3 P8: stay resident and take requests on stdin (see the --serve block in main).
bool serve = false;
/// The vision path: keep a per-cell (t, h, w) rotary position table so --serve can take GENI requests.
@@ -287,6 +390,9 @@ struct Options {
/// prompt again, the v0.1.2 behaviour). One is the GDN recurrence of the 36 layers, the QSA indexer tails and
/// the PLE history (~118 MB of host RAM); the KV cache itself is positional and stays where it is.
int prompt_cache = 6;
+ int64_t conversation_cache_mib = 0; // opt-in host RAM for independent conversations
+ int conversation_cache_slots = 4;
+ int64_t conversation_cache_min_free_mib = 2560;
/// --serve: also keep a checkpoint every N freshly read prompt tokens (0 = only at the last turn boundary)
int64_t prompt_cache_every = 16384;
/// --serve: a prompt read from token 0 is also checkpointed at its first turn boundary - the end of the system
@@ -322,7 +428,8 @@ void usage() {
" --pack DIR the pack directory (default pack/full)\n"
" --tokens LIST the prompt as comma-separated token IDS (required)\n"
" --tokens-file PATH pretokenized prompt, commas or whitespace (alternative to --tokens)\n"
- " --ple-gguf PATH required PLE table (original second GGUF shard)\n"
+ " --ple-gguf PATH required PLE table (original second GGUF shard); with --native, the model's\n"
+ " shard that holds per_layer_token_embd.weight when not given\n"
" --no-ple explicit diagnostic ablation of the PLE layer\n"
" --ple-io direct|mmap|ram n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n"
" reads, the table never enters RAM or the file cache; mmap: A/B arm;\n"
@@ -365,6 +472,17 @@ void usage() {
" --expert-cache-cpu-order experimental GPU expert reduction matching CPU order\n"
" --max-new N tokens to generate (default 16)\n"
" --max-context N KV/state capacity (default 4096)\n"
+ " --rope-scaling T extend the context past the trained one: none, linear\n"
+ " (position interpolation) or yarn - llama.cpp's types and names.\n"
+ " Default: the model file's rope keys, else none. Fixed at startup:\n"
+ " K in the cache is post-RoPE, so one run one scaling\n"
+ " --rope-scale F the extension factor for linear/yarn (default: the model file's\n"
+ " factor, else 1 = off)\n"
+ " --rope-freq-base N the raw ggml knobs: the frequency base (0 = the model's 1e7) and\n"
+ " --rope-freq-scale F the angle shrink (0 = 1/--rope-scale)\n"
+ " --yarn-orig-ctx N the trained context the correction targets (0 = 262144)\n"
+ " --yarn-ext-factor F --yarn-attn-factor F --yarn-beta-fast F --yarn-beta-slow F\n"
+ " YaRN's knobs; defaults: -1 (auto: 1 for yarn), 1, 32, 1\n"
" --greedy argmax (the default)\n"
" --seed S enable sampling with this Philox seed\n"
" --top-k N --top-p F --temperature F\n"
@@ -380,6 +498,9 @@ void usage() {
" --vision --serve takes images too (GENI requests; embeddings from strata-vision)\n"
" --prompt-cache N --serve: keep N conversation checkpoints between requests (default 6, ~118 MB\n"
" of RAM each; 0 = read every prompt from the start)\n"
+ " --conversation-cache-mib N --serve: RAM budget for parked conversations (default 0 = off)\n"
+ " --conversation-cache-slots N --serve: at most N parked conversations (default 4)\n"
+ " --conversation-cache-min-free-mib N --serve: physical RAM floor when parking (default 2560)\n"
" --prompt-cache-every N --serve: also checkpoint every N fresh prompt tokens (default 16384, 0 = off)\n"
" --turn-token ID --serve: the token that opens a chat turn (default 248045, <|im_start|>)\n"
" --short-read N --serve: read at most N fresh text tokens through the decode windows instead\n"
@@ -443,25 +564,15 @@ void usage() {
" a VRAM cache that holds every expert; for machines with less RAM than experts)\n"
" The A/B arm: the mmap's rate depends on the OS page cache holding\n"
" 34 GB, and measured 71.97 vs 34.78 ms/token cold vs warm.\n"
- " --resident-cpu-experts with mmap and a static profile, keep CPU misses resident in ordinary RAM.\n"
- " Borrowed GPU-cache entries may read from mmap during prompt prefill.\n");
-}
-
-/// All shards of a split GGUF, from shard 1's path ("...-00001-of-00002.gguf"); just the path when it is not split.
-std::vector<std::string> model_shards(const std::string& first) {
- const std::string tag = "-00001-of-";
- const size_t at = first.rfind(tag);
- if (at == std::string::npos || first.size() < at + tag.size() + 10) return {first};
- const int total = std::atoi(first.substr(at + tag.size(), 5).c_str());
- std::vector<std::string> out;
- for (int i = 1; i <= total && i <= 99; ++i) {
- char num[8];
- std::snprintf(num, sizeof num, "%05d", i);
- std::string p = first;
- p.replace(at + 1, 5, num);
- if (std::ifstream(p, std::ios::binary)) out.push_back(p);
- }
- return out.empty() ? std::vector<std::string>{first} : out;
+ " --shared-expert-arena FILE Linux: back the resident arena with one MAP_SHARED file.\n"
+ " Put this file on /dev/shm, not ordinary SSD storage.\n"
+ " A small header binds an existing backing file to the same pack.\n"
+ " --resident-cpu-experts with mmap and a static profile, keep the experts the GPU cache does not\n"
+ " hold resident in ordinary RAM (and the prompt path's lend region as far as\n"
+ " RAM allows); adaptive swaps exchange them, so none is read from the file again.\n"
+ " --resident-experts the low-RAM PC's resident mode (setup): --mmap-experts --resident-cpu-experts\n"
+ " with the copy page-locked when possible, 4 GiB headroom, plain mmap if it\n"
+ " does not fit. Same answers as --mmap-experts for the same placement.\n");
}
bool parse_i64_list(const char* s, std::vector<int64_t>& out, std::string& err) {
@@ -641,11 +752,19 @@ MemSample mem_sample() {
return m;
}
+// the stage the watchdog names: "<where> <detail>", and the prompt chunk a batched read is in (#251)
+std::string stage_text() {
+ const strata::core::Progress& p = strata::core::progress();
+ std::string s = std::string(p.where.load()) + " " + std::to_string((long long) p.detail.load());
+ if (const int64_t c = p.chunk.load(); c >= 0) s += " of the prompt chunk from token " + std::to_string((long long) c);
+ return s;
+}
+
void stall_report(std::FILE* f, uint64_t layers_during) {
strata::core::Progress& p = strata::core::progress();
- std::fprintf(f, "strata serve: stall report (engine %s): stage \"%s %lld\" for %lld s; %llu layers served since the "
- "last finished step (0 = stopped, more = slow)\n", STRATA_VERSION, p.where.load(),
- (long long) p.detail.load(), (long long) ((strata::core::progress_now_ms() - p.since_ms.load()) / 1000),
+ std::fprintf(f, "strata serve: stall report (engine %s): stage \"%s\" for %lld s; %llu layers served since the "
+ "last finished step (0 = stopped, more = slow)\n", STRATA_VERSION, stage_text().c_str(),
+ (long long) ((strata::core::progress_now_ms() - p.since_ms.load()) / 1000),
(unsigned long long) layers_during);
for (int pass = 0; pass < 2; ++pass) {
if (pass == 1) {
@@ -720,19 +839,8 @@ int argmax(const std::vector<float>& v) {
// back rejected drafts.
// A checkpoint is only valid while the positional cells below it still hold ITS tokens, so the serve loop keeps
// just the checkpoints that are prefixes of the tokens the session holds now.
-struct ImgKey {
- int64_t start = 0; ///< the image's first <|image_pad|> position
- uint64_t hash = 0; ///< its embeddings and grid: the pad tokens alone are the same for every picture
- bool operator==(const ImgKey& o) const { return start == o.start && hash == o.hash; }
-};
-
-struct ConvCheckpoint {
- std::vector<int32_t> ids; ///< the tokens this state has consumed
- std::vector<ImgKey> imgs; ///< the images among them
- std::vector<uint8_t> gdn, ple, tails;
- uint64_t used = 0; ///< last-use stamp for the retention policy (conv_cache.hpp)
- std::vector<ConvCheckpoint> stage_parts; ///< a layer split's later stages: their sessions' running state
-};
+using ImgKey = strata::core::ConversationImageKey;
+using ConvCheckpoint = strata::core::ConversationCheckpoint;
uint64_t fnv1a(const void* data, size_t n, uint64_t h = 1469598103934665603ull) {
const uint8_t* p = (const uint8_t*) data;
@@ -740,93 +848,31 @@ uint64_t fnv1a(const void* data, size_t n, uint64_t h = 1469598103934665603ull)
return h;
}
-struct ConvStateSizes {
- size_t gdn = 0, ple = 0, tail = 0;
-};
+using ConvStateSizes = strata::core::ConversationStateSizes;
-ConvStateSizes conv_state_sizes(const strata::core::ModelGeometry& g) {
+ConvStateSizes conv_state_sizes(const strata::core::ModelGeometry& g, const strata::core::SessionState& ss) {
ConvStateSizes z;
- z.gdn = (size_t) g.n_gdn_layers() *
- ((size_t) g.ssm_state_size * (size_t) g.ssm_v_heads * (size_t) g.ssm_state_size +
- (size_t) g.ssm_conv_channels * (size_t) (g.ssm_d_conv - 1)) * sizeof(float);
- z.ple = (size_t) strata::kernels::NG_HIST * (size_t) strata::kernels::NG_HC_DIM * sizeof(float);
- z.tail = (size_t) (strata::kernels::qsa_real_shapes().idx_block - 1) * (size_t) g.idx_key_dim * sizeof(float);
+ std::string error;
+ // a split stage's session owns only its layer range's state (see SessionState's carve note); the geometry
+ // and the carve have already passed engine validation
+ strata::core::conversation_session_sizes(g, ss, z, error);
return z;
}
-/// Copies the running state out. The caller has synchronized the device.
-bool checkpoint_save(ConvCheckpoint &c, const strata::core::SessionState &ss,
- const strata::core::ModelGeometry &g) try {
- const ConvStateSizes z = conv_state_sizes(g);
- c.gdn.resize(z.gdn);
- c.ple.resize(ss.ple_hist != nullptr ? z.ple : 0);
- c.tails.resize(z.tail * (size_t) g.n_qsa_layers());
- if (DPCT_CHECK_ERROR(dpct::get_in_order_queue()
- .memcpy(c.gdn.data(), ss.gdn_state, z.gdn)
- .wait()) != 0) return false;
- if (!c.ple.empty() &&
- DPCT_CHECK_ERROR(dpct::get_in_order_queue()
- .memcpy(c.ple.data(), ss.ple_hist, z.ple)
- .wait()) != 0)
- return false;
- for (int64_t i = 0; i < g.n_qsa_layers(); ++i)
- if (DPCT_CHECK_ERROR(dpct::get_in_order_queue()
- .memcpy(c.tails.data() + (size_t)i * z.tail,
- ss.qsa_states[i].idx_tail, z.tail)
- .wait()) != 0)
- return false;
- return true;
-}
-catch (sycl::exception const &exc) {
- std::cerr << exc.what() << "Exception caught at file:" << __FILE__
- << ", line:" << __LINE__ << std::endl;
- std::exit(1);
+/// Copies the running state out (this session's carve only). The caller has synchronized the device.
+bool checkpoint_save(ConvCheckpoint& c, const strata::core::SessionState& ss, const strata::core::ModelGeometry& g) {
+ std::string error;
+ if (strata::core::conversation_checkpoint_save(c, ss, g, error)) return true;
+ std::fprintf(stderr, "strata serve: checkpoint save: %s\n", error.c_str()); // the caller's ERR has no reason
+ return false;
}
/// Puts a checkpoint's running state back; the positional cells below it are the caller's to guarantee.
-bool checkpoint_restore(const ConvCheckpoint &c, strata::core::SessionState &ss,
- const strata::core::ModelGeometry &g) try {
- const ConvStateSizes z = conv_state_sizes(g);
- if (c.gdn.size() != z.gdn || c.tails.size() != z.tail * (size_t) g.n_qsa_layers()) return false;
- /*
- 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 (DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
- ss.gdn_state, c.gdn.data(), z.gdn).wait()) != 0) return false;
- /*
- 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 (!c.ple.empty() && DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
- ss.ple_hist, c.ple.data(), z.ple).wait()) != 0)
- return false;
- for (int64_t i = 0; i < g.n_qsa_layers(); ++i)
- /*
- 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 (DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
- ss.qsa_states[i].idx_tail, c.tails.data() + (size_t)i * z.tail,
- z.tail).wait()) != 0)
- return false;
- // the PLE's token window is the last two tokens, OLDEST FIRST, -1 where there is none (as session_zero leaves it)
- const size_t L = c.ids.size();
- ss.ple_prev[0] = L >= 2 ? c.ids[L - 2] : -1;
- ss.ple_prev[1] = L >= 1 ? c.ids[L - 1] : -1;
- return DPCT_CHECK_ERROR(
- dpct::get_current_device().queues_wait_and_throw()) == 0;
-}
-catch (sycl::exception const &exc) {
- std::cerr << exc.what() << "Exception caught at file:" << __FILE__
- << ", line:" << __LINE__ << std::endl;
- std::exit(1);
+bool checkpoint_restore(const ConvCheckpoint& c, strata::core::SessionState& ss, const strata::core::ModelGeometry& g) {
+ std::string error;
+ if (strata::core::conversation_checkpoint_restore(c, ss, g, error)) return true;
+ std::fprintf(stderr, "strata serve: checkpoint restore: %s\n", error.c_str());
+ return false;
}
// --control-vector-scaled: llama.cpp's `common_control_vector_load` (every file's `direction.<l>` times its scale,
@@ -966,7 +1012,7 @@ catch (sycl::exception const &exc) {
} // namespace
-int main(int argc, char** argv) {
+int main(int argc, char **argv) try {
// **UNBUFFERED, BECAUSE THE INTERESTING OUTPUT IS THE OUTPUT BEFORE A CRASH.** `stdout` redirected to a
// pipe or a file is block-buffered, so a program that dies loses every line it had already printed - which
// turns "it crashed at step 7" into "it crashed somewhere", and the difference is a debugging session.
@@ -991,6 +1037,7 @@ int main(int argc, char** argv) {
if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", what); std::exit(2); }
return argv[++i];
};
+ bool parsed = true;
if (a == "--help" || a == "-h") { usage(); return 0; }
else if (a == "--pack") o.pack = next("--pack");
else if (a == "--tokens") {
@@ -1013,6 +1060,15 @@ int main(int argc, char** argv) {
}
else if (a == "--max-new") o.max_new = std::atoll(next("--max-new"));
else if (a == "--max-context") o.max_context = std::atoll(next("--max-context"));
+ else if (a == "--rope-scaling") o.rope_scaling = next("--rope-scaling");
+ else if (a == "--rope-scale") o.rope_scale = std::atof(next("--rope-scale"));
+ else if (a == "--rope-freq-base") o.rope_freq_base = std::atof(next("--rope-freq-base"));
+ else if (a == "--rope-freq-scale") o.rope_freq_scale = std::atof(next("--rope-freq-scale"));
+ else if (a == "--yarn-orig-ctx") o.yarn_orig_ctx = std::atof(next("--yarn-orig-ctx"));
+ else if (a == "--yarn-ext-factor") o.yarn_ext_factor = std::atof(next("--yarn-ext-factor"));
+ else if (a == "--yarn-attn-factor") o.yarn_attn_factor = std::atof(next("--yarn-attn-factor"));
+ else if (a == "--yarn-beta-fast") o.yarn_beta_fast = std::atof(next("--yarn-beta-fast"));
+ else if (a == "--yarn-beta-slow") o.yarn_beta_slow = std::atof(next("--yarn-beta-slow"));
else if (a == "--greedy") o.greedy = true;
else if (a == "--seed") { o.seed = (uint64_t) std::atoll(next("--seed")); o.greedy = false; }
else if (a == "--top-k") o.top_k = std::atoi(next("--top-k"));
@@ -1068,7 +1124,11 @@ int main(int argc, char** argv) {
else if (a == "--pool-workers") o.pool_workers = std::atoi(next("--pool-workers"));
else if (a == "--no-host-worker") o.no_host_worker = true;
else if (a == "--no-ple-prefetch") o.no_ple_prefetch = true;
- else if (a == "--expert-cache") {
+ else parsed = false;
+ // The chain continues here in a second statement: one chain of 120+ `else if` passed MSVC's limit of 128
+ // nested blocks (C1061). The order of the tests and what each does are unchanged.
+ if (!parsed) {
+ if (a == "--expert-cache") {
const std::string v = next("--expert-cache");
o.expert_cache = (v == "auto") ? -1 : std::atoi(v.c_str());
}
@@ -1100,10 +1160,25 @@ int main(int argc, char** argv) {
else if (a == "--spec-split") o.spec_split = true;
else if (a == "--layer-split") o.layer_split = next("--layer-split");
else if (a == "--split-device") o.split_device = next("--split-device");
+ else if (a == "--split-skip-if-fits") o.split_skip_if_fits = true;
else if (a == "--pcie-mode") o.pcie_mode = next("--pcie-mode");
else if (a == "--serve") o.serve = true;
else if (a == "--vision") o.vision = true;
else if (a == "--prompt-cache") o.prompt_cache = std::max(0, std::atoi(next("--prompt-cache")));
+ else if (a == "--conversation-cache-mib" || a == "--conversation-cache-slots" ||
+ a == "--conversation-cache-min-free-mib") {
+ const std::string value = next(a.c_str());
+ int64_t number = 0;
+ const auto result = std::from_chars(value.data(), value.data() + value.size(), number);
+ const int64_t limit = a == "--conversation-cache-slots" ? INT32_MAX : INT64_MAX / (1024 * 1024);
+ if (result.ec != std::errc{} || result.ptr != value.data() + value.size() || number < 0 || number > limit) {
+ std::fprintf(stderr, "%s needs a nonnegative integer within range\n", a.c_str());
+ return 2;
+ }
+ if (a == "--conversation-cache-mib") o.conversation_cache_mib = number;
+ else if (a == "--conversation-cache-min-free-mib") o.conversation_cache_min_free_mib = number;
+ else o.conversation_cache_slots = (int) number;
+ }
else if (a == "--prompt-cache-every") o.prompt_cache_every = std::max(0LL, std::atoll(next("--prompt-cache-every")));
else if (a == "--prompt-cache-root") o.prompt_cache_root = std::max(0LL, std::atoll(next("--prompt-cache-root")));
else if (a == "--turn-token") o.turn_token = std::atoll(next("--turn-token"));
@@ -1155,8 +1230,30 @@ int main(int argc, char** argv) {
else if (a == "--expert-profile") o.expert_profile = next("--expert-profile");
else if (a == "--gpu-stages") o.gpu_stages = true;
else if (a == "--mmap-experts") o.mmap_experts = true;
+ else if (a == "--shared-expert-arena") o.shared_expert_arena = next("--shared-expert-arena");
else if (a == "--resident-cpu-experts") o.resident_cpu_experts = true;
else if (a == "--stream-experts") o.stream_experts = true;
+ else if (a == "--resident-experts") {
+ o.mmap_experts = o.resident_cpu_experts = o.resident_pin = o.resident_soft = true;
+ o.resident_headroom = 4ull << 30;
+ // A/B arms: STRATA_RESIDENT_PIN=0 keeps the copy pageable (the --resident-cpu-experts form);
+ // STRATA_RESIDENT_HEADROOM_GIB=N leaves N GiB of the available RAM free instead of 4
+ if (const char* v = std::getenv("STRATA_RESIDENT_PIN"); v != nullptr && std::string(v) == "0")
+ o.resident_pin = false;
+ if (const char* v = std::getenv("STRATA_RESIDENT_HEADROOM_GIB"); v != nullptr && std::atof(v) >= 0.0)
+ o.resident_headroom = (uint64_t) (std::atof(v) * 1073741824.0);
+ }
+ else if (a == "--resident-budget-gib") {
+ const double gib = std::atof(next("--resident-budget-gib"));
+ if (!(gib > 0.0)) { std::fprintf(stderr, "strata generate: --resident-budget-gib needs N > 0\n"); return 2; }
+ o.resident_budget = (uint64_t) (gib * 1073741824.0);
+ o.mmap_experts = o.resident_cpu_experts = o.resident_pin = true;
+ o.resident_headroom = 4ull << 30;
+ if (const char* v = std::getenv("STRATA_RESIDENT_PIN"); v != nullptr && std::string(v) == "0")
+ o.resident_pin = false;
+ if (const char* v = std::getenv("STRATA_RESIDENT_HEADROOM_GIB"); v != nullptr && std::atof(v) >= 0.0)
+ o.resident_headroom = (uint64_t) (std::atof(v) * 1073741824.0);
+ }
else if (a == "--stats") o.stats = true;
else if (a == "--shared-late") o.shared_late = true;
else if (a == "--keep-canonical") o.keep_canonical = true;
@@ -1173,6 +1270,14 @@ int main(int argc, char** argv) {
usage();
return 2;
}
+ }
+ }
+ if (o.serve && o.conversation_cache_mib > 0 && (o.prompt_cache == 0 || o.conversation_cache_slots == 0))
+ std::fprintf(stderr, "strata serve: warning: conversation caching is disabled by %s\n",
+ o.prompt_cache == 0 ? "--prompt-cache 0" : "--conversation-cache-slots 0");
+ if (o.conversation_cache_mib > 0 && o.conversation_cache_slots > 0 && o.prompt_cache > 0 && !o.layer_split.empty()) {
+ std::fprintf(stderr, "strata serve: conversation parking does not yet support --layer-split; disable parking with --conversation-cache-mib 0\n");
+ return 2;
}
// Layer split (multi-GPU): the later stages run layers [K_i, K_i+1) on their own GPUs (--split-device, default
// the next visible ones); "auto" places the K from each GPU's free VRAM once the weights are in (below). Across
@@ -1228,9 +1333,13 @@ int main(int argc, char** argv) {
return 2;
}
}
- const bool multi_gpu = !split_devs.empty() && !split_same;
- if (o.resident_cpu_experts && (!o.mmap_experts || o.expert_profile.empty() || o.adapt_every != 0)) {
- std::fprintf(stderr, "strata generate: --resident-cpu-experts requires --mmap-experts, a static --expert-profile and --adapt-every 0\n");
+ bool multi_gpu = !split_devs.empty() && !split_same; // cleared by --split-skip-if-fits before any stage loads
+ if (o.mmap_experts && !o.shared_expert_arena.empty()) {
+ std::fprintf(stderr, "strata generate: --shared-expert-arena backs the resident arena and cannot be used with --mmap-experts\n");
+ return 2;
+ }
+ if (o.resident_cpu_experts && (!o.mmap_experts || o.expert_profile.empty())) {
+ std::fprintf(stderr, "strata generate: --resident-cpu-experts requires --mmap-experts and a static --expert-profile\n");
return 2;
}
if (o.resident_cpu_experts &&
@@ -1247,8 +1356,15 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "strata generate: a layer split across GPUs needs --expert-profile\n");
return 2;
}
- o.no_prefill_borrow = true; // each stage's prompt path has its own buffers
- borrow_explicit = true;
+ // A STAGE'S PROMPT PATH BORROWS FROM THAT STAGE'S OWN EXPERT CACHE. This used to set
+ // `no_prefill_borrow = true` - "each stage's prompt path has its own buffers" - which is true, but it is
+ // a reason to give each stage its own LOAN, not a reason to make every stage withhold a chunk-sized
+ // reserve from its cache for the whole session. Forced on, it also collapsed `--prefill auto` to 2048
+ // (below) and skipped the lend arm, so a stage paid for its prompt buffers twice over: once in VRAM it
+ // never got back, once in the smaller chunk. At `--prefill 5524` that reserve is 3.8 GiB per stage,
+ // more than either 8 GB card had - which is how adding two GPUs to the two 12 GB ones lost 260K.
+ // The loan is the tail of the stage's own cache (see `PfPart` in the serve block); outside the prompt
+ // that tail is expert cache, so a large chunk costs a stage nothing permanent.
int n_vis = 1;
if (DPCT_CHECK_ERROR(n_vis = dpct::device_count()) != 0 || n_vis < 1)
n_vis = 1;
@@ -1277,7 +1393,26 @@ int main(int argc, char** argv) {
// 610 vs 792 tok/s) but is what keeps every expert in VRAM at a long context - 80,000 tokens without it: the
// reserve for the KV and the chunk buffers evicts ~1,900 experts, prompt 790 tok/s and decode 2 tok/s after it;
// with it: 1,062 tok/s and 39.5 tok/s. So by default only above a 32K context; the flags still decide.
- if (!borrow_explicit) o.no_prefill_borrow = o.max_context <= 32768;
+ // SYCL port (0.1.31 merge): borrowing hangs in the first chunk of a long prompt (GPU busy, no chunk ever finishes;
+ // 2026-10-01, 40K and 128K prompts, with and without --kv-resident) since upstream's borrow rework; without it the
+ // same prompts read at 1,017-1,189 tok/s. Off by default until that is found; --prefill-borrow opts in.
+ if (!borrow_explicit) o.no_prefill_borrow = true;
+#if defined(STRATA_USE_HIP)
+ {
+ // every GPU this run uses must be an architecture the binary has code for (a gfx1100 build on a gfx1201
+ // card would otherwise fail later with "invalid device function")
+ std::vector<int> used{0};
+ if (multi_gpu) used.insert(used.end(), split_devs.begin(), split_devs.end());
+ for (int r = 0; r < 3; ++r)
+ if (o.expert_cache_remote[(size_t) r] > 0) used.push_back(remote_dev[r]);
+ for (const int d : used) {
+ if (const std::string why = strata::core::gpu_arch_problem(d); !why.empty()) {
+ std::fprintf(stderr, "strata generate: %s\n", why.c_str());
+ return 1;
+ }
+ }
+ }
+#endif
if (o.prefill_auto && (o.no_prefill_borrow || o.expert_profile.empty())) {
o.prefill_auto = false; // nothing to lend from: the buffers are reserved for the session, so keep them small
o.prefill_chunk = 2048;
@@ -1332,8 +1467,24 @@ int main(int argc, char** argv) {
}
strata::core::layer_set_shared_early(!o.shared_late);
if (!o.native_preset.empty()) {
+ try {
+ // every shard of the model (<name>-0000N-of-0000M.gguf beside --native). A missing shard is an error
+ // here: it used to be skipped, leaving a model with some tensors absent and a later error, or none.
+ o.native_shards = strata::gguf_split_paths(o.native_preset);
+ // --ple-gguf defaults to the shard that holds the PLE table, found by name: shard 2 of the ISTA files
+ // and of Unsloth's UD-Q4_K_XL, shard 1 of Swift's
+ if (o.ple_gguf.empty() && !o.no_ple) {
+ const strata::GgufModel model(o.native_shards);
+ size_t at = 0;
+ if (model.find("per_layer_token_embd.weight", &at) != nullptr) o.ple_gguf = o.native_shards[at];
+ }
+ } catch (const std::exception& e) {
+ std::fprintf(stderr, "strata generate: --native %s: %s\n", o.native_preset.c_str(), e.what());
+ return 2;
+ }
if (o.no_ple || o.ple_gguf.empty()) {
- std::fprintf(stderr, "strata generate: --native requires --ple-gguf (the PLE key is native too)\n");
+ std::fprintf(stderr, "strata generate: --native requires --ple-gguf (the PLE key is native too), and no "
+ "shard of the model holds per_layer_token_embd.weight\n");
return 2;
}
o.stream_token = true;
@@ -1345,7 +1496,7 @@ int main(int argc, char** argv) {
if (o.native_dense_gguf.empty()) {
// every shard of the model (<name>-0000N-of-0000M.gguf beside --native), then the PLE shard: a split
// may put any layer in any shard (Swift's GGUFs: layers 13-47 in shard 2, the PLE table in shard 1)
- o.native_dense_gguf = model_shards(o.native_preset);
+ o.native_dense_gguf = o.native_shards;
if (std::find(o.native_dense_gguf.begin(), o.native_dense_gguf.end(), o.ple_gguf) == o.native_dense_gguf.end())
o.native_dense_gguf.push_back(o.ple_gguf);
}
@@ -1378,6 +1529,46 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "strata generate: positive --max-new and --max-context must fit the prompt and generation\n");
return 2;
}
+ // THE ROPE KNOBS (rope_scaling.hpp). Anything invalid dies here, at second zero, rather than becoming a
+ // NaN angle inside one of the twelve QSA layers. Only the RANGES are checked - the config itself is
+ // resolved after the model file has had its say, right before session_init.
+ strata::kernels::RopeScaling rope_cfg; // type filled here; the rest at the resolution below
+ {
+ using RST = strata::kernels::RopeScalingType;
+ // an absent --rope-scaling (the empty default) leaves the type to the model file's rope keys,
+ // resolved below; anything present must be one of the three names
+ if (o.rope_scaling == "none") rope_cfg.type = RST::None;
+ else if (o.rope_scaling == "linear") rope_cfg.type = RST::Linear;
+ else if (o.rope_scaling == "yarn") rope_cfg.type = RST::YaRN;
+ else if (!o.rope_scaling.empty()) {
+ std::fprintf(stderr, "strata generate: --rope-scaling must be none, linear or yarn (got '%s')\n",
+ o.rope_scaling.c_str());
+ return 2;
+ }
+ // every knob FINITE first: `atof("nan")` is NaN, and a NaN passes every range comparison below
+ for (const double v : {o.rope_scale, o.rope_freq_base, o.rope_freq_scale, o.yarn_orig_ctx, o.yarn_ext_factor,
+ o.yarn_attn_factor, o.yarn_beta_fast, o.yarn_beta_slow})
+ if (!std::isfinite(v)) {
+ std::fprintf(stderr, "strata generate: a rope scaling knob is not a finite number (%g)\n", v);
+ return 2;
+ }
+ // 0 is the absent default; an explicit factor must extend, not shrink
+ if (o.rope_scale != 0 && o.rope_scale < 1.0) {
+ std::fprintf(stderr, "strata generate: --rope-scale %g must be >= 1 (it extends the context, not shrinks it)\n",
+ o.rope_scale);
+ return 2;
+ }
+ if (o.rope_freq_base != 0 && o.rope_freq_base <= 1.0) {
+ std::fprintf(stderr, "strata generate: --rope-freq-base must be a base above 1 (0 = the model's)\n");
+ return 2;
+ }
+ if (o.rope_freq_scale < 0 || o.yarn_orig_ctx < 0 || o.yarn_ext_factor < -1.0 || o.yarn_attn_factor <= 0 ||
+ o.yarn_beta_fast <= 0 || o.yarn_beta_slow <= 0) {
+ std::fprintf(stderr, "strata generate: invalid rope scaling knob (see usage: --yarn-ext-factor <0 = auto, "
+ "--yarn-orig-ctx 0 = default, the rest positive)\n");
+ return 2;
+ }
+ }
if (!std::isfinite(o.temperature) || o.temperature < 0 || !std::isfinite(o.top_p) ||
o.top_p <= 0 || o.top_p > 1 || o.top_k < 0 || o.expert_cache < -1 ||
o.pool_workers < 0 || std::any_of(o.expert_cache_remote.begin(), o.expert_cache_remote.end(),
@@ -1400,6 +1591,23 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "strata generate: --native-flash-attn-short requires the normal decode loop for status validation\n");
return 2;
}
+ // The whole-model graph measurements replay every layer through CUDA0's session, which a layer split carves to
+ // CUDA0's own range - the answer would read another stage's state. Refused here rather than at the call, so
+ // the reason is visible before 55 GB is loaded.
+ if (multi_gpu && (o.gpu_only_full || o.gpu_stages)) {
+ std::fprintf(stderr, "strata generate: --gpu-only-full and --gpu-stages replay the whole model through one "
+ "session, which a layer split does not have; run them without --layer-split\n");
+ return 2;
+ }
+ if (!o.native_head_gguf.empty()) {
+ try {
+ o.native_head_shards = o.native_head_gguf == o.native_preset ? o.native_shards
+ : strata::gguf_split_paths(o.native_head_gguf);
+ } catch (const std::exception& e) {
+ std::fprintf(stderr, "strata generate: --native-head-gguf %s: %s\n", o.native_head_gguf.c_str(), e.what());
+ return 2;
+ }
+ }
if (o.native_ple_key && (o.native_dense_gguf.empty() || o.no_ple)) {
std::fprintf(stderr, "strata generate: --native-ple-key requires PLE and --native-dense-gguf\n");
return 2;
@@ -1413,6 +1621,15 @@ int main(int argc, char** argv) {
// compiled `/arch:AVX512`, so on a CPU without those features it does not fail - it executes an illegal
// instruction at some unpredictable token. Refusing at second zero is the whole point of P2.S3's check.
strata::kernels::cpu::expert_set_oracle_q8_0(o.cpu_oracle_q8_0);
+ // ... and nothing runs on a CPU without AVX2: every CPU expert kernel is AVX2 at least (the AVX-512 ones are
+ // chosen above it), and so is ggml-cpu in the release build, which the native pack's layout load initializes
+ // next. Refused here, by name, rather than an illegal instruction in the first expert.
+ if (!strata::kernels::cpu::cpu_avx2_ok()) {
+ std::fprintf(stderr, "strata generate: this CPU (%s) does not support AVX2 with FMA and F16C, which every CPU "
+ "expert kernel needs; Strata runs on Intel Haswell (2013), AMD Zen (2017) or newer\n",
+ strata::kernels::cpu::cpu_name().c_str());
+ return 2;
+ }
std::string err;
if (!o.native_head_gguf.empty() && !o.stream_token) {
@@ -1428,6 +1645,20 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
return 1;
}
+ // Every layer's formats must have GPU expert kernels and a prompt-path dequantizer, checked here, before
+ // anything is allocated: an unsupported down type used to exit from inside the first verify window, and
+ // an unsupported dequant type left the prompt path's fp16 buffer unwritten.
+ const auto& lay = strata::kernels::cpu::expert_layout();
+ for (int64_t l = 0; lay.native && l < (int64_t) lay.fmt.size(); ++l) {
+ const auto& f = lay.fmt[(size_t) l];
+ if (!strata::kernels::native_expert_supported(f.gu_type, f.d_type, f.n_embd, f.n_ff)) {
+ std::fprintf(stderr, "strata generate: layer %lld's experts are %s/%s (ggml types %d/%d), which this "
+ "engine has no GPU kernels for\n", (long long) l,
+ strata::ggml_type_name((uint32_t) f.gu_type), strata::ggml_type_name((uint32_t) f.d_type),
+ f.gu_type, f.d_type);
+ return 1;
+ }
+ }
}
const bool native_pack = strata::kernels::cpu::expert_layout().native;
// STRATA_EARLY_REMOTE_CONTEXTS=1: create EVERY secondary context here, like CUDA1's. Under WSL2 the driver's
@@ -1473,6 +1704,109 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "strata generate: this CPU has no AVX-512: the expert kernels run on %s "
"(multi-token for the i-quant gate/up rows)\n",
std::getenv("STRATA_NO_IQ256") == nullptr ? "AVX-2" : "ggml-cpu vec_dot (STRATA_NO_IQ256 set)");
+ strata::core::ModelGeometry g; // canonical defaults; the model file overrides the MoE shape below
+ int64_t K = 10;
+ // THE ROPE CONFIG RESOLVES HERE, BEFORE ANY WEIGHT MOVES - the CLI and the model file have both spoken,
+ // and `session_init` below builds the rope table from it and captures the kernels reading its constants
+ // (rope_scaling.hpp); the only hard constraint is "set before that", and dying on a bad rope key beats
+ // scanning gigabytes of shards first. Precedence: an EXPLICIT flag over the model file's rope keys over
+ // the struct defaults. The empty --rope-scaling and the 0 --rope-scale mean the flag is absent, so the
+ // model file decides; an explicit value - `none` and `1` included, the opt-outs - wins over the model file.
+ {
+ // The model file's rope keys (llama.cpp's names under the arch prefix), when it carries any - the
+ // artifact today ships none, so this is a no-op defaults channel for future fine-tunes.
+ std::string gguf_rope_type;
+ double gguf_rope_base = 0, gguf_rope_factor = 0, gguf_rope_orig_ctx = 0;
+ if (!o.native_preset.empty()) {
+ // a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10; the model file
+ // is the authority on its own MoE shape - everything else in the geometry is unchanged
+ try {
+ strata::GgufFile model_gguf(o.native_shards.front()); // the metadata shard
+ if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_count")) g.n_expert = (int64_t) v->u;
+ if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_used_count")) K = (int64_t) v->u;
+ if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.freq_base")) gguf_rope_base = v->num();
+ if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.type")) gguf_rope_type = v->s;
+ if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.factor")) gguf_rope_factor = v->num();
+ if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.original_context_length"))
+ gguf_rope_orig_ctx = v->num();
+ } catch (const std::exception& e) {
+ std::fprintf(stderr, "strata generate: reading the model's expert shape from %s: %s\n",
+ o.native_preset.c_str(), e.what());
+ return 1;
+ }
+ }
+ using RST = strata::kernels::RopeScalingType;
+ if (!o.rope_scaling.empty()) {
+ // the early validation pinned the spelling; `none` here is the CLI opting OUT of the model file's keys
+ if (o.rope_scaling == "linear") rope_cfg.type = RST::Linear;
+ else if (o.rope_scaling == "yarn") rope_cfg.type = RST::YaRN;
+ else rope_cfg.type = RST::None;
+ } else if (!gguf_rope_type.empty()) {
+ if (gguf_rope_type == "linear") rope_cfg.type = RST::Linear;
+ else if (gguf_rope_type == "yarn") rope_cfg.type = RST::YaRN;
+ else if (gguf_rope_type != "none") {
+ std::fprintf(stderr, "strata generate: %s carries rope.scaling.type '%s' - none, linear or yarn only\n",
+ o.native_preset.c_str(), gguf_rope_type.c_str());
+ return 2;
+ }
+ }
+ if (o.rope_scale > 0) rope_cfg.factor = o.rope_scale; // an explicit factor, 1 included
+ else if (gguf_rope_factor > 1.0) rope_cfg.factor = gguf_rope_factor;
+ if (o.rope_freq_base > 0) rope_cfg.freq_base = o.rope_freq_base;
+ else if (gguf_rope_base > 1.0) rope_cfg.freq_base = gguf_rope_base;
+ if (o.yarn_orig_ctx > 0) rope_cfg.orig_ctx = o.yarn_orig_ctx;
+ else if (gguf_rope_orig_ctx >= 1) rope_cfg.orig_ctx = gguf_rope_orig_ctx;
+ rope_cfg.freq_scale_in = o.rope_freq_scale;
+ rope_cfg.ext_factor = o.yarn_ext_factor >= 0 ? o.yarn_ext_factor
+ : (rope_cfg.type == RST::YaRN ? 1.0 : 0.0);
+ rope_cfg.attn_factor = o.yarn_attn_factor;
+ rope_cfg.beta_fast = o.yarn_beta_fast;
+ rope_cfg.beta_slow = o.yarn_beta_slow;
+ if (rope_cfg.type == RST::None) {
+ // none is the trained rotation, exactly: the scaling knobs are inert (the table builder and
+ // `kernel_args` ignore them), and resetting them keeps the logged/queried config honest. Only the
+ // frequency base survives - it is the rotation itself, not a scaling knob.
+ const bool knobs = o.rope_scale > 1.0 || o.rope_freq_scale > 0 || o.yarn_ext_factor > 0 ||
+ o.yarn_attn_factor != 1.0;
+ const double base = rope_cfg.freq_base;
+ rope_cfg = strata::kernels::RopeScaling{};
+ rope_cfg.freq_base = base;
+ if (knobs)
+ std::fprintf(stderr, "strata generate: note: no rope scaling is active (none), so --rope-scale, "
+ "--rope-freq-scale and the --yarn-* knobs have no effect\n");
+ }
+ // THE RESOLVED CONFIG IS VALIDATED AS A WHOLE, with the one rule every rotation site also applies
+ // (rope_scaling.hpp): the CLI ranges above cannot see a model-file value, nor a combination such as a
+ // --rope-freq-scale that turns the resolved factor non-finite.
+ if (const char* why = strata::kernels::rope_scaling_invalid(rope_cfg)) {
+ std::fprintf(stderr, "strata generate: invalid rope scaling configuration: %s (type %s, factor %g, "
+ "freq_scale %g, base %g, original context %g)\n",
+ why, rope_cfg.type == RST::YaRN ? "yarn" : rope_cfg.type == RST::Linear ? "linear" : "none",
+ rope_cfg.factor, rope_cfg.freq_scale(), rope_cfg.freq_base, rope_cfg.orig_ctx);
+ return 2;
+ }
+ strata::kernels::rope_scaling_set(rope_cfg);
+ if (rope_cfg.type != RST::None) {
+ const char* tn = rope_cfg.type == RST::YaRN ? "yarn" : "linear";
+ std::fprintf(stderr,
+ "strata generate: rope scaling %s, factor %.6g (freq_scale %.6g, base %.6g, mscale %.6f), "
+ "--max-context %lld against a trained context of %.0f\n",
+ tn, rope_cfg.factor, rope_cfg.freq_scale(), rope_cfg.freq_base, rope_cfg.mscale(),
+ (long long) o.max_context, rope_cfg.orig_ctx);
+ if ((double) o.max_context <= rope_cfg.orig_ctx)
+ std::fprintf(stderr,
+ "strata generate: note: the context is within the trained %.0f - no position needs the "
+ "extension, and the resolved scaling still applies to every angle\n",
+ rope_cfg.orig_ctx);
+ // only when there IS a magnitude correction: YaRN's log term (ext_factor != 0) or an explicit
+ // --yarn-attn-factor; plain linear (mscale 1) has none, and saying otherwise was TODO 22
+ if (rope_cfg.mscale() != 1.0)
+ std::fprintf(stderr,
+ "strata generate: note: the %s magnitude correction scales cos and sin by %.6f "
+ "at every position\n",
+ rope_cfg.type == RST::YaRN ? "YaRN" : "--yarn-attn-factor", rope_cfg.mscale());
+ }
+ }
strata::core::NativeEmbed native_embed;
if (native_pack) {
if (o.native_preset.empty() || o.spec < 2 || o.keep_canonical ||
@@ -1482,7 +1816,7 @@ int main(int argc, char** argv) {
return 2;
}
const strata::core::ModelGeometry g0;
- if (!native_embed.load(o.native_preset, g0.n_embd, 248320, err)) {
+ if (!native_embed.load(o.native_shards, g0.n_embd, 248320, err)) {
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
return 1;
}
@@ -1584,21 +1918,6 @@ int main(int argc, char** argv) {
strata::kernels::mrope_table_set(d_mrope);
}
strata::kernels::ple_set_native_postops(o.native_ple_postops);
- strata::core::ModelGeometry g; // canonical defaults; the model file overrides the MoE shape below
- int64_t K = 10;
- if (!o.native_preset.empty()) {
- // a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10; the model file
- // is the authority on its own MoE shape - everything else in the geometry is unchanged
- try {
- strata::GgufFile model_gguf(o.native_preset);
- if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_count")) g.n_expert = (int64_t) v->u;
- if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_used_count")) K = (int64_t) v->u;
- } catch (const std::exception& e) {
- std::fprintf(stderr, "strata generate: reading the model's expert shape from %s: %s\n",
- o.native_preset.c_str(), e.what());
- return 1;
- }
- }
// before session_init: every graph captured from here on has the vector's kernels where it applies
std::string cvec_summary = "0";
if (!o.cvec_files.empty()) {
@@ -1614,14 +1933,8 @@ int main(int argc, char** argv) {
return 2;
}
- void* sbuf = nullptr;
- if (DPCT_CHECK_ERROR(sbuf = (void *)sycl::malloc_device(
- strata::core::session_bytes(g, o.max_context, K),
- dpct::get_in_order_queue())) != 0) {
- std::fprintf(stderr, "strata generate: session state allocation failed\n");
- return 1;
- }
strata::core::SessionState ss;
+ void* sbuf = nullptr; // allocated after the layer-split search, sized to CUDA0's own layer range (the carve)
// **THE ENGINE RAN ON THE LEGACY DEFAULT STREAM, WHICH ON WDDM IS THE SLOW PATH.** All four session
// calls - `session_capture`, `session_replay`, `session_token` and `session_loop` - were handed `nullptr`,
// i.e. stream 0. `bench/micro/kernel_costs.cu` measures what that costs: EVERY kernel it launches through
@@ -1640,30 +1953,6 @@ int main(int argc, char** argv) {
return 1;
}
void* const main_cs = (void*) main_stream;
- if (strata::core::session_init(g, o.max_context, K, sbuf, ss) == 0) {
- std::fprintf(stderr, "strata generate: session_init failed\n");
- return 1;
- }
- // **A GENERATE RUN ON A NATIVE PACK NEVER ZEROED THE SESSION STATE.** The canonical path zeroes it from
- // `put_input` at position 0 (`session_zero`, with the embedding as `R`), but a native pack breaks out of that
- // loop before the first `put_input` - it runs verify windows instead - and neither the batched prompt path
- // nor the verifier zeroes anything. `sbuf` is `cudaMalloc`'d, so the GDN recurrence, the QSA KV/indexer
- // state, the PLE history and `R` all started from whatever the allocator last held: finite on a fresh
- // allocation and overflow/NaN after reuse, which surfaced as the whole layer stack saturating and every
- // prompt decoding to the same token. `--serve` zeroes exactly this state when `resume == 0`; generate mode
- // always starts from an empty sequence, so it must too.
- // (#167) Every pack, not only a native one: a canonical pack whose prompt goes through the batched prompt path
- // (--prefill) starts at position 0 without a put_input, so it never zeroed the state either.
- strata::core::session_zero(ss, g, nullptr, main_cs);
- if (DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()) !=
- 0) {
- std::fprintf(stderr, "strata generate: zeroing the session state failed\n");
- return 1;
- }
- if (g.n_qsa_layers() > 0 && ss.qsa_states[0].kv_mode == 1)
- std::fprintf(stderr, "strata generate: KV streaming: %lld of %lld cells per QSA layer in VRAM, the K/V in "
- "%.2f GiB of pinned RAM\n", (long long) (ss.qsa_states[0].n_slots * 4),
- (long long) o.max_context, (double) strata::core::qsa_kv_host_bytes() / 1073741824.0);
// ---- **THE HALF-LEVEL DUMP HAS TO BE ARMED BEFORE `session_capture`, AND THE LADDER MUST NOT BE.** The
// half copies are issued from inside `block_layer_pre`/`block_layer_post`, so they are only ever enqueued
@@ -1749,7 +2038,8 @@ int main(int argc, char** argv) {
ss.ple.w.key_scales = (const float*) ((const uint8_t*) wk->data + wk->codes_bytes);
}
if (o.native_ple_key && wk->quantized()) {
- if (!wk->native_data || (wk->native_type != 42 && wk->native_type != 18 && wk->native_type != 23) || !wk->native_q8_1) {
+ if (!wk->native_data || (wk->native_type != 42 && wk->native_type != 18 && wk->native_type != 23 &&
+ wk->native_type != 8) || !wk->native_q8_1) {
std::fprintf(stderr, "strata generate: native PLE key is absent or incompatible\n");
return 1;
}
@@ -1761,13 +2051,28 @@ int main(int argc, char** argv) {
ss.ple.w.norm_key = (const float*) wnk->data;
ss.ple.w.norm_query = (const float*) wnq->data;
ss.ple.w.norm_conv = (const float*) wnc->data;
+ // The conv1d kernel reads F16, so this cast is a claim about the pack's storage. A checkpoint that keeps
+ // the tensor F32 (Q8_0, UD-Q4_K_XL) would hand the kernel the low halves of the f32 words - not an error,
+ // a plausible wrong layer-1 routing. tools/iq_pack.py narrows it (index kind 3); a pack that did not is
+ // refused here (#255, gopinath87607). F16 is index kind 5 or 3 (F16InF32) in a native pack and kind 0
+ // (verbatim 2-byte F16) in the canonical Q2_0 pack; BF16 (kind 4) has the same size and is not F16.
+ const bool f16 = wc->kind == strata::core::WeightKind::F16InF32 ||
+ (wc->kind == strata::core::WeightKind::Verbatim && wc->code_bits == 0);
+ if (!f16 || wc->bytes != (uint64_t) wc->elements * 2) {
+ std::fprintf(stderr, "strata generate: blk.1.ple_conv1d.weight is not stored as F16 (pack index kind %d, "
+ "%llu B for %lld values); the PLE conv1d kernel reads F16 - repack with "
+ "tools/iq_pack.py\n",
+ (int) wc->kind, (unsigned long long) wc->bytes, (long long) wc->elements);
+ return 1;
+ }
ss.ple.w.conv1d_f16 = (const uint16_t*) wc->data;
ss.ple.consts = strata::kernels::ple_artifact_consts();
if (o.ple_delay_us > 0) ple_table.set_injected_delay_us(o.ple_delay_us);
ss.ple.table = &ple_table;
ss.ple.token = &ss.ple_token;
ss.ple.prev = ss.ple_prev;
- ss.ple.hist = ss.ple_hist;
+ // `ss.ple.hist` and the ready() check wait for `session_init`, which carves the history - the session is
+ // now allocated after the layer-split search (see the carve), and the wiring lands there
ss.ple.emb_host = ple_emb_host.data();
if (DPCT_CHECK_ERROR(ple_emb_dev = (float *)sycl::malloc_device(
(size_t)strata::kernels::NG_N_EMBD * 4,
@@ -1780,12 +2085,6 @@ int main(int argc, char** argv) {
}
ss.ple.emb_dev = ple_emb_dev;
ss.ple.scratch = ple_scratch;
- if (!ss.ple.ready()) {
- std::fprintf(stderr, "strata generate: the PLE run is not ready after construction\n");
- return 1;
- }
- std::fprintf(stderr, "strata generate: PLE on, table %llu rows of %s\n",
- (unsigned long long) ple_table.rows(), o.ple_gguf.c_str());
} else {
std::fprintf(stderr,
"strata generate: PLE OFF by explicit --no-ple diagnostic request.\n"
@@ -1803,6 +2102,70 @@ int main(int argc, char** argv) {
return 1;
}
+ // ---- --split-skip-if-fits: before any later stage loads, does CUDA0 alone hold every profiled pair? What it
+ // still has to allocate on one GPU is the whole session (the KV of every layer), the drafter and the head
+ // (kDrafterMib below), the verify windows and the reserve; the prompt path borrows from the cache. If the
+ // profile's pairs fit in what is left, a split would only add the hand-offs: run on CUDA0 alone.
+ if (multi_gpu && split_auto && o.split_skip_if_fits) {
+ std::vector<std::pair<int32_t, int32_t>> prof;
+ int64_t pslots = 0;
+ std::string perr;
+ const bool remote = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0;
+ if (remote || o.expert_profile.empty() ||
+ !strata::core::read_expert_profile(o.expert_profile, g.n_layers, g.n_expert, prof, pslots, perr)) {
+ std::fprintf(stderr, "strata generate: --split-skip-if-fits: %s; the split stays\n",
+ remote ? "remote expert caches are in use" : perr.empty() ? "no expert profile" : perr.c_str());
+ } else {
+ const auto& lay = strata::kernels::cpu::expert_layout();
+ int64_t pairs_bytes = 0;
+ for (const auto& pr : prof)
+ pairs_bytes += native_pack ? ((int64_t) lay.blob_bytes(pr.first) + 255) / 256 * 256 : (int64_t) lay.max_blob;
+ size_t fb = 0, tb = 0;
+ /*
+ DPCT1106: 'cudaMemGetInfo' was migrated with the Intel
+ extensions for device information which may not be supported by all
+ compilers or runtimes. You may need to adjust the code.
+ */
+ dpct::get_current_device().get_memory_info(fb, tb);
+ const int64_t session = (int64_t) strata::core::session_bytes(g, o.max_context, K, 0, g.n_layers);
+ const int64_t held_back = session + (((int64_t) o.vram_reserve_mib + 1000 + 96) << 20); // + drafter/head, windows
+ const int64_t room = (int64_t) fb - held_back;
+ dpct::device_info dp{};
+ dpct::get_device(0).get_device_info(dp);
+ if (pairs_bytes <= room) {
+ std::fprintf(stderr,
+ "strata generate: layer split skipped "
+ "(--split-skip-if-fits): CUDA0 (%s) holds all "
+ "%zu profiled pairs (%.2f GiB) with the session "
+ "(%.2f GiB, %lld-token context), "
+ "the drafter and the reserve: %.2f GiB free, %.2f "
+ "GiB to spare - one GPU\n",
+ dp.get_name(), prof.size(),
+ (double)pairs_bytes / 1073741824.0,
+ (double)session / 1073741824.0,
+ (long long)o.max_context,
+ (double)fb / 1073741824.0,
+ (double)(room - pairs_bytes) / 1073741824.0);
+ multi_gpu = false;
+ split_auto = false;
+ split_devs.clear();
+ split_at.clear();
+ o.layer_split.clear();
+ } else {
+ std::fprintf(stderr,
+ "strata generate: --split-skip-if-fits: CUDA0 "
+ "(%s) would hold only %.2f of the "
+ "profile's %.2f GiB (%.2f GiB free, %.2f GiB for "
+ "the session, drafter and "
+ "reserve): the split stays\n",
+ dp.get_name(),
+ (double)std::max<int64_t>(room, 0) / 1073741824.0,
+ (double)pairs_bytes / 1073741824.0,
+ (double)fb / 1073741824.0,
+ (double)held_back / 1073741824.0);
+ }
+ }
+ }
// ---- layer split across GPUs: each later stage's own copy of the dense weights, its session and (the last) the
// head, made on its device before the host arena is mapped (as the drafter below, for the same WDDM reason)
std::vector<std::unique_ptr<GpuStage>> stages;
@@ -1810,7 +2173,6 @@ int main(int argc, char** argv) {
stages.push_back(std::make_unique<GpuStage>());
GpuStage& st = *stages.back();
st.dev = split_devs[i];
- const bool last = i + 1 == split_devs.size();
double free_gib = 0;
if (!strata::core::RemoteExperts::preflight(st.dev, free_gib, err)) {
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
@@ -1832,18 +2194,14 @@ int main(int argc, char** argv) {
err.c_str());
return 1;
}
- void* sbuf_s = nullptr;
+ // THE SESSION AND THE HEAD WAIT FOR THE SPLIT SEARCH. `session_bytes` prices a stage's session by its
+ // LAYER RANGE (the carve - every stage used to hold all 48 layers' state whatever it ran), so the
+ // sessions are allocated after the search below has set `st.lb`/`st.le`; the last stage's head follows.
+ /*
+ DPCT1025: The SYCL queue is created ignoring the flag and priority
+ options.
+ */
if (DPCT_CHECK_ERROR(
- sbuf_s = (void *)sycl::malloc_device(
- strata::core::session_bytes(g, o.max_context, K),
- dpct::get_in_order_queue())) != 0 ||
- strata::core::session_init(g, o.max_context, K, sbuf_s, st.ss) ==
- 0 ||
- /*
- DPCT1025: The SYCL queue is created ignoring the flag and
- priority options.
- */
- DPCT_CHECK_ERROR(
st.stream = dpct::get_current_device().create_queue(true)) !=
0 ||
/*
@@ -1854,14 +2212,7 @@ int main(int argc, char** argv) {
st.adapt_stream =
dpct::get_current_device().create_queue(true)) != 0 ||
DPCT_CHECK_ERROR(st.adapt_ev = new sycl::event()) != 0) {
- std::fprintf(stderr, "strata generate: layer split, CUDA%d: the session state failed\n", st.dev);
- return 1;
- }
- const strata::core::WeightRef* wo_s = st.wt.find("output.weight");
- if (wo_s == nullptr ||
- (last && !o.native_head_gguf.empty() && !st.head.load(o.native_head_gguf, g.n_embd, wo_s->ne1, err))) {
- std::fprintf(stderr, "strata generate: layer split, CUDA%d head: %s\n", st.dev,
- wo_s == nullptr ? "output.weight is missing" : err.c_str());
+ std::fprintf(stderr, "strata generate: layer split, CUDA%d: its streams failed\n", st.dev);
return 1;
}
// a control vector (the speed projection): its tables on this device too - the stage's layers apply it here
@@ -1904,134 +2255,11 @@ int main(int argc, char** argv) {
runtimes. You may need to adjust the code.
*/
dpct::get_current_device().get_memory_info(fb, tb);
- std::fprintf(stderr, "strata generate: layer split: CUDA%d holds its weights, session%s; %.2f GiB free\n",
- st.dev, last ? " and head" : "", (double) fb / 1073741824.0);
+ std::fprintf(stderr, "strata generate: layer split: CUDA%d holds its weights; %.2f GiB free (its session "
+ "follows the split search)\n", st.dev, (double) fb / 1073741824.0);
}
GpuStage* const last_st = stages.empty() ? nullptr : stages.back().get();
- // Secure MTP's CUDA0 allocations before the large host arena is registered with both CUDA contexts.
- // In particular WDDM can refuse the draft weights after mapping tens of GiB of host pages.
- strata::core::MtpDrafter mtp;
- if (!o.mtp.empty()) {
- if (o.spec < 2) {
- std::fprintf(stderr, "strata generate: --mtp is ignored without --spec T (T >= 2)\n");
- o.mtp.clear();
- }
- if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size());
- // the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned,
- // so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference
- static const strata::core::ModelGeometry draft_geometry{};
- // with a layer split across GPUs the drafter reads the last stage's residual: it lives on that device
- const strata::core::OnDevice on_mtp(last_st ? last_st->dev : -1);
- if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st ? last_st->ss : ss, o.spec, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; }
- }
- // Create the additional contexts after MTP has secured CUDA0 memory, but
- // before the host arena maps its expert pages into their address spaces.
- for (int r = 1; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0 && !early_remote) {
- double free_gib = 0;
- if (!strata::core::RemoteExperts::preflight(remote_dev[r], free_gib, err)) {
- std::fprintf(stderr, "strata generate: %s\n", err.c_str());
- return 1;
- }
- std::fprintf(stderr, "strata generate: CUDA%d context ready, %.2f GiB free before expert arena registration\n",
- remote_dev[r], free_gib);
- }
-
- // ---- the CPU expert pool
- //
- // R2.1: the experts are loaded into a RESIDENT ARENA by default. The mmap path is kept behind
- // `--mmap-experts` because it is the A/B arm, not because it is competitive.
- //
- // The reasoning is the review's C1 and it is now measured on both sides. `FileExpertSource` maps the 34 GB
- // file, and mapped file pages are the first thing the OS reclaims; the engine's rate then depends on whether
- // the standby list happens to hold `experts.bin`, which is why two consecutive runs of the SAME BINARY with
- // the SAME FLAGS measured 71.97 and 34.78 ms/token in the pool (7.54 vs 12.18 tok/s). The arena is
- // anonymous memory the engine owns, and the pool runs at 19.41 ms/token - 1.79x better than the warm mmap
- // and 3.7x better than the cold one.
- //
- // IT IS NOT PINNED, and that is reported rather than hidden: `cudaHostRegister` on 31.64 GiB fails with
- // "out of memory" (you cannot pin 34 of 63 GB) and the arena falls back to 4 KB anonymous pages. That is
- // fine for the CPU pool - which is all that exists today - and NOT fine for Phase 3, whose cache fills and
- // CPU/PCIe miss split need the GPU to DMA out of this arena. Read `note()` when that lands.
- //
- // The earlier "the arena does not fit" conclusion was WRONG and is worth recording: the failure was a stale
- // CUDA error left set by the failed `cudaHostRegister` and read later by `gr_read`'s launch check. See the
- // note in `pinned.cu`.
- strata::core::FileExpertSource src;
- strata::core::ArenaExpertSource arena_src;
- strata::core::GgufExpertSource gguf_src;
- strata::core::ExpertSource* srcp = nullptr;
- if (o.mmap_experts) {
- // FileExpertSource maps the pack's experts.bin: a canonical pack has it; a native (IQ) pack has it when
- // built with `tools/iq_pack.py --experts-bin` (the per-layer blob sizes of its layout, PR #121). The low-RAM
- // mode: the experts come from the file through the OS cache instead of a pinned copy in RAM, for a PC whose
- // GPU holds most of them but whose RAM cannot hold them all.
- if (native_pack && !std::filesystem::exists(std::filesystem::path(o.pack) / "experts.bin")) {
- std::fprintf(stderr, "strata generate: --mmap-experts needs the pack's experts.bin; %s is a native (IQ) pack "
- "built without it: python tools/iq_pack.py --gguf <shard 1> --out %s --experts-bin\n",
- o.pack.c_str(), o.pack.c_str());
- return 2;
- }
- if (!src.open(o.pack, g.n_layers, g.n_expert, err)) {
- std::fprintf(stderr, "strata generate: %s\n", err.c_str());
- return 1;
- }
- std::fprintf(stderr, "strata generate: experts via mmap (--mmap-experts; the A/B arm of R2.1)\n");
- srcp = &src;
- } else if (o.stream_experts) {
- // the SYCL port: a card that holds every expert needs no host copy of them, and a 23 GiB machine cannot
- // hold one. The profile fill reads each blob once from the shard; nothing reads from here afterwards
- // unless a slot is lent to the prefill and refilled.
- if (!native_pack || o.native_preset.empty()) {
- std::fprintf(stderr, "strata generate: --stream-experts needs a native (IQ) pack and --native SHARD1\n");
- return 2;
- }
- if (!gguf_src.open(o.native_preset, g.n_layers, g.n_expert, err)) {
- std::fprintf(stderr, "strata generate: %s\n", err.c_str());
- return 1;
- }
- std::fprintf(stderr, "strata generate: experts streamed from the GGUF on demand (--stream-experts): no host "
- "arena; every expert must fit the VRAM cache\n");
- srcp = &gguf_src;
- } else {
- arena_src.set_gguf(o.native_preset); // plan v0.3 P6: a native pack may take its experts from shard 1
- // On the multi-GPU Windows experiment, start with at most 8 GiB of mapped host pages.
- // Unregistered layers remain in the resident arena and use the CPU expert path.
- // (a layer split across GPUs too: pinning all of it into two contexts leaves WDDM refusing every later
- // allocation - measured on the 5080 + 3090 rig: cudaMemGetInfo and the next cudaMalloc fail)
- const uint64_t pin_limit = (o.expert_cache_remote[0] > 0 || multi_gpu) ? (8ull << 30) : 0;
- if (!arena_src.open(o.pack, g.n_layers, g.n_expert, /*threads=*/6, err, pin_limit)) {
- std::fprintf(stderr, "strata generate: %s\n", err.c_str());
- return 1;
- }
- std::fprintf(stderr, "strata generate: expert arena: %s\n", arena_src.note().c_str());
- std::fprintf(stderr, "strata generate: loaded %.2f GiB at %.2f GiB/s\n",
- (double) strata::kernels::cpu::expert_layout().total / (1024.0 * 1024 * 1024),
- arena_src.load_gib_per_second());
- // A rate under ~0.2 GiB/s is not the hardware. Task Scheduler / service contexts throttle this
- // read+fill about 24x (measured 0.05 vs 1.42 GiB/s for the same binary, args and cache state; the
- // scheduler's defaults - Below normal priority and a least-privilege token - were the only
- // difference between the runs). Say so instead of letting the user blame the disk; see
- // docs/DETAILS.md, "Running it at startup (Task Scheduler)".
-#ifdef _WIN32 // a Windows launch context; elsewhere a load this slow is the disk
- if (arena_src.load_gib_per_second() > 0.0 && arena_src.load_gib_per_second() < 0.2) {
- std::fprintf(stderr,
- "strata generate: hint: ~24x below what this hardware streams from a normal "
- "launch. If Strata is started by Task Scheduler or a service, register the task "
- "with Priority 4 (Normal) and 'Run with highest privileges' - the scheduler's "
- "defaults (Below normal + a least-privilege token) throttle the load. See "
- "docs/DETAILS.md ('Running it at startup').\n");
- }
-#endif
- srcp = &arena_src;
- }
- strata::kernels::cpu::ExpertPool pool(o.pool_workers, /*pin=*/true, /*host_works=*/!o.no_host_worker);
- if (o.no_ple_prefetch) strata::kernels::ple_prefetch_enable(false);
- // ---- R4's slot storage. Allocated AFTER the weights and the session, so `cudaMemGetInfo` inside `open`
- // sees the memory this process actually has left rather than the card's idle figure - and refuses with both
- // numbers if the slots do not fit, instead of handing back a cache smaller than it was asked for.
- mem_mark("the weights, the session and the drafter");
- strata::core::ExpertCache xcache;
std::vector<std::pair<int32_t, int32_t>> profile;
if (!o.expert_profile.empty()) {
int64_t pslots = 0;
@@ -2059,8 +2287,24 @@ int main(int argc, char** argv) {
// 99.53/99.34/99.15%, measured 99.5/99.4/99.0%).
// Up to 3 GPUs every placement is tried; beyond, the layers are shared in proportion to speed.
// STRATA_SPLIT_MISS_MS tunes the miss cost (a slower CPU: higher).
- const int64_t split_pf_mib = o.prefill_chunk > 0 ? 160 + (o.prefill_chunk * 680) / 1024 : 0;
- auto stage_room = [&](int dev, bool later) -> int64_t {
+ // THE PROMPT PATH'S BUFFERS ARE BORROWED FROM THE CACHE, NOT WITHHELD BESIDE IT. With borrowing the cache
+ // is sized first and at full size, and the prompt path is laid out in the tail of it (`Prefill::relayout`),
+ // so it withholds no VRAM of its own and this reserve is zero. Only without borrowing - no profile to fill
+ // a cache from, or --no-prefill-borrow - do the buffers take a reserve, and then this estimate stands in
+ // for buffers that cannot be priced exactly yet because the sessions do not exist. `plan_lend` uses the
+ // exact `Prefill::bytes_needed` as soon as it can.
+ const bool pf_borrow = !o.no_prefill_borrow && !o.expert_profile.empty();
+ const int64_t split_pf_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0;
+ // ---- WHAT A STAGE RESERVES, AND ON WHICH STAGE. The flat 1 GiB this used to withhold from EVERY stage
+ // after the first was booked "for its windows and the drafter", but the windows measure 75 MiB ("window up
+ // to 6 tokens, 74.1 MiB of device buffers", on every boot) and the drafter is loaded on ONE stage - the
+ // last one, which is also the only one that holds the head. On the two identical 8 GB cards that GiB was
+ // the entire difference between CUDA0's cache and CUDA1's: 814 slots against 188, 2026-09-30. Both of
+ // those allocations are already made before a stage's cache is sized, so what has to be held back here is
+ // the windows and - only on the stage that carries them - the drafter and the head.
+ const int64_t kWindowMib = 96; // the verify windows; 75 MiB measured, rounded up
+ const int64_t kDrafterMib = 1000; // the MTP drafter (839 MiB) + the head, on the last stage only
+ auto stage_room = [&](int dev, bool later, bool drafter) -> int64_t {
try {
const strata::core::OnDevice on(dev);
size_t fb = 0, tb = 0;
@@ -2070,7 +2314,8 @@ int main(int argc, char** argv) {
runtimes. You may need to adjust the code.
*/
- const int64_t reserve = ((int64_t) o.vram_reserve_mib + split_pf_mib + (later ? 1024 : 0)) << 20;
+ const int64_t reserve = ((int64_t) o.vram_reserve_mib + split_pf_mib + (later ? kWindowMib : 0) +
+ (drafter ? kDrafterMib : 0)) << 20;
return std::max<int64_t>((int64_t) fb - reserve, 0);
}
catch (sycl::exception const &exc) {
@@ -2086,7 +2331,7 @@ int main(int argc, char** argv) {
std::vector<double> layer_ms((size_t) ns);
for (int i = 0; i < ns; ++i) {
const int dev = i == 0 ? 0 : stages[(size_t) i - 1]->dev;
- cap[(size_t) i] = stage_room(i == 0 ? -1 : dev, i > 0);
+ cap[(size_t) i] = stage_room(i == 0 ? -1 : dev, i > 0, i + 1 == ns);
int sms = 0, khz = 0;
sms = dpct::get_device(dev).get_max_compute_units();
if (DPCT_CHECK_ERROR(
@@ -2101,7 +2346,7 @@ int main(int argc, char** argv) {
std::max(1.0, (double)sms * (double)khz / 1e6); // SMs x GHz
layer_ms[(size_t) i] = 0.33 * (84.0 * 2.617) / speed;
std::fprintf(stderr, "strata generate: layer split auto: CUDA%d %d SMs at %.2f GHz -> %.2f ms per layer, "
- "%.2f GiB for experts\n", dev, sms, khz / 1e6, layer_ms[(size_t) i],
+ "%.2f GiB free before its session carve\n", dev, sms, khz / 1e6, layer_ms[(size_t) i],
(double) cap[(size_t) i] / 1073741824.0);
}
const double miss_ms = std::getenv("STRATA_SPLIT_MISS_MS") ? std::atof(std::getenv("STRATA_SPLIT_MISS_MS")) : 190.0;
@@ -2113,6 +2358,15 @@ int main(int argc, char** argv) {
};
// the predicted window time (ms) of a placement, and the routed mass its caches hold
auto predict = [&](const std::vector<int64_t>& at, double& held_mass, int64_t& held) -> double {
+ // THE CARVE, PRICED: a placement gives stage i the layers [lb, le), and that range's session is a
+ // real cost on its device - subtracted here so the search knows what it leaves for experts. This
+ // is why the sessions are allocated after the search: `session_bytes` is pure arithmetic.
+ std::vector<int64_t> capr((size_t) ns);
+ for (int i = 0; i < ns; ++i) {
+ const int64_t lb = i == 0 ? 0 : at[(size_t) i - 1];
+ const int64_t le = i + 1 < ns ? at[(size_t) i] : g.n_layers;
+ capr[(size_t) i] = cap[(size_t) i] - (int64_t) strata::core::session_bytes(g, o.max_context, K, lb, le);
+ }
std::fill(used.begin(), used.end(), 0);
held_mass = 0;
held = 0;
@@ -2122,7 +2376,7 @@ int main(int argc, char** argv) {
int st = 0;
while (st + 1 < ns && l >= at[(size_t) st]) ++st;
if (full[(size_t) st]) continue;
- if (used[(size_t) st] + cost(l) > cap[(size_t) st]) { full[(size_t) st] = true; continue; } // as the fill
+ if (used[(size_t) st] + cost(l) > capr[(size_t) st]) { full[(size_t) st] = true; continue; } // as the fill
used[(size_t) st] += cost(l);
held_mass += mass[r];
++held;
@@ -2174,24 +2428,233 @@ int main(int argc, char** argv) {
(long long) split_at[i], (long long) (g.n_layers - 1));
return 2;
}
- // the stage that runs a layer (0: CUDA0's)
- auto stage_of = [&](int64_t l) -> int {
- int st = 0;
- while (st < (int) split_at.size() && l >= split_at[(size_t) st]) ++st;
- return st;
- };
- if (multi_gpu) {
- std::vector<std::pair<int32_t, int32_t>> mine;
- for (const auto& pr : profile) {
- const int st = stage_of(pr.first);
- (st == 0 ? mine : stages[(size_t) st - 1]->profile).push_back(pr);
+ // the stage that runs a layer (0: CUDA0's)
+ auto stage_of = [&](int64_t l) -> int {
+ int st = 0;
+ while (st < (int) split_at.size() && l >= split_at[(size_t) st]) ++st;
+ return st;
+ };
+ if (multi_gpu) {
+ std::vector<std::pair<int32_t, int32_t>> mine;
+ for (const auto& pr : profile) {
+ const int st = stage_of(pr.first);
+ (st == 0 ? mine : stages[(size_t) st - 1]->profile).push_back(pr);
+ }
+ profile.swap(mine);
+ for (size_t i = 0; i < stages.size(); ++i) {
+ stages[i]->lb = split_at[i];
+ stages[i]->le = i + 1 < stages.size() ? split_at[i + 1] : g.n_layers;
+ }
+ }
+
+ // ---- CUDA0's session, and the stages' sessions: sized to each device's own layer range (the carve). A
+ // stage that runs [lb, le) carves only those layers' GDN rows and QSA pools - before the carve every stage
+ // held all 48 layers' state whatever layers it ran, which is the same disease the chunked-QSA-prefill PR
+ // fixed in llama.cpp: allocation sized by the whole model instead of the device's own work.
+ {
+ const strata::core::OnDevice on0(0);
+ const int64_t hi0 = multi_gpu ? split_at[0] : -1;
+ if (DPCT_CHECK_ERROR(
+ sbuf = (void *)sycl::malloc_device(
+ strata::core::session_bytes(g, o.max_context, K, 0, hi0),
+ dpct::get_in_order_queue())) != 0) {
+ std::fprintf(stderr, "strata generate: session state allocation failed\n");
+ return 1;
+ }
+ if (strata::core::session_init(g, o.max_context, K, sbuf, ss, 0, hi0) == 0) {
+ std::fprintf(stderr, "strata generate: session_init failed\n");
+ return 1;
+ }
+ if (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1)
+ std::fprintf(stderr, "strata generate: KV streaming: %lld of %lld cells per QSA layer in VRAM, the K/V in "
+ "%.2f GiB of pinned RAM\n",
+ (long long) (ss.qsa_states[ss.qsa_primary()].n_slots * 4),
+ (long long) o.max_context, (double) strata::core::qsa_kv_host_bytes() / 1073741824.0);
+ // the PLE block above built everything but the history, which session_init has just carved
+ ss.ple.hist = ss.ple_hist;
+ // (#167) generate mode starts from an empty sequence, and nothing else zeroes this state before the prompt
+ // path or the verifier reads it (--serve zeroes it per request when nothing is reused)
+ strata::core::session_zero(ss, g, nullptr, main_cs);
+ if (DPCT_CHECK_ERROR(
+ dpct::get_current_device().queues_wait_and_throw()) != 0) {
+ std::fprintf(stderr, "strata generate: zeroing the session state failed\n");
+ return 1;
+ }
+ if (!o.ple_gguf.empty()) {
+ if (!ss.ple.ready()) {
+ std::fprintf(stderr, "strata generate: the PLE run is not ready after construction\n");
+ return 1;
+ }
+ std::fprintf(stderr, "strata generate: PLE on, table %llu rows of %s\n",
+ (unsigned long long) ple_table.rows(), o.ple_gguf.c_str());
+ }
+ }
+ for (size_t i = 0; i < stages.size(); ++i) {
+ GpuStage& st = *stages[i];
+ const strata::core::OnDevice on(st.dev);
+ void* sbuf_s = nullptr;
+ if (DPCT_CHECK_ERROR(sbuf_s = (void *)sycl::malloc_device(
+ strata::core::session_bytes(g, o.max_context,
+ K, st.lb, st.le),
+ dpct::get_in_order_queue())) != 0 ||
+ strata::core::session_init(g, o.max_context, K, sbuf_s, st.ss,
+ st.lb, st.le) == 0) {
+ std::fprintf(stderr, "strata generate: layer split, CUDA%d: the session state failed\n", st.dev);
+ return 1;
+ }
+ const bool last = i + 1 == stages.size();
+ const strata::core::WeightRef* wo_s = st.wt.find("output.weight");
+ if (wo_s == nullptr ||
+ (last && !o.native_head_gguf.empty() && !st.head.load(o.native_head_shards, g.n_embd, wo_s->ne1, err))) {
+ std::fprintf(stderr, "strata generate: layer split, CUDA%d head: %s\n", st.dev,
+ wo_s == nullptr ? "output.weight is missing" : err.c_str());
+ return 1;
+ }
+ size_t fb = 0, tb = 0;
+ /*
+ DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions
+ for device information which may not be supported by all compilers or
+ runtimes. You may need to adjust the code.
+ */
+ dpct::get_current_device().get_memory_info(fb, tb);
+ std::fprintf(stderr, "strata generate: layer split: CUDA%d holds its weights, session [%lld, %lld)%s; "
+ "%.2f GiB free\n", st.dev, (long long) st.lb, (long long) st.le,
+ last ? " and the head" : "", (double) fb / 1073741824.0);
+ }
+
+ // Secure MTP's CUDA0 allocations before the large host arena is registered with both CUDA contexts.
+ // In particular WDDM can refuse the draft weights after mapping tens of GiB of host pages.
+ strata::core::MtpDrafter mtp;
+ if (!o.mtp.empty()) {
+ if (o.spec < 2) {
+ std::fprintf(stderr, "strata generate: --mtp is ignored without --spec T (T >= 2)\n");
+ o.mtp.clear();
+ }
+ if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size());
+ // the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned,
+ // so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference
+ static const strata::core::ModelGeometry draft_geometry{};
+ // with a layer split across GPUs the drafter reads the last stage's residual: it lives on that device
+ const strata::core::OnDevice on_mtp(last_st ? last_st->dev : -1);
+ if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st ? last_st->ss : ss, o.spec, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; }
+ }
+ // Create the additional contexts after MTP has secured CUDA0 memory, but
+ // before the host arena maps its expert pages into their address spaces.
+ for (int r = 1; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0 && !early_remote) {
+ double free_gib = 0;
+ if (!strata::core::RemoteExperts::preflight(remote_dev[r], free_gib, err)) {
+ std::fprintf(stderr, "strata generate: %s\n", err.c_str());
+ return 1;
+ }
+ std::fprintf(stderr, "strata generate: CUDA%d context ready, %.2f GiB free before expert arena registration\n",
+ remote_dev[r], free_gib);
+ }
+
+ // ---- the CPU expert pool
+ //
+ // R2.1: the experts are loaded into a RESIDENT ARENA by default. The mmap path is kept behind
+ // `--mmap-experts` because it is the A/B arm, not because it is competitive.
+ //
+ // The reasoning is the review's C1 and it is now measured on both sides. `FileExpertSource` maps the 34 GB
+ // file, and mapped file pages are the first thing the OS reclaims; the engine's rate then depends on whether
+ // the standby list happens to hold `experts.bin`, which is why two consecutive runs of the SAME BINARY with
+ // the SAME FLAGS measured 71.97 and 34.78 ms/token in the pool (7.54 vs 12.18 tok/s). The arena is
+ // anonymous memory the engine owns, and the pool runs at 19.41 ms/token - 1.79x better than the warm mmap
+ // and 3.7x better than the cold one.
+ //
+ // IT IS NOT PINNED, and that is reported rather than hidden: `cudaHostRegister` on 31.64 GiB fails with
+ // "out of memory" (you cannot pin 34 of 63 GB) and the arena falls back to 4 KB anonymous pages. That is
+ // fine for the CPU pool - which is all that exists today - and NOT fine for Phase 3, whose cache fills and
+ // CPU/PCIe miss split need the GPU to DMA out of this arena. Read `note()` when that lands.
+ //
+ // The earlier "the arena does not fit" conclusion was WRONG and is worth recording: the failure was a stale
+ // CUDA error left set by the failed `cudaHostRegister` and read later by `gr_read`'s launch check. See the
+ // note in `pinned.cu`.
+ strata::core::FileExpertSource src;
+ strata::core::ArenaExpertSource arena_src;
+ strata::core::GgufExpertSource gguf_src;
+ strata::core::ExpertSource* srcp = nullptr;
+ if (o.stream_experts && !o.mmap_experts) {
+ // the SYCL port: a card that holds every expert needs no host copy of them, and a 23 GiB machine cannot
+ // hold one. The profile fill reads each blob once from the shard; nothing reads from here afterwards
+ // unless a slot is lent to the prefill and refilled (the experts no slot holds: the pinned host mirror).
+ if (!native_pack || o.native_preset.empty()) {
+ std::fprintf(stderr, "strata generate: --stream-experts needs a native (IQ) pack and --native SHARD1\n");
+ return 2;
+ }
+ if (!gguf_src.open(o.native_preset, g.n_layers, g.n_expert, err)) {
+ std::fprintf(stderr, "strata generate: %s\n", err.c_str());
+ return 1;
}
- profile.swap(mine);
- for (size_t i = 0; i < stages.size(); ++i) {
- stages[i]->lb = split_at[i];
- stages[i]->le = i + 1 < stages.size() ? split_at[i + 1] : g.n_layers;
+ std::fprintf(stderr, "strata generate: experts streamed from the GGUF on demand (--stream-experts): no host "
+ "arena; every expert must fit the VRAM cache\n");
+ srcp = &gguf_src;
+ } else if (o.mmap_experts) {
+ // FileExpertSource maps the pack's experts.bin: a canonical pack has it; a native (IQ) pack has it when
+ // built with `tools/iq_pack.py --experts-bin` (the per-layer blob sizes of its layout, PR #121). The low-RAM
+ // mode: the experts come from the file through the OS cache instead of a pinned copy in RAM, for a PC whose
+ // GPU holds most of them but whose RAM cannot hold them all.
+ // CS-T: a native pack without experts.bin maps the model's GGUF shards instead (native_experts.txt's spans,
+ // checked against the files first) - no 30-77 GB copy of the experts on the disk
+ src.set_gguf(o.native_preset);
+ if (const char* v = std::getenv("STRATA_FETCH_THREADS"); v != nullptr && std::atoi(v) > 0)
+ src.set_fetch_threads(std::atoi(v));
+ if (!src.open(o.pack, g.n_layers, g.n_expert, err)) {
+ std::fprintf(stderr, "strata generate: %s\n", err.c_str());
+ return 1;
+ }
+ std::fprintf(stderr, "strata generate: experts via mmap (--mmap-experts; %s)\n",
+ src.gguf_mode() ? "the GGUF shards in place, no experts.bin" : "the A/B arm of R2.1");
+ srcp = &src;
+ } else {
+ arena_src.set_gguf(o.native_preset); // plan v0.3 P6: a native pack may take its experts from shard 1
+ // Under WDDM (Windows, WSL2), a multi-GPU run (a layer split, or remote experts) starts with at most 8 GiB of
+ // mapped host pages: pinning all of it into two contexts leaves WDDM refusing every later allocation -
+ // measured on the 5080 + 3090 rig: cudaMemGetInfo and the next cudaMalloc fail. Unregistered layers remain
+ // in the resident arena; their streamed experts go through the pinned staging ring. A Linux driver has no
+ // such limit, so there the whole arena is pinned (#253). STRATA_ARENA_PIN_GIB overrides both ways.
+ const int pin_env = strata::core::arena_pin_cap_gib(); // -1 unset, -2 "auto" (#243, Windows sliced pin)
+ const bool pin_wddm_cap = pin_env < 0 && (o.expert_cache_remote[0] > 0 || multi_gpu) && under_wddm();
+ const uint64_t pin_limit = pin_env >= 0 ? (uint64_t) pin_env << 30 : pin_wddm_cap ? (8ull << 30) : 0;
+ if (pin_env >= 0)
+ std::fprintf(stderr, "strata generate: STRATA_ARENA_PIN_GIB=%d: %s\n", pin_env,
+ pin_env == 0 ? "the whole expert arena is pinned" : "the expert arena's pinning is capped");
+ else if (pin_wddm_cap)
+ std::fprintf(stderr, "strata generate: multi-GPU under WDDM: at most 8 GiB of the expert arena is pinned "
+ "(STRATA_ARENA_PIN_GIB changes it)\n");
+ if (!arena_src.open(o.pack, g.n_layers, g.n_expert, /*threads=*/6, err, pin_limit,
+ o.shared_expert_arena)) {
+ std::fprintf(stderr, "strata generate: %s\n", err.c_str());
+ return 1;
+ }
+ std::fprintf(stderr, "strata generate: expert arena: %s\n", arena_src.note().c_str());
+ std::fprintf(stderr, "strata generate: loaded %.2f GiB at %.2f GiB/s\n",
+ (double) strata::kernels::cpu::expert_layout().total / (1024.0 * 1024 * 1024),
+ arena_src.load_gib_per_second());
+ // A rate under ~0.2 GiB/s is not the hardware. Task Scheduler / service contexts throttle this
+ // read+fill about 24x (measured 0.05 vs 1.42 GiB/s for the same binary, args and cache state; the
+ // scheduler's defaults - Below normal priority and a least-privilege token - were the only
+ // difference between the runs). Say so instead of letting the user blame the disk; see
+ // docs/DETAILS.md, "Running it at startup (Task Scheduler)".
+#ifdef _WIN32 // a Windows launch context; elsewhere a load this slow is the disk
+ if (arena_src.load_gib_per_second() > 0.0 && arena_src.load_gib_per_second() < 0.2) {
+ std::fprintf(stderr,
+ "strata generate: hint: ~24x below what this hardware streams from a normal "
+ "launch. If Strata is started by Task Scheduler or a service, register the task "
+ "with Priority 4 (Normal) and 'Run with highest privileges' - the scheduler's "
+ "defaults (Below normal + a least-privilege token) throttle the load. See "
+ "docs/DETAILS.md ('Running it at startup').\n");
}
+#endif
+ srcp = &arena_src;
}
+ strata::kernels::cpu::ExpertPool pool(o.pool_workers, /*pin=*/true, /*host_works=*/!o.no_host_worker);
+ if (o.no_ple_prefetch) strata::kernels::ple_prefetch_enable(false);
+ // ---- R4's slot storage. Allocated AFTER the weights and the session, so `cudaMemGetInfo` inside `open`
+ // sees the memory this process actually has left rather than the card's idle figure - and refuses with both
+ // numbers if the slots do not fit, instead of handing back a cache smaller than it was asked for.
+ mem_mark("the weights, the session and the drafter");
+ strata::core::ExpertCache xcache;
// THE HEAD BEFORE THE CACHE. The expert cache takes what is free minus the reserve, so everything allocated
// after it comes out of the reserve. The native head (~0.5 GB with IQ3_S) was loaded after it and ate most of
// the 700 MiB: 128K IQ3_S ended with 30 MiB free, the driver paged, and a request stalled for good at its first
@@ -2201,7 +2664,7 @@ int main(int argc, char** argv) {
const int64_t n_vocab = wo->ne1;
strata::core::NativeHead native_head;
if (!o.native_head_gguf.empty() && !multi_gpu) { // a layer split's head is on its last stage
- if (!native_head.load(o.native_head_gguf, g.n_embd, n_vocab, err)) {
+ if (!native_head.load(o.native_head_shards, g.n_embd, n_vocab, err)) {
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
return 1;
}
@@ -2227,9 +2690,9 @@ int main(int argc, char** argv) {
dpct::get_current_device().get_memory_info(free_b, total_b);
// Plan v0.3 P5: the batched prompt path's chunk buffers are allocated later, so they are reserved here -
// under WDDM an over-subscribed allocation does not fail, it pages to system memory and crawls.
- // (with borrowing - the default with a profile - the prompt path lends cache slots instead)
- const bool borrow = !o.no_prefill_borrow && !o.expert_profile.empty();
- const int64_t prefill_mib = (o.prefill_chunk > 0 && !borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0;
+ // (with borrowing - the default with a profile - the prompt path lends cache slots instead; `pf_borrow` is
+ // the predicate a local `borrow` was here, hoisted above so both cache-size branches read the same one)
+ const int64_t prefill_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0;
// the draft layer's head and logits are allocated when it binds, after this: 0.1.27's CJK subset made them
// ~110-180 MiB larger, and out of the reserve they left 16 GB cards below the stall line (#199)
const int64_t mtp_bind = (!o.mtp.empty() && native_head.loaded())
@@ -2245,8 +2708,9 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "strata generate: no VRAM is left for the expert cache: lower --max-context, use "
"--kv k8v4, run images on the CPU, or close other programs that use the GPU\n");
} else if (multi_gpu && o.expert_cache > 0) {
- // a layer split's prompt path has its own buffers (it borrows no slots): an explicit cache size leaves room
- // for them and the reserve, or the first prompt fails with "device buffers ... do not fit"
+ // an explicit cache size leaves room for the prompt path's buffers and the reserve, or the first prompt
+ // fails with "device buffers ... do not fit" (with borrowing - the default with a profile - the path lends
+ // slots instead and `prefill_mib` is 0, so only the reserve is checked)
size_t free_b = 0, total_b = 0;
/*
DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions
@@ -2254,7 +2718,7 @@ int main(int argc, char** argv) {
runtimes. You may need to adjust the code.
*/
dpct::get_current_device().get_memory_info(free_b, total_b);
- const int64_t prefill_mib = o.prefill_chunk > 0 ? 160 + (o.prefill_chunk * 680) / 1024 : 0;
+ const int64_t prefill_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0;
const int64_t reserve = ((int64_t) o.vram_reserve_mib + prefill_mib) << 20;
const int64_t fit = std::max<int64_t>(((int64_t) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob, 0);
if (o.expert_cache > fit) {
@@ -2497,18 +2961,12 @@ int main(int argc, char** argv) {
"STRATA_MIRROR_MIB or the free RAM, or lower --max-context\n", (long long) unmirrored_misses);
}
- if (o.resident_cpu_experts) {
- if (!src.pin_cache_complement(xcache, err, /*pin=*/false)) {
- std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str());
- return 1;
- }
- std::fprintf(stderr, "strata generate: steady-state CPU cache misses are resident in ordinary RAM; borrowed cache entries may use mmap during prompt prefill\n");
- }
-
for (auto& stp : stages) {
GpuStage& st = *stp;
const auto& lay = strata::kernels::cpu::expert_layout();
- const int64_t room = stage_room(st.dev, true);
+ // the drafter and the head are already allocated by now (they load above, before this), so what is left
+ // to hold back is the windows - and `free_b` has already lost the drafter.
+ const int64_t room = stage_room(st.dev, true, false);
const strata::core::OnDevice on(st.dev);
std::vector<int64_t> sized;
int64_t used = 0;
@@ -2645,6 +3103,40 @@ int main(int argc, char** argv) {
drive.d.src = srcp;
drive.d.n_expert = g.n_expert;
drive.d.jobs.resize((size_t) K);
+ // CS-T: routing-aware prefetch of the file tier (the GGUF in place): the next layer's router on this layer's MoE
+ // input predicts its experts and their pages are warmed meanwhile. It only warms pages; STRATA_LOOKAHEAD=0 is
+ // the A/B arm, STRATA_LOOKAHEAD_K the experts per token (default 10).
+ strata::core::RouterLookahead lookahead;
+ if (srcp == &src && src.warms() && [] { const char* v = std::getenv("STRATA_LOOKAHEAD"); return v == nullptr || std::atoi(v) != 0; }()) {
+ std::vector<std::vector<uint16_t>> routers((size_t) g.n_layers);
+ bool ok = true;
+ for (int64_t l = 0; l < g.n_layers && ok; ++l) {
+ const strata::core::WeightRef* w = wt.find("blk." + std::to_string(l) + ".ffn_gate_inp.weight");
+ ok = w != nullptr && w->kind == strata::core::WeightKind::Bf16InF32 &&
+ w->bytes == (uint64_t) (g.n_expert * g.n_embd) * 2;
+ if (!ok) break;
+ routers[(size_t) l].resize((size_t) (g.n_expert * g.n_embd));
+ ok = DPCT_CHECK_ERROR(dpct::get_in_order_queue()
+ .memcpy(routers[(size_t)l].data(),
+ w->data, (size_t)w->bytes)
+ .wait()) == 0;
+ }
+ const char* kv = std::getenv("STRATA_LOOKAHEAD_K");
+ if (ok && lookahead.start(std::move(routers), g.n_embd, g.n_expert, kv ? std::atoi(kv) : 10, &src, err)) {
+ drive.d.lookahead = &lookahead;
+ 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
+ with 0. You need to rewrite this code.
+ */
+ (void)0;
+ std::fprintf(stderr, "strata generate: routing-aware prefetch off (%s)\n",
+ ok ? err.c_str() : "the routers are not BF16 in the arena");
+ err.clear();
+ }
+ }
// ---- R4.2c: THE HIT PATH. Every one of these is required for `hits_ready()`, which is all-or-nothing on
// purpose: a half-configured hit path would compute some experts twice and others not at all, and a token
// built on that is wrong rather than refused.
@@ -2783,7 +3275,11 @@ int main(int argc, char** argv) {
// ---- the graphs
strata::core::SessionGraphs gr;
if (!o.no_capture && !native_pack) { // plan v0.3 P6: a native pack runs verify windows only
- if (!strata::core::session_capture(wt, g, ss, d_parts, gr, err, /*split=*/o.gpu_stages)) {
+ // a layer split's CUDA0 session owns only [0, split_at[0]), so its graphs cover that range; the
+ // whole-model replay paths (`session_loop`, the plain generate loop) refuse rather than read another
+ // stage's state - a split runs its layers on the stages' verifiers (serve) or prefill stage chain
+ if (!strata::core::session_capture(wt, g, ss, d_parts, gr, err, /*split=*/o.gpu_stages, 0,
+ multi_gpu ? split_at[0] : -1)) {
std::fprintf(stderr, "strata generate: session_capture: %s\n", err.c_str());
return 1;
}
@@ -3344,7 +3840,7 @@ int main(int argc, char** argv) {
(long long) resident);
}
if (!o.no_capture && !o.no_token_graph && layer_dump == nullptr && half_dump == nullptr &&
- (hit_fn == nullptr || thits.on()) && !native_pack) {
+ (hit_fn == nullptr || thits.on()) && !native_pack && !multi_gpu) { // a split's token graph cannot span stages
if (!strata::core::session_capture_token(wt, g, ss, d_parts, loop_scratch.y_miss, loop_scratch.parts_bytes,
tgraph, err, thits.on() ? &thits : nullptr)) {
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
@@ -3411,11 +3907,8 @@ int main(int argc, char** argv) {
}
return k;
};
- auto lend_bytes = [&](int32_t first) -> uint64_t {
- return xcache.slot_offsets() ? (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[first])
- : (uint64_t) (xcache.slots() - first) *
- (uint64_t) strata::kernels::cpu::expert_layout().max_blob;
- };
+ // `lend_bytes` went with the single-cache serve loan: a participant's loan is priced by `part_bytes` from its
+ // OWN cache, and the only other user of the old helper was the serve path's own relayout.
auto request_chunk = [](int64_t tokens, int64_t max_chunk) -> int64_t {
if (tokens <= 0 || max_chunk <= 0) return 0;
const int64_t rounded = tokens > std::numeric_limits<int64_t>::max() - 255
@@ -3428,16 +3921,17 @@ int main(int argc, char** argv) {
// lent slot's expert is streamed during the prompt and refilled after it; measured on a 12 GB card, 32K Q2_0
// prompt: 4096 791 tok/s, 6144 878, 8192 973 with 69% of the slots lent). A request lends only what its own
// prompt needs (Prefill::relayout), so a big chunk costs short prompts nothing. 0 = none fits.
+ // at 8192-token chunks nearly every expert streams anyway, so a lent slot costs little: 90% when the
+ // copies are DMA from pinned RAM (Q2_0 8192 + a 384-slot ring: 1283 tok/s), 85% when host copies are the
+ // limit (lending more only streams more through them). STRATA_PREFILL_LEND_PCT overrides (tuning).
+ // Hoisted out of plan_lend: the serve path's per-stage loans obey the same cap, one participant at a time.
+ const int64_t kAutoLendPct = [] {
+ const char* v = std::getenv("STRATA_PREFILL_LEND_PCT");
+ return v ? (int64_t) std::atoi(v)
+ : (int64_t) (strata::prefill::Prefill::pinned_share() >= 0.9 ? 90 : 85);
+ }();
auto plan_lend = [&](int64_t& chunk) -> int64_t {
static constexpr int64_t kAutoChunks[] = {8192, 6144, 4096, 3072, 2048, 1024, 512, 256};
- // at 8192-token chunks nearly every expert streams anyway, so a lent slot costs little: 90% when the
- // copies are DMA from pinned RAM (Q2_0 8192 + a 384-slot ring: 1283 tok/s), 85% when host copies are the
- // limit (lending more only streams more through them). STRATA_PREFILL_LEND_PCT overrides (tuning).
- const int64_t kAutoLendPct = [] {
- const char* v = std::getenv("STRATA_PREFILL_LEND_PCT");
- return v ? (int64_t) std::atoi(v)
- : (int64_t) (strata::prefill::Prefill::pinned_share() >= 0.9 ? 90 : 85);
- }();
auto slots_for = lend_slots;
if (o.prefill_auto) {
for (const int64_t c : kAutoChunks) {
@@ -3452,6 +3946,43 @@ int main(int argc, char** argv) {
}
return 0;
};
+ // ---- the resident RAM mode (--resident-experts / --resident-cpu-experts): the experts the GPU cache does not
+ // hold are copied from experts.bin into RAM once, so no decode or prompt step reads the file (the plain mmap
+ // mode reads them through the OS file cache, which a small-RAM PC keeps giving back to the SSD). Built here,
+ // after the prompt path's lend plan is known: the slots it may lend (the cache's last ones) have their experts
+ // streamed during a prompt and copied back after it, so those are kept in RAM too as far as RAM allows. The
+ // bytes are the file's bytes and the placement is the same, so the answers are the plain mmap mode's; the
+ // share-of-pinned figure above (which sizes the prompt path) is left as the mmap mode's for the same reason.
+ if (o.resident_cpu_experts) {
+ int64_t lend_from = -1;
+ if (o.prefill_chunk > 0 && !o.no_prefill_borrow && d_res != nullptr && xcache.slots() > 0) {
+ int64_t chunk = o.prefill_chunk;
+ const int64_t k = plan_lend(chunk);
+ if (k > 0) lend_from = xcache.slots() - k;
+ }
+ if (src.pin_cache_complement(xcache, err, o.resident_pin, {}, lend_from, o.resident_headroom,
+ o.resident_budget, &profile)) {
+ if (o.adapt_every > 0 && o.adapt_swaps > 0 &&
+ !src.reserve_exchanges(std::min<int64_t>(o.adapt_swaps, 96), err)) {
+ std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str());
+ return 1;
+ }
+ std::fprintf(stderr, "strata generate: resident RAM mode: %.2f GiB of experts in RAM (%s), %lld in the GPU "
+ "cache; adaptive swaps %s\n",
+ (double) src.resident_bytes() / 1073741824.0,
+ src.complement_pinned() ? "page-locked" : src.locked_bytes() > 0 ? "locked" : "pageable",
+ (long long) xcache.resident(),
+ o.adapt_every > 0 && o.adapt_swaps > 0 ? "exchange them with the GPU cache (no file reads)"
+ : "off");
+ } else if (o.resident_soft) {
+ std::fprintf(stderr, "strata generate: WARNING: the resident RAM mode does not fit (%s); the experts the "
+ "GPU does not hold are read from the model folder through the OS file cache "
+ "(--mmap-experts), which is slower when the RAM cannot keep them\n", err.c_str());
+ } else {
+ std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str());
+ return 1;
+ }
+ }
if (o.serve) {
if (o.spec < 2 || o.mtp.empty() || o.prefill_chunk <= 0 ||
(graph_hits && (thits.d_res == nullptr || host_res.empty()))) {
@@ -3463,48 +3994,239 @@ int main(int argc, char** argv) {
void* borrow = nullptr;
uint64_t borrow_bytes = 0;
int32_t lend_first = -1; // the first slot the prompt path may borrow (its largest chunk)
- int32_t lend_first_now = -1; // where its buffers are laid out now
- // a cache too small to lend the prompt path its buffers would make it allocate them on top - on a card the
- // cache already filled to its reserve, that is the over-subscription the auto sizing avoids - so the
- // prompt chunk is halved until its buffers fit in the lendable slots (a smaller chunk only reads slower)
- if (!o.no_prefill_borrow && d_res != nullptr) {
- int64_t chunk = o.prefill_chunk;
- if (const int64_t k = plan_lend(chunk); k > 0) {
+ // ---- WHO BORROWS, AND FROM WHOSE CACHE. One entry per prompt path: CUDA0's (layers [0, split_at[0]),
+ // which is the whole model without a split) borrowing the tail of CUDA0's cache, then one per stage
+ // borrowing the tail of ITS OWN cache. A loan is sized by the exact `Prefill::bytes_needed` for the
+ // chunk, is laid out by `Prefill::relayout`, and is refilled before any window reads - so outside the
+ // prompt the whole cache is expert cache. THIS IS THE POINT OF THE STRUCT: the loan used to exist only
+ // for CUDA0, and `no_prefill_borrow` made every stage instead withhold a chunk-sized reserve from its
+ // cache for the entire session, which is what cost the 4-way its context (see the note at the top of the
+ // layer-split block). A stage may only lend the rows for ITS OWN layers: `host_res` is one table whose
+ // slot values are indices into whichever cache owns the layer, so a loan that marked rows by slot number
+ // alone would hand CUDA0 a slot belonging to another stage's cache.
+ struct PfPart {
+ strata::core::ExpertCache* cache = nullptr;
+ const strata::core::SessionState* ses = nullptr;
+ strata::prefill::Prefill* sp = nullptr;
+ int dev = -1; // -1: leave the device alone (CUDA0)
+ int64_t lb = 0, le = 0; // the layers whose rows this cache holds - the only rows it may lend
+ int32_t first = -1; // the first slot it may lend, for the chunk that was chosen
+ int32_t first_now = -1; // where its buffers are laid out now
+ int64_t lent_chunk = 0;
+ std::vector<std::pair<int32_t, int32_t>> lent;
+ };
+ auto part_slots = [&](const PfPart& p, int64_t c) -> int64_t {
+ const uint64_t need = strata::prefill::Prefill::bytes_needed(g, *p.ses, c);
+ strata::core::ExpertCache& xc = *p.cache;
+ if (xc.slot_offsets() != nullptr) { // sized slots: from the end until they hold `need`
+ int64_t k = 0;
+ while (k < xc.slots() &&
+ (uint64_t) (xc.bytes() - (int64_t) xc.slot_offsets()[xc.slots() - k]) < need) ++k;
+ return k;
+ }
+ const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;
+ return (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob);
+ };
+ auto part_bytes = [&](const PfPart& p, int32_t first) -> uint64_t {
+ strata::core::ExpertCache& xc = *p.cache;
+ return xc.slot_offsets() ? (uint64_t) (xc.bytes() - (int64_t) xc.slot_offsets()[first])
+ : (uint64_t) (xc.slots() - first) *
+ (uint64_t) strata::kernels::cpu::expert_layout().max_blob;
+ };
+ std::vector<PfPart> pf_parts;
+ // a cache too small to lend the prompt path its buffers would make it allocate them on top - on a card
+ // whose cache already filled its reserve, that is the over-subscription the auto sizing avoids - so the
+ // chunk is the largest one EVERY participant can lend (a smaller chunk only reads slower)
+ if (pf_borrow && d_res != nullptr) {
+ pf_parts.push_back({&xcache, &ss, &sp, -1, 0, multi_gpu ? split_at[0] : g.n_layers, -1, -1, 0, {}});
+ for (auto& st : stages)
+ pf_parts.push_back({&st->cache, &st->ss, &st->sp, st->dev, st->lb, st->le, -1, -1, 0, {}});
+ // The two tests plan_lend makes for CUDA0 alone, one participant at a time: a loan must leave the
+ // 128-slot floor. The percentage cap is an AUTO-chunk rule and only the auto scan applies it - an
+ // explicit --prefill is the operator's number, and a loan of it only has to fit. With one participant
+ // (no split) this reduces to plan_lend exactly, so the single-GPU loan is unchanged from main.
+ auto fits = [&](int64_t c, bool cap) -> bool {
+ for (const PfPart& p : pf_parts) {
+ const int64_t k = part_slots(p, c);
+ if (k <= 0 || k + 128 > p.cache->slots()) return false;
+ if (cap && k * 100 > kAutoLendPct * p.cache->slots()) return false;
+ }
+ return true;
+ };
+ static constexpr int64_t kAutoChunks[] = {8192, 6144, 4096, 3072, 2048, 1024, 512, 256};
+ int64_t chunk = 0;
+ if (o.prefill_auto) {
+ for (const int64_t c : kAutoChunks)
+ if (fits(c, true)) { chunk = c; break; }
+ } else {
+ for (int64_t c = o.prefill_chunk; c >= 256; c /= 2)
+ if (fits(c, false)) { chunk = c; break; }
+ }
+ if (chunk > 0) {
if (o.prefill_auto)
std::fprintf(stderr, "strata serve: prompt chunk auto: %lld tokens\n", (long long) chunk);
else if (chunk != o.prefill_chunk)
- std::fprintf(stderr, "strata serve: prompt chunk %lld -> %lld tokens so its buffers fit in the "
- "expert cache\n", (long long) o.prefill_chunk, (long long) chunk);
+ std::fprintf(stderr, "strata serve: prompt chunk %lld -> %lld tokens so its buffers fit in "
+ "every expert cache\n", (long long) o.prefill_chunk, (long long) chunk);
o.prefill_chunk = chunk;
- lend_first = (int32_t) (xcache.slots() - k);
- lend_first_now = lend_first;
+ for (PfPart& p : pf_parts) {
+ p.first = (int32_t) (p.cache->slots() - part_slots(p, chunk));
+ p.first_now = p.first;
+ }
+ lend_first = pf_parts[0].first;
borrow = xcache.device_slot(lend_first);
- borrow_bytes = xcache.slot_offsets()
- ? (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[lend_first])
- : (uint64_t) k * (uint64_t) strata::kernels::cpu::expert_layout().max_blob;
+ borrow_bytes = part_bytes(pf_parts[0], lend_first);
} else if (o.prefill_auto) {
o.prefill_chunk = 1024; // nothing lendable: small buffers of its own
+ } else if (pf_parts.size() > 1) {
+ // An explicit chunk no stage can lend in full. main falls back to the prompt path's own buffers
+ // here and so do we, rather than refusing to start - but say what every stage has, because a split
+ // stage that has to allocate these on top of a cache that already filled its VRAM will not fit,
+ // and `init` would otherwise report only that the buffers do not fit.
+ std::fprintf(stderr, "strata serve: no stage can lend the prompt path its %lld-token buffers, so "
+ "each stage allocates its own:\n", (long long) o.prefill_chunk);
+ for (const PfPart& p : pf_parts)
+ std::fprintf(stderr, "strata serve: CUDA%d has %lld slots, and a %lld-token chunk needs "
+ "the last %lld of them\n", p.dev < 0 ? 0 : p.dev,
+ (long long) p.cache->slots(), (long long) o.prefill_chunk,
+ (long long) part_slots(p, o.prefill_chunk));
}
} else if (o.prefill_auto && d_res == nullptr) {
o.prefill_chunk = 1024; // #85: no expert cache at all (a full 8 GB card): small buffers of its own
}
- if (borrow != nullptr)
- std::fprintf(stderr, "strata serve: the prompt path borrows %lld cache slots (%.2f GiB)\n",
+ if (borrow != nullptr) {
+ std::fprintf(stderr, "strata serve: the prompt path borrows %lld CUDA0 cache slots (%.2f GiB)\n",
(long long) (xcache.slots() - lend_first), (double) borrow_bytes / 1073741824.0);
- else
+ for (size_t i = 1; i < pf_parts.size(); ++i) // one loan per stage, from that stage's own cache
+ std::fprintf(stderr, "strata serve: CUDA%d prompt path borrows %lld of its %lld slots (%.2f GiB)\n",
+ pf_parts[i].dev, (long long) (pf_parts[i].cache->slots() - pf_parts[i].first),
+ (long long) pf_parts[i].cache->slots(),
+ (double) part_bytes(pf_parts[i], pf_parts[i].first) / 1073741824.0);
+ } else {
std::fprintf(stderr, "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)\n");
- // layer split across GPUs: a prompt path per stage, each handing its chunk's rows to the next
- for (size_t i = 0; i < stages.size(); ++i) {
- GpuStage& st = *stages[i];
- st.sp.set_stage(st.lb, i + 1 < stages.size() ? st.le : -1, i + 1 < stages.size() ? &stages[i + 1]->sp : nullptr);
- const strata::core::OnDevice on(st.dev);
- if (!st.sp.init(st.wt, g, st.ss, srcp, &st.cache, host_res.data(), o.prefill_chunk, (void*) st.stream, err)) {
- std::fprintf(stderr, "strata serve: layer split, CUDA%d prompt path: %s\n", st.dev, err.c_str());
- return 1;
+ }
+ // layer split across GPUs: a prompt path per stage, each handing its chunk's rows to the next.
+ // THE CHUNK STEPS DOWN INSTEAD OF EXITING. A split's stage caches are sized after the arena is registered, and
+ // the prompt path's own buffers (no loan) are not priced into them: with the whole arena pinned (#253) a
+ // `--prefill auto` split could stop at start with "device buffers for a chunk of 2048 tokens do not fit". A
+ // chunk that does not fit is tried again one size smaller, down to 512 tokens (a smaller chunk only reads slower).
+ auto init_prompt_paths = [&]() -> int { // 0: ready; 1: failed (err set); 2: failed with "do not fit"
+ for (size_t i = 0; i < stages.size(); ++i) {
+ GpuStage& st = *stages[i];
+ st.sp.set_stage(st.lb, i + 1 < stages.size() ? st.le : -1, i + 1 < stages.size() ? &stages[i + 1]->sp : nullptr);
+ const strata::core::OnDevice on(st.dev);
+ void* sb = nullptr; // this stage's own loan, out of its own cache
+ uint64_t sbb = 0;
+ // `first < 0`: no loan was taken (nothing was lendable), so this stage allocates its own buffers
+ if (i + 1 < pf_parts.size() && pf_parts[i + 1].first >= 0) {
+ sb = st.cache.device_slot(pf_parts[i + 1].first);
+ sbb = part_bytes(pf_parts[i + 1], pf_parts[i + 1].first);
+ }
+ if (!st.sp.init(st.wt, g, st.ss, srcp, &st.cache, host_res.data(), o.prefill_chunk, (void*) st.stream,
+ err, sb, sbb)) {
+ err = "layer split, CUDA" + std::to_string(st.dev) + " prompt path: " + err;
+ return err.find("do not fit") != std::string::npos ? 2 : 1;
+ }
+ }
+ if (multi_gpu) sp.set_stage(0, split_at[0], &stages[0]->sp);
+ if (!sp.init(wt, g, ss, srcp, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes))
+ return err.find("do not fit") != std::string::npos ? 2 : 1;
+ return 0;
+ };
+ static constexpr int64_t kStepChunks[] = {6144, 4096, 3072, 2048, 1536, 1024, 512};
+ {
+ // First by arithmetic: a prompt path without a loan allocates its buffers, so the chunk must leave
+ // headroom on that device (a chunk that fits to the last MiB left hipBLAS nothing: its GEMMs then
+ // failed to launch on gfx1201 and the prompt hung). `bytes_needed` is the same count `init` makes.
+ const int64_t kHeadroom = 512ll << 20;
+ auto own_fits = [&](int64_t c, int &dev_out, int64_t &need_out,
+ int64_t &free_out) -> bool {
+ try {
+ for (size_t i = 0; i <= stages.size(); ++i) {
+ const bool loan = i == 0 ? borrow != nullptr : (i < pf_parts.size() && pf_parts[i].first >= 0);
+ if (loan) continue;
+ const int dev = i == 0 ? -1 : stages[i - 1]->dev;
+ const strata::core::OnDevice on(dev);
+ size_t fb = 0, tb = 0;
+ /*
+ DPCT1106: 'cudaMemGetInfo' was migrated with the Intel
+ extensions for device information which may not be supported
+ by all compilers or runtimes. You may need to adjust the
+ code.
+ */
+ dpct::get_current_device().get_memory_info(fb, tb);
+ const int64_t need = (int64_t) strata::prefill::Prefill::bytes_needed(g, i == 0 ? ss : stages[i - 1]->ss, c);
+ if (need + kHeadroom > (int64_t) fb) {
+ dev_out = dev < 0 ? 0 : dev; need_out = need; free_out = (int64_t) fb;
+ return false;
+ }
+ }
+ return true;
+ }
+ catch (sycl::exception const &exc) {
+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__
+ << ", line:" << __LINE__ << std::endl;
+ std::exit(1);
+ }
+ };
+ int dev = 0;
+ int64_t need = 0, fb = 0;
+ if (!own_fits(o.prefill_chunk, dev, need, fb)) {
+ int64_t c = 0;
+ for (const int64_t s : kStepChunks) {
+ int d2 = 0;
+ int64_t n2 = 0, f2 = 0;
+ if (s < o.prefill_chunk && own_fits(s, d2, n2, f2)) { c = s; break; }
+ }
+ if (c > 0) {
+ std::fprintf(stderr, "strata serve: a %lld-token chunk's prompt buffers need %lld MiB on CUDA%d, "
+ "%lld MiB free: %lld-token chunks\n", (long long) o.prefill_chunk,
+ (long long) (need >> 20), dev, (long long) (fb >> 20), (long long) c);
+ o.prefill_chunk = c;
+ }
}
}
- if (multi_gpu) sp.set_stage(0, split_at[0], &stages[0]->sp);
- if (!sp.init(wt, g, ss, srcp, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes)) {
+ for (;;) {
+ const int r = init_prompt_paths();
+ if (r == 0) break;
+ int64_t next = 0;
+ for (const int64_t c : kStepChunks)
+ if (c < o.prefill_chunk) { next = c; break; }
+ if (r == 2 && next > 0) {
+ std::fprintf(stderr, "strata serve: %s: trying a %lld-token chunk\n", err.c_str(), (long long) next);
+ // start the prompt paths over (a failed init may hold buffers), and consume the failed allocation's
+ // error: it is sticky, and the next launch check would report "out of memory" for a kernel
+ for (auto& stp : stages) {
+ 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.
+ */
+ (void)0;
+ }
+ 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.
+ */
+ (void)0;
+ o.prefill_chunk = next;
+ if (borrow != nullptr) { // smaller loans for the smaller chunk
+ for (PfPart& p : pf_parts)
+ if (p.first >= 0) {
+ p.first = (int32_t) (p.cache->slots() - part_slots(p, next));
+ p.first_now = p.first;
+ }
+ lend_first = pf_parts[0].first;
+ borrow = xcache.device_slot(lend_first);
+ borrow_bytes = part_bytes(pf_parts[0], lend_first);
+ }
+ err.clear();
+ continue;
+ }
std::fprintf(stderr, "strata serve: %s\n", err.c_str());
if (err.find("fit") != std::string::npos) // #85: say what frees VRAM
std::fprintf(stderr, "strata serve: the GPU has too little free VRAM for the prompt path: turn images "
@@ -3648,6 +4370,69 @@ int main(int argc, char** argv) {
std::vector<ConvCheckpoint> checks;
uint64_t check_clock = 0; // the checkpoints' LRU clock; creation and every use advance it
bool cvec_cached = true; // the control vector's state the live session and the checkpoints were read with
+ strata::core::ConversationCache conversations(
+ o.prompt_cache > 0 ? (size_t) o.conversation_cache_mib * 1024 * 1024 : 0,
+ (size_t) o.conversation_cache_slots);
+ // Save only on a switch/rewind, not on each continuing request. No graph
+ // addresses change: all parked images live in ordinary host vectors.
+ auto park_current = [&](size_t held) -> bool {
+ if (!conversations.enabled() || !live_ok || live.empty()) return true;
+ const strata::core::ConversationView view{live, live_imgs, checks, cvec_cached};
+ auto reuse = conversations.take_reuse();
+ size_t estimate = 0;
+ if (!strata::core::conversation_snapshot_bytes(view, ss, g, mtp.kv_state(), estimate, err)) {
+ std::fprintf(stderr, "strata serve: conversation cache: skip parking (%s)\n", err.c_str());
+ err.clear(); // A recoverable miss must not poison the batched draft prefill's error channel.
+ return true;
+ }
+ const size_t fresh_estimate = estimate;
+ if (!reuse.kv.empty() && !strata::core::conversation_snapshot_capture_bytes(
+ reuse, view, ss, g, mtp.kv_state(), estimate, err)) {
+ reuse = {};
+ estimate = fresh_estimate;
+ err.clear();
+ }
+ if (!reuse.kv.empty() && !conversations.can_fit(estimate, held)) {
+ // Optional growth capacity must not evict useful conversations.
+ reuse = {};
+ estimate = fresh_estimate;
+ }
+ if (!conversations.make_room(estimate, held)) {
+ std::fprintf(stderr, "strata serve: conversation cache: skip parking (snapshot %zu MiB exceeds available budget)\n",
+ estimate >> 20);
+ return true;
+ }
+ const auto t0 = Clock::now();
+ try {
+ const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib * 1024 * 1024;
+ const size_t additional = estimate - reuse.bytes();
+ if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(),
+ additional, floor)) {
+ std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor, or telemetry unavailable)\n",
+ additional >> 20, (long long) o.conversation_cache_min_free_mib);
+ return true;
+ }
+ strata::core::SavedConversation image;
+ size_t reused_bytes = 0;
+ if (!strata::core::conversation_snapshot_save(image, view, ss, g, mtp.kv_state(), err,
+ std::move(reuse), &reused_bytes)) return false;
+ if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), 0, floor)) {
+ std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM floor after capture, or telemetry unavailable)\n");
+ return true;
+ }
+ const size_t snapshot_bytes = image.bytes();
+ const bool stored = conversations.put(std::move(image), held);
+ std::fprintf(stderr, "strata serve: conversation cache: %s %zu tokens in %.1f ms; parked=%zu bytes=%zu evictions=%zu snapshot_bytes=%zu reused_kv_bytes=%zu\n",
+ stored ? "parked" : "skipped", live.size(),
+ std::chrono::duration<double, std::milli>(Clock::now() - t0).count(),
+ conversations.size(), conversations.bytes(), conversations.evictions(), snapshot_bytes, reused_bytes);
+ } catch (const std::bad_alloc&) {
+ // The active state has not been touched. Continue with normal
+ // prompt processing rather than killing a serving process.
+ std::fprintf(stderr, "strata serve: conversation cache: allocation failed; skip parking\n");
+ }
+ return true;
+ };
int64_t pp_total = 0, pp_from = 0, pp_next_check = 0;
Clock::time_point pp_t0 = Clock::now();
auto imgs_below = [&](const std::vector<ImgKey>& all, int64_t L) {
@@ -3678,6 +4463,8 @@ int main(int argc, char** argv) {
c.gdn = std::move((*parts)[0].gdn);
c.ple = std::move((*parts)[0].ple);
c.tails = std::move((*parts)[0].tails);
+ c.dead = std::move((*parts)[0].dead);
+ c.block_pos = std::move((*parts)[0].block_pos);
for (size_t i = 1; i < parts->size(); ++i) c.stage_parts.push_back(std::move((*parts)[i]));
} else {
if (DPCT_CHECK_ERROR(
@@ -3687,6 +4474,7 @@ int main(int argc, char** argv) {
for (auto& st : stages) { // a layer split's later stages: their sessions' part
const strata::core::OnDevice on(st->dev);
ConvCheckpoint part;
+ part.ids = c.ids;
if (DPCT_CHECK_ERROR(dpct::get_current_device()
.queues_wait_and_throw()) != 0 ||
!checkpoint_save(part, st->ss, g)) return false;
@@ -3717,6 +4505,9 @@ int main(int argc, char** argv) {
// E-9: batched through the prompt path when it can (one GPU: a layer split's drafter is on the last stage)
const bool batched = !multi_gpu && sp.draft_kv(mtp, R_rows, nxt.data(), T, p0, e);
if (!e.empty() || (!batched && !mtp.prefill(R_rows, nxt.data(), T, p0, e))) return false;
+ if (std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr)
+ std::fprintf(stderr, "strata serve: DRAFT_PREFILL path=%s mode=%d cells=%lld\n",
+ batched ? "batched" : "token", mtp.kv_state().kv_mode, (long long) T);
// progress for the server window: PP <position reached> <prompt tokens> <ms> <fresh tokens/s>
const int64_t done = p0 + T;
const double ms = std::chrono::duration<double, std::milli>(Clock::now() - pp_t0).count();
@@ -3756,6 +4547,7 @@ int main(int argc, char** argv) {
if (o.prompt_cache <= 0 || o.prompt_cache_every <= 0 || done < part_next[i]) return true;
part_next[i] = done + o.prompt_cache_every;
ConvCheckpoint part; // this stage's state at `done` (its stream is synchronized)
+ part.ids.assign(cur.begin(), cur.begin() + done);
if (!checkpoint_save(part, stage_ss, g)) { e = "saving a checkpoint part failed"; return false; }
std::lock_guard<std::mutex> lk(part_mu);
auto& v = part_at[done];
@@ -3825,6 +4617,7 @@ int main(int argc, char** argv) {
sycl::info::event_command_status::complete) return;
}
for (auto& st : stages) st->adapt_live = false;
+ src.commit_exchanges(); // the resident RAM mode: the evicted experts take their places in RAM
for (const auto& [i, slot] : pending) host_res[(size_t) i] = slot;
pending.clear();
res_upload();
@@ -3862,6 +4655,7 @@ int main(int argc, char** argv) {
}
std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; });
if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps);
+ if (!resident_stage_swaps(src, xcache, host_res, g.n_expert, swaps, adapt_stream)) return false;
bool main_live = false;
for (const Swap& s : swaps) {
const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out;
@@ -3994,16 +4788,38 @@ int main(int argc, char** argv) {
compilers or runtimes. You may need to adjust the code.
*/
dpct::get_current_device().get_memory_info(free_b, total_b);
- std::printf("INFO context=%lld kv=%s kv_resident=%lld expert_slots=%lld expert_cache_mib=%lld spec=%d "
+ // "Experts in VRAM" is every tier, not one card's. This used to report `xcache` alone, so a layer split
+ // showed CUDA0's cache as if it were the whole GPU's: a 4-GPU 256K run read 3327 experts when the four
+ // cards held 13320, and the Monitor tab was wrong by 4x for every multi-GPU config. The tiers are
+ // disjoint by construction (remote_experts.cpp skips any pair a stage already claimed), so they add.
+ const int64_t slots_primary = (int64_t) xcache.slots();
+ const int64_t mib_primary = (int64_t) (xcache.bytes() >> 20);
+ int64_t slots_all = slots_primary, mib_all = mib_primary;
+ for (const auto& st : stages) {
+ slots_all += (int64_t) st->cache.slots();
+ mib_all += (int64_t) (st->cache.bytes() >> 20);
+ }
+ for (int r = 0; r < 3; ++r)
+ if (o.expert_cache_remote[(size_t) r] > 0) {
+ slots_all += remote_experts[(size_t) r].resident();
+ mib_all += (int64_t) (remote_experts[(size_t) r].gib() * 1024.0);
+ }
+ std::printf("INFO context=%lld kv=%s kv_resident=%lld expert_slots=%lld expert_cache_mib=%lld "
+ "expert_slots_primary=%lld expert_cache_primary_mib=%lld spec=%d "
"mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s arena_mib=%lld pool_workers=%d pcie_frac=%.2f "
- "spec_min_p=%.2f engine=" STRATA_VERSION "\n",
+ "spec_min_p=%.2f conversation_cache_mib=%lld conversation_cache_slots=%d "
+ "conversation_cache_min_free_mib=%lld engine=" STRATA_VERSION "\n",
(long long) o.max_context, o.kv.c_str(),
- (long long) (g.n_qsa_layers() > 0 && ss.qsa_states[0].kv_mode == 1
- ? ss.qsa_states[0].n_slots * 4 : 0),
- (long long) xcache.slots(), (long long) (xcache.bytes() >> 20), o.spec, o.mtp_max_t,
+ (long long) (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1
+ ? ss.qsa_states[ss.qsa_primary()].n_slots * 4 : 0),
+ (long long) slots_all, (long long) mib_all,
+ (long long) slots_primary, (long long) mib_primary,
+ o.spec, o.mtp_max_t,
o.suffix_draft, (long long) (free_b >> 20), cvec_summary.c_str(),
- (long long) (strata::kernels::cpu::expert_layout().total >> 20), pool.workers(), o.pcie_frac,
- o.spec_min_p);
+ (long long) ((o.mmap_experts ? src.resident_bytes() : strata::kernels::cpu::expert_layout().total) >> 20),
+ pool.workers(), o.pcie_frac,
+ o.spec_min_p, (long long) o.conversation_cache_mib, o.conversation_cache_slots,
+ (long long) o.conversation_cache_min_free_mib);
}
// issue #29: a request whose heartbeat (tokens, prompt chunks, verify windows) stops for this long is stuck on
// a flag nobody will raise - end the engine with where it was, so the server starts it again instead of the
@@ -4023,10 +4839,11 @@ int main(int argc, char** argv) {
const uint64_t b = p.beats.load();
if (!p.busy.load() || b != last) { last = b; ticks_at = p.ticks.load(); since = now; continue; }
if (now - since < std::chrono::seconds(limit)) continue;
- std::fprintf(stderr, "strata serve: no progress for %d s during a request (%s %lld) - stopping "
+ std::fprintf(stderr, "strata serve: no progress for %d s during a request (%s) - stopping "
"the engine so the server starts it again (issue #29)\n",
- limit, p.where.load(), (long long) p.detail.load());
+ limit, stage_text().c_str());
stall_report(stderr, p.ticks.load() - ticks_at);
+ strata::core::release_gpu_waits(stderr); // #267: no spin kernel outlives the process
std::fflush(stderr);
std::abort();
}
@@ -4236,12 +5053,17 @@ int main(int argc, char** argv) {
std::array<int64_t, 3> remote_before{};
std::array<int64_t, 3> launches_before{};
std::array<uint64_t, 3> compact_before{}, full_before{};
+ // ms_begin/ms_wait are cumulative since boot; the log line used to print them next to per-request deltas,
+ // so the host time read as if it belonged to this request. Take deltas here like every other column.
+ std::array<double, 3> begin_before{}, wait_before{};
for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0)
{
remote_before[(size_t) r] = remote_experts[(size_t) r].computed();
launches_before[(size_t) r] = remote_experts[(size_t) r].launched_layers();
compact_before[(size_t) r] = remote_experts[(size_t) r].returned_bytes();
full_before[(size_t) r] = remote_experts[(size_t) r].full_row_bytes();
+ begin_before[(size_t) r] = remote_experts[(size_t) r].ms_begin();
+ wait_before[(size_t) r] = remote_experts[(size_t) r].ms_wait();
}
cur = ids;
const Clock::time_point r0 = Clock::now();
@@ -4254,20 +5076,10 @@ int main(int argc, char** argv) {
if ((int32_t) ids[(size_t) i] != pre[(size_t) i]) return false;
return imgs_below(req_imgs, L) == pre_imgs;
};
- // the control vector for this request. The live session and the checkpoints were read one way, so a
- // switch reads the prompt again from the start
- if (strata::kernels::cvec().loaded()) {
- const bool want = req_cvec != 0;
- if (want != cvec_cached) {
- live_ok = false;
- checks.clear();
- cvec_cached = want;
- }
- strata::kernels::cvec_set_enabled(want);
- }
+ const bool want_cvec = strata::kernels::cvec().loaded() ? req_cvec != 0 : true;
int64_t resume = 0;
bool from_live = false;
- if (o.prompt_cache > 0) {
+ if (o.prompt_cache > 0 && want_cvec == cvec_cached) {
if (live_ok && starts_with(live, live_imgs)) { resume = (int64_t) live.size(); from_live = true; }
for (const ConvCheckpoint& c : checks)
if ((int64_t) c.ids.size() > resume && starts_with(c.ids, c.imgs)) {
@@ -4275,6 +5087,63 @@ int main(int argc, char** argv) {
from_live = false;
}
}
+ const auto parked = conversations.best(ids, req_imgs, want_cvec);
+ std::optional<strata::core::SavedConversation> incoming;
+ if (parked.tokens > resume) incoming.emplace(conversations.take(parked.index));
+ // Reject the entire image before parking/overwriting the outgoing
+ // state. Invalid entries can safely fall back to its existing prefix.
+ if (incoming && !strata::core::conversation_snapshot_validate(*incoming, ss, g, mtp.kv_state(), err)) {
+ std::fprintf(stderr, "strata serve: conversation cache: discard invalid snapshot (%s)\n", err.c_str());
+ incoming.reset();
+ err.clear();
+ }
+ // Preserve the outgoing branch before any checkpoint rewind, reset,
+ // or incoming restore overwrites the positional state it requires.
+ if ((!from_live || incoming) && !park_current(incoming ? incoming->bytes() : 0)) {
+ std::printf("ERR %s\n", err.c_str());
+ return 1;
+ }
+ if (incoming) {
+ const auto t0 = Clock::now();
+ if (strata::core::conversation_snapshot_restore(*incoming, ss, g, mtp.kv_state(), err) !=
+ strata::core::ConversationRestore::restored) {
+ // Already prevalidated above: a failure here is fatal, never
+ // permission to decode from a partially restored session.
+ std::printf("ERR restoring parked conversation: %s\n", err.c_str());
+ return 1;
+ }
+ if (std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) {
+ uint64_t draft_hash = 0;
+ if (!strata::core::conversation_kv_verify(incoming->kv.back(), mtp.kv_state(), g,
+ int64_t(incoming->live.ids.size()), false, draft_hash, err)) {
+ std::printf("ERR verifying restored draft KV: %s\n", err.c_str());
+ return 1;
+ }
+ std::fprintf(stderr, "strata serve: SNAPSHOT_VERIFY draft=%016llx cells=%lld mode=%d source=%s resident=%lld\n",
+ (unsigned long long) draft_hash, (long long) incoming->kv.back().cells,
+ mtp.kv_state().kv_mode, "ram",
+ (long long) (mtp.kv_state().n_slots * strata::kernels::qsa_real_shapes().page_size));
+ }
+ live = std::move(incoming->live.ids);
+ live_imgs = std::move(incoming->live.imgs);
+ checks = std::move(incoming->checkpoints);
+ cvec_cached = incoming->cvec;
+ resume = parked.tokens;
+ from_live = parked.live;
+ if (std::getenv("STRATA_SNAPSHOT_FULL_CAPTURE") == nullptr)
+ conversations.retain(std::move(incoming->kv), int64_t(live.size()));
+ incoming.reset(); // Running-state/checkpoint copies are no longer needed.
+ std::fprintf(stderr, "strata serve: conversation cache: restored %lld tokens (%s) in %.1f ms; parked=%zu bytes=%zu\n",
+ (long long) resume, from_live ? "live" : "checkpoint",
+ std::chrono::duration<double, std::milli>(Clock::now() - t0).count(),
+ conversations.size(), conversations.bytes());
+ }
+ if (want_cvec != cvec_cached) {
+ live_ok = false;
+ checks.clear();
+ cvec_cached = want_cvec;
+ }
+ if (strata::kernels::cvec().loaded()) strata::kernels::cvec_set_enabled(want_cvec);
// this request rewrites every cell from `resume` on, so a checkpoint past it (or not on this prompt's
// path) no longer has its cells; the ones kept are prefixes of both the old tokens and the new
checks.erase(std::remove_if(checks.begin(), checks.end(), [&](const ConvCheckpoint& c) {
@@ -4330,6 +5199,7 @@ int main(int argc, char** argv) {
tr("request", n, geni ? 1 : 0);
mtp.set_prompt_len(n);
const int64_t read_from = reread_to > 0 ? 0 : resume;
+ conversations.limit_reuse(read_from);
pp_total = n;
pp_from = read_from;
pp_t0 = r0;
@@ -4381,6 +5251,20 @@ int main(int argc, char** argv) {
if (drive.d.failed && drive.d.fail) e = drive.d.fail;
return false;
}
+ // STRATA_LOGPOS=<path>: the teacher-forced log-probability of every token read here (every
+ // token is committed and nxt[t] is the prompt's own next token), appended to <path>; the last
+ // column is the log-probability of STRATA_LOGPOS_EXTRA (default 248046, <|im_end|>), so the
+ // end-of-turn mass a chat model puts on raw text can be taken out of the measurement
+ static std::FILE* logpos = [] {
+ const char* p = std::getenv("STRATA_LOGPOS");
+ return p != nullptr ? std::fopen(p, "ab") : nullptr;
+ }();
+ static const int32_t logpos_extra = [] {
+ const char* p = std::getenv("STRATA_LOGPOS_EXTRA");
+ return p != nullptr ? (int32_t) std::atoi(p) : (int32_t) 248046;
+ }();
+ if (logpos != nullptr && !ver.window_logprobs(nxt.data(), T, q, logpos_extra, logpos, e))
+ return false;
if (!ver.commit(T, e) || !mtp.prefill(ver.final_R_all(), nxt.data(), T, q, e)) return false;
q += T;
}
@@ -4393,76 +5277,75 @@ int main(int argc, char** argv) {
};
// the batched path's slots are lent just before its first run and given back (refilled) before a window
// reads - so the windows always see the whole expert cache - or once the prompt is read
- std::vector<std::pair<int32_t, int32_t>> lent_now;
- int64_t lent_chunk = 0; // the chunk the lent slots hold the prompt path's buffers for
- auto refill = [&](std::string &e) -> bool {
- try {
- if (lent_now.empty()) return true;
- tr("refill start", (long long) lent_now.size());
- for (const auto& [i, slot] : lent_now) { // D-4: queued, one wait (STRATA_REFILL_BLOCKING=1: each)
+ // Every participant gives its loan back here: the rows it lent are refilled into the SAME slots from
+ // the arena, the residency table is restored, and one upload puts it on every device. A stage refills
+ // through its own cache and its own device - a slot refilled into the wrong cache would leave that
+ // stage's cache holding an expert it does not own, which is silent and produces plausible tokens.
+ auto refill_one = [&](PfPart& p, std::string& e) -> bool {
+ if (p.lent.empty()) return true;
+ tr("refill start", (long long) p.lent.size());
+ const strata::core::OnDevice on(p.dev);
+ for (const auto& [i, slot] : p.lent) { // D-4: queued, one wait (STRATA_REFILL_BLOCKING=1: each)
const uint8_t* b = srcp->blob(i / g.n_expert, i % g.n_expert);
const int64_t nb = (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(i / g.n_expert);
- if (b == nullptr || !(refill_blocking() ? xcache.fill_slot_blocking(slot, b, e, nb)
- : xcache.fill_slot_queued(slot, b, e, nb)))
+ if (b == nullptr || !(refill_blocking() ? p.cache->fill_slot_blocking(slot, b, e, nb)
+ : p.cache->fill_slot_queued(slot, b, e, nb)))
return false;
host_res[(size_t) i] = slot;
}
- if (!xcache.sync_queued(e)) return false;
- dpct::get_in_order_queue()
- .memcpy(d_res, host_res.data(),
- host_res.size() * sizeof(int32_t))
- .wait();
- lent_now.clear();
- lent_chunk = 0;
+ if (!p.cache->sync_queued(e)) return false;
+ p.lent.clear();
+ p.lent_chunk = 0;
+ return true;
+ };
+ auto refill = [&](std::string& e) -> bool {
+ bool any = false;
+ for (PfPart& p : pf_parts)
+ if (!p.lent.empty()) { any = true; if (!refill_one(p, e)) return false; }
+ if (any) res_upload();
return true;
- }
- catch (sycl::exception const &exc) {
- std::cerr << exc.what() << "Exception caught at file:" << __FILE__
- << ", line:" << __LINE__ << std::endl;
- std::exit(1);
- }
};
// lend the slots `tokens` batched prompt tokens need: the prompt path's buffers for min(chunk, tokens
- // rounded up to 256), laid out in the last of the slots it may borrow
- auto lend = [&](int64_t tokens, std::string &e) -> bool {
- try {
- if (lend_first < 0) return true; // its own buffers: nothing to lend
+ // rounded up to 256), laid out in the last of the slots it may borrow - per participant, out of that
+ // participant's own cache, and marking only that participant's own layers
+ auto lend = [&](int64_t tokens, std::string& e) -> bool {
+ if (pf_parts.empty()) return true; // its own buffers: nothing to lend
+ // what this segment needs, capped by the configured chunk: a request lends only what its own
+ // prompt needs, so a large chunk costs a short prompt nothing
const int64_t want = request_chunk(tokens, o.prefill_chunk);
if (want <= 0) {
e = "prefill: cannot lend buffers for an empty request segment";
return false;
}
- if (!lent_now.empty()) {
- if (want <= lent_chunk) return true;
- if (!refill(e)) return false;
- }
- const int64_t slots = lend_slots(want);
- if (slots <= 0 || slots > xcache.slots() - lend_first) {
- e = "prefill: request-sized buffers exceed the configured lend region";
- return false;
- }
- const int32_t first = std::max<int32_t>(lend_first, (int32_t) (xcache.slots() - slots));
- if (want != sp.chunk() || first != lend_first_now) {
- if (!sp.relayout(want, xcache.device_slot(first), lend_bytes(first), e)) return false;
- lend_first_now = first;
- }
- for (size_t i = 0; i < host_res.size(); ++i)
- if (host_res[i] >= first) {
- lent_now.emplace_back((int32_t) i, host_res[i]);
- host_res[i] = strata::core::kNotResident;
+ bool any = false;
+ for (PfPart& p : pf_parts) {
+ if (p.first < 0) continue;
+ if (!p.lent.empty()) {
+ if (want <= p.lent_chunk) continue; // its current loan already covers this
+ // ONLY this participant's loan goes back: `refill` would return the other participants'
+ // loans too, and their buffers are still laid out in their caches - marking those slots
+ // resident again would hand the next window a prompt buffer in place of an expert
+ if (!refill_one(p, e)) return false;
}
- dpct::get_in_order_queue()
- .memcpy(d_res, host_res.data(),
- host_res.size() * sizeof(int32_t))
- .wait();
- lent_chunk = want;
+ const strata::core::OnDevice on(p.dev);
+ const int32_t first = std::max<int32_t>(p.first, (int32_t) (p.cache->slots() - part_slots(p, want)));
+ if (want != p.sp->chunk() || first != p.first_now) {
+ if (!p.sp->relayout(want, p.cache->device_slot(first), part_bytes(p, first), e)) return false;
+ p.first_now = first;
+ }
+ for (int64_t l = p.lb; l < p.le; ++l) // THIS participant's layers only
+ for (int64_t ex = 0; ex < g.n_expert; ++ex) {
+ const size_t i = (size_t) (l * g.n_expert + ex);
+ if (host_res[i] >= first) {
+ p.lent.emplace_back((int32_t) i, host_res[i]);
+ host_res[i] = strata::core::kNotResident;
+ any = true;
+ }
+ }
+ p.lent_chunk = want;
+ }
+ if (any) res_upload();
return true;
- }
- catch (sycl::exception const &exc) {
- std::cerr << exc.what() << "Exception caught at file:" << __FILE__
- << ", line:" << __LINE__ << std::endl;
- std::exit(1);
- }
};
apply_pending(true);
// per-request sampling for the verify window's head (greedy when temperature is absent)
@@ -4480,6 +5363,7 @@ int main(int argc, char** argv) {
req_sp.penalty_present = req_penalty_present;
req_sp.counter = 0;
ver.set_sampling(req_sp);
+ mtp.set_draft_sampling(req_sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise)
drive.d.pcie_num = std::max(0, std::min(256, (int) (req_pcie_frac * 256.0 + 0.5)));
// a layer split: CUDA0's share as asked; a later GPU keeps its own (its link) unless the request sets one
for (int st = 0; st < split_drive.n; ++st)
@@ -4600,6 +5484,9 @@ int main(int argc, char** argv) {
double dt_run = 0, dt_commit = 0, dt_draft = 0;
int64_t dec_windows = 0, dec_T = 0;
const int64_t decode_hits0 = drive.d.cache_hits;
+ // CS-T: the RAM and file tiers of this request (the mmap source; 0 with the arena)
+ const int64_t ram0 = src.ram_reads(), files0 = src.file_reads();
+ const uint64_t file_bytes0 = src.file_read_bytes();
const int64_t decode_look0 = drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused;
if (cancelled) finish = "cancel";
while (!cancelled && produced_n < max_new) {
@@ -4678,6 +5565,10 @@ int main(int argc, char** argv) {
std::fflush(stdout);
++rounds;
const Clock::time_point tw2 = Clock::now();
+ // coupled drafts with penalties: the next window's row-0 history (`consumed` holds this window's
+ // commit, outv[a] is its row 0) - the drafts extend it on the device as the verify rows will
+ if (hist_n > 0 && mtp.coupled() && !eos && produced_n < max_new)
+ mtp.set_draft_history(consumed.data(), (int64_t) consumed.size(), outv[(size_t) a]);
const bool drafted = eos || produced_n >= max_new ||
mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) req_spec_min_p);
{
@@ -4730,20 +5621,39 @@ int main(int argc, char** argv) {
if (state_hash && live_ok) {
// DEBUG: a fingerprint of every part of the session over the positions it holds ([0, L)), and
// separately of what lies past them in the last KV page (stale cells, fine unless something reads them)
- dpct::get_current_device().queues_wait_and_throw();
+ if (DPCT_CHECK_ERROR(
+ dpct::get_current_device().queues_wait_and_throw()) !=
+ 0) {
+ std::printf("ERR synchronizing state fingerprint\n");
+ return 1;
+ }
const int64_t L = (int64_t) live.size();
const strata::kernels::QsaShapes qs = [&] {
strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();
s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_dim = g.idx_key_dim;
return s;
}();
+ bool hash_ok = true;
+ std::array<uint8_t, 65536> hash_buffer;
auto hash_dev = [&](const void *p, size_t bytes, uint64_t h) {
try {
- std::vector<uint8_t> b(bytes);
- if (bytes) dpct::get_in_order_queue()
- .memcpy(b.data(), p, bytes)
- .wait(); // VRAM or a streamed host copy
- return fnv1a(b.data(), b.size(), h);
+ for (size_t offset = 0; hash_ok && offset < bytes;) {
+ const size_t n = std::min(hash_buffer.size(), bytes - offset);
+ // VRAM or a streamed host copy, with fixed diagnostic workspace.
+ if (DPCT_CHECK_ERROR(
+ dpct::get_in_order_queue()
+ .memcpy(hash_buffer.data(),
+ static_cast<const uint8_t *>(p) +
+ offset,
+ n)
+ .wait()) != 0) {
+ hash_ok = false;
+ break;
+ }
+ h = fnv1a(hash_buffer.data(), n, h);
+ offset += n;
+ }
+ return h;
}
catch (sycl::exception const &exc) {
std::cerr << exc.what()
@@ -4763,20 +5673,24 @@ int main(int argc, char** argv) {
}
return h;
};
- const ConvStateSizes z = conv_state_sizes(g);
+ const ConvStateSizes z = conv_state_sizes(g, ss);
uint64_t h_gdn = hash_dev(ss.gdn_state, z.gdn, 1469598103934665603ull);
- if (std::getenv("STRATA_STATE_HASH_GDN") != nullptr) { // per GDN layer: which one differs first
- const size_t per = z.gdn / (size_t) g.n_gdn_layers();
+ if (std::getenv("STRATA_STATE_HASH_GDN") != nullptr && ss.gdn_alloc > 0) { // per GDN layer: which one differs first
+ const size_t per = z.gdn / (size_t) ss.gdn_alloc;
std::string s;
char b[8];
- for (int64_t i = 0; i < g.n_gdn_layers(); ++i) {
+ for (int64_t i = 0; i < ss.gdn_alloc; ++i) {
std::snprintf(b, sizeof(b), "%04llx ", (unsigned long long) (hash_dev((const uint8_t*) ss.gdn_state + i * per, per, 1469598103934665603ull) & 0xffff));
s += b;
}
std::fprintf(stderr, "strata serve: STATE_HASH_GDN %s\n", s.c_str());
}
- uint64_t h_ple = hash_dev(ss.ple_hist, z.ple, 1469598103934665603ull);
+ uint64_t h_ple = hash_dev(ss.ple_hist, ss.ple_hist ? z.ple : 0, 1469598103934665603ull);
uint64_t h_tail = 1469598103934665603ull, h_pool = h_tail, h_kv = h_tail, h_stale = h_tail;
+ // pooled= keeps its 0.1.29 meaning: the completed rows [0, L / idx_block) only. pooled_full= adds the
+ // spare row at L / idx_block (the `dead` key the next block completion overwrites), which a
+ // conversation restore writes back; dead= is the spare key itself
+ uint64_t h_dead = h_tail, h_pool_full = h_tail;
const int64_t kvb = qs.head_dim, scb = (qs.head_dim / 64) * 2;
// a state's K/V arrays and their bytes per (cell, head) row: the host copy when it has one
auto kv_arrays = [&](const strata::core::QsaState& st) {
@@ -4789,18 +5703,24 @@ int main(int argc, char** argv) {
const int64_t q4b = (int64_t) strata::kernels::kv_q4_bytes_per_head((int) qs.head_dim);
a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q4 : st.v_q4, q4b},
{h ? st.host.k_scale : st.k_scale, scb}};
- } else {
+ } else if (st.kv_int8) {
a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q : st.v_q, kvb},
{h ? st.host.k_scale : st.k_scale, scb}, {h ? st.host.v_scale : st.v_scale, scb}};
+ } else {
+ a = {{h ? st.host.k_pool : st.k_pool, qs.head_dim * 2},
+ {h ? st.host.v_pool : st.v_pool, qs.head_dim * 2}};
}
return a;
};
const int64_t end_cell = std::min<int64_t>(((L + qs.page_size - 1) / qs.page_size) * qs.page_size,
- ss.qsa_states[0].max_cells);
- for (int64_t i = 0; i < g.n_qsa_layers(); ++i) {
- const strata::core::QsaState& st = ss.qsa_states[i];
+ ss.max_cells); // = the primary state's max_cells
+ for (int64_t j = 0; j < ss.qsa_alloc; ++j) { // this session's owned QSA ordinals only
+ const strata::core::QsaState& st = ss.qsa_states[ss.qsa_ord0 + j];
h_tail = hash_dev(st.idx_tail, z.tail, h_tail);
+ h_dead = hash_dev(st.idx_dead, z.dead, h_dead);
h_pool = hash_dev(st.idx_pooled, (size_t) (L / qs.idx_block) * qs.idx_dim * 4, h_pool);
+ h_pool_full = hash_dev(st.idx_pooled, (size_t) (L > 0 ? L / qs.idx_block + 1 : 0) * qs.idx_dim * 4,
+ h_pool_full);
// KV streaming: the host copy is the identity layout and holds every cell
for (const auto& [pool, w] : kv_arrays(st)) {
h_kv = hash_cells(pool, w, 0, L, h_kv);
@@ -4812,18 +5732,26 @@ int main(int argc, char** argv) {
const int64_t mL = std::min<int64_t>(L, ms.max_cells);
for (const auto& [pool, w] : kv_arrays(ms))
if (pool != nullptr) h_mtp = hash_cells(pool, w, 0, mL, h_mtp);
+ if (!hash_ok) {
+ std::printf("ERR reading state fingerprint\n");
+ return 1;
+ }
std::fprintf(stderr, "strata serve: STATE_HASH L=%lld gdn=%016llx ple=%016llx tail=%016llx pooled=%016llx "
- "kv=%016llx mtp=%016llx stale=%016llx ple_prev=%d,%d\n", (long long) L,
+ "kv=%016llx mtp=%016llx stale=%016llx dead=%016llx pooled_full=%016llx ple_prev=%d,%d\n", (long long) L,
(unsigned long long) h_gdn, (unsigned long long) h_ple, (unsigned long long) h_tail,
(unsigned long long) h_pool, (unsigned long long) h_kv, (unsigned long long) h_mtp,
- (unsigned long long) h_stale, ss.ple_prev[0], ss.ple_prev[1]);
+ (unsigned long long) h_stale, (unsigned long long) h_dead,
+ (unsigned long long) h_pool_full, ss.ple_prev[0], ss.ple_prev[1]);
}
const int64_t req_hits = drive.d.cache_hits - decode_hits0;
const int64_t req_look = (drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused) - decode_look0;
// DONE <generated> <prompt> <prompt ms> <decode ms> <finish> <drafts accepted> <drafts offered> <reused> [hits] [lookups]
- std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld\n", (long long) produced_n, (long long) n, prompt_ms,
- decode_ms, finish, (long long) draft_accepted, (long long) draft_offered, (long long) resume,
- (long long) req_hits, (long long) req_look);
+ // [RAM blobs] [file blobs] [file MB] (CS-T tiers; appended, so an older server reads the rest)
+ std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f\n", (long long) produced_n,
+ (long long) n, prompt_ms, decode_ms, finish, (long long) draft_accepted, (long long) draft_offered,
+ (long long) resume, (long long) req_hits, (long long) req_look,
+ (long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0),
+ (double) (src.file_read_bytes() - file_bytes0) / 1e6);
std::fflush(stdout);
if (drive.routing != nullptr) std::fflush(drive.routing); // the routing trace survives a crash and is watchable mid-session
const int64_t fresh = n - resume;
@@ -4840,6 +5768,19 @@ int main(int argc, char** argv) {
100.0 * (double) req_hits / (double) req_look,
(long long) req_hits, (long long) req_look);
}
+ // the resident RAM mode, cumulative: experts read from experts.bin since the copy was made (what the plain
+ // mmap mode reads through the OS file cache, from the SSD when the RAM could not keep it)
+ if (src.complement_ready())
+ std::fprintf(stderr, "strata serve: resident RAM: %.2f GiB of experts in RAM, %lld exchanged with the "
+ "VRAM tier, %lld blob reads from the file\n",
+ (double) src.resident_bytes() / 1073741824.0, (long long) src.exchanges(),
+ (long long) src.file_reads());
+ // CS-T: the tiers, cumulative - GPU cache hits (the decode lookups above), RAM copy, files (SSD / OS cache)
+ if (srcp == &src)
+ std::fprintf(stderr, "strata serve: expert tiers: GPU %lld hits this request; since the start RAM %lld blobs, files %lld blobs "
+ "%.1f MB read%s\n", (long long) req_hits, (long long) src.ram_reads(),
+ (long long) src.file_reads(), (double) src.file_read_bytes() / 1e6,
+ src.gguf_mode() ? " (the GGUF in place)" : "");
// STRATA_SPLIT_TIMING: where each verify stage's host time went, cumulative per window since the start
// (waiting for its GPU to ring a layer, the CPU pool and plan per layer, staging the window)
if (static const bool st_timing = std::getenv("STRATA_SPLIT_TIMING") != nullptr; st_timing)
@@ -4850,12 +5791,14 @@ int main(int argc, char** argv) {
"pool + plan %.3f ms, host staging %.3f ms, commit %.3f ms\n", st,
(long long) v.windows, v.ms_wait / w, v.ms_pool / w, v.ms_host / w, v.ms_commit / w);
}
- if (g.n_qsa_layers() > 0 && ss.qsa_states[0].kv_mode == 1) {
+ if (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1) {
// KV streaming, cumulative over the process: blocks the selections named vs blocks read from RAM
+ // (this device's owned ordinals; a split's other stages hold theirs)
uint64_t miss = 0, look = 0;
bool over = false;
- for (int64_t i = 0; i < g.n_qsa_layers(); ++i) {
- const strata::kernels::KvStreamCounters c = strata::kernels::kv_stream_counters(ss.qsa_states[i].map);
+ for (int64_t j = 0; j < ss.qsa_alloc; ++j) {
+ const strata::kernels::KvStreamCounters c =
+ strata::kernels::kv_stream_counters(ss.qsa_states[ss.qsa_ord0 + j].map);
miss += c.misses; look += c.lookups; over = over || c.overflow;
}
std::fprintf(stderr, "strata serve: KV streaming: %.2f%% of %llu block reads hit VRAM, %.1f MiB read "
@@ -4869,12 +5812,13 @@ int main(int argc, char** argv) {
for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0)
std::fprintf(stderr, "strata serve: CUDA%d: %lld expert entries, %lld active layer launches, %.1f MiB returned "
"(%.1f MiB with full rows) in this request; host %.0f ms staging+launching, %.0f ms "
- "waiting for it (since start)\n", r + 1,
+ "waiting for it in this request\n", r + 1,
(long long) (remote_experts[(size_t) r].computed() - remote_before[(size_t) r]),
(long long) (remote_experts[(size_t) r].launched_layers() - launches_before[(size_t) r]),
(double) (remote_experts[(size_t) r].returned_bytes() - compact_before[(size_t) r]) / 1048576.0,
(double) (remote_experts[(size_t) r].full_row_bytes() - full_before[(size_t) r]) / 1048576.0,
- remote_experts[(size_t) r].ms_begin(), remote_experts[(size_t) r].ms_wait());
+ remote_experts[(size_t) r].ms_begin() - begin_before[(size_t) r],
+ remote_experts[(size_t) r].ms_wait() - wait_before[(size_t) r]);
}
// SYCL port: the requests are done and their output written; leave without unwinding the GPU objects (the OS
// reclaims them). Their destructors ran against a runtime already shutting down and aborted (exit 139).
@@ -5211,7 +6155,8 @@ int main(int argc, char** argv) {
// The sampled-token synchronization also completes every captured QSA
// status readback. Retain one status per layer so a later layer cannot
// hide an earlier failure; no extra synchronization or token allocation.
- if (o.native_flash_attn_short) for (int64_t i = 0; i < g.n_qsa_layers(); ++i) {
+ if (o.native_flash_attn_short) for (int64_t j = 0; j < ss.qsa_alloc; ++j) {
+ const int64_t i = ss.qsa_ord0 + j; // the global ordinal, as the session's carve names it
const int32_t status = ss.qsa_states[i].host_step[strata::kernels::kStepCount];
if (status != 0) {
std::fprintf(stderr, "strata generate: native attention status %d at QSA layer %lld, position %lld\n",
@@ -5299,6 +6244,7 @@ int main(int argc, char** argv) {
}
mem_mark("the verifier and the drafter's binding");
ver.set_sampling(sp); // the CLI's own sampling (until 0.1.19 this loop was always greedy); no penalties here
+ if (use_mtp) mtp.set_draft_sampling(sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise)
ver.set_split(o.spec_split);
// auto: the copy kernel for every pack. DMA (the native packs' default until 0.1.13) has the host call
// cudaMemcpyAsync + cudaLaunchHostFunc inside a verify window while the GPU spins on the flag they raise;
@@ -5310,6 +6256,10 @@ int main(int argc, char** argv) {
if (drive.d.pcie_num < 0) drive.d.pcie_num = 0;
if (drive.d.pcie_num > 256) drive.d.pcie_num = 256;
const int64_t pcie0 = drive.d.pcie_experts;
+ // CS-T: the file tier since the decode began (the prompt path's copies are before this)
+ const int64_t files0 = src.file_reads(), ram0 = src.ram_reads();
+ const uint64_t fbytes0 = src.file_blob_bytes(), fall0 = src.file_read_bytes();
+ const double fms0 = src.file_ms();
if (o.adapt_every > 0 && o.adapt_swaps > 0) drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f);
int64_t swaps_total = 0;
double ms_adapt = 0;
@@ -5336,6 +6286,7 @@ int main(int argc, char** argv) {
else if (adapt_ev->get_info<
sycl::info::event::command_execution_status>() !=
sycl::info::event_command_status::complete) return;
+ src.commit_exchanges(); // the resident RAM mode: the evicted experts take their places in RAM
for (const auto& [i, slot] : pending) host_res[(size_t) i] = slot;
pending.clear();
if (d_res != nullptr)
@@ -5384,6 +6335,10 @@ int main(int argc, char** argv) {
}
std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; });
if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps);
+ if (!resident_stage_swaps(src, xcache, host_res, g.n_expert, swaps, adapt_stream)) {
+ std::fprintf(stderr, "strata generate: an adaptive refill failed (copying evicted experts back)\n");
+ return false;
+ }
for (const Swap& s : swaps) {
const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out;
const int32_t slot = host_res[out];
@@ -5590,6 +6545,26 @@ int main(int argc, char** argv) {
if (rounds > 0 && !drive.d.usage.empty())
std::printf("%-24s %lld experts swapped into the VRAM tier (every %d rounds, %.3f ms/round)\n", "adaptive tier",
(long long) swaps_total, o.adapt_every, ms_adapt / rounds);
+ if (src.complement_ready())
+ std::printf("%-24s %.2f GiB of experts in RAM, %lld exchanged with the VRAM tier, %lld blob reads from "
+ "the file\n", "resident RAM", (double) src.resident_bytes() / 1073741824.0,
+ (long long) src.exchanges(), (long long) src.file_reads());
+ if (srcp == &src) { // CS-T: the RAM and file tiers (the GPU cache's share is the hit rate above)
+ const double fms = src.file_ms() - fms0, fmb = (double) (src.file_blob_bytes() - fbytes0) / 1e6;
+ std::printf("%-24s decode: RAM %lld blobs, files %lld blobs, %.1f MB read from the files (%.2f MB/round, "
+ "%.1f ms/round of reading, %.2f GB/s per reading thread)%s; prompt copies %.1f MB\n",
+ "expert tiers", (long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0),
+ fmb, rounds > 0 ? fmb / rounds : 0.0, rounds > 0 ? fms / rounds : 0.0,
+ fms > 0 ? fmb / fms : 0.0, src.gguf_mode() ? " (the GGUF in place)" : "",
+ (double) (fall0 - fbytes0) / 1e6);
+ if (drive.d.lookahead != nullptr)
+ std::printf("%-24s %lld experts warmed, %lld of the file tier's %lld blob reads had been warmed (%.1f%%); "
+ "predictor %.1f ms/round on its thread, %lld layers skipped (still busy)\n", "routing prefetch",
+ (long long) src.warmed(), (long long) src.warmed_hits(),
+ (long long) (src.file_reads() - files0),
+ src.file_reads() > files0 ? 100.0 * (double) src.warmed_hits() / (double) (src.file_reads() - files0) : 0.0,
+ rounds > 0 ? drive.d.lookahead->busy_ms() / rounds : 0.0, (long long) drive.d.lookahead->skipped());
+ }
if (rounds > 0 && drive.d.pcie_num > 0)
std::printf("%-24s %.2f distinct experts per layer read over PCIe (share %d/256 of the misses)\n",
"pcie experts", (double) (drive.d.pcie_experts - pcie0) / (double) (rounds * g.n_layers),
@@ -5788,3 +6763,8 @@ int main(int argc, char** argv) {
sycl::free(arena, dpct::get_in_order_queue());
return 0;
}
+catch (sycl::exception const &exc) {
+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__
+ << ", line:" << __LINE__ << std::endl;
+ std::exit(1);
+}
diff --git a/sycl/tools/fixups.py b/sycl/tools/fixups.py
index 17ebf1dd9..cb786c278 100644
--- a/sycl/tools/fixups.py
+++ b/sycl/tools/fixups.py
@@ -41,7 +41,9 @@ for rel in all_sources():
edit(rel, sub(r"^(\s*)cudaGraphUpload\(\w+, \w+\);", r"\1// no cudaGraphUpload on SYCL: a finalized command_graph is already resident", re.M))
# __fadd_rn / __float_as_uint spellings
for _ in range(3): # nested __fadd_rn(__fadd_rn(a, b), c)
- edit(rel, sub(r"__fadd_rn\((\([^()]*\)|[^,()]+),\s*([^()]+)\)", r"(\1 + \2)"))
+ # the second operand parenthesised: `__fadd_rn(sum, c ? x : y)` must not become `(sum + c ? x : y)`
+ # (2026-10-01: it did, in the QSA indexer's pooled sum and the QSA block scores - the sum was replaced, not added)
+ edit(rel, sub(r"__fadd_rn\((\([^()]*\)|[^,()]+),\s*([^()]+)\)", r"(\1 + (\2))"))
edit(rel, lambda s: s.replace("__float_as_uint(", "sycl::bit_cast<uint32_t>("))
# 4. volatile casts on kernel arguments (the kernels take plain pointers).
edit(rel, lambda s: s.replace("(const volatile sycl::float4 *)", "(const sycl::float4 *)"))
@@ -86,7 +88,17 @@ def doorbell(s):
" for (uint32_t spin = 0; spin < strata::kSpinMax && strata::sys_load(flag) != want; ++spin) {}")
s = s.replace(" while (strata::sys_load(flag) < value) /* spin (no __nanosleep on SYCL) */;",
" for (uint32_t spin = 0; spin < strata::kSpinMax && strata::sys_load(flag) < value; ++spin) {}")
+ # upstream 0.1.31 spells the waits `while (*flag ...) strata_spin_pause();` and the ring with 4-space indent:
+ # same treatment (system-scope loads/stores, bounded: an unbounded orphaned spin wedges the B70's GT)
+ s = s.replace(" *(volatile uint32_t*) seq = *(volatile uint32_t*) seq + 1u;", " strata::sys_store(seq, strata::sys_load(seq) + 1u);")
+ s = s.replace(" while (*flag != want) strata_spin_pause();",
+ " for (uint32_t spin = 0; spin < strata::kSpinMax && strata::sys_load(flag) != want; ++spin) strata_spin_pause();")
+ s = s.replace(" while (*flag < value) strata_spin_pause();",
+ " for (uint32_t spin = 0; spin < strata::kSpinMax && strata::sys_load(flag) < value; ++spin) strata_spin_pause();")
return s
+# 0.1.31: dp4a.hpp's spin pause is __nanosleep, which SYCL lacks: the bounded spin (kSpinMax) is the backoff
+edit("include/strata/kernels/dp4a.hpp", lambda s: s.replace(" __nanosleep(100);\n",
+ " // SYCL port: no __nanosleep; the doorbell waits are bounded by strata::kSpinMax instead\n"))
edit("src/kernels/cuda/elementwise.dp.cpp", doorbell)
edit("src/kernels/cuda/verify_kernels.dp.cpp", doorbell)
@@ -181,6 +193,11 @@ edit("src/kernels/cuda/verify_kernels.dp.cpp", lambda s: s.replace(
# make the launchers that have no in-kernel fallback refuse the device (their callers then use the older
# kernels, exactly as on a pre-Ampere card). The XMX joint_matrix versions are phase-4 follow-up work.
OFF = "#if 0 // SYCL: inline PTX (mma/ldmatrix/cp.async) - the XMX port is pending; see tools/fixups.py"
+# 0.1.31: a Turing m16n8k8 branch (`#elif !STRATA_PA_SM80`) with its own inline PTX; dpct's DPCT_COMPATIBILITY_TEMP
+# selects it on SYCL. Unreachable there (qsa_prompt_attn_batch refuses the device), so it compiles to nothing.
+edit("src/kernels/cuda/qsa_prompt_attn.dp.cpp", lambda s: s.replace(
+ '#elif !STRATA_PA_SM80\n asm volatile("mma.sync.aligned.m16n8k8',
+ '#elif 0 // SYCL: Turing\'s m16n8k8 PTX (unreachable: the launcher refuses this device)\n asm volatile("mma.sync.aligned.m16n8k8'))
ON = "#if 1 // SYCL: the scalar path (the PTX one above is not ported yet)"
for rel in ["src/kernels/cuda/qsa_prompt_attn.dp.cpp", "src/kernels/cuda/qsa_select.dp.cpp",
"src/kernels/cuda/native_qsa_score.dp.cpp"]: