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: int8 expert products: work-group kernels (activation tiles and codebook in local memory), STRATA_PREFILL_MMQ=auto from a measured per-GPU crossover cached per device/driver/format, per-group FP16 fallback, per-device state, clamped down-matrix reads, AOT guard for non-Xe2, docs; 4K +12.5%, 1K +20% with identical tokens
Niko12219a01b6e3b898
diff --git a/docs/INTEL_INT8_EXPERTS.md b/docs/INTEL_INT8_EXPERTS.mdindex 37e2b67dd..2025998fe 100644--- a/docs/INTEL_INT8_EXPERTS.md+++ b/docs/INTEL_INT8_EXPERTS.md@@ -1,57 +1,89 @@# Fused int8 DPAS expert products on Battlemage (branch f-151-b70)-Behaviour note, written before the kernel (2026-10-18), kept in step with `sycl/src/prefill/esimd_moe.dp.cpp`.+Behaviour note, written before the kernel (2026-10-18) and kept in step with `sycl/src/prefill/esimd_moe.dp.cpp`. The measured numbers+are at the end.## What it replaces-The prompt path computes a routed expert as dequantize (gate/up and down to FP16, 9.8 MB written) then three oneMKL / SwiGLU-launches. On the Arc Pro B70 (IQ3_S, 4K prompt) that chain is ~38 us of GPU time per expert (dequant 25.6 us, GEMMs and-SwiGLU ~12 us) and 23% of the prompt. The fused path decodes the quantized weights in registers straight into the DPAS B-operand, so the FP16 copy never exists and the weights are read once, compressed (2.1 MB per expert instead of 9.8 MB written and-read back).+The prompt path computes a routed expert as dequantize (gate/up and down to FP16, 9.8 MB written) then oneMKL GEMMs and SwiGLU. On+the Arc Pro B70 (IQ3_S pack, 4K prompt) that chain is ~38 us of GPU time per expert (dequant 25.6 us, GEMMs and SwiGLU ~12 us) and+23% of the prompt. The fused path decodes the quantized weights in registers straight into the DPAS B operand, so the FP16 copy+never exists and the weights are read once, compressed (2.1 MB per expert instead of 9.8 MB written and read back).++## Switches++* `STRATA_PREFILL_MMQ=1` (alias `STRATA_PF_I8=1`): every group of experts whose formats are supported takes the int8 chain.+* `STRATA_PREFILL_MMQ=0` (or unset, the default): the FP16 path everywhere. The name is MMQ's because the other backends' int8+ prompt-expert path is MMQ; here it is this kernel.+* `STRATA_PREFILL_MMQ=auto`: per group, int8 while the group's mean rows per expert are under the crossover measured on this GPU.+ At the first layer of each expert format the engine times both chains on synthetic experts (random blobs of the layer's format and+ shape, uneven row counts like a real group) at 16, 32, 64, 128 and 256 mean rows per expert, interpolates where the FP16 chain+ becomes the faster one, flags the result "clear" when the cost ratio falls steadily and the bracketing samples are 5% away from+ 1, and keeps it in `~/.cache/strata/i8-crossover.txt` (`STRATA_CACHE_DIR` moves it) keyed by device name, driver version, the two+ ggml types and the shape. A matching key is read back instead of measured. The measurement costs ~1.2 s once, during the first+ prompt. A measurement that fails (no VRAM) falls back to 64 rows.+* `STRATA_I8_FORCE=0` hides the device from the kernels, `STRATA_I8_MT=2|4|8` forces the tile height, `STRATA_I8_WG=0` the+ non-work-group kernels, `STRATA_I8_GRF=128` the 128-register mode, `STRATA_I8_DBG` bring-up switches (skip decode / loads / stores).+* Default off until the owner decides. The activations are quantized, so the bits differ from the FP16 path (see "Quality").## Tiles and thresholds-* One hardware thread (ESIMD, sub-group 16, 256 GRF where the device builds it) owns 16 output rows of one expert, all of K, and- `MT x 8` activation rows. `MT` = 2, 4, 8 or 12, chosen per launch from the mean number of 8-row tiles per expert in the group- (<=2 -> 2, <=4 -> 4, <=8 -> 8, else 12; `STRATA_I8_MT` overrides). 12 keeps one decode for up to 96 rows.-* An expert with more rows than `8 MT` is split over row-block threads; each decodes the same weights again, so the redundancy is- `ceil(rows / (8 MT))`.-* A 128-output work-group tile (the 16/32/64 rows x 128 outputs of the plan) is eight such threads side by side. There is no- shared memory and no barrier, because the decode is per thread and the activations are read straight from L1/L2 as ready-made- A tiles; this was chosen over SLM staging because the K step is one DPAS (32), the B fragment never leaves registers, and the- tiled activations make each A operand one 256-byte block load.-* K step 32 (one s8 DPAS 8x16x32) with the 128-wide unrolling inside the superblock loop for IQ3_S (8 steps per 256).-* Group of up to 16 experts per launch (the same group the FP16 grouped XMX path holds in the prompt walk).+* One hardware thread (ESIMD, sub-group 16, 256 GRF) owns 16 output rows of one expert, all of K, and `MT x 8` activation rows.+ `MT` = 2, 4 or 8 from the group's mean number of 8-row tiles per expert (<=2 -> 2, <=4 -> 4, else 8). A thread's accumulators are+ MT tiles of 512 bytes in an 8 KB register file (256 GRF of 32 bytes), so MT 12 or two output tiles per thread spilled 3-15 KB and ran+ 2-5x slower. An expert with more rows than 8 MT is split over row-block threads, each decoding the weights again.+* A work group is 8 such threads on 8 consecutive output tiles (128 outputs) of one row block: the activation tiles of the row block+ are read from global memory once per group, in chunks of 4 steps of 32 (128 of K), into double-buffered local memory (one barrier per+ chunk), and every thread reads them from there; the group also copies the codebook the decoders gather from into local memory.+ IQ2_S gate/up keeps the plain kernel: its 8 KB codebook costs more to copy per group than the gathers save (35 against 16 us).+* K step 32 (one s8 DPAS 8x16x32): decode the 16 rows' 32 values (lanes = rows, one weight decode per tile, applied to all MT row+ tiles), one DPAS into a zeroed int32 tile, float epilogue. Group of up to 16 experts per launch (the same group the FP16 grouped path+ holds in the prompt walk), 4 launches per group (quantize, gate/up, SwiGLU + quantize, down) against 4 per expert.+* The kernels need the s8 8x16x32 matrix combination (Xe2: Battlemage, Lunar Lake). Large GRF: `grf_size<256>` is requested for+ every kernel; a device that cannot build it keeps its default and the spills show in the build log. DP4a fallback: none; without the+ DPAS combination `available()` is false and the FP16 path runs (the build without ESIMD for an Alchemist / Xe-HPC AOT device+ compiles stubs, `STRATA_I8_NO_ESIMD`).## Scales-* Activations: llama.cpp's q8_1 grid. Per row and 32 of K, `d = amax / 127`, `q = round(x / d)` half away from zero, stored as int8- in DPAS A-operand order (`[8-row tile][K/32][8 rows x 32 bytes]`), with the 8 row scales of a tile contiguous.-* Weights: IQ3_S `d (1 + 2 s)` per 32 (exact in float), IQ4_NL `d` per 32; the int8 values are the codebook entries with their- signs (IQ3_S: odd 1..15, IQ4_NL: -127..113), never rounded.-* Each 32-block's int32 dot product (<= 32 * 127 * 127 < 2^24: exact in int32 and exactly convertible to float) is converted and- accumulated as `acc += float(dot) * (sw[n] * dx[m])` in float, K ascending. The only roundings are the float multiply/add and the- activation quantization.-* After gate/up, `silu(gate) * up` (the FP16 path's formula, in float, not rounded to FP16) is quantized per 32 of the 640 FF- values into the down input.+* Activations: llama.cpp's q8_1 grid. Per row and 32 of K, `d = amax / 127`, `q = round(x / d)` half away from zero, int8 stored in+ DPAS A-operand order (`[8-row tile][K/32][8 rows x 32 bytes]`, experts padded to 8 rows with zeros), the 8 row scales of a tile+ contiguous.+* Weights: IQ3_S `d (1 + 2 s)` per 32, IQ3_XXS `d (2 s + 1) / 4`, IQ2_S `d (2 s + 1) / 8` per 16 (two DPAS per 32, the other half+ zeroed), IQ4_NL `d` per 32, Q2_0 `d` per 64; the int8 values are the codebook entries with their signs (IQ3_S/IQ3_XXS/IQ2_S: 1..62,+ IQ4_NL: -127..113, Q2_0: -1..2), never rounded.+* Each 32-block's int32 dot product (<= 32 * 127 * 127) is exact and exactly convertible to float; it is scaled by the weight scale of the+ column and the activation scale of the row and added to a float accumulator, K ascending (the float multiply and add are the only+ roundings besides the activation quantization). After gate/up, `silu(gate) * up` (the FP16 path's formula, in float, not rounded+ to FP16) is quantized per 32 of the 640 FF values into the down input.## Edge cases and fallback rules-* Row counts are padded to tiles of 8 with zero rows (stores are masked to the real rows). An expert with no rows is not in the- group.-* IQ3_S rows are 110-byte blocks (2-byte aligned only): every field is read as dwords, two gathers and a funnel shift when it is- not dword aligned, and the second gather is clamped to the matrix end (an unclamped read past the last block faulted the GPU once).-* Supported now: gate/up IQ3_S (ggml type 21) with K a multiple of 256, down IQ4_NL (20) with K a multiple of 32, output rows a- multiple of 16. Any other type or shape makes `gate_up()` / `down()` return false and the caller keeps the FP16 path.-* `available()` is false without the ESIMD aspect and an s8 8x16x32 matrix combination (Alchemist has 8x8x32; non-Intel devices),- `STRATA_I8_FORCE=0` turns it off.-* Selection (`prefill.cpp`): `STRATA_PREFILL_MMQ=1` (alias `STRATA_PF_I8=1`) runs the layers whose experts are the supported- types through it, `=0` keeps the FP16 path, `=auto` uses the measured crossover (below). Default off until the owner decides after- the quality check.--## Different bits--The activation quantization makes the result differ from the dequantize + oneMKL path by about 0.3-0.5% rms per product (the-q8_1 error), which is also what llama.cpp's MMQ path carries. `esimd_moe_parity` reports it against the FP16 path and against an-FP64 reference; KL and the task suites are in `phaseA-tests/notes-151-b70.md`.+* A row count is padded to a tile of 8 with zero rows (stores are masked to the real rows); an expert with no rows is not in the group.+* IQ3_S rows are 110-byte blocks (IQ3_XXS 98, IQ2_S 82, IQ4_NL / Q2_0 18): 2-byte aligned only, so every field is read as dwords, two+ gathers and a funnel shift when not dword aligned. The down matrix ends the expert blob, so its reads clamp the second dword of an unaligned read to the+ matrix's last dword (`ld32c`); the gate/up reads stay inside the blob (the down matrix follows them). The first version read up to 3 bytes+ past the end of a test allocation and faulted the GPU (an xe CAT error and an engine reset; nothing else was affected).+* Supported: gate/up IQ3_S (21), IQ3_XXS (18), IQ2_S (22) with K a multiple of 256; down IQ4_NL (20) with K a multiple of 32 and Q2_0+ (42) with K a multiple of 64; 640 FF x 2560 embedding; output rows a multiple of 16; a held group of at most 16 experts. Any other type or+ shape makes the layer take the FP16 path (IQ4_XS gate/up, 1 of 48 layers of the IQ3_S pack). A group the kernels cannot run (no VRAM for+ the int8 scratch, a format they refuse) takes the FP16 chain for that group.+* Multi-GPU: the codebooks, the scratch and the availability are kept per device.++## ESIMD on this compiler (oneAPI 2026.1, bmg-g31) - what went wrong while writing it++* A dynamic index into a kernel-argument array gave a garbage value (the first weight read faulted the GPU, the xe driver logged+ hundreds of page faults and reset the engine, the box recovered each time): the kernels read the arrays at constant indices+ (`pick_expert`, the unrolled expert lookup in the quantize kernels).+* `t % n` and `t / n` with a run-time `n` gave `t % n == t`: the kernels use 2-D grids.+* `gather<T, N, VS>` with VS > 1 is not available on Battlemage; a lambda capturing a simd by reference puts it in private memory.++## Quality++The int8 path is near-lossless against the FP16 path. 28 prompts (code, reasoning, chat, multi-turn, long up to 3.2K tokens), 6002+positions teacher-forced on the FP16 path's greedy continuations (`cuda_kl.py` with `STRATA_FOLLOW`), fixed flags: reference against+itself KL exactly 0; int8 against reference KL mean 0.0002 nats (p99 0.006, max 0.04), top-1 99.7%, perplexity ratio 1.0004, first-token+KL 0.0005. For comparison a chunk-size change (`--prefill 8192` against 4096) moves the first-token distribution by 0.01-0.03 nats.+The kernel arithmetic itself matches an exact host reference on the same int8 activations to 3e-7 relative; against FP64 with the+unquantized activations each product carries ~1% rms (the q8_1 grid; synthetic data with 1% outliers), the chain 1.7% against+dequantize + oneMKL. `esimd_moe_parity` runs all six gate/up x down type pairs.diff --git a/sycl/CMakeLists.txt b/sycl/CMakeLists.txtindex 39be503d0..2ae19f1a0 100644--- a/sycl/CMakeLists.txt+++ b/sycl/CMakeLists.txt@@ -42,6 +42,9 @@ if(STRATA_SYCL_AOT MATCHES "^(bmg|lnl)")elseif(STRATA_SYCL_AOT MATCHES "^pvc")add_compile_definitions(STRATA_NO_DG2_XMX=1) # the grouped XMX kernels (sub-group 8, 8x8x16) do not compile for Xe2 / Xe-HPCendif()+if(STRATA_SYCL_AOT AND NOT STRATA_SYCL_AOT MATCHES "^(bmg|lnl)")+ add_compile_definitions(STRATA_I8_NO_ESIMD=1) # 151-b70: the fused int8 DPAS expert kernels (ESIMD, s8 8x16x32) are Xe2-only: no AOT build for Alchemist / Xe-HPC+endif()if(STRATA_SYCL_AOT)list(APPEND _sycl_flags -fsycl-targets=spir64_gen)# the divide/sqrt rounding option (below) must reach ocloc here: an AOT build has no spir64 backend to take it@@ -390,8 +393,11 @@ if(STRATA_SYCL_PARITY)target_link_libraries(xmx_group_parity PRIVATE strata_kernels strata_prefill)add_executable(esimd_moe_parity ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/esimd_moe_parity.cpp) # 151-b70: fused int8 expert products vs dequant+oneMKL and FP64target_link_libraries(esimd_moe_parity PRIVATE strata_kernels strata_prefill)- add_executable(esimd_dpas_probe ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/esimd_dpas_probe.cpp) # ESIMD DPAS peak (registers only)- add_executable(esimd_i8_bench ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/esimd_i8_bench.cpp) # ESIMD int8 DPAS GEMM on pre-decoded weights+ add_test(NAME esimd_moe_parity COMMAND esimd_moe_parity 60 8 2) # 151-b70: skips (exit 0) on a device without the s8 8x16x32 DPAS+ if(NOT STRATA_SYCL_AOT OR STRATA_SYCL_AOT MATCHES "^(bmg|lnl)") # DPAS s8 8x16x32 (Xe2): not for an Alchemist / Xe-HPC AOT build+ add_executable(esimd_dpas_probe ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/esimd_dpas_probe.cpp) # ESIMD DPAS peak (registers only)+ add_executable(esimd_i8_bench ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/esimd_i8_bench.cpp) # ESIMD int8 DPAS GEMM on pre-decoded weights+ endif()# one native expert three ways on real GGUF rows (ggml reference, CPU path, GPU native_expert_grouped):# native_expert_parity <shard1.gguf> [layer ...]if(STRATA_NATIVE_EXPERTS)diff --git a/sycl/src/prefill/esimd_moe.dp.cpp b/sycl/src/prefill/esimd_moe.dp.cppindex 0d4d4b3ad..608f428ee 100644--- a/sycl/src/prefill/esimd_moe.dp.cpp+++ b/sycl/src/prefill/esimd_moe.dp.cpp@@ -33,9 +33,30 @@#include <type_traits>#include <string>#include <vector>+#include <unordered_map>#include "strata/sycl_queue.hpp"#include "strata/prefill/esimd_moe.hpp"+#ifdef STRATA_I8_NO_ESIMD+// an AOT build for a device without the s8 8x16x32 DPAS (Alchemist, Xe-HPC): no ESIMD kernels, available() is false+namespace strata::prefill::i8 {+void make_layout(Layout& lo, const int32_t* cnt, int n) {+ lo.n = n;+ int r = 0, t = 0;+ for (int i = 0; i < n; ++i) { lo.cnt[i] = cnt[i]; lo.row0[i] = r; lo.tile0[i] = t; r += cnt[i]; t += (cnt[i] + 7) / 8; }+ lo.row0[n] = r;+ lo.tile0[n] = t;+}+bool available(void*) { return false; }+size_t xq_bytes(const Layout& lo, int K) { return (size_t) lo.tile0[lo.n] * 8 * K; }+size_t dx_bytes(const Layout& lo, int K) { return (size_t) lo.tile0[lo.n] * (K / 32) * 8 * sizeof(float); }+bool workspace(const Layout&, int, int, Workspace&, void*) { return false; }+void quantize_rows(const uint16_t*, const Layout&, int, int8_t*, float*, void*) {}+bool gate_up(int, const uint8_t* const*, size_t, int, const Layout&, int, const int8_t*, const float*, float*, void*) { return false; }+void swiglu_quantize(const float*, const Layout&, int, int8_t*, float*, void*) {}+bool down(int, const uint8_t* const*, size_t, int, const Layout&, int, const int8_t*, const float*, float*, void*) { return false; }+} // namespace strata::prefill::i8+#elsenamespace strata::prefill::i8 {namespace {#define GGML_TABLE_BEGIN(type, name, size) static const type name[size] = {@@ -65,8 +86,9 @@ constexpr int N_TABLE = 3456;uint32_t* tables(sycl::queue& q) {static std::mutex mu;- static uint32_t* t = nullptr; // one device per process in the port+ static std::unordered_map<sycl::device, uint32_t*> per_dev; // a layer split has one prompt path per cardstd::lock_guard<std::mutex> lk(mu);+ uint32_t*& t = per_dev[q.get_device()];if (!t) {std::vector<uint32_t> h(N_TABLE, 0);for (int i = 0; i < 512; ++i) h[O_IQ3S + i] = iq3s_grid[i];@@ -95,6 +117,17 @@ SYCL_ESIMD_FUNCTION inline simd<uint32_t, 16> ld32(const uint8_t* base, simd<uinsimd<uint32_t, 16> sh = (off & 2u) << 3; // 0 or 16return (lo >> sh) | ((hi << 16) << (16u - sh));}+// the same with the second dword clamped to byte offset `lim` (the last dword of the matrix): the down matrix ends the expert blob, and a block+// whose last field is not dword aligned would otherwise read up to 3 bytes past it+SYCL_ESIMD_FUNCTION inline simd<uint32_t, 16> ld32c(const uint8_t* base, simd<uint32_t, 16> off, uint32_t lim) {+ simd<uint32_t, 16> a = off & ~3u;+ simd<uint32_t, 16> a2 = a + 4u;+ a2.merge(simd<uint32_t, 16>(lim), a2 > lim);+ simd<uint32_t, 16> lo = gather<uint32_t, 16>(reinterpret_cast<const uint32_t*>(base), a);+ simd<uint32_t, 16> hi = gather<uint32_t, 16>(reinterpret_cast<const uint32_t*>(base), a2);+ simd<uint32_t, 16> sh = (off & 2u) << 3;+ return (lo >> sh) | ((hi << 16) << (16u - sh));+}SYCL_ESIMD_FUNCTION inline simd<uint32_t, 16> ld16(const uint8_t* base, simd<uint32_t, 16> off) {simd<uint32_t, 16> a = off & ~3u;simd<uint32_t, 16> lo = gather<uint32_t, 16>(reinterpret_cast<const uint32_t*>(base), a);@@ -132,6 +165,7 @@ struct GArgs {int nkb; // K / 32int rowb; // bytes per weight rowint ldy;+ uint32_t lim; // byte offset of the last dword of the matrix the clamped reads (ld32c) stay insideint dbg; // bring-up switches (STRATA_I8_DBG): 1 skip the decode, 2 skip the activation loads, 4 skip the stores, 8 skip the K loop};@@ -161,16 +195,16 @@ int fill_args_mt(GArgs& a, const Layout& lo, int MT) {return rb;}-template <int F, int MT> struct TagGu;-template <int F, int MT> struct TagDn;+template <int F, int MT, int G> struct TagGu;+template <int F, int MT, int G> struct TagDn;// ------------------------------------------------------------------------------------------------ gate/up-template <int F, int MT>+template <int F, int MT, int G>void launch_gu(sycl::queue& q, const GArgs a, int nrowblocks) {- auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<256>};+ auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<G>};constexpr int NS = (F == T_IQ2S) ? 2 : 1; // IQ2_S: two scales per 32 values -> two DPAS with the other half zeroedq.submit([&](sycl::handler& h) {- h.parallel_for<TagGu<F, MT>>(sycl::range<2>((size_t) nrowblocks, (size_t) a.ntiles), props, [=](sycl::id<2> id) SYCL_ESIMD_KERNEL {+ h.parallel_for<TagGu<F, MT, G>>(sycl::range<2>((size_t) nrowblocks, (size_t) a.ntiles), props, [=](sycl::id<2> id) SYCL_ESIMD_KERNEL {const int rbg = (int) id[0], nt = (int) id[1];const Pick pk = pick_expert(a, rbg);const int cnt = pk.cnt;@@ -307,11 +341,11 @@ void launch_gu(sycl::queue& q, const GArgs a, int nrowblocks) {}// ------------------------------------------------------------------------------------------------ down-template <int F, int MT>+template <int F, int MT, int G>void launch_dn(sycl::queue& q, const GArgs a, int nrowblocks) {- auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<256>};+ auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<G>};q.submit([&](sycl::handler& h) {- h.parallel_for<TagDn<F, MT>>(sycl::range<2>((size_t) nrowblocks, (size_t) a.ntiles), props, [=](sycl::id<2> id) SYCL_ESIMD_KERNEL {+ h.parallel_for<TagDn<F, MT, G>>(sycl::range<2>((size_t) nrowblocks, (size_t) a.ntiles), props, [=](sycl::id<2> id) SYCL_ESIMD_KERNEL {const int rbg = (int) id[0], nt = (int) id[1];const Pick pk = pick_expert(a, rbg);const int cnt = pk.cnt;@@ -334,7 +368,7 @@ void launch_dn(sycl::queue& q, const GArgs a, int nrowblocks) {sw0 = half_of(ld16(We, ro + P));#pragma unrollfor (int j = 0; j < 4; ++j) {- simd<uint32_t, 16> qd = ld32(We, ro + (P + 2 + 4 * j));+ simd<uint32_t, 16> qd = ld32c(We, ro + (P + 2 + 4 * j), a.lim);// four byte-pair lookups (lo value in byte 0, hi value in byte 1), repacked into the two dwordssimd<uint32_t, 16> t0 = gather<uint32_t, 16>(T + O_IQ4, (qd & 0xffu) << 2);simd<uint32_t, 16> t1 = gather<uint32_t, 16>(T + O_IQ4, ((qd >> 8) & 0xffu) << 2);@@ -348,8 +382,8 @@ void launch_dn(sycl::queue& q, const GArgs a, int nrowblocks) {const uint32_t P = (uint32_t) (kb >> 1) * 18;const int hb = kb & 1;sw0 = half_of(ld16(We, ro + P));- simd<uint32_t, 16> q0 = ld32(We, ro + (P + 2 + 8 * hb));- simd<uint32_t, 16> q1 = ld32(We, ro + (P + 6 + 8 * hb));+ simd<uint32_t, 16> q0 = ld32c(We, ro + (P + 2 + 8 * hb), a.lim);+ simd<uint32_t, 16> q1 = ld32c(We, ro + (P + 6 + 8 * hb), a.lim);#pragma unrollfor (int r = 0; r < 8; ++r) {simd<uint32_t, 16> qb = ((r < 4 ? q0 : q1) >> (8 * (r & 3))) & 0xffu;@@ -390,6 +424,324 @@ void launch_dn(sycl::queue& q, const GArgs a, int nrowblocks) {});}+// ------------------------------------------------------------------------------------------------ work-group versions+// A work group is WGT = 8 threads side by side on 8 consecutive output tiles (128 outputs) of the same row block. The+// activation tiles of the row block are read from global memory ONCE per group, in chunks of 4 steps of 32 (128 of K), into local+// memory (double buffered, one barrier per chunk) and every thread reads them from there, instead of every thread reading all of+// them from L2 (80 threads per expert re-read the same ~200 KB: the activation loads were 8 of 19 us of gate/up). The codebook+// the decoders gather from is copied into local memory by the group once (its gathers then cost ~nothing).+constexpr int WGT = 8;+constexpr auto kAl16 = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::alignment<16>};++// bytes of the tables a format gathers from (local memory), and the segments copied from the global table buffer+template <int F> constexpr int tab_bytes() {+ return F == T_IQ3S ? 2048 : F == T_IQ3XXS ? 1536 : F == T_IQ2S ? 8192 : 1024; // IQ3XXS: grid 1024 + ksigns 512+}++template <int F, int MT>+struct WgLayout {+ static constexpr int TB = tab_bytes<F>();+ static constexpr int ASZ = MT * 1024; // activation tiles of one stage: MT tiles x 4 steps x 256 bytes+ static constexpr int DSZ = MT * 128; // their scales: MT tiles x 4 steps x 32 bytes+ static constexpr int STAGE = ASZ + DSZ;+ static constexpr int TOTAL = TB + 2 * STAGE;+ static constexpr int SPLIT = 8 / MT; // threads per tile in the staging load+ static constexpr int PART = 1024 / SPLIT; // bytes of one tile's activations a thread stages+};++// Staging of one chunk's activation tiles: global -> registers (LOAD_CHUNK) -> local memory stage SS (STORE_CHUNK). Macros, not+// lambdas: a lambda capturing the staging registers by reference put them in private memory.+#define LOAD_CHUNK(CC) \+ if (s_tile < nvalid) { \+ const int* src_ = Xi + ((size_t) (tbase + s_tile) * a.nkb + (CC) * 4) * 64 + s_part * (L::PART / 4); \+ _Pragma("unroll") \+ for (int k = 0; k < L::PART / 256; ++k) stg.template select<64, 1>(64 * k) = block_load<int, 64>(src_ + 64 * k, kAl16); \+ if (s_part == 0) stg_dx = block_load<float, 32>(a.dx + ((size_t) (tbase + s_tile) * a.nkb + (CC) * 4) * 8, kAl16); \+ }+#define STORE_CHUNK(SS) \+ if (s_tile < nvalid) { \+ const uint32_t base_ = L::TB + (SS) * L::STAGE; \+ _Pragma("unroll") \+ for (int k = 0; k < L::PART / 256; ++k) \+ slm_block_store<int, 64>(base_ + s_tile * 1024 + s_part * L::PART + 256 * k, stg.template select<64, 1>(64 * k), kAl16); \+ if (s_part == 0) slm_block_store<float, 32>(base_ + L::ASZ + s_tile * 128, stg_dx, kAl16); \+ }++template <int F, int MT, int G> struct TagGuW;+template <int F, int MT, int G> struct TagDnW;++template <int F, int MT, int G>+void launch_gu_wg(sycl::queue& q, const GArgs a, int nrowblocks) {+ using L = WgLayout<F, MT>;+ auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<G>};+ constexpr int NS = (F == T_IQ2S) ? 2 : 1;+ q.submit([&](sycl::handler& h) {+ h.parallel_for<TagGuW<F, MT, G>>(sycl::nd_range<2>(sycl::range<2>((size_t) nrowblocks, (size_t) a.ntiles), sycl::range<2>(1, WGT)), props,+ [=](sycl::nd_item<2> it) SYCL_ESIMD_KERNEL {+ slm_init<L::TOTAL>();+ const int rbg = (int) it.get_group(0), lt = (int) it.get_local_id(1), nt = (int) it.get_global_id(1);+ const Pick pk = pick_expert(a, rbg);+ const int cnt = pk.cnt;+ const int ntl = (cnt + 7) >> 3;+ const int tl0 = (rbg - pk.rb0) * MT;+ const int nvalid = (ntl - tl0) < MT ? (ntl - tl0) : MT;+ const int tbase = pk.tile0 + tl0;+ const uint8_t* We = pk.blob;+ const uint32_t* T = a.tab;+ const int* Xi = reinterpret_cast<const int*>(a.Xq);+ // the codebook into local memory: thread lt copies its eighth of each segment+ if constexpr (F == T_IQ3S) {+#pragma unroll+ for (int k = 0; k < tab_bytes<F>() / WGT / 64; ++k)+ slm_block_store<uint32_t, 16>(lt * (tab_bytes<F>() / WGT) + 64 * k, block_load<uint32_t, 16>(T + O_IQ3S + (lt * (tab_bytes<F>() / WGT) + 64 * k) / 4, kAl16), kAl16);+ } else if constexpr (F == T_IQ3XXS) {+#pragma unroll+ for (int k = 0; k < 1024 / WGT / 64; ++k)+ slm_block_store<uint32_t, 16>(lt * (1024 / WGT) + 64 * k, block_load<uint32_t, 16>(T + O_IQ3XXS + (lt * (1024 / WGT) + 64 * k) / 4, kAl16), kAl16);+ slm_block_store<uint32_t, 16>(1024 + lt * (512 / WGT), block_load<uint32_t, 16>(T + O_KSIGNS + lt * (512 / WGT) / 4, kAl16), kAl16);+ } else { // IQ2_S+#pragma unroll+ for (int k = 0; k < tab_bytes<F>() / WGT / 64; ++k)+ slm_block_store<uint32_t, 16>(lt * (tab_bytes<F>() / WGT) + 64 * k, block_load<uint32_t, 16>(T + O_IQ2S + (lt * (tab_bytes<F>() / WGT) + 64 * k) / 4, kAl16), kAl16);+ }+ // staging: this thread's piece of the chunk c (tile, part) into registers, then into stage s+ const int s_tile = lt / L::SPLIT, s_part = lt % L::SPLIT;+ simd<int, L::PART / 4> stg;+ simd<float, 32> stg_dx;+ simd<uint32_t, 16> lane(0, 1);+ simd<uint32_t, 16> ro = (lane & 1u) * a.sec_off + ((lane >> 1) + (uint32_t) (8 * nt)) * (uint32_t) a.rowb;+ simd<float, 128 * MT> acc = 0.f;+ const int nchunks = (a.dbg & 8) ? 0 : (a.nkb >> 2);+ if (nchunks > 0) { LOAD_CHUNK(0); STORE_CHUNK(0); }+ barrier(); // the codebook and chunk 0 are in local memory+ simd<float, 16> d = 0.f;+ simd<uint32_t, 16> w0 = 0, w1 = 0, w2 = 0, w3 = 0;+ for (int c = 0; c < nchunks; ++c) {+ const int sb = c >> 1;+ const int stage_off = L::TB + (c & 1) * L::STAGE;+ if (c + 1 < nchunks) { LOAD_CHUNK(c + 1); }+ if ((c & 1) == 0) { // new superblock: its scale and the fields shared by its 8 steps+ const uint32_t P = (uint32_t) sb * blk_bytes<F>();+ d = half_of(ld16(We, ro + P));+ if constexpr (F == T_IQ3S) {+ w0 = ld32(We, ro + (P + 106)); w1 = ld32(We, ro + (P + 66)); w2 = ld32(We, ro + (P + 70));+ } else if constexpr (F == T_IQ2S) {+ w0 = ld32(We, ro + (P + 74)); w1 = ld32(We, ro + (P + 78)); w2 = ld32(We, ro + (P + 66)); w3 = ld32(We, ro + (P + 70));+ }+ }+ const uint32_t P = (uint32_t) sb * blk_bytes<F>();+#pragma unroll 1+ for (int ib4 = 0; ib4 < 4; ++ib4) {+ const int ib = ((c & 1) << 2) + ib4;+ simd<uint32_t, 128> fr0 = 0x01010101u, fr1 = 0u;+ simd<float, 16> sw0 = 1.f, sw1 = 1.f;+ if (!(a.dbg & 1)) {+ if constexpr (F == T_IQ3S) {+ simd<uint32_t, 16> q0 = ld32(We, ro + (P + 2 + 8 * ib));+ simd<uint32_t, 16> q1 = ld32(We, ro + (P + 6 + 8 * ib));+ simd<uint32_t, 16> sg = ld32(We, ro + (P + 74 + 4 * ib));+ simd<uint32_t, 16> qhv = (((ib < 4) ? w1 : w2) >> (8 * (ib & 3))) & 0xffu;+ simd<uint32_t, 16> scn = ((w0 >> (8 * (ib >> 1))) >> (4 * (ib & 1))) & 0xfu;+ sw0 = d * simd<float, 16>(simd<int, 16>(scn * 2u + 1u));+#pragma unroll+ for (int r = 0; r < 8; ++r) {+ simd<uint32_t, 16> qsw = r < 4 ? q0 : q1;+ simd<uint32_t, 16> idx = ((qsw >> (8 * (r & 3))) & 0xffu) | (((qhv >> r) & 1u) << 8);+ simd<uint32_t, 16> g = slm_gather<uint32_t, 16>(idx << 2);+ simd<uint32_t, 16> nib = ((sg >> (8 * (r >> 1))) >> (4 * (r & 1))) & 0xfu;+ fr0.template select<16, 1>(16 * r) = apply_signs(g, nib);+ }+ } else if constexpr (F == T_IQ3XXS) {+ simd<uint32_t, 16> q0 = ld32(We, ro + (P + 2 + 8 * ib));+ simd<uint32_t, 16> q1 = ld32(We, ro + (P + 6 + 8 * ib));+ simd<uint32_t, 16> aux = ld32(We, ro + (P + 66 + 4 * ib));+ sw0 = d * simd<float, 16>(simd<int, 16>((aux >> 28) * 2u + 1u)) * 0.25f;+#pragma unroll+ for (int il = 0; il < 4; ++il) {+ simd<uint32_t, 16> sbyte = slm_gather<uint32_t, 16>(1024u + (((aux >> (7 * il)) & 127u) << 2));+#pragma unroll+ for (int hh = 0; hh < 2; ++hh) {+ const int r = 2 * il + hh;+ simd<uint32_t, 16> qsw = r < 4 ? q0 : q1;+ simd<uint32_t, 16> idx = (qsw >> (8 * (r & 3))) & 0xffu;+ simd<uint32_t, 16> g = slm_gather<uint32_t, 16>(idx << 2);+ fr0.template select<16, 1>(16 * r) = apply_signs(g, (sbyte >> (4 * hh)) & 0xfu);+ }+ }+ } else if constexpr (F == T_IQ2S) {+ simd<uint32_t, 16> idw = ld32(We, ro + (P + 2 + 4 * ib));+ simd<uint32_t, 16> sgw = ld32(We, ro + (P + 34 + 4 * ib));+ simd<uint32_t, 16> qhb = (((ib < 4) ? w2 : w3) >> (8 * (ib & 3))) & 0xffu;+ simd<uint32_t, 16> scb = (((ib < 4) ? w0 : w1) >> (8 * (ib & 3))) & 0xffu;+ sw0 = d * simd<float, 16>(simd<int, 16>((scb & 0xfu) * 2u + 1u)) * 0.125f;+ sw1 = d * simd<float, 16>(simd<int, 16>((scb >> 4) * 2u + 1u)) * 0.125f;+#pragma unroll+ for (int il = 0; il < 4; ++il) {+ simd<uint32_t, 16> idx = ((idw >> (8 * il)) & 0xffu) | ((qhb << (8 - 2 * il)) & 0x300u);+ simd<uint32_t, 16> gl = slm_gather<uint32_t, 16>(idx << 3);+ simd<uint32_t, 16> gh = slm_gather<uint32_t, 16>((idx << 3) + 4u);+ simd<uint32_t, 16> sbyte = (sgw >> (8 * il)) & 0xffu;+ simd<uint32_t, 16> vl = apply_signs(gl, sbyte & 0xfu);+ simd<uint32_t, 16> vh = apply_signs(gh, sbyte >> 4);+ if (il < 2) {+ fr0.template select<16, 1>(16 * (2 * il)) = vl;+ fr0.template select<16, 1>(16 * (2 * il + 1)) = vh;+ } else {+ fr1.template select<16, 1>(16 * (2 * il)) = vl;+ fr1.template select<16, 1>(16 * (2 * il + 1)) = vh;+ }+ }+ fr0.template select<64, 1>(64) = 0u;+ fr1.template select<64, 1>(0) = 0u;+ }+ }+#pragma unroll+ for (int i = 0; i < MT; ++i) {+ if (i < nvalid) {+ simd<int, 64> av = 0x01010101;+ simd<float, 8> dxv = 1.f;+ if (!(a.dbg & 2)) {+ av = slm_block_load<int, 64>(stage_off + i * 1024 + ib4 * 256, kAl16);+ dxv = slm_block_load<float, 8>(stage_off + L::ASZ + i * 128 + ib4 * 32, kAl16);+ }+ simd<float, 128> tf = dpas_s8(fr0, av);+#pragma unroll+ for (int r = 0; r < 8; ++r) {+ const float dxr = dxv[r];+ acc.template select<16, 1>(128 * i + 16 * r) += tf.template select<16, 1>(16 * r) * (sw0 * dxr);+ }+ if constexpr (NS == 2) {+ simd<float, 128> tg = dpas_s8(fr1, av);+#pragma unroll+ for (int r = 0; r < 8; ++r) {+ const float dxr = dxv[r];+ acc.template select<16, 1>(128 * i + 16 * r) += tg.template select<16, 1>(16 * r) * (sw1 * dxr);+ }+ }+ }+ }+ }+ if (c + 1 < nchunks) { STORE_CHUNK((c + 1) & 1); }+ barrier();+ }+#pragma unroll+ for (int i = 0; i < MT; ++i) {+ if (i < nvalid) {+#pragma unroll+ for (int r = 0; r < 8; ++r) {+ const int rl = (tl0 + i) * 8 + r;+ if (rl < cnt && !(a.dbg & 4))+ block_store<float, 16>(a.Y + ((size_t) (pk.row0 + rl)) * a.ldy + 16 * nt, acc.template select<16, 1>(128 * i + 16 * r));+ }+ }+ }+ });+ });+}++template <int F, int MT, int G>+void launch_dn_wg(sycl::queue& q, const GArgs a, int nrowblocks) {+ using L = WgLayout<F, MT>;+ auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<G>};+ q.submit([&](sycl::handler& h) {+ h.parallel_for<TagDnW<F, MT, G>>(sycl::nd_range<2>(sycl::range<2>((size_t) nrowblocks, (size_t) a.ntiles), sycl::range<2>(1, WGT)), props,+ [=](sycl::nd_item<2> it) SYCL_ESIMD_KERNEL {+ slm_init<L::TOTAL>();+ const int rbg = (int) it.get_group(0), lt = (int) it.get_local_id(1), nt = (int) it.get_global_id(1);+ const Pick pk = pick_expert(a, rbg);+ const int cnt = pk.cnt;+ const int ntl = (cnt + 7) >> 3;+ const int tl0 = (rbg - pk.rb0) * MT;+ const int nvalid = (ntl - tl0) < MT ? (ntl - tl0) : MT;+ const int tbase = pk.tile0 + tl0;+ const uint8_t* We = pk.blob;+ const uint32_t* T = a.tab;+ const int* Xi = reinterpret_cast<const int*>(a.Xq);+ constexpr uint32_t TOFF = (F == T_IQ4NL) ? O_IQ4 : O_Q2;+#pragma unroll+ for (int k = 0; k < tab_bytes<F>() / WGT / 64; ++k)+ slm_block_store<uint32_t, 16>(lt * (tab_bytes<F>() / WGT) + 64 * k, block_load<uint32_t, 16>(T + TOFF + (lt * (tab_bytes<F>() / WGT) + 64 * k) / 4, kAl16), kAl16);+ const int s_tile = lt / L::SPLIT, s_part = lt % L::SPLIT;+ simd<int, L::PART / 4> stg;+ simd<float, 32> stg_dx;+ simd<uint32_t, 16> lane(0, 1);+ simd<uint32_t, 16> ro = (lane + (uint32_t) (16 * nt)) * (uint32_t) a.rowb + a.sec_off;+ simd<float, 128 * MT> acc = 0.f;+ const int nchunks = (a.dbg & 8) ? 0 : (a.nkb >> 2);+ if (nchunks > 0) { LOAD_CHUNK(0); STORE_CHUNK(0); }+ barrier();+ for (int c = 0; c < nchunks; ++c) {+ const int stage_off = L::TB + (c & 1) * L::STAGE;+ if (c + 1 < nchunks) { LOAD_CHUNK(c + 1); }+#pragma unroll 1+ for (int ib4 = 0; ib4 < 4; ++ib4) {+ const int kb = c * 4 + ib4;+ simd<float, 16> sw0 = 1.f;+ simd<uint32_t, 128> fr0 = 0x01010101u;+ if (!(a.dbg & 1)) {+ if constexpr (F == T_IQ4NL) {+ const uint32_t P = (uint32_t) kb * 18;+ sw0 = half_of(ld16(We, ro + P));+#pragma unroll+ for (int j = 0; j < 4; ++j) {+ simd<uint32_t, 16> qd = ld32c(We, ro + (P + 2 + 4 * j), a.lim);+ simd<uint32_t, 16> t0 = slm_gather<uint32_t, 16>((qd & 0xffu) << 2);+ simd<uint32_t, 16> t1 = slm_gather<uint32_t, 16>(((qd >> 8) & 0xffu) << 2);+ simd<uint32_t, 16> t2 = slm_gather<uint32_t, 16>(((qd >> 16) & 0xffu) << 2);+ simd<uint32_t, 16> t3 = slm_gather<uint32_t, 16>((qd >> 24) << 2);+ fr0.template select<16, 1>(16 * j) = (t0 & 0xffu) | ((t1 & 0xffu) << 8) | ((t2 & 0xffu) << 16) | (t3 << 24);+ fr0.template select<16, 1>(16 * (j + 4)) =+ ((t0 >> 8) & 0xffu) | (t1 & 0xff00u) | ((t2 & 0xff00u) << 8) | ((t3 & 0xff00u) << 16);+ }+ } else { // T_Q2_0+ const uint32_t P = (uint32_t) (kb >> 1) * 18;+ const int hb = kb & 1;+ sw0 = half_of(ld16(We, ro + P));+ simd<uint32_t, 16> q0 = ld32c(We, ro + (P + 2 + 8 * hb), a.lim);+ simd<uint32_t, 16> q1 = ld32c(We, ro + (P + 6 + 8 * hb), a.lim);+#pragma unroll+ for (int r = 0; r < 8; ++r) {+ simd<uint32_t, 16> qb = ((r < 4 ? q0 : q1) >> (8 * (r & 3))) & 0xffu;+ fr0.template select<16, 1>(16 * r) = slm_gather<uint32_t, 16>(qb << 2);+ }+ }+ }+#pragma unroll+ for (int i = 0; i < MT; ++i) {+ if (i < nvalid) {+ simd<int, 64> av = 0x01010101;+ simd<float, 8> dxv = 1.f;+ if (!(a.dbg & 2)) {+ av = slm_block_load<int, 64>(stage_off + i * 1024 + ib4 * 256, kAl16);+ dxv = slm_block_load<float, 8>(stage_off + L::ASZ + i * 128 + ib4 * 32, kAl16);+ }+ simd<float, 128> tf = dpas_s8(fr0, av);+#pragma unroll+ for (int r = 0; r < 8; ++r) {+ const float dxr = dxv[r];+ acc.template select<16, 1>(128 * i + 16 * r) += tf.template select<16, 1>(16 * r) * (sw0 * dxr);+ }+ }+ }+ }+ if (c + 1 < nchunks) { STORE_CHUNK((c + 1) & 1); }+ barrier();+ }+#pragma unroll+ for (int i = 0; i < MT; ++i) {+ if (i < nvalid) {+#pragma unroll+ for (int r = 0; r < 8; ++r) {+ const int rl = (tl0 + i) * 8 + r;+ if (rl < cnt && !(a.dbg & 4))+ block_store<float, 16>(a.Y + ((size_t) (pk.row0 + rl)) * a.ldy + 16 * nt, acc.template select<16, 1>(128 * i + 16 * r));+ }+ }+ }+ });+ });+}+// MT from the group's mean number of 8-row tiles per expert.int pick_mt(const Layout& lo) {const double mean = lo.n ? (double) lo.tile0[lo.n] / lo.n : 0;@@ -406,6 +758,17 @@ int mt_for(const Layout& lo) {return mo ? mo : pick_mt(lo);}+// register mode per tile height: STRATA_I8_GRF=128 (more threads per EU, spills at MT 8) or 256; default 256+int wg_for() {+ static const int v = [] { const char* s = std::getenv("STRATA_I8_WG"); return s ? std::atoi(s) : 1; }();+ return v;+}+int grf_for(int mt) {+ static const int g = [] { const char* s = std::getenv("STRATA_I8_GRF"); return s ? std::atoi(s) : 256; }();+ (void) mt;+ return g == 128 ? 128 : 256;+}+template <class F>bool dispatch_mt(int mt, F&& f) {switch (mt) {@@ -444,10 +807,14 @@ void make_layout(Layout& lo, const int32_t* cnt, int n) {bool available(void* stream) {sycl::queue& q = *strata::q_of(stream);- static const bool ok = [&] {+ static std::mutex mu;+ static std::unordered_map<sycl::device, bool> per_dev;+ std::lock_guard<std::mutex> lk(mu);+ const sycl::device d = q.get_device();+ if (auto it = per_dev.find(d); it != per_dev.end()) return it->second;+ const bool ok = [&] {const char* v = std::getenv("STRATA_I8_FORCE");if (v && v[0] == '0') return false;- sycl::device d = q.get_device();if (!d.has(sycl::aspect::ext_intel_esimd)) return false;namespace mx = sycl::ext::oneapi::experimental::matrix;bool s8 = false;@@ -455,6 +822,7 @@ bool available(void* stream) {if (c.atype == mx::matrix_type::sint8 && c.btype == mx::matrix_type::sint8 && c.nsize == 16 && c.ksize == 32) s8 = true;return s8;}();+ per_dev[d] = ok;return ok;}@@ -464,9 +832,13 @@ size_t dx_bytes(const Layout& lo, int K) { return (size_t) lo.tile0[lo.n] * (K /bool workspace(const Layout& lo, int K, int n_ff, Workspace& ws, void* stream) {sycl::queue& q = *strata::q_of(stream);static std::mutex mu;- static Workspace cur;- static size_t cap_x = 0, cap_h = 0;+ struct St { Workspace cur; size_t cap_x = 0, cap_h = 0; };+ static std::unordered_map<sycl::device, St> per_dev;std::lock_guard<std::mutex> lk(mu);+ St& st = per_dev[q.get_device()];+ Workspace& cur = st.cur;+ size_t& cap_x = st.cap_x;+ size_t& cap_h = st.cap_h;const size_t nx = xq_bytes(lo, K), nh = xq_bytes(lo, n_ff);if (nx > cap_x || nh > cap_h) {q.wait();@@ -497,16 +869,19 @@ void quantize_rows(const uint16_t* X, const Layout& lo, int K, int8_t* Xq, floatq.submit([&](sycl::handler& h) {h.parallel_for<QuantTag>(sycl::range<2>((size_t) lo.tile0[lo.n], (size_t) a.nkb), [=](sycl::id<2> id) SYCL_ESIMD_KERNEL {const int T = (int) id[0], kb = (int) id[1];- int e = 0;- while (e + 1 < a.n && T >= a.tile0[e + 1]) ++e;- const int cnt = a.row0[e + 1] - a.row0[e];+ // the expert of tile T, by constant-index reads of the argument arrays (see pick_expert)+ int t0e = a.tile0[0], r0e = a.row0[0], r1e = a.row0[1];+#pragma unroll+ for (int i = 1; i < kMaxGroup; ++i)+ if (i < a.n && T >= a.tile0[i]) { t0e = a.tile0[i]; r0e = a.row0[i]; r1e = a.row0[i + 1]; }+ const int cnt = r1e - r0e;simd<float, 8> dxv = 0.f;#pragma unrollfor (int r = 0; r < 8; ++r) {- const int rl = (T - a.tile0[e]) * 8 + r;+ const int rl = (T - t0e) * 8 + r;simd<uint32_t, 8> qd = 0u;if (rl < cnt) {- simd<half, 32> xh = block_load<half, 32>(Xh + ((size_t) (a.row0[e] + rl)) * a.ld + kb * 32);+ simd<half, 32> xh = block_load<half, 32>(Xh + ((size_t) (r0e + rl)) * a.ld + kb * 32);simd<float, 32> x = xh;float amax = hmax<float>(abs(x));const float dd = amax / 127.f;@@ -539,16 +914,19 @@ void swiglu_quantize(const float* GU, const Layout& lo, int n_ff, int8_t* Hq, flq.submit([&](sycl::handler& h) {h.parallel_for<SwigluTag>(sycl::range<2>((size_t) lo.tile0[lo.n], (size_t) a.nkb), [=](sycl::id<2> id) SYCL_ESIMD_KERNEL {const int T = (int) id[0], kb = (int) id[1];- int e = 0;- while (e + 1 < a.n && T >= a.tile0[e + 1]) ++e;- const int cnt = a.row0[e + 1] - a.row0[e];+ // the expert of tile T, by constant-index reads of the argument arrays (see pick_expert)+ int t0e = a.tile0[0], r0e = a.row0[0], r1e = a.row0[1];+#pragma unroll+ for (int i = 1; i < kMaxGroup; ++i)+ if (i < a.n && T >= a.tile0[i]) { t0e = a.tile0[i]; r0e = a.row0[i]; r1e = a.row0[i + 1]; }+ const int cnt = r1e - r0e;simd<float, 8> dxv = 0.f;#pragma unrollfor (int r = 0; r < 8; ++r) {- const int rl = (T - a.tile0[e]) * 8 + r;+ const int rl = (T - t0e) * 8 + r;simd<uint32_t, 8> qd = 0u;if (rl < cnt) {- simd<float, 64> v = block_load<float, 64>(GU + ((size_t) (a.row0[e] + rl)) * a.ld + kb * 64);+ simd<float, 64> v = block_load<float, 64>(GU + ((size_t) (r0e + rl)) * a.ld + kb * 64);simd<float, 32> g = v.template select<32, 2>(0);simd<float, 32> u = v.template select<32, 2>(1);simd<float, 32> x = g * u / (1.f + exp(-g));@@ -591,9 +969,19 @@ bool gate_up(int gu_type, const uint8_t* const* blob, size_t up_off, int n_ff, cconst int rb = fill_args_mt(a, lo, mt);return dispatch_mt(mt, [&](auto mtc) {constexpr int MT = decltype(mtc)::value;- if (gu_type == T_IQ3S) launch_gu<T_IQ3S, MT>(q, a, rb);- else if (gu_type == T_IQ3XXS) launch_gu<T_IQ3XXS, MT>(q, a, rb);- else launch_gu<T_IQ2S, MT>(q, a, rb);+ if (wg_for() && gu_type != T_IQ2S && a.nkb % 4 == 0 && a.ntiles % WGT == 0) { // IQ2_S: its 8 KB codebook copied into local memory by every group costs more than it saves (35 vs 16 us)+ if (gu_type == T_IQ3S) launch_gu_wg<T_IQ3S, MT, 256>(q, a, rb);+ else if (gu_type == T_IQ3XXS) launch_gu_wg<T_IQ3XXS, MT, 256>(q, a, rb);+ else launch_gu_wg<T_IQ2S, MT, 256>(q, a, rb);+ } else if (grf_for(MT) == 128) {+ if (gu_type == T_IQ3S) launch_gu<T_IQ3S, MT, 128>(q, a, rb);+ else if (gu_type == T_IQ3XXS) launch_gu<T_IQ3XXS, MT, 128>(q, a, rb);+ else launch_gu<T_IQ2S, MT, 128>(q, a, rb);+ } else {+ if (gu_type == T_IQ3S) launch_gu<T_IQ3S, MT, 256>(q, a, rb);+ else if (gu_type == T_IQ3XXS) launch_gu<T_IQ3XXS, MT, 256>(q, a, rb);+ else launch_gu<T_IQ2S, MT, 256>(q, a, rb);+ }});}@@ -612,15 +1000,25 @@ bool down(int d_type, const uint8_t* const* blob, size_t down_off, int n_embd, ca.ntiles = n_embd / 16;a.nkb = n_ff / 32;a.rowb = (n_ff / block_vals_of(d_type)) * block_bytes_of(d_type);+ a.lim = (uint32_t) (down_off + (size_t) n_embd * (size_t) a.rowb) - 4u;a.ldy = n_embd;a.dbg = dbg_flags();const int mt = mt_for(lo);const int rb = fill_args_mt(a, lo, mt);return dispatch_mt(mt, [&](auto mtc) {constexpr int MT = decltype(mtc)::value;- if (d_type == T_IQ4NL) launch_dn<T_IQ4NL, MT>(q, a, rb);- else launch_dn<T_Q2_0, MT>(q, a, rb);+ if (wg_for() && a.nkb % 4 == 0 && a.ntiles % WGT == 0) {+ if (d_type == T_IQ4NL) launch_dn_wg<T_IQ4NL, MT, 256>(q, a, rb);+ else launch_dn_wg<T_Q2_0, MT, 256>(q, a, rb);+ } else if (grf_for(MT) == 128) {+ if (d_type == T_IQ4NL) launch_dn<T_IQ4NL, MT, 128>(q, a, rb);+ else launch_dn<T_Q2_0, MT, 128>(q, a, rb);+ } else {+ if (d_type == T_IQ4NL) launch_dn<T_IQ4NL, MT, 256>(q, a, rb);+ else launch_dn<T_Q2_0, MT, 256>(q, a, rb);+ }});}} // namespace strata::prefill::i8+#endif // STRATA_I8_NO_ESIMDdiff --git a/sycl/src/prefill/prefill.cpp b/sycl/src/prefill/prefill.cppindex 650dd77fc..6b9f5355d 100644--- a/sycl/src/prefill/prefill.cpp+++ b/sycl/src/prefill/prefill.cpp@@ -43,6 +43,11 @@#include <algorithm>#include <set>+#include <map>+#include <cmath>+#include <chrono>+#include <stdexcept>+#include <sys/stat.h>#include <tuple>#include <chrono>#include <cmath>@@ -797,6 +802,191 @@ strata::kernels::QsaAttnPools pools_of(const strata::kernels::KvHostPools& h, co}} // namespace++// ------------------------------------------------------------------------------------------------ 151-b70: int8 or FP16 experts+// STRATA_PREFILL_MMQ=auto picks per group of experts from the measured cost on THIS GPU: at the first layer of a given expert+// format the int8 chain (quantize, gate/up, SwiGLU + quantize, down) and the FP16 chain (dequantize, two GEMMs, SwiGLU) are timed on+// synthetic experts (random blobs of the layer's format and shape) at 16, 32, 64, 128 and 256 rows per expert, and the crossover+// (the mean rows per expert where the FP16 chain becomes the faster one, interpolated on the cost ratio) is kept, with a flag for+// how clear the measurement was. It is cached in a small text file (STRATA_CACHE_DIR, else ~/.cache/strata/i8-crossover.txt) keyed by+// device name, driver, formats and shape, and read back instead of measured when the key matches.+namespace {+struct I8Cross { double rows = 0; bool confident = false; bool measured = false; };++std::string i8_cache_file() {+ const char* d = std::getenv("STRATA_CACHE_DIR");+ std::string dir;+ if (d && d[0]) dir = d;+ else if (const char* h = std::getenv("HOME")) dir = std::string(h) + "/.cache/strata";+ else if (const char* a = std::getenv("LOCALAPPDATA")) dir = std::string(a) + "/strata";+ else return "";+ return dir + "/i8-crossover.txt";+}+bool i8_cache_read(const std::string& key, I8Cross& out) {+ const std::string path = i8_cache_file();+ if (path.empty()) return false;+ std::FILE* f = std::fopen(path.c_str(), "r");+ if (!f) return false;+ char line[700];+ bool ok = false;+ while (std::fgets(line, sizeof line, f)) {+ char k[600]; double rows; int conf;+ if (std::sscanf(line, "%599[^\t]\t%lf\t%d", k, &rows, &conf) == 3 && key == k) { out.rows = rows; out.confident = conf != 0; ok = true; }+ }+ std::fclose(f);+ return ok;+}+void i8_cache_write(const std::string& key, const I8Cross& c) {+ const std::string path = i8_cache_file();+ if (path.empty()) return;+ const std::string dir = path.substr(0, path.rfind('/'));+ std::vector<std::string> keep; // the other keys' lines+ if (std::FILE* f = std::fopen(path.c_str(), "r")) {+ char line[700];+ while (std::fgets(line, sizeof line, f)) {+ std::string s(line);+ if (s.compare(0, key.size() + 1, key + "\t") != 0) keep.push_back(s);+ }+ std::fclose(f);+ }+ std::FILE* f = std::fopen(path.c_str(), "w");+ if (!f) {+ ::mkdir(dir.c_str(), 0755);+ f = std::fopen(path.c_str(), "w");+ if (!f) return;+ }+ for (auto& s : keep) std::fputs(s.c_str(), f);+ std::fprintf(f, "%s\t%.1f\t%d\n", key.c_str(), c.rows, c.confident ? 1 : 0);+ std::fclose(f);+}++template <class M>+I8Cross i8_calibrate(M& m, const strata::kernels::cpu::NativeFmt& f) {+ namespace i8 = strata::prefill::i8;+ sycl::queue& q = *m.cs;+ const std::string dev = q.get_device().template get_info<sycl::info::device::name>() + "|" ++ q.get_device().template get_info<sycl::info::device::driver_version>();+ char keyb[600];+ std::snprintf(keyb, sizeof keyb, "%s|%d|%d|%lldx%lld", dev.c_str(), f.gu_type, f.d_type, (long long) f.n_ff, (long long) f.n_embd);+ const std::string key = keyb;+ I8Cross res;+ if (i8_cache_read(key, res)) {+ std::fprintf(stderr, "strata: int8 experts: crossover %.0f rows per expert (%s) from the cache for %s\n", res.rows,+ res.confident ? "clear" : "not clear", key.c_str());+ return res;+ }+ constexpr int E = 8;+ const int rows_list[5] = {16, 32, 64, 128, 256};+ const int N = (int) f.n_embd, NF = (int) f.n_ff;+ double t8[5] = {}, t16[5] = {};+ const double facs[E] = {0.15, 0.35, 0.6, 0.85, 1.1, 1.4, 1.8, 2.45};+ double fac[E];+ std::vector<uint8_t*> blobs(E, nullptr);+ uint16_t *X = nullptr, *Hh = nullptr;+ float *GU = nullptr, *Dm = nullptr;+ bool ok = true;+ try {+ // rows per expert are uneven like a real group (a few big experts and many small ones): factors of the mean, mean 1+ for (int i = 0; i < E; ++i) { fac[i] = facs[i] / 1.0875; }+ size_t rmax = 0;+ for (int i = 0; i < E; ++i) rmax += (size_t) std::max(1.0, 256.0 * fac[i] + 0.5) + 8; // rows of the largest sample (plus padding)+ for (int i = 0; i < E; ++i) blobs[i] = sycl::malloc_device<uint8_t>(f.bytes + 256, q);+ X = sycl::malloc_device<uint16_t>(rmax * N, q);+ Hh = sycl::malloc_device<uint16_t>(rmax * NF, q);+ GU = sycl::malloc_device<float>(rmax * 2 * NF, q);+ Dm = sycl::malloc_device<float>(rmax * N, q);+ for (int i = 0; i < E; ++i) ok = ok && blobs[i];+ ok = ok && X && Hh && GU && Dm;+ if (!ok) throw std::runtime_error("no VRAM for the measurement");+ // synthetic experts: random bytes with a sane fp16 scale at every block start (the cost does not depend on the values)+ std::vector<uint8_t> hb(f.bytes + 256);+ uint32_t s = 12345;+ auto rnd = [&] { s = s * 1664525u + 1013904223u; return s >> 8; };+ for (size_t i = 0; i < hb.size(); ++i) hb[i] = (uint8_t) rnd();+ const int gb = f.gu_type == 21 ? 110 : f.gu_type == 18 ? 98 : 82;+ for (size_t o = 0; o + 2 <= f.up_off * 2 && o < hb.size(); o += gb) { hb[o] = 0x00; hb[o + 1] = 0x2C; }+ for (size_t o = f.down_off; o + 2 <= f.bytes; o += 18) { hb[o] = 0x00; hb[o + 1] = 0x2C; }+ for (int i = 0; i < E; ++i) q.memcpy(blobs[i], hb.data(), f.bytes);+ std::vector<uint16_t> hx(rmax * N);+ for (auto& x : hx) x = (uint16_t) (0x3400 + (rnd() & 0x3ff)); // ~0.25..0.5, no zeros+ q.memcpy(X, hx.data(), hx.size() * 2);+ q.wait();+ auto timeit = [&](auto&& fn) {+ fn(); q.wait();+ const auto w0 = std::chrono::steady_clock::now();+ while (std::chrono::duration<double>(std::chrono::steady_clock::now() - w0).count() < 0.02) { fn(); q.wait(); }+ double best = 1e30;+ for (int r = 0; r < 4; ++r) {+ const auto t0 = std::chrono::steady_clock::now();+ fn(); q.wait();+ best = std::min(best, std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count());+ }+ return best;+ };+ for (int ri = 0; ri < 5; ++ri) {+ const int R = rows_list[ri];+ int32_t cnt[i8::kMaxGroup];+ for (int i = 0; i < E; ++i) cnt[i] = std::max(1, (int) (R * fac[i] + 0.5));+ i8::Layout lo;+ i8::make_layout(lo, cnt, E);+ i8::Workspace ws;+ if (!i8::workspace(lo, N, NF, ws, &q)) throw std::runtime_error("workspace");+ std::vector<const uint8_t*> pb(E);+ for (int i = 0; i < E; ++i) pb[i] = blobs[i];+ bool refused = false;+ t8[ri] = timeit([&] {+ i8::quantize_rows(X, lo, N, ws.xq, ws.dx, &q);+ if (!i8::gate_up(f.gu_type, pb.data(), f.up_off, NF, lo, N, ws.xq, ws.dx, GU, &q)) refused = true;+ i8::swiglu_quantize(GU, lo, NF, ws.hq, ws.dh, &q);+ if (!i8::down(f.d_type, pb.data(), f.down_off, N, lo, NF, ws.hq, ws.dh, Dm, &q)) refused = true;+ }) / E;+ if (refused) throw std::runtime_error("the int8 kernels refused this format");+ t16[ri] = timeit([&] {+ int64_t o = 0;+ for (int i = 0; i < E; ++i) {+ const int qd = i % DQ;+ strata::kernels::iq_dequant_expert_f16(f.gu_type, f.d_type, blobs[i], blobs[i] + f.up_off, blobs[i] + f.down_off, NF, N,+ m.dq_gu[qd], m.dq_d[qd], &q);+ m.gemm.f16(X + o * N, m.dq_gu[qd], GU + o * 2 * NF, cnt[i], 2 * NF, N);+ strata::prefill::swiglu_interleaved(GU + o * 2 * NF, Hh + o * NF, cnt[i], &q);+ m.gemm.f16(Hh + o * NF, m.dq_d[qd], Dm + o * N, cnt[i], N, NF);+ o += cnt[i];+ }+ }) / E;+ }+ } catch (const std::exception& e) {+ std::fprintf(stderr, "strata: int8 experts: the crossover measurement failed (%s): the int8 path is used below 64 rows per expert\n", e.what());+ ok = false;+ }+ for (auto* b : blobs) if (b) sycl::free(b, q);+ if (X) sycl::free(X, q);+ if (Hh) sycl::free(Hh, q);+ if (GU) sycl::free(GU, q);+ if (Dm) sycl::free(Dm, q);+ if (!ok) { res.rows = 64; res.confident = false; return res; }+ // crossover: the first R where the FP16 chain is the faster one, interpolated in log(ratio) between the two bracketing sizes+ double ratio[5];+ for (int i = 0; i < 5; ++i) ratio[i] = t16[i] / t8[i]; // > 1: int8 faster+ int first = -1;+ for (int i = 0; i < 5; ++i) if (ratio[i] < 1.0) { first = i; break; }+ if (first < 0) res.rows = 512; // int8 wins everywhere measured+ else if (first == 0) res.rows = 0; // FP16 wins even at 16 rows+ else {+ const double a = std::log(ratio[first - 1]), b = std::log(ratio[first]);+ const double t = a / (a - b);+ res.rows = std::exp(std::log((double) rows_list[first - 1]) + t * (std::log((double) rows_list[first]) - std::log((double) rows_list[first - 1])));+ }+ // clear: the ratio falls with the rows (within 5%) and the samples bracketing the crossover are at least 5% away from 1+ bool mono = true;+ for (int i = 1; i < 5; ++i) if (ratio[i] > ratio[i - 1] * 1.05) mono = false;+ res.confident = mono && (first < 0 ? ratio[4] > 1.05 : first == 0 ? ratio[0] < 0.95 : (ratio[first - 1] > 1.05 && ratio[first] < 0.95));+ res.measured = true;+ std::fprintf(stderr, "strata: int8 experts, measured here (%s): us per expert at 16/32/64/128/256 rows, int8 %.1f/%.1f/%.1f/%.1f/%.1f, FP16 %.1f/%.1f/%.1f/%.1f/%.1f -> crossover %.0f rows per expert (%s)\n",+ key.c_str(), t8[0], t8[1], t8[2], t8[3], t8[4], t16[0], t16[1], t16[2], t16[3], t16[4], res.rows, res.confident ? "clear" : "not clear");+ i8_cache_write(key, res);+ return res;+}+} // namespacePrefill::Prefill() : impl_(new Impl) {}Prefill::~Prefill() { release(); }@@ -4000,28 +4190,62 @@ bool Prefill::run_impl(const int64_t *tokens, int64_t n, int64_t pos0,int64_t nr = 0;for (int i = 0; i < xg_n; ++i) nr += xg_c[i];if (i8on) {- if (static bool said = false; !said) {- said = true;- std::fprintf(stderr, "strata: prompt experts on the fused int8 DPAS products (STRATA_PREFILL_MMQ=1)\n");+ // STRATA_PREFILL_MMQ=1: always; =auto: while the group's mean rows per expert are under the crossover+ // measured on this GPU (i8_calibrate); a group above it takes the FP16 chain below+ bool use_i8 = true;+ if (i8_mode() == 2) {+ static std::map<std::tuple<const void*, int, int>, I8Cross> xover; // per queue (a layer split has a card per queue)+ auto it = xover.find({(const void*) m.cs, f.gu_type, f.d_type});+ if (it == xover.end()) it = xover.emplace(std::make_tuple((const void*) m.cs, f.gu_type, f.d_type), i8_calibrate(m, f)).first;+ use_i8 = (double) nr / xg_n < it->second.rows;+ static long groups_i8 = 0, groups_fp = 0;+ (use_i8 ? groups_i8 : groups_fp) += 1;+ if (static bool said_n = false; !said_n && groups_i8 + groups_fp >= 500) {+ said_n = true;+ std::fprintf(stderr, "strata: int8 experts (auto): %ld groups took the int8 chain, %ld the FP16 chain\n", groups_i8, groups_fp);+ }}- namespace i8 = strata::prefill::i8;- i8::Layout lo8;- i8::make_layout(lo8, xg_c, xg_n);- i8::Workspace ws8;- const bool ws_ok = i8::workspace(lo8, (int) N, f.n_ff, ws8, m.cs);- pt.mark(kPfGemmGU, cs);- if (ws_ok &&- (i8::quantize_rows(m.Xs + xg_r0 * N, lo8, (int) N, ws8.xq, ws8.dx, m.cs), true) &&- i8::gate_up(f.gu_type, xg_g, f.up_off, f.n_ff, lo8, (int) N, ws8.xq, ws8.dx,- m.GU + xg_r0 * 1280, m.cs)) {- i8::swiglu_quantize(m.GU + xg_r0 * 1280, lo8, f.n_ff, ws8.hq, ws8.dh, m.cs);- pt.mark(kPfGemmD, cs);- i8::down(f.d_type, xg_g, f.down_off, (int) N, lo8, f.n_ff, ws8.hq, ws8.dh,- m.Dm + xg_r0 * N, m.cs);- } else {- std::fprintf(stderr, "strata: the int8 expert products refused layer %lld (workspace %d)\n",- (long long) l, (int) ws_ok);- std::exit(1);+ bool done8 = false;+ if (use_i8) {+ if (static bool said = false; !said) {+ said = true;+ std::fprintf(stderr, "strata: prompt experts on the fused int8 DPAS products (STRATA_PREFILL_MMQ=%s)\n",+ i8_mode() == 2 ? "auto" : "1");+ }+ namespace i8 = strata::prefill::i8;+ i8::Layout lo8;+ i8::make_layout(lo8, xg_c, xg_n);+ i8::Workspace ws8;+ pt.mark(kPfGemmGU, cs);+ if (i8::workspace(lo8, (int) N, f.n_ff, ws8, m.cs)) {+ i8::quantize_rows(m.Xs + xg_r0 * N, lo8, (int) N, ws8.xq, ws8.dx, m.cs);+ if (i8::gate_up(f.gu_type, xg_g, f.up_off, f.n_ff, lo8, (int) N, ws8.xq, ws8.dx, m.GU + xg_r0 * 1280, m.cs)) {+ i8::swiglu_quantize(m.GU + xg_r0 * 1280, lo8, f.n_ff, ws8.hq, ws8.dh, m.cs);+ pt.mark(kPfGemmD, cs);+ done8 = i8::down(f.d_type, xg_g, f.down_off, (int) N, lo8, f.n_ff, ws8.hq, ws8.dh, m.Dm + xg_r0 * N, m.cs);+ }+ }+ if (!done8) {+ if (static bool said_f = false; !said_f) {+ said_f = true;+ std::fprintf(stderr, "strata: the int8 expert products could not run (layer %lld, no workspace or a format they do not handle): the FP16 chain is used\n", (long long) l);+ }+ }+ }+ if (!done8) { // the FP16 chain: dequantize, two oneMKL GEMMs, SwiGLU, per expert+ int64_t o = xg_r0;+ for (int i = 0; i < xg_n; ++i) {+ const int qd = i % DQ;+ pt.mark(kPfDequant, cs);+ strata::kernels::iq_dequant_expert_f16(f.gu_type, f.d_type, xg_g[i], xg_u[i], xg_d[i], f.n_ff, f.n_embd,+ m.dq_gu[qd], m.dq_d[qd], m.cs);+ pt.mark(kPfGemmGU, cs);+ m.gemm.f16(m.Xs + o * N, m.dq_gu[qd], m.GU + o * 1280, xg_c[i], 1280, N);+ swiglu_interleaved(m.GU + o * 1280, m.Hh + o * 640, xg_c[i], m.cs);+ pt.mark(kPfGemmD, cs);+ m.gemm.f16(m.Hh + o * 640, m.dq_d[qd], m.Dm + o * N, xg_c[i], N, 640);+ o += xg_c[i];+ }}if (xg_ns > 0) {const int rel = xg_slots[xg_ns - 1];