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: aligned loads for the Q6_K decode kernel (decode 45 -> 54 tok/s); PLE gather trace

maxfridbecd83544431b5
diff --git a/docs/INTEL.md b/docs/INTEL.md
index 57a0acf98..14093b671 100644
--- a/docs/INTEL.md
+++ b/docs/INTEL.md
@@ -374,6 +374,22 @@ runtime's teardown began); it now exits directly once its requests are done.
setting beats SIMD32 beyond run-to-run noise (SIMD32 itself lands at 39 or 45 tok/s). Output tokens identical.
The same bench shows the real headroom: the dense decode kernels stream 100-280 GB/s of a 608 GB/s card
(Q6_K, the most common type, ~146 GB/s at 2-4 columns).
+ **Found and fixed: misaligned loads.** A Q6_K block is 210 bytes, so every block's `ql`/`qh` runs start only
+ 2-byte aligned, and the B70 splits a misaligned 16-byte load into pieces. The same weights repacked at a
+ 224-byte stride ran 2.3-4.7x faster (`q6k_align_bench`). Without changing the layout, the wide Q6_K kernel now
+ does two aligned 16-byte loads and a shift (`load16_a2`; both stay inside the block) and takes every Q6_K
+ shape and window width (it used to be gated to n_out >= 4096, 1-4 columns): 2560->10240 at 1/2/4/6 columns
+ 160/145/141/101 -> 493/432/331/273 GB/s, the 248K-row head 150 -> 407 GB/s at 1 column. Output tokens
+ identical. **Coder decode 44.9 -> 54 tok/s** (2k prompt, greedy). `STRATA_MMVQ_A2=0` restores the old path.
+ Still misaligned: IQ4_XS (136 B, 8-aligned, ~100 GB/s), IQ4_NL (18 B), Q8_0 (34 B); Q4_K/Q5_K are aligned
+ but use 4-byte loads in the multi kernel (230-280 GB/s).
+
+**Two-speed runs, explained (2026-09-30).** Identical greedy runs decode at either ~45 or ~39 tok/s. A per-gather
+trace of the PLE reader (`STRATA_PLE_TRACE=1`) shows the slow runs pay one 226 ms PLE read stall in the first
+decode round, after the window graphs are captured; every other read and round matches the fast runs. Prompt time
+plus decode time is the same in both modes (4.95-5.17 s): the stall lands either in the prompt's PLE wait or in the
+first decode round, so it is a once-per-process cost, not lost throughput. Ruled out: NVMe APST, the I/O scheduler
+(`none`), CPU starvation (93% idle during decode), I/O thread count. Compare runs on time to first token + decode.
6. INT8 prompt GEMMs: experts dequantized to INT8, oneMKL/oneDNN INT8 on XMX (half the dequant bytes, 2x rate).
7. Fewer graph nodes per decode round (~2,500 at ~5 us): norm+rope, scores+top-k, gate+quantize fused.
8. Wider speculation (two draft branches per verify window): the kernels are latency-bound, so it is nearly free.
diff --git a/sycl/CMakeLists.txt b/sycl/CMakeLists.txt
index f4392de3e..949aa17b2 100644
--- a/sycl/CMakeLists.txt
+++ b/sycl/CMakeLists.txt
@@ -195,6 +195,8 @@ if(STRATA_SYCL_PARITY)
target_link_libraries(mmvq_bench PRIVATE strata_kernels)
add_executable(mmvq_sg_bench ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/mmvq_sg_bench.cpp) # SIMD16 vs 32 decode mmvq
target_link_libraries(mmvq_sg_bench PRIVATE strata_kernels)
+ add_executable(q6k_align_bench ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/q6k_align_bench.cpp) # Q6_K block alignment
+ target_link_libraries(q6k_align_bench PRIVATE strata_kernels)
add_executable(xmx_gemm_bench ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/xmx_gemm_bench.cpp) # XMX quantized GEMM vs dequant+oneMKL
target_link_libraries(xmx_gemm_bench PRIVATE strata_kernels strata_prefill) # -qmkl for the oneMKL reference
# one native expert three ways on real GGUF rows (ggml reference, CPU path, GPU native_expert_grouped):
diff --git a/sycl/include/strata/kernels/native_mmvq.hpp b/sycl/include/strata/kernels/native_mmvq.hpp
index a49412449..4b3e82a6f 100644
--- a/sycl/include/strata/kernels/native_mmvq.hpp
+++ b/sycl/include/strata/kernels/native_mmvq.hpp
@@ -31,6 +31,8 @@ std::size_t native_q8_1_bytes(int n_in, int ncols = 1);
// graph capture; captured graphs keep the kernels they captured.
void native_mmvq_set_multi_exact(bool exact);
void native_mmvq_set_q6k_wide(bool on); // SYCL port: the 16-byte-load Q6_K kernel (default on)
+void native_q6_k_mmvq_stride224(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols,
+ void* stream); // SYCL port: experiment, Q6_K blocks at a 224-byte stride
bool native_mmvq_multi_exact();
// One quantization may serve multiple weight matrices sharing the same input.
diff --git a/sycl/src/kernels/cuda/native_mmvq.dp.cpp b/sycl/src/kernels/cuda/native_mmvq.dp.cpp
index 8abf24759..f6d4fe6ac 100644
--- a/sycl/src/kernels/cuda/native_mmvq.dp.cpp
+++ b/sycl/src/kernels/cuda/native_mmvq.dp.cpp
@@ -1328,7 +1328,33 @@ void native_mmvq_rowwarp_kernel(const typename F::Block* __restrict__ w, const Q
// 4-byte loads and measures 130-140 GB/s on the 8192-wide Q6_K projections. Here 8 lanes share a 256-block:
// lane g takes positions iqs = 4g..4g+3, so its ql (16 B), qh (16 B) and each column's q8 ints (16 B) are one
// vector load each; a 32-lane sub-group has four blocks in flight. One row per warp, WARPS rows per group.
-template <int NCOLS, int RPW, int SG = WARP>
+// SYCL port: a 16-byte load from a 2-byte aligned address as two aligned 16-byte loads and a shift. A Q6_K block
+// is 210 bytes, so its ql/qh runs start 2-byte aligned, and the B70 splits a misaligned vector load into pieces:
+// the wide kernel streamed 145 GB/s that way against 640 GB/s for the same blocks repacked at a 16-byte stride.
+// Both aligned loads stay inside the 210-byte block for the ql and qh runs (last byte read <= block + 207).
+__dpct_inline__ sycl::int4 load16_a2(const void* p) {
+ const uintptr_t a = reinterpret_cast<uintptr_t>(p);
+ const sycl::int4* q = reinterpret_cast<const sycl::int4*>(a & ~uintptr_t(15));
+ const int k = int(a >> 2) & 3; // dword offset within the first aligned chunk
+ const bool half = (a & 2) != 0; // and a 2-byte shift (the address is always 2-byte aligned)
+ const sycl::int4 lo = q[0], hi = q[1];
+ const uint32_t d[8] = {(uint32_t) lo.x(), (uint32_t) lo.y(), (uint32_t) lo.z(), (uint32_t) lo.w(),
+ (uint32_t) hi.x(), (uint32_t) hi.y(), (uint32_t) hi.z(), (uint32_t) hi.w()};
+ uint32_t w[5];
+#pragma unroll
+ for (int i = 0; i < 5; ++i) // w = d[k .. k+4] by selects (no indexed register access)
+ w[i] = k == 0 ? d[i] : k == 1 ? d[i + 1] : k == 2 ? d[i + 2] : d[(i + 3) & 7];
+ uint32_t o[4];
+#pragma unroll
+ for (int i = 0; i < 4; ++i) o[i] = half ? (w[i] >> 16) | (w[i + 1] << 16) : w[i];
+ return sycl::int4((int) o[0], (int) o[1], (int) o[2], (int) o[3]);
+}
+inline bool q6k_a2() { // STRATA_MMVQ_A2=0 turns the aligned-load path off
+ static const bool v = std::getenv("STRATA_MMVQ_A2") == nullptr || std::atoi(std::getenv("STRATA_MMVQ_A2")) != 0;
+ return v;
+}
+
+template <int NCOLS, int RPW, int SG = WARP, int BS = (int) sizeof(Q6KBlock), bool A2 = false> // BS: block stride
void native_mmvq_q6k_wide_kernel(const Q6KBlock* __restrict__ w, const Q81Block* __restrict__ x,
float* __restrict__ y, int n_in, int n_out) {
auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
@@ -1349,9 +1375,15 @@ void native_mmvq_q6k_wide_kernel(const Q6KBlock* __restrict__ w, const Q81Block*
sycl::int4 ql4[RPW], qh4[RPW]; float dsc0[RPW], dsc1[RPW];
#pragma unroll
for (int r = 0; r < RPW; ++r) {
- const Q6KBlock* b = w + std::size_t(row0 + (row0 + r < n_out ? r : 0)) * blocks_per_row + kbx;
- ql4[r] = reinterpret_cast<const sycl::int4*>(b->ql)[g];
- qh4[r] = reinterpret_cast<const sycl::int4*>(b->qh)[qh4_idx];
+ const Q6KBlock* b = reinterpret_cast<const Q6KBlock*>(reinterpret_cast<const uint8_t*>(w) +
+ (std::size_t(row0 + (row0 + r < n_out ? r : 0)) * blocks_per_row + kbx) * BS);
+ if constexpr (A2) {
+ ql4[r] = load16_a2(b->ql + 16 * g);
+ qh4[r] = load16_a2(b->qh + 16 * qh4_idx);
+ } else {
+ ql4[r] = reinterpret_cast<const sycl::int4*>(b->ql)[g];
+ qh4[r] = reinterpret_cast<const sycl::int4*>(b->qh)[qh4_idx];
+ }
const float d = b->d;
dsc0[r] = d * (float) b->scales[scale_offset]; dsc1[r] = d * (float) b->scales[scale_offset + 4];
}
@@ -1397,6 +1429,78 @@ void native_mmvq_q6k_wide_kernel(const Q6KBlock* __restrict__ w, const Q81Block*
if (lane == 0 && row0 + r < n_out) y[std::size_t(j) * n_out + row0 + r] = v;
}
}
+// SYCL port: the wide Q6_K kernel with its weight loads issued U steps ahead. The wide kernel's 2560-wide rows
+// are ~3 steps of load -> wait -> dot per sub-group, so each sub-group has one 16-byte load per lane in flight
+// at a time and the kernel is latency-bound (~146 GB/s). Here a sub-group first issues the ql/qh/scale loads
+// of U steps (4U blocks), then does their dots; the activation reads stay inline (they are L1 hits, shared by
+// every row). One row per sub-group, WARPS rows per group.
+template <int NCOLS, int U>
+void native_mmvq_q6k_pf_kernel(const Q6KBlock* __restrict__ w, const Q81Block* __restrict__ x,
+ float* __restrict__ y, int n_in, int n_out) {
+ auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
+ const int lane = int(item.get_local_id(2)), warp = int(item.get_local_id(1));
+ const int row = int(item.get_group(2)) * WARPS + warp;
+ if (row >= n_out) return;
+ const int blocks_per_row = n_in / QK, x_stride = n_in / Q8K;
+ const int g = lane & 7, sub = lane >> 3;
+ const int vh_shift = 2 * ((g & 3) >> 1);
+ const int qh4_idx = 2 * (g >> 2) + (g & 1);
+ const int scale_offset = 8 * (g >> 2) + (g & 3);
+ const int bq8_offset = 4 * (g >> 2) + ((g & 3) >> 1);
+ const int u_int4 = g & 1;
+ const Q6KBlock* wr = w + std::size_t(row) * blocks_per_row;
+ float acc[NCOLS] = {};
+ for (int kb0 = 0; kb0 < blocks_per_row; kb0 += 4 * U) {
+ sycl::int4 ql4[U], qh4[U]; float dsc0[U], dsc1[U]; bool ok[U];
+#pragma unroll
+ for (int u = 0; u < U; ++u) { // all U steps' weight loads first
+ const int kbx = kb0 + 4 * u + sub;
+ ok[u] = kbx < blocks_per_row;
+ const Q6KBlock* b = wr + (ok[u] ? kbx : 0);
+ ql4[u] = reinterpret_cast<const sycl::int4*>(b->ql)[g];
+ qh4[u] = reinterpret_cast<const sycl::int4*>(b->qh)[qh4_idx];
+ const float d = b->d;
+ dsc0[u] = d * (float) b->scales[scale_offset]; dsc1[u] = d * (float) b->scales[scale_offset + 4];
+ }
+#pragma unroll
+ for (int u = 0; u < U; ++u) {
+ if (!ok[u]) continue;
+ const int kby = (kb0 + 4 * u + sub) * (QK / Q8K);
+ const int vl[4] = {ql4[u].x(), ql4[u].y(), ql4[u].z(), ql4[u].w()};
+ const int vh[4] = {qh4[u].x() >> vh_shift, qh4[u].y() >> vh_shift, qh4[u].z() >> vh_shift, qh4[u].w() >> vh_shift};
+ int vi0[4], vi1[4];
+#pragma unroll
+ for (int p = 0; p < 4; ++p) {
+ vi0[p] = dpct::vectorized_binary<sycl::char4>((vl[p] & 0x0f0f0f0f) | ((vh[p] << 4) & 0x30303030), 0x20202020, dpct::sub_sat());
+ vi1[p] = dpct::vectorized_binary<sycl::char4>(((vl[p] >> 4) & 0x0f0f0f0f) | (((vh[p] >> 4) << 4) & 0x30303030), 0x20202020, dpct::sub_sat());
+ }
+#pragma unroll
+ for (int j = 0; j < NCOLS; ++j) {
+ const Q81Block* xb = x + std::size_t(j) * x_stride + kby + bq8_offset;
+ const sycl::int4 a0 = reinterpret_cast<const sycl::int4*>(xb[0].qs)[u_int4];
+ const sycl::int4 a1 = reinterpret_cast<const sycl::int4*>(xb[2].qs)[u_int4];
+ int s0 = 0, s1 = 0;
+ s0 = strata::dp4a(vi0[0], a0.x(), s0); s0 = strata::dp4a(vi0[1], a0.y(), s0);
+ s0 = strata::dp4a(vi0[2], a0.z(), s0); s0 = strata::dp4a(vi0[3], a0.w(), s0);
+ s1 = strata::dp4a(vi1[0], a1.x(), s1); s1 = strata::dp4a(vi1[1], a1.y(), s1);
+ s1 = strata::dp4a(vi1[2], a1.z(), s1); s1 = strata::dp4a(vi1[3], a1.w(), s1);
+ acc[j] += (float) xb[0].ds[0] * dsc0[u] * (float) s0 + (float) xb[2].ds[0] * dsc1[u] * (float) s1;
+ }
+ }
+ }
+ auto sg = item.get_sub_group();
+#pragma unroll
+ for (int j = 0; j < NCOLS; ++j) {
+ float v = acc[j];
+#pragma unroll
+ for (int o = WARP / 2; o > 0; o >>= 1) v += sycl::permute_group_by_xor(sg, v, o);
+ if (lane == 0) y[std::size_t(j) * n_out + row] = v;
+ }
+}
+inline int q6k_pf() { // STRATA_MMVQ_PF: weight-load steps issued ahead in the wide Q6_K kernel (0 = off)
+ static const int v = std::getenv("STRATA_MMVQ_PF") ? std::atoi(std::getenv("STRATA_MMVQ_PF")) : 0;
+ return v;
+}
inline int q6k_wide_rpw() {
static const int v = std::getenv("STRATA_MMVQ_WIDE_RPW") ? std::atoi(std::getenv("STRATA_MMVQ_WIDE_RPW")) : 1;
return v;
@@ -1406,6 +1510,26 @@ void launch_q6k_wide(const void* weights, const void* x_q8_1, float* y, int n_in
const auto* w = static_cast<const Q6KBlock*>(weights);
const auto* x = static_cast<const Q81Block*>(x_q8_1);
const int rpw = q6k_wide_rpw();
+ if (const int pf = q6k_pf(); pf > 0) {
+ const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
+ const sycl::range<3> t(1, WARPS, WARP);
+#define STRATA_Q6PF(UU) if (pf == UU) { \
+ s->parallel_for<dpct_kernel_name<class native_mmvq_q6k_pf, dpct_kernel_scalar<NCOLS>, dpct_kernel_scalar<UU>>>( \
+ sycl::nd_range<3>(sycl::range(1, 1, blocks) * t, t), \
+ [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { native_mmvq_q6k_pf_kernel<NCOLS, UU>(w, x, y, n_in, n_out); }); \
+ return; }
+ STRATA_Q6PF(2) STRATA_Q6PF(3) STRATA_Q6PF(4) STRATA_Q6PF(6)
+#undef STRATA_Q6PF
+ }
+ if (rpw == 1 && q6k_a2()) {
+ const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
+ s->parallel_for<dpct_kernel_name<class native_mmvq_q6k_wide_a2, dpct_kernel_scalar<NCOLS>>>(
+ sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, WARPS, WARP), sycl::range(1, WARPS, WARP)),
+ [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
+ native_mmvq_q6k_wide_kernel<NCOLS, 1, WARP, (int) sizeof(Q6KBlock), true>(w, x, y, n_in, n_out);
+ });
+ return;
+ }
if (rpw == 1 && mmvq_sg16(false, n_out)) {
constexpr int NWG = WARPS * WARP / 16;
const unsigned blocks = unsigned((std::size_t(n_out) + NWG - 1) / NWG);
@@ -1427,6 +1551,16 @@ void launch_q6k_wide(const void* weights, const void* x_q8_1, float* y, int n_in
sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, WARPS, WARP), sycl::range(1, WARPS, WARP)),
[=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { native_mmvq_q6k_wide_kernel<NCOLS, 1>(w, x, y, n_in, n_out); });
}
+// SYCL port: alignment experiment - Q6_K blocks repacked at a 224-byte stride (every block 16-byte aligned).
+template <int NCOLS>
+void launch_q6k_wide224(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, dpct::queue_ptr s) {
+ const auto* w = static_cast<const Q6KBlock*>(weights);
+ const auto* x = static_cast<const Q81Block*>(x_q8_1);
+ const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
+ s->parallel_for<dpct_kernel_name<class native_mmvq_q6k_wide224, dpct_kernel_scalar<NCOLS>>>(
+ sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, WARPS, WARP), sycl::range(1, WARPS, WARP)),
+ [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { native_mmvq_q6k_wide_kernel<NCOLS, 1, WARP, 224>(w, x, y, n_in, n_out); });
+}
bool g_q6k_wide = std::getenv("STRATA_MMVQ_WIDE") == nullptr || std::atoi(std::getenv("STRATA_MMVQ_WIDE")) != 0;
template <typename F, int NCOLS, int RPW>
@@ -1695,6 +1829,17 @@ void small_f32(const void* weights, const float* x, void* scratch_q8_1,
void native_mmvq_set_multi_exact(bool exact) { g_multi_exact = exact; }
void native_mmvq_set_q6k_wide(bool on) { g_q6k_wide = on; }
+void native_q6_k_mmvq_stride224(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols,
+ void* stream) {
+ const auto s = strata::q_of(stream);
+ switch (ncols) {
+ case 1: launch_q6k_wide224<1>(weights, x_q8_1, y, n_in, n_out, s); return;
+ case 2: launch_q6k_wide224<2>(weights, x_q8_1, y, n_in, n_out, s); return;
+ case 3: launch_q6k_wide224<3>(weights, x_q8_1, y, n_in, n_out, s); return;
+ case 4: launch_q6k_wide224<4>(weights, x_q8_1, y, n_in, n_out, s); return;
+ default: launch_q6k_wide224<6>(weights, x_q8_1, y, n_in, n_out, s); return;
+ }
+}
bool native_mmvq_multi_exact() { return g_multi_exact; }
std::size_t native_q8_1_bytes(int n_in, int ncols) {
@@ -2116,13 +2261,22 @@ void native_q4_k_f32(const void* weights, const float* x, void* scratch_q8_1,
void native_q6_k_mmvq(const void* weights, const void* x_q8_1, float* y,
int n_in, int n_out, int ncols, void* stream) {
// SYCL port: 16-byte-load kernel for the decode shapes (ncols <= 4)
- if (g_q6k_wide && ncols >= 1 && ncols <= 4 && n_in % 256 == 0 && n_out >= 4096) { // measured: wins only on the wide projections
- dpct::queue_ptr s = strata::q_of(stream);
+ // With the aligned loads (load16_a2) the wide kernel wins on every Q6_K shape and window width: 2.6-3.4x the
+ // misaligned-load kernels in q6k_align_bench, decode 44.9 -> 54 tok/s on the Coder, output tokens identical.
+ // Without them (STRATA_MMVQ_A2=0) it won only on n_out >= 4096 at 1-4 columns, the old gate.
+ static const int wide_min = std::getenv("STRATA_MMVQ_WIDE_MIN") ? std::atoi(std::getenv("STRATA_MMVQ_WIDE_MIN")) : q6k_a2() ? 0 : 4096;
+ static const int wide_maxc = std::getenv("STRATA_MMVQ_WIDE_MAXC") ? std::atoi(std::getenv("STRATA_MMVQ_WIDE_MAXC")) : q6k_a2() ? 8 : 4;
+ if (g_q6k_wide && ncols >= 1 && ncols <= wide_maxc && n_in % 256 == 0 && n_out >= wide_min) {
+ const auto s = strata::q_of(stream);
switch (ncols) {
case 1: launch_q6k_wide<1>(weights, x_q8_1, y, n_in, n_out, s); return;
case 2: launch_q6k_wide<2>(weights, x_q8_1, y, n_in, n_out, s); return;
case 3: launch_q6k_wide<3>(weights, x_q8_1, y, n_in, n_out, s); return;
- default: launch_q6k_wide<4>(weights, x_q8_1, y, n_in, n_out, s); return;
+ case 4: launch_q6k_wide<4>(weights, x_q8_1, y, n_in, n_out, s); return;
+ case 5: launch_q6k_wide<5>(weights, x_q8_1, y, n_in, n_out, s); return;
+ case 6: launch_q6k_wide<6>(weights, x_q8_1, y, n_in, n_out, s); return;
+ case 7: launch_q6k_wide<7>(weights, x_q8_1, y, n_in, n_out, s); return;
+ default: launch_q6k_wide<8>(weights, x_q8_1, y, n_in, n_out, s); return;
}
}
// SYCL port: the row-blocked kernel for the decode shapes (ncols <= 4)
diff --git a/sycl/src/kernels/q6k_align_bench.cpp b/sycl/src/kernels/q6k_align_bench.cpp
new file mode 100644
index 000000000..e68149e3b
--- /dev/null
+++ b/sycl/src/kernels/q6k_align_bench.cpp
@@ -0,0 +1,59 @@
+// sycl/src/kernels/q6k_align_bench.cpp - SYCL port: does Q6_K's 210-byte (2-byte aligned) block stride cost the wide
+// mmvq kernel its bandwidth? Same weights at stride 210 and repacked at 224 (16-byte aligned); outputs must match.
+#include "strata/kernels/native_mmvq.hpp"
+#include <sycl/sycl.hpp>
+#include <dpct/dpct.hpp>
+#include <chrono>
+#include <cmath>
+#include <cstdio>
+#include <cstring>
+#include <functional>
+#include <vector>
+int main() {
+ sycl::queue* s = &dpct::get_in_order_queue();
+ const int shapes[][2] = {{2560, 10240}, {2560, 12288}, {6144, 2560}, {2560, 248320}};
+ for (auto& sh : shapes) {
+ const int n_in = sh[0], n_out = sh[1];
+ const size_t nb = (size_t) n_out * (n_in / 256);
+ std::vector<uint8_t> hw(nb * 210), hp(nb * 224, 0);
+ for (size_t i = 0; i < hw.size(); ++i) hw[i] = (uint8_t) (i * 2654435761u >> 13) & 0x3b;
+ for (size_t b = 0; b < nb; ++b) std::memcpy(&hp[b * 224], &hw[b * 210], 210);
+ void* w = sycl::malloc_device(hw.size(), *s);
+ void* wp = sycl::malloc_device(hp.size(), *s);
+ s->memcpy(w, hw.data(), hw.size()).wait(); s->memcpy(wp, hp.data(), hp.size()).wait();
+ for (int nc : {1, 2, 4, 6}) {
+ std::vector<float> hx((size_t) nc * n_in);
+ for (size_t i = 0; i < hx.size(); ++i) hx[i] = (float) ((i * 7919) % 1000) / 500.f - 1.f;
+ float* x = sycl::malloc_device<float>(hx.size(), *s);
+ void* xq = sycl::malloc_device((size_t) nc * (n_in / 32) * 36, *s);
+ float* y = sycl::malloc_device<float>((size_t) nc * n_out, *s);
+ s->memcpy(x, hx.data(), hx.size() * 4).wait();
+ strata::kernels::native_quantize_q8_1(x, xq, n_in, nc, s);
+ auto time = [&](const std::function<void()>& run, std::vector<float>& out) {
+ const auto w0 = std::chrono::steady_clock::now();
+ while (std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - w0).count() < 150) {
+ for (int i = 0; i < 10; ++i) run();
+ s->wait();
+ }
+ const int it = 200;
+ const auto t0 = std::chrono::steady_clock::now();
+ for (int i = 0; i < it; ++i) run();
+ s->wait();
+ out.resize((size_t) nc * n_out);
+ s->memcpy(out.data(), y, out.size() * 4).wait();
+ return std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count() / it;
+ };
+ std::vector<float> y0, y1;
+ const double a = time([&] { strata::kernels::native_q6_k_mmvq(w, xq, y, n_in, n_out, nc, s); }, y0);
+ const double b = time([&] { strata::kernels::native_q6_k_mmvq_stride224(wp, xq, y, n_in, n_out, nc, s); }, y1);
+ double num = 0, den = 0;
+ for (size_t i = 0; i < y0.size(); ++i) { num += std::fabs((double) y0[i] - y1[i]); den += std::fabs((double) y0[i]); }
+ const double gb = nb * 210.0 / 1e3;
+ std::printf("q6_k %5d x %6d cols %d: stride 210 %7.1f us %6.1f GB/s | stride 224 %7.1f us %6.1f GB/s (%.2fx) | rel diff %.1e\n",
+ n_in, n_out, nc, a, gb / a, b, gb / b, a / b, num / (den > 0 ? den : 1));
+ sycl::free(x, *s); sycl::free(xq, *s); sycl::free(y, *s);
+ }
+ sycl::free(w, *s); sycl::free(wp, *s);
+ }
+ return 0;
+}
diff --git a/sycl/src/ngram/ple_reader.cpp b/sycl/src/ngram/ple_reader.cpp
new file mode 100644
index 000000000..19e017b4d
--- /dev/null
+++ b/sycl/src/ngram/ple_reader.cpp
@@ -0,0 +1,477 @@
+// sycl/src/ngram/ple_reader.cpp - SYCL port: upstream src/ngram/ple_reader.cpp plus a per-gather timing trace
+// (STRATA_PLE_TRACE=1: where a decode round's PLE wait goes). See include/strata/ngram/ple_reader.hpp.
+#include <cstdio>
+#include <cstdlib>
+#include "strata/ngram/ple_reader.hpp"
+
+#include <algorithm>
+#include <condition_variable>
+#include <cstring>
+#include <deque>
+#include <exception>
+#include <mutex>
+#include <thread>
+#include <unordered_map>
+
+namespace strata::ngram {
+
+using platform::Completion;
+using platform::DirectFile;
+using platform::now_us;
+
+double ReaderStats::percentile(double q) const {
+ if (read_us.empty()) return 0.0;
+ std::vector<float> v(read_us);
+ const size_t k = std::min(v.size() - 1, (size_t) (q * (double) (v.size() - 1) + 0.5));
+ std::nth_element(v.begin(), v.begin() + (ptrdiff_t) k, v.end());
+ return v[k];
+}
+
+namespace {
+
+constexpr size_t LATENCY_RING = 65536;
+constexpr uint32_t WAYS = 8;
+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;
+ std::vector<uint32_t> keys; // sets * WAYS
+ std::vector<uint8_t> data; // sets * WAYS * ROW_BYTES
+ std::vector<uint8_t> next; // per-set replacement pointer
+ uint64_t used = 0;
+
+ void init(uint64_t rows) {
+ sets = rows / WAYS;
+ keys.assign(sets * WAYS, EMPTY);
+ data.assign(sets * WAYS * ROW_BYTES, 0);
+ next.assign(sets, 0);
+ used = 0;
+ }
+ static uint64_t mix(uint32_t r) {
+ uint64_t x = r * 0x9E3779B97F4A7C15ull;
+ return x ^ (x >> 29);
+ }
+ const uint8_t* find(uint32_t row) const {
+ 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];
+ return nullptr;
+ }
+ void insert(uint32_t row, const uint8_t* bytes) {
+ if (sets == 0 || find(row) != nullptr) return;
+ const uint64_t s = mix(row) % sets;
+ uint32_t w = next[s];
+ 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);
+ }
+};
+
+struct Use {
+ uint32_t row;
+ uint32_t in_page; // byte offset of the row inside the read buffer
+ uint8_t* dst;
+};
+
+struct Job {
+ uint64_t offset = 0; // aligned file offset
+ uint32_t length = 0; // PAGE or 2 * PAGE (a row that straddles a page boundary)
+ uint32_t ticket = 0;
+ std::vector<Use> uses;
+ double issued_us = 0;
+};
+
+struct TicketState {
+ uint32_t pending = 0; // jobs not yet completed
+ uint32_t jobs = 0; // SYCL port trace: jobs issued, and when it was issued / first submitted / last completed
+ double t_issue = 0, t_first = 0, t_last = 0;
+};
+bool ple_trace() {
+ static const bool v = std::getenv("STRATA_PLE_TRACE") != nullptr;
+ return v;
+}
+
+} // namespace
+
+// THREADING. With `io_thread` (the default) one worker thread owns every DirectFile call: it submits queued jobs
+// and reaps completions, so `issue` on the caller's thread only builds jobs and wakes it (~11 us per ReadFile
+// no longer lands on the host loop). `mu` guards everything below except `file`, which only the worker touches
+// (plus `wake`, which is thread-safe). Without `io_thread` the caller does all of it, as before.
+struct PleReader::Impl {
+ DirectFile file;
+ uint64_t table_offset = 0;
+ uint64_t n_rows = 0;
+ uint32_t max_inflight = 0;
+ uint8_t* slab = nullptr; // max_inflight slots of 2 pages
+ std::vector<uint32_t> free_slots;
+ std::vector<Job> inflight; // indexed by slot
+ std::vector<Completion> delayed; // completed but held back by fault injection
+ std::deque<Job> queue; // not yet submitted
+ std::unordered_map<uint32_t, TicketState> tickets;
+ uint32_t next_ticket = 1;
+ RowCache cache;
+ ReaderStats stats;
+ size_t ring_pos = 0;
+ double delay_us = 0;
+ std::string error;
+
+ bool threaded = false;
+ bool stop = false;
+ std::mutex mu;
+ std::condition_variable cv_work; // worker: there is something to submit
+ std::condition_variable cv_done; // collectors: a ticket may have completed
+ std::thread worker;
+
+ uint8_t* slot_buf(uint32_t s) { return slab + (size_t) s * 2 * PAGE; }
+ bool busy() const { return free_slots.size() < max_inflight || !delayed.empty(); }
+
+ void cancel_queued() {
+ for (const Job& job : queue) {
+ auto it = tickets.find(job.ticket);
+ if (it != tickets.end() && it->second.pending > 0) --it->second.pending;
+ }
+ queue.clear();
+ }
+
+ void record_latency(double us) {
+ stats.read_us_sum += us;
+ if (stats.read_us.size() < LATENCY_RING) stats.read_us.push_back((float) us);
+ else stats.read_us[ring_pos++ % LATENCY_RING] = (float) us;
+ }
+
+ bool pump() {
+ while (!queue.empty() && !free_slots.empty()) {
+ const uint32_t s = free_slots.back();
+ free_slots.pop_back();
+ inflight[s] = std::move(queue.front());
+ queue.pop_front();
+ Job& j = inflight[s];
+ j.issued_us = now_us();
+ if (ple_trace()) {
+ 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)) {
+ j.uses.clear();
+ auto it = tickets.find(j.ticket);
+ if (it != tickets.end() && it->second.pending > 0) --it->second.pending;
+ free_slots.push_back(s);
+ cancel_queued();
+ return false;
+ }
+ stats.submit_us += now_us() - j.issued_us;
+ ++stats.reads;
+ }
+ return true;
+ }
+
+ bool finish(const Completion& c) {
+ const uint32_t s = (uint32_t) c.tag;
+ if (s >= inflight.size()) {
+ error = "PleReader: invalid table-read completion";
+ cancel_queued();
+ return false;
+ }
+ Job& j = inflight[s];
+ if (!c.ok) {
+ error = "PleReader: a table read failed";
+ cancel_queued();
+ j.uses.clear();
+ auto it = tickets.find(j.ticket);
+ if (it != tickets.end() && it->second.pending > 0) --it->second.pending;
+ free_slots.push_back(s);
+ return false;
+ }
+ record_latency(now_us() - j.issued_us);
+ 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) {
+ error = "PleReader: short read inside the table";
+ cancel_queued();
+ j.uses.clear();
+ auto it = tickets.find(j.ticket);
+ if (it != tickets.end() && it->second.pending > 0) --it->second.pending;
+ free_slots.push_back(s);
+ return false;
+ }
+ }
+ for (const Use& u : j.uses) {
+ std::memcpy(u.dst, buf + u.in_page, ROW_BYTES);
+ cache.insert(u.row, buf + u.in_page);
+ }
+ auto it = tickets.find(j.ticket);
+ if (it != tickets.end() && it->second.pending > 0) --it->second.pending;
+ if (ple_trace() && it != tickets.end()) it->second.t_last = now_us();
+ j.uses.clear();
+ free_slots.push_back(s);
+ return error.empty() ? pump() : true;
+ }
+
+ /// Completions (or wake packets) just returned by `file.wait`, applying fault injection.
+ bool process(const Completion* got, int n) {
+ bool ok = true;
+ for (int i = 0; i < n; ++i) {
+ if (got[i].tag == DirectFile::WAKE_TAG) continue;
+ if (got[i].tag >= inflight.size()) {
+ error = "PleReader: invalid table-read completion";
+ cancel_queued();
+ ok = false;
+ continue;
+ }
+ if (delay_us > 0 && now_us() - inflight[(uint32_t) got[i].tag].issued_us < delay_us) {
+ delayed.push_back(got[i]);
+ ++stats.late_injected;
+ continue;
+ }
+ if (!finish(got[i])) ok = false; // drain the rest of this batch so no completed slot is stranded
+ }
+ return ok;
+ }
+
+ bool release_delayed() {
+ const double now = now_us();
+ for (size_t i = 0; i < delayed.size();) {
+ if (now - inflight[(uint32_t) delayed[i].tag].issued_us >= delay_us) {
+ const Completion c = delayed[i];
+ delayed.erase(delayed.begin() + (ptrdiff_t) i);
+ if (!finish(c)) return false;
+ } else {
+ ++i;
+ }
+ }
+ return true;
+ }
+
+ /// Caller-thread mode: process whatever has completed; blocks up to `timeout_ms` for the first completion.
+ bool drain(int timeout_ms) {
+ Completion got[64];
+ if (!delayed.empty()) {
+ if (!release_delayed()) return false;
+ timeout_ms = 0; // keep polling the held completions
+ }
+ const int n = file.wait(got, 64, timeout_ms);
+ return process(got, n);
+ }
+
+ void worker_loop() {
+ std::unique_lock<std::mutex> lk(mu);
+ for (;;) {
+ cv_work.wait(lk, [&] { return stop || !queue.empty() || busy(); });
+ 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";
+ if (!error.empty()) {
+ cv_done.notify_all();
+ if (!busy()) { cv_work.wait(lk, [&] { return stop; }); break; }
+ }
+ if (!busy()) { cv_done.notify_all(); continue; }
+ // Block in the port WITHOUT the lock, so `issue` can queue work; `issue` wakes us with a packet.
+ const int timeout = delayed.empty() ? -1 : 0;
+ lk.unlock();
+ Completion got[64];
+ const int n = file.wait(got, 64, timeout);
+ lk.lock();
+ if (!process(got, n) && error.empty()) error = "PleReader: read failed";
+ cv_done.notify_all();
+ }
+ }
+};
+
+PleReader::PleReader() : impl_(new Impl) {}
+PleReader::~PleReader() {
+ close();
+ delete impl_;
+}
+
+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) {
+ close();
+ if (max_inflight == 0 || max_inflight > 1024) { err = "PleReader: max_inflight must be 1..1024"; return false; }
+ if (!impl_->file.open(path, err)) return false;
+ 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;
+ }
+ impl_->table_offset = table_offset;
+ impl_->n_rows = n_rows;
+ impl_->max_inflight = max_inflight;
+ impl_->slab = (uint8_t*) DirectFile::alloc_aligned((size_t) max_inflight * 2 * PAGE);
+ if (impl_->slab == nullptr) { err = "PleReader: cannot allocate read buffers"; close(); return false; }
+ 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_->error.clear();
+ reset_stats();
+ impl_->stop = false;
+ impl_->threaded = io_thread;
+ if (io_thread) {
+ try {
+ impl_->worker = std::thread([this] { impl_->worker_loop(); });
+ } catch (const std::exception& e) {
+ err = std::string("PleReader: cannot create I/O worker: ") + e.what();
+ close();
+ return false;
+ } catch (...) {
+ err = "PleReader: cannot create I/O worker";
+ close();
+ return false;
+ }
+ }
+ return true;
+}
+
+void PleReader::close() {
+ Impl& m = *impl_;
+ if (m.worker.joinable()) {
+ {
+ std::lock_guard<std::mutex> lk(m.mu);
+ m.stop = true;
+ m.queue.clear(); // unsubmitted work is dropped; in-flight reads still drain
+ }
+ m.cv_work.notify_all();
+ m.file.wake();
+ m.worker.join();
+ }
+ // Outstanding reads must finish before their buffers are released (caller-thread mode, or a worker that
+ // stopped on an error).
+ if (m.file.is_open()) {
+ while (m.free_slots.size() < m.max_inflight) {
+ Completion c[64];
+ const int n = m.file.wait(c, 64, -1);
+ if (n == 0) break;
+ for (int i = 0; i < n; ++i)
+ if (c[i].tag != DirectFile::WAKE_TAG) m.free_slots.push_back((uint32_t) c[i].tag);
+ }
+ }
+ m.file.close();
+ DirectFile::free_aligned(m.slab);
+ m.slab = nullptr;
+ m.queue.clear();
+ m.tickets.clear();
+ m.delayed.clear();
+ m.inflight.clear();
+ m.free_slots.clear();
+ m.cache.init(0);
+ m.threaded = false;
+ m.stop = false;
+}
+
+bool PleReader::is_open() const { return impl_->file.is_open(); }
+
+PleReader::Ticket PleReader::issue(const uint32_t* rows, size_t n, uint8_t* out_raw) {
+ Impl& m = *impl_;
+ std::unique_lock<std::mutex> lk(m.mu, std::defer_lock);
+ if (m.threaded) lk.lock();
+ const uint32_t id = m.next_ticket++;
+ if (m.next_ticket == 0) m.next_ticket = 1;
+ 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;
+ ++m.stats.requests;
+ if (rows[i] >= m.n_rows) {
+ std::memset(dst, 0, ROW_BYTES);
+ continue;
+ }
+ if (const uint8_t* hit = m.cache.find(rows[i])) {
+ std::memcpy(dst, hit, ROW_BYTES);
+ ++m.stats.cache_hits;
+ continue;
+ }
+ const uint64_t at = m.table_offset + (uint64_t) rows[i] * ROW_BYTES;
+ const uint64_t first = at / PAGE * PAGE;
+ const uint32_t length = (uint32_t) ((at + ROW_BYTES - 1) / PAGE * PAGE - first + PAGE);
+ auto f = by_page.find(first);
+ if (f != by_page.end()) {
+ Job& j = jobs[f->second];
+ j.length = std::max(j.length, length);
+ j.uses.push_back(Use{rows[i], (uint32_t) (at - first), dst});
+ ++m.stats.dedup_rows;
+ continue;
+ }
+ by_page.emplace(first, jobs.size());
+ Job j;
+ j.offset = first;
+ j.length = length;
+ j.ticket = id;
+ j.uses.push_back(Use{rows[i], (uint32_t) (at - first), dst});
+ jobs.push_back(std::move(j));
+ }
+ // Sorted by offset: prefill chunks then read the SSD in near-sequential order.
+ std::sort(jobs.begin(), jobs.end(), [](const Job& a, const Job& b) { return a.offset < b.offset; });
+ ts.pending = (uint32_t) jobs.size();
+ ts.jobs = ts.pending;
+ ts.t_issue = now_us();
+ const bool has_jobs = ts.pending > 0;
+ for (Job& j : jobs) m.queue.push_back(std::move(j));
+ if (m.threaded) {
+ lk.unlock();
+ if (has_jobs) {
+ m.cv_work.notify_one();
+ m.file.wake(); // in case the worker is blocked in the port
+ }
+ } else if (!m.pump() && m.error.empty()) {
+ m.error = "PleReader: submit failed";
+ }
+ return Ticket{id};
+}
+
+bool PleReader::collect(Ticket t, std::string& err) {
+ Impl& m = *impl_;
+ const double start = now_us();
+ if (m.threaded) {
+ std::unique_lock<std::mutex> lk(m.mu);
+ auto it = m.tickets.find(t.id);
+ if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; }
+ m.cv_done.wait(lk, [&] {
+ const auto current = m.tickets.find(t.id);
+ return current == m.tickets.end() || current->second.pending == 0;
+ });
+ it = m.tickets.find(t.id);
+ if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; }
+ if (!m.error.empty()) { err = m.error; return false; }
+ m.stats.wait_us += now_us() - start;
+ if (ple_trace() && it->second.jobs > 0 && it->second.jobs < 200) {
+ const TicketState& ts = it->second;
+ const double now = now_us();
+ std::fprintf(stderr, "ple trace: %3u jobs issue->submit %8.1f submit->last %8.1f last->return %8.1f "
+ "collect wait %8.1f us\n", ts.jobs, ts.t_first - ts.t_issue, ts.t_last - ts.t_first,
+ now - ts.t_last, now - start);
+ }
+ m.tickets.erase(it);
+ return true;
+ }
+ auto it = m.tickets.find(t.id);
+ if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; }
+ while (it->second.pending > 0) {
+ const bool drained = m.drain(-1);
+ if (!drained && m.error.empty()) m.error = "PleReader: read failed";
+ it = m.tickets.find(t.id);
+ if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; }
+ }
+ if (!m.error.empty()) { err = m.error; return false; }
+ m.stats.wait_us += now_us() - start;
+ m.tickets.erase(it);
+ return true;
+}
+
+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; }
+void PleReader::reset_stats() {
+ impl_->stats = ReaderStats{};
+ impl_->ring_pos = 0;
+}
+uint64_t PleReader::cache_capacity() const { return impl_->cache.sets * WAYS; }
+uint64_t PleReader::cache_size() const { return impl_->cache.used; }
+
+} // namespace strata::ngram