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: port upstream 0.1.32 (re-migration 3-way merge)

maxfridbefddee3a47d9c
diff --git a/docs/INTEL.md b/docs/INTEL.md
index e8939dbee..28ad6f85e 100644
--- a/docs/INTEL.md
+++ b/docs/INTEL.md
@@ -28,7 +28,7 @@ PCIe 3.0 x8 slot (the card trains at Gen3 x8 there; it can do Gen5 x16).
Decode speed with speculative decoding depends on the text: code drafts well, prose less so (see "Speed 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 engine 0.1.31-sycl (2026-10-01);
+tokens) on engine 0.1.31-sycl (2026-10-01; 0.1.32-sycl reproduces them exactly);
"Decode round 2" below lists what each change bought.
## Setup
@@ -490,6 +490,23 @@ part of the procedure now: it caught a dropped mirror hook and four doorbell wai
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.
+**The 0.1.32 merge (2026-10-01).** Upstream 0.1.31 -> 0.1.32 (89 commits) by the same steps; the hash-only
+differences are now canonicalized before `git merge-file` (the port's kernel-name hashes are kept), which left 10
+files with real conflicts. What it needed:
+
+- **Upstream's async commit** (`set_commit_async` / `wait_commit`) maps onto the port's own deferred commit
+ (`commit(n, err, false)` + `commit_finish`); `wait_commit` is `commit_finish`.
+- **Upstream's new hyper-connection read variants** (split / staged, chosen per card by a bit-for-bit self-test at
+ start) are not used by the port, which keeps its sliced down / split norm read; the self-test segfaulted on the
+ B70, so on SYCL it runs only with `STRATA_HC_CHECK=1` (open). The port's split-norm kernel was renamed
+ (`gr_norm_split_port_kernel`): upstream now has one of the same name.
+- Two kernel names collided after hash canonicalization (renamed), and fused_gr's per-block shared-memory query is
+ a fixup now.
+- **Result:** every output identical to 0.1.31 (Coder 19 / 2,184-token prompts and IQ2_XS, 256 greedy tokens),
+ same speeds (Coder 77.7-78.1 / 75.7 tok/s, IQ2_XS 58.5), 40K prompt 1,201 tok/s then 65.1 tok/s decode.
+ `kv_hybrid_parity` and `qsa_prompt_attn_parity` pass (the tests now turn on the XMX prompt attention they
+ check); `iq_multi_parity` (IQ2_XS) and `s2_expert_grouped_parity` as before.
+
**Not ported yet (2026-10-01).**
- Three kernels carry inline PTX (`mma.sync` tensor-core matrix ops, `ldmatrix`, `cp.async`):
diff --git a/sycl/CMakeLists.txt b/sycl/CMakeLists.txt
index c7e3697a3..6444dd872 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.31 LANGUAGES C CXX) # the upstream engine version this port tracks
+project(strata_sycl VERSION 0.1.32 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)
diff --git a/sycl/include/strata/core/coupled_draft.hpp b/sycl/include/strata/core/coupled_draft.hpp
index 78e6c9390..f7640d570 100644
--- a/sycl/include/strata/core/coupled_draft.hpp
+++ b/sycl/include/strata/core/coupled_draft.hpp
@@ -52,15 +52,23 @@ 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 = [] {
+inline bool& coupled_draft_state() {
+ static bool on = [] {
const char* e = std::getenv("STRATA_SPEC_COUPLED");
return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0;
}();
return on;
}
+/// Whether coupled draft sampling is enabled (via STRATA_SPEC_COUPLED=1 or --coupled-draft CLI flag).
+inline bool coupled_draft_env() {
+ return coupled_draft_state();
+}
+
+inline void set_coupled_draft(bool on) {
+ coupled_draft_state() = 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; }
diff --git a/sycl/include/strata/core/session.hpp b/sycl/include/strata/core/session.hpp
index 526dc3dff..af9cbfc77 100644
--- a/sycl/include/strata/core/session.hpp
+++ b/sycl/include/strata/core/session.hpp
@@ -99,6 +99,9 @@ uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k, int
/// 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);
+/// Before the memory `session_init` carved is freed: forgets what points into it from outside the session (the
+/// rope kernels' registered angle table, #280), so a later session never rotates by freed memory.
+void session_release(SessionState& s);
/// 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);
diff --git a/sycl/include/strata/core/verify.hpp b/sycl/include/strata/core/verify.hpp
index 7d8bfb0d5..3b676c414 100644
--- a/sycl/include/strata/core/verify.hpp
+++ b/sycl/include/strata/core/verify.hpp
@@ -75,6 +75,9 @@ public:
/// One window: `tokens[0..T)` at positions pos0.., the pool served per layer; `out[t]` = argmax after token t.
/// The PLE rows are gathered here from `ss.ple_prev` and the tokens. Captures the T-token graph on first use.
bool run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out, std::string& err);
+ /// Diagnostics: row `t` of the last window's head logits (n_vocab floats) to the host. Valid after run().
+ bool copy_logits(int t, float* host) const;
+ int64_t vocab() const { return next_ ? next_->vocab() : n_vocab_; }
/// The sampling the verify window's head applies (temperature / top_p / top_k / seed). Set per
/// request; greedy by default. The sampling itself runs OUTSIDE the captured graph - its
/// parameters would otherwise be baked forever - so this can change between requests freely.
@@ -123,6 +126,14 @@ public:
/// SYCL port: capture every window graph now (one per window size) instead of on first use, so the first
/// request does not pay for them (a 2,400-node graph takes tens of ms to finalize on this backend).
bool warm(std::string& err);
+ /// (upstream 0.1.32; the port maps it onto commit_finish, verify.cpp) commit() returns without waiting for its graph (a single-GPU session sets it): the next window follows it on
+ /// the same stream and the drafter reads nothing it writes, so it overlaps the draft. Whoever reads or writes
+ /// the session from another stream or the host afterwards (a new request, a checkpoint, a snapshot, the prompt
+ /// path, the end of a run) calls wait_commit() first. STRATA_COMMIT_SYNC=1 keeps the wait.
+ static void set_commit_async(bool on);
+ /// Waits for the last commit graph when commit() did not (an event recorded after it, not the whole device);
+ /// false with `err` when it failed. Free when nothing is pending.
+ bool wait_commit(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
@@ -182,7 +193,8 @@ private:
int pending_commit_ = 0; ///< n_keep of a launched, unfinished commit (0: none)
std::chrono::steady_clock::time_point pending_commit_t0_{};
bool record_window(int T, dpct::queue_ptr cs, std::string &err);
- static constexpr int kProfPer = 32; // stamps per layer
+ static constexpr int kProfPer = 33; // stamps per layer (32 left the hc-read second
+ // half's up-stamp at slot 32 = the next layer's slot 0: D8)
bool prof_on_ = false;
unsigned long long* prof_ = nullptr; // device: n_layers * kProfPer + 4 stamps
std::vector<unsigned long long> prof_h_;
@@ -219,6 +231,10 @@ private:
uint32_t* h_flag_ = nullptr; uint32_t* m_flag_ = nullptr;
uint32_t* h_flagA_ = nullptr; uint32_t* m_flagA_ = nullptr; // the GPU plan is in place
uint32_t* h_flagB_ = nullptr; uint32_t* m_flagB_ = nullptr; // the PCIe share's DMA copies have landed
+ dpct::event_ptr commit_done_ =
+ nullptr; // recorded after an async commit (set_commit_async); see
+ // wait_commit
+ bool commit_pending_ = false;
dpct::queue_ptr copy_ =
&dpct::get_in_order_queue(); // the copy engine's stream (DMA of missed
// experts)
diff --git a/sycl/include/strata/kernels/mrope.hpp b/sycl/include/strata/kernels/mrope.hpp
index fecd37378..ed27cf809 100644
--- a/sycl/include/strata/kernels/mrope.hpp
+++ b/sycl/include/strata/kernels/mrope.hpp
@@ -19,12 +19,32 @@
#include <dpct/dpct.hpp>
#include <cstdint>
+#include "strata/kernels/rope_scaling.hpp"
+
namespace strata::kernels {
/// The table of the CURRENT device (a layer split sets one per device; null = the identity).
void mrope_table_set(const int32_t* device_table);
const int32_t* mrope_table();
+/// #280, opt-in (STRATA_ROPE_TABLE=1): the rotation angles, 32 pairs of a 64-wide rotary slice, from the session's
+/// float64 table (build_rope_table, [max_pos][32] cos and sin in VRAM, the rope scaling inside) of the CURRENT
+/// device. With it the rope kernels rotate by the table's exact angles; without it they compute pos * powf(...) with cosf/sinf, which under
+/// --use_fast_math is 0.0014 rad off at 32K and ~0.02 at 262K, and the prompt path (precise libm) and decode
+/// (fast-math) disagree with each other.
+struct RopeTab {
+ const float* cos = nullptr; ///< null: no table, the kernels compute the angle as they always did
+ const float* sin = nullptr;
+ int max_pos = 0;
+};
+/// Registers the table the session just built with `scaling` (the latest one of the device wins).
+void rope_table_set(const float* cos_tab, const float* sin_tab, int max_pos, const RopeScaling& scaling);
+/// Forgets the table `cos_tab` (on every device) - before the memory that holds it is freed (session_release).
+void rope_table_release(const float* cos_tab);
+/// The registered table when STRATA_ROPE_TABLE=1 and it was built with `scaling`; otherwise none (the default: the
+/// kernels compute the angle exactly as before).
+RopeTab rope_table_for(const RopeScaling& scaling);
+
#if defined(SYCL_LANGUAGE_VERSION) || defined(__HIPCC__)
/// ggml rope_multi, is_imrope, sections {11, 11, 10, 0}: sector = pair % 32; sector % 3 == 1 -> h (sector < 33),
/// == 2 -> w (sector < 30), == 0 -> t (sector < 33). For pairs 0..31 all three bounds hold, so it is pair % 3.
@@ -36,6 +56,25 @@ __dpct_inline__ int mrope_pos(const int32_t *tab, int pos, int pair) {
*/
return tab ? *(tab + (size_t)pos * 3 + pair % 3) : pos;
}
+/// cos and sin of rotary position p, pair `pair` (0..31) from the table (scaling and magnitude included); false
+/// when there is no table or p lies past it - then the caller computes the angle as it always did
+__dpct_inline__ bool rope_tab_cs(const RopeTab &t, int p, int pair, float &c,
+ float &s) {
+ if (t.cos == nullptr || p < 0 || p >= t.max_pos) return false;
+ /*
+ 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.
+ */
+ c = *(t.cos + (size_t)p * 32 + pair);
+ /*
+ 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.
+ */
+ s = *(t.sin + (size_t)p * 32 + pair);
+ return true;
+}
#endif
} // namespace strata::kernels
diff --git a/sycl/src/core/conversation_snapshot.cpp b/sycl/src/core/conversation_snapshot.cpp
index 74ea5dcfc..92664a7b3 100644
--- a/sycl/src/core/conversation_snapshot.cpp
+++ b/sycl/src/core/conversation_snapshot.cpp
@@ -45,8 +45,12 @@ bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index
// 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};
+ // Format 3 identifies snapshot K8V4 only; never pass it to the block movers. Rotated INT8 K/V (#293,
+ // STRATA_KV_ROT=1) is another format too (+16): its bytes mean nothing to a state that does not rotate, so a
+ // snapshot or prompt checkpoint taken with the rotation never restores into one without it, nor the reverse.
+ // (Q4_0 is always rotated: nothing to tell apart; without the rotation the format is the one it always was.)
+ const int rotated = st.kv_rot && !st.kv_q4 && !st.kv_hybrid ? 16 : 0;
+ l = {(st.kv_hybrid ? 3 : qsa_kv_format(st)) + rotated, 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,
diff --git a/sycl/src/core/conversation_snapshot_test.cpp b/sycl/src/core/conversation_snapshot_test.cpp
index 7544df2ab..c42233bb2 100644
--- a/sycl/src/core/conversation_snapshot_test.cpp
+++ b/sycl/src/core/conversation_snapshot_test.cpp
@@ -313,6 +313,17 @@ int main() {
}
auto bad=a; bad.head_dim++;
check(!conversation_kv_restore(bad,f.state,f.g,upto,index,err),"reject incompatible geometry");
+ if (fmt==kKvInt8) {
+ // #293: INT8 K/V saved through the Hadamard rotation (STRATA_KV_ROT=1) never restores into a state
+ // without it, nor the reverse
+ f.state.kv_rot=true;
+ ConversationKv rotated;
+ check(conversation_kv_save(rotated,f.state,f.g,upto,index,err),"save rotated INT8");
+ check(!conversation_kv_restore(a,f.state,f.g,upto,index,err),"unrotated image into a rotated state rejected");
+ f.state.kv_rot=false;
+ check(!conversation_kv_restore(rotated,f.state,f.g,upto,index,err),"rotated image into an unrotated state rejected");
+ check(conversation_kv_restore(a,f.state,f.g,upto,index,err),"unrotated image still restores");
+ }
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");
diff --git a/sycl/src/core/device.dp.cpp b/sycl/src/core/device.dp.cpp
index 5804ed88c..fad48c260 100644
--- a/sycl/src/core/device.dp.cpp
+++ b/sycl/src/core/device.dp.cpp
@@ -109,6 +109,33 @@ std::string gpu_arch_problem(int ordinal) {
#endif
}
+std::string device_code_error() try {
+#if defined(STRATA_USE_HIP)
+ return ""; // gpu_arch_problem() checks the HIP architectures against STRATA_HIP_ARCHS, before this point
+#else
+ // every .cu of the engine is compiled for the same CMAKE_CUDA_ARCHITECTURES, so this kernel stands for all
+ dpct::kernel_function_info a{};
+ const dpct::err0 e = DPCT_CHECK_ERROR(
+ dpct::get_kernel_function_info(&a, (const void *)poison_kernel));
+ if (e == 0) return {};
+ /*
+ DPCT1026: The call to cudaGetLastError was removed because this
+ functionality is redundant in SYCL.
+ */
+ /*
+ DPCT1009: SYCL reports errors using exceptions and does not use error
+ codes. Please replace the "get_error_string_dummy(...)" with a real
+ error-handling function.
+ */
+ return dpct::get_error_string_dummy(e);
+#endif
+}
+catch (sycl::exception const &exc) {
+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__
+ << ", line:" << __LINE__ << std::endl;
+ std::exit(1);
+}
+
DeviceInfo device_info(int ordinal) {
int count = 0;
check(DPCT_CHECK_ERROR(count = dpct::device_count()), "cudaGetDeviceCount");
@@ -245,8 +272,8 @@ DeviceArena::DeviceArena(uint64_t bytes, int ordinal, bool poison)
});
}
/*
- DPCT1010: SYCL uses exceptions to report errors and does not
- use the error codes. The cudaGetLastError function call was replaced
+ DPCT1010: SYCL uses exceptions to report errors and does not use
+ the error codes. The cudaGetLastError function call was replaced
with 0. You need to rewrite this code.
*/
check(0, "poison_kernel");
diff --git a/sycl/src/core/layer.cpp b/sycl/src/core/layer.cpp
index 0ac8fb1e7..54da32fd5 100644
--- a/sycl/src/core/layer.cpp
+++ b/sycl/src/core/layer.cpp
@@ -26,6 +26,7 @@
#include "strata/kernels/native_router.hpp"
#include "strata/kernels/native_qsa.hpp"
#include "strata/kernels/native_qsa_indexer.hpp"
+#include "strata/kernels/mrope.hpp"
#include "strata/kernels/native_rope.hpp"
#include "strata/kernels/native_flash_attn.hpp"
#include "strata/kernels/fused_gr.hpp"
@@ -175,8 +176,9 @@ if (!w.wants_q8k()) { s_gemv_q8_0_split(x80, p.codes, p.scales, p.offset,
// namespace
void layer_set_native_bf16(bool enabled) { native_bf16_projections = enabled; }
void layer_set_native_flash_attn_short(bool enabled) { native_flash_attn_short = enabled; }
-namespace { bool g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false; }
+namespace { bool g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false, g_kv_int8_rot = false; }
void qsa_set_kv_int8(bool enabled) { g_kv_int8 = enabled; }
+void qsa_set_kv_int8_rotate(bool enabled) { g_kv_int8_rot = enabled; }
bool qsa_kv_int8() { return g_kv_int8; }
void qsa_set_kv_q4(bool enabled) { g_kv_q4 = enabled; }
bool qsa_kv_q4() { return g_kv_q4; }
@@ -625,6 +627,7 @@ uint64_t qsa_state_init(const ModelGeometry &g, int64_t max_cells, void *base,
st.kv_int8 = false;
st.kv_q4 = false;
}
+ st.kv_rot = st.kv_q4 || (st.kv_int8 && g_kv_int8_rot); // K8V4 rotates only V (below)
st.kv_mode = p.mode;
st.n_slots = p.slots;
const uint64_t rows = (uint64_t) p.slots * s.n_head_kv * s.page_size; // VRAM rows: the slots
@@ -752,6 +755,9 @@ uint64_t qsa_state_init(const ModelGeometry &g, int64_t max_cells, void *base,
dpct::get_in_order_queue()
.memcpy(st.sin_tab, hs.data(), hs.size() * 4)
.wait();
+ st.owns_rope = true;
+ if (s.n_rot == 64) // the native and prompt-path rope kernels read it (mrope.hpp, STRATA_ROPE_TABLE=1)
+ strata::kernels::rope_table_set(st.cos_tab, st.sin_tab, (int) max_cells, strata::kernels::rope_scaling());
}
// the page table starts as the IDENTITY, which is the simplest legal mapping and what a caller that does
// not page at all wants; a streamed state starts with nothing resident, a ring at `block % n_slots`.
@@ -1041,11 +1047,14 @@ if (st.kv_hybrid) {
strata::kernels::fwht256_inplace_cuda(b.vcur, g.n_head_kv, stream);
kv_append_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, st.step, b.kcur, b.kcur, s, stream, nullptr); // mode 0: no host mirror
strata::kernels::kv_append_q4_step(st.v_q4, st.v_q4, st.page_table, st.step, b.vcur, b.vcur, s, stream, nullptr);
-} else if (st.kv_q4) {
- strata::kernels::fwht256_inplace_cuda(b.kcur, g.n_head_kv, stream); // Q4_0: rotated K and V (kv_q4.hpp)
+} else {
+if (st.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1
+ strata::kernels::fwht256_inplace_cuda(b.kcur, g.n_head_kv, stream);
strata::kernels::fwht256_inplace_cuda(b.vcur, g.n_head_kv, stream);
+}
+if (st.kv_q4) {
strata::kernels::kv_append_q4_step(st.k_q4, st.v_q4, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host);
-} 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()) {
+} 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); } /* not K8V4 */ { 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, rope_scaling(), stream);
@@ -1091,7 +1100,7 @@ int64_t max_blocks = (st.max_cells / s.idx_block) + 2;
}
// KV streaming: every block the selection names is made resident before anything reads it
qsa_kv_resolve(st, g, b.ids, st.step, 1, cap, stream);
- if (st.kv_q4) strata::kernels::fwht256_inplace_cuda(b.qcur, g.n_head, stream); // <Hq, Hk> = <q, k>
+ if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(b.qcur, g.n_head, stream); // <Hq, Hk> = <q, k>
if (g_fast_attn && !native_flash_attn_short && dump == nullptr) {
const strata::kernels::QsaAttnPools pools = qsa_attn_pools(st);
strata::kernels::qsa_decode_attn_step(b.qcur, pools, b.ids, st.step, cap, s, b.attn_scratch, b.attn, stream);
@@ -1125,7 +1134,7 @@ int64_t max_blocks = (st.max_cells / s.idx_block) + 2;
}
} else qsa_attend_step(b.qcur, b.k_scratch, b.v_scratch, st.step, cap, s, b.attn, nullptr, stream);
}
- if (st.kv_q4 || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(b.attn, g.n_head, stream); // the output back: H is self-inverse
+ if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(b.attn, g.n_head, stream); // the output back: H is self-inverse
dump_slot(dump, g, layer, b.attn, (uint64_t) 2 * g.n_embd + 2 * g.hc, (uint64_t) g.n_head * g.head_dim, stream); { const uint64_t vs = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + (uint64_t) 2 * g.n_head_kv * g.head_dim; dump_slot(dump, g, layer, (const float*) b.v_scratch, vs, (uint64_t) g.n_head_kv * g.head_dim / 2, stream); dump_slot(dump, g, layer, (const float*) b.ids, vs + (uint64_t) g.n_head_kv * g.head_dim / 2, 4, stream); dump_slot(dump, g, layer, (const float*) st.step, vs + (uint64_t) g.n_head_kv * g.head_dim / 2 + 4, 4, stream); }
// ---- 9. Gate the attention output before its projection. Native CUDA keeps F32
// sigmoid/multiply arithmetic and uses Q8_1 for the native quantized projection.
diff --git a/sycl/src/core/mtp.cpp b/sycl/src/core/mtp.cpp
index 4e9a013c0..b862ead22 100644
--- a/sycl/src/core/mtp.cpp
+++ b/sycl/src/core/mtp.cpp
@@ -572,12 +572,15 @@ bool MtpDrafter::record_forward(int T, int step_row0, dpct::queue_ptr cs,
native_mmvq(GGML_Q8_0, q8("self_attn.v_proj.weight"), xq_, vcur_, (int) N, (int) (NKV * HD), T, cs);
for (int t = 0; t < T; ++t) {
norm_rope(kcur_ + t * NKV * HD, f32("self_attn.k_norm.weight"), (int) NKV, (int) HD, pos + t * NH);
- if (st_.kv_q4) { // Q4_0 KV (kv_q4.hpp): rotated K and V
+ if (st_.kv_rot) { // rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1
fwht256_inplace_cuda(kcur_ + t * NKV * HD, NKV, cs);
fwht256_inplace_cuda(vcur_ + t * NKV * HD, NKV, cs);
+ }
+ // stored in the state's own format (#293 appended rotated INT8 K/V as Q4_0, into pools INT8 never has)
+ if (st_.kv_q4)
kv_append_q4_step(st_.k_q4, st_.v_q4, st_.page_table, step + t * 4, kcur_ + t * NKV * HD,
vcur_ + t * NKV * HD, s, cs, &st_.host);
- } else if (st_.kv_int8)
+ else if (st_.kv_int8)
kv_append_q8_step(st_.k_q, st_.v_q, st_.k_scale, st_.v_scale, st_.page_table, step + t * 4,
kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st_.host);
else
@@ -602,12 +605,12 @@ bool MtpDrafter::record_forward(int T, int step_row0, dpct::queue_ptr cs,
return false;
}
norm_rope(qc, f32("self_attn.q_norm.weight"), (int) NH, (int) HD, pos + t * NH);
- if (st_.kv_q4) fwht256_inplace_cuda(qc, NH, cs);
+ if (st_.kv_rot) fwht256_inplace_cuda(qc, NH, cs);
}
const QsaAttnPools pools = qsa_attn_pools(st_);
if (window_ > 0) window_ids(const_cast<int32_t*>(step), T, (int) window_, ident_, cap_, cs);
qsa_decode_attn_batch(qcur_, pools, ident_, step, cap_, s, attn_scratch_, attn_, T, cs);
- if (st_.kv_q4) fwht256_inplace_cuda(attn_, (int64_t) T * NH, cs);
+ if (st_.kv_rot) fwht256_inplace_cuda(attn_, (int64_t) T * NH, cs);
for (int t = 0; t < T; ++t)
native_qsa_gate_apply(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, attn32_ + t * NH * HD, (int) NH, (int) HD, cs);
native_quantize_q8_1(attn32_, xq_, (int) (NH * HD), T, cs);
diff --git a/sycl/src/core/native_dense.cpp b/sycl/src/core/native_dense.cpp
index 7b0ff4a31..867c72767 100644
--- a/sycl/src/core/native_dense.cpp
+++ b/sycl/src/core/native_dense.cpp
@@ -60,6 +60,16 @@ bool NativeDense::served_names(const std::vector<std::string>& shards, bool incl
}
}
+bool NativeDense::keep_unquantized_ple_key(const std::string& pack_dir, std::set<std::string>& skip,
+ std::string& err) {
+ const std::string key = "blk.1.ple_key.weight";
+ if (!skip.count(key)) return true;
+ int code_bits = -1;
+ if (!WeightTable::index_code_bits(pack_dir, key, code_bits, err)) return false;
+ if (code_bits == 0) skip.erase(key);
+ return true;
+}
+
NativeDense::~NativeDense() {
if (scratch_) sycl::free(scratch_, dpct::get_in_order_queue());
for (void *p : weights_)
@@ -148,6 +158,8 @@ bool NativeDense::load(const std::vector<std::string> &shards,
auto& ref = found->second;
if (ref.native_data) { err = "native dense: override already attached"; return false; }
if (!strata::kernels::native_mmvq_supported(tensor.type)) continue;
+ // #326: the pack keeps an unquantized (--compat-bf16) key, which the PLE reads from the arena
+ if (tensor.name == "blk.1.ple_key.weight" && !ref.quantized()) continue;
if (!ref.quantized() || tensor.shape.size() != 2 ||
ref.ne0 <= 0 || ref.ne0 > INT_MAX || ref.ne1 <= 0 || ref.ne1 > INT_MAX ||
tensor.shape[0] != (uint64_t) ref.ne0 || tensor.shape[1] != (uint64_t) ref.ne1) {
diff --git a/sycl/src/core/native_head.cpp b/sycl/src/core/native_head.cpp
index 3ebfe6389..fd3f2bfea 100644
--- a/sycl/src/core/native_head.cpp
+++ b/sycl/src/core/native_head.cpp
@@ -163,13 +163,15 @@ bool NativeEmbed::load(const std::vector<std::string> &shards, int64_t n_embd,
int64_t n_vocab, std::string &err) try {
try {
const strata::GgufModel model(shards);
- err = strata::check_architecture(model.meta());
+ // --embd-gguf's one-tensor file (tools/embd_bf16_pack.py) says "strata-embd": only its tensor is checked
+ const strata::MetaValue* arch = model.meta().get("general.architecture");
+ err = arch != nullptr && arch->s == "strata-embd" ? std::string() : 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) {
+ !strata::kernels::embed_type_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 "
"dequantizer";
return false;
diff --git a/sycl/src/core/session.cpp b/sycl/src/core/session.cpp
index c4e7cf86d..2c75bde59 100644
--- a/sycl/src/core/session.cpp
+++ b/sycl/src/core/session.cpp
@@ -4,6 +4,7 @@
#include <dpct/dpct.hpp>
#include "strata/sycl_queue.hpp"
#include "strata/core/session.hpp"
+#include "strata/kernels/mrope.hpp"
#include "strata/core/progress.hpp"
#include "strata/kernels/qsa.hpp"
@@ -129,6 +130,14 @@ uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void
return used;
}
+void session_release(SessionState& s) {
+ for (int64_t j = 0; s.qsa_states != nullptr && j < s.qsa_alloc; ++j)
+ if (s.qsa_states[j].owns_rope) {
+ strata::kernels::rope_table_release(s.qsa_states[j].cos_tab);
+ s.qsa_states[j].owns_rope = false;
+ }
+}
+
void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init, void* stream) {
dpct::queue_ptr cs = strata::q_of(stream);
// the residual: `hc` copies of the one vector a caller hands in. A real sequence's first token is the
diff --git a/sycl/src/core/verify.cpp b/sycl/src/core/verify.cpp
index 1fdb4e07b..6ac06f282 100644
--- a/sycl/src/core/verify.cpp
+++ b/sycl/src/core/verify.cpp
@@ -220,6 +220,7 @@ bool Verifier::init(const WeightTable &wt, const ModelGeometry &g,
device_ = dpct::get_current_device_id(); // a layer split's stage on another
// GPU: its streams, graphs and
// buffers live there
+ strata::kernels::fused_gr_check(); // once per card: which bitwise-equal hyper-connection read runs there
wt_ = &wt;
g_ = &g;
ss_ = &ss;
@@ -643,7 +644,7 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {
native_mmvq(wv->native_type, wv->native_data, xq_, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs);
if (qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV);
else for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH);
- if (st.kv_q4) { // Q4_0 KV (kv_q4.hpp): K and V rotated before they are stored
+ if (st.kv_rot) { // K and V rotated before they are stored (kv_q4.hpp)
fwht256_inplace_cuda(kcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);
fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);
} else if (st.kv_hybrid) { // K8V4: only V is rotated
@@ -693,6 +694,7 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {
return false;
}
norm_rope(qcur_ + tb * NH * HD, wqn, (int) (n * NH), (int) HD, pos_ + tb * NH);
+ if (st.kv_rot) fwht256_inplace_cuda(qcur_ + tb * NH * HD, (int64_t) n * NH, cs); // <Hq, Hk> = <q, k>
bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wiq->data, qidx_ + tb * IQ * ID, IQ * ID,
N, IQ * ID, n, cs);
norm_rope(qidx_ + tb * IQ * ID, wiqn, (int) (n * IQ), (int) ID, pos_i + tb * IQ);
@@ -714,7 +716,7 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {
return false;
}
norm_rope(qc, wqn, (int) NH, (int) HD, pos_ + t * NH);
- if (st.kv_q4) fwht256_inplace_cuda(qc, NH, cs); // <Hq, Hk> = <q, k>
+ if (st.kv_rot) fwht256_inplace_cuda(qc, NH, cs); // <Hq, Hk> = <q, k>
}
for (int t = tb; t < te; ++t) {
float* qx = qidx_ + t * IQ * ID;
@@ -735,7 +737,7 @@ bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {
qsa_decode_attn_batch(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, cap_,
s, attn_scratch_ + (size_t) tb * attn_scratch_floats_, attn_ + tb * NH * HD, n, cs);
stamp(l, 13, grp);
- if (st.kv_q4 || st.kv_hybrid) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = H
+ if (st.kv_rot || st.kv_hybrid) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = H
if (qb) native_qsa_gate_apply(attn_ + tb * NH * HD, qfull_ + tb * NH * 2 * HD, attn32_ + tb * NH * HD,
(int) (n * NH), (int) HD, cs);
else
@@ -956,7 +958,7 @@ std::string Verifier::profile_report() {
"k/v+norm-rope", "kv+idx append", "q+q-idx", "scores+topk", "kv-resolve",
"attention", "gate", "", "out-proj", "hc-read1+router", "shared+quant",
"waitA", "VRAM hits", "waitB", "PCIe grp", "waitCPU", "copy+combine",
- "(gap)", "head", " hc0 norm", " hc0 down", " hc0 up", "", ""};
+ "(gap)", "head", " hc0 norm", " hc0 down", " hc0 up", "", "", ""};
std::string out;
char b[80];
double total = 0;
@@ -1397,6 +1399,13 @@ bool Verifier::run(int T, const int32_t *tokens, int64_t pos0, PoolMultiFn pool,
.wait();
const int64_t L = g.n_layers;
auto at = [&](int64_t l, int i) { return prof_h_[(size_t) (l * kProfPer + i)]; };
+ // D8: the derived columns below read stamps the hc-read kernels write themselves or the next
+ // layer's first. A slot no kernel stamped is 0 and its unsigned difference wrapped to ~1e19 ns -
+ // which is why (gap)/head/hc0 printed ~1e14 ms per window. A missing or out-of-order stamp now
+ // contributes nothing.
+ const auto gap = [](unsigned long long to, unsigned long long from) {
+ return (from != 0 && to != 0 && to >= from) ? (double) (to - from) : 0.0;
+ };
for (int64_t l = 0; l < L; ++l) {
const int kind = is_qsa_layer(g, l) ? 1 : 0;
unsigned long long prev = at(l, 0);
@@ -1406,13 +1415,16 @@ bool Verifier::run(int T, const int32_t *tokens, int64_t pos0, PoolMultiFn pool,
prof_sum_[kind][i] += (double) (x - prev);
prev = x;
}
- if (l + 1 < L) prof_sum_[kind][25] += (double) (at(l + 1, 0) - at(l, 24));
- prof_sum_[kind][27] += (double) (at(l, 27) - at(l, 0)); // hc-read0: norm
- prof_sum_[kind][28] += (double) (at(l, 28) - at(l, 27)); // down
- prof_sum_[kind][29] += (double) (at(l, 1) - at(l, 28)); // up
- prof_sum_[kind][1] -= (double) (at(l, 1) - at(l, 0)); // (hc-read0 shown split)
+ if (l + 1 < L) prof_sum_[kind][25] += gap(at(l + 1, 0), at(l, 24));
+ const double dn = gap(at(l, 27), at(l, 0)), dd = gap(at(l, 28), at(l, 27)), du = gap(at(l, 1), at(l, 28));
+ if (dn > 0 && dd > 0 && du > 0) { // the split exists: show it split, not twice
+ prof_sum_[kind][27] += dn; // hc-read0: norm
+ prof_sum_[kind][28] += dd; // down
+ prof_sum_[kind][29] += du; // up (through both halves, as before)
+ prof_sum_[kind][1] -= gap(at(l, 1), at(l, 0)); // (hc-read0 shown split)
+ }
}
- prof_sum_[0][26] += (double) (at(L, 1) - at(L, 0));
+ prof_sum_[0][26] += gap(at(L, 1), at(L, 0));
++prof_windows_;
if (std::getenv("STRATA_VERIFY_EAGER") != nullptr) // SYCL port: the stage table per window, host-clocked
std::fprintf(stderr, "verify stages T=%d (ms/window):%s\n", T, profile_report().c_str());
@@ -1562,9 +1574,24 @@ bool Verifier::window_logprobs(const int32_t* targets, int T, int64_t pos0, int3
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,
+ std::fprintf(out, "%lld\t%d\t%.9f\t%lld\t%.9f\t%d\t%.9f\t%.9f", (long long) (pos0 + t), (int) tgt,
(double) row[tgt] - lse, (long long) top, maxv - lse, (int) (top == (int64_t) tgt), extra,
without);
+ // STRATA_LOGPOS_TOPK=K: the K most likely tokens and their log-probabilities too (`id:logprob`), for a
+ // top-k comparison with another engine on the same tokens (docs/UNSLOTH_Q4.md)
+ static const int topk = [] {
+ const char* v = std::getenv("STRATA_LOGPOS_TOPK");
+ return v != nullptr ? std::max(0, std::min(256, std::atoi(v))) : 0;
+ }();
+ if (topk > 0) {
+ std::vector<int32_t> order((size_t) n_vocab_);
+ for (int64_t v = 0; v < n_vocab_; ++v) order[(size_t) v] = (int32_t) v;
+ std::partial_sort(order.begin(), order.begin() + topk, order.end(),
+ [&](int32_t a, int32_t b) { return row[a] > row[b]; });
+ for (int j = 0; j < topk; ++j)
+ std::fprintf(out, "\t%d:%.6f", order[(size_t) j], (double) row[order[(size_t) j]] - lse);
+ }
+ std::fprintf(out, "\n");
}
std::fflush(out);
return true;
@@ -1573,6 +1600,12 @@ bool Verifier::window_logprobs(const int32_t* targets, int T, int64_t pos0, int3
return false;
}
+// Upstream's set_commit_async/wait_commit (0.1.32) on the port's own deferred commit: commit(n, err, false) leaves
+// the graph running and commit_finish() collects it (it also advances ss.ple_prev, so a pending commit must be
+// finished before the next window). The flag is kept for the API; the port decides per call site (generate.cpp).
+namespace { bool g_commit_async = false; }
+void Verifier::set_commit_async(bool on) { g_commit_async = on && std::getenv("STRATA_COMMIT_SYNC") == nullptr; }
+
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; }
@@ -1646,4 +1679,20 @@ catch (sycl::exception const &exc) {
std::exit(1);
}
+bool Verifier::wait_commit(std::string& err) {
+ if (!commit_finish(err)) return false;
+ return next_ == nullptr || next_->wait_commit(err);
+}
+
+bool Verifier::copy_logits(int t, float* host) const {
+ if (next_ != nullptr) return next_->copy_logits(t, host); // a layer split: the head is on the last stage
+ if (head_logits_ == nullptr || host == nullptr || t < 0 || n_vocab_ <= 0) return false;
+ try {
+ cs_->memcpy(host, head_logits_ + (size_t) t * (size_t) n_vocab_, (size_t) n_vocab_ * sizeof(float)).wait();
+ } catch (sycl::exception const&) {
+ return false;
+ }
+ return true;
+}
+
} // namespace strata::core
diff --git a/sycl/src/core/weights.cpp b/sycl/src/core/weights.cpp
index e09aa13cf..7a7ed123c 100644
--- a/sycl/src/core/weights.cpp
+++ b/sycl/src/core/weights.cpp
@@ -119,6 +119,29 @@ bool WeightTable::pool_bytes(const std::string& pack_dir, uint64_t& out, std::st
return true;
}
+bool WeightTable::index_code_bits(const std::string& pack_dir, const std::string& name, int& code_bits,
+ std::string& err) {
+ const std::string path = pack_dir + "/index.txt";
+ std::FILE* f = std::fopen(path.c_str(), "rb");
+ if (!f) { err = "cannot open " + path; return false; }
+ char line[1024];
+ code_bits = -1;
+ while (std::fgets(line, sizeof line, f)) {
+ if (line[0] == '#') continue;
+ char row[256] = {0};
+ unsigned long long dummy = 0;
+ long long ne = 0;
+ int i1 = 0, i2 = 0, bits = 0;
+ // the first ten fields of the row `load` parses: name file kind src_off src_bytes dst_off dst_bytes ne0 ne1 code_bits
+ if (std::sscanf(line, "%255s %d %d %llu %llu %llu %llu %lld %lld %d", row, &i1, &i2, &dummy, &dummy, &dummy,
+ &dummy, &ne, &ne, &bits) != 10)
+ continue;
+ if (name == row) { code_bits = bits; break; }
+ }
+ std::fclose(f);
+ return true;
+}
+
bool WeightTable::load(const std::string &pack_dir, void *arena_base,
uint64_t arena_bytes, std::string &err,
const std::set<std::string> *skip) try {
diff --git a/sycl/src/kernels/cuda/cvec.dp.cpp b/sycl/src/kernels/cuda/cvec.dp.cpp
index 8d0a4be4a..c118d5171 100644
--- a/sycl/src/kernels/cuda/cvec.dp.cpp
+++ b/sycl/src/kernels/cuda/cvec.dp.cpp
@@ -194,8 +194,8 @@ bool cvec_upload(const std::vector<float>& dir, const std::vector<float>& s, int
for (int d = 0; d < kDevices; ++d) {
if (g_dev[d].dir == nullptr) continue;
/*
- DPCT1093: The "d" device may be not the one intended for use. Adjust
- the selected device if needed.
+ DPCT1093: The "d" device may be not the one intended for use.
+ Adjust the selected device if needed.
*/
dpct::select_device(d);
dpct::get_current_device().queues_wait_and_throw();
@@ -237,8 +237,8 @@ void cvec_set_enabled(bool on) {
for (int d = 0; d < kDevices; ++d) {
if (g_dev[d].on == nullptr) continue;
/*
- DPCT1093: The "d" device may be not the one intended for use. Adjust
- the selected device if needed.
+ DPCT1093: The "d" device may be not the one intended for use.
+ Adjust the selected device if needed.
*/
dpct::select_device(d);
dpct::get_current_device()
diff --git a/sycl/src/kernels/cuda/dequant_bf16.dp.cpp b/sycl/src/kernels/cuda/dequant_bf16.dp.cpp
index 3f4e68a4f..272e95425 100644
--- a/sycl/src/kernels/cuda/dequant_bf16.dp.cpp
+++ b/sycl/src/kernels/cuda/dequant_bf16.dp.cpp
@@ -82,6 +82,17 @@ __dpct_inline__ void group32(const uint8_t *row_blocks, int gi_in_row, T *out) {
put(out, j, (float) (((b[6 + j] & 0x0F) | xh0) - 16) * d);
put(out, j + 16, (float) (((b[6 + j] >> 4) | xh1) - 16) * d);
}
+ } else if constexpr (TYPE == 7) { // Q5_1
+ const uint8_t* b = row_blocks + (size_t) gi_in_row * 24;
+ const float d = h2f(b), m = h2f(b + 2);
+ const uint32_t qh = (uint32_t) b[4] | ((uint32_t) b[5] << 8) |
+ ((uint32_t) b[6] << 16) | ((uint32_t) b[7] << 24);
+ for (int j = 0; j < 16; ++j) {
+ const int xh0 = ((qh >> j) & 1) << 4;
+ const int xh1 = ((qh >> (j + 16)) & 1) << 4;
+ put(out, j, (float) ((b[8 + j] & 15) | xh0) * d + m);
+ put(out, j + 16, (float) ((b[8 + j] >> 4) | xh1) * d + m);
+ }
} else if constexpr (TYPE == 8) { // Q8_0
const uint8_t* b = row_blocks + (size_t) gi_in_row * 34;
const float d = h2f(b);
@@ -192,6 +203,7 @@ bool geometry(int type, int& block_elems, int& block_bytes) {
switch (type) {
case 2: block_elems = 32; block_bytes = 18; return true;
case 6: block_elems = 32; block_bytes = 22; return true;
+ case 7: block_elems = 32; block_bytes = 24; return true;
case 8: block_elems = 32; block_bytes = 34; return true;
case 20: block_elems = 32; block_bytes = 18; return true;
case 11: block_elems = 256; block_bytes = 110; return true;
@@ -243,6 +255,7 @@ void launch(int type, const void* blocks, int64_t row0, int64_t rows, int64_t co
switch (type) {
case 2: STRATA_DQ(2);
case 6: STRATA_DQ(6);
+ case 7: STRATA_DQ(7);
case 8: STRATA_DQ(8);
case 11: STRATA_DQ(11);
case 12: STRATA_DQ(12);
diff --git a/sycl/src/kernels/cuda/fused_gr.dp.cpp b/sycl/src/kernels/cuda/fused_gr.dp.cpp
index 3421c8398..2a9f35b98 100644
--- a/sycl/src/kernels/cuda/fused_gr.dp.cpp
+++ b/sycl/src/kernels/cuda/fused_gr.dp.cpp
@@ -5,12 +5,18 @@
#include <sycl/sycl.hpp>
#include <dpct/dpct.hpp>
#include "strata/sycl_queue.hpp"
+#include "strata/core/emulate.hpp"
#include "strata/kernels/fused_gr.hpp"
#include "strata/kernels/bf16_bits.hpp"
#include "strata/kernels/verify_kernels.hpp"
+#include <atomic>
#include <cstdio>
#include <cstdlib>
+#include <cstring>
+#include <random>
+#include <string>
+#include <vector>
namespace strata::kernels {
namespace {
@@ -320,7 +326,7 @@ auto &part =
// elements of stream c in the same order as in the per-token kernel (i = 4t + 1024k), and the warp and cross-warp
// sums run in the same order, so rs and xn are bitwise the old kernel's. The scaled values stay in registers
// (at most 3 float4 per thread) instead of a second pass over global memory.
-__dpct_inline__ void gr_norm_split_kernel(GrMulti m) {
+__dpct_inline__ void gr_norm_split_port_kernel(GrMulti m) {
auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
auto& part = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[WARPS]>(item.get_group());
auto& s_rs = *sycl::ext::oneapi::group_local_memory_for_overwrite<float>(item.get_group());
@@ -952,6 +958,538 @@ auto &lo = *sycl::ext::oneapi::group_local_memory_for_overwrite<
m.a[k].mixed[d0 + col] = sum / (float) HC;
}
}
+// ================================ #315: split / staged - the same arithmetic, split differently ==================
+// The multi read's variants beside the plain read (0.1.31's default; not main's opt-in STRATA_GR_V3 read, which sums
+// in another order). Every variant computes each output with exactly the plain read's operations in its order (so
+// bitwise the plain read and the single-token read); only who does what, and when, changes. `fused_gr_check`
+// compares them on the card before a verify window uses them (STRATA_HC_SPLIT below).
+// - the norm (split and staged): one block per token AND stream instead of one per token. Each thread visits
+// exactly the elements, in the order, it visited for that stream in the plain read, so every sum of squares and rs
+// is the same; then it recomputes its R' * w_norm and writes it times rs (the plain read stored the product and
+// scaled it in place: the same two roundings). On an RTX 4080 SUPER, the plain read's norm took 0.58 ms per
+// 4-token round (96 launches of 1-4 blocks), this one 0.23 ms.
+// - the down projection, split: the plain read's kernel.
+// - the down projection, staged: the plain read's 8 rows per block and lane order, but the activations arrive by
+// cp.async in half-stream tiles, two in flight, so no thread waits on a chain of loads, and they sit in shared
+// memory as two planes (floats 0-3 and 4-7 of every 8), so a warp's reads hit no bank twice. The next tile's
+// weights are loaded while the current one is used. A tile is 160 = 5 x 32 chunks of 8, so a lane still
+// accumulates its chunks lane + 32 q in ascending order, as in the plain read with either tile. Before sm_80
+// (and on HIP) the staging is a plain copy: the same bits, only not asynchronous.
+constexpr int kHcPlain = 1, kHcSplit = 2, kHcStaged = 3;
+constexpr int H_TILE = 1280; // staged tile: half a stream = 160 chunks of 8, 5 per lane
+constexpr int HQ = H_TILE / 8 / 32;
+constexpr int N_HTILES = D / H_TILE; // 8
+static_assert(N % H_TILE == 0, "a staged tile never straddles two streams");
+static_assert(H_TILE % 256 == 0, "a staged tile holds whole rounds of 32 chunks: the plain read's lane order");
+
+/*
+DPCT1110: The total declared local variable size in device function
+gr_norm_split_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_norm_split_kernel(GrMulti m) {
+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
+auto &part = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[WARPS]>(
+ sycl::ext::oneapi::this_work_item::get_work_group<3>());
+ auto &s_rs = *sycl::ext::oneapi::group_local_memory_for_overwrite<float>(
+ sycl::ext::oneapi::this_work_item::get_work_group<3>());
+ const FusedGrArgs &a = m.a[item_ct1.get_group(2)];
+ const int c = item_ct1.get_group(1);
+ float *xn = m.xn + (size_t)item_ct1.get_group(2) * D;
+ const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
+ const float gw = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f;
+ float ss = 0.0f;
+ for (int i = t * 4; i < D; i += THREADS * 4) {
+ if (i / N != c) continue; // another stream's element: another block's
+ const int d = i - c * N;
+ sycl::float4 r = *reinterpret_cast<const sycl::float4 *>(a.R + i);
+ if (a.apply) {
+ const sycl::float4 b =
+ *reinterpret_cast<const sycl::float4 *>(a.bo_prev + d);
+ 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 float sq =
+ r.x() * r.x() + r.y() * r.y() + r.z() * r.z() + r.w() * r.w();
+ ss += sq;
+ }
+ const float v = warp_sum(ss);
+ if (lane == 0) part[warp] = 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 (t == 0) {
+ float s = 0.0f;
+#pragma unroll
+ for (int w = 0; w < WARPS; ++w) s += part[w];
+ s_rs = sycl::rsqrt(s / (float)N + a.eps);
+ a.rs[c] = s_rs;
+ }
+ /*
+ DPCT1065: Consider replacing sycl::nd_item::barrier() with
+ sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
+ performance if there is no access to global memory.
+ */
+ item_ct1.barrier();
+ const float rs = s_rs;
+ for (int i = t * 4; i < D; i += THREADS * 4) {
+ if (i / N != c) continue;
+ const int d = i - c * N;
+ sycl::float4 r = *reinterpret_cast<const sycl::float4 *>(a.R + i);
+ if (a.apply) {
+ const sycl::float4 b =
+ *reinterpret_cast<const sycl::float4 *>(a.bo_prev + d);
+ 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 =
+ *reinterpret_cast<const sycl::float4 *>(a.w_norm + i);
+ const float px = r.x() * g.x(), py = r.y() * g.y(), pz = r.z() * g.z(),
+ pw = r.w() * g.w();
+ *reinterpret_cast<sycl::float4 *>(xn + i) =
+ sycl::float4(px * rs, py * rs, pz * rs, pw * rs);
+ }
+}
+
+#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP >= 800 && \
+ !defined(__HIPCC__)
+#define STRATA_GR_CP_ASYNC 1
+#endif
+__dpct_inline__ void cp_async16(void *smem, const void *gmem) {
+#if defined(STRATA_GR_CP_ASYNC)
+ auto sa = smem;
+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
+ asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(sa),
+ "l"(gmem)
+ : "memory");
+#else
+ *(((uint32_t *)(uintptr_t)sa)) = *(((uint32_t *)(uintptr_t)gmem));
+ if (16 > 4)
+ *(((uint32_t *)(uintptr_t)sa) + 1) =
+ *(((uint32_t *)(uintptr_t)gmem) + 1);
+ if (16 > 8)
+ *(((uint32_t *)(uintptr_t)sa) + 2) =
+ *(((uint32_t *)(uintptr_t)gmem) + 2);
+ if (16 > 12)
+ *(((uint32_t *)(uintptr_t)sa) + 3) =
+ *(((uint32_t *)(uintptr_t)gmem) + 3);
+#endif
+#else
+ *reinterpret_cast<float4*>(smem) = *reinterpret_cast<const float4*>(gmem);
+#endif
+}
+__dpct_inline__ void cp_async_commit() {
+#if defined(STRATA_GR_CP_ASYNC)
+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
+ asm volatile("cp.async.commit_group;\n" ::: "memory");
+#else
+
+#endif
+#endif
+}
+__dpct_inline__ void cp_async_wait1() {
+#if defined(STRATA_GR_CP_ASYNC)
+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
+ asm volatile("cp.async.wait_group 1;\n" ::: "memory");
+#else
+
+#endif
+#endif
+}
+__dpct_inline__ void cp_async_wait0() {
+#if defined(STRATA_GR_CP_ASYNC)
+#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
+ asm volatile("cp.async.wait_group 0;\n" ::: "memory");
+#else
+
+#endif
+#endif
+}
+
+// `dot8` with its 8 activations as two float4: the same eight fmaf in the same order
+__dpct_inline__ float dot8v(const sycl::uint4 w, const sycl::float4 x0,
+ const sycl::float4 x1) {
+ float acc = 0.0f;
+ acc = sycl::fma(sycl::bit_cast<float>(w.x() << 16), (float)(x0.x()), acc);
+ acc = sycl::fma(sycl::bit_cast<float>(w.x() & 0xffff0000u), (float)(x0.y()),
+ acc);
+ acc = sycl::fma(sycl::bit_cast<float>(w.y() << 16), (float)(x0.z()), acc);
+ acc = sycl::fma(sycl::bit_cast<float>(w.y() & 0xffff0000u), (float)(x0.w()),
+ acc);
+ acc = sycl::fma(sycl::bit_cast<float>(w.z() << 16), (float)(x1.x()), acc);
+ acc = sycl::fma(sycl::bit_cast<float>(w.z() & 0xffff0000u), (float)(x1.y()),
+ acc);
+ acc = sycl::fma(sycl::bit_cast<float>(w.w() << 16), (float)(x1.z()), acc);
+ acc = sycl::fma(sycl::bit_cast<float>(w.w() & 0xffff0000u), (float)(x1.w()),
+ acc);
+ return acc;
+}
+
+// Stage tile `h` of every token into `buf`: [T][2 planes][160 chunks] float4, plane 0 = floats 0-3 of a chunk.
+__dpct_inline__ void stage_htile(const GrMulti &m, int T, int h,
+ sycl::float4 *buf, int t) {
+ for (int i = t; i < T * (H_TILE / 4); i += THREADS) {
+ const int k = i / (H_TILE / 4), s4 = i - k * (H_TILE / 4); // s4: float4 of the tile, chunk s4/2, half s4&1
+ const float* src = m.xn + (size_t) k * D + (size_t) h * H_TILE + (size_t) s4 * 4;
+ cp_async16(buf + (size_t) k * (H_TILE / 4) + (s4 & 1) * (H_TILE / 8) + (s4 >> 1), src);
+ }
+}
+
+/*
+DPCT1110: The total declared local variable size in device function
+gr_down_staged_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_staged_kernel(GrMulti m, uint8_t *dpct_local) {
+ auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
+ auto hbuf = (sycl::float4 *)dpct_local; // 2 buffers x [T][2][160] float4
+ const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
+ const int T = m.T;
+ const bool inject_block = item_ct1.get_group(2) == DOWN_BLOCKS;
+ const int row = inject_block ? warp : item_ct1.get_group(2) * WARPS + warp;
+ const bool active = !(inject_block && (m.a[0].w_inject == nullptr || warp >= HC));
+ const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D;
+ const sycl::uint4 *w4 = reinterpret_cast<const sycl::uint4 *>(wrow);
+ const size_t buf_f4 = (size_t) T * (H_TILE / 4); // float4 per buffer (the second one follows the first)
+ float acc[kFusedGrMaxT];
+#pragma unroll
+ for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f;
+ sycl::uint4 wv[HQ], wnext[HQ];
+ if (active) {
+#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 < HQ; ++q) wv[q] = *(w4 + lane + 32 * q);
+ }
+ stage_htile(m, T, 0, hbuf, t);
+ cp_async_commit();
+ stage_htile(m, T, 1, hbuf + buf_f4, t);
+ cp_async_commit();
+#pragma unroll 1
+ for (int h = 0; h < N_HTILES; ++h) {
+ if (active && h + 1 < N_HTILES) {
+#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 < HQ; ++q)
+ wnext[q] = *(w4 + (h + 1) * (H_TILE / 8) + lane + 32 * q);
+ }
+ if (h + 1 < N_HTILES) cp_async_wait1(); // tile h has landed (h + 1 may still be on its way)
+ else cp_async_wait0();
+ /*
+ DPCT1118: SYCL group functions and algorithms must be encountered in
+ converged control flow. You may need to adjust the code.
+ */
+ /*
+ DPCT1065: Consider replacing sycl::nd_item::barrier() with
+ sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
+ better performance if there is no access to global memory.
+ */
+ item_ct1.barrier();
+ const sycl::float4 *cur = hbuf + (h & 1) * buf_f4;
+ if (active) {
+#pragma unroll
+ for (int q = 0; q < HQ; ++q) {
+ const int j = lane + 32 * q;
+#pragma unroll
+ for (int k = 0; k < kFusedGrMaxT; ++k) {
+ if (k < T) {
+ const sycl::float4 *pk = cur + (size_t)k * (H_TILE / 4);
+ acc[k] += dot8v(wv[q], pk[j], pk[H_TILE / 8 + j]);
+ }
+ }
+ }
+ }
+ /*
+ DPCT1118: SYCL group functions and algorithms must be encountered in
+ converged control flow. You may need to adjust the code.
+ */
+ /*
+ DPCT1065: Consider replacing sycl::nd_item::barrier() with
+ sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
+ better performance if there is no access to global memory.
+ */
+ item_ct1.barrier(); // every warp is done with buffer h & 1
+ if (h + 2 < N_HTILES) stage_htile(m, T, h + 2, hbuf + (h & 1) * buf_f4, t);
+ cp_async_commit(); // an empty group at the end keeps the wait counts simple
+ if (h + 1 < N_HTILES) {
+#pragma unroll
+ for (int q = 0; q < HQ; ++q) wv[q] = wnext[q];
+ }
+ }
+ if (!active) return;
+ float s[kFusedGrMaxT];
+#pragma unroll
+ for (int k = 0; k < kFusedGrMaxT; ++k) s[k] = k < T ? warp_sum(acc[k]) : 0.0f;
+ // lane k writes token k (every lane holds every sum after the xor reduction)
+#pragma unroll
+ for (int k = 0; k < kFusedGrMaxT; ++k) {
+ if (k >= T || lane != k) continue;
+ if (inject_block) {
+ m.a[k].inject_out[row] = s[k];
+ } else {
+ const float x = s[k] / (float) HC;
+ m.a[k].lo[row] = x / (1.0f + sycl::native::exp(-x));
+ }
+ }
+}
+
+// The tokens a down kernel may carry in one launch on the current card, and the plain read's tile: the plain read
+// stages n_tok * TILEV floats (1280 on sm_75, 2560 elsewhere), staged two tiles of n_tok * H_TILE. The shared-memory
+// opt-in is set here once per device (a per-DEVICE setting: a layer split runs these kernels on two cards).
+int down_chunk(bool staged, int* tile_out) {
+ static bool attr[64] = {};
+ static int chunk[64] = {}; // tokens the plain down kernel may carry in one launch on this card
+ static int chunk_staged[64] = {}; // the same for staged
+ static int tile[64] = {}; // the plain down kernel's TILEV on this card (1280 on sm_75, 2560 elsewhere)
+ int dev = 0;
+ dev = dpct::get_current_device_id();
+ if (dev < 0 || dev >= 64) {
+ *tile_out = 2560;
+ return kFusedGrMaxT;
+ }
+ if (!attr[dev]) {
+ 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();
+ optin = strata::smem_optin_of(optin); // STRATA_EMULATE_CC (tests only)
+ // the down kernel stages n_tok*TILEV floats of dynamic shared memory - 80 KB at the full 8 tokens of the
+ // CUDA tile. sm_75 gets the smaller tile: all eight tokens fit one 40 KiB launch there (no more slicing),
+ // the TQ-5 prefetch holds half the registers, and the smaller blocks raise how many of the 41-block grid
+ // share an SM. Cards whose opt-in is still below that (or that report no opt-in at all) slice the tokens;
+ // 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.
+#if defined(__HIPCC__)
+ const bool small_tile = true; // all eight tokens fit gfx1100's 64 KiB LDS at this tile
+#else
+ int cc_maj = 0, cc_min = 0;
+ cc_maj = dpct::get_device(dev).get_major_version();
+ cc_min = dpct::get_device(dev).get_minor_version();
+ const bool small_tile = strata::cc_major_of(cc_maj) * 10 + strata::cc_minor_of(cc_min) == 75;
+#endif
+ const int tv = small_tile ? 1280 : 2560;
+ tile[dev] = tv;
+ int want = (int) (kFusedGrMaxT * tv * sizeof(float));
+ if (optin > 0 && want > optin) want = optin;
+ if (small_tile) {
+ /*
+ DPCT1026: The call to cudaFuncSetAttribute was removed because
+ SYCL currently does not support corresponding setting.
+ */
+ } else {
+ /*
+ DPCT1026: The call to cudaFuncSetAttribute was removed because
+ SYCL currently does not support corresponding setting.
+ */
+ }
+ int want_staged = (int) (2 * kFusedGrMaxT * H_TILE * sizeof(float));
+ if (optin > 0 && want_staged > optin) want_staged = 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
+ // The opt-in is a promise a pre-Volta card does not keep: an sm_60 answers
+ // 65536 and accepts the cudaFuncSetAttribute for 61440 B, then fails the
+ // LAUNCH with "invalid argument". What such a card will launch is its
+ // per-block limit, so the capacity comes from that below sm_70 - the same
+ // tokens the "no opt-in" branch assumes, but taken from the attribute that is
+ // actually enforced.
+#if defined(__HIPCC__)
+ const int usable = optin > 0 ? optin : 48 * 1024;
+#else
+ int cc = 0, per_block = 0;
+ cc = dpct::get_device(dev).get_major_version();
+ per_block = (int) dpct::get_device(dev).get_local_mem_size(); // SYCL: the work-group local memory
+ cc = strata::cc_major_of(cc);
+ const int usable = (cc >= 7 && optin > 0) ? optin : per_block;
+#endif
+ const int capacity = usable / (int) (tv * sizeof(float));
+ chunk[dev] = capacity < 1 ? 1 : (capacity > kFusedGrMaxT ? kFusedGrMaxT : capacity);
+ const int capacity_staged = usable / (int) (2 * H_TILE * sizeof(float));
+ chunk_staged[dev] = capacity_staged < 1 ? 1 : (capacity_staged > kFusedGrMaxT ? kFusedGrMaxT : capacity_staged);
+ attr[dev] = true;
+ }
+ *tile_out = tile[dev] ? tile[dev] : 2560;
+ return staged ? chunk_staged[dev] : chunk[dev];
+}
+
+// The multi read as `variant` (kHcPlain, kHcSplit or kHcStaged): the norm, the down projection in launches of as
+// many tokens as fit the card, the up projection; the profile's stamps after the norm and after the down projection.
+// kHcPlain is the default read exactly as before (never main's opt-in STRATA_GR_V3 path, which fused_gr_read_multi
+// takes first).
+void launch_multi(const GrMulti &m, int variant, dpct::queue_ptr st,
+ unsigned long long *stamp_buf, int stamp_i0) {
+ const int n_tok = m.T;
+ if (variant >= kHcSplit) {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+
+ st->parallel_for<dpct_kernel_name<class gr_norm_split_kernel_200589>>(
+ sycl::nd_range<3>(sycl::range(1, HC, (unsigned)n_tok) *
+ 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_norm_split_kernel(m);
+ });
+ } else {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+
+ st->parallel_for<dpct_kernel_name<class gr_norm_multi_kernel_2f4d93>>(
+ sycl::nd_range<3>(sycl::range(1, 1, n_tok) *
+ 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_norm_multi_kernel(m);
+ });
+ }
+ if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, (void*) st);
+ const bool staged = variant >= kHcStaged;
+ int tv = 2560;
+ const int chunk_tok = down_chunk(staged, &tv);
+ /*
+ 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 per_tok =
+ (staged ? (size_t)2 * H_TILE : (size_t)tv) * sizeof(float);
+ for (int c0 = 0; c0 < n_tok; c0 += chunk_tok) {
+ const int ct = n_tok - c0 < chunk_tok ? n_tok - c0 : chunk_tok;
+ GrMulti c{};
+ if (ct == n_tok) {
+ c = m;
+ } else {
+ c.xn = m.xn + (size_t) c0 * D;
+ c.T = ct;
+ for (int k = 0; k < ct; ++k) c.a[k] = m.a[c0 + k];
+ }
+ const size_t smem = (size_t) ct * per_tok;
+ if (staged) {
+ 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(smem), cgh);
+
+ cgh.parallel_for<
+ dpct_kernel_name<class gr_down_staged_kernel_41b428>>(
+ sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 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_staged_kernel(
+ c, dpct_local_acc_ct1
+ .get_multi_ptr<sycl::access::decorated::no>()
+ .get());
+ });
+ });
+ } else if (tv == 1280) {
+ 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(smem), cgh);
+
+ cgh.parallel_for<
+ dpct_kernel_name<class gr_down_multi_kernel_fa80e0,
+ dpct_kernel_scalar<1280>>>(
+ sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 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<1280>(
+ c, 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(smem), cgh);
+
+ cgh.parallel_for<
+ dpct_kernel_name<class gr_down_multi_kernel_41414e,
+ dpct_kernel_scalar<2560>>>(
+ sycl::nd_range<3>(sycl::range(1, 1, DOWN_BLOCKS + 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<2560>(
+ c, dpct_local_acc_ct1
+ .get_multi_ptr<sycl::access::decorated::no>()
+ .get());
+ });
+ });
+ }
+ }
+ if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st);
+ {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+
+ st->parallel_for<dpct_kernel_name<class gr_up_multi_kernel_1a7280>>(
+ 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_multi_kernel(m);
+ });
+ }
+}
+
+/// STRATA_HC_SPLIT: unset or 2 = the newest the check accepts (staged), 1 = at most split, 0 = the plain read
+int env_variant() {
+ const char* e = std::getenv("STRATA_HC_SPLIT");
+ if (e == nullptr || e[0] == '\0') return kHcStaged;
+ if (e[0] == '0') return kHcPlain;
+ if (e[0] == '1') return kHcSplit;
+ return kHcStaged;
+}
+
+// per device: the variant `fused_gr_check` chose (0 = not checked yet)
+std::atomic<int> g_variant[64];
+
} // namespace
// one partials buffer per queue (the verifier's and the drafter's launches never share a queue; within a queue the
@@ -1128,7 +1666,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi
if (gr_norm_split())
st->parallel_for<dpct_kernel_name<class gr_norm_split_k>>(
sycl::nd_range<3>(sycl::range(1, 1, n_tok * HC) * sycl::range(1, 1, THREADS), sycl::range(1, 1, THREADS)),
- [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { gr_norm_split_kernel(m); });
+ [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { gr_norm_split_port_kernel(m); });
else
st->parallel_for<dpct_kernel_name<class gr_norm_multi_kernel_2f4d92>>(
sycl::nd_range<3>(sycl::range(1, 1, n_tok) *
@@ -1310,4 +1848,280 @@ void fused_gr_read(const FusedGrArgs& a, void* stream) {
const dpct::err0 e = 0;
}
+
+namespace {
+
+/// The plain read, split, staged and (for one token) the single-token read on random bf16 weights and random inputs,
+/// 1..8 tokens, with and without the pending write; every output of split and staged compared with the plain read's
+/// bit for bit (and the plain read's with the single-token read's). `why[v]` gets the first difference of variant
+/// v; false if the check itself could not run.
+bool fused_gr_selftest(bool ok_variant[4], std::string why[4]) try {
+ constexpr int TM = kFusedGrMaxT;
+ constexpr int NV = 4; // sets: 0 = plain, 1 = split, 2 = staged, 3 = single-token
+ std::mt19937 rng(20260930u);
+ std::normal_distribution<float> nd(0.0f, 1.0f);
+ std::vector<uint16_t> h_down((size_t) LR * D), h_up((size_t) D * LR), h_inj((size_t) HC * D);
+ std::vector<float> h_norm(D), h_R((size_t) TM * D), h_bo((size_t) TM * N), h_ip((size_t) TM * HC);
+ for (auto& w : h_down) w = bf16_from_f32(0.02f * nd(rng));
+ for (auto& w : h_up) w = bf16_from_f32(0.05f * nd(rng));
+ for (auto& w : h_inj) w = bf16_from_f32(0.02f * nd(rng));
+ for (auto& w : h_norm) w = 1.0f + 0.1f * nd(rng);
+ for (auto& x : h_R) x = nd(rng);
+ for (auto& x : h_bo) x = 0.5f * nd(rng);
+ for (auto& x : h_ip) x = 2.0f * nd(rng);
+ for (int v = 0; v < 4; ++v) { ok_variant[v] = v == 1; why[v].clear(); }
+
+ const size_t n_set = (size_t) TM * (D + D + LR + HC + HC + N); // R_out, xn, lo, rs, inject, mixed (floats)
+ const size_t bytes = h_down.size() * 2 + h_up.size() * 2 + h_inj.size() * 2 +
+ (h_norm.size() + h_R.size() + h_bo.size() + h_ip.size() + NV * n_set) * 4 + 32 * 256;
+ uint8_t* base = nullptr;
+ if (DPCT_CHECK_ERROR(base = (uint8_t *)sycl::malloc_device(
+ bytes, dpct::get_in_order_queue())) != 0) {
+ /*
+ DPCT1026: The call to cudaGetLastError was removed because this
+ functionality is redundant in SYCL.
+ */
+ why[0] =
+ "no room for the check (" + std::to_string(bytes >> 20) + " MiB)";
+ return false;
+ }
+ size_t off = 0;
+ auto take = [&](size_t b) { void* p = base + off; off += (b + 255) / 256 * 256; return p; };
+ uint16_t* d_down = (uint16_t*) take(h_down.size() * 2);
+ uint16_t* d_up = (uint16_t*) take(h_up.size() * 2);
+ uint16_t* d_inj = (uint16_t*) take(h_inj.size() * 2);
+ float* d_norm = (float*) take(h_norm.size() * 4);
+ float* d_R = (float*) take(h_R.size() * 4);
+ float* d_bo = (float*) take(h_bo.size() * 4);
+ float* d_ip = (float*) take(h_ip.size() * 4);
+ struct Set { float *R_out, *xn, *lo, *rs, *inj, *mixed; } set[NV];
+ for (Set& x : set) {
+ x.R_out = (float*) take((size_t) TM * D * 4); x.xn = (float*) take((size_t) TM * D * 4);
+ x.lo = (float*) take((size_t) TM * LR * 4); x.rs = (float*) take((size_t) TM * HC * 4);
+ x.inj = (float*) take((size_t) TM * HC * 4); x.mixed = (float*) take((size_t) TM * N * 4);
+ }
+ dpct::queue_ptr st = &dpct::get_in_order_queue();
+ /*
+ DPCT1025: The SYCL queue is created ignoring the flag and priority
+ options.
+ */
+ bool ok =
+ off <= bytes &&
+ DPCT_CHECK_ERROR(st = dpct::get_current_device().create_queue(true)) ==
+ 0 &&
+ /*
+ 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.
+ */
+ DPCT_CHECK_ERROR(
+ st->memcpy(d_down, h_down.data(), h_down.size() * 2)) == 0 &&
+ /*
+ 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.
+ */
+ DPCT_CHECK_ERROR(st->memcpy(d_up, h_up.data(), h_up.size() * 2)) == 0 &&
+ /*
+ 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.
+ */
+ DPCT_CHECK_ERROR(st->memcpy(d_inj, h_inj.data(), h_inj.size() * 2)) ==
+ 0 &&
+ /*
+ 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.
+ */
+ DPCT_CHECK_ERROR(
+ st->memcpy(d_norm, h_norm.data(), h_norm.size() * 4)) == 0 &&
+ /*
+ 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.
+ */
+ DPCT_CHECK_ERROR(st->memcpy(d_R, h_R.data(), h_R.size() * 4)) == 0 &&
+ /*
+ 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.
+ */
+ DPCT_CHECK_ERROR(st->memcpy(d_bo, h_bo.data(), h_bo.size() * 4)) == 0 &&
+ /*
+ 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.
+ */
+ DPCT_CHECK_ERROR(st->memcpy(d_ip, h_ip.data(), h_ip.size() * 4)) == 0;
+ if (!ok) why[0] = "setting up the check failed";
+ std::vector<float> h1, h2;
+ // true when equal; false with the first difference in `w` (or a read-back failure in `ok`)
+ auto same = [&](const float* d1, const float* d2, size_t n, const char* what, int T, int apply, std::string& w) {
+ h1.resize(n);
+ h2.resize(n);
+ /*
+ 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(st->memcpy(h1.data(), d1, n * 4)) != 0 ||
+ /*
+ 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.
+ */
+ DPCT_CHECK_ERROR(st->memcpy(h2.data(), d2, n * 4)) != 0 ||
+ DPCT_CHECK_ERROR(st->wait()) != 0) {
+ why[0] = "reading back the check failed";
+ ok = false;
+ return false;
+ }
+ for (size_t i = 0; i < n; ++i) {
+ uint32_t u1, u2;
+ std::memcpy(&u1, &h1[i], 4);
+ std::memcpy(&u2, &h2[i], 4);
+ if (u1 != u2) {
+ char buf[192];
+ std::snprintf(buf, sizeof buf, "%s differs for %d token(s)%s at %zu (%08x, not %08x)", what, T,
+ apply ? " with the pending write" : "", i, u2, u1);
+ w = buf;
+ return false;
+ }
+ }
+ return true;
+ };
+ auto all_same = [&](const Set& s1, const Set& s2, int T, int apply, std::string& w) {
+ return same(s1.lo, s2.lo, (size_t) T * LR, "lo", T, apply, w) &&
+ same(s1.rs, s2.rs, (size_t) T * HC, "rs", T, apply, w) &&
+ same(s1.inj, s2.inj, (size_t) T * HC, "inject", T, apply, w) &&
+ same(s1.mixed, s2.mixed, (size_t) T * N, "mixed", T, apply, w) &&
+ same(s1.R_out, s2.R_out, (size_t) T * D, "R", T, apply, w);
+ };
+ ok_variant[2] = ok_variant[3] = ok;
+ bool single_ok = ok;
+ for (int apply = 0; apply < 2 && ok; ++apply) {
+ for (int T = 1; T <= TM && ok; ++T) {
+ FusedGrArgs a[NV][TM];
+ for (int v = 0; v < NV; ++v) {
+ const size_t span = (size_t) ((uint8_t*) (set[v].mixed + (size_t) TM * N) - (uint8_t*) set[v].R_out);
+ ok = ok &&
+ DPCT_CHECK_ERROR(st->memset(set[v].R_out, 0xFF, span)) ==
+ 0; // the whole set
+ for (int k = 0; k < T; ++k) {
+ FusedGrArgs& x = a[v][k];
+ x.R = d_R + (size_t) k * D; x.R_out = set[v].R_out + (size_t) k * D; x.apply = apply != 0;
+ x.bo_prev = d_bo + (size_t) k * N; x.inj_prev = d_ip + (size_t) k * HC;
+ x.w_norm = d_norm; x.w_down = d_down; x.w_up = d_up; x.w_inject = d_inj; x.eps = 1e-6f;
+ x.lo = set[v].lo + (size_t) k * LR; x.rs = set[v].rs + (size_t) k * HC;
+ x.inject_out = set[v].inj + (size_t) k * HC; x.mixed = set[v].mixed + (size_t) k * N;
+ }
+ }
+ for (int v = 0; v < 3; ++v) {
+ GrMulti m;
+ for (int k = 0; k < T; ++k) m.a[k] = a[v][k];
+ m.xn = set[v].xn;
+ m.T = T;
+ launch_multi(m, v + 1, st, nullptr, 0);
+ }
+ if (T == 1) fused_gr_read(a[3][0], st);
+ /*
+ DPCT1010: SYCL uses exceptions to report errors and does not
+ use the error codes. The cudaGetLastError function call was replaced
+ with 0. You need to rewrite this code.
+ */
+ if (0 != 0 || DPCT_CHECK_ERROR(st->wait()) != 0) {
+ why[0] = "a kernel of the check failed";
+ ok = false;
+ break;
+ }
+ if (ok_variant[2] && !all_same(set[0], set[1], T, apply, why[2])) ok_variant[2] = false;
+ if (ok && ok_variant[3] && !all_same(set[0], set[2], T, apply, why[3])) ok_variant[3] = false;
+ if (ok && T == 1 && single_ok && !all_same(set[3], set[0], T, apply, why[1])) single_ok = false;
+ }
+ }
+ if (!single_ok && ok) { // the plain read itself disagrees with the single-token read
+ why[2] = why[3] = "the plain read differs from the single-token read: " + why[1];
+ ok_variant[2] = ok_variant[3] = false;
+ }
+ if (st != &dpct::get_in_order_queue()) {
+ st->wait();
+ dpct::get_current_device().destroy_queue(st);
+ }
+ sycl::free(base, dpct::get_in_order_queue());
+ /*
+ DPCT1026: The call to cudaGetLastError was removed because this
+ functionality is redundant in SYCL.
+ */
+ if (!ok) ok_variant[2] = ok_variant[3] = false;
+ return ok;
+}
+catch (sycl::exception const &exc) {
+ std::cerr << exc.what() << "Exception caught at file:" << __FILE__
+ << ", line:" << __LINE__ << std::endl;
+ std::exit(1);
+}
+
+} // namespace
+
+int fused_gr_variant() {
+ int dev = 0;
+ dev = dpct::get_current_device_id();
+ const int v = dev >= 0 && dev < 64 ? g_variant[dev].load() : 0;
+ if (v > 0) return v;
+ // not checked on this card: the plain read, unless STRATA_HC_SPLIT names a variant (a test such as gr_parity)
+ const char* e = std::getenv("STRATA_HC_SPLIT");
+ return e != nullptr && (e[0] == '1' || e[0] == '2') ? env_variant() : kHcPlain;
+}
+
+void fused_gr_check() {
+ int dev = 0;
+ dev = dpct::get_current_device_id();
+ if (dev < 0 || dev >= 64 || g_variant[dev].load() > 0) return;
+ // SYCL port: the port's own read (sliced down / split norm, STRATA_GR_DOWN_SLICED etc.) does not use upstream's
+ // variants, and their self-test crashes on the B70 (0.1.32 merge, under investigation): opt-in only.
+ if (std::getenv("STRATA_HC_CHECK") == nullptr) {
+ g_variant[dev].store(kHcPlain);
+ return;
+ }
+ const int want = env_variant();
+ if (want == kHcPlain) {
+ g_variant[dev].store(kHcPlain);
+ std::fprintf(stderr, "strata hc: CUDA%d: the hyper-connection read runs as the plain one (STRATA_HC_SPLIT=0)\n",
+ dev);
+ return;
+ }
+ bool okv[4];
+ std::string why[4];
+ const bool ran = fused_gr_selftest(okv, why);
+ int use = kHcPlain;
+ if (want >= kHcStaged && okv[kHcStaged]) use = kHcStaged;
+ else if (okv[kHcSplit]) use = kHcSplit;
+ g_variant[dev].store(use);
+ if (!ran)
+ std::fprintf(stderr, "strata hc: CUDA%d: the check of split/staged could not run (%s)\n", dev, why[0].c_str());
+ static const char* const name[4] = {"", "plain", "split", "staged"};
+ for (int v = kHcStaged; v >= kHcSplit; --v)
+ if (v <= want && !okv[v] && ran)
+ std::fprintf(stderr, "strata hc: CUDA%d: the %s read differs from the plain read on this card - not used: "
+ "%s\n", dev, name[v], why[v].c_str());
+ static const char* const what[4] = {
+ "", "the plain read (the norm per token, the down projection on 41 blocks)",
+ "split (the norm per token and stream, then the plain read's down projection)",
+ "staged (the norm per token and stream, the down projection's activations staged ahead by cp.async)"};
+ std::fprintf(stderr, "strata hc: CUDA%d: the hyper-connection read runs as %s%s\n", dev, what[use],
+ use >= kHcSplit ? "; checked bit for bit against the plain read on this card (STRATA_HC_SPLIT=1 or 0 "
+ "for the earlier ones)" : "");
+}
+
+
} // namespace strata::kernels
diff --git a/sycl/src/kernels/cuda/iq_kernels.dp.cpp b/sycl/src/kernels/cuda/iq_kernels.dp.cpp
index 375517367..2d035a7fc 100644
--- a/sycl/src/kernels/cuda/iq_kernels.dp.cpp
+++ b/sycl/src/kernels/cuda/iq_kernels.dp.cpp
@@ -1816,7 +1816,17 @@ inline void dq_q8_0(const void *vx, int64_t ibs, dst_t *yy, int tid) {
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.
+// BF16 (the token embedding as the checkpoint ships it, tools/embd_bf16_pack.py): 8 values per thread.
+template <typename dst_t>
+inline void dq_bf16(const void *vx, int64_t ibs, dst_t *yy, int tid) {
+ const uint16_t* x = (const uint16_t*) vx + ibs * 256 + tid * 8;
+#pragma unroll
+ for (int j = 0; j < 8; ++j) yy[tid * 8 + j] =
+ cvt<dst_t>(sycl::bit_cast<float>((uint32_t)x[j] << 16));
+}
+
+// Every type below must also be in is_iq() (BF16: embed_type_supported): 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) {
@@ -1838,6 +1848,7 @@ dq_dispatch(int ty, const void *vx, int64_t ibs, dst_t *y, int tid) {
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;
+ case 30: dq_bf16(vx, ibs, y, tid); break;
default: break;
}
}
@@ -2170,6 +2181,7 @@ 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); }
+bool embed_type_supported(int t) noexcept { return is_iq(t) || t == 30; }
size_t iq_row_bytes(int t, int64_t n) noexcept {
switch (t) {
@@ -2187,6 +2199,7 @@ size_t iq_row_bytes(int t, int64_t n) noexcept {
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);
+ case 30: return (size_t) n * 2; // BF16: the token embedding only (iq_embed_rows, iq_dequant_f32)
default: return 0;
}
}
@@ -2270,7 +2283,7 @@ __dpct_inline__ void embed_rows_kernel(
void iq_embed_rows(int t, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok, int64_t n_embd,
float* out, void* stream) {
if (n_tok <= 0) return;
- if (n_embd % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_embed_rows: bad arguments\n"); std::exit(1); }
+ if (n_embd % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_embed_rows: bad arguments\n"); std::exit(1); }
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
@@ -2299,7 +2312,7 @@ void iq_embed_rows(int t, const void* table, size_t row_bytes, const int32_t* to
}
void iq_dequant_f32(int t, const void* src, int64_t n, float* dst, void* stream) {
- if (n % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_f32: bad arguments\n"); std::exit(1); }
+ if (n % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_dequant_f32: bad arguments\n"); std::exit(1); }
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
diff --git a/sycl/src/kernels/cuda/native_gdn_preprocess.dp.cpp b/sycl/src/kernels/cuda/native_gdn_preprocess.dp.cpp
index d9f3b1f9d..5e7d69313 100644
--- a/sycl/src/kernels/cuda/native_gdn_preprocess.dp.cpp
+++ b/sycl/src/kernels/cuda/native_gdn_preprocess.dp.cpp
@@ -147,8 +147,10 @@ __dpct_inline__ void gate_softplus(const float *__restrict__ alpha,
OpenCL C 1.2 standard.
*/
const float value = alpha[i] + dt[i];
- const float softplus =
- value > 20.0f ? value : sycl::log(1.0f + sycl::native::exp(value));
+ const float softplus = value > 20.0f
+ ? value
+ : sycl::log1p(sycl::native::exp(
+ value)); // 1 + e^v loses e^v below ~1e-7
gate[i] = softplus * ssm_a[i];
}
diff --git a/sycl/src/kernels/cuda/native_gr_postops.dp.cpp b/sycl/src/kernels/cuda/native_gr_postops.dp.cpp
index 48d9be425..436af20f3 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 177fa97d0..5f284fc59 100644
--- a/sycl/src/kernels/cuda/native_mmvq.dp.cpp
+++ b/sycl/src/kernels/cuda/native_mmvq.dp.cpp
@@ -223,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) {
@@ -2643,7 +2643,7 @@ void native_iq4_nl_f32(const void* weights, const float* x, void* scratch_q8_1,
}
bool native_mmvq_supported(int ggml_type) noexcept {
- return ggml_type == 2 || ggml_type == 6 || ggml_type == 8 || ggml_type == 11 ||
+ return ggml_type == 2 || ggml_type == 6 || ggml_type == 7 || ggml_type == 8 || ggml_type == 11 ||
ggml_type == 12 || ggml_type == 13 || ggml_type == 14 || ggml_type == 20 ||
ggml_type == 23 || ggml_type == 42 || ggml_type == 16 || ggml_type == 17 || ggml_type == 18 ||
ggml_type == 21 || ggml_type == 22 || ggml_type == 29;
@@ -2654,6 +2654,7 @@ std::size_t native_mmvq_weight_bytes(int ggml_type, int n_in, int n_out) {
switch (ggml_type) {
case 2: block_elems = 32; block_bytes = 18; break;
case 6: block_elems = 32; block_bytes = 22; break;
+ case 7: block_elems = 32; block_bytes = 24; break;
case 8: block_elems = 32; block_bytes = 34; break;
case 20: block_elems = 32; block_bytes = 18; break;
case 11: block_elems = 256; block_bytes = 110; break;
@@ -2680,6 +2681,7 @@ void native_mmvq(int ggml_type, const void* weights, const void* x_q8_1, float*
switch (ggml_type) {
case 2: native_q4_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
case 6: native_q5_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
+ case 7: iq_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
case 8: native_q8_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
case 20: native_iq4_nl_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
case 11: native_q3_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
diff --git a/sycl/src/kernels/cuda/native_qsa_indexer.dp.cpp b/sycl/src/kernels/cuda/native_qsa_indexer.dp.cpp
index 3c3c062c0..52f01ccba 100644
--- a/sycl/src/kernels/cuda/native_qsa_indexer.dp.cpp
+++ b/sycl/src/kernels/cuda/native_qsa_indexer.dp.cpp
@@ -48,15 +48,18 @@ 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, float freq_scale, float corr_low,
- float corr_high, float ext_factor, float mscale,
- const int32_t *__restrict__ mtab) {
+// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table. The host launches <false> whenever
+// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it;
+// with it merely skipped at run time, the compiled default path changed its results).
+template <bool TAB>
+__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, RopeTab rt) {
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;
@@ -128,11 +131,13 @@ __dpct_inline__ void append(const float *__restrict__ raw,
const int pair = d % (ROT / 2);
// 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);
+ if (!(TAB && rope_tab_cs(rt, pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s))) {
+ const float theta_extrap =
+ (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) *
+ dpct::pow(theta_scale, float(pair));
+ 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;
}
@@ -146,22 +151,25 @@ __dpct_inline__ void append(const float *__restrict__ raw,
// the RMS norm, gamma, the rotation at pos_base + 4b. `k(j)` is the key of the block's cell j: a row of this batch
// (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, float freq_scale,
- float corr_low, float corr_high,
- float ext_factor, float mscale,
- const int32_t *mtab, bool zero_pos) {
+template <bool TAB>
+__dpct_inline__ float
+pooled_value(const float *values, int d, int rope_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,
+ const RopeTab &rt) {
float y = values[d];
if (d < ROT) {
const int pair = d % (ROT / 2);
// 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);
+ if (!(TAB && rope_tab_cs(rt, zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s))) {
+ const float theta_extrap =
+ (zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair)) *
+ dpct::pow(theta_scale, float(pair));
+ 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;
}
@@ -183,12 +191,13 @@ __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
+template <bool TAB>
__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) {
+ const int32_t *__restrict__ mtab, RopeTab rt) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
const int d = item_ct1.get_local_id(2);
auto &values =
@@ -225,18 +234,18 @@ append_first(const float *__restrict__ raw, const float *__restrict__ gamma,
const float scale = sycl::rsqrt(square_sum / D + epsilon);
if (d < D) values[d] = scale * mean * gamma[d];
/*
- DPCT1113: Consider replacing
- sycl::nd_item::barrier(sycl::access::fence_space::local_space) with
- sycl::nd_item::barrier() if function "append_first" is called in a
- multidimensional kernel.
+ 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(sycl::access::fence_space::local_space);
+ item_ct1.barrier();
if (d >= D) return;
- const float y = pooled_value(values, d, 0, theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale,
- mtab, true);
+ const float y = pooled_value<TAB>(values, d, 0, theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale,
+ mtab, true, rt);
pooled[d] = y;
dead[d] = y;
}
+template <bool TAB>
__dpct_inline__ void
append_blocks(const float *__restrict__ raw, int64_t n, int64_t p0,
int pos_base, const float *__restrict__ gamma, float epsilon,
@@ -244,8 +253,8 @@ append_blocks(const float *__restrict__ raw, int64_t n, int64_t p0,
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) {
+ float ext_factor, float mscale, const int32_t *__restrict__ mtab,
+ RopeTab rt) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
const int64_t b = first_block + item_ct1.get_group(2);
const int d = item_ct1.get_local_id(2);
@@ -288,11 +297,16 @@ append_blocks(const float *__restrict__ raw, int64_t n, int64_t p0,
const float square_sum = norm_scale(mean, partials, d);
const float scale = sycl::rsqrt(square_sum / D + epsilon);
if (d < D) values[d] = scale * mean * gamma[d];
- item_ct1.barrier(sycl::access::fence_space::local_space);
+ /*
+ 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 (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, freq_scale, corr_low, corr_high,
- ext_factor, mscale, mtab, false);
+ pooled[std::size_t(b) * D + d] = pooled_value<TAB>(values, d, rope_pos, theta_scale, freq_scale, corr_low, corr_high,
+ ext_factor, mscale, mtab, false, rt);
if (b == last_block) {
pooled[std::size_t(b + 1) * D + d] = dead[d];
if (d == 0) *block_pos = rope_pos;
@@ -342,6 +356,8 @@ void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_dev
if (overlaps(spans[i], spans[j])) throw std::invalid_argument("native QSA indexer buffers overlap");
const float theta_scale = powf((float) scaling.freq_base, -2.0f / ROT);
const RopeKernelArgs k = scaling.kernel_args(ROT); // none: the identity constants
+ const RopeTab rt = rope_table_for(scaling);
+ if (rt.cos != nullptr)
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
@@ -350,18 +366,42 @@ void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_dev
->submit([&](sycl::handler &cgh) {
auto mrope_table_ct16 = mrope_table();
- cgh.parallel_for<dpct_kernel_name<class append_182f95>>(
+ cgh.parallel_for<dpct_kernel_name<class append_182f95,
+ dpct_kernel_scalar<true>>>(
+ sycl::nd_range<3>(sycl::range(1, 1, THREADS),
+ sycl::range(1, 1, THREADS)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1)
+ [[sycl::reqd_sub_group_size(32)]] {
+ append<true>(raw, relative_pos_device, pos_base,
+ gamma, epsilon, b.tail, b.dead,
+ b.pooled, b.block_pos, int(max_cells),
+ theta_scale, k.freq_scale, k.corr_low,
+ k.corr_high, k.ext_factor,
+ k.attn_factor, mrope_table_ct16, rt);
+ });
+ });
+ } else {
+ 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_ct16 = mrope_table();
+
+ cgh.parallel_for<dpct_kernel_name<class append_182f95,
+ dpct_kernel_scalar<false>>>(
sycl::nd_range<3>(sycl::range(1, 1, THREADS),
sycl::range(1, 1, THREADS)),
exp_props,
[=](sycl::nd_item<3> item_ct1)
[[sycl::reqd_sub_group_size(32)]] {
- append(raw, relative_pos_device, pos_base, gamma,
- epsilon, b.tail, b.dead, b.pooled,
- b.block_pos, int(max_cells), theta_scale,
- k.freq_scale, k.corr_low, k.corr_high,
- k.ext_factor, k.attn_factor,
- mrope_table_ct16);
+ append<false>(raw, relative_pos_device, pos_base,
+ gamma, epsilon, b.tail, b.dead,
+ b.pooled, b.block_pos, int(max_cells),
+ theta_scale, k.freq_scale, k.corr_low,
+ k.corr_high, k.ext_factor,
+ k.attn_factor, mrope_table_ct16, rt);
});
});
}
@@ -399,36 +439,77 @@ void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, in
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();
+ const RopeTab rt = rope_table_for(scaling);
if (p0 == 0) {
+ if (rt.cos != nullptr)
+ {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+
+ st->parallel_for<dpct_kernel_name<class append_first_ea2d1f,
+ dpct_kernel_scalar<true>>>(
+ sycl::nd_range<3>(sycl::range(1, 1, THREADS),
+ sycl::range(1, 1, THREADS)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1)
+ [[sycl::reqd_sub_group_size(32)]] {
+ append_first<true>(raw, gamma, epsilon, b.dead,
+ b.pooled, theta_scale, fsf, cl, ch,
+ ef, ms, mtab, rt);
+ });
+ } else {
+ auto exp_props = sycl::ext::oneapi::experimental::properties{
+ sycl::ext::oneapi::experimental::use_root_sync};
+
+ st->parallel_for<dpct_kernel_name<class append_first_ea2d1f,
+ dpct_kernel_scalar<false>>>(
+ sycl::nd_range<3>(sycl::range(1, 1, THREADS),
+ sycl::range(1, 1, THREADS)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1)
+ [[sycl::reqd_sub_group_size(32)]] {
+ append_first<false>(raw, gamma, epsilon, b.dead,
+ b.pooled, theta_scale, fsf, cl, ch,
+ ef, ms, mtab, rt);
+ });
+ }
+ }
+ // completed blocks: those whose last cell (4b+3) lies in [p0, p0 + n)
+ const int64_t first = p0 <= R - 1 ? 0 : (p0 - (R - 1) + R - 1) / R; // the smallest b with 4b+3 >= p0
+ const int64_t hi = p0 + n - 1 >= R - 1 ? (p0 + n - 1 - (R - 1)) / R : -1; // the largest b with 4b+3 <= p0+n-1
+ if (hi >= first && rt.cos != nullptr)
+ {
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
- st->parallel_for<dpct_kernel_name<class append_first_ea2d1f>>(
- sycl::nd_range<3>(sycl::range(1, 1, THREADS),
+ st->parallel_for<dpct_kernel_name<class append_blocks_a6c94e,
+ dpct_kernel_scalar<true>>>(
+ sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(hi - first + 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)]] {
- append_first(raw, gamma, epsilon, b.dead, b.pooled, theta_scale,
- fsf, cl, ch, ef, ms, mtab);
+ append_blocks<true>(raw, n, p0, pos_base, gamma, epsilon,
+ b.tail, b.dead, b.pooled, b.block_pos,
+ first, hi, theta_scale, fsf, cl, ch, ef, ms,
+ mtab, rt);
});
- }
- // completed blocks: those whose last cell (4b+3) lies in [p0, p0 + n)
- const int64_t first = p0 <= R - 1 ? 0 : (p0 - (R - 1) + R - 1) / R; // the smallest b with 4b+3 >= p0
- const int64_t hi = p0 + n - 1 >= R - 1 ? (p0 + n - 1 - (R - 1)) / R : -1; // the largest b with 4b+3 <= p0+n-1
- if (hi >= first)
+ } else if (hi >= first)
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
- st->parallel_for<dpct_kernel_name<class append_blocks_a6c94e>>(
+ st->parallel_for<dpct_kernel_name<class append_blocks_a6c94e,
+ dpct_kernel_scalar<false>>>(
sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(hi - first + 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)]] {
- append_blocks(raw, n, p0, pos_base, gamma, epsilon, b.tail,
- b.dead, b.pooled, b.block_pos, first, hi,
- theta_scale, fsf, cl, ch, ef, ms, mtab);
+ append_blocks<false>(raw, n, p0, pos_base, gamma, epsilon,
+ b.tail, b.dead, b.pooled, b.block_pos,
+ first, hi, theta_scale, fsf, cl, ch, ef,
+ ms, mtab, rt);
});
}
{
diff --git a/sycl/src/kernels/cuda/native_qsa_score.dp.cpp b/sycl/src/kernels/cuda/native_qsa_score.dp.cpp
index a45806800..fe729bc0e 100644
--- a/sycl/src/kernels/cuda/native_qsa_score.dp.cpp
+++ b/sycl/src/kernels/cuda/native_qsa_score.dp.cpp
@@ -189,32 +189,32 @@ __dpct_inline__ void score_kernel(const float *__restrict__ pooled,
h[j] = sycl::fmax(v, 0.0f);
}
/*
- 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.
*/
float sum = h[0] + h[1] + h[2] + h[3];
/*
- 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 (bias) sum = sum + bias[row];
/*
- 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.
*/
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
- 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.
*/
sum = sum + 0.0f;
#pragma unroll
diff --git a/sycl/src/kernels/cuda/native_rope.dp.cpp b/sycl/src/kernels/cuda/native_rope.dp.cpp
index 6dfe25684..9f67374c5 100644
--- a/sycl/src/kernels/cuda/native_rope.dp.cpp
+++ b/sycl/src/kernels/cuda/native_rope.dp.cpp
@@ -31,6 +31,7 @@
#include <atomic>
#include <cmath>
#include <cstdint>
+#include <cstdlib>
#include <limits>
#include <stdexcept>
@@ -41,11 +42,15 @@ bool overlaps(const void* a, size_t an, const void* b, size_t bn) {
auto x = reinterpret_cast<uintptr_t>(a), y = reinterpret_cast<uintptr_t>(b);
return x <= y ? y - x < an : x - y < bn;
}
+// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table. The host launches <false> whenever
+// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it;
+// with it merely skipped at run time, the compiled default path changed its results).
+template <bool TAB>
__dpct_inline__ void apply(const float *x, float *out, int rows, int width,
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) {
+ const int32_t *mtab, RopeTab rt) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
const int row = item_ct1.get_group(1);
const int pair = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
@@ -59,10 +64,12 @@ __dpct_inline__ void apply(const float *x, float *out, int rows, int width,
}
return;
}
- 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);
+ if (!(TAB && rope_tab_cs(rt, mrope_pos(mtab, positions[row], pair), pair, c, s))) {
+ const float theta_extrap = mrope_pos(mtab, positions[row], pair) *
+ dpct::pow(theta_scale, float(pair));
+ 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,6 +93,40 @@ catch (sycl::exception const &exc) {
} // namespace
void mrope_table_set(const int32_t* device_table) { mrope_tab[mrope_dev()].store(device_table, std::memory_order_relaxed); }
const int32_t* mrope_table() { return mrope_tab[mrope_dev()].load(std::memory_order_relaxed); }
+namespace {
+// #280: the float64 angle table of each device, set at session init (before any graph is captured)
+struct RopeReg {
+ RopeTab tab;
+ RopeScaling scaling;
+};
+RopeReg rope_tab[kMropeDevices] = {};
+bool same_scaling(const RopeScaling& a, const RopeScaling& b) {
+ return a.type == b.type && a.freq_base == b.freq_base && a.factor == b.factor && a.freq_scale_in == b.freq_scale_in &&
+ a.orig_ctx == b.orig_ctx && a.ext_factor == b.ext_factor && a.attn_factor == b.attn_factor &&
+ a.beta_fast == b.beta_fast && a.beta_slow == b.beta_slow;
+}
+// opt-in: STRATA_ROPE_TABLE=1 (the table's angles differ from the fast-math ones in the last bits, so outputs move)
+bool rope_table_enabled() {
+ static const bool on = [] {
+ const char* e = std::getenv("STRATA_ROPE_TABLE");
+ return e != nullptr && e[0] == '1';
+ }();
+ return on;
+}
+} // namespace
+void rope_table_set(const float* cos_tab, const float* sin_tab, int max_pos, const RopeScaling& scaling) {
+ rope_tab[mrope_dev()] = RopeReg{RopeTab{cos_tab, sin_tab, max_pos}, scaling};
+}
+void rope_table_release(const float* cos_tab) {
+ // every device's entry that points at it (the caller may free it from another current device)
+ for (RopeReg& r : rope_tab)
+ if (cos_tab != nullptr && r.tab.cos == cos_tab) r = RopeReg{};
+}
+RopeTab rope_table_for(const RopeScaling& scaling) {
+ if (!rope_table_enabled()) return {};
+ const RopeReg& r = rope_tab[mrope_dev()];
+ return r.tab.cos != nullptr && same_scaling(r.scaling, scaling) ? r.tab : RopeTab{};
+}
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,
@@ -106,6 +147,9 @@ void native_rope_apply(const float* x, float* out, int rows, int head_dim,
// Match pinned host-side float powf before device fast powf/trigonometry.
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
+ const RopeTab rt = rope_table_for(scaling);
+ const dpct::dim3 grid((head_dim / 2 + 127) / 128, rows);
+ if (rt.cos != nullptr)
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
@@ -114,16 +158,34 @@ void native_rope_apply(const float* x, float* out, int rows, int head_dim,
->submit([&](sycl::handler &cgh) {
auto mrope_table_ct12 = mrope_table();
- cgh.parallel_for<dpct_kernel_name<class apply_b955ef>>(
- sycl::nd_range<3>(
- sycl::range(1, rows, (head_dim / 2 + 127) / 128) *
- sycl::range(1, 1, 128),
- sycl::range(1, 1, 128)),
+ cgh.parallel_for<dpct_kernel_name<class apply_b955ef,
+ dpct_kernel_scalar<true>>>(
+ sycl::nd_range<3>(grid * sycl::range(1, 1, 128),
+ sycl::range(1, 1, 128)),
+ exp_props, [=](sycl::nd_item<3> item_ct1) {
+ apply<true>(x, out, rows, head_dim, n_rot, theta_scale,
+ k.freq_scale, k.corr_low, k.corr_high,
+ k.ext_factor, k.attn_factor, positions,
+ mrope_table_ct12, rt);
+ });
+ });
+ } else {
+ 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_ct12 = mrope_table();
+
+ cgh.parallel_for<dpct_kernel_name<class apply_b955ef,
+ dpct_kernel_scalar<false>>>(
+ sycl::nd_range<3>(grid * sycl::range(1, 1, 128),
+ sycl::range(1, 1, 128)),
exp_props, [=](sycl::nd_item<3> item_ct1) {
- apply(x, out, rows, head_dim, n_rot, theta_scale,
- k.freq_scale, k.corr_low, k.corr_high,
- k.ext_factor, k.attn_factor, positions,
- mrope_table_ct12);
+ apply<false>(x, out, rows, head_dim, n_rot, theta_scale,
+ k.freq_scale, k.corr_low, k.corr_high,
+ k.ext_factor, k.attn_factor, positions,
+ mrope_table_ct12, rt);
});
});
}
diff --git a/sycl/src/kernels/cuda/qsa.dp.cpp b/sycl/src/kernels/cuda/qsa.dp.cpp
index c5df718b5..7fe2cdaf3 100644
--- a/sycl/src/kernels/cuda/qsa.dp.cpp
+++ b/sycl/src/kernels/cuda/qsa.dp.cpp
@@ -44,6 +44,7 @@
#include <sycl/sycl.hpp>
#include <dpct/dpct.hpp>
#include "strata/sycl_queue.hpp"
+#include "strata/core/emulate.hpp"
#include "strata/kernels/qsa.hpp"
#include "strata/kernels/f16_bits.hpp"
@@ -1019,6 +1020,7 @@ void qsa_attend_step(const float *q, const uint16_t *k_scratch,
the code.
*/
max_shared = dpct::get_device(dev).get_local_mem_size();
+ max_shared = strata::smem_optin_of(max_shared);
if ((int) smem > max_shared) {
std::fprintf(stderr, "qsa: qsa_attend: max_ids %lld needs %zu B of shared, over the %d B limit\n",
(long long) max_ids, smem, max_shared);
diff --git a/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp b/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp
index 65e05f045..3baef3ce5 100644
--- a/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp
+++ b/sycl/src/kernels/cuda/qsa_prompt_attn.dp.cpp
@@ -3,6 +3,9 @@
#include <sycl/sycl.hpp>
#include <dpct/dpct.hpp>
#include "strata/sycl_queue.hpp"
+#include "strata/core/emulate.hpp"
+#include <cstdlib>
+#include <cstring>
#include "strata/kernels/qsa_prompt_attn.hpp"
#include "strata/kernels/qsa_prompt_attn_xmx.hpp"
#include "strata/kernels/kv_q8.hpp"
@@ -12,6 +15,7 @@
#include <cstdio>
#include <cstdlib>
+#include <cstring>
#include <type_traits>
namespace strata::kernels {
@@ -178,9 +182,9 @@ prompt_attn_kernel(const float *__restrict__ q, QsaAttnPools p,
sycl::fmax(S.qmax[2], S.qmax[3]));
int qe = 0;
/*
- DPCT1017: The sycl::frexp call is used instead of the frexpf call. These
- two calls do not provide exactly the same functionality. Check the potential
- precision and/or performance issues for the generated code.
+ DPCT1017: The sycl::frexp call is used instead of the frexpf call.
+ These two calls do not provide exactly the same functionality. Check the
+ potential precision and/or performance issues for the generated code.
*/
if (qm > 0.0f) sycl::frexp(
qm, sycl::address_space_cast<sycl::access::address_space::generic_space,
@@ -701,9 +705,9 @@ prompt_attn_i8_kernel(const float *__restrict__ q, QsaAttnPools p,
sycl::fmax(S.qmax[2], S.qmax[3]));
int qe = 0;
/*
- DPCT1017: The sycl::frexp call is used instead of the frexpf call. These
- two calls do not provide exactly the same functionality. Check the potential
- precision and/or performance issues for the generated code.
+ DPCT1017: The sycl::frexp call is used instead of the frexpf call.
+ These two calls do not provide exactly the same functionality. Check the
+ potential precision and/or performance issues for the generated code.
*/
if (qm > 0.0f) sycl::frexp(
qm, sycl::address_space_cast<sycl::access::address_space::generic_space,
@@ -1171,6 +1175,287 @@ catch (sycl::exception const &exc) {
std::exit(1);
}
+#if defined(__HIPCC__)
+// ---- S6: the int8-KV prompt attention on RDNA4 matrix cores (opt-in: STRATA_HIP_WMMA=1, gfx12 only). The design of
+// the v2 kernel above with gfx12's v_wmma_f32_16x16x16_f16 (wave32) in place of m16n8k16: wave w owns dims
+// [64w, 64w+64) (int8 scale group w) for q.k and p.v; q and p are split into FP16 hi + lo parts, the int8 codes enter
+// exactly as FP16, the scales are applied in FP32 and the four groups' q.k partials are added in a fixed order.
+// FP32-level accuracy, deterministic, but not bitwise equal to qsa_decode_attn_batch (another summation order).
+// Fragment layout (16x16x16, wave32, checked on gfx1201): A lane l holds A[l % 16][(l / 16) * 8 + i], B lane l holds
+// B[(l / 16) * 8 + i][l % 16], C/D lane l holds D[(l / 16) * 8 + i][l % 16], i = 0..7.
+#if defined(__gfx1200__) || defined(__gfx1201__)
+#define STRATA_PA_WMMA 1
+#else
+#define STRATA_PA_WMMA 0
+#endif
+typedef _Float16 wh8 __attribute__((ext_vector_type(8)));
+typedef float wf8 __attribute__((ext_vector_type(8)));
+constexpr int WCH = 32; // cells per chunk (two 16-cell tiles)
+constexpr int WVS = 80; // staged V row stride in bytes (64 codes, 16-byte aligned, banks spread)
+struct alignas(16) SmemW {
+ float part[4][16][WCH + 1]; // q.k per dim group
+ float p[16][WCH + 1];
+ float vs[4][WCH]; // V scale per (group, cell)
+ int valid[WCH]; // the cell has a resident pool row
+ uint8_t v[4][WCH][WVS]; // per wave: the chunk's V codes of its group, one row per cell
+ float qmax[4];
+ float alpha[16];
+ float lsum[16];
+ float mrow[16];
+};
+
+__device__ __forceinline__ wf8 wmma_f16(wh8 a, wh8 b, wf8 c) {
+#if STRATA_PA_WMMA
+ return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c);
+#else
+ __builtin_trap();
+ return c;
+#endif
+}
+
+__device__ __forceinline__ wh8 i8x8_to_h8(uint2 x) { // exact: |code| <= 128
+ wh8 h;
+#pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ h[i] = (_Float16) (int) (int8_t) (x.x >> (8 * i));
+ h[4 + i] = (_Float16) (int) (int8_t) (x.y >> (8 * i));
+ }
+ return h;
+}
+
+__global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* __restrict__ q, QsaAttnPools p,
+ const int32_t* __restrict__ ids,
+ const int32_t* __restrict__ steps, int n_kv_heads,
+ int page_size, float scale_log2,
+ float* __restrict__ attn, int cap) {
+#if STRATA_PA_WMMA
+ __shared__ SmemW S;
+ const int qi = blockIdx.x, kvh = blockIdx.y;
+ const int n_head = n_kv_heads * G;
+ q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
+ attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
+ ids += (size_t) qi * cap;
+ const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);
+ const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
+ const int col = lane & 15, half = lane >> 4; // fragment column / k half
+ const int dim0 = warp * 64;
+
+ float qm = 0.0f;
+ for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i]));
+#pragma unroll
+ for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o));
+ if (lane == 0) S.qmax[warp] = qm;
+ if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; }
+ __syncthreads();
+ qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3]));
+ int qe = 0;
+ if (qm > 0.0f) frexpf(qm, &qe);
+ const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14);
+ // q A fragments of this wave's 64 dims: row = col (heads 12..15 zero), k = dim0 + kk*16 + half*8 + i
+ wh8 qh[4], ql[4];
+#pragma unroll
+ for (int kk = 0; kk < 4; ++kk) {
+ float x[8];
+ if (col < G) {
+ const float4* src = reinterpret_cast<const float4*>(q + (size_t) col * HD + dim0 + kk * 16 + half * 8);
+ const float4 a = src[0], b = src[1];
+ x[0] = a.x; x[1] = a.y; x[2] = a.z; x[3] = a.w; x[4] = b.x; x[5] = b.y; x[6] = b.z; x[7] = b.w;
+ } else {
+#pragma unroll
+ for (int i = 0; i < 8; ++i) x[i] = 0.0f;
+ }
+#pragma unroll
+ for (int i = 0; i < 8; ++i) {
+ const float v = x[i] * qup;
+ const _Float16 hi = (_Float16) v;
+ qh[kk][i] = hi;
+ ql[kk][i] = (_Float16) (v - (float) hi);
+ }
+ }
+
+ wf8 acc[4];
+#pragma unroll
+ for (int j = 0; j < 4; ++j) acc[j] = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
+
+ const int n_chunks = (n + WCH - 1) / WCH;
+ for (int ci = 0; ci < n_chunks; ++ci) {
+ const int c0 = ci * WCH;
+ // this lane's cell of the chunk (lane = cell index): its pool row, or -1 (past the selection, or a block the
+ // KV streaming left non-resident: masked as in the decode kernel)
+ long long myrow = -1;
+ if (c0 + lane < n) {
+ const int cell = __ldg(ids + c0 + lane);
+ const long long page = (long long) __ldg(p.page_table + cell / page_size);
+ if (page >= 0) myrow = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
+ }
+ // stage this wave's V slice of the chunk (64 bytes of each row) and the V scale; the K fragments come straight
+ // from global memory (8 consecutive codes per lane)
+ {
+ uint4 v0 = make_uint4(0, 0, 0, 0), v1 = v0, v2 = v0, v3 = v0;
+ float vsc = 0.0f;
+ if (myrow >= 0) {
+ const uint4* src = reinterpret_cast<const uint4*>(p.v_q + myrow * HD + dim0);
+ v0 = __ldg(src); v1 = __ldg(src + 1); v2 = __ldg(src + 2); v3 = __ldg(src + 3);
+ vsc = __half2float(__ushort_as_half(__ldg(p.v_scale + myrow * (HD / KV_Q8_GROUP) + warp)));
+ }
+ uint4* dst = reinterpret_cast<uint4*>(&S.v[warp][lane][0]);
+ dst[0] = v0; dst[1] = v1; dst[2] = v2; dst[3] = v3;
+ S.vs[warp][lane] = vsc;
+ if (warp == 0) S.valid[lane] = myrow >= 0;
+ }
+ // q.k over this wave's 64 dims for two 16-cell tiles, times the cell's K scale for this group
+#pragma unroll
+ for (int nt = 0; nt < 2; ++nt) {
+ const long long rr = __shfl(myrow, nt * 16 + col);
+ wf8 s = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
+ float ksc = 0.0f;
+ if (rr >= 0) ksc = __half2float(__ushort_as_half(__ldg(p.k_scale + rr * (HD / KV_Q8_GROUP) + warp)));
+#pragma unroll
+ for (int kk = 0; kk < 4; ++kk) {
+ uint2 kx = make_uint2(0, 0);
+ if (rr >= 0) kx = __ldg(reinterpret_cast<const uint2*>(p.k_q + rr * HD + dim0 + kk * 16 + half * 8));
+ const wh8 b = i8x8_to_h8(kx);
+ s = wmma_f16(qh[kk], b, s);
+ s = wmma_f16(ql[kk], b, s);
+ }
+#pragma unroll
+ for (int i = 0; i < 8; ++i) S.part[warp][half * 8 + i][nt * 16 + col] = s[i] * ksc;
+ }
+ __syncthreads();
+ // online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread
+ {
+ const int r = t >> 3, sub = t & 7;
+ float x[4], mx = -INFINITY;
+#pragma unroll
+ for (int j = 0; j < 4; ++j) {
+ const int c = sub * 4 + j;
+ // past the selection, or a masked cell (non-resident page, as in the decode kernel): no weight
+ x[j] = S.valid[c] ? (((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c]) * qdown
+ : -INFINITY;
+ mx = fmaxf(mx, x[j]);
+ }
+#pragma unroll
+ for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o));
+ const float m_old = S.mrow[r];
+ const float m_new = fmaxf(m_old, mx);
+ float sum = 0.0f;
+#pragma unroll
+ for (int j = 0; j < 4; ++j) {
+ const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new);
+ S.p[r][sub * 4 + j] = e;
+ sum += e;
+ }
+#pragma unroll
+ for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
+ if (sub == 0) {
+ const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new);
+ S.alpha[r] = a;
+ S.lsum[r] = fmaf(S.lsum[r], a, sum);
+ S.mrow[r] = m_new;
+ }
+ }
+ __syncthreads();
+ // p.v over this wave's 64 dims: 4 tiles of 16 dims, 2 k-steps of 16 cells
+ {
+ float vmax = S.vs[warp][lane];
+#pragma unroll
+ for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o));
+ const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f);
+ wf8 tmp[4];
+#pragma unroll
+ for (int j = 0; j < 4; ++j) tmp[j] = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
+#pragma unroll
+ for (int ks = 0; ks < 2; ++ks) {
+ const int cb = ks * 16 + half * 8; // this lane's 8 cells
+ wh8 ah, al;
+#pragma unroll
+ for (int i = 0; i < 8; ++i) {
+ const float pv = S.p[col][cb + i] * (S.vs[warp][cb + i] * vup);
+ const _Float16 hi = (_Float16) pv;
+ ah[i] = hi;
+ al[i] = (_Float16) (pv - (float) hi);
+ }
+#pragma unroll
+ for (int j = 0; j < 4; ++j) {
+ const int d = j * 16 + col;
+ wh8 b;
+#pragma unroll
+ for (int i = 0; i < 8; ++i) b[i] = (_Float16) (int) (int8_t) S.v[warp][cb + i][d];
+ tmp[j] = wmma_f16(ah, b, tmp[j]);
+ tmp[j] = wmma_f16(al, b, tmp[j]);
+ }
+ }
+ float a[8];
+#pragma unroll
+ for (int i = 0; i < 8; ++i) a[i] = S.alpha[half * 8 + i];
+#pragma unroll
+ for (int j = 0; j < 4; ++j)
+#pragma unroll
+ for (int i = 0; i < 8; ++i) acc[j][i] = fmaf(acc[j][i], a[i], tmp[j][i] * vdown);
+ }
+ // no barrier here: `v`/`vs` are this wave's own, and `p`/`alpha`/`valid` are rewritten only after the next
+ // chunk's first barrier (which every wave reaches after its p.v)
+ }
+ float inv[8];
+#pragma unroll
+ for (int i = 0; i < 8; ++i) {
+ const float l = S.lsum[half * 8 + i];
+ inv[i] = l > 0.0f ? 1.0f / l : 0.0f;
+ }
+#pragma unroll
+ for (int j = 0; j < 4; ++j)
+#pragma unroll
+ for (int i = 0; i < 8; ++i) {
+ const int row = half * 8 + i;
+ if (row < G) attn[(size_t) row * HD + dim0 + j * 16 + col] = acc[j][i] * inv[i];
+ }
+#else
+ __builtin_trap();
+#endif
+}
+
+// gfx12 (RDNA4) only, and only on request: the output differs from the default kernel's in its last bits
+bool hip_wmma_usable() {
+ static const bool want = [] {
+ const char* e = std::getenv("STRATA_HIP_WMMA");
+ return e != nullptr && e[0] == '1';
+ }();
+ if (!want) return false;
+ static int arch[64] = {}; // 0 unknown, 1 gfx12, 2 other
+ int dev = 0;
+ if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= 64) { (void) hipGetLastError(); return false; }
+ if (arch[dev] == 0) {
+ hipDeviceProp_t prop{};
+ if (hipGetDeviceProperties(&prop, dev) != hipSuccess) { (void) hipGetLastError(); return false; }
+ arch[dev] = std::strncmp(prop.gcnArchName, "gfx12", 5) == 0 ? 1 : 2;
+ static bool told = false;
+ if (!told) {
+ told = true;
+ std::fprintf(stderr, "strata: STRATA_HIP_WMMA: the prompt attention on matrix cores %s (%s)\n",
+ arch[dev] == 1 ? "on" : "unavailable", prop.gcnArchName);
+ }
+ }
+ return arch[dev] == 1;
+}
+
+bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
+ const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) {
+ const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
+ for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
+ const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
+ prompt_attn_wmma_kernel<<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, 0, st>>>(
+ q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,
+ (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
+ }
+ const cudaError_t e = cudaGetLastError();
+ if (e != cudaSuccess) {
+ std::fprintf(stderr, "qsa_prompt_attn_batch (wmma): %s\n", cudaGetErrorString(e));
+ std::exit(1);
+ }
+ return true;
+}
+#endif
+
} // namespace
bool qsa_prompt_attn_batch(const float *q, const QsaAttnPools &pools,
@@ -1202,7 +1487,9 @@ bool qsa_prompt_attn_batch(const float *q, const QsaAttnPools &pools,
*/
return false;
}
- cc_major[dev] = major;
+ // STRATA_QSA_WARP=1|attn (an A/B arm): the pre-sm_80 kernels on any card, as RTX 20 runs them
+ const char* w = std::getenv("STRATA_QSA_WARP");
+ cc_major[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "attn")) ? 7 : strata::cc_major_of(major);
}
(void) cc_major[dev];
// SYCL: the mma.sync kernel below is not ported (upstream's Turing/sm_80 split - `turing` - does not
@@ -1211,7 +1498,14 @@ bool qsa_prompt_attn_batch(const float *q, const QsaAttnPools &pools,
return false; // the caller takes the older kernel
}
#if defined(__HIPCC__)
- return false; // the tensor-core kernel is compiled out on AMD (its major version is not a CUDA sm)
+ // the tensor-core kernels are compiled out on AMD (its major version is not a CUDA sm); RDNA4 has its own int8-KV
+ // matrix-core kernel, opt-in (STRATA_HIP_WMMA=1); everything else keeps the old kernel
+ (void) turing;
+ if (pools.k_q != nullptr && pools.v_q != nullptr && pools.k_scale != nullptr && pools.v_scale != nullptr &&
+ pools.k_q4 == nullptr && pools.v_q4 == nullptr && s.head_dim == HD && s.n_head == (int64_t) G * s.n_head_kv &&
+ cap > 0 && ids && steps && pools.page_table && hip_wmma_usable())
+ return launch_wmma(q, pools, ids, steps, cap, s, attn, n_q, (cudaStream_t) stream);
+ return false;
#endif
if (pools.k_q4 != nullptr || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !ids ||
!steps || !pools.page_table)
diff --git a/sycl/src/kernels/cuda/qsa_select.dp.cpp b/sycl/src/kernels/cuda/qsa_select.dp.cpp
index 9a195a20d..d562f00c5 100644
--- a/sycl/src/kernels/cuda/qsa_select.dp.cpp
+++ b/sycl/src/kernels/cuda/qsa_select.dp.cpp
@@ -3,11 +3,15 @@
#include <sycl/sycl.hpp>
#include <dpct/dpct.hpp>
#include "strata/sycl_queue.hpp"
+#include "strata/core/emulate.hpp"
+#include <cstdlib>
+#include <cstring>
#include "strata/kernels/qsa_select.hpp"
#include <cfloat>
#include <cstdio>
#include <cstdlib>
+#include <cstring>
namespace strata::kernels {
namespace {
@@ -417,6 +421,160 @@ __dpct_inline__ void block_scores_tc_kernel(
}
}
+#if defined(__HIPCC__)
+// ---- gfx12 (RDNA4: gfx1200 / gfx1201) scorer on v_wmma_f32_16x16x16_bf16 (wave32). Same GEMM as above: for a tile of 16
+// queries, every block's score is sum over the 4 indexer heads of relu(q_h . k), K = 128. FP32-level accuracy from a
+// three-way bf16 split of both operands (x = hi + mid + lo EXACTLY - the top 8, next 8 and last 8 bits of the fp32
+// mantissa, so bf16's fp32-sized exponent range needs no scaling) and the six products of order <= 2, smallest first;
+// like the TF32 kernel it sums in another order than the warp kernel (not bitwise). The tail block n_bid is the warp
+// kernel's arithmetic (block_scores_tail_kernel).
+// D = A x B with A = 16 key blocks (row l%16 of a lane, k = 8*(l/16)+i), B = 16 queries (column l%16, same k):
+// a lane ends up with 8 consecutive blocks of ONE query, written as one run. No LDS for keys: a lane reads its
+// 32-byte slice of the key row from global (the 16 query tiles of a launch re-read them from L2); the queries are
+// split once per CTA into LDS.
+#if defined(__gfx1200__) || defined(__gfx1201__)
+#define STRATA_SEL_GFX12 1
+#else
+#define STRATA_SEL_GFX12 0
+#endif
+typedef short sel_s8 __attribute__((ext_vector_type(8)));
+typedef float sel_f8 __attribute__((ext_vector_type(8)));
+typedef uint32_t sel_u4 __attribute__((ext_vector_type(4)));
+constexpr int WQT = 16; // queries per CTA (the N of one WMMA)
+constexpr int WITER = 4; // key tiles per warp (the CTA covers 4 warps * WITER * 16 blocks)
+constexpr int WQS = IDX_DIM + 8; // bf16 elements per LDS row: 272 bytes, conflict-free 16-byte reads
+
+__device__ __forceinline__ sel_f8 wmma_bf16(const sel_s8& a, const sel_s8& b, const sel_f8& c) {
+#if STRATA_SEL_GFX12
+ return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c);
+#else
+ /* unreachable on SYCL: the launcher refuses this device */
+ return c;
+#endif
+}
+// the bf16 pieces of x as fp32 bit patterns whose upper 16 bits are the bf16 (lower 16 are zero)
+__device__ __forceinline__ void split3(float x, uint32_t& hi, uint32_t& mid, uint32_t& lo) {
+ hi = sycl::bit_cast<uint32_t>(x) & 0xffff0000u;
+ const float r1 = x - __uint_as_float(hi); // exact
+ mid = sycl::bit_cast<uint32_t>(r1) & 0xffff0000u;
+ lo = sycl::bit_cast<uint32_t>(r1 - __uint_as_float(mid)) & 0xffff0000u; // exact: at most 8 significant bits left
+}
+__device__ __forceinline__ uint32_t pack_bf16x2(uint32_t a, uint32_t b) { // low half = a's bf16, high half = b's
+#if STRATA_SEL_GFX12
+ return __builtin_amdgcn_perm(b, a, 0x07060302u);
+#else
+ return (a >> 16) | (b & 0xffff0000u);
+#endif
+}
+
+__global__ void __launch_bounds__(128) block_scores_wmma_kernel(const float* __restrict__ pooled,
+ const float* __restrict__ q_idx,
+ const int32_t* __restrict__ steps, int64_t nq,
+ int64_t max_blocks, int64_t reach,
+ float* __restrict__ out) {
+ __shared__ __align__(16) uint16_t sq[3][IDX_HEADS][WQT][WQS]; // hi / mid / lo, [head][query][dim]
+ __shared__ int s_nbid[WQT];
+ const int t = threadIdx.x, lane = t & 31, warp = t >> 5, l16 = lane & 15, g = lane >> 4;
+ const int64_t q0 = (int64_t) blockIdx.y * WQT;
+ for (int i = t; i < WQT * IDX_HEADS * IDX_DIM / 4; i += 128) {
+ const int row = i / (IDX_DIM / 4), c = i % (IDX_DIM / 4);
+ const int qr = row / IDX_HEADS, h = row % IDX_HEADS;
+ float4 v = make_float4(0.f, 0.f, 0.f, 0.f);
+ if (q0 + qr < nq) v = reinterpret_cast<const float4*>(q_idx + (q0 + qr) * IDX_HEADS * IDX_DIM)[h * (IDX_DIM / 4) + c];
+ const float x[4] = {v.x, v.y, v.z, v.w};
+ uint32_t hb[4], mb[4], lb[4];
+#pragma unroll
+ for (int j = 0; j < 4; ++j) split3(x[j], hb[j], mb[j], lb[j]);
+ *reinterpret_cast<uint2*>(&sq[0][h][qr][c * 4]) = make_uint2(pack_bf16x2(hb[0], hb[1]), pack_bf16x2(hb[2], hb[3]));
+ *reinterpret_cast<uint2*>(&sq[1][h][qr][c * 4]) = make_uint2(pack_bf16x2(mb[0], mb[1]), pack_bf16x2(mb[2], mb[3]));
+ *reinterpret_cast<uint2*>(&sq[2][h][qr][c * 4]) = make_uint2(pack_bf16x2(lb[0], lb[1]), pack_bf16x2(lb[2], lb[3]));
+ }
+ if (t < WQT) s_nbid[t] = q0 + t < nq ? steps[(q0 + t) * kStepCount + kStepNBid] : 0;
+ __syncthreads();
+ int hi_nbid = 0;
+#pragma unroll
+ for (int i = 0; i < WQT; ++i) hi_nbid = max(hi_nbid, s_nbid[i]);
+ const int64_t qi = q0 + l16;
+ const int nb_q = s_nbid[l16];
+ for (int it = 0; it < WITER; ++it) {
+ const int64_t b0 = (((int64_t) blockIdx.x * WITER + it) * 4 + warp) * 16;
+ if (b0 >= reach || b0 >= hi_nbid) break; // warp-uniform; later tiles start higher
+ const int64_t row = b0 + l16;
+ const bool rv = row < hi_nbid && row < max_blocks;
+ const float* kp = pooled + (rv ? row : 0) * IDX_DIM + g * 8;
+ // acc: the hi*hi products; cor: the five smaller ones (<= 2^-8 of it). Kept apart and added once at the end: a
+ // correction summed into the big accumulator is rounded to ITS ulp at every one of the 48 steps (measured: 8e-7
+ // of the score scale; apart, near the warp kernel's)
+ sel_f8 acc[IDX_HEADS], cor[IDX_HEADS];
+#pragma unroll
+ for (int h = 0; h < IDX_HEADS; ++h) acc[h] = cor[h] = sel_f8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
+#pragma unroll 2
+ for (int kk = 0; kk < IDX_DIM / 16; ++kk) {
+ float4 k0 = make_float4(0.f, 0.f, 0.f, 0.f), k1 = k0;
+ if (rv) {
+ k0 = *reinterpret_cast<const float4*>(kp + kk * 16);
+ k1 = *reinterpret_cast<const float4*>(kp + kk * 16 + 4);
+ }
+ const float x[8] = {k0.x, k0.y, k0.z, k0.w, k1.x, k1.y, k1.z, k1.w};
+ uint32_t hb[8], mb[8], lb[8];
+#pragma unroll
+ for (int j = 0; j < 8; ++j) split3(x[j], hb[j], mb[j], lb[j]);
+ sel_u4 ah, am, al;
+#pragma unroll
+ for (int j = 0; j < 4; ++j) {
+ ah[j] = pack_bf16x2(hb[2 * j], hb[2 * j + 1]);
+ am[j] = pack_bf16x2(mb[2 * j], mb[2 * j + 1]);
+ al[j] = pack_bf16x2(lb[2 * j], lb[2 * j + 1]);
+ }
+ const sel_s8 Ah = __builtin_bit_cast(sel_s8, ah), Am = __builtin_bit_cast(sel_s8, am),
+ Al = __builtin_bit_cast(sel_s8, al);
+#pragma unroll
+ for (int h = 0; h < IDX_HEADS; ++h) {
+ const sel_s8 Bh = *reinterpret_cast<const sel_s8*>(&sq[0][h][l16][kk * 16 + g * 8]);
+ const sel_s8 Bm = *reinterpret_cast<const sel_s8*>(&sq[1][h][l16][kk * 16 + g * 8]);
+ const sel_s8 Bl = *reinterpret_cast<const sel_s8*>(&sq[2][h][l16][kk * 16 + g * 8]);
+ cor[h] = wmma_bf16(Al, Bh, cor[h]);
+ cor[h] = wmma_bf16(Ah, Bl, cor[h]);
+ cor[h] = wmma_bf16(Am, Bm, cor[h]);
+ cor[h] = wmma_bf16(Ah, Bm, cor[h]);
+ cor[h] = wmma_bf16(Am, Bh, cor[h]);
+ acc[h] = wmma_bf16(Ah, Bh, acc[h]);
+ }
+ }
+ // relu per head, heads added in order (as the warp kernel); this lane: query qi, blocks b0 + 8g .. 8g+7
+ if (qi < nq) {
+#pragma unroll
+ for (int i = 0; i < 8; ++i) {
+ const int64_t b = b0 + g * 8 + i;
+ if (b >= nb_q || b >= max_blocks) continue;
+ float score = 0.0f;
+#pragma unroll
+ for (int h = 0; h < IDX_HEADS; ++h) {
+ const float d = acc[h][i] + cor[h][i];
+ score += d > 0.0f ? d : 0.0f;
+ }
+ out[qi * max_blocks + b] = score;
+ }
+ }
+ }
+}
+
+// the gfx12 kernel needs gfx1200/gfx1201 code objects and a gfx12 device (gfx1100 has WMMA too, with another layout)
+bool sel_gfx12_device() {
+ static int ok[64] = {}; // per device: 0 unknown, 1 yes, 2 no
+ int dev = 0;
+ if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
+ if (ok[dev] == 0) {
+ cudaDeviceProp prop;
+ ok[dev] = (cudaGetDeviceProperties(&prop, dev) == cudaSuccess &&
+ (std::strncmp(prop.gcnArchName, "gfx1200", 7) == 0 || std::strncmp(prop.gcnArchName, "gfx1201", 7) == 0))
+ ? 1 : 2;
+ cudaGetLastError();
+ }
+ return ok[dev] == 1;
+}
+#endif // __HIPCC__
+
// the tail block n_bid of each query: exactly block_scores_kernel's arithmetic for that block
__dpct_inline__ void block_scores_tail_kernel(const float *__restrict__ dead,
const float *__restrict__ q_idx,
@@ -462,6 +620,14 @@ __dpct_inline__ void block_scores_tail_kernel(const float *__restrict__ dead,
// block_topk_kernel's (radix threshold, ties to the lowest index, cells ascending): identical ids.
constexpr int TK_T = 1024;
constexpr int TK_PER = 33;
+#if defined(__HIPCC__)
+// AMD (RDNA, wave32): a 1,024-thread block may use 192 VGPRs per lane, so the keys of 66 blocks per thread fit - contexts
+// up to 4 * 1024 * 66 = 270,336 cells (the 262,144 --max-context) keep the register kernel. NVIDIA's 64 registers per
+// thread at 1,024 threads allow only TK_PER.
+constexpr int TK_PER_MAX = 66;
+#else
+constexpr int TK_PER_MAX = TK_PER;
+#endif
__dpct_inline__ int block_excl_scan(int v, int *s_warp, int &total) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
@@ -471,9 +637,9 @@ __dpct_inline__ int block_excl_scan(int v, int *s_warp, int &total) {
#pragma unroll
for (int o = 1; o < 32; o <<= 1) {
/*
- DPCT1108: '__shfl_up_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_up_sync' was migrated with the experimental feature
+ masked sub_group function which may not be supported by all compilers or
+ runtimes. You may need to adjust the code.
*/
const int y = dpct::experimental::shift_sub_group_right(
0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), x,
@@ -522,6 +688,7 @@ __dpct_inline__ int block_excl_scan(int v, int *s_warp, int &total) {
return r;
}
+template <int PER>
/*
DPCT1110: The total declared local variable size in device function
block_topk_reg_kernel exceeds 128 bytes and may cause high register pressure.
@@ -555,11 +722,11 @@ auto &hist =
}
const float* sc = scores + qi * max_blocks;
const int64_t nb = n_bid + 1;
- const int64_t per = (nb + TK_T - 1) / TK_T; // <= TK_PER (the caller checks)
+ const int64_t per = (nb + TK_T - 1) / TK_T; // <= PER (the caller checks)
const int64_t b0 = (int64_t) t * per, b1 = (b0 + per < nb) ? b0 + per : nb;
- uint32_t key[TK_PER];
+ uint32_t key[PER];
#pragma unroll
- for (int j = 0; j < TK_PER; ++j) key[j] = (b0 + j < b1) ? order_key(sc[b0 + j]) : 0u;
+ for (int j = 0; j < PER; ++j) key[j] = (b0 + j < b1) ? order_key(sc[b0 + j]) : 0u;
auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); };
uint32_t prefix = 0;
int above = 0;
@@ -569,7 +736,7 @@ auto &hist =
sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8));
#pragma unroll
- for (int j = 0; j < TK_PER; ++j) {
+ for (int j = 0; j < PER; ++j) {
const int64_t b = b0 + j;
if (b >= b1) break;
const int w = weight(b);
@@ -642,7 +809,7 @@ auto &hist =
const int64_t eq_budget = width - above;
int gt = 0, eq = 0;
#pragma unroll
- for (int j = 0; j < TK_PER; ++j) {
+ for (int j = 0; j < PER; ++j) {
const int64_t b = b0 + j;
if (b >= b1) break;
const int w = weight(b);
@@ -659,7 +826,7 @@ auto &hist =
int64_t wpos = block_excl_scan(sel, s_warp, tot);
int64_t eq_left = my_eq;
#pragma unroll
- for (int j = 0; j < TK_PER; ++j) {
+ for (int j = 0; j < PER; ++j) {
const int64_t b = b0 + j;
if (b >= b1) break;
const int w = weight(b);
@@ -839,6 +1006,25 @@ bool qsa_block_scores_tc(const float *pooled, const float *dead,
void *stream, int64_t active_blocks) try {
if (nq <= 0) return true;
if (s.idx_dim != IDX_DIM || s.idx_n_head != IDX_HEADS || s.idx_block != R || nq > 65535 * TC_QT) return false;
+#if defined(__HIPCC__)
+ // AMD: the gfx12 (RDNA4) WMMA scorer, opt-in (STRATA_SELECT_WMMA=1): it selects slightly differently from the warp
+ // kernel (254/256 queries the same), so the default keeps the warp kernel; every other target keeps it too (false)
+ static const bool wmma_on = [] {
+ const char* v = std::getenv("STRATA_SELECT_WMMA");
+ return v != nullptr && v[0] != '\0' && v[0] != '0';
+ }();
+ if (!wmma_on || !sel_gfx12_device()) return false;
+ {
+ const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;
+ const int64_t per = (int64_t) 4 * WITER * 16;
+ const dim3 grid((unsigned) ((reach + per - 1) / per), (unsigned) ((nq + WQT - 1) / WQT));
+ block_scores_wmma_kernel<<<grid, 128, 0, (cudaStream_t) stream>>>(pooled, q_idx, steps, nq, max_blocks, reach, scores);
+ block_scores_tail_kernel<<<(unsigned) nq, 32, 0, (cudaStream_t) stream>>>(dead, q_idx, steps, max_blocks, scores);
+ const cudaError_t e = cudaGetLastError();
+ if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores_tc: %s\n", cudaGetErrorString(e)); std::exit(1); }
+ return true;
+ }
+#else
{ // sm_80 or newer (TF32 MMA); an older card keeps the warp kernel
static int cc_major[64] = {};
int dev = 0;
@@ -860,14 +1046,13 @@ bool qsa_block_scores_tc(const float *pooled, const float *dead,
*/
return false;
}
- cc_major[dev] = major;
+ // STRATA_QSA_WARP=1|select (an A/B arm): the pre-sm_80 kernels on any card, as RTX 20 runs them
+ const char* w = std::getenv("STRATA_QSA_WARP");
+ cc_major[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "select")) ? 7 : strata::cc_major_of(major);
}
(void) cc_major[dev];
return false; // SYCL: the tensor-core kernel is not ported yet; the caller takes the older kernel
}
-#if defined(__HIPCC__)
- return false; // the tensor-core kernel is compiled out on AMD (its major version is not a CUDA sm)
-#endif
static bool attr[64] = {}; // the shared-memory opt-in is per device (a layer split runs it on several)
int adev = 0;
adev = dpct::get_current_device_id();
@@ -947,6 +1132,7 @@ bool qsa_block_scores_tc(const float *pooled, const float *dead,
*/
return true;
+#endif
}
catch (sycl::exception const &exc) {
std::cerr << exc.what() << "Exception caught at file:" << __FILE__
@@ -988,12 +1174,30 @@ void qsa_block_topk_ref(const float* scores, const int32_t* steps, int64_t nq, i
}
void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap,
- const QsaShapes& s, int32_t* ids, void* stream) {
+ const QsaShapes& s, int32_t* ids, void* stream, int64_t active_blocks) {
// keys in registers when every query's blocks fit (contexts up to ~135K cells); the same ids. STRATA_TOPK_OLD=1:
// the kernel that reads them from memory on every pass
static const bool old = std::getenv("STRATA_TOPK_OLD") != nullptr;
if (nq <= 0) return;
- if (old || max_blocks > (int64_t) TK_T * TK_PER) {
+ // the blocks a query can have: the call's active count when the caller knows it (the prompt path), else the capacity.
+ // Decode (no count) keeps the capacity rule and the original register width: nothing changes there.
+#if defined(__HIPCC__)
+ const bool counted = active_blocks > 0;
+#else
+ // CUDA keeps 0.1.32's capacity rule: #337's dispatch was measured on RDNA4 only, and on the RTX 5070 the 64K
+ // prompts read 1-3% slower with it
+ const bool counted = false;
+ (void) active_blocks;
+#endif
+ const int64_t reach = counted && active_blocks < max_blocks ? active_blocks : max_blocks;
+ const int64_t fit = (int64_t) TK_T * (counted ? TK_PER_MAX : TK_PER);
+#if defined(__HIPCC__)
+ constexpr int64_t kRegMinBlocks = 7168; // gfx1201: below ~28K cells the 1,024-thread kernel's fixed cost loses to the ref
+ const bool too_small = counted && reach < kRegMinBlocks;
+#else
+ const bool too_small = false;
+#endif
+ if (old || too_small || reach > fit) {
qsa_block_topk_ref(scores, steps, nq, max_blocks, cap, s, ids, stream);
return;
}
@@ -1001,26 +1205,49 @@ void qsa_block_topk(const float* scores, const int32_t* steps, int64_t nq, int64
std::fprintf(stderr, "qsa_block_topk: unsupported geometry or cap\n");
std::exit(1);
}
+ if (reach <= (int64_t) TK_T * TK_PER)
+ /*
+ 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};
+
+ strata::q_of(stream)
+ ->parallel_for<dpct_kernel_name<class block_topk_reg_kernel_652097,
+ dpct_kernel_scalar<TK_PER>>>(
+ sycl::nd_range<3>(sycl::range(1, 1, (unsigned)nq) *
+ sycl::range(1, 1, TK_T),
+ sycl::range(1, 1, TK_T)),
+ exp_props,
+ [=](sycl::nd_item<3> item_ct1)
+ [[sycl::reqd_sub_group_size(32)]] {
+ block_topk_reg_kernel<TK_PER>(scores, steps, max_blocks,
+ cap, ids);
+ });
+ } else
/*
- DPCT1049: The work-group size passed to the SYCL kernel may exceed the
- limit. To get the device limit, query info::device::max_work_group_size.
- Adjust the work-group size if needed.
+ 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};
strata::q_of(stream)
- ->parallel_for<
- dpct_kernel_name<class block_topk_reg_kernel_652097>>(
+ ->parallel_for<dpct_kernel_name<class block_topk_reg_kernel_652098,
+ dpct_kernel_scalar<TK_PER_MAX>>>(
sycl::nd_range<3>(sycl::range(1, 1, (unsigned)nq) *
sycl::range(1, 1, TK_T),
sycl::range(1, 1, TK_T)),
exp_props,
[=](sycl::nd_item<3> item_ct1)
[[sycl::reqd_sub_group_size(32)]] {
- block_topk_reg_kernel(scores, steps, max_blocks, cap,
- ids);
+ block_topk_reg_kernel<TK_PER_MAX>(scores, steps,
+ max_blocks, cap, ids);
});
}
/*
diff --git a/sycl/src/kernels/cuda/quantize_act.dp.cpp b/sycl/src/kernels/cuda/quantize_act.dp.cpp
index ec13c7dd4..ac4d0fdb1 100644
--- a/sycl/src/kernels/cuda/quantize_act.dp.cpp
+++ b/sycl/src/kernels/cuda/quantize_act.dp.cpp
@@ -221,10 +221,10 @@ __dpct_inline__ void quantize_q8_K_kernel(const float *__restrict__ x,
// from the reference in 1 element of 524,288 for exactly this reason, and `__fmul_rn` pins the
// rounding step the source actually performs.
/*
- 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 int v = nearest_int_dev(iscale * xb[j]);
qs[j] = (int8_t)sycl::min(
diff --git a/sycl/src/kernels/cuda/router_top10.dp.cpp b/sycl/src/kernels/cuda/router_top10.dp.cpp
index b91748e72..1a602e5de 100644
--- a/sycl/src/kernels/cuda/router_top10.dp.cpp
+++ b/sycl/src/kernels/cuda/router_top10.dp.cpp
@@ -313,10 +313,185 @@ runtimes. You may need to adjust the code.
}
}
+#if defined(__HIPCC__)
+// ---- S6, AMD: the same router, BIT-IDENTICAL, without its serial parts. Measured on RDNA4 (gfx1201) the kernel
+// above took 39 us per call in decode (16% of the GPU's decode time): the ascending double sum is 512 dependent FP64
+// adds (~50 cycles each there), the ten selection passes are 20 block barriers, and the renormalisation re-reads its
+// ten weights from global memory one by one. Here:
+// * the sum's ONLY use is inv = (float) (1.0 / sum). Every term is positive and the largest is exactly 1
+// (exp(0)), so the serial sum and any other summation order both lie within 2^-43 (relative) of the exact sum
+// (|serial - exact| <= 511u, |tree - exact| <= 21u, u = 2^-53). 1.0 / x and the float cast are monotone: when
+// the bracket [tree (1 - 2^-40), tree (1 + 2^-40)] maps to ONE float, that float is the serial sum's. Otherwise
+// (about 1 row in 1000 in the parity test, or a non-finite sum) thread 0 runs the serial sum as before;
+// * the selection runs on wave 0 alone with the probabilities in registers (16 per lane): the largest p with the
+// lowest index on ties is unique, so the butterfly finds the same expert as the block reduction did;
+// * the renormalisation sums the ten weights in rank order from registers and divides them in parallel.
+// Same expressions, same operands: the ids and weights are bitwise those of router_top10_kernel (hip_router_fast
+// checks it on 65,536 rows with ties, near-ties, NaN rows and the forced serial path). STRATA_HIP_ROUTER_OLD=1: the
+// kernel above.
+template <bool FORCE_SERIAL>
+__global__ void router_top10_fast_kernel(const float* __restrict__ logits, int n_tokens, int n_expert, int k,
+ int* __restrict__ ids, float* __restrict__ weights) {
+ extern __shared__ unsigned char s_raw[];
+ const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u;
+ double* s_ex = (double*) (s_raw + taken_bytes);
+ __shared__ float s_red[RT_MAX_THREADS / 32];
+ __shared__ double s_dred[RT_MAX_THREADS / 32];
+ __shared__ float s_inv;
+ const int t = blockIdx.x;
+ if (t >= n_tokens) return;
+ const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
+ const int nt = blockDim.x, nw = (nt + 31) >> 5;
+ const float* l = logits + (size_t) t * n_expert;
+ // the max: as router_top10_kernel (exact, order-independent)
+ float mx = -INFINITY;
+ for (int e = tid; e < n_expert; e += nt) mx = fmaxf(mx, l[e]);
+ for (int off = 16; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_down_sync(0xffffffffu, mx, off));
+ if (lane == 0) s_red[warp] = mx;
+ __syncthreads();
+ if (tid < 32) {
+ float v = (tid < nw) ? s_red[tid] : -INFINITY;
+ for (int off = 16; off > 0; off >>= 1) v = fmaxf(v, __shfl_down_sync(0xffffffffu, v, off));
+ if (tid == 0) s_red[0] = v;
+ }
+ __syncthreads();
+ mx = s_red[0];
+ // the exponentials (the same expression), and a tree sum of them for the bracket
+ double part = 0.0;
+ for (int e = tid; e < n_expert; e += nt) {
+ const double x = exp((double) l[e] - (double) mx);
+ s_ex[e] = x;
+ part += x;
+ }
+ for (int off = 16; off > 0; off >>= 1) part += __shfl_xor_sync(0xffffffffu, part, off);
+ if (lane == 0) s_dred[warp] = part;
+ __syncthreads();
+ double tot = 0.0;
+ for (int w = 0; w < nw; ++w) tot += s_dred[w];
+ const double lo = tot * (1.0 - 0x1p-40), hi = tot * (1.0 + 0x1p-40);
+ const float f_lo = (float) (1.0 / hi), f_hi = (float) (1.0 / lo);
+ float inv;
+ if (!FORCE_SERIAL && tot >= 1.0 && hi < 1e300 && f_lo == f_hi) {
+ inv = f_lo;
+ } else { // block-uniform (every thread computed the same tot): the serial sum, exactly as router_top10_kernel
+ if (tid == 0) {
+ double sum = 0.0;
+ for (int e = 0; e < n_expert; ++e) sum += s_ex[e];
+ s_inv = (float) (1.0 / sum);
+ }
+ __syncthreads();
+ inv = s_inv;
+ }
+ if (warp != 0) return;
+ // wave 0: lane holds experts lane + 32 j; p is router_top10_kernel's expression
+ constexpr int PER = 16;
+ float pv[PER];
+ unsigned live = 0;
+#pragma unroll
+ for (int j = 0; j < PER; ++j) {
+ const int e = lane + 32 * j;
+ pv[j] = -INFINITY;
+ if (e < n_expert) { pv[j] = (float) (s_ex[e] * inv); live |= 1u << j; }
+ }
+ float my_w = 0.0f;
+ int my_id = 0, nsel = 0;
+ for (int i = 0; i < k; ++i) {
+ float bv = -INFINITY;
+ int bi = n_expert; // a sentinel that loses to every real index
+#pragma unroll
+ for (int j = 0; j < PER; ++j)
+ if (((live >> j) & 1u) && pv[j] > bv) { bv = pv[j]; bi = lane + 32 * j; }
+ for (int off = 16; off > 0; off >>= 1) {
+ const float ov = __shfl_xor_sync(0xffffffffu, bv, off);
+ const int oi = __shfl_xor_sync(0xffffffffu, bi, off);
+ if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
+ }
+ if (bi >= n_expert) break; // as router_top10_kernel: no rank i or later is written (every p left is NaN)
+ if ((bi & 31) == lane) live &= ~(1u << (bi >> 5));
+ if (lane == i) { my_w = bv; my_id = bi; }
+ nsel = i + 1;
+ }
+ if (nsel == k) {
+ double s = 0.0;
+ for (int i = 0; i < k; ++i) s += (double) __shfl_sync(0xffffffffu, my_w, i);
+ const double sc = fmax(s, 6.103515625e-05); // 2**-14
+ if (lane < k) {
+ ids[(size_t) t * k + lane] = my_id;
+ weights[(size_t) t * k + lane] = (float) ((double) my_w / sc);
+ }
+ } else { // router_top10_kernel's tail exactly: unwritten ranks keep what the buffer held and are renormalised too
+ if (lane < nsel) { ids[(size_t) t * k + lane] = my_id; weights[(size_t) t * k + lane] = my_w; }
+ __threadfence();
+ if (lane == 0) {
+ double s = 0.0;
+ for (int i = 0; i < k; ++i) s += (double) weights[(size_t) t * k + i];
+ const double sc = fmax(s, 6.103515625e-05);
+ for (int i = 0; i < k; ++i)
+ weights[(size_t) t * k + i] = (float) ((double) weights[(size_t) t * k + i] / sc);
+ }
+ }
+}
+
+void launch_generic(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights, void* stream,
+ int mode) { // mode 0: router_top10_kernel, 1: the HIP fast kernel, 2: the fast kernel's serial path
+ int threads = n_expert < RT_MAX_THREADS ? n_expert : RT_MAX_THREADS;
+ threads = (threads + 31) & ~31;
+ const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u;
+ const size_t smem = taken_bytes + (size_t) n_expert * sizeof(double) + (size_t) n_expert * sizeof(float);
+ if (mode == 1) {
+ router_top10_fast_kernel<false><<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>(
+ logits, n_tokens, n_expert, k, ids, weights);
+ return;
+ }
+ if (mode == 2) {
+ router_top10_fast_kernel<true><<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>(
+ logits, n_tokens, n_expert, k, ids, weights);
+ return;
+ }
+ router_top10_kernel<<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>(
+ logits, n_tokens, n_expert, k, ids, weights);
+}
+#endif
+
} // namespace
+bool router_top10_variant(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights,
+ void* stream, int variant) {
+#if defined(__HIPCC__)
+ if (n_tokens <= 0 || n_expert <= 64 || n_expert > 512 || k <= 0 || k > 32) return false;
+ if (variant < 0 || variant > 2) return false;
+ launch_generic(logits, n_tokens, n_expert, k, ids, weights, stream, variant);
+ return cudaGetLastError() == cudaSuccess;
+#else
+ (void) logits; (void) n_tokens; (void) n_expert; (void) k; (void) ids; (void) weights; (void) stream;
+ (void) variant;
+ return false;
+#endif
+}
+
void router_top10(const float *logits, int n_tokens, int n_expert, int k,
int *ids, float *weights, void *stream) try {
+#if defined(__HIPCC__)
+ {
+ static const bool old = std::getenv("STRATA_HIP_ROUTER_OLD") != nullptr;
+ if (!old && n_tokens > 0 && n_expert > 64 && n_expert <= 512 && k > 0 && k <= 32) {
+ launch_generic(logits, n_tokens, n_expert, k, ids, weights, stream, 1);
+ const cudaError_t e = cudaGetLastError();
+ if (e != cudaSuccess) {
+ std::fprintf(stderr, "router_top10 launch: %s\n", cudaGetErrorString(e));
+ std::exit(1);
+ }
+ if (stream == nullptr) {
+ const cudaError_t s = cudaDeviceSynchronize();
+ if (s != cudaSuccess) {
+ std::fprintf(stderr, "router_top10: %s\n", cudaGetErrorString(s));
+ std::exit(1);
+ }
+ }
+ return;
+ }
+ }
+#endif
if (n_tokens <= 0 || n_expert <= 0 || k <= 0) return;
if (k > 64) {
std::fprintf(stderr, "router_top10: k %d exceeds the kernel's 64\n", k);
diff --git a/sycl/src/kernels/cuda/verify_kernels.dp.cpp b/sycl/src/kernels/cuda/verify_kernels.dp.cpp
index 7b9178e18..f3ca2482a 100644
--- a/sycl/src/kernels/cuda/verify_kernels.dp.cpp
+++ b/sycl/src/kernels/cuda/verify_kernels.dp.cpp
@@ -1278,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 / gfx12: a constant 100 MHz counter, in ns
+ t = wall_clock64() * 10ull; // gfx10.3 / 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/kv_hybrid_parity.cpp b/sycl/src/kernels/kv_hybrid_parity.cpp
index cfcde58c0..871532de3 100644
--- a/sycl/src/kernels/kv_hybrid_parity.cpp
+++ b/sycl/src/kernels/kv_hybrid_parity.cpp
@@ -283,9 +283,9 @@ int main() {
for (auto& x : q) x = nd(rng);
float* d_q = dalloc<float>(q.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
+ 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(
diff --git a/sycl/src/kernels/kv_q4_parity.cpp b/sycl/src/kernels/kv_q4_parity.cpp
index 61d43df4a..46e43fb8c 100644
--- a/sycl/src/kernels/kv_q4_parity.cpp
+++ b/sycl/src/kernels/kv_q4_parity.cpp
@@ -116,9 +116,9 @@ int main() {
float* d_src = dalloc<float>(n_vectors * 256);
float* d_dst = dalloc<float>(n_vectors * 256);
/*
- 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_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
@@ -213,9 +213,9 @@ int main() {
for (int i = 0; i < pages; ++i) table[i] = (i * 3 + 5) % pages; // permutation
int32_t* d_table = dalloc<int32_t>(pages);
/*
- 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_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
@@ -351,9 +351,9 @@ int main() {
ids[i] = positions[rng() % n_fill];
}
/*
- 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_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
@@ -362,9 +362,9 @@ int main() {
int32_t hstep[k::kStepCount] = {0, 0, 0, max_ids};
/*
- 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(
diff --git a/sycl/src/kernels/ple_parity.cpp b/sycl/src/kernels/ple_parity.cpp
index 66997602c..76f3e1117 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_current_device().queues_wait_and_throw(), 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_current_device().queues_wait_and_throw(), 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_current_device().queues_wait_and_throw(), 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_current_device().queues_wait_and_throw(), 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_current_device().queues_wait_and_throw(), 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_current_device().queues_wait_and_throw(), 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_current_device().queues_wait_and_throw(), 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_current_device().queues_wait_and_throw(), 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_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
d_emb, cap.emb.data() + (size_t)p * nd, nd * 4).wait()),
diff --git a/sycl/src/kernels/q5_projection_parity.cpp b/sycl/src/kernels/q5_projection_parity.cpp
new file mode 100644
index 000000000..a89dde240
--- /dev/null
+++ b/sycl/src/kernels/q5_projection_parity.cpp
@@ -0,0 +1,86 @@
+// Q5_1 shared-expert projection: Strata CUDA dequantization vs ggml.
+#define NOMINMAX
+#define DPCT_PROFILING_ENABLED
+#include <sycl/sycl.hpp>
+#include <dpct/dpct.hpp>
+#include "strata/artifact/gguf_reader.hpp"
+#include "strata/kernels/dequant_bf16.hpp"
+#include "ggml.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <cstdint>
+#include <cstring>
+#include <vector>
+
+int main(int argc, char **argv) try {
+ if (argc != 2) {
+ std::fprintf(stderr, "usage: q5_projection_parity <shard1.gguf>\n");
+ return 2;
+ }
+ strata::GgufFile gguf(argv[1]);
+ const auto* t = gguf.find("blk.0.ffn_down_shexp.weight");
+ if (!t || t->type != 7 || t->shape.size() != 2) {
+ std::fprintf(stderr, "expected blk.0.ffn_down_shexp.weight Q5_1\n");
+ return 2;
+ }
+ const int64_t cols = (int64_t) t->shape[0], rows = std::min<int64_t>(4, (int64_t) t->shape[1]);
+ const size_t weight_bytes = (size_t) rows * (size_t) (cols / 32) * 24;
+ const size_t elements = (size_t) rows * (size_t) cols;
+ const uint8_t* source = gguf.tensor_data(*t);
+ void *dweight = nullptr, *dfloat = nullptr, *dbf16 = nullptr;
+ if (DPCT_CHECK_ERROR(dweight = (void *)sycl::malloc_device(
+ weight_bytes, dpct::get_in_order_queue())) != 0 ||
+ DPCT_CHECK_ERROR(
+ dfloat = (void *)sycl::malloc_device(
+ elements * sizeof(float), dpct::get_in_order_queue())) != 0 ||
+ DPCT_CHECK_ERROR(dbf16 = (void *)sycl::malloc_device(
+ elements * sizeof(uint16_t),
+ dpct::get_in_order_queue())) != 0) {
+ std::fprintf(stderr, "CUDA allocation failed\n");
+ return 1;
+ }
+ /*
+ DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
+ the original code the source host memory is pageable memory. If the memory
+ is not pageable, call wait() on event return by memcpy API to ensure
+ synchronization behavior.
+ */
+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dweight, source, weight_bytes).wait();
+ strata::kernels::dequant_f32(7, dweight, 0, rows, cols, (float*) dfloat, nullptr);
+ strata::kernels::dequant_bf16(7, dweight, 0, rows, cols, (uint16_t*) dbf16, nullptr);
+ std::vector<float> got(elements), ref(elements);
+ std::vector<uint16_t> got_bf16(elements);
+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
+ .memcpy(got.data(), dfloat, elements * sizeof(float))
+ .wait();
+ (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
+ .memcpy(got_bf16.data(), dbf16, elements * sizeof(uint16_t))
+ .wait();
+ sycl::free(dweight, dpct::get_in_order_queue());
+ sycl::free(dfloat, dpct::get_in_order_queue());
+ sycl::free(dbf16, dpct::get_in_order_queue());
+ const auto* traits = ggml_get_type_traits(GGML_TYPE_Q5_1);
+ for (int64_t r = 0; r < rows; ++r)
+ traits->to_float(source + (size_t) r * (size_t) (cols / 32) * 24,
+ ref.data() + (size_t) r * (size_t) cols, cols);
+ double max_abs = 0;
+ size_t bf16_bad = 0;
+ for (size_t i = 0; i < elements; ++i) {
+ max_abs = std::max(max_abs, (double) std::fabs(got[i] - ref[i]));
+ uint32_t bits;
+ std::memcpy(&bits, &ref[i], sizeof(bits));
+ const uint16_t expected = (uint16_t) ((bits + 0x7fffu + ((bits >> 16) & 1u)) >> 16);
+ if (got_bf16[i] != expected) ++bf16_bad;
+ }
+ const bool ok = max_abs <= 1e-6 && bf16_bad == 0;
+ std::printf("Q5_1 projection: %zu elements, max_abs %.3e, bf16 differences %zu %s\n",
+ elements, max_abs, bf16_bad, ok ? "PASS" : "FAIL");
+ return ok ? 0 : 1;
+}
+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/src/kernels/qsa_prompt_attn_parity.cpp b/sycl/src/kernels/qsa_prompt_attn_parity.cpp
index f358a4b7c..ba4a99640 100644
--- a/sycl/src/kernels/qsa_prompt_attn_parity.cpp
+++ b/sycl/src/kernels/qsa_prompt_attn_parity.cpp
@@ -7,6 +7,7 @@
// 1. against FP64, the new kernel's error is no larger than a small multiple of the old kernel's (both FP32 math);
// 2. the new and old outputs agree to a relative 1e-4 of the output scale;
// then times both over a prompt chunk (the old one in batches of 32, as prefill.cpp calls it).
+// HIP builds (S6): the same checks for the RDNA4 matrix-core kernel (STRATA_HIP_WMMA), skipped (77) off gfx12.
// Usage: qsa_prompt_attn_parity [context=32768] [queries=2048] [reps=5]
#define DPCT_PROFILING_ENABLED
#include <sycl/sycl.hpp>
@@ -19,6 +20,7 @@
#include <cmath>
#include <cstdio>
#include <cstdlib>
+#include <cstring>
#include <random>
#include <vector>
@@ -250,12 +252,32 @@ int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16
} // namespace
int main(int argc, char** argv) {
+ setenv("STRATA_PROMPT_ATTN_XMX", "1", 0); // SYCL port: the batched kernel under test is the XMX one (opt-in in the engine)
+#if defined(__HIP_PLATFORM_AMD__)
+ // S6: on AMD the kernel under test is the RDNA4 matrix-core one (opt-in in the engine); other cards skip
+ {
+ int dev = 0;
+ hipDeviceProp_t prop{};
+ if (hipGetDevice(&dev) != hipSuccess || hipGetDeviceProperties(&prop, dev) != hipSuccess) return 2;
+ if (std::strncmp(prop.gcnArchName, "gfx12", 5) != 0) {
+ std::printf("SKIP: %s is not gfx12 (the matrix-core prompt attention is RDNA4 only)\n", prop.gcnArchName);
+ return 77;
+ }
+#if defined(_WIN32)
+ _putenv_s("STRATA_HIP_WMMA", "1");
+#else
+ setenv("STRATA_HIP_WMMA", "1", 1);
+#endif
+ }
+#endif
const int64_t ctx = argc > 1 ? std::atoll(argv[1]) : 32768;
const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 2048;
const int reps = argc > 3 ? std::atoi(argv[3]) : 5;
int fails = 0;
fails += run(1, ctx, nq, reps);
- fails += run(0, ctx, nq, reps);
+#if !defined(__HIP_PLATFORM_AMD__)
+ fails += run(0, ctx, nq, reps); // FP16 KV: the RDNA4 kernel takes int8 KV only
+#endif
fails += run(1, 1500, std::min<int64_t>(nq, 1500), reps); // short context: the selection is every cell
fails += run(1, 2100, std::min<int64_t>(nq, 256), reps); // the identity-to-sparse edge
std::printf("FAILURES: %d\n", fails);
diff --git a/sycl/src/kernels/qsa_select_bench.cpp b/sycl/src/kernels/qsa_select_bench.cpp
index 533237f94..d911aee33 100644
--- a/sycl/src/kernels/qsa_select_bench.cpp
+++ b/sycl/src/kernels/qsa_select_bench.cpp
@@ -1,7 +1,9 @@
// src/kernels/qsa_select_bench.cpp - the prompt path's QSA selection (qsa_select.hpp) timed per stage, block scores
// (the warp kernel and the tensor-core one) and top-k, for a batch of consecutive queries at a given context, and
// the two scorers compared: score difference and how many selections differ (GPU, synthetic, no model).
-// Usage: qsa_select_bench [context=131072] [queries=256] [reps=10]
+// Usage: qsa_select_bench [context=131072] [queries=256] [reps=10] [capacity_cells]
+// capacity_cells (the engine's --max-context): the score buffers and the top-k dispatch follow the CAPACITY
+// (max_blocks = capacity / 4 + 2), the work follows the context. Default: capacity = context (max_blocks = ctx / 4 + 1).
#define DPCT_PROFILING_ENABLED
#include <sycl/sycl.hpp>
#include <dpct/dpct.hpp>
@@ -49,7 +51,8 @@ int main(int argc, char** argv) {
const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 256;
const int reps = argc > 3 ? std::atoi(argv[3]) : 10;
const k::QsaShapes s = k::qsa_real_shapes();
- const int64_t max_blocks = ctx / 4 + 1, cap = k::qsa_selection_width(k::kTopkMaxCells, s);
+ const int64_t capacity = argc > 4 ? std::atoll(argv[4]) : 0;
+ const int64_t max_blocks = capacity > 0 ? capacity / 4 + 2 : ctx / 4 + 1, cap = k::qsa_selection_width(k::kTopkMaxCells, s);
std::mt19937 rng(7);
std::normal_distribution<float> nd(0.f, 1.f);
// keys with a shared direction plus noise, so the scores have a spread like a real indexer's
@@ -95,6 +98,8 @@ int main(int argc, char** argv) {
"malloc");
const int64_t active = steps[(size_t) ((nq - 1) * k::kStepCount + k::kStepNBid)] + 1;
auto run_old = [&] { k::qsa_block_scores(d_pooled, d_dead, d_q, d_steps, nq, max_blocks, s, sc_old, nullptr, active); };
+ // a device without the tensor-core scorer (HIP other than gfx12): time the warp scorer and the top-k only
+ const bool have_tc = k::qsa_block_scores_tc(d_pooled, d_dead, d_q, d_steps, 1, max_blocks, s, sc_new, nullptr, active);
auto run_new = [&] {
if (!k::qsa_block_scores_tc(d_pooled, d_dead, d_q, d_steps, nq, max_blocks, s, sc_new, nullptr, active)) {
std::fprintf(stderr, "tc scorer refused\n");
@@ -102,15 +107,18 @@ int main(int argc, char** argv) {
}
};
run_old();
- run_new();
+ if (have_tc) run_new();
+ else ck(DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
+ sc_new, sc_old, (size_t)(nq * max_blocks) * 4).wait()),
+ "copy");
k::qsa_block_topk_ref(sc_old, d_steps, nq, max_blocks, cap, s, ids_old, nullptr);
- k::qsa_block_topk(sc_new, d_steps, nq, max_blocks, cap, s, ids_new, nullptr);
+ k::qsa_block_topk(sc_new, d_steps, nq, max_blocks, cap, s, ids_new, nullptr, active);
int32_t* ids_reg = nullptr; // the register top-k on the OLD scores: must equal the reference exactly
ck(DPCT_CHECK_ERROR(
ids_reg = (int32_t *)sycl::malloc_device(
(size_t)(nq * cap) * 4, dpct::get_in_order_queue())),
"malloc");
- k::qsa_block_topk(sc_old, d_steps, nq, max_blocks, cap, s, ids_reg, nullptr);
+ k::qsa_block_topk(sc_old, d_steps, nq, max_blocks, cap, s, ids_reg, nullptr, active);
ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
"warm");
// compare
@@ -161,6 +169,32 @@ int main(int argc, char** argv) {
cells_diff += (int64_t) d.size() / 2;
cells_all += w;
}
+ // accuracy against an FP64 host reference on a sample (blocks below n_bid; the tail block is the warp kernel's own
+ // arithmetic in both scorers). Gate, as the prompt-attention harness's: the scorer under test is no worse than 4x
+ // the warp kernel's error, floored at 1e-6 of the score scale.
+ double err_old = 0, err_new = 0, scale = 0;
+ {
+ std::mt19937 srng(11);
+ const int64_t nqs = std::min<int64_t>(nq, 32);
+ for (int64_t qs = 0; qs < nqs; ++qs) {
+ const int64_t i = qs * nq / nqs;
+ const int64_t nbid = steps[(size_t) (i * k::kStepCount + k::kStepNBid)];
+ if (nbid <= 0) continue;
+ for (int sidx = 0; sidx < 1024; ++sidx) {
+ const int64_t j = sidx < 64 ? std::min<int64_t>(nbid - 1, sidx) : (int64_t) (srng() % (uint64_t) nbid);
+ double ref = 0;
+ for (int h = 0; h < 4; ++h) {
+ double d = 0;
+ for (int c = 0; c < 128; ++c) d += (double) q[(size_t) (i * 512 + h * 128 + c)] * (double) pooled[(size_t) (j * 128 + c)];
+ ref += d > 0 ? d : 0;
+ }
+ scale = std::max(scale, std::fabs(ref));
+ err_old = std::max(err_old, std::fabs(ref - (double) a[(size_t) (i * max_blocks + j)]));
+ err_new = std::max(err_new, std::fabs(ref - (double) b[(size_t) (i * max_blocks + j)]));
+ }
+ }
+ }
+ const bool acc_ok = !have_tc || err_new <= std::max(4.0 * err_old, 1e-6 * scale);
// time
dpct::event_ptr e0, e1;
e0 = new sycl::event(); e1 = new sycl::event();
@@ -184,14 +218,17 @@ int main(int argc, char** argv) {
std::exit(1);
}
};
- const float t_old = timed(run_old), t_new = timed(run_new);
+ const float t_old = timed(run_old), t_new = have_tc ? timed(run_new) : t_old;
const float t_tk = timed([&] { k::qsa_block_topk_ref(sc_old, d_steps, nq, max_blocks, cap, s, ids_old, nullptr); });
- const float t_tk2 = timed([&] { k::qsa_block_topk(sc_old, d_steps, nq, max_blocks, cap, s, ids_reg, nullptr); });
+ const float t_tk2 = timed([&] { k::qsa_block_topk(sc_old, d_steps, nq, max_blocks, cap, s, ids_reg, nullptr, active); });
std::printf("top-k %.3f -> %.3f ms (%.1fx), register top-k identical to the reference %lld/%lld\n", t_tk, t_tk2,
t_tk / t_tk2, (long long) reg_same, (long long) nq);
+ std::printf("%s accuracy vs FP64 (score scale %.3g): warp kernel max err %.3g, tensor-core max err %.3g (%.2g of scale)\n",
+ !have_tc ? "SKIP" : acc_ok ? "PASS" : "FAIL", scale, err_old, err_new, scale > 0 ? err_new / scale : 0.0);
+ if (!have_tc) std::printf("tensor-core scorer not available on this device: warp scorer %.3f ms, top-k %.3f ms (%.0f%% of the two)\n", t_old, t_tk2, 100.0 * t_tk2 / (t_old + t_tk2));
std::printf("ctx %lld, %lld queries x %lld blocks: scores %.3f -> %.3f ms (%.1fx), top-k %.3f ms; score rel diff "
"mean %.2g max %.2g; selections identical %lld/%lld, cells differing %.4f%%\n", (long long) ctx,
(long long) nq, (long long) active, t_old, t_new, t_old / t_new, t_tk, sum_rel / std::max(1.0, n_rel),
max_rel, (long long) same_sel, (long long) nq, cells_all ? 100.0 * (double) cells_diff / (double) cells_all : 0.0);
- return 0;
+ return acc_ok && reg_same == nq ? 0 : 1;
}
diff --git a/sycl/src/kernels/router_top10_parity.cpp b/sycl/src/kernels/router_top10_parity.cpp
index d30a47700..ae920a04f 100644
--- a/sycl/src/kernels/router_top10_parity.cpp
+++ b/sycl/src/kernels/router_top10_parity.cpp
@@ -79,9 +79,9 @@ int run_case(const char* name, const std::vector<float>& logits, int n_tokens, i
h_w.size(), dpct::get_in_order_queue())),
"malloc w");
/*
- 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_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
diff --git a/sycl/src/kernels/s2_gemv_q8_parity.cpp b/sycl/src/kernels/s2_gemv_q8_parity.cpp
index 3a578322b..25d169aaa 100644
--- a/sycl/src/kernels/s2_gemv_q8_parity.cpp
+++ b/sycl/src/kernels/s2_gemv_q8_parity.cpp
@@ -74,27 +74,27 @@ int main(int argc, char** argv) {
(size_t)n_out, dpct::get_in_order_queue())),
"m y2");
/*
- 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_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
d_x, x.data(), x.size() * sizeof(float)).wait()),
"c 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_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
d_codes, codes.data(), codes.size()).wait()),
"c codes");
/*
- 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_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
@@ -198,9 +198,9 @@ int main(int argc, char** argv) {
hx.size(), dpct::get_in_order_queue())),
"m hx");
/*
- 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_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
diff --git a/sycl/src/kernels/s_gemv_parity.cpp b/sycl/src/kernels/s_gemv_parity.cpp
index f2ba1f18c..5017cfb72 100644
--- a/sycl/src/kernels/s_gemv_parity.cpp
+++ b/sycl/src/kernels/s_gemv_parity.cpp
@@ -247,36 +247,36 @@ void test_q4k(long long n_in, long long n_out, double tol, int* total_bad) {
(size_t)n_out, dpct::get_in_order_queue())),
"cudaMalloc y");
/*
- DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
- the original code the source host memory is pageable memory. If the memory
- is not pageable, call wait() on event return by memcpy API to ensure
+ 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_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
d_x, x.data(), x.size() * sizeof(uint16_t)).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_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
d_codes, codes.data(), codes.size()).wait()),
"copy codes");
/*
- 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_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
d_scales, scales.data(), scales.size() * sizeof(float)).wait()),
"copy scales");
/*
- 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_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
@@ -367,27 +367,27 @@ void bench_s2_gemv(long long n_in, long long n_out, int iters, int* split_bad) {
(size_t)n_out, dpct::get_in_order_queue())),
"bench y");
/*
- DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
- the original code the source host memory is pageable memory. If the memory
- is not pageable, call wait() on event return by memcpy API to ensure
+ 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_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
d_x, x.data(), x.size() * sizeof(uint16_t)).wait()),
"bench 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_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
d_codes, codes.data(), codes.size()).wait()),
"bench copy codes");
/*
- 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_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
diff --git a/sycl/src/kernels/sampler_parity.cpp b/sycl/src/kernels/sampler_parity.cpp
index 4117ed8d8..7938ed9bb 100644
--- a/sycl/src/kernels/sampler_parity.cpp
+++ b/sycl/src/kernels/sampler_parity.cpp
@@ -109,9 +109,9 @@ int run(const char* name, const std::vector<float>& logits, int n_tokens, const
(size_t)n_tokens, dpct::get_in_order_queue())),
"malloc out");
/*
- DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
- the original code the source host memory is pageable memory. If the memory
- is not pageable, call wait() on event return by memcpy API to ensure
+ 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_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
diff --git a/sycl/src/ngram/ple_reader.cpp b/sycl/src/ngram/ple_reader.cpp
index 19e017b4d..4a9df10e6 100644
--- a/sycl/src/ngram/ple_reader.cpp
+++ b/sycl/src/ngram/ple_reader.cpp
@@ -5,6 +5,7 @@
#include "strata/ngram/ple_reader.hpp"
#include <algorithm>
+#include <chrono>
#include <condition_variable>
#include <cstring>
#include <deque>
@@ -36,15 +37,17 @@ constexpr uint32_t EMPTY = 0xFFFFFFFFu;
/// Set-associative row cache: 8 ways per set, round-robin replacement inside a set. Bounded by construction.
struct RowCache {
uint64_t sets = 0;
+ uint32_t rb = ROW_BYTES; // bytes per row
std::vector<uint32_t> keys; // sets * WAYS
- std::vector<uint8_t> data; // sets * WAYS * ROW_BYTES
+ std::vector<uint8_t> data; // sets * WAYS * rb
std::vector<uint8_t> next; // per-set replacement pointer
uint64_t used = 0;
- void init(uint64_t rows) {
+ void init(uint64_t rows, uint32_t row_bytes = ROW_BYTES) {
sets = rows / WAYS;
+ rb = row_bytes;
keys.assign(sets * WAYS, EMPTY);
- data.assign(sets * WAYS * ROW_BYTES, 0);
+ data.assign(sets * WAYS * rb, 0);
next.assign(sets, 0);
used = 0;
}
@@ -56,7 +59,7 @@ struct RowCache {
if (sets == 0) return nullptr;
const uint64_t s = mix(row) % sets;
for (uint32_t w = 0; w < WAYS; ++w)
- if (keys[s * WAYS + w] == row) return &data[(s * WAYS + w) * ROW_BYTES];
+ if (keys[s * WAYS + w] == row) return &data[(s * WAYS + w) * rb];
return nullptr;
}
void insert(uint32_t row, const uint8_t* bytes) {
@@ -66,7 +69,7 @@ struct RowCache {
next[s] = (uint8_t) ((w + 1) % WAYS);
if (keys[s * WAYS + w] == EMPTY) ++used;
keys[s * WAYS + w] = row;
- std::memcpy(&data[(s * WAYS + w) * ROW_BYTES], bytes, ROW_BYTES);
+ std::memcpy(&data[(s * WAYS + w) * rb], bytes, rb);
}
};
@@ -82,6 +85,7 @@ struct Job {
uint32_t ticket = 0;
std::vector<Use> uses;
double issued_us = 0;
+ bool keepalive = false;// no rows and no ticket: it only keeps the SSD awake (`set_keepalive`)
};
struct TicketState {
@@ -104,6 +108,7 @@ struct PleReader::Impl {
DirectFile file;
uint64_t table_offset = 0;
uint64_t n_rows = 0;
+ uint32_t row_bytes = ROW_BYTES;
uint32_t max_inflight = 0;
uint8_t* slab = nullptr; // max_inflight slots of 2 pages
std::vector<uint32_t> free_slots;
@@ -117,6 +122,12 @@ struct PleReader::Impl {
size_t ring_pos = 0;
double delay_us = 0;
std::string error;
+ // the keep-alive (`set_keepalive`), steady-clock microseconds; `keep_us` 0 = off
+ double keep_us = 0;
+ double keep_window_us = 0;
+ double last_issue_us = 0; // the last `issue`
+ double last_read_us = 0; // the last read that went out, rows or keep-alive
+ uint64_t rng = 0x9E3779B97F4A7C15ull;
bool threaded = false;
bool stop = false;
@@ -154,7 +165,14 @@ struct PleReader::Impl {
auto tt = tickets.find(j.ticket);
if (tt != tickets.end() && tt->second.t_first == 0) tt->second.t_first = j.issued_us;
}
- if (!file.submit(j.offset, slot_buf(s), j.length, s, error)) {
+ std::string kerr; // a keep-alive read that cannot go out must not fail the reader
+ if (!file.submit(j.offset, slot_buf(s), j.length, s, j.keepalive ? kerr : error)) {
+ if (j.keepalive) { // no more of them: the SSD may sleep as before
+ keep_us = 0;
+ j.keepalive = false;
+ free_slots.push_back(s);
+ continue;
+ }
j.uses.clear();
auto it = tickets.find(j.ticket);
if (it != tickets.end() && it->second.pending > 0) --it->second.pending;
@@ -162,12 +180,35 @@ struct PleReader::Impl {
cancel_queued();
return false;
}
- stats.submit_us += now_us() - j.issued_us;
- ++stats.reads;
+ last_read_us = j.issued_us;
+ if (!j.keepalive) { // a keep-alive read counts when it completes (`finish`)
+ stats.submit_us += now_us() - j.issued_us;
+ ++stats.reads;
+ }
}
return true;
}
+ /// When the next keep-alive read is due, or < 0 when none is: it is off, the reader failed, or no rows
+ /// were asked for within the window (then the SSD may sleep; the next `issue` re-arms it).
+ double keepalive_due(double now) const {
+ if (keep_us <= 0 || !error.empty() || last_issue_us <= 0 || now - last_issue_us > keep_window_us) return -1;
+ return last_read_us + keep_us;
+ }
+
+ /// One page of the table, a different one each time, so the SSD really reads (not its controller's buffer).
+ void queue_keepalive() {
+ rng ^= rng << 13;
+ rng ^= rng >> 7;
+ rng ^= rng << 17;
+ const uint64_t first = table_offset / PAGE, end = (table_offset + n_rows * (uint64_t) row_bytes) / PAGE;
+ Job j;
+ j.offset = (first + (end > first ? rng % (end - first) : 0)) * PAGE;
+ j.length = PAGE;
+ j.keepalive = true;
+ queue.push_back(std::move(j));
+ }
+
bool finish(const Completion& c) {
const uint32_t s = (uint32_t) c.tag;
if (s >= inflight.size()) {
@@ -176,6 +217,17 @@ struct PleReader::Impl {
return false;
}
Job& j = inflight[s];
+ if (j.keepalive) { // no rows: it counts once it is done, with how long it took;
+ if (c.ok) { // a failed one turns the keep-alive off, not the reader
+ ++stats.keepalive_reads;
+ stats.keepalive_us_max = std::max(stats.keepalive_us_max, now_us() - j.issued_us);
+ } else {
+ keep_us = 0;
+ }
+ j.keepalive = false;
+ free_slots.push_back(s);
+ return error.empty() ? pump() : true;
+ }
if (!c.ok) {
error = "PleReader: a table read failed";
cancel_queued();
@@ -189,7 +241,7 @@ struct PleReader::Impl {
stats.bytes += c.bytes;
const uint8_t* buf = slot_buf(s);
for (const Use& u : j.uses) {
- if (u.in_page + ROW_BYTES > c.bytes) {
+ if (u.in_page + row_bytes > c.bytes) {
error = "PleReader: short read inside the table";
cancel_queued();
j.uses.clear();
@@ -200,7 +252,7 @@ struct PleReader::Impl {
}
}
for (const Use& u : j.uses) {
- std::memcpy(u.dst, buf + u.in_page, ROW_BYTES);
+ std::memcpy(u.dst, buf + u.in_page, row_bytes);
cache.insert(u.row, buf + u.in_page);
}
auto it = tickets.find(j.ticket);
@@ -260,7 +312,14 @@ struct PleReader::Impl {
void worker_loop() {
std::unique_lock<std::mutex> lk(mu);
for (;;) {
- cv_work.wait(lk, [&] { return stop || !queue.empty() || busy(); });
+ // Idle: wait for work. While rows are being asked for, the wait ends in time for a keep-alive read.
+ while (!(stop || !queue.empty() || busy())) {
+ const double now = now_us();
+ const double due = keepalive_due(now);
+ if (due < 0) cv_work.wait(lk);
+ else if (now >= due) queue_keepalive();
+ else cv_work.wait_for(lk, std::chrono::microseconds(std::max<int64_t>(1000, (int64_t) (due - now))));
+ }
if (stop && !busy()) break;
if (error.empty() && !pump() && error.empty()) error = "PleReader: submit failed";
if (!delayed.empty() && !release_delayed() && error.empty()) error = "PleReader: read failed";
@@ -288,11 +347,13 @@ PleReader::~PleReader() {
}
bool PleReader::open(const std::string& path, uint64_t table_offset, uint64_t n_rows, uint32_t max_inflight,
- uint64_t cache_rows, std::string& err, bool io_thread) {
+ uint64_t cache_rows, std::string& err, bool io_thread, uint32_t row_bytes) {
close();
if (max_inflight == 0 || max_inflight > 1024) { err = "PleReader: max_inflight must be 1..1024"; return false; }
+ if (row_bytes == 0 || row_bytes > PAGE) { err = "PleReader: row_bytes must be 1..4096"; return false; }
if (!impl_->file.open(path, err)) return false;
- if (table_offset + n_rows * (uint64_t) ROW_BYTES > impl_->file.size()) {
+ impl_->row_bytes = row_bytes;
+ if (table_offset + n_rows * (uint64_t) row_bytes > impl_->file.size()) {
err = "PleReader: the table extends past the end of " + path;
close();
return false;
@@ -305,8 +366,12 @@ bool PleReader::open(const std::string& path, uint64_t table_offset, uint64_t n_
impl_->inflight.assign(max_inflight, Job{});
impl_->free_slots.clear();
for (uint32_t s = max_inflight; s-- > 0;) impl_->free_slots.push_back(s);
- impl_->cache.init(cache_rows);
+ impl_->cache.init(cache_rows, row_bytes);
impl_->error.clear();
+ impl_->keep_us = 0;
+ impl_->last_issue_us = impl_->last_read_us = 0;
+ impl_->rng = 0x9E3779B97F4A7C15ull ^ (uint64_t) now_us();
+ if (impl_->rng == 0) impl_->rng = 1;
reset_stats();
impl_->stop = false;
impl_->threaded = io_thread;
@@ -360,9 +425,12 @@ void PleReader::close() {
m.cache.init(0);
m.threaded = false;
m.stop = false;
+ m.keep_us = 0;
+ m.last_issue_us = m.last_read_us = 0;
}
bool PleReader::is_open() const { return impl_->file.is_open(); }
+uint32_t PleReader::row_bytes() const { return impl_->row_bytes; }
PleReader::Ticket PleReader::issue(const uint32_t* rows, size_t n, uint8_t* out_raw) {
Impl& m = *impl_;
@@ -370,24 +438,28 @@ PleReader::Ticket PleReader::issue(const uint32_t* rows, size_t n, uint8_t* out_
if (m.threaded) lk.lock();
const uint32_t id = m.next_ticket++;
if (m.next_ticket == 0) m.next_ticket = 1;
+ const double now = now_us();
+ const bool rearm = m.keep_us > 0 && (m.last_issue_us <= 0 || now - m.last_issue_us > m.keep_window_us);
+ m.last_issue_us = now;
TicketState& ts = m.tickets[id];
std::unordered_map<uint64_t, size_t> by_page; // aligned offset -> index in `jobs`
std::vector<Job> jobs;
for (size_t i = 0; i < n; ++i) {
- uint8_t* dst = out_raw + i * ROW_BYTES;
+ const uint32_t rb = m.row_bytes;
+ uint8_t* dst = out_raw + i * rb;
++m.stats.requests;
if (rows[i] >= m.n_rows) {
- std::memset(dst, 0, ROW_BYTES);
+ std::memset(dst, 0, rb);
continue;
}
if (const uint8_t* hit = m.cache.find(rows[i])) {
- std::memcpy(dst, hit, ROW_BYTES);
+ std::memcpy(dst, hit, rb);
++m.stats.cache_hits;
continue;
}
- const uint64_t at = m.table_offset + (uint64_t) rows[i] * ROW_BYTES;
+ const uint64_t at = m.table_offset + (uint64_t) rows[i] * rb;
const uint64_t first = at / PAGE * PAGE;
- const uint32_t length = (uint32_t) ((at + ROW_BYTES - 1) / PAGE * PAGE - first + PAGE);
+ const uint32_t length = (uint32_t) ((at + rb - 1) / PAGE * PAGE - first + PAGE);
auto f = by_page.find(first);
if (f != by_page.end()) {
Job& j = jobs[f->second];
@@ -416,6 +488,8 @@ PleReader::Ticket PleReader::issue(const uint32_t* rows, size_t n, uint8_t* out_
if (has_jobs) {
m.cv_work.notify_one();
m.file.wake(); // in case the worker is blocked in the port
+ } else if (rearm) {
+ m.cv_work.notify_one(); // the keep-alive had lapsed: start it again
}
} else if (!m.pump() && m.error.empty()) {
m.error = "PleReader: submit failed";
@@ -462,14 +536,33 @@ bool PleReader::collect(Ticket t, std::string& err) {
return true;
}
+void PleReader::set_keepalive(double period_ms, double window_s) {
+ Impl& m = *impl_;
+ {
+ std::lock_guard<std::mutex> lk(m.mu);
+ m.keep_us = m.threaded && period_ms > 0 ? period_ms * 1000.0 : 0.0;
+ m.keep_window_us = window_s > 0 ? window_s * 1e6 : 0.0;
+ }
+ m.cv_work.notify_all();
+}
+
void PleReader::set_injected_delay_us(double delay_us) {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->delay_us = delay_us < 0 ? 0 : delay_us;
}
const ReaderStats& PleReader::stats() const { return impl_->stats; }
+ReaderStats PleReader::snapshot() const {
+ Impl& m = *impl_;
+ std::unique_lock<std::mutex> lk(m.mu, std::defer_lock);
+ if (m.threaded) lk.lock();
+ return m.stats;
+}
void PleReader::reset_stats() {
- impl_->stats = ReaderStats{};
- impl_->ring_pos = 0;
+ Impl& m = *impl_;
+ std::unique_lock<std::mutex> lk(m.mu, std::defer_lock);
+ if (m.threaded) lk.lock(); // the worker may be counting a keep-alive read
+ m.stats = ReaderStats{};
+ m.ring_pos = 0;
}
uint64_t PleReader::cache_capacity() const { return impl_->cache.sets * WAYS; }
uint64_t PleReader::cache_size() const { return impl_->cache.used; }
diff --git a/sycl/src/prefill/kernels.dp.cpp b/sycl/src/prefill/kernels.dp.cpp
index 88adbd50d..29e30e35a 100644
--- a/sycl/src/prefill/kernels.dp.cpp
+++ b/sycl/src/prefill/kernels.dp.cpp
@@ -49,6 +49,11 @@ __dpct_inline__ uint16_t bf(float f) {
u += 0x7fffu + ((u >> 16) & 1u);
return (uint16_t) (u >> 16);
}
+// The BF16 GEMMs' second operand (STRATA_PREFILL_BF16X2): what the BF16 image `hi` left out of f, itself in BF16.
+// W.hi + W.lo carries ~16 mantissa bits of the activation - the decode path's FP32 x to within ~1e-5.
+__dpct_inline__ uint16_t bf_lo(float f, uint16_t hi) {
+ return bf(f - sycl::bit_cast<float>((uint32_t)hi << 16));
+}
__dpct_inline__ float sigm(float x) {
return 1.0f / (1.0f + sycl::native::exp(-x));
}
@@ -57,6 +62,13 @@ __dpct_inline__ uint16_t hf(float f) {
sycl::vec<float, 1>(f)
.convert<sycl::half, sycl::rounding_mode::rte>()[0]);
}
+// A SwiGLU product for an FP16 GEMM: saturated, so a token with a massive activation cannot turn into inf and then
+// NaN in the down projection (decode's q8_1 has room to ~8e6; FP16 ends at 65504). A NaN stays NaN (fminf/fmaxf
+// would make it -65504 and hide where it came from); finite values below 65504 round exactly as before.
+__dpct_inline__ uint16_t hf_sat(float f) {
+ return hf(sycl::isnan(f) ? f
+ : sycl::fmin(sycl::fmax(f, -65504.0f), 65504.0f));
+}
// block-wide sum for blockDim.x <= 1024, result broadcast
inline float block_sum(float v, float *sh) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
@@ -108,7 +120,8 @@ unsigned blocks_for(int64_t n, int t = 256) { return (unsigned) ((n + t - 1) / t
__dpct_inline__ void gr_norm_kernel(const float *__restrict__ R,
const float *__restrict__ w, float eps,
float *__restrict__ xn,
- uint16_t *__restrict__ xn16) {
+ uint16_t *__restrict__ xn16,
+ uint16_t *__restrict__ xn16_lo) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
sycl::ext::oneapi::this_work_item::get_work_group<3>());
@@ -124,7 +137,9 @@ auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
d += item_ct1.get_local_range(2)) {
const float v = r[d] * rs * w[c * N + d];
xn[row * N + d] = v;
- xn16[row * N + d] = bf(v);
+ const uint16_t h = bf(v);
+ xn16[row * N + d] = h;
+ if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h);
}
}
// F-1: the row scale only (and the BF16 image); gr_mix_r_kernel recomputes r * rs * w itself, in the same order,
@@ -132,7 +147,8 @@ auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
__dpct_inline__ void gr_norm_rs_kernel(const float *__restrict__ R,
const float *__restrict__ w, float eps,
float *__restrict__ rs_out,
- uint16_t *__restrict__ xn16) {
+ uint16_t *__restrict__ xn16,
+ uint16_t *__restrict__ xn16_lo) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
sycl::ext::oneapi::this_work_item::get_work_group<3>());
@@ -145,16 +161,20 @@ auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
d += item_ct1.get_local_range(2)) ss += r[d] * r[d];
const float rs = sycl::rsqrt(block_sum(ss, sh) / (float)N + eps);
if (item_ct1.get_local_id(2) == 0) rs_out[row] = rs;
-#pragma unroll
for (int d = item_ct1.get_local_id(2); d < N;
- d += item_ct1.get_local_range(2))
- xn16[row * N + d] = bf(r[d] * rs * w[c * N + d]);
+ d += item_ct1.get_local_range(2)) {
+ const float v = r[d] * rs * w[c * N + d];
+ const uint16_t h = bf(v);
+ xn16[row * N + d] = h;
+ if (xn16_lo) xn16_lo[row * N + d] = bf_lo(v, h);
+ }
}
__dpct_inline__ void
gr_mix_r_kernel(const float *__restrict__ R, const float *__restrict__ rs,
const float *__restrict__ w, const float *__restrict__ g,
float *__restrict__ mixed, uint16_t *__restrict__ mixed16,
- int64_t T, uint16_t *__restrict__ mixed_h) {
+ int64_t T, uint16_t *__restrict__ mixed_h,
+ uint16_t *__restrict__ mixed16_lo) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
const int64_t i =
(int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
@@ -170,17 +190,23 @@ gr_mix_r_kernel(const float *__restrict__ R, const float *__restrict__ rs,
}
s /= (float) HC;
mixed[i] = s;
- if (mixed16) mixed16[i] = bf(s);
+ if (mixed16) {
+ const uint16_t h = bf(s);
+ mixed16[i] = h;
+ if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h);
+ }
if (mixed_h) mixed_h[i] = hf(s);
}
// F-2: gr_write_kernel for one row (t, c), then gr_norm_rs_kernel's reduction over it with the next half's norm
// weights - the same thread-to-element mapping (256 threads, stride 256) and block_sum, so rs and the BF16 image are
// the same bits, and R is not read back
constexpr int GRW_PER = (N + 255) / 256;
-__dpct_inline__ void gr_write_norm_rs_kernel(
- float *__restrict__ R, const float *__restrict__ bo,
- const float *__restrict__ inj, int64_t inj_ld, const float *__restrict__ w,
- float eps, float *__restrict__ rs_out, uint16_t *__restrict__ xn16) {
+__dpct_inline__ void
+gr_write_norm_rs_kernel(float *__restrict__ R, const float *__restrict__ bo,
+ const float *__restrict__ inj, int64_t inj_ld,
+ const float *__restrict__ w, float eps,
+ float *__restrict__ rs_out, uint16_t *__restrict__ xn16,
+ uint16_t *__restrict__ xn16_lo) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
sycl::ext::oneapi::this_work_item::get_work_group<3>());
@@ -203,24 +229,33 @@ auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
if (item_ct1.get_local_id(2) == 0) rs_out[row] = rs;
k = 0;
#pragma unroll
- for (int d = item_ct1.get_local_id(2); d < N; d += 256, ++k)
- xn16[row * N + d] = bf(v[k] * rs * w[c * N + d]);
+ for (int d = item_ct1.get_local_id(2); d < N; d += 256, ++k) {
+ const float x = v[k] * rs * w[c * N + d];
+ const uint16_t h = bf(x);
+ xn16[row * N + d] = h;
+ if (xn16_lo) xn16_lo[row * N + d] = bf_lo(x, h);
+ }
}
__dpct_inline__ void gr_silu_kernel(const float *__restrict__ lo,
- uint16_t *__restrict__ lo16, int64_t n) {
+ uint16_t *__restrict__ lo16,
+ uint16_t *__restrict__ lo16_lo, int64_t n) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
const int64_t i =
(int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
item_ct1.get_local_id(2);
if (i >= n) return;
const float x = lo[i] / (float) HC;
- lo16[i] = bf(x / (1.0f + sycl::native::exp(-x)));
+ const float v = x / (1.0f + sycl::native::exp(-x));
+ const uint16_t h = bf(v);
+ lo16[i] = h;
+ if (lo16_lo) lo16_lo[i] = bf_lo(v, h);
}
__dpct_inline__ void gr_mix_kernel(const float *__restrict__ xn,
const float *__restrict__ g,
float *__restrict__ mixed,
uint16_t *__restrict__ mixed16, int64_t T,
- uint16_t *__restrict__ mixed_h) {
+ uint16_t *__restrict__ mixed_h,
+ uint16_t *__restrict__ mixed16_lo) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
const int64_t i =
(int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
@@ -235,7 +270,11 @@ __dpct_inline__ void gr_mix_kernel(const float *__restrict__ xn,
}
s /= (float) HC;
mixed[i] = s;
- if (mixed16) mixed16[i] = bf(s);
+ if (mixed16) {
+ const uint16_t h = bf(s);
+ mixed16[i] = h;
+ if (mixed16_lo) mixed16_lo[i] = bf_lo(s, h);
+ }
if (mixed_h) mixed_h[i] = hf(s);
}
__dpct_inline__ void gr_write_kernel(float *__restrict__ R,
@@ -870,7 +909,7 @@ __dpct_inline__ void swiglu_il_kernel(const float *__restrict__ gu,
if (i >= n * 640) return;
const int64_t r = i / 640, k = i % 640;
const float g = gu[r * 1280 + 2 * k], u = gu[r * 1280 + 2 * k + 1];
- h16[i] = hf(g / (1.0f + sycl::native::exp(-g)) * u);
+ h16[i] = hf_sat(g / (1.0f + sycl::native::exp(-g)) * u);
}
__dpct_inline__ void swiglu_pair_kernel(const float *__restrict__ g,
const float *__restrict__ u,
@@ -881,7 +920,7 @@ __dpct_inline__ void swiglu_pair_kernel(const float *__restrict__ g,
item_ct1.get_local_id(2);
if (i >= n * 640) return;
const float a = g[i];
- h16[i] = hf(a / (1.0f + sycl::native::exp(-a)) * u[i]);
+ h16[i] = hf_sat(a / (1.0f + sycl::native::exp(-a)) * u[i]);
}
__dpct_inline__ void gather_rows16_kernel(const uint16_t *__restrict__ x,
const int32_t *__restrict__ src,
@@ -940,23 +979,29 @@ auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
for (int64_t c = item_ct1.get_local_id(2); c < cols;
c += item_ct1.get_local_range(2)) r[c] = s * r[c] * w[c];
}
-__dpct_inline__ void rope_kernel(float *__restrict__ x, int64_t heads,
- int64_t dim, int64_t ld, int64_t pos0,
- float theta_scale, float freq_scale,
- float corr_low, float corr_high,
- float ext_factor, float mscale,
- const int32_t *__restrict__ mtab) {
+// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table. The host launches <false> whenever
+// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it;
+// with it merely skipped at run time, the compiled default path changed its results).
+template <bool TAB>
+__dpct_inline__ void
+rope_kernel(float *__restrict__ x, int64_t heads, int64_t dim, int64_t ld,
+ int64_t pos0, float theta_scale, float freq_scale, float corr_low,
+ float corr_high, float ext_factor, float mscale,
+ const int32_t *__restrict__ mtab, strata::kernels::RopeTab rt) {
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_extrap =
- (float)strata::kernels::mrope_pos(mtab, (int)(pos0 + t), pair) *
- dpct::pow(theta_scale, (float)pair);
float c, s;
- strata::kernels::rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale,
- pair, c, s);
+ if (!(TAB && strata::kernels::rope_tab_cs(rt, strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair), pair, c,
+ s))) {
+ const float theta_extrap =
+ (float)strata::kernels::mrope_pos(mtab, (int)(pos0 + t), pair) *
+ dpct::pow(theta_scale, (float)pair);
+ 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;
@@ -1085,15 +1130,18 @@ __dpct_inline__ void round_f16_kernel(const float *__restrict__ x,
.convert<float, sycl::rounding_mode::automatic>()[0];
}
__dpct_inline__ void to_bf16_kernel(const float *__restrict__ x,
- uint16_t *__restrict__ y, int64_t n) {
+ uint16_t *__restrict__ y,
+ uint16_t *__restrict__ ylo, int64_t n) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
-#pragma unroll
for (int64_t i =
(int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
item_ct1.get_local_id(2);
i < n; i += (int64_t)item_ct1.get_group_range(2) *
- item_ct1.get_local_range(2))
- y[i] = bf(x[i]);
+ item_ct1.get_local_range(2)) {
+ const uint16_t h = bf(x[i]);
+ y[i] = h;
+ if (ylo) ylo[i] = bf_lo(x[i], h);
+ }
}
} // namespace
@@ -1173,7 +1221,7 @@ void round_f16(const float* x, float* y, int64_t n, void* stream) {
}
check("round_f16");
}
-void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream) {
+void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream, uint16_t* ylo) {
if (n <= 0) return;
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
@@ -1188,13 +1236,14 @@ void to_bf16(const float* x, uint16_t* y, int64_t n, void* stream) {
sycl::range(1, 1, 256),
sycl::range(1, 1, 256)),
exp_props, [=](sycl::nd_item<3> item_ct1) {
- to_bf16_kernel(x, y, n);
+ to_bf16_kernel(x, y, ylo, n);
});
}
check("to_bf16");
}
-void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream) {
+void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t* xn16, int64_t T, void* stream,
+ uint16_t* xn16_lo) {
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
@@ -1207,12 +1256,13 @@ void gr_norm(const float* R, const float* w_norm, float eps, float* xn, uint16_t
exp_props,
[=](sycl::nd_item<3> item_ct1)
[[sycl::reqd_sub_group_size(32)]] {
- gr_norm_kernel(R, w_norm, eps, xn, xn16);
+ gr_norm_kernel(R, w_norm, eps, xn, xn16, xn16_lo);
});
}
check("gr_norm");
}
-void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream) {
+void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint16_t* xn16, int64_t T, void* stream,
+ uint16_t* xn16_lo) {
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
@@ -1225,13 +1275,13 @@ void gr_norm_rs(const float* R, const float* w_norm, float eps, float* rs, uint1
exp_props,
[=](sycl::nd_item<3> item_ct1)
[[sycl::reqd_sub_group_size(32)]] {
- gr_norm_rs_kernel(R, w_norm, eps, rs, xn16);
+ gr_norm_rs_kernel(R, w_norm, eps, rs, xn16, xn16_lo);
});
}
check("gr_norm_rs");
}
void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float* gated, float* mixed, uint16_t* mixed16,
- int64_t T, void* stream, uint16_t* mixed_h) {
+ int64_t T, void* stream, uint16_t* mixed_h, uint16_t* mixed16_lo) {
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
@@ -1243,13 +1293,13 @@ void gr_mix_r(const float* R, const float* rs, const float* w_norm, const float*
sycl::range(1, 1, 256)),
exp_props, [=](sycl::nd_item<3> item_ct1) {
gr_mix_r_kernel(R, rs, w_norm, gated, mixed, mixed16, T,
- mixed_h);
+ mixed_h, mixed16_lo);
});
}
check("gr_mix_r");
}
void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_ld, const float* w_norm_next, float eps,
- float* rs, uint16_t* xn16, int64_t T, void* stream) {
+ float* rs, uint16_t* xn16, int64_t T, void* stream, uint16_t* xn16_lo) {
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
@@ -1264,33 +1314,33 @@ void gr_write_norm_rs(float* R, const float* bo, const float* inj, int64_t inj_l
[=](sycl::nd_item<3> item_ct1)
[[sycl::reqd_sub_group_size(32)]] {
gr_write_norm_rs_kernel(R, bo, inj, inj_ld, w_norm_next,
- eps, rs, xn16);
+ eps, rs, xn16, xn16_lo);
});
}
check("gr_write_norm_rs");
}
-void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream) {
+void gr_silu(const float* lo, uint16_t* lo16, int64_t T, void* stream, uint16_t* lo16_lo) {
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
strata::q_of(stream)
->submit([&](sycl::handler &cgh) {
- auto T_LR_ct2 = T * LR;
+ auto T_LR_ct3 = T * LR;
cgh.parallel_for<dpct_kernel_name<class gr_silu_kernel_f26d34>>(
sycl::nd_range<3>(sycl::range(1, 1, blocks_for(T * LR)) *
sycl::range(1, 1, 256),
sycl::range(1, 1, 256)),
exp_props, [=](sycl::nd_item<3> item_ct1) {
- gr_silu_kernel(lo, lo16, T_LR_ct2);
+ gr_silu_kernel(lo, lo16, lo16_lo, T_LR_ct3);
});
});
}
check("gr_silu");
}
void gr_mix(const float* xn, const float* gated, float* mixed, uint16_t* mixed16, int64_t T, void* stream,
- uint16_t* mixed_h) {
+ uint16_t* mixed_h, uint16_t* mixed16_lo) {
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
@@ -1301,7 +1351,8 @@ void gr_mix(const float* xn, const float* gated, float* mixed, uint16_t* mixed16
sycl::range(1, 1, 256),
sycl::range(1, 1, 256)),
exp_props, [=](sycl::nd_item<3> item_ct1) {
- gr_mix_kernel(xn, gated, mixed, mixed16, T, mixed_h);
+ gr_mix_kernel(xn, gated, mixed, mixed16, T, mixed_h,
+ mixed16_lo);
});
}
check("gr_mix");
@@ -1692,6 +1743,8 @@ void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t p
}
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
+ const strata::kernels::RopeTab rt = strata::kernels::rope_table_for(scaling);
+ if (rt.cos != nullptr)
{
auto exp_props = sycl::ext::oneapi::experimental::properties{
sycl::ext::oneapi::experimental::use_root_sync};
@@ -1701,15 +1754,37 @@ void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t p
auto strata_kernels_mrope_table_ct11 =
strata::kernels::mrope_table();
- cgh.parallel_for<dpct_kernel_name<class rope_kernel_4d58b9>>(
+ cgh.parallel_for<dpct_kernel_name<class rope_kernel_4d58b9,
+ dpct_kernel_scalar<true>>>(
+ sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(T * heads)) *
+ sycl::range(1, 1, 32),
+ sycl::range(1, 1, 32)),
+ exp_props, [=](sycl::nd_item<3> item_ct1) {
+ rope_kernel<true>(x, heads, dim, ld, pos0, theta_scale,
+ k.freq_scale, k.corr_low, k.corr_high,
+ k.ext_factor, k.attn_factor,
+ strata_kernels_mrope_table_ct11, rt);
+ });
+ });
+ } else {
+ 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_ct11 =
+ strata::kernels::mrope_table();
+
+ cgh.parallel_for<dpct_kernel_name<class rope_kernel_4d58b9,
+ dpct_kernel_scalar<false>>>(
sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(T * heads)) *
sycl::range(1, 1, 32),
sycl::range(1, 1, 32)),
exp_props, [=](sycl::nd_item<3> item_ct1) {
- rope_kernel(x, heads, dim, ld, pos0, theta_scale,
- k.freq_scale, k.corr_low, k.corr_high,
- k.ext_factor, k.attn_factor,
- strata_kernels_mrope_table_ct11);
+ rope_kernel<false>(
+ x, heads, dim, ld, pos0, theta_scale, k.freq_scale,
+ k.corr_low, k.corr_high, k.ext_factor,
+ k.attn_factor, strata_kernels_mrope_table_ct11, rt);
});
});
}
diff --git a/sycl/src/prefill/prefill.cpp b/sycl/src/prefill/prefill.cpp
index 6fa9ae0db..53542f578 100644
--- a/sycl/src/prefill/prefill.cpp
+++ b/sycl/src/prefill/prefill.cpp
@@ -89,9 +89,19 @@ double g_pinned_share = 1.0;
// 8192-token chunks: 96 slots 1153 tok/s, 384 1294 (the next layer's experts arrive during its attention half) -
// and 96 when a large share goes through host copies (IQ3_S on 64 GB, a third unpinned: 96 slots 1216, 256 1070 -
// the host copies are the limit and the bigger ring only takes cache slots). STRATA_PREFILL_RING overrides.
+int g_ring_override = 0; // #340: set by a layer split (Prefill::set_ring_override); 0 = the rule below
inline int ring_slots(size_t T) {
const char* v = std::getenv("STRATA_PREFILL_RING");
- const int r = v ? std::atoi(v) : (g_pinned_share >= 0.9 ? 384 : 96);
+#if defined(STRATA_USE_HIP)
+ // S6: with the opt-in RDNA4 matrix-core attention (STRATA_HIP_WMMA=1) a 96-slot ring: measured with it, 9070 XT
+ // 4K prompts 718 -> 1,211 tok/s (16K 1,949 -> 2,032), R9700 4K 2,426 -> 2,483 (16K the same)
+ static const bool wmma = [] {
+ const char* e = std::getenv("STRATA_HIP_WMMA");
+ return e != nullptr && e[0] == '1';
+ }();
+ if (!v && g_ring_override <= 0 && wmma) return (int64_t) T >= stream_all_min() ? 96 : STAGE;
+#endif
+ const int r = v ? std::atoi(v) : g_ring_override > 0 ? g_ring_override : (g_pinned_share >= 0.9 ? 384 : 96);
if (v && r == STAGE) return STAGE; // Explicit opt-in to routed-only staging, including large chunks.
// SYCL port: routed-only staging by default. The stream-all walk (every non-resident expert of every layer, copied
// ahead across layers) hangs on the B70 in its first large chunk - the copy engine stops on a barrier (xe resets bcs
@@ -103,6 +113,20 @@ inline int ring_slots(size_t T) {
return (int64_t) T >= stream_all_min() ? big : STAGE;
}
constexpr int DQ = 2; // dequantized-expert ring (FP16 gate/up + down)
+// The BF16-weight projections (hyper-connection, SSM alpha/beta, indexer, router, shared gate, PLE key/value) take
+// BF16 activations here and FP32 ones in decode. STRATA_PREFILL_BF16X2=1 adds each activation's BF16 remainder as a
+// second GEMM (Y = W.hi + W.lo, ~16 mantissa bits): a router that picks its top 10 from the same x decode would.
+// 2 = all but the hyper-connection's; 1 = the hyper-connection's too (its activations are 10240 wide and its up
+// projection writes as much: slower); 0 (the default: opt-in, it changes the prompt path's numbers) = off.
+inline int bf16x2_mode() {
+ static const int v = [] {
+ const char* e = std::getenv("STRATA_PREFILL_BF16X2");
+ return e != nullptr ? std::atoi(e) : 0;
+ }();
+ return v;
+}
+inline bool bf16x2() { return bf16x2_mode() != 0; }
+inline bool bf16x2_hc() { return bf16x2_mode() == 1; }
// F-1: STRATA_GR_UNFUSED=1 keeps the FP32 copy of the normalized rows (gr_norm + gr_mix), the A/B arm
inline bool gr_unfused() {
@@ -322,6 +346,7 @@ struct Prefill::Impl {
uint16_t *xn16 = nullptr, *lo16 = nullptr;
float* mixed = nullptr;
uint16_t *mixed_bf = nullptr, *mixed_h = nullptr;
+ uint16_t *xn16_lo = nullptr, *lo16_lo = nullptr, *mixed_bf_lo = nullptr; // bf16x2(): the BF16 GEMMs' low parts
float* bo = nullptr;
// GDN
float *qkv = nullptr, *z = nullptr, *ab = nullptr, *gate = nullptr, *beta = nullptr, *hbuf = nullptr, *y = nullptr;
@@ -607,8 +632,15 @@ bool Prefill::init(const core::WeightTable &wt, const core::ModelGeometry &g,
m.stager = std::make_unique<Stager>();
const int hw = (int) std::thread::hardware_concurrency();
const char* stv = std::getenv("STRATA_STAGER_THREADS"); // D-5: the host copy threads of unpinned blobs
- if (!m.stager->init((size_t) MAXBLOB(), stv ? std::clamp(std::atoi(stv), 1, 32) : std::max(2, std::min(4, hw / 4))))
- ok = false;
+ // A GGUF read in place (UD-Q4_K_XL beyond its RAM budget): most of a chunk's blobs are page faults on the
+ // SSD, so the copies need many reads in flight - 32 threads and a 128-deep ring read a 4K chunk in 29 s
+ // instead of 71 s on an RTX 5070 / NVMe PC (4 threads, 16 deep: the defaults, kept for every other source)
+ bool files = false;
+ for (int64_t l = 0; src != nullptr && !files && l < g.n_layers; ++l)
+ for (int64_t e = 0; !files && e < g.n_expert; ++e) files = src->transient(l, e);
+ const int threads = stv ? std::clamp(std::atoi(stv), 1, 32) : files ? 32 : std::max(2, std::min(4, hw / 4));
+ if (files && std::getenv("STRATA_STAGER_RING") == nullptr) m.stager->kRing = 4 * threads;
+ if (!m.stager->init((size_t) MAXBLOB(), threads)) ok = false;
}
m.steps_host.resize(T * strata::kernels::kStepCount);
m.ids_host.resize(T * K); m.slot_host.resize(T * K); m.src_host.resize(T * K); m.cnt.resize(m.g->n_expert); m.off.resize(m.g->n_expert + 1);
@@ -722,6 +754,8 @@ bool Prefill::carve(size_t T, void* alloc) {
m.gated = o.take<float>(T * D, ok); m.inj = o.take<float>(T * HC, ok);
m.mixed = o.take<float>(T * N, ok); m.mixed_bf = o.take<uint16_t>(T * N, ok);
m.mixed_h = o.take<uint16_t>(T * N, ok); m.bo = o.take<float>(T * N, ok);
+ if (bf16x2_hc()) { m.xn16_lo = o.take<uint16_t>(T * D, ok); m.lo16_lo = o.take<uint16_t>(T * LR, ok); }
+ if (bf16x2()) m.mixed_bf_lo = o.take<uint16_t>(T * N, ok);
m.steps_dev = o.take<int32_t>(T * strata::kernels::kStepCount, ok);
strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();
s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads;
@@ -973,9 +1007,11 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t
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, strata::kernels::rope_scaling(), m.cs);
- if (st.kv_q4) {
+ if (st.kv_rot) { // rotated as the drafter's own decode stores them (mtp.cpp)
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);
+ }
+ if (st.kv_q4) {
strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, c0, nb, Kc, Vc, s, m.cs, &st.host);
} else {
kv_append(Kc, Vc, nb, c0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool,
@@ -1001,6 +1037,7 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t
return true;
}
void Prefill::set_pinned_share(double share) { g_pinned_share = share; }
+void Prefill::set_ring_override(int slots) { g_ring_override = slots > 0 ? slots : 0; }
double Prefill::pinned_share() { return g_pinned_share; }
uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk) {
@@ -1014,6 +1051,8 @@ uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::Session
auto f = [&](size_t n) { o.take<float>(n, ok); };
f(T * N); f(T * D); f(T * D); o.take<uint16_t>(T * D, ok); f(T * LR); o.take<uint16_t>(T * LR, ok);
f(T * D); f(T * HC); f(T * N); o.take<uint16_t>(T * N, ok); o.take<uint16_t>(T * N, ok); f(T * N);
+ if (bf16x2_hc()) { o.take<uint16_t>(T * D, ok); o.take<uint16_t>(T * LR, ok); }
+ if (bf16x2()) o.take<uint16_t>(T * N, ok);
o.take<int32_t>(T * strata::kernels::kStepCount, ok);
strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();
s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads;
@@ -1052,9 +1091,10 @@ bool native_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y
return true;
}
bool bf16_proj(Gemm& gm, const core::WeightRef* w, const uint16_t* X, float* Y, int64_t T, const std::string& name,
- std::string& err, int64_t ldy = 0) {
+ std::string& err, int64_t ldy = 0, const uint16_t* X_lo = nullptr) {
if (w->kind != core::WeightKind::Bf16InF32 || !w->data) { err = "prefill: " + name + " is not a resident BF16 tensor"; return false; }
gm.bf16(X, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy);
+ if (X_lo) gm.bf16(X_lo, (const uint16_t*) w->data, Y, T, w->ne1 > 0 ? w->ne1 : 1, w->ne0, ldy, 1.0f);
return true;
}
@@ -1499,7 +1539,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
const auto tp = Clock::now();
const strata::kernels::PleWeights& pw = ss.ple.w;
constexpr int64_t HD = strata::kernels::NG_HC_DIM;
- const uint64_t per_token = (uint64_t) (3 * HD + N + 4) * 4 + (uint64_t) N * 2 + 4096;
+ const uint64_t per_token = (uint64_t) (3 * HD + N + 4) * 4 + (uint64_t) N * (bf16x2() ? 4 : 2) + 4096;
const int64_t SB = std::min<int64_t>(T, (int64_t) (m.region_bytes / per_token));
for (int64_t s0 = 0; s0 < T; s0 += SB) {
const int64_t nb = std::min(SB, T - s0);
@@ -1511,16 +1551,19 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
float* val = carve_f((size_t) nb * N);
float* gate = carve_f((size_t) nb * 4);
uint16_t* e16 = (uint16_t*) carve_f((size_t) nb * N / 2);
+ uint16_t* e16_lo = bf16x2() ? (uint16_t*) carve_f((size_t) nb * N / 2) : nullptr;
const float* emb = m.ple_emb + s0 * N;
if (pw.key_bf16 != nullptr) {
- to_bf16(emb, e16, nb * N, m.cs);
+ to_bf16(emb, e16, nb * N, m.cs, e16_lo);
m.gemm.bf16(e16, pw.key_bf16, key, nb, HD, N);
+ if (e16_lo) m.gemm.bf16(e16_lo, pw.key_bf16, key, nb, HD, N, 0, 1.0f);
} else {
to_f16(emb, e16, nb * N, m.cs);
m.gemm.native(e16, pw.key_native_type, pw.key_native_data, key, nb, HD, N);
- to_bf16(emb, e16, nb * N, m.cs);
+ to_bf16(emb, e16, nb * N, m.cs, e16_lo);
}
m.gemm.bf16(e16, pw.value_bf16, val, nb, N, N);
+ if (e16_lo) m.gemm.bf16(e16_lo, pw.value_bf16, val, nb, N, N, 0, 1.0f);
try {
strata::kernels::native_ple_postops_batch(key, m.R + s0 * D, val, ss.ple.hist, pw, qn, gated,
gate, (int) nb, m.cs);
@@ -1551,15 +1594,16 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
*wu = need(v, su.c_str(), err), *wi = need(v, si.c_str(), err);
if (!wn || !wd || !wu || !wi) return false;
pt.mark(kPfHc, cs);
- if (gr_unfused()) gr_norm(m.R, (const float*) wn->data, EPS, m.xn, m.xn16, T, m.cs);
- else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs);
+ if (gr_unfused()) gr_norm(m.R, (const float*) wn->data, EPS, m.xn, m.xn16, T, m.cs, m.xn16_lo);
+ else if (!normed) gr_norm_rs(m.R, (const float*) wn->data, EPS, m.grs, m.xn16, T, m.cs, m.xn16_lo);
normed = false;
- if (!bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err)) return false;
- gr_silu(m.lo, m.lo16, T, m.cs);
- if (!bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err)) return false;
- if (!bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err)) return false;
- if (gr_unfused()) gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h);
- else gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h);
+ if (!bf16_proj(m.gemm, wd, m.xn16, m.lo, T, sd, err, 0, m.xn16_lo)) return false;
+ gr_silu(m.lo, m.lo16, T, m.cs, m.lo16_lo);
+ if (!bf16_proj(m.gemm, wu, m.lo16, m.gated, T, su, err, 0, m.lo16_lo)) return false;
+ if (!bf16_proj(m.gemm, wi, m.xn16, m.inj, T, si, err, 0, m.xn16_lo)) return false;
+ if (gr_unfused()) gr_mix(m.xn, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h, m.mixed_bf_lo);
+ else gr_mix_r(m.R, m.grs, (const float*) wn->data, m.gated, m.mixed, m.mixed_bf, T, m.cs, m.mixed_h,
+ m.mixed_bf_lo);
if (half == 0 && !core::is_qsa_layer(g, l)) {
// ======================= GDN =======================
@@ -1574,8 +1618,8 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
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;
- if (!bf16_proj(m.gemm, wa, m.mixed_bf, m.ab, T, v.name("ssm_alpha.weight"), err, 2 * HV)) return false;
- if (!bf16_proj(m.gemm, wb, m.mixed_bf, m.ab + HV, T, v.name("ssm_beta.weight"), err, 2 * HV)) return false;
+ if (!bf16_proj(m.gemm, wa, m.mixed_bf, m.ab, T, v.name("ssm_alpha.weight"), err, 2 * HV, m.mixed_bf_lo)) return false;
+ if (!bf16_proj(m.gemm, wb, m.mixed_bf, m.ab + HV, T, v.name("ssm_beta.weight"), err, 2 * HV, m.mixed_bf_lo)) return false;
pt.mark(kPfGdnConv, cs); // "gdn" is the projections in; the rest on their own lines
gdn_gates(m.ab, (const float*) wdt->data, (const float*) wsa->data, m.gate, m.beta, T, m.cs);
gdn_conv(conv, m.qkv, (const float*) wc->data, m.hbuf, T, EPS, m.cs);
@@ -1599,8 +1643,8 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
if (!native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false;
if (!native_proj(m.gemm, wv, m.mixed_h, m.Vc, T, v.name("attn_v.weight"), err)) return false;
if (!native_proj(m.gemm, wq, m.mixed_h, m.Qf, T, v.name("attn_q.weight"), err)) return false;
- 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;
+ if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err, 0, m.mixed_bf_lo)) return false;
+ if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err, 0, m.mixed_bf_lo)) 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, 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
@@ -1620,20 +1664,23 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
staged ? &m.stage : nullptr);
strata::kernels::kv_append_q4(st.v_q4, st.v_q4, st.page_table, p0, T, m.Vc, m.Vc, s, m.cs,
nullptr, staged ? &m.stage : nullptr);
- } else if (st.kv_q4) { // Q4_0 KV (kv_q4.hpp): rotated K and V, the queries below too, the output back
- strata::kernels::fwht256_inplace_cuda(m.Kc, T * 2, m.cs);
- strata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, m.cs);
- strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, p0, T, m.Kc, m.Vc, s, m.cs,
- &st.host, staged ? &m.stage : nullptr);
} else {
- kv_append(m.Kc, m.Vc, T, p0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool,
- st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, m.cs,
- &st.host, staged ? &m.stage : nullptr);
+ if (st.kv_rot) { // rotated K and V (kv_q4.hpp), the queries below too, the output back
+ strata::kernels::fwht256_inplace_cuda(m.Kc, T * 2, m.cs);
+ strata::kernels::fwht256_inplace_cuda(m.Vc, T * 2, m.cs);
+ }
+ if (st.kv_q4)
+ strata::kernels::kv_append_q4(st.k_q4, st.v_q4, st.page_table, p0, T, m.Kc, m.Vc, s, m.cs,
+ &st.host, staged ? &m.stage : nullptr);
+ else
+ kv_append(m.Kc, m.Vc, T, p0, st.page_table, s.page_size, st.kv_int8 ? nullptr : st.k_pool,
+ st.kv_int8 ? nullptr : st.v_pool, st.k_q, st.v_q, st.k_scale, st.v_scale, m.cs,
+ &st.host, staged ? &m.stage : nullptr);
}
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, strata::kernels::rope_scaling(), m.cs);
- if (st.kv_q4) strata::kernels::fwht256_inplace_cuda(m.q, T * 24, m.cs);
+ if (st.kv_rot) 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, strata::kernels::rope_scaling(), m.cs);
// the indexer appends, token by token; then scores + selection for many queries at once:
@@ -1671,7 +1718,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
strata::kernels::qsa_block_scores(st.idx_pooled, st.idx_dead, m.q_idx + t0 * 512, steps0, nb,
m.max_blocks, s, m.sel_scores, m.cs, active);
strata::kernels::qsa_block_topk(m.sel_scores, steps0, nb, m.max_blocks, m.cap, s,
- m.sel_ids + t0 * m.cap, m.cs);
+ m.sel_ids + t0 * m.cap, m.cs, active);
}
// STRATA_SEL_OVERLAP (debug, D-1's question): how much do neighbouring queries' selections share?
// Per tile of 16 queries: the union of their selected cells against the sum of their widths.
@@ -1831,7 +1878,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
m.steps_dev + t0 * strata::kernels::kStepCount, m.cap,
s, m.attn_scratch, m.attn + t0 * ZV, nb, m.cs);
}
- if (st.kv_q4 || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * 24, m.cs);
+ if (st.kv_rot || st.kv_hybrid) strata::kernels::fwht256_inplace_cuda(m.attn, T * 24, m.cs);
pt.mark(kPfQsa, cs);
gate_attn(m.attn, m.Qf, m.attn_h, T, m.cs);
if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err)) return false;
@@ -1845,7 +1892,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
*wsd = need(v, "ffn_down_shexp.weight", err);
if (!wr || !wgi || !wsg || !wsu || !wsd) return false;
pt.mark(kPfRouter, cs);
- if (!bf16_proj(m.gemm, wr, m.mixed_bf, m.logits, T, v.name("ffn_gate_inp.weight"), err)) return false;
+ if (!bf16_proj(m.gemm, wr, m.mixed_bf, m.logits, T, v.name("ffn_gate_inp.weight"), err, 0, m.mixed_bf_lo)) return false;
route(m.logits, m.ids, m.w, T, m.g->n_expert, m.cs);
// the shared expert and its scalar gate
if (!native_proj(m.gemm, wsg, m.mixed_h, m.sgate, T, v.name("ffn_gate_shexp.weight"), err)) return false;
@@ -1854,6 +1901,7 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
if (!native_proj(m.gemm, wsd, m.sh_h, m.shared, T, v.name("ffn_down_shexp.weight"), err)) return false;
if (wgi->kind != core::WeightKind::Bf16InF32) { err = "prefill: shared gate is not BF16"; return false; }
m.gemm.bf16(m.mixed_bf, (const uint16_t*) wgi->data, m.sg, T, 1, N);
+ if (m.mixed_bf_lo) m.gemm.bf16(m.mixed_bf_lo, (const uint16_t*) wgi->data, m.sg, T, 1, N, 0, 1.0f);
// group the (token, k) pairs by expert on the host
pt.mark(kPfHostGroup, cs);
// (the sync below also orders this layer's writes of slot/src/bounds after the previous
@@ -2222,7 +2270,8 @@ bool Prefill::run(const int64_t *tokens, int64_t n, int64_t pos0,
if (!wnn) return false;
}
if (wnn) {
- gr_write_norm_rs(m.R, m.bo, m.inj, HC, (const float*) wnn->data, EPS, m.grs, m.xn16, T, m.cs);
+ gr_write_norm_rs(m.R, m.bo, m.inj, HC, (const float*) wnn->data, EPS, m.grs, m.xn16, T, m.cs,
+ m.xn16_lo);
normed = true;
} else {
gr_write(m.R, m.bo, m.inj, HC, T, m.cs);
diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp
index 18881b90b..926e1d1a0 100644
--- a/sycl/src/program/generate.cpp
+++ b/sycl/src/program/generate.cpp
@@ -22,6 +22,7 @@
#include "strata/core/expert_cache.hpp"
#include "strata/core/conversation_snapshot.hpp"
#include "strata/core/conversation_memory.hpp"
+#include "strata/core/coupled_draft.hpp"
#include "strata/core/expert_source.hpp"
#include "strata/core/gguf_expert_source.hpp"
#include "strata/kernels/resident_plan_mirror.hpp"
@@ -61,6 +62,8 @@
#include "strata/spec/suffix_drafter.hpp"
#include "strata/kernels/cvec.hpp"
#include "strata/core/progress.hpp"
+#include "strata/core/device.hpp"
+#include "strata/core/emulate.hpp"
#ifndef NOMINMAX
#define NOMINMAX // gguf_reader.hpp includes windows.h
#endif
@@ -231,6 +234,8 @@ struct Options {
/// 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.
std::string native_preset;
+ /// The token embedding from this GGUF instead of --native's (tools/embd_bf16_pack.py: BF16 as shipped)
+ std::string embd_gguf;
/// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM.
std::string ple_io = "direct";
int64_t ple_row_cache = 1 << 20; ///< bounded row cache (rows of 90 B); 0 disables
@@ -269,10 +274,13 @@ struct Options {
bool graph_only = false;
bool gpu_only_full = false; ///< R0.3: pre + post + head, the true per-token GPU floor
int pool_workers = 0; ///< R2.2: 0 = "all physical cores minus the host's"; >0 overrides
+ /// #272: the pool's core layout; `all` (the default) is the layout it always had, auto / p-cores are opt-in
+ strata::kernels::cpu::PoolAffinity pool_affinity = strata::kernels::cpu::PoolAffinity::All;
/// R2.2's first half, as an A/B arm. **ON by default**, because the measurement that justifies it is the
/// pool's own drain: 33.7 GB/s against 5/6 x 44.14 = 36.8 for five workers, on a machine whose sixth core
/// is reserved for a host thread that has nothing to do while the drain runs.
bool no_host_worker = false;
+ bool coupled_draft = strata::core::coupled_draft_env(); ///< Coupled draft sampling for MTP drafter under sampling
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
@@ -337,6 +345,9 @@ struct Options {
/// `--prefill auto`: the largest chunk (up to 8192) whose buffers the expert cache can lend. Every expert a chunk
/// routes to is streamed once per chunk, so a bigger chunk streams fewer bytes per token (the "ubatch" effect).
bool prefill_auto = false;
+ /// #282, opt-in: the largest chunk `--prefill auto` may take - 8192 by default; `--prefill auto:16384` or
+ /// `auto:32768` (or STRATA_PREFILL_AUTO_MAX) lets it go further, never past the context
+ int64_t prefill_auto_max = 8192;
bool no_split_rows = false; ///< plan v0.3 P4 A/B: one whole expert per pool thread
/// Plan v0.3 P5: the prompt path borrows the top expert-cache slots for its buffers and refills them after
/// the prompt (default); `--no-prefill-borrow` reserves the buffers' VRAM for the whole session instead.
@@ -468,6 +479,8 @@ void usage() {
" indexer, RoPE, PLE postops, and the CPU q8_0 contract unless the\n"
" expert cache is on. Individual --native-* flags stay for A/B.\n"
" --native-head-gguf PATH native Q5_K head from model shard 1; requires --stream-token\n"
+ " --embd-gguf PATH the token embedding from this GGUF instead of --native's (tools/embd_bf16_pack.py:\n"
+ " BF16 as the checkpoint ships it; mapped host memory, no VRAM)\n"
" --native-dense-gguf PATH native GDN/QSA/shared projections; repeat for each source model shard\n"
" --expert-cache-cpu-order experimental GPU expert reduction matching CPU order\n"
" --max-new N tokens to generate (default 16)\n"
@@ -516,7 +529,8 @@ void usage() {
" --no-token-graph A/B: two graphs per layer (the host launches each) instead of one per token\n"
" --no-fused-gr A/B: the six-kernel hyper-connection read and a separate write (native)\n"
" --prefill CHUNK batched prompt processing in chunks of CHUNK tokens (needs --native); auto =\n"
- " the largest chunk up to 8192 whose buffers the expert cache can lend\n"
+ " the largest chunk up to 8192 whose buffers the expert cache can lend;\n"
+ " auto:16384 / auto:32768 (or STRATA_PREFILL_AUTO_MAX) allow bigger ones\n"
" --no-pool skip the CPU expert pool (the GPU-only floor)\n"
" --sync-every-layer debug: synchronise after every layer\n"
" --ple-gguf PATH the n-gram/PLE shard. WITHOUT IT LAYER 1's PLE IS SILENTLY SKIPPED,\n"
@@ -557,8 +571,14 @@ void usage() {
" pool is six threads on six cores instead of five plus an idle core;\n"
" this flag restores the five-worker form for comparison on `pool phases`.\n"
" --pool-workers N R2.2: CPU expert pool worker count. Default 0 = every physical core\n"
- " except the one the host loop spins on. A sweep is how the pool's\n"
+ " except the one the host loop spins on (with --pool-affinity auto or\n"
+ " p-cores on a hybrid CPU: P-cores minus 1). A sweep is how the pool's\n"
" deviation from `cpu_s2` is attributed.\n"
+ " --pool-affinity MODE Worker CPU affinity: all (default: one worker per physical core, as\n"
+ " always), auto (hybrid CPUs: P-cores first, then their SMT siblings,\n"
+ " then E-cores) or p-cores (P-cores and their siblings only).\n"
+ " --coupled-draft enable coupled draft sampling for MTP drafter under sampling (STRATA_SPEC_COUPLED)\n"
+ " --no-coupled-draft disable coupled draft sampling (propose argmax drafts)\n"
" --mmap-experts R2.1: opt OUT of the resident expert arena, back to MapViewOfFile.\n"
" --stream-experts no host arena: experts read from the GGUF on demand (needs a native pack and\n"
" a VRAM cache that holds every expert; for machines with less RAM than experts)\n"
@@ -1114,6 +1134,7 @@ int main(int argc, char **argv) try {
else if (a == "--cpu-oracle-q8-0") o.cpu_oracle_q8_0 = true;
else if (a == "--native") o.native_preset = next("--native");
else if (a == "--native-head-gguf") o.native_head_gguf = next("--native-head-gguf");
+ else if (a == "--embd-gguf") o.embd_gguf = next("--embd-gguf");
else if (a == "--native-dense-gguf") o.native_dense_gguf.push_back(next("--native-dense-gguf"));
else if (a == "--no-capture") o.no_capture = true;
else if (a == "--no-pool") o.no_pool = true;
@@ -1122,8 +1143,20 @@ int main(int argc, char **argv) try {
else if (a == "--graph-only") o.graph_only = true;
else if (a == "--gpu-only-full") o.gpu_only_full = true;
else if (a == "--pool-workers") o.pool_workers = std::atoi(next("--pool-workers"));
+ else if (a == "--pool-affinity") {
+ const std::string v = next("--pool-affinity");
+ if (v == "auto") o.pool_affinity = strata::kernels::cpu::PoolAffinity::Auto;
+ else if (v == "p-cores" || v == "pcores") o.pool_affinity = strata::kernels::cpu::PoolAffinity::PCores;
+ else if (v == "all") o.pool_affinity = strata::kernels::cpu::PoolAffinity::All;
+ else {
+ std::fprintf(stderr, "strata generate: unknown --pool-affinity value '%s' (expected auto, p-cores, or all)\n", v.c_str());
+ return 2;
+ }
+ }
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 == "--coupled-draft") o.coupled_draft = true;
+ else if (a == "--no-coupled-draft") o.coupled_draft = false;
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.
@@ -1140,8 +1173,13 @@ int main(int argc, char **argv) try {
else if (a == "--vram-reserve-mib") o.vram_reserve_mib = std::atoi(next("--vram-reserve-mib"));
else if (a == "--prefill") {
const std::string v = next("--prefill");
- o.prefill_auto = v == "auto";
- o.prefill_chunk = o.prefill_auto ? 8192 : std::atoll(v.c_str());
+ o.prefill_auto = v == "auto" || v.rfind("auto:", 0) == 0;
+ // #282: auto:N (N = 16384 or 32768) or STRATA_PREFILL_AUTO_MAX lets auto take chunks above 8192
+ const char* env_max = std::getenv("STRATA_PREFILL_AUTO_MAX");
+ const long long want_max = v.rfind("auto:", 0) == 0 ? std::atoll(v.c_str() + 5)
+ : (o.prefill_auto && env_max != nullptr ? std::atoll(env_max) : 8192);
+ o.prefill_auto_max = want_max >= 32768 ? 32768 : want_max >= 16384 ? 16384 : 8192;
+ o.prefill_chunk = o.prefill_auto ? o.prefill_auto_max : std::atoll(v.c_str());
}
else if (a == "--no-split-rows") o.no_split_rows = true;
else if (a == "--no-prefill-borrow") { o.no_prefill_borrow = true; borrow_explicit = true; }
@@ -1272,6 +1310,7 @@ int main(int argc, char **argv) try {
}
}
}
+ strata::core::set_coupled_draft(o.coupled_draft);
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");
@@ -1334,6 +1373,7 @@ int main(int argc, char **argv) try {
}
}
bool multi_gpu = !split_devs.empty() && !split_same; // cleared by --split-skip-if-fits before any stage loads
+ bool split_own_auto = false; // #340: the split keeps own prompt buffers by its rule (not --no-prefill-borrow)
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;
@@ -1365,6 +1405,59 @@ int main(int argc, char **argv) try {
// 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.
+ // #340 - BUT A LOAN IS NOT FREE PER REQUEST: every stage streams the lent experts during the prompt and
+ // copies them back after it, so on cards that hold (nearly) every expert of their layers a 2K prompt read
+ // 37% slower than 0.1.29's own buffers (2x RX 9070 XT / R9700: 1570 -> 990 tok/s; 2x A5000 in #340: -35%).
+ // So a split keeps 0.1.29's own buffers (2048-token chunks, priced into the split search) when they are a
+ // small part of every card - at most 12% of its VRAM (16 GB and larger cards) - and borrows on smaller cards,
+ // where the reserve would cost the cache (and the context) the paragraph above is about. Measured with own
+ // buffers on the 9070 XT + R9700: 2K 1588 tok/s, 16K 2006 (0.1.29 1568 / 1935, 0.1.31 993 / 1852).
+ // OPT-IN (the owner's choice for 0.1.32): own buffers change which experts a full card keeps resident, so the
+ // split's output differs from 0.1.31's; the default borrows as 0.1.31 did - with the concurrent refill and the
+ // 96-blob split ring that alone gave 2K +27%, 16K +5% over 0.1.31, decode unchanged, output identical.
+ // STRATA_SPLIT_OWN=auto: the 12% rule above; 1: own buffers on any cards; unset/0: borrow.
+ // --split-skip-if-fits keeps the loans (it can fall back to one GPU, which must stay as it is).
+ const char* own_env = std::getenv("STRATA_SPLIT_OWN");
+ if (!o.no_prefill_borrow && !o.split_skip_if_fits && own_env != nullptr && own_env[0] != '0') {
+ const char* v = std::string(own_env) == "auto" ? nullptr : own_env;
+ bool own = v ? v[0] == '1' : true;
+ // the buffers of a 2048-token chunk (or the --prefill one) + a 96-blob ring (as split_pf_mib prices them)
+ const int64_t own_chunk = o.prefill_auto || o.prefill_chunk <= 0 ? 2048 : o.prefill_chunk;
+ const int64_t reserve_mib = 160 + (own_chunk * 680) / 1024 + 96 * 4;
+ std::string why;
+ if (!v) {
+ std::vector<int> devs = {0};
+ for (const int d : split_devs) devs.push_back(d);
+ for (const int d : devs) {
+ dpct::device_info prop{};
+ /*
+ DPCT1026: The call to cudaGetLastError was removed
+ because this functionality is redundant in SYCL.
+ */
+ if (DPCT_CHECK_ERROR(
+ dpct::get_device(d).get_device_info(prop)) != 0) {
+ ; own = false; break;
+ }
+ const int64_t total_mib =
+ (int64_t)(prop.get_global_mem_size() >> 20);
+ if (reserve_mib * 100 > 12 * total_mib) {
+ own = false;
+ why = "CUDA" + std::to_string(d) + " has " + std::to_string(total_mib) + " MiB";
+ break;
+ }
+ }
+ }
+ if (own) {
+ o.no_prefill_borrow = true;
+ split_own_auto = true;
+ std::fprintf(stderr, "strata generate: layer split: every stage keeps its own prompt buffers (~%lld MiB "
+ "each, %lld-token chunks)%s\n", (long long) reserve_mib, (long long) own_chunk,
+ v ? " (STRATA_SPLIT_OWN=1)" : "");
+ } else if (!why.empty()) {
+ std::fprintf(stderr, "strata generate: layer split: the prompt paths borrow from the caches (%s)\n",
+ why.c_str());
+ }
+ }
int n_vis = 1;
if (DPCT_CHECK_ERROR(n_vis = dpct::device_count()) != 0 || n_vis < 1)
n_vis = 1;
@@ -1448,6 +1541,12 @@ int main(int argc, char **argv) try {
}
strata::core::qsa_set_kv_int8(o.kv == "int8");
strata::core::qsa_set_kv_q4(o.kv == "q4_0"); // PR #21: 4-bit codes after a Hadamard rotation (kv_q4.hpp)
+ // STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation --kv q4_0 already uses. Opt-in: first-token KL to
+ // fp16 K/V improved on an NVFP4 pack (0.0066 -> 0.0051) but not on IQ2_XS (0.0022 -> 0.0054)
+ const char* kv_rot = std::getenv("STRATA_KV_ROT");
+ strata::core::qsa_set_kv_int8_rotate(kv_rot != nullptr && kv_rot[0] == '1');
+ if (kv_rot != nullptr && kv_rot[0] == '1' && o.kv == "int8")
+ std::fprintf(stderr, "strata generate: STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation (opt-in)\n");
strata::core::qsa_set_kv_hybrid(o.kv == "k8v4"); // K8V4: INT8 K + rotated Q4_0 V, 816 B/cell
if (o.kv_resident < 0) {
std::fprintf(stderr, "strata generate: --kv-resident must be >= 0\n");
@@ -1497,7 +1596,14 @@ int main(int argc, char **argv) try {
// 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 = o.native_shards;
- if (std::find(o.native_dense_gguf.begin(), o.native_dense_gguf.end(), o.ple_gguf) == o.native_dense_gguf.end())
+ // a PLE-only table (tools/ple_fp8_pack.py: architecture strata-ple) holds no projections
+ bool ple_only = false;
+ try {
+ strata::GgufFile pg(o.ple_gguf);
+ if (const strata::MetaValue* v = pg.get("general.architecture")) ple_only = v->s == "strata-ple";
+ } catch (const std::exception&) {}
+ if (!ple_only &&
+ 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);
}
// Plan v0.3 (24 Sep): the CPU experts stay on the VNNI kernel. The llama.cpp-CPU-exact q8_0 contract
@@ -1816,15 +1922,16 @@ int main(int argc, char **argv) try {
return 2;
}
const strata::core::ModelGeometry g0;
- if (!native_embed.load(o.native_shards, g0.n_embd, 248320, err)) {
+ if (!native_embed.load(o.embd_gguf.empty() ? o.native_shards : std::vector<std::string>{o.embd_gguf}, g0.n_embd,
+ 248320, err)) {
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
return 1;
}
strata::core::set_native_embed(&native_embed);
std::fprintf(stderr, "strata generate: native pack: %s experts (largest blob %.2f MB), token embedding "
- "type %d in mapped host memory (%.0f MiB)\n",
+ "%s in mapped host memory (%.0f MiB)\n",
o.pack.c_str(), (double) strata::kernels::cpu::expert_layout().max_blob / 1e6,
- native_embed.type(), (double) native_embed.bytes() / 1048576.0);
+ strata::ggml_type_name((uint32_t) native_embed.type()), (double) native_embed.bytes() / 1048576.0);
}
// Plan v0.3 P1: tensors served in native form are not also loaded in canonical form (~2.7 GB of VRAM back
// to the expert cache with --native). `--keep-canonical` loads both, as before.
@@ -1838,6 +1945,11 @@ int main(int argc, char **argv) try {
if (!o.native_head_gguf.empty()) skip.insert("output.weight");
// the PLE module validates its canonical key at construction (8 MB); a native pack has none to load
if (!native_pack) skip.erase("blk.1.ple_key.weight");
+ // #326: a --compat-bf16 pack (OrcaRouter IQ3_XXS) keeps its BF16 key in the arena
+ if (native_pack && !strata::core::NativeDense::keep_unquantized_ple_key(o.pack, skip, err)) {
+ std::fprintf(stderr, "strata generate: %s\n", err.c_str());
+ return 1;
+ }
if (native_pack) skip.insert("token_embd.weight");
}
uint64_t pool_bytes = 0;
@@ -2009,6 +2121,17 @@ int main(int argc, char **argv) try {
pio.max_inflight = (uint32_t) o.ple_inflight;
pio.cache_rows = (uint64_t) o.ple_row_cache;
pio.io_thread = !o.ple_sync_submit;
+ // Keep the SSD awake while rows are being asked for (PleReader::set_keepalive): some SSDs stall the first
+ // reads 50-150 ms after ~250 ms without a command. STRATA_SSD_KEEPALIVE = ms without a read before one
+ // page is read anyway (default 100, 0 = off), STRATA_SSD_KEEPALIVE_WINDOW = seconds after the last row
+ // request that this goes on (default 60; then the SSD may sleep until the next request).
+ {
+ const char* ka = std::getenv("STRATA_SSD_KEEPALIVE");
+ const char* kw = std::getenv("STRATA_SSD_KEEPALIVE_WINDOW");
+ pio.keepalive_ms = ka != nullptr && *ka ? std::clamp(std::atof(ka), 0.0, 10000.0) : 100.0;
+ pio.keepalive_window_s = kw != nullptr && *kw ? std::clamp(std::atof(kw), 1.0, 86400.0) : 60.0;
+ if (pio.mode != strata::kernels::PleIo::Direct || !pio.io_thread) pio.keepalive_ms = 0;
+ }
if (!ple_table.open(o.ple_gguf, err, pio)) {
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
return 1;
@@ -2017,6 +2140,12 @@ int main(int argc, char **argv) try {
std::fprintf(stderr, "strata generate: PLE table %s (--ple-io ram) in %.1f s\n",
ple_table.locked() ? "locked in RAM" : "loaded (not locked)",
std::chrono::duration<double>(Clock::now() - tpl).count());
+ if (pio.keepalive_ms > 0)
+ std::fprintf(stderr, "strata generate: the SSD is kept awake while rows are read: one page of the table after "
+ "%.0f ms without a read, until %.0f s after the last request "
+ "(STRATA_SSD_KEEPALIVE=0 turns it off)\n", pio.keepalive_ms, pio.keepalive_window_s);
+ else if (pio.mode == strata::kernels::PleIo::Direct)
+ std::fprintf(stderr, "strata generate: SSD keep-alive off: the SSD may fall asleep between reads\n");
const strata::core::WeightRef* wk = wt.find("blk.1.ple_key.weight");
const strata::core::WeightRef* wv = wt.find("blk.1.ple_value.weight");
const strata::core::WeightRef* wnk = wt.find("blk.1.ple_norm_key.weight");
@@ -2166,6 +2295,7 @@ int main(int argc, char **argv) try {
}
}
}
+ strata::core::Verifier::set_commit_async(!multi_gpu); // see Verifier::set_commit_async
// ---- 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;
@@ -2294,7 +2424,16 @@ int main(int argc, char **argv) try {
// 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;
+ // (#340: the estimate predates the streamed ring: from 1024-token chunks the prompt path also holds a ring of
+ // whole expert blobs, which a split without borrowing sizes at 96 (Prefill::set_ring_override below) and books
+ // here - without it a `--no-prefill-borrow` split filled the cards and the draft head no longer fit)
+ const int64_t split_ring_mib =
+ (multi_gpu && !pf_borrow && o.prefill_chunk >= 1024)
+ ? (int64_t) ((96ull * (uint64_t) strata::kernels::cpu::expert_layout().max_blob + (1ull << 20) - 1) >> 20)
+ : 0;
+ if (split_ring_mib > 0) strata::prefill::Prefill::set_ring_override(96);
+ const int64_t split_pf_mib =
+ (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 + split_ring_mib : 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
@@ -2304,7 +2443,17 @@ int main(int argc, char **argv) try {
// 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 {
+ // #340: with the own prompt buffers chosen by the split's rule (not asked for with --no-prefill-borrow) the
+ // boundary is searched as the borrowing configuration would (no reserve): the reserve then only makes the caches
+ // smaller, which measured cost no decode (K=28 on 9070 XT + R9700: 58.4 tok/s own vs 58.5 borrowing), while a
+ // search with the reserve moved the boundary to K=32 and decode to 54.8. STRATA_SPLIT_OWN_PLACE=reserve: the
+ // search sees the reserve.
+ static const bool place_with_reserve = [] {
+ const char* v = std::getenv("STRATA_SPLIT_OWN_PLACE");
+ return v != nullptr && std::string(v) == "reserve";
+ }();
+ auto stage_room = [&](int dev, bool later, bool drafter,
+ bool search = false) -> int64_t {
try {
const strata::core::OnDevice on(dev);
size_t fb = 0, tb = 0;
@@ -2314,7 +2463,8 @@ int main(int argc, char **argv) try {
runtimes. You may need to adjust the code.
*/
- const int64_t reserve = ((int64_t) o.vram_reserve_mib + split_pf_mib + (later ? kWindowMib : 0) +
+ const int64_t pf = search && split_own_auto && !place_with_reserve ? 0 : split_pf_mib;
+ const int64_t reserve = ((int64_t) o.vram_reserve_mib + pf + (later ? kWindowMib : 0) +
(drafter ? kDrafterMib : 0)) << 20;
return std::max<int64_t>((int64_t) fb - reserve, 0);
}
@@ -2331,7 +2481,7 @@ int main(int argc, char **argv) try {
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, i + 1 == ns);
+ cap[(size_t) i] = stage_room(i == 0 ? -1 : dev, i > 0, i + 1 == ns, true);
int sms = 0, khz = 0;
sms = dpct::get_device(dev).get_max_compute_units();
if (DPCT_CHECK_ERROR(
@@ -2571,6 +2721,52 @@ int main(int argc, char **argv) try {
// 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;
+ { // the card, and whether this build has code for it (a binary built for other GPUs fails at its first kernel
+ // otherwise, after the whole expert arena has loaded) - before the arena starts loading
+ int dev = 0;
+ dpct::device_info p{};
+ const bool named =
+ DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()) == 0 &&
+ DPCT_CHECK_ERROR(dpct::get_device(dev).get_device_info(p)) == 0;
+ /*
+ DPCT1010: SYCL uses exceptions to report errors and does not use the
+ error codes. The cudaGetLastError function call was replaced with 0. You
+ need to rewrite this code.
+ */
+ if (!named) 0;
+ const char *name =
+ named && p.get_name()[0] ? p.get_name() : "(an unnamed GPU)";
+#if defined(STRATA_USE_HIP)
+ std::fprintf(stderr, "strata generate: GPU %d: %s (%s)\n", dev, name, named ? p.gcnArchName : "?");
+#else
+ std::fprintf(
+ stderr, "strata generate: GPU %d: %s, compute capability %d.%d%s\n",
+ dev, name,
+ /*
+ DPCT1005: The SYCL device version is different from CUDA Compute
+ Compatibility. You may need to rewrite this code.
+ */
+ strata::cc_major_of(p.get_major_version()),
+ strata::cc_minor_of(p.get_minor_version()),
+ strata::emulated_cc()
+ ? " (STRATA_EMULATE_CC: a test mode, the card is emulated)"
+ : "");
+#endif
+ const std::string e = strata::core::device_code_error();
+ if (!e.empty()) {
+ std::fprintf(
+ stderr,
+ "strata generate: this engine has no code for %s (sm_%d%d): %s "
+ "- rebuild it for this "
+ /*
+ DPCT1005: The SYCL device version is different from CUDA
+ Compute Compatibility. You may need to rewrite this code.
+ */
+ "card (setup does: START-HERE.bat --setup)\n",
+ name, p.get_major_version(), p.get_minor_version(), e.c_str());
+ return 1;
+ }
+ }
strata::core::ArenaExpertSource arena_src;
strata::core::GgufExpertSource gguf_src;
strata::core::ExpertSource* srcp = nullptr;
@@ -2648,7 +2844,13 @@ int main(int argc, char **argv) try {
#endif
srcp = &arena_src;
}
- strata::kernels::cpu::ExpertPool pool(o.pool_workers, /*pin=*/true, /*host_works=*/!o.no_host_worker);
+ strata::kernels::cpu::ExpertPool pool(o.pool_workers, /*pin=*/true, /*host_works=*/!o.no_host_worker, o.pool_affinity);
+ if (pool.is_hybrid() && pool.affinity() != strata::kernels::cpu::PoolAffinity::All) {
+ const char* aff_str = pool.affinity() == strata::kernels::cpu::PoolAffinity::PCores ? "p-cores" :
+ pool.affinity() == strata::kernels::cpu::PoolAffinity::All ? "all" : "auto";
+ std::fprintf(stderr, "strata generate: hybrid CPU detected (%d P-cores / %d threads, %d E-cores), pool workers: %d, affinity: %s\n",
+ pool.p_cores(), pool.p_threads(), pool.e_cores(), pool.workers(), aff_str);
+ }
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
@@ -3931,10 +4133,15 @@ int main(int argc, char **argv) try {
: (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};
+ // 32768 and 16384 (#282, opt-in: --prefill auto:32768): a 32K prompt with IQ2_XS (RTX 5090, 64K context)
+ // read at 5,624 tok/s in 8192-token chunks and 6,465 in one 32768 chunk (40K -> 18K experts streamed; an
+ // NVFP4 pack at 262K: 3,535 -> 5,201)
+ static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256};
auto slots_for = lend_slots;
if (o.prefill_auto) {
for (const int64_t c : kAutoChunks) {
+ // above 8192: only when asked for, and only when a prompt of the context can use it
+ if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue;
const int64_t k = slots_for(c);
if (k + 128 <= xcache.slots() && k * 100 <= kAutoLendPct * xcache.slots()) { chunk = c; return k; }
}
@@ -4033,6 +4240,22 @@ int main(int argc, char **argv) try {
: (uint64_t) (xc.slots() - first) *
(uint64_t) strata::kernels::cpu::expert_layout().max_blob;
};
+ // #340: a layer split whose caches already hold most experts streams few of them through the prompt path, so
+ // the 384-slot ring (sized for a card that streams nearly every expert of a chunk) only makes every stage's
+ // loan bigger: 96 slots (0.1.30's ring here) when >= 75% of the (layer, expert) pairs are resident. One GPU
+ // keeps the pinned-share rule. STRATA_SPLIT_RING=N: N slots on a split; 0: the pinned-share rule.
+ if (multi_gpu && !host_res.empty()) {
+ int64_t res_n = 0;
+ for (const int32_t r : host_res) res_n += r >= 0;
+ const double res_share = (double) res_n / (double) host_res.size();
+ const char* v = std::getenv("STRATA_SPLIT_RING");
+ const int ring = v ? std::atoi(v) : (res_share >= 0.75 ? 96 : 0);
+ if (ring > 0) {
+ strata::prefill::Prefill::set_ring_override(ring);
+ std::fprintf(stderr, "strata serve: layer split: %.0f%% of the experts resident, the prompt path's "
+ "streamed ring %d slots\n", 100.0 * res_share, ring);
+ }
+ }
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
@@ -4053,11 +4276,13 @@ int main(int argc, char **argv) try {
}
return true;
};
- static constexpr int64_t kAutoChunks[] = {8192, 6144, 4096, 3072, 2048, 1024, 512, 256};
+ static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256};
int64_t chunk = 0;
if (o.prefill_auto) {
- for (const int64_t c : kAutoChunks)
+ for (const int64_t c : kAutoChunks) {
+ if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue; // #282, as plan_lend
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; }
@@ -4073,9 +4298,50 @@ int main(int argc, char **argv) try {
p.first = (int32_t) (p.cache->slots() - part_slots(p, chunk));
p.first_now = p.first;
}
+ // #340: a split stage whose card still has room for the chunk's buffers (its cache already holds
+ // every expert of its layers, so auto stopped short of its VRAM) keeps them as its own instead of
+ // borrowing cache slots: nothing of it is lent, streamed during the prompt or refilled after it.
+ // Room = the buffers + 1.5 GiB (the verify windows, the draft head, hipBLAS/cuBLAS workspaces made
+ // after this). Layer splits only - one GPU keeps its loan exactly as before.
+ // STRATA_SPLIT_OWN_BUFFERS=0: every stage borrows (0.1.30/0.1.31).
+ static const bool own_ok = [] {
+ const char* v = std::getenv("STRATA_SPLIT_OWN_BUFFERS");
+ return v == nullptr || v[0] != '0';
+ }();
+ if (pf_parts.size() > 1 && own_ok) {
+ for (PfPart& p : pf_parts) {
+ const strata::core::OnDevice on(p.dev);
+ size_t fb = 0, tb = 0;
+ /*
+ DPCT1010: SYCL uses exceptions to report errors and
+ does not use the error codes. The cudaGetLastError
+ function call was replaced with 0. You need to rewrite
+ this code.
+ */
+ /*
+ 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.
+ */
+ if (DPCT_CHECK_ERROR(
+ dpct::get_current_device().get_memory_info(
+ fb, tb)) != 0) {
+ (void)0; continue;
+ }
+ const uint64_t need = strata::prefill::Prefill::bytes_needed(g, *p.ses, chunk);
+ if ((uint64_t) fb >= need + (3ull << 29)) {
+ std::fprintf(stderr, "strata serve: CUDA%d keeps its own prompt buffers (%.2f GiB of "
+ "%.2f GiB free): no loan\n", p.dev < 0 ? 0 : p.dev,
+ (double) need / 1073741824.0, (double) fb / 1073741824.0);
+ p.first = -1;
+ p.first_now = -1;
+ }
+ }
+ }
lend_first = pf_parts[0].first;
- borrow = xcache.device_slot(lend_first);
- borrow_bytes = part_bytes(pf_parts[0], lend_first);
+ borrow = lend_first >= 0 ? xcache.device_slot(lend_first) : nullptr;
+ borrow_bytes = lend_first >= 0 ? part_bytes(pf_parts[0], lend_first) : 0;
} else if (o.prefill_auto) {
o.prefill_chunk = 1024; // nothing lendable: small buffers of its own
} else if (pf_parts.size() > 1) {
@@ -4094,11 +4360,14 @@ int main(int argc, char **argv) try {
} 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 CUDA0 cache slots (%.2f GiB)\n",
- (long long) (xcache.slots() - lend_first), (double) borrow_bytes / 1073741824.0);
+ bool any_loan = borrow != nullptr;
+ for (size_t i = 1; i < pf_parts.size(); ++i) any_loan = any_loan || pf_parts[i].first >= 0;
+ if (any_loan) {
+ 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);
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",
+ if (pf_parts[i].first >= 0) 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);
@@ -4214,15 +4483,15 @@ int main(int argc, char **argv) try {
*/
(void)0;
o.prefill_chunk = next;
- if (borrow != nullptr) { // smaller loans for the smaller chunk
+ if (any_loan) { // 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);
+ borrow = lend_first >= 0 ? xcache.device_slot(lend_first) : nullptr;
+ borrow_bytes = lend_first >= 0 ? part_bytes(pf_parts[0], lend_first) : 0;
}
err.clear();
continue;
@@ -4235,6 +4504,55 @@ int main(int argc, char **argv) try {
return 1;
}
mem_mark("the head and the prompt path");
+ // #340: STRATA_SPLIT_SMALL_OWN=S (tokens): on a layer split, every stage that borrows keeps the slots for an
+ // S-token chunk's buffers for the whole session (0.1.29's own buffers, carved from the tail of its cache):
+ // a request of at most S prompt tokens then lends, streams and refills nothing, a longer one lends (and
+ // refills) only the slots above them. Their experts stay non-resident (the CPU / PCIe path computes them).
+ // STRATA_SPLIT_SMALL_MAX=M: a request of at most M prompt tokens reads in S-token chunks on those stages
+ // (several chunks, still nothing lent) instead of borrowing for a bigger one.
+ int64_t split_small = 0, split_small_max = 0;
+ if (multi_gpu && !pf_parts.empty() && !host_res.empty()) {
+ const char* v = std::getenv("STRATA_SPLIT_SMALL_OWN");
+ const int64_t S = v ? request_chunk(std::atoll(v), o.prefill_chunk) : 0;
+ const char* vm = std::getenv("STRATA_SPLIT_SMALL_MAX");
+ split_small = S;
+ split_small_max = S > 0 ? std::max<int64_t>(S, vm ? std::atoll(vm) : S) : 0;
+ int64_t evicted = 0;
+ for (PfPart& p : pf_parts) {
+ if (S <= 0 || p.first < 0) continue;
+ const int32_t first_s = std::max<int32_t>(p.first, (int32_t) (p.cache->slots() - part_slots(p, S)));
+ int64_t n = 0;
+ for (int64_t l = p.lb; l < p.le; ++l)
+ for (int64_t ex = 0; ex < g.n_expert; ++ex) {
+ int32_t& r = host_res[(size_t) (l * g.n_expert + ex)];
+ if (r >= first_s) { r = strata::core::kNotResident; ++n; }
+ }
+ evicted += n;
+ std::fprintf(stderr, "strata serve: CUDA%d keeps %lld slots for %lld-token prompts (%lld experts "
+ "no longer resident)\n", p.dev < 0 ? 0 : p.dev,
+ (long long) (p.cache->slots() - first_s), (long long) S, (long long) n);
+ }
+ if (evicted > 0) {
+ if (d_res != nullptr)
+ /*
+ DPCT1114: cudaMemcpy is migrated to asynchronization
+ memcpy, assuming in the original code the source host memory
+ is pageable memory. If the memory is not pageable, call
+ wait() on event return by memcpy API to ensure
+ synchronization behavior.
+ */
+ dpct::get_in_order_queue().memcpy(d_res, host_res.data(),
+ host_res.size() *
+ sizeof(int32_t)).wait();
+ for (auto& st : stages) {
+ const strata::core::OnDevice on(st->dev);
+ dpct::get_in_order_queue()
+ .memcpy(st->d_res, host_res.data(),
+ host_res.size() * sizeof(int32_t))
+ .wait();
+ }
+ }
+ }
// the penalty-history buffer: one row per verify-window row (`penalty_rows`), each the last
// `penalty_last_n` tokens that row's pick follows, -1 padded in front. Allocated once at the cap for
// the widest window; a request without penalties gets a null buffer and takes the byte-for-byte
@@ -4392,11 +4710,17 @@ int main(int argc, char **argv) try {
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;
- }
+ // A park carrying its own retained K/V replaces memory the cache
+ // already held, so capacity is make_room's call - it runs next either
+ // way, and put()'s accounting still bounds the budget. The with-reuse
+ // estimate must stay uncapped: it counts the retained buffers'
+ // capacity and directories, and put() charges that same true size -
+ // a capped figure would under-evict and overfill the budget.
+ // #342: before make_room evicts oldest-first, the copies of this conversation a turn back go (they hold
+ // nothing the outgoing chain does not, apart from the tail this conversation rewrote)
+ if (const size_t dropped = conversations.drop_superseded(live, live_imgs, checks, cvec_cached))
+ std::fprintf(stderr, "strata serve: conversation cache: dropped %zu superseded cop%s of this "
+ "conversation; parked=%zu\n", dropped, dropped == 1 ? "y" : "ies", conversations.size());
if (!conversations.make_room(estimate, held)) {
std::fprintf(stderr, "strata serve: conversation cache: skip parking (snapshot %zu MiB exceeds available budget)\n",
estimate >> 20);
@@ -5077,6 +5401,13 @@ int main(int argc, char **argv) try {
return imgs_below(req_imgs, L) == pre_imgs;
};
const bool want_cvec = strata::kernels::cvec().loaded() ? req_cvec != 0 : true;
+ // the last request's final commit may still be running on the verifier's stream (set_commit_async):
+ // everything below reads, restores or zeroes the session from other streams and the host (the end of the
+ // last request waited already; this covers a request that ended on an error path)
+ if (!ver.wait_commit(err)) {
+ std::printf("ERR %s\n", err.c_str());
+ return 1;
+ }
int64_t resume = 0;
bool from_live = false;
if (o.prompt_cache > 0 && want_cvec == cvec_cached) {
@@ -5268,6 +5599,8 @@ int main(int argc, char **argv) try {
if (!ver.commit(T, e) || !mtp.prefill(ver.final_R_all(), nxt.data(), T, q, e)) return false;
q += T;
}
+ // the batched prompt path (other streams), checkpoints and snapshots may follow: the last commit first
+ if (!ver.wait_commit(e)) return false;
const double ms = std::chrono::duration<double, std::milli>(Clock::now() - pp_t0).count();
std::printf("PP %lld %lld %.0f %.1f\n", (long long) b, (long long) pp_total, ms,
ms > 0.0 ? 1000.0 * (double) (b - pp_from) / ms : 0.0);
@@ -5281,8 +5614,8 @@ int main(int argc, char **argv) try {
// 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;
+ // (split in two halves so a layer split can queue every stage's copies before it waits for any: #340)
+ auto refill_issue = [&](PfPart& p, std::string& e) -> bool {
tr("refill start", (long long) p.lent.size());
const strata::core::OnDevice on(p.dev);
size_t queued = 0;
@@ -5296,16 +5629,44 @@ int main(int argc, char **argv) try {
// SYCL port: drain before GgufExpertSource's 512-buffer blob ring can wrap onto a queued copy
if (!refill_blocking() && ++queued % 256 == 0 && !p.cache->sync_queued(e)) return false;
}
+ return true;
+ };
+ auto refill_wait = [&](PfPart& p, std::string& e) -> bool {
+ const strata::core::OnDevice on(p.dev);
if (!p.cache->sync_queued(e)) return false;
p.lent.clear();
p.lent_chunk = 0;
return true;
};
+ auto refill_one = [&](PfPart& p, std::string& e) -> bool {
+ if (p.lent.empty()) return true;
+ return refill_issue(p, e) && refill_wait(p, e);
+ };
+ // #340: with several stages every stage's copies go out first (each card on its own link), then each is
+ // waited for - the same copies into the same slots, so the same cache; one stage: refill_one exactly.
+ // STRATA_REFILL_SERIAL=1: stage after stage, as 0.1.30/0.1.31.
+ static const bool refill_serial = std::getenv("STRATA_REFILL_SERIAL") != nullptr;
auto refill = [&](std::string& e) -> bool {
- bool any = false;
+ const auto t_rf = Clock::now();
+ int64_t n_lent = 0, n_parts = 0;
for (PfPart& p : pf_parts)
- if (!p.lent.empty()) { any = true; if (!refill_one(p, e)) return false; }
- if (any) res_upload();
+ if (!p.lent.empty()) { n_lent += (int64_t) p.lent.size(); ++n_parts; }
+ if (n_parts > 1 && !refill_serial) {
+ for (PfPart& p : pf_parts)
+ if (!p.lent.empty() && !refill_issue(p, e)) return false;
+ for (PfPart& p : pf_parts)
+ if (!p.lent.empty() && !refill_wait(p, e)) return false;
+ } else {
+ for (PfPart& p : pf_parts)
+ if (!p.lent.empty() && !refill_one(p, e)) return false;
+ }
+ if (n_parts > 0) res_upload();
+ if (trace && n_parts > 0) {
+ std::fprintf(stderr, "strata trace: refilled %lld slots on %lld stage(s) in %.1f ms\n",
+ (long long) n_lent, (long long) n_parts,
+ std::chrono::duration<double, std::milli>(Clock::now() - t_rf).count());
+ std::fflush(stderr);
+ }
return true;
};
// lend the slots `tokens` batched prompt tokens need: the prompt path's buffers for min(chunk, tokens
@@ -5313,9 +5674,13 @@ int main(int argc, char **argv) try {
// 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
+ const auto t_ln = Clock::now();
// 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);
+ const int64_t want_full = request_chunk(tokens, o.prefill_chunk);
+ // #340: a short enough request reads in the stages' own S-token chunks (nothing lent)
+ const int64_t want = split_small > 0 && tokens <= split_small_max ? std::min(want_full, split_small)
+ : want_full;
if (want <= 0) {
e = "prefill: cannot lend buffers for an empty request segment";
return false;
@@ -5348,6 +5713,13 @@ int main(int argc, char **argv) try {
p.lent_chunk = want;
}
if (any) res_upload();
+ if (trace) {
+ int64_t n_lent = 0;
+ for (const PfPart& p : pf_parts) n_lent += (int64_t) p.lent.size();
+ std::fprintf(stderr, "strata trace: lent %lld slots for %lld tokens in %.1f ms\n", (long long) n_lent,
+ (long long) want, std::chrono::duration<double, std::milli>(Clock::now() - t_ln).count());
+ std::fflush(stderr);
+ }
return true;
};
apply_pending(true);
@@ -5598,6 +5970,11 @@ int main(int argc, char **argv) try {
p += a + 1;
}
const double decode_ms = std::chrono::duration<double, std::milli>(Clock::now() - d0).count();
+ // the last commit (set_commit_async): the session is complete before anything reads or copies it
+ if (!ver.wait_commit(err)) {
+ std::printf("ERR %s\n", err.c_str());
+ return 1;
+ }
if (dec_timing && dec_windows > 0) {
const DecSnap d1 = dec_snap();
const double w = (double) dec_windows, L = (double) g.n_layers;
@@ -6472,6 +6849,16 @@ int main(int argc, char **argv) try {
if (first_window) {
first_window = false;
ttft_ms = std::chrono::duration<double, std::milli>(Clock::now() - t_start).count();
+ // Diagnostics: the first window runs the prompt's last token over the state the prompt path left
+ // (keys, values, recurrent state), so its logits carry whatever that path did. A native pack never
+ // runs the per-token loop --dump-logits reads; this is where prompt paths can be compared by output.
+ if (const char* fl = std::getenv("STRATA_DUMP_FIRST_LOGITS")) {
+ std::vector<float> row((size_t) ver.vocab());
+ std::FILE* f = ver.copy_logits(0, row.data()) ? std::fopen(fl, "wb") : nullptr;
+ if (f == nullptr || std::fwrite(row.data(), sizeof(float), row.size(), f) != row.size())
+ std::fprintf(stderr, "strata generate: STRATA_DUMP_FIRST_LOGITS: cannot write %s\n", fl);
+ if (f) std::fclose(f);
+ }
}
// plan v0.3 P6: the adaptive tier's host work (ranking, copy submission) runs on its own thread while the
// GPU commits and drafts; it touches only the residency tables, which nothing reads until the next window
@@ -6521,6 +6908,11 @@ int main(int argc, char **argv) try {
std::fprintf(stderr, "strata generate: position %lld, %lld tokens, %lld rounds\n", (long long) p,
(long long) produced.size(), (long long) rounds);
}
+ // the last commit (set_commit_async) before anything reads the session again
+ if (!ver.wait_commit(err)) {
+ std::fprintf(stderr, "strata generate: %s\n", err.c_str());
+ return 1;
+ }
std::printf("%-24s %lld rounds of %d, drafts accepted %lld of %lld (%.3f), %.2f tokens per round\n",
"speculation", (long long) rounds, o.spec, (long long) drafts_ok, (long long) drafts_total,
drafts_total > 0 ? (double) drafts_ok / (double) drafts_total : 0.0,
diff --git a/sycl/tools/fixups.py b/sycl/tools/fixups.py
index 453cd364a..02caddfdc 100644
--- a/sycl/tools/fixups.py
+++ b/sycl/tools/fixups.py
@@ -99,6 +99,10 @@ def doorbell(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"))
+# 0.1.31/0.1.32: fused_gr's per-block shared-memory query stays CUDA (dpct leaves the attribute untranslated)
+edit("src/kernels/cuda/fused_gr.dp.cpp", lambda s: s.replace(
+ " cudaDeviceGetAttribute(&per_block, cudaDevAttrMaxSharedMemoryPerBlock, dev);\n",
+ " per_block = (int) dpct::get_device(dev).get_local_mem_size(); // SYCL: the work-group local memory\n"))
edit("src/kernels/cuda/elementwise.dp.cpp", doorbell)
edit("src/kernels/cuda/verify_kernels.dp.cpp", doorbell)