diff --git a/docs/INTEL.md b/docs/INTEL.md index 41967e5e..1fd07148 100644 --- a/docs/INTEL.md +++ b/docs/INTEL.md @@ -881,3 +881,61 @@ gate identical in the 32K and the 128K configuration); every one has an off swit | decode | 23-25 tok/s; GPU 92% busy at 165 W, CPU idle | | prefill | 149 tok/s on a 2,701-token prompt; 424 tok/s on a 104,798-token prompt at 131k context | | quality | correct code on every test; matches the NVIDIA path token for token in spirit, not measured | + +## Arc Pro B70: `--prefill 8192` in the long-context config (2026-10-18, branch f-151-b70) + +`setup_intel.py` now recommends 8,192-token prompt chunks for a Battlemage card with 24 GB or more when the context is over 32K (the +prompt borrows cache slots; `recommended_prefill()`), 4,096 everywhere else, and it keeps a chunk size you put in the config. +Arc Pro B70, IQ3_S, setup's 128K flags (`--kv-resident 32768 --vram-reserve-mib 2048`), `--pcie-frac 0 --adapt-every 0`, 2 rounds, +32 greedy tokens after the prompt (identical in every run): + +| prompt | `--prefill 4096` | `--prefill 8192` | cache slots | decode after | +|---|---|---|---|---| +| 16K | 1,222 tok/s | 1,347-1,362 (+10-11%) | 11,795 both | 33-38 / 38 | +| 32K | 1,187 | 1,361-1,383 (+15-16%) | 11,794-11,795 both | 35 / 38.6 | + +The lent slots are refilled after the prompt, so the bigger chunk costs the decode nothing. First-token logits against 4096 +(`STRATA_DUMP_FIRST_LOGITS`, whole vocabulary): KL 1.1e-2 nats at 16K and 3.0e-2 at 32K, top-1 the same, largest logit +difference 1.0 (the chunk boundary moves where the QSA block selection is made, so a different chunk size is not bit-identical; +two runs of the same size are, KL 0). With the 32K context (own prompt buffers, no borrowing) a bigger chunk is +20% on a 16K +prompt (1,236 -> 1,478-1,482) but takes 1,397 cache slots (10,926 -> 9,529) and decode after it falls 9-16%, so 4,096 stays there. + +## Arc Pro B70: the fused int8 expert path for the prompt (2026-10-18, branch f-151-b70, default on for Battlemage) + +On a Battlemage GPU (B70, B580, B570: detected by the device architecture id, `bmg-g21` and `bmg-g31`, not by name) the engine computes the routed experts of the prompt with ESIMD kernels that decode the quantized weights in +registers straight into the s8 DPAS B operand (no FP16 copy of the expert, 2.1 MB of weights read instead of 9.8 MB written and read +back) and multiply them by q8_1-quantized activations; `sycl/src/prefill/esimd_moe.dp.cpp`, behaviour note and switches in +[INTEL_INT8_EXPERTS.md](INTEL_INT8_EXPERTS.md). Gate/up IQ3_S, IQ3_XXS, IQ2_S and down IQ4_NL, Q2_0 are covered (47 of the 48 layers of +the mixed IQ3_S pack; the other layer, IQ4_XS gate/up, and any other format keep the FP16 path). Default (STRATA_PREFILL_MMQ unset) is `auto` on Battlemage and the FP16 chain on every other GPU (Alchemist A750 / A770, Lunar Lake, other vendors); `=0` turns it off, `=1` forces it, `=auto` is the default. The activations are +quantized, so the bits differ from the FP16 path. `auto` times both chains on this GPU at the first layer of each format and takes int8 +below the measured crossover (130-250 rows per expert here), per group of experts. + +Arc Pro B70, IQ3_S pack, 32K config, `--prefill 4096`, fixed flags (`STRATA_PREFILL_CPU_SHARE=0 STRATA_ROUTE_TAIL_SKIP=0 --pcie-frac 0 +--adapt-every 0`), 5 interleaved rounds per size, prefill tok/s (medians; the noise arm is the default run again): + +| prompt | default | noise arm | `=1` | `=auto` | +|---|---|---|---|---| +| 1,024 tokens | 645.8 | 648.3 | 775.4 (+20%) | 783.5 (+21%) | +| 4,095 tokens | 1,257.0 | 1,256.8 | 1,413.8 (+12.5%) | 1,407.7 (+12.0%) | + +The output tokens are identical in all runs. Quality (teacher-forced KL against the FP16 path over 6,002 positions of 28 prompts): mean +2e-4 nats, p99 6e-3, top-1 99.7%, perplexity ratio 1.0004; a `--prefill 8192` chunk moves the first-token distribution by 1e-2 to 3e-2 +for comparison. At more than ~130 rows per expert (a chunk of 8,192 tokens or more) the int8 chain stops winning because every row block +decodes the weights again (1.03x at 194 rows against 1.4-1.9x at 60): use `auto`. + +### Arc Pro B70, what else was measured on the prompt path (2026-10-18, branch f-151-b70) + +All on the 4,095-token IQ3_S prompt, 32K config, `--prefill 4096`, fixed flags, 3-4 interleaved rounds with a noise arm (prefill tok/s, +medians, output tokens identical in every arm): + +| change | result | +|---|---| +| `STRATA_GDN_XE=1` (variant 6, the sub-group recurrence that is the default on Alchemist; bit-identical) | 1,251 -> 1,207 (-3.5%): stays off on Battlemage | +| `STRATA_PROMPT_ATTN_XMX=1` / `=32` (the joint_matrix prompt attention, 64- / 32-cell chunks) | 1,258 -> 952 / 913 (-24% / -27%): stays opt-in | +| QSA prompt attention, probabilities stored `[cell][head]` and read as three vectors per cell in the value phase (`STRATA_ATTN_RS=2`, now the default; first-token logits md5 equal at 4K and 16K) | 1,254 -> 1,265 (+0.9%, 3 of 3 rounds) | +| the same plus a 16-shuffle reduce-scatter of the 12 heads' score sums (`STRATA_ATTN_RS=1`; also bit-exact) | 1,254 -> 1,236 (-1.5%): the score phase is not shuffle bound | +| int8 expert groups of 24 or 32 experts instead of 16 | 1,416 -> 1,420 / 1,416: no effect | +| K-quant / Q5_1 / Q8_0 multi-entry decode kernels (`STRATA_KQ_SPLIT`, on by default; bit-identical to `=0`), `native_grouped_parity --kqbench 16`, synthetic UD-Q4_K_XL-shaped experts | 1 token: 76.4 vs 75.0 us (-1.8%); 2 tokens: 122.5 vs 135.9 us (+10%); 4 tokens (an MTP window): 202.6 vs 233 us (+13%); Q6_K 4 tokens 387 vs 485 (+20%), Q8_0 290 vs 341 (+15%) | + +The B70's int8 expert kernels also build and pass the parity test as a SPIR-V JIT build and as an AOT build for `bmg-g21` (compile only: no +G21 card here); an AOT build for another device (Alchemist, Xe-HPC) gets stubs (`STRATA_I8_NO_ESIMD`). diff --git a/docs/INTEL_INT8_EXPERTS.md b/docs/INTEL_INT8_EXPERTS.md new file mode 100644 index 00000000..aea0da14 --- /dev/null +++ b/docs/INTEL_INT8_EXPERTS.md @@ -0,0 +1,89 @@ +# Fused int8 DPAS expert products on Battlemage (branch f-151-b70) + +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 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`: 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` (the Battlemage default): 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 (unset): `auto` on a Battlemage GPU (bmg-g21 or bmg-g31 by the SYCL architecture id, not by name; the kernels must be in the binary and pass `available()`), the FP16 path on every other GPU. The engine prints one line at load ("int8 prompt experts are on ... STRATA_PREFILL_MMQ=0 turns them off"). If the kernels are not in the binary for the device (an AOT build for other devices) or a launch throws, the group and the rest of the process take the FP16 chain with one log line. 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) 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, 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 + +* 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` 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.txt index ba639519..b5570d21 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-HPC endif() +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 @@ -245,7 +248,8 @@ target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_ker strata_resolve(_prefill src/prefill/gemm.cu src/prefill/kernels.cu src/prefill/prefill.cpp) add_library(strata_prefill STATIC ${_prefill} ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/moe_fused_stub.cpp # upstream's fused int8 kernels: not built here - ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/xmx_moe.dp.cpp) # A770 port: grouped XMX expert GEMM + ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/xmx_moe.dp.cpp # A770 port: grouped XMX expert GEMM + ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/esimd_moe.dp.cpp) # 151-b70: fused int8 DPAS expert products (ESIMD, Battlemage) target_compile_options(strata_prefill PUBLIC -qmkl=sequential) target_link_options(strata_prefill PUBLIC -qmkl=sequential) target_link_libraries(strata_prefill PUBLIC strata_engine) @@ -387,6 +391,16 @@ if(STRATA_SYCL_PARITY) target_link_libraries(xmx_gemm_bench PRIVATE strata_kernels strata_prefill) # -qmkl for the oneMKL reference add_executable(xmx_group_parity ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/xmx_group_parity.cpp) # A770: fused grouped XMX 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 FP64 + target_link_libraries(esimd_moe_parity PRIVATE strata_kernels strata_prefill) + 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 + add_executable(esimd_moe_mode_test ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/esimd_moe_mode_test.cpp) # 151-b70: the default choice of the expert chain (no GPU) + target_include_directories(esimd_moe_mode_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) + add_test(NAME esimd_moe_mode_test COMMAND esimd_moe_mode_test) + 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 [layer ...] if(STRATA_NATIVE_EXPERTS) diff --git a/sycl/include/strata/prefill/esimd_moe.hpp b/sycl/include/strata/prefill/esimd_moe.hpp new file mode 100644 index 00000000..e2a28723 --- /dev/null +++ b/sycl/include/strata/prefill/esimd_moe.hpp @@ -0,0 +1,82 @@ +// 151-b70: fused int8 DPAS expert products for the prompt path of the SYCL port (Battlemage, ESIMD). +// +// A group of experts' gate/up and down products straight from their quantized blobs: the weights are decoded in registers into +// the DPAS B operand (int8, one decode per 16 output rows and 32 of K), the activations are int8 with a float scale per 32 of K +// (llama.cpp's q8_1 grid, rounding half away from zero), each 32-block's int32 dot product is converted and scaled in float. +// The FP16 weights never exist in memory. The bits differ from the dequantize + oneMKL path (activations are quantized): the +// caller keeps it opt-in until a quality check (docs/INTEL.md, "int8 expert path"). +// +// Row layout. A group's rows are the experts' rows back to back (cnt[0], cnt[1], ... rows, as the FP16 path has them). The +// int8 activations are stored per expert padded to a multiple of 8 rows, in DPAS A-operand order: +// Xq [padded rows / 8][K / 32][8 rows x 8 dwords] dx [padded rows / 8][K / 32][8 floats] +// so one 256-byte block load is an 8x32 A tile. Pad rows are zero. +#pragma once +#include +#include + +namespace strata::prefill::i8 { + +constexpr int kMaxGroup = 16; + +/// Per group: the experts' row counts and where their (8-row padded) tiles start. +struct Layout { + int n = 0; + int cnt[kMaxGroup] = {}; + int row0[kMaxGroup + 1] = {}; // first row of expert i (unpadded), row0[n] = total rows + int tile0[kMaxGroup + 1] = {}; // first 8-row tile of expert i in the padded layout, tile0[n] = total tiles +}; +void make_layout(Layout& lo, const int32_t* cnt, int n); + +/// True when this device can run the kernels (a Battlemage-class device: sub-group 16 and the s8 DPAS 8x16x32). +bool available(void* stream); +/// True when this device is a Battlemage GPU by its architecture id (bmg-g21: B580 / B570, bmg-g31: B70), not by its name. The default +/// choice below uses it: Lunar Lake and the other Xe2 parts can run the kernels (`available`) but are not defaulted. False in a build +/// without the ESIMD kernels (STRATA_I8_NO_ESIMD). +bool battlemage(void* stream); +/// True when any GPU on this machine is a Battlemage one (sizes the staging ring before a queue exists). +bool any_battlemage(); + +/// Which chain the prompt experts take. `env` is STRATA_PREFILL_MMQ (else STRATA_PF_I8), null or empty when unset. Returns 0 = the +/// FP16 chain (dequantize + oneMKL), 1 = the int8 chain everywhere, 2 = auto (int8 per group while the group's rows per expert are under +/// the crossover measured on this GPU). Set: "0" -> 0, "auto" -> 2, any other number -> 1. Unset: auto on a Battlemage device whose +/// kernels are in the binary and run, else 0 (Alchemist and every other GPU keep the FP16 chain). +inline int choose_mode(const char* env, bool battlemage_device, bool kernels_available) { + if (env != nullptr && env[0] != 0) { + if (env[0] == 'a' || env[0] == 'A') return 2; + long v = 0; + for (const char* c = env; *c >= '0' && *c <= '9' && v < 1000000; ++c) v = v * 10 + (*c - '0'); + return v != 0 ? 1 : 0; + } + return (battlemage_device && kernels_available) ? 2 : 0; +} + +size_t xq_bytes(const Layout& lo, int K); // int8 activations, padded tiles +size_t dx_bytes(const Layout& lo, int K); // their scales (floats) + +/// Scratch for one group: int8 activation tiles + scales for the gate/up input (K) and for the down input (n_ff). Grow-only, +/// owned by the library (device USM on the queue's device). +struct Workspace { + int8_t* xq = nullptr; + float* dx = nullptr; + int8_t* hq = nullptr; + float* dh = nullptr; +}; +bool workspace(const Layout& lo, int K, int n_ff, Workspace& ws, void* stream); + +/// FP16 rows X[row0[n]][K] -> int8 tiles + scales. +void quantize_rows(const uint16_t* X, const Layout& lo, int K, int8_t* Xq, float* dx, void* stream); + +/// GU[row][v] (FP32, row stride 2 * n_ff), v = 2 r gate row r, 2 r + 1 up row r (the interleave swiglu_interleaved reads), for the +/// rows of the group. blob[i] holds expert i's gate rows at 0 and its up rows at up_off (ggml IQ3_S rows, K a multiple of 256). +/// Returns false when the type / shape is not handled (the caller keeps its other path). +bool gate_up(int gu_type, const uint8_t* const* blob, size_t up_off, int n_ff, const Layout& lo, int K, const int8_t* Xq, + const float* dx, float* GU, void* stream); + +/// Hq / dh: silu(gate) * up from GU (FP32, interleaved) quantized per 32 of n_ff into the same tile layout (K = n_ff). +void swiglu_quantize(const float* GU, const Layout& lo, int n_ff, int8_t* Hq, float* dh, void* stream); + +/// Dm[row][n_embd] (FP32) = Hq . down^T, down rows (n_embd of them, K = n_ff) in ggml type d_type at blob[i] + down_off. +bool down(int d_type, const uint8_t* const* blob, size_t down_off, int n_embd, const Layout& lo, int n_ff, const int8_t* Hq, + const float* dh, float* Dm, void* stream); + +} // namespace strata::prefill::i8 diff --git a/sycl/setup_intel.py b/sycl/setup_intel.py index 1fd8bb87..2c1f8c2a 100644 --- a/sycl/setup_intel.py +++ b/sycl/setup_intel.py @@ -145,6 +145,23 @@ def split_likely_short(arena_gb: float, vram_gbs: list) -> bool: return arena_gb > 0 and total > 0 and arena_gb > SPLIT_SHORT_FRACTION * total +PREFILL_BMG_MIN_GB = 24.0 # a Battlemage card with this much VRAM runs the prompt in 8,192-token chunks (to_sycl) + + +def recommended_prefill(vram_gb: float, ctx: int, driver: str = "xe", devid: str = "") -> tuple: + """(chunk size, one plain line saying why or ""). 4096 everywhere (to_sycl's old rule), except a Battlemage card (xe + driver, not an A-series) with 24 GB or more and a context over 32K, where the prompt borrows cache slots: 8192. + Measured on the Arc Pro B70 (IQ3_S, 128K context, setup's flags, 2 interleaved rounds): a 16K prompt 1,222 -> 1,347-1,362 + tok/s (+10-11%), a 32K prompt 1,187 -> 1,361-1,383 (+15-16%), the same 32 greedy tokens, the same 11,795 cache slots (the + lent slots are refilled after the prompt), decode after it unchanged (38 tok/s). With the 32K context (own prompt + buffers) a bigger chunk takes 1,400 cache slots from the decode (-9..-16% decode for +20% prompt), so that stays 4096.""" + bmg = driver != "i915" and devid not in ALCHEMIST_IDS and devid in INTEL_ARC + if bmg and vram_gb >= PREFILL_BMG_MIN_GB and ctx > 32768: + return 8192, ("prompt reading: chunks of 8,192 tokens on this Arc (the prompt borrows cache slots, so decode keeps all " + "of them): 10-16% faster on 16K-32K prompts than 4,096 (change --prefill in the config to pick another)") + return 4096, "" + + def to_sycl(cfg: dict, exe: Path, ram: float, keep: dict, vram_gb: float = 0.0, driver: str = "xe", devid: str = "") -> dict: """setup's config (written for its HIP path) -> the SYCL port's: the container's paths, experts streamed from the @@ -198,10 +215,13 @@ def to_sycl(cfg: dict, exe: Path, ram: float, keep: dict, vram_gb: float = 0.0, else: args += ["--stream-experts", "--vram-reserve-mib", reserve] if ctx > 32768 or vram_gb >= 24: # long contexts: 4096-token chunks keep the prompt buffers small; a - drop(args, "--prefill", True) # 24 GB+ card with part of the experts in the RAM mirror streams those - args += ["--prefill", "4096"] # over PCIe once per chunk, so fewer, bigger chunks read the prompt - # faster (Arc Pro B70, IQ3_S, a 4,095-token prompt: 2,048-token - # chunks 618 tok/s, 4,096: 1,002; docs/INTEL.md); it costs ~700 cache slots + # 24 GB+ card with part of the experts in the RAM mirror streams those over PCIe once per chunk, so fewer, bigger + # chunks read the prompt faster (Arc Pro B70, IQ3_S, a 4,095-token prompt: 2,048-token chunks 618 tok/s, 4,096: 1,002; + # docs/INTEL.md); it costs ~700 cache slots. A Battlemage card with the prompt borrowing cache slots reads 8,192. + # A chunk size the user already put in the config is kept: this is a recommendation, not a rule. + if flag(args, "--prefill") in (None, "auto", "2048", "4096", "8192"): + drop(args, "--prefill", True) + args += ["--prefill", str(recommended_prefill(vram_gb, ctx, driver, devid)[0])] out = {k: v for k, v in cfg.items() if k not in ("lib_dirs", "env", "vision", "gpus")} out.update({"backend": "sycl", "exe": str(SYCL_WRAPPER), "args": args, "sycl_root": str(MOUNT)}) env = {} @@ -325,6 +345,11 @@ def install(argv) -> None: S.warn(f"{model} on this Arc computes the experts the card does not hold on the CPU (about {need} GB of " f"weights; this PC has {real_ram:.0f} GB of RAM): the start will be slow or fail - a smaller model " "(--model) fits better (docs/INTEL.md)") + if flag(cfg["args"], "--prefill") == "8192": + why = recommended_prefill(sel["vram_gb"], int(flag(cfg["args"], "--max-context") or 32768), sel["driver"], + sel.get("devid", ""))[1] + if why: + S.say(" " + why) Path(cfg_path).write_text(json.dumps(cfg, indent=1), encoding="utf-8") script = write(model, cfg_path, port, open_browser) script.write_text(script.read_text().replace(str(ROOT / "serve" / "server.py"), str(SERVER))) diff --git a/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp b/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp index c4c3d8c6..24ea37ad 100644 --- a/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp +++ b/sycl/src/kernels/cuda/qsa_decode_attn.dp.cpp @@ -109,7 +109,7 @@ __dpct_inline__ void load8(const QsaAttnPools &p, bool value, long long row, } else load8_q4(p, value, row, d0, out); } -template +template /* DPCT1110: The total declared local variable size in device function attn_chunk_kernel exceeds 128 bytes and may cause high register pressure. @@ -136,7 +136,7 @@ attn_chunk_kernel(const float *__restrict__ q, QsaAttnPools p, sycl::ext::oneapi::this_work_item::get_work_group< 3>()); // 12 KB: this KV head's query heads auto &sp = - *sycl::ext::oneapi::group_local_memory_for_overwrite( + *sycl::ext::oneapi::group_local_memory_for_overwrite( sycl::ext::oneapi::this_work_item::get_work_group< 3>()); // scores, then probabilities auto &srow = @@ -148,6 +148,8 @@ attn_chunk_kernel(const float *__restrict__ q, QsaAttnPools p, two expressions do not provide the exact same functionality. Check the generated code for potential precision and/or performance issues. */ + // the scores and probabilities: [head][cell], or - RS - [cell][head] so the value phase reads a cell's 12 probabilities as 3 vectors + const auto spi = [](int h, int c) { return RS != 0 ? c * G + h : h * CHUNK + c; }; const int n_ids = *(step + kStepWidth); const int chunk = item_ct1.get_group(2), kvh = item_ct1.get_group(1); const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5; @@ -187,7 +189,7 @@ attn_chunk_kernel(const float *__restrict__ q, QsaAttnPools p, const int c = t % CHUNK, h0 = (t / CHUNK) * HPT; if (c >= n_here || srow[c] < 0) { #pragma unroll - for (int j = 0; j < HPT; ++j) sp[h0 + j][c] = -FLT_MAX; + for (int j = 0; j < HPT; ++j) sp[spi(h0 + j, c)] = -FLT_MAX; } else { float a[HPT][32]; #pragma unroll @@ -214,18 +216,69 @@ attn_chunk_kernel(const float *__restrict__ q, QsaAttnPools p, for (int o = 16; o > 0; o >>= 1) #pragma unroll for (int l = 0; l < o; ++l) a[j][l] = a[j][l] + a[j][l + o]; - sp[h0 + j][c] = a[j][0] * scale; + sp[spi(h0 + j, c)] = a[j][0] * scale; } } } else // scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions. for (int c = warp; c < CHUNK; c += WARPS) { if (c >= n_here || srow[c] < 0) { - if (lane < G) sp[lane][c] = -FLT_MAX; + if (lane < G) sp[spi(lane, c)] = -FLT_MAX; continue; } float k8[8]; load8(p, false, srow[c], lane * 8, k8); + if constexpr (RS == 1) { + // 151-b70: the 12 heads' 32-lane butterfly sums as ONE reduce-scatter - 16 shuffles instead of 60. Each stage pairs the + // same lanes in the same order as warp_sum (xor 16, 8, 4, 2, 1) and adds own + partner, so every head's sum is the + // same tree and the same bits; the heads are padded to 16, halved at each stage (the lane keeps the half its bit + // selects, sends the other), and after the xor-2 stage lane 2h + {0, 1} holds head h's partial pair; xor 1 finishes it. + float part[16]; +#pragma unroll + for (int h = 0; h < G; ++h) { + const sycl::float4 qa = + *reinterpret_cast(&sq[h][lane * 8]); + const sycl::float4 qb = + *reinterpret_cast(&sq[h][lane * 8 + 4]); + part[h] = k8[0] * qa.x() + k8[1] * qa.y() + k8[2] * qa.z() + + k8[3] * qa.w() + k8[4] * qb.x() + k8[5] * qb.y() + + k8[6] * qb.z() + k8[7] * qb.w(); + } +#pragma unroll + for (int h = G; h < 16; ++h) part[h] = 0.0f; + const auto xr = [](float v, int o) { + return dpct::experimental::permute_sub_group_by_xor( + 0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), v, o); + }; + float c8[8]; + const bool b16 = (lane & 16) != 0, b8 = (lane & 8) != 0, b4 = (lane & 4) != 0, b2 = (lane & 2) != 0; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float send = b16 ? part[i] : part[8 + i]; + const float keep = b16 ? part[8 + i] : part[i]; + c8[i] = keep + xr(send, 16); + } + float c4[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const float send = b8 ? c8[i] : c8[4 + i]; + const float keep = b8 ? c8[4 + i] : c8[i]; + c4[i] = keep + xr(send, 8); + } + float c2[2]; +#pragma unroll + for (int i = 0; i < 2; ++i) { + const float send = b4 ? c4[i] : c4[2 + i]; + const float keep = b4 ? c4[2 + i] : c4[i]; + c2[i] = keep + xr(send, 4); + } + const float send1 = b2 ? c2[0] : c2[1]; + const float keep1 = b2 ? c2[1] : c2[0]; + float s = keep1 + xr(send1, 2); + s = s + xr(s, 1); + const int head = (lane >> 1) & 15; + if ((lane & 1) == 0 && head < G) sp[spi(head, c)] = s * scale; + } else { #pragma unroll for (int h = 0; h < G; ++h) { const sycl::float4 qa = @@ -236,7 +289,8 @@ attn_chunk_kernel(const float *__restrict__ q, QsaAttnPools p, k8[3] * qa.w() + k8[4] * qb.x() + k8[5] * qb.y() + k8[6] * qb.z() + k8[7] * qb.w(); s = warp_sum(s); - if (lane == 0) sp[h][c] = s * scale; + if (lane == 0) sp[spi(h, c)] = s * scale; + } } } /* @@ -247,7 +301,7 @@ attn_chunk_kernel(const float *__restrict__ q, QsaAttnPools p, item_ct1.barrier(); // per-head chunk max and exp-sum: warp w handles heads w and w+8. for (int h = warp; h < G; h += WARPS) { - const float a = sp[h][lane], b = sp[h][lane + 32]; + const float a = sp[spi(h, lane)], b = sp[spi(h, lane + 32)]; const float m = warp_max(sycl::fmax(a, b)); const float ea = (lane < n_here && srow[lane] >= 0) ? sycl::native::exp(a - m) @@ -255,8 +309,8 @@ attn_chunk_kernel(const float *__restrict__ q, QsaAttnPools p, const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? sycl::native::exp(b - m) : 0.0f; - sp[h][lane] = ea; - sp[h][lane + 32] = eb; + sp[spi(h, lane)] = ea; + sp[spi(h, lane + 32)] = eb; const float l = warp_sum(ea + eb); if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; } } @@ -300,8 +354,20 @@ attn_chunk_kernel(const float *__restrict__ q, QsaAttnPools p, const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8); v = (float) nibble * d; } + if constexpr (RS != 0) { + // the cell's 12 probabilities as three vector loads (the layout is [cell][head]); the same fma per head in the same order #pragma unroll - for (int h = 0; h < G; ++h) acc[h] = sycl::fma(sp[h][c], v, acc[h]); + for (int q4 = 0; q4 < G / 4; ++q4) { + const sycl::float4 pv = *reinterpret_cast(&sp[c * G + 4 * q4]); + acc[4 * q4 + 0] = sycl::fma(pv.x(), v, acc[4 * q4 + 0]); + acc[4 * q4 + 1] = sycl::fma(pv.y(), v, acc[4 * q4 + 1]); + acc[4 * q4 + 2] = sycl::fma(pv.z(), v, acc[4 * q4 + 2]); + acc[4 * q4 + 3] = sycl::fma(pv.w(), v, acc[4 * q4 + 3]); + } + } else { +#pragma unroll + for (int h = 0; h < G; ++h) acc[h] = sycl::fma(sp[spi(h, c)], v, acc[h]); + } } #pragma unroll for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h]; @@ -638,13 +704,66 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3 }); \ }); \ } +#define STRATA_ATTN_RSK(M, V) \ + { \ + auto exp_props = sycl::ext::oneapi::experimental::properties{ \ + sycl::ext::oneapi::experimental::use_root_sync}; \ + dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16}); \ + \ + st->submit([&](sycl::handler &cgh) { \ + auto q_ct0 = q; \ + QsaAttnPools pools_ct1 = pools; \ + auto ids_ct2 = ids; \ + auto steps_ct3 = steps; \ + auto s_n_head_kv_ct4 = (int)s.n_head_kv; \ + auto s_page_size_ct5 = (int)s.page_size; \ + auto scale_ct6 = scale; \ + auto part_acc_ct7 = part_acc; \ + auto part_m_ct8 = part_m; \ + auto part_l_ct9 = part_l; \ + auto n_chunks_ct10 = n_chunks; \ + auto cap_ct11 = (int)cap; \ + auto stride_ct12 = stride; \ + \ + cgh.parallel_for, \ + dpct_kernel_scalar>>( \ + sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS), \ + sycl::range(1, 1, THREADS)), \ + exp_props, \ + [=](sycl::nd_item<3> item_ct1) \ + [[sycl::reqd_sub_group_size(32)]] { \ + attn_chunk_kernel( \ + q_ct0, pools_ct1, ids_ct2, steps_ct3, \ + s_n_head_kv_ct4, s_page_size_ct5, scale_ct6, \ + part_acc_ct7, part_m_ct8, part_l_ct9, \ + n_chunks_ct10, cap_ct11, stride_ct12); \ + }); \ + }); \ + } +#undef STRATA_ATTN_RSK_DEFINED + // 151-b70: STRATA_ATTN_RS=2 (default): the probabilities in [cell][head] order and the value phase reading a cell's 12 as three vectors - the same + // bits (first-token logits md5 equal at 4K and 16K), +0.8..0.9% prompt tok/s on the B70; =1 adds a 16-shuffle reduce-scatter for the scores + // (bit-exact too, but -1.5% here: the score phase is not shuffle bound); =0 the layout before + static const int rs_on = [] { const char* v = std::getenv("STRATA_ATTN_RS"); return v ? std::atoi(v) : 2; }(); if (lane_cell) { if (kv_mode == 3) { STRATA_ATTN_LC(3); } else if (kv_mode == 2) { STRATA_ATTN_LC(2); } else if (kv_mode == 1) { STRATA_ATTN_LC(1); } else { STRATA_ATTN_LC(0); } + } else if (rs_on == 1) { + if (kv_mode == 3) { STRATA_ATTN_RSK(3, 1); } + else if (kv_mode == 2) { STRATA_ATTN_RSK(2, 1); } + else if (kv_mode == 1) { STRATA_ATTN_RSK(1, 1); } + else { STRATA_ATTN_RSK(0, 1); } + } else if (rs_on == 2) { + if (kv_mode == 3) { STRATA_ATTN_RSK(3, 2); } + else if (kv_mode == 2) { STRATA_ATTN_RSK(2, 2); } + else if (kv_mode == 1) { STRATA_ATTN_RSK(1, 2); } + else { STRATA_ATTN_RSK(0, 2); } } else #undef STRATA_ATTN_LC +#undef STRATA_ATTN_RSK if (kv_mode == 3) { auto exp_props = sycl::ext::oneapi::experimental::properties{ diff --git a/sycl/src/kernels/esimd_dpas_probe.cpp b/sycl/src/kernels/esimd_dpas_probe.cpp new file mode 100644 index 00000000..4f512880 --- /dev/null +++ b/sycl/src/kernels/esimd_dpas_probe.cpp @@ -0,0 +1,68 @@ +// esimd_dpas_probe (151-b70): the DPAS peak an ESIMD kernel reaches on one device, registers only. +// esimd_dpas_probe [reps=4096] [threads=8192] +// Modes: fp16 (8x16x16, fp32 acc), s8 (8x16x32, int32 acc). RC=8 rows per DPAS, MT row tiles x NT column tiles of +// accumulators per hardware thread; the A/B operands are loaded once (random bits), so the loop is pure DPAS. +// Build: icpx -fsycl -fsycl-targets=intel_gpu_bmg_g31 -O3 esimd_dpas_probe.cpp +#include +#include +#include +#include +#include +#include +#include + +using namespace sycl::ext::intel::esimd; +namespace xmx = sycl::ext::intel::esimd::xmx; + +template +double run(sycl::queue& q, int reps, int threads, uint32_t* src, float* out) { + constexpr int KW = S8 ? 8 : 8; // dwords per row of A (K=32 s8 / K=16 fp16: 8 dwords) + constexpr auto PA = S8 ? xmx::dpas_argument_type::s8 : xmx::dpas_argument_type::fp16; + using CT = std::conditional_t; + auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size}; + auto t0 = std::chrono::steady_clock::now(); + q.submit([&](sycl::handler& h) { + h.parallel_for(sycl::nd_range<1>(threads, 8), props, [=](sycl::nd_item<1> it) SYCL_ESIMD_KERNEL { + const int tid = it.get_global_id(0); + simd a[MT]; + simd b[NT]; + simd acc[MT][NT]; + for (int i = 0; i < MT; ++i) a[i] = simd(0x3c003c00u + i * 0x01010101 + tid, 1); + for (int j = 0; j < NT; ++j) b[j] = simd(0x3c003c00u + j * 0x00010001, 1); + for (int i = 0; i < MT; ++i) for (int j = 0; j < NT; ++j) acc[i][j] = 0; + for (int r = 0; r < reps; ++r) { +#pragma unroll + for (int i = 0; i < MT; ++i) +#pragma unroll + for (int j = 0; j < NT; ++j) + acc[i][j] = xmx::dpas<8, 8, CT, CT, int, int, PA, PA>(acc[i][j], b[j], a[i]); + } + float s = 0; + for (int i = 0; i < MT; ++i) for (int j = 0; j < NT; ++j) { simd f = acc[i][j]; s += reduce(f, std::plus<>()); } + out[tid] = s; + }); + }).wait(); + return std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); +} + +int main(int argc, char** argv) { + int reps = argc > 1 ? atoi(argv[1]) : 4096, threads = argc > 2 ? atoi(argv[2]) : 8192; + sycl::queue q{sycl::gpu_selector_v, sycl::property::queue::in_order()}; + std::printf("device %s\n", q.get_device().get_info().c_str()); + float* out = sycl::malloc_device(threads, q); + uint32_t* src = nullptr; + auto rep = [&](const char* nm, double (*fn)(sycl::queue&, int, int, uint32_t*, float*), int mt, int nt, bool s8) { + fn(q, 64, threads, src, out); + double best = 1e30; + for (int k = 0; k < 3; ++k) best = std::min(best, fn(q, reps, threads, src, out)); + const double ops = 2.0 * 8 * 16 * (s8 ? 32 : 16) * (double) mt * nt * reps * threads; + std::printf("%-22s %.1f T%s/s (%.3f s)\n", nm, ops / best / 1e12, s8 ? "OPS" : "FLOPS", best); + }; + rep("fp16 4x2 grf256", run, 4, 2, false); + rep("fp16 4x2 grf128", run, 4, 2, false); + rep("fp16 2x2 grf256", run, 2, 2, false); + rep("s8 4x2 grf256", run, 4, 2, true); + rep("s8 4x2 grf128", run, 4, 2, true); + rep("s8 2x2 grf256", run, 2, 2, true); + return 0; +} diff --git a/sycl/src/kernels/esimd_i8_bench.cpp b/sycl/src/kernels/esimd_i8_bench.cpp new file mode 100644 index 00000000..c1444c78 --- /dev/null +++ b/sycl/src/kernels/esimd_i8_bench.cpp @@ -0,0 +1,204 @@ +// esimd_i8_bench (151-b70): an ESIMD int8 DPAS expert GEMM on pre-decoded weights, us per expert. +// esimd_i8_bench [M=80] [experts=64] [reps=10] +// Y[M][N] = sum_kb dx[m][kb] * sw[n][kb] * (Xq[m][kb*32..] . Wq[n][kb*32..]) (int8 x int8 -> int32 per 32 of K, then a float +// scale: the shape of a quantized-weight x q8_1 product). Operands are pre-tiled in DPAS register order: +// Xq [E][M/8][K/32][64 dwords] (8 rows x 32 bytes: an 8x32 A tile, row-major) +// dx [E][M/8][K/32][8 floats] +// Wq [E][N/16][K/32][8][16 dwords] (the B tile: dword r of column n at r*16+n) +// sw [E][N/16][K/32][16 floats] +// Build: icpx -fsycl -fsycl-targets=intel_gpu_bmg_g31 -O3 esimd_i8_bench.cpp +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef EPIV +#define EPIV 1 +#endif +using namespace sycl::ext::intel::esimd; +namespace xmx = sycl::ext::intel::esimd::xmx; + +struct Args { + const uint32_t* Xq; const float* dx; const uint32_t* Wq; const float* sw; float* Y; + int M, N, K, MTILES, NTILES, alias; +}; + +template +SYCL_ESIMD_FUNCTION inline void sfor(F&& f) { + [&](std::integer_sequence) SYCL_ESIMD_FUNCTION { + (f(std::integral_constant{}), ...); + }(std::make_integer_sequence{}); +} + +template +void run(sycl::queue& q, const Args a, int E) { + const int nkb = a.K / 32; + const int mtg = (a.MTILES + MT - 1) / MT, ntg = a.NTILES / NT; + const size_t nthr = (size_t) E * mtg * ntg; + auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size}; + q.submit([&](sycl::handler& h) { + h.parallel_for(sycl::range<1>(nthr), props, [=](sycl::id<1> id) SYCL_ESIMD_KERNEL { + struct St { + simd b; simd sw; simd a; simd dx; + }; + const int t = (int) id[0]; + const int nt0 = (t % ntg) * NT, mt0 = ((t / ntg) % mtg) * MT, e = t / (ntg * mtg); + simd acc = 0.f; + simd acci = 0; + const uint32_t* Xe = a.Xq + (size_t) e * a.MTILES * nkb * 64; + const float* dxe = a.dx + (size_t) e * a.MTILES * nkb * 8; + const uint32_t* We = a.Wq + (size_t) (a.alias ? 0 : e) * a.NTILES * nkb * 128; + const float* swe = a.sw + (size_t) (a.alias ? 0 : e) * a.NTILES * nkb * 16; + St sA, sB; + auto ld = [&](int kb, St& s) SYCL_ESIMD_FUNCTION { + sfor([&](auto jj) SYCL_ESIMD_FUNCTION { + constexpr int j = decltype(jj)::value; + s.b.template select<128, 1>(128 * j) = block_load(We + ((size_t) (nt0 + j) * nkb + kb) * 128); + s.sw.template select<16, 1>(16 * j) = block_load(swe + ((size_t) (nt0 + j) * nkb + kb) * 16); + }); + sfor([&](auto ii) SYCL_ESIMD_FUNCTION { + constexpr int i = decltype(ii)::value; + const int mi = (mt0 + i < a.MTILES) ? mt0 + i : a.MTILES - 1; + s.a.template select<64, 1>(64 * i) = block_load(Xe + ((size_t) mi * nkb + kb) * 64); + s.dx.template select<8, 1>(8 * i) = block_load(dxe + ((size_t) mi * nkb + kb) * 8); + }); + }; + auto cmp = [&](int kb, St& s) SYCL_ESIMD_FUNCTION { + sfor([&](auto ii) SYCL_ESIMD_FUNCTION { + constexpr int i = decltype(ii)::value; + sfor([&](auto jj) SYCL_ESIMD_FUNCTION { + constexpr int j = decltype(jj)::value; + constexpr int o = 128 * (i * NT + j); + simd bv = s.b.template select<128, 1>(128 * j).template bit_cast_view(); + simd av = s.a.template select<64, 1>(64 * i).template bit_cast_view(); + if constexpr (EPI == 0) { + simd c0 = acci.template select<128, 1>(o); + acci.template select<128, 1>(o) = xmx::dpas<8, 8, int, int, int, int, xmx::dpas_argument_type::s8, xmx::dpas_argument_type::s8>(c0, bv, av); + } else if constexpr (EPI == 1) { + simd tmp = xmx::dpas<8, 8, int, int, int, int, xmx::dpas_argument_type::s8, xmx::dpas_argument_type::s8>( + simd(0), bv, av); + simd tf = tmp; + simd sw = s.sw.template select<16, 1>(16 * j); +#pragma unroll + for (int r = 0; r < 8; ++r) { + const float dxr = s.dx[8 * i + r]; + acc.template select<16, 1>(o + 16 * r) += tf.template select<16, 1>(16 * r) * (sw * dxr); + } + } else { + simd tmp = xmx::dpas<8, 8, int, int, int, int, xmx::dpas_argument_type::s8, xmx::dpas_argument_type::s8>( + simd(0), bv, av); + simd sw = s.sw.template select<16, 1>(16 * j); + simd isw = convert(sw * 50.f); +#pragma unroll + for (int r = 0; r < 8; ++r) + acci.template select<16, 1>(o + 16 * r) += tmp.template select<16, 1>(16 * r) * isw; + if ((kb & 3) == 3) { + simd tf = acci.template select<128, 1>(o); + acci.template select<128, 1>(o) = 0; +#pragma unroll + for (int r = 0; r < 8; ++r) { + const float dxr = s.dx[8 * i + r]; + acc.template select<16, 1>(o + 16 * r) += tf.template select<16, 1>(16 * r) * (sw * dxr); + } + } + } + }); + }); + }; + ld(0, sA); + for (int kb = 0; kb < nkb; kb += 2) { + ld(kb + 1, sB); + cmp(kb, sA); + if (kb + 2 < nkb) ld(kb + 2, sA); + cmp(kb + 1, sB); + } + if constexpr (EPI == 0) acc = acci; + sfor([&](auto ii) SYCL_ESIMD_FUNCTION { + constexpr int i = decltype(ii)::value; + sfor([&](auto jj) SYCL_ESIMD_FUNCTION { + constexpr int j = decltype(jj)::value; +#pragma unroll + for (int r = 0; r < 8; ++r) { + const int m = (mt0 + i) * 8 + r; + if (m < a.M) block_store(a.Y + ((size_t) e * a.M + m) * a.N + (nt0 + j) * 16, + acc.template select<16, 1>(128 * (i * NT + j) + 16 * r)); + } + }); + }); + }); + }); +} + +int main(int argc, char** argv) { + const int M = argc > 1 ? std::atoi(argv[1]) : 80; + const int E = argc > 2 ? std::atoi(argv[2]) : 64; + const int reps = argc > 3 ? std::atoi(argv[3]) : 10; + sycl::queue q{sycl::gpu_selector_v, sycl::property::queue::in_order()}; + std::printf("device %s, M %d, %d experts\n", q.get_device().get_info().c_str(), M, E); + struct Shape { const char* nm; int N, K; } shapes[2] = {{"gate+up", 1280, 2560}, {"down", 2560, 640}}; + std::mt19937 rng(7); + for (const Shape& sh : shapes) { + const int N = sh.N, K = sh.K, nkb = K / 32, MTILES = (M + 7) / 8, NTILES = N / 16; + const size_t nX = (size_t) E * MTILES * nkb * 64, nW = (size_t) E * NTILES * nkb * 128; + std::vector hX(nX), hW(nW); + std::vector hdx((size_t) E * MTILES * nkb * 8), hsw((size_t) E * NTILES * nkb * 16); + for (auto& x : hX) x = rng(); for (auto& x : hW) x = rng() & 0x0f0f0f0fu; // small weights, |w| <= 15 like a grid + for (auto& x : hdx) x = 0.01f * (1 + rng() % 8); + for (auto& x : hsw) x = 0.02f * (1 + rng() % 8); + uint32_t *dX = sycl::malloc_device(nX, q), *dW = sycl::malloc_device(nW, q); + float *ddx = sycl::malloc_device(hdx.size(), q), *dsw = sycl::malloc_device(hsw.size(), q); + float* dY = sycl::malloc_device((size_t) E * M * N, q); + q.memcpy(dX, hX.data(), nX * 4); q.memcpy(dW, hW.data(), nW * 4); + q.memcpy(ddx, hdx.data(), hdx.size() * 4); q.memcpy(dsw, hsw.data(), hsw.size() * 4); q.wait(); + Args a{dX, ddx, dW, dsw, dY, M, N, K, MTILES, NTILES, argc > 4 ? std::atoi(argv[4]) : 0}; + auto time = [&](auto&& fn) { + fn(); q.wait(); + double best = 1e30; + for (int r = 0; r < reps; ++r) { + const auto t0 = std::chrono::steady_clock::now(); + fn(); q.wait(); + best = std::min(best, std::chrono::duration(std::chrono::steady_clock::now() - t0).count()); + } + return best / E; + }; + const double ops = 2.0 * M * N * K; + struct V { const char* nm; double t; } vs[6]; + vs[0] = {"2x2g256", time([&] { run<2, 2, 256, EPIV>(q, a, E); })}; + vs[1] = {"2x2g128", time([&] { run<2, 2, 128, EPIV>(q, a, E); })}; + vs[2] = {"1x2g128", time([&] { run<1, 2, 128, EPIV>(q, a, E); })}; + vs[3] = {"2x1g128", time([&] { run<2, 1, 128, EPIV>(q, a, E); })}; + vs[4] = {"1x1g128", time([&] { run<1, 1, 128, EPIV>(q, a, E); })}; + vs[5] = {"1x4g256", time([&] { run<1, 4, 256, EPIV>(q, a, E); })}; + // check expert 3 (last run's output: MT8 NT1) against a host reference + std::vector hY((size_t) M * N); + q.memcpy(hY.data(), dY + (size_t) 3 * M * N, hY.size() * 4).wait(); + double maxerr = 0, maxref = 0; + for (int m = 0; m < M; m += 5) for (int n = 0; n < N; n += 7) { + double ref = 0; + const int mt = m / 8, r = m % 8, nt = n / 16, c = n % 16; + for (int kb = 0; kb < nkb; ++kb) { + long long s = 0; + for (int k = 0; k < 32; ++k) { + // A tile: row r at dwords r*8 .. ; B tile: dword (k/4) of column c at (k/4)*16 + c + const uint32_t aw = hX[(((size_t) 3 * MTILES + mt) * nkb + kb) * 64 + r * 8 + k / 4]; + const uint32_t bw = hW[(((size_t) 3 * NTILES + nt) * nkb + kb) * 128 + (k / 4) * 16 + c]; + s += (long long) (int8_t) (aw >> (8 * (k % 4))) * (int8_t) (bw >> (8 * (k % 4))); + } + ref += (double) s * hdx[(((size_t) 3 * MTILES + mt) * nkb + kb) * 8 + r] * hsw[(((size_t) 3 * NTILES + nt) * nkb + kb) * 16 + c]; + } + maxref = std::max(maxref, std::fabs(ref)); maxerr = std::max(maxerr, std::fabs(ref - hY[(size_t) m * N + n])); + } + std::printf("%-8s N %d K %d:", sh.nm, N, K); + for (auto& v : vs) std::printf(" %s %.1f us (%.0f TOPS)", v.nm, v.t, ops / v.t / 1e6); + std::printf("\n max err %.3g of %.3g\n", maxerr, maxref); + sycl::free(dX, q); sycl::free(dW, q); sycl::free(ddx, q); sycl::free(dsw, q); sycl::free(dY, q); + } + return 0; +} diff --git a/sycl/src/kernels/esimd_iq3s_decode_bench.cpp b/sycl/src/kernels/esimd_iq3s_decode_bench.cpp new file mode 100644 index 00000000..09188bb9 --- /dev/null +++ b/sycl/src/kernels/esimd_iq3s_decode_bench.cpp @@ -0,0 +1,168 @@ +// esimd_iq3s_decode_bench (151-b70): IQ3_S rows decoded to DPAS B fragments (int8) by an ESIMD kernel, lanes = 16 rows. +// esimd_iq3s_decode_bench [N=1280] [K=2560] [experts=16] [write=1] +// Output per expert: Wq [N/16][K/32][8][16] dwords (the B tile of a DPAS s8 8x16x32: dword r of row n at r*16+n), sw [N/16][K/32][16] floats +// (d * (1 + 2 s) per row and 32-block). Checked against a host decode with ggml's own grid. Reports us per expert and GB/s of +// compressed weights consumed. write=0 keeps the fragments in registers (an xor checksum) to separate decode from the plane write. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define GGML_COMMON_DECL_CPP +#define GGML_COMMON_IMPL_CPP +#include "ggml-common.h" + +using namespace sycl::ext::intel::esimd; + +constexpr int BLK = 110; // sizeof(block_iq3_s) + +template +SYCL_ESIMD_FUNCTION __attribute__((always_inline)) inline void sfor(F&& f) { + [&](std::integer_sequence) SYCL_ESIMD_FUNCTION { + (f(std::integral_constant{}), ...); + }(std::make_integer_sequence{}); +} + +// unaligned 32-bit read at a 2-byte aligned byte offset (per lane) through two dword gathers +SYCL_ESIMD_FUNCTION inline simd ld32(const uint8_t* base, simd off) { + simd a = off & ~3u; + simd lo = gather(reinterpret_cast(base), a); + simd hi = gather(reinterpret_cast(base), a + 4u); + simd sh = (off & 2u) << 3; // 0 or 16 + return (lo >> sh) | ((hi << 16) << (16u - sh)); +} +SYCL_ESIMD_FUNCTION inline simd ld16(const uint8_t* base, simd off) { + simd a = off & ~3u; + simd lo = gather(reinterpret_cast(base), a); + return (lo >> ((off & 2u) << 3)) & 0xffffu; +} + +template +void run(sycl::queue& q, const uint8_t* W, const uint32_t* grid, uint32_t* Wq, float* sw, uint32_t* sink, int N, int K, int E) { + const int nsb = K / 256, ntiles = N / 16, rowb = nsb * BLK; + const size_t nthr = (size_t) E * ntiles; + auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<128>}; + q.submit([&](sycl::handler& h) { + h.parallel_for(sycl::range<1>(nthr), props, [=](sycl::id<1> id) SYCL_ESIMD_KERNEL { + const int t = (int) id[0], nt = t % ntiles, e = t / ntiles; + const uint8_t* We = W + (size_t) e * N * rowb; + simd rowoff = (simd(0, 1) + (uint32_t) (nt * 16)) * (uint32_t) rowb; + simd chk = 0; + for (int sb = 0; sb < nsb; ++sb) { + const uint32_t P = sb * BLK; + simd d16 = ld16(We, rowoff + P); + simd dlo = d16.template bit_cast_view().template select<16, 2>(0); + simd dh16 = dlo.template bit_cast_view(); + simd d = dh16; + simd sc4 = ld32(We, rowoff + (P + 106)); + simd qh4 = ld32(We, rowoff + (P + 66)); + simd qh8 = ld32(We, rowoff + (P + 70)); +#pragma unroll + for (int ib = 0; ib < 8; ++ib) { + simd q0 = ld32(We, rowoff + (P + 2 + 8 * ib)); + simd q1 = ld32(We, rowoff + (P + 6 + 8 * ib)); + simd sg = ld32(We, rowoff + (P + 74 + 4 * ib)); + simd qhv = ((ib < 4 ? qh4 : qh8) >> (8 * (ib & 3))) & 0xffu; + simd scn = ((sc4 >> (8 * (ib >> 1))) >> (4 * (ib & 1))) & 0xfu; + simd swv = d * simd(simd(scn * 2u + 1u)); + simd frag; +#pragma unroll + for (int r = 0; r < 8; ++r) { + simd qsw = r < 4 ? q0 : q1; + simd idx = ((qsw >> (8 * (r & 3))) & 0xffu) | (((qhv >> r) & 1u) << 8); + simd g = gather(grid, idx << 2); + simd nib = ((sg >> (8 * (r >> 1))) >> (4 * (r & 1))) & 0xfu; + simd m = ((nib * 0x00204081u) & 0x01010101u); + simd mask = m * 255u; + frag.template select<16, 1>(16 * r) = (g ^ mask) + m; + } + if constexpr (WRITE) { + const size_t fi = ((size_t) e * ntiles + nt) * (K / 32) + sb * 8 + ib; + block_store(Wq + fi * 128, frag); + block_store(sw + fi * 16, swv); + } else { + simd x = swv.template bit_cast_view(); +#pragma unroll + for (int r = 0; r < 8; ++r) x ^= frag.template select<16, 1>(16 * r); + chk ^= x; + } + } + } + if constexpr (!WRITE) block_store(sink + (size_t) t * 16, chk); + }); + }); +} + +int main(int argc, char** argv) { + const int N = argc > 1 ? std::atoi(argv[1]) : 1280, K = argc > 2 ? std::atoi(argv[2]) : 2560; + const int E = argc > 3 ? std::atoi(argv[3]) : 16, WR = argc > 4 ? std::atoi(argv[4]) : 1; + sycl::queue q{sycl::gpu_selector_v, sycl::property::queue::in_order()}; + std::printf("device %s, N %d K %d, %d experts, write %d\n", q.get_device().get_info().c_str(), N, K, E, WR); + const int nsb = K / 256, ntiles = N / 16, rowb = nsb * BLK; + std::mt19937 rng(11); + std::vector hW((size_t) E * N * rowb); + for (size_t i = 0; i < hW.size(); ++i) hW[i] = (uint8_t) rng(); + for (size_t b = 0; b < hW.size() / BLK; ++b) { // sane fp16 d + const sycl::half dh = sycl::half(0.002f + 0.0001f * (rng() % 50)); + std::memcpy(&hW[b * BLK], &dh, 2); + } + uint8_t* dW = sycl::malloc_device(hW.size() + 4096, q); + uint32_t* dgrid = sycl::malloc_device(512, q); + uint32_t* dWq = sycl::malloc_device((size_t) E * ntiles * (K / 32) * 128, q); + float* dsw = sycl::malloc_device((size_t) E * ntiles * (K / 32) * 16, q); + uint32_t* dsink = sycl::malloc_device((size_t) E * ntiles * 16, q); + q.memcpy(dW, hW.data(), hW.size()); q.memcpy(dgrid, iq3s_grid, 512 * 4); q.wait(); + auto go = [&] { if (WR) run<1>(q, dW, dgrid, dWq, dsw, dsink, N, K, E); else run<0>(q, dW, dgrid, dWq, dsw, dsink, N, K, E); q.wait(); }; + go(); + double best = 1e30; + for (int r = 0; r < 10; ++r) { + const auto t0 = std::chrono::steady_clock::now(); + go(); + best = std::min(best, std::chrono::duration(std::chrono::steady_clock::now() - t0).count()); + } + std::printf("decode: %.1f us per expert (%.0f GB/s of compressed weights)\n", best / E, (double) N * rowb / (best / E) / 1e3); + if (WR) { // host check of expert 1 + const int e = E > 1 ? 1 : 0; + std::vector hQ((size_t) ntiles * (K / 32) * 128); + std::vector hS((size_t) ntiles * (K / 32) * 16); + q.memcpy(hQ.data(), dWq + (size_t) e * hQ.size(), hQ.size() * 4).wait(); + q.memcpy(hS.data(), dsw + (size_t) e * hS.size(), hS.size() * 4).wait(); + long bad = 0, badS = 0; + for (int n = 0; n < N; n += 3) { + for (int sb = 0; sb < nsb; ++sb) { + const uint8_t* blk = &hW[((size_t) e * N + n) * rowb + (size_t) sb * BLK]; + sycl::half dh; std::memcpy(&dh, blk, 2); + const uint8_t *qs = blk + 2, *qh = blk + 66, *sgn = blk + 74, *scl = blk + 106; + for (int ib = 0; ib < 8; ++ib) { + const int sc = (scl[ib / 2] >> (4 * (ib % 2))) & 0xf; + const float swr = (float) dh * (1 + 2 * sc); + const size_t fi = ((size_t) (n / 16) * (K / 32) + sb * 8 + ib); + if (std::fabs(hS[fi * 16 + n % 16] - swr) > 1e-6f * std::fabs(swr)) ++badS; + for (int r = 0; r < 8; ++r) { + const int idx = qs[8 * ib + r] | (((qh[ib] >> r) & 1) << 8); + const uint8_t* g = (const uint8_t*) &iq3s_grid[idx]; + const uint8_t sbyte = sgn[4 * ib + r / 2]; + uint32_t want = 0; + for (int j = 0; j < 4; ++j) { + const int kk = 4 * (r & 1) + j; + const int v = (sbyte >> kk & 1) ? -(int) g[j] : (int) g[j]; + want |= (uint32_t) (uint8_t) (int8_t) v << (8 * j); + } + if (hQ[fi * 128 + r * 16 + n % 16] != want) ++bad; + } + } + } + } + std::printf("check expert %d: %ld bad dwords, %ld bad scales\n", e, bad, badS); + } + return 0; +} diff --git a/sycl/src/kernels/esimd_moe_mode_test.cpp b/sycl/src/kernels/esimd_moe_mode_test.cpp new file mode 100644 index 00000000..69d69572 --- /dev/null +++ b/sycl/src/kernels/esimd_moe_mode_test.cpp @@ -0,0 +1,30 @@ +// 151-b70: the default choice of the prompt-expert chain (strata::prefill::i8::choose_mode), no GPU needed. +// unset : auto on a Battlemage device whose kernels are available, else the FP16 chain +// STRATA_PREFILL_MMQ=0 / 1 / auto : off / forced / auto, whatever the device +#include +#include "strata/prefill/esimd_moe.hpp" + +using strata::prefill::i8::choose_mode; +static int bad = 0; +#define CHECK(cond, what) do { if (!(cond)) { std::printf("FAIL: %s\n", what); ++bad; } } while (0) + +int main() { + // unset or empty + CHECK(choose_mode(nullptr, true, true) == 2, "unset on Battlemage -> auto"); + CHECK(choose_mode("", true, true) == 2, "empty on Battlemage -> auto"); + CHECK(choose_mode(nullptr, true, false) == 0, "unset on Battlemage without kernels (AOT stub, failed probe) -> FP16"); + CHECK(choose_mode(nullptr, false, true) == 0, "unset on Alchemist / any non-Battlemage device that can run the kernels -> FP16"); + CHECK(choose_mode(nullptr, false, false) == 0, "unset elsewhere -> FP16"); + // explicit + CHECK(choose_mode("0", true, true) == 0, "=0 on Battlemage turns it off"); + CHECK(choose_mode("1", true, true) == 1, "=1 forces int8"); + CHECK(choose_mode("1", false, true) == 1, "=1 forces it on a non-Battlemage device too (the caller still needs available())"); + CHECK(choose_mode("auto", false, true) == 2, "=auto"); + CHECK(choose_mode("Auto", true, true) == 2, "=Auto"); + CHECK(choose_mode("0", false, false) == 0, "=0 elsewhere"); + CHECK(choose_mode("00", true, true) == 0, "=00 is 0"); + CHECK(choose_mode("2", true, true) == 1, "any other number forces int8"); + CHECK(choose_mode("off", true, true) == 0, "an unparsable word is 0, as atoi had it"); + if (bad == 0) std::printf("esimd_moe_mode_test: all OK\n"); + return bad == 0 ? 0 : 1; +} diff --git a/sycl/src/kernels/esimd_moe_parity.cpp b/sycl/src/kernels/esimd_moe_parity.cpp new file mode 100644 index 00000000..ebaddf2d --- /dev/null +++ b/sycl/src/kernels/esimd_moe_parity.cpp @@ -0,0 +1,284 @@ +// esimd_moe_parity (151-b70): the fused int8 DPAS expert products (prefill/esimd_moe.dp.cpp) against +// (a) the engine's dequantize + oneMKL path (FP16 weights, FP16 activations), the path they replace, +// (b) an FP64 host reference from the blobs with the unquantized activations, +// (c) an exact host reference on the SAME int8 activations the device produced (isolates the kernel arithmetic from the +// activation quantization: only the float accumulation order differs), +// for every gate/up x down type pair the kernels handle, and times both paths per expert. +// esimd_moe_parity [mean_rows=80] [experts=16] [reps=10] [seed=1] [gate_up_type down_type] +// types: gate/up 21 IQ3_S, 18 IQ3_XXS, 22 IQ2_S; down 20 IQ4_NL, 42 Q2_0. +// Exit status 1 when (c) is off by more than 2e-5 of the largest value or (b) exceeds the int8 activation error budget. +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/iq_dequant_expert.hpp" +#include "strata/prefill/esimd_moe.hpp" +#include "strata/prefill/kernels.hpp" +#include "strata/sycl_queue.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define GGML_TABLE_BEGIN(type, name, size) static const type name[size] = { +#define GGML_TABLE_END() }; +#include "../prefill/iq_tables.inc" + +namespace i8 = strata::prefill::i8; +static uint16_t f2h(float f) { return sycl::bit_cast(sycl::half(f)); } +static float h2f(uint16_t h) { return (float) sycl::bit_cast(h); } + +static int block_bytes(int t) { return t == 21 ? 110 : t == 18 ? 98 : t == 22 ? 82 : 18; } +static int block_vals(int t) { return (t == 21 || t == 18 || t == 22) ? 256 : t == 42 ? 64 : 32; } + +// host decode of one row (K values) -> double +static void dec_row(int t, const uint8_t* row, int K, double* out) { + const int bb = block_bytes(t), bv = block_vals(t); + for (int b = 0; b < K / bv; ++b) { + const uint8_t* blk = row + (size_t) b * bb; + uint16_t dh; std::memcpy(&dh, blk, 2); + const double d = h2f(dh); + double* o = out + (size_t) b * bv; + if (t == 21) { + const uint8_t *qs = blk + 2, *qh = blk + 66, *sgn = blk + 74, *scl = blk + 106; + for (int ib = 0; ib < 8; ++ib) { + const double dd = d * (1 + 2 * ((scl[ib / 2] >> (4 * (ib % 2))) & 0xf)); + for (int r = 0; r < 8; ++r) { + const int idx = qs[8 * ib + r] | (((qh[ib] >> r) & 1) << 8); + const uint8_t* g = (const uint8_t*) &iq3s_grid[idx]; + const uint8_t sb = sgn[4 * ib + r / 2]; + for (int j = 0; j < 4; ++j) o[ib * 32 + 4 * r + j] = dd * ((sb >> (4 * (r & 1) + j) & 1) ? -(int) g[j] : (int) g[j]); + } + } + } else if (t == 18) { + const uint8_t* qs = blk + 2; + for (int ib = 0; ib < 8; ++ib) { + uint32_t aux; std::memcpy(&aux, blk + 66 + 4 * ib, 4); + const double dd = d * (0.5 + (aux >> 28)) * 0.5; + for (int l = 0; l < 4; ++l) { + const uint8_t sb = ksigns_iq2xs[(aux >> (7 * l)) & 127]; + const uint8_t *g1 = (const uint8_t*) &iq3xxs_grid[qs[8 * ib + 2 * l]], *g2 = (const uint8_t*) &iq3xxs_grid[qs[8 * ib + 2 * l + 1]]; + for (int j = 0; j < 4; ++j) { + o[ib * 32 + 8 * l + j] = dd * ((sb >> j & 1) ? -(int) g1[j] : (int) g1[j]); + o[ib * 32 + 8 * l + 4 + j] = dd * ((sb >> (4 + j) & 1) ? -(int) g2[j] : (int) g2[j]); + } + } + } + } else if (t == 22) { + const uint8_t *qs = blk + 2, *qh = blk + 66, *scl = blk + 74, *sgn = blk + 34; + for (int ib = 0; ib < 8; ++ib) + for (int l = 0; l < 4; ++l) { + const int idx = qs[4 * ib + l] | ((qh[ib] << (8 - 2 * l)) & 0x300); + const uint8_t* g = (const uint8_t*) &iq2s_grid[idx]; + const double dd = d * (0.5 + ((scl[ib] >> (4 * (l / 2))) & 0xf)) * 0.25; + const uint8_t sb = sgn[4 * ib + l]; + for (int j = 0; j < 8; ++j) o[ib * 32 + 8 * l + j] = dd * ((sb >> j & 1) ? -(int) g[j] : (int) g[j]); + } + } else if (t == 20) { + for (int j = 0; j < 16; ++j) { + o[j] = d * kvalues_iq4nl[blk[2 + j] & 15]; + o[16 + j] = d * kvalues_iq4nl[blk[2 + j] >> 4]; + } + } else { // 42 Q2_0 + for (int i = 0; i < 64; ++i) o[i] = d * (((blk[2 + i / 4] >> ((i % 4) * 2)) & 3) - 1); + } + } +} + +struct Result { bool ok; double t_ref, t_fused; }; + +static Result run_case(sycl::queue* q, dpct::blas::descriptor_ptr hd, int gt, int dt, int mean, int n, int reps, int seed) { + const int K = 2560, NFF = 640, NE = 2560; + std::mt19937 rng(seed); + std::vector cnt(n); + std::gamma_distribution gd(1.5, mean / 1.5); + int tot = 0; + for (auto& c : cnt) { c = std::max(1, (int) gd(rng)); tot += c; } + if (n >= 3) { cnt[0] = 1; cnt[1] = 7; cnt[2] = 9; tot = 0; for (int c : cnt) tot += c; } // pad edge cases + i8::Layout lo; + i8::make_layout(lo, cnt.data(), n); + + const size_t rowb_gu = (size_t) (K / block_vals(gt)) * block_bytes(gt), rowb_dn = (size_t) (NFF / block_vals(dt)) * block_bytes(dt); + const size_t gate_b = NFF * rowb_gu, down_b = NE * rowb_dn, blob_b = 2 * gate_b + down_b; + std::vector> hb(n); + std::vector db(n); + for (int i = 0; i < n; ++i) { + hb[i].resize(blob_b); + for (auto& x : hb[i]) x = (uint8_t) rng(); + for (size_t o = 0; o < 2 * gate_b; o += block_bytes(gt)) { const uint16_t d = f2h(0.0004f + 0.00002f * (rng() % 50)); std::memcpy(&hb[i][o], &d, 2); } + for (size_t o = 2 * gate_b; o < blob_b; o += block_bytes(dt)) { const uint16_t d = f2h(0.0004f + 0.00002f * (rng() % 50)); std::memcpy(&hb[i][o], &d, 2); } + db[i] = sycl::malloc_device(blob_b + 256, *q); + q->memcpy(db[i], hb[i].data(), blob_b); + } + std::vector hx((size_t) tot * K); + std::normal_distribution nd(0.f, 1.f); + for (auto& x : hx) { float v = nd(rng) * 0.5f; if (rng() % 97 == 0) v *= 12.f; x = f2h(v); } // a few outliers + uint16_t* dxh = sycl::malloc_device(hx.size(), *q); + q->memcpy(dxh, hx.data(), hx.size() * 2); + int8_t* Xq = sycl::malloc_device(i8::xq_bytes(lo, K), *q); + float* dX = sycl::malloc_device(i8::dx_bytes(lo, K) / 4, *q); + int8_t* Hq = sycl::malloc_device(i8::xq_bytes(lo, NFF), *q); + float* dH = sycl::malloc_device(i8::dx_bytes(lo, NFF) / 4, *q); + float *GU = sycl::malloc_device((size_t) tot * 2 * NFF, *q), *Dm = sycl::malloc_device((size_t) tot * NE, *q); + float *GUr = sycl::malloc_device((size_t) tot * 2 * NFF, *q), *Dmr = sycl::malloc_device((size_t) tot * NE, *q); + uint16_t* Hh = sycl::malloc_device((size_t) tot * NFF, *q); + uint16_t* dwgu = sycl::malloc_device((size_t) 2 * NFF * K, *q); + uint16_t* dwd = sycl::malloc_device((size_t) NE * NFF, *q); + q->wait(); + std::vector pb(n); + for (int i = 0; i < n; ++i) pb[i] = db[i]; + + auto fused = [&]() { + i8::quantize_rows(dxh, lo, K, Xq, dX, q); + if (!i8::gate_up(gt, pb.data(), gate_b, NFF, lo, K, Xq, dX, GU, q)) { std::printf("gate_up refused (type %d)\n", gt); std::exit(2); } + i8::swiglu_quantize(GU, lo, NFF, Hq, dH, q); + if (!i8::down(dt, pb.data(), 2 * gate_b, NE, lo, NFF, Hq, dH, Dm, q)) { std::printf("down refused (type %d)\n", dt); std::exit(2); } + }; + auto ref = [&]() { + int64_t o = 0; + for (int i = 0; i < n; ++i) { + strata::kernels::iq_dequant_expert_f16(gt, dt, db[i], db[i] + gate_b, db[i] + 2 * gate_b, NFF, K, dwgu, dwd, q); + const float a = 1.f, b = 0.f; + dpct::blas::gemm(hd, oneapi::mkl::transpose::trans, oneapi::mkl::transpose::nontrans, 2 * NFF, cnt[i], K, &a, dwgu, + dpct::library_data_t::real_half, K, dxh + o * K, dpct::library_data_t::real_half, K, &b, + GUr + o * 2 * NFF, dpct::library_data_t::real_float, 2 * NFF, dpct::compute_type::f32); + strata::prefill::swiglu_interleaved(GUr + o * 2 * NFF, Hh + o * NFF, cnt[i], q); + dpct::blas::gemm(hd, oneapi::mkl::transpose::trans, oneapi::mkl::transpose::nontrans, NE, cnt[i], NFF, &a, dwd, + dpct::library_data_t::real_half, NFF, Hh + o * NFF, dpct::library_data_t::real_half, NFF, &b, + Dmr + o * NE, dpct::library_data_t::real_float, NE, dpct::compute_type::f32); + o += cnt[i]; + } + }; + auto tm = [&](auto f) { + f(); q->wait(); + const auto t0 = std::chrono::steady_clock::now(); + while (std::chrono::duration(std::chrono::steady_clock::now() - t0).count() < 0.5) { f(); q->wait(); } // GPU clocks up + const auto a = std::chrono::steady_clock::now(); + for (int r = 0; r < reps; ++r) f(); + q->wait(); + return std::chrono::duration(std::chrono::steady_clock::now() - a).count() / reps; + }; + + fused(); q->wait(); + std::vector hXq(i8::xq_bytes(lo, K)); + std::vector hdX(i8::dx_bytes(lo, K) / 4), hGU((size_t) tot * 2 * NFF); + q->memcpy(hXq.data(), Xq, hXq.size()); + q->memcpy(hdX.data(), dX, hdX.size() * 4); + q->memcpy(hGU.data(), GU, hGU.size() * 4).wait(); + const int nkb = K / 32; + auto xq_at = [&](int tile, int r, int k) { return (int) hXq[(((size_t) tile * nkb + k / 32) * 8 + r) * 32 + (k % 32)]; }; + auto dx_at = [&](int tile, int r, int kb) { return (double) hdX[((size_t) tile * nkb + kb) * 8 + r]; }; + bool ok = true; + std::vector wrow(K); + double err_c = 0, mx_c = 0, err_b = 0, rms_bref = 0; + int sampled = 0; + for (int e = 0; e < n; ++e) + for (int rl = 0; rl < cnt[e]; rl += (cnt[e] > 12 ? 5 : 1)) { + const int tile = lo.tile0[e] + rl / 8, r = rl % 8, row = lo.row0[e] + rl; + for (int v = 0; v < 2 * NFF; v += 37) { + dec_row(gt, &hb[e][(size_t) (v & 1 ? gate_b : 0) + (size_t) (v >> 1) * rowb_gu], K, wrow.data()); + double refc = 0, refb = 0; + for (int kb = 0; kb < nkb; ++kb) { + double s = 0; + for (int k = 0; k < 32; ++k) s += (double) xq_at(tile, r, kb * 32 + k) * wrow[kb * 32 + k]; + refc += s * dx_at(tile, r, kb); + } + for (int k = 0; k < K; ++k) refb += (double) h2f(hx[(size_t) row * K + k]) * wrow[k]; + const double got = hGU[(size_t) row * 2 * NFF + v]; + err_c = std::max(err_c, std::fabs(got - refc)); mx_c = std::max(mx_c, std::fabs(refc)); + err_b += (got - refb) * (got - refb); rms_bref += refb * refb; + ++sampled; + } + } + const bool ok1 = err_c <= 2e-5 * mx_c && std::sqrt(err_b / rms_bref) < 0.02; + ok = ok && ok1; + std::printf(" gate/up type %2d: exact-int8 ref max err %.2e of %.2e (%.1e) vs FP64 true rms rel err %.2e (%d samples) %s\n", gt, + err_c, mx_c, err_c / mx_c, std::sqrt(err_b / rms_bref), sampled, ok1 ? "OK" : "FAIL"); + { + std::vector hHq(i8::xq_bytes(lo, NFF)); + std::vector hdH(i8::dx_bytes(lo, NFF) / 4), hDm((size_t) tot * NE); + q->memcpy(hHq.data(), Hq, hHq.size()); + q->memcpy(hdH.data(), dH, hdH.size() * 4); + q->memcpy(hDm.data(), Dm, hDm.size() * 4).wait(); + const int nkh = NFF / 32; + double ec = 0, mc = 0, eb = 0, rb = 0, hq_bad = 0; + std::vector drow(NFF); + int smp = 0; + for (int e = 0; e < n; ++e) + for (int rl = 0; rl < cnt[e]; rl += (cnt[e] > 12 ? 5 : 1)) { + const int tile = lo.tile0[e] + rl / 8, r = rl % 8, row = lo.row0[e] + rl; + std::vector H(NFF); + for (int j = 0; j < NFF; ++j) { + const double g = hGU[(size_t) row * 2 * NFF + 2 * j], u = hGU[(size_t) row * 2 * NFF + 2 * j + 1]; + H[j] = g / (1.0 + std::exp(-g)) * u; + } + for (int kb = 0; kb < nkh; ++kb) { + double amax = 0; for (int k = 0; k < 32; ++k) amax = std::max(amax, std::fabs(H[kb * 32 + k])); + const double dd = hdH[((size_t) tile * nkh + kb) * 8 + r]; + if (std::fabs(dd - amax / 127.0) > 1e-5 * amax + 1e-30) hq_bad += 1; + } + for (int v = 0; v < NE; v += 41) { + dec_row(dt, &hb[e][2 * gate_b + (size_t) v * rowb_dn], NFF, drow.data()); + double refc = 0, refb = 0; + for (int kb = 0; kb < nkh; ++kb) { + double s = 0; + for (int k = 0; k < 32; ++k) s += (double) hHq[(((size_t) tile * nkh + kb) * 8 + r) * 32 + k] * drow[kb * 32 + k]; + refc += s * hdH[((size_t) tile * nkh + kb) * 8 + r]; + } + for (int k = 0; k < NFF; ++k) refb += H[k] * drow[k]; + const double got = hDm[(size_t) row * NE + v]; + ec = std::max(ec, std::fabs(got - refc)); mc = std::max(mc, std::fabs(refc)); + eb += (got - refb) * (got - refb); rb += refb * refb; + ++smp; + } + } + const bool ok2 = ec <= 2e-5 * mc && std::sqrt(eb / rb) < 0.03 && hq_bad == 0; + ok = ok && ok2; + std::printf(" down type %2d : exact-int8 ref max err %.2e of %.2e (%.1e) vs FP64 true rms rel err %.2e, swiglu scale mismatches %.0f (%d samples) %s\n", + dt, ec, mc, ec / mc, std::sqrt(eb / rb), hq_bad, smp, ok2 ? "OK" : "FAIL"); + } + ref(); q->wait(); + { + std::vector a((size_t) tot * NE), b((size_t) tot * NE); + q->memcpy(a.data(), Dmr, a.size() * 4); + q->memcpy(b.data(), Dm, b.size() * 4).wait(); + double e2 = 0, r2 = 0; + for (size_t i = 0; i < a.size(); ++i) { e2 += (double) (a[i] - b[i]) * (a[i] - b[i]); r2 += (double) a[i] * a[i]; } + std::printf(" chain vs dequantize + oneMKL (FP16 path): rms rel diff %.2e (rows %d)\n", std::sqrt(e2 / r2), tot); + } + Result res{ok, tm(ref) / n, tm(fused) / n}; + const double t_q = tm([&] { i8::quantize_rows(dxh, lo, K, Xq, dX, q); }) / n; + const double t_gu = tm([&] { i8::gate_up(gt, pb.data(), gate_b, NFF, lo, K, Xq, dX, GU, q); }) / n; + const double t_sw = tm([&] { i8::swiglu_quantize(GU, lo, NFF, Hq, dH, q); }) / n; + const double t_dn = tm([&] { i8::down(dt, pb.data(), 2 * gate_b, NE, lo, NFF, Hq, dH, Dm, q); }) / n; + std::printf(" rows %d (%d experts, mean %.0f): dequant+oneMKL %.1f us/expert | fused int8 %.1f us/expert (%.2fx) [quantize %.1f, gate/up %.1f, swiglu+q %.1f, down %.1f]\n", + tot, n, (double) tot / n, res.t_ref, res.t_fused, res.t_ref / res.t_fused, t_q, t_gu, t_sw, t_dn); + for (int i = 0; i < n; ++i) sycl::free(db[i], *q); + sycl::free(dxh, *q); sycl::free(Xq, *q); sycl::free(dX, *q); sycl::free(Hq, *q); sycl::free(dH, *q); sycl::free(GU, *q); + sycl::free(Dm, *q); sycl::free(GUr, *q); sycl::free(Dmr, *q); sycl::free(Hh, *q); sycl::free(dwgu, *q); sycl::free(dwd, *q); + return res; +} + +int main(int argc, char** argv) { + const int mean = argc > 1 ? std::atoi(argv[1]) : 80; + const int n = argc > 2 ? std::atoi(argv[2]) : 16; + const int reps = argc > 3 ? std::atoi(argv[3]) : 10; + const int seed = argc > 4 ? std::atoi(argv[4]) : 1; + sycl::queue* q = &dpct::get_in_order_queue(); + if (!i8::available(q)) { std::printf("esimd_moe_parity: SKIP (no ESIMD device with the s8 8x16x32 DPAS)\n"); return 0; } + dpct::blas::descriptor_ptr hd = new dpct::blas::descriptor(); + hd->set_queue(q); + std::vector> cases = {{21, 20}, {18, 20}, {22, 20}, {21, 42}, {18, 42}, {22, 42}}; + if (argc > 6) cases = {{std::atoi(argv[5]), std::atoi(argv[6])}}; + int fails = 0; + for (auto [gt, dt] : cases) { + std::printf("gate/up %d, down %d, mean %d rows, %d experts\n", gt, dt, mean, n); + fails += !run_case(q, hd, gt, dt, mean, n, reps, seed).ok; + } + std::printf("%s\n", fails ? "FAILED" : "all OK"); + return fails ? 1 : 0; +} diff --git a/sycl/src/prefill/esimd_moe.dp.cpp b/sycl/src/prefill/esimd_moe.dp.cpp new file mode 100644 index 00000000..e0f9a077 --- /dev/null +++ b/sycl/src/prefill/esimd_moe.dp.cpp @@ -0,0 +1,1051 @@ +// 151-b70: fused int8 DPAS expert products (ESIMD, Battlemage) - see include/strata/prefill/esimd_moe.hpp and +// docs/INTEL_INT8_EXPERTS.md (the behaviour note). +// +// * Tile. One hardware thread owns 16 output rows (a DPAS N tile; for gate/up the 16 virtual rows alternate gate/up) and up to +// MT x 8 activation rows (MT = 2, 4 or 8, picked per group from the experts' mean row count). It walks K in steps of 32: +// decode the 16 weight rows' 32 values into the B operand (registers only), then for each of its row tiles one s8 DPAS 8x16x32 +// into a zeroed int32 tile, converted to float and scaled by (weight scale of the row and 32-block) x (activation scale of the +// row and 32-block) into a float accumulator. There is no shared memory and no barrier. +// * Decode once per tile: the B operand is decoded once per thread and applied to all its MT row tiles. An expert with more rows +// than 8 x MT is split over row-block threads, each decoding again. A thread's accumulators are MT tiles of 512 bytes in an +// 8 KB register file (256 GRF of 32 bytes): MT 12, or two output tiles per thread, spilled (3-15 KB) and ran 2-5x slower. +// * Scales. Activations: q8_1 as llama.cpp (d = amax / 127, q = round half away from zero), one float per row and 32 of K. +// Weights: IQ3_S d (1 + 2 s), IQ3_XXS d (2 s + 1) / 4, IQ2_S d (2 s + 1) / 8 per 16 (two DPAS per 32 with the other half +// zeroed), IQ4_NL d per 32, Q2_0 d per 64; the int8 values are the codebook entries with their signs, never rounded. The int32 +// dot product of a 32-block is exact and exactly convertible to float. The float accumulation order is fixed (K ascending). +// * Edge cases. Rows are padded to tiles of 8 with zeros (stores are masked to the real rows); a group of up to 16 experts per +// launch; K a multiple of 256 (IQ3_S / IQ3_XXS / IQ2_S) / 64 (Q2_0) / 32 (IQ4_NL); output rows a multiple of 16. Blob reads +// never go past a matrix end. +// * Fallback. available() is false without the s8 8x16x32 DPAS (a non-Battlemage device) and the caller keeps the dequantize + +// oneMKL path; gate_up()/down() return false for a type / shape they do not handle. +// * ESIMD on this compiler (oneAPI 2026.1, bmg-g31): a dynamic index into the kernel-argument arrays, and `/` or `%` by a run-time +// value, gave wrong values / garbage pointers (the first weight read faulted the GPU); the kernels use constant-index reads +// (pick_expert) and 2-D grids. gather with VS > 1 is not available on Battlemage. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#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; } +bool battlemage(void*) { return false; } +bool any_battlemage() { 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 +#else +namespace strata::prefill::i8 { +namespace { +#define GGML_TABLE_BEGIN(type, name, size) static const type name[size] = { +#define GGML_TABLE_END() }; +#include "iq_tables.inc" +#undef GGML_TABLE_BEGIN +#undef GGML_TABLE_END + +using namespace sycl::ext::intel::esimd; +namespace xmx = sycl::ext::intel::esimd::xmx; +using half = sycl::half; + +// ggml types handled +constexpr int T_IQ3XXS = 18, T_IQ4NL = 20, T_IQ3S = 21, T_IQ2S = 22, T_Q2_0 = 42; +template constexpr int blk_bytes() { return F == T_IQ3S ? 110 : F == T_IQ3XXS ? 98 : F == T_IQ2S ? 82 : F == T_IQ4NL ? 18 : 18; } +constexpr int block_bytes_of(int f) { return f == T_IQ3S ? 110 : f == T_IQ3XXS ? 98 : f == T_IQ2S ? 82 : 18; } +constexpr int block_vals_of(int f) { return (f == T_IQ3S || f == T_IQ3XXS || f == T_IQ2S) ? 256 : f == T_Q2_0 ? 64 : 32; } + +// One device table buffer (uint32 units): the codebooks the decoders gather from. +constexpr int O_IQ3S = 0; // iq3s_grid[512] +constexpr int O_IQ3XXS = 512; // iq3xxs_grid[256] +constexpr int O_IQ2S = 768; // iq2s_grid[1024] as 2048 dwords (low dword of an entry first) +constexpr int O_KSIGNS = 2816; // ksigns_iq2xs[128], one byte in the low byte of each dword +constexpr int O_IQ4 = 2944; // [256]: byte b -> kvalues_iq4nl[b & 15] in byte 0, kvalues_iq4nl[b >> 4] in byte 1 +constexpr int O_Q2 = 3200; // [256]: byte b -> its four 2-bit codes minus 1, as four int8 (Q2_0 values) +constexpr int N_TABLE = 3456; + +uint32_t* tables(sycl::queue& q) { + static std::mutex mu; + static std::unordered_map per_dev; // a layer split has one prompt path per card + std::lock_guard lk(mu); + uint32_t*& t = per_dev[q.get_device()]; + if (!t) { + std::vector h(N_TABLE, 0); + for (int i = 0; i < 512; ++i) h[O_IQ3S + i] = iq3s_grid[i]; + for (int i = 0; i < 256; ++i) h[O_IQ3XXS + i] = iq3xxs_grid[i]; + for (int i = 0; i < 1024; ++i) { h[O_IQ2S + 2 * i] = (uint32_t) iq2s_grid[i]; h[O_IQ2S + 2 * i + 1] = (uint32_t) (iq2s_grid[i] >> 32); } + for (int i = 0; i < 128; ++i) h[O_KSIGNS + i] = ksigns_iq2xs[i]; + for (int b = 0; b < 256; ++b) { + h[O_IQ4 + b] = (uint32_t) (uint8_t) kvalues_iq4nl[b & 15] | ((uint32_t) (uint8_t) kvalues_iq4nl[b >> 4] << 8); + uint32_t q2 = 0; + for (int k = 0; k < 4; ++k) q2 |= (uint32_t) (uint8_t) (int8_t) (((b >> (2 * k)) & 3) - 1) << (8 * k); + h[O_Q2 + b] = q2; + } + uint32_t* d = sycl::malloc_device(N_TABLE, q); + q.memcpy(d, h.data(), N_TABLE * 4); + q.wait(); + t = d; + } + return t; +} + +// unaligned 32-bit read at a 2-byte aligned byte offset (per lane) through two dword gathers +SYCL_ESIMD_FUNCTION inline simd ld32(const uint8_t* base, simd off) { + simd a = off & ~3u; + simd lo = gather(reinterpret_cast(base), a); + simd hi = gather(reinterpret_cast(base), a + 4u); + simd sh = (off & 2u) << 3; // 0 or 16 + return (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 ld32c(const uint8_t* base, simd off, uint32_t lim) { + simd a = off & ~3u; + simd a2 = a + 4u; + a2.merge(simd(lim), a2 > lim); + simd lo = gather(reinterpret_cast(base), a); + simd hi = gather(reinterpret_cast(base), a2); + simd sh = (off & 2u) << 3; + return (lo >> sh) | ((hi << 16) << (16u - sh)); +} +SYCL_ESIMD_FUNCTION inline simd ld16(const uint8_t* base, simd off) { + simd a = off & ~3u; + simd lo = gather(reinterpret_cast(base), a); + return (lo >> ((off & 2u) << 3)) & 0xffffu; +} +SYCL_ESIMD_FUNCTION inline simd half_of(simd h16) { + simd lo = h16.template bit_cast_view().template select<16, 2>(0); + simd hh = lo.template bit_cast_view(); + simd f = hh; + return f; +} +SYCL_ESIMD_FUNCTION inline simd dpas_s8(simd b, simd a) { + simd bi = b.template bit_cast_view(); + return xmx::dpas<8, 8, int, int, int, int, xmx::dpas_argument_type::s8, xmx::dpas_argument_type::s8>(simd(0), bi, a); +} +// sign nibble -> four negation bytes: (g ^ mask) + m negates the bytes whose sign bit is set (g is never 0xFF per byte) +SYCL_ESIMD_FUNCTION inline simd apply_signs(simd g, simd nib) { + simd m = ((nib * 0x00204081u) & 0x01010101u); + simd mask = m * 255u; + return (g ^ mask) + m; +} + +struct GArgs { + const uint8_t* blob[kMaxGroup]; + uint32_t sec_off; // gate/up: byte offset of the up rows; down: byte offset of the down rows + int n; + int row0[kMaxGroup + 1]; + int tile0[kMaxGroup + 1]; + int rb0[kMaxGroup + 1]; // first row block of expert i + const int8_t* Xq; + const float* dx; + float* Y; + const uint32_t* tab; + int ntiles; // output tiles of 16 + int nkb; // K / 32 + int rowb; // bytes per weight row + int ldy; + uint32_t lim; // byte offset of the last dword of the matrix the clamped reads (ld32c) stay inside + int 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 +}; + +// The expert a work item belongs to, with constant-index reads of the kernel argument arrays. +struct Pick { int e, row0, cnt, tile0, rb0; const uint8_t* blob; }; +SYCL_ESIMD_FUNCTION inline Pick pick_expert(const GArgs& a, int rbg) { + Pick p{0, a.row0[0], a.row0[1] - a.row0[0], a.tile0[0], a.rb0[0], a.blob[0]}; +#pragma unroll + for (int i = 1; i < kMaxGroup; ++i) + if (i < a.n && rbg >= a.rb0[i]) p = Pick{i, a.row0[i], a.row0[i + 1] - a.row0[i], a.tile0[i], a.rb0[i], a.blob[i]}; + return p; +} + +int fill_args_mt(GArgs& a, const Layout& lo, int MT) { + int rb = 0; + for (int i = 0; i < lo.n; ++i) { + a.row0[i] = lo.row0[i]; + a.tile0[i] = lo.tile0[i]; + a.rb0[i] = rb; + const int ntl = (lo.cnt[i] + 7) / 8; + rb += (ntl + MT - 1) / MT; + } + a.row0[lo.n] = lo.row0[lo.n]; + a.tile0[lo.n] = lo.tile0[lo.n]; + a.rb0[lo.n] = rb; + a.n = lo.n; + return rb; +} + +template struct TagGu; +template struct TagDn; + +// ------------------------------------------------------------------------------------------------ gate/up +template +void launch_gu(sycl::queue& q, const GArgs a, int nrowblocks) { + auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size}; + constexpr int NS = (F == T_IQ2S) ? 2 : 1; // IQ2_S: two scales per 32 values -> two DPAS with the other half zeroed + q.submit([&](sycl::handler& h) { + h.parallel_for>(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; + 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; + simd lane(0, 1); + simd ro = (lane & 1u) * a.sec_off + ((lane >> 1) + (uint32_t) (8 * nt)) * (uint32_t) a.rowb; + simd acc = 0.f; + const int* Xi = reinterpret_cast(a.Xq); + for (int sb = 0; sb < ((a.dbg & 8) ? 0 : (a.nkb >> 3)); ++sb) { + const uint32_t P = (uint32_t) sb * blk_bytes(); + const simd d = half_of(ld16(We, ro + P)); + simd w0 = 0, w1 = 0, w2 = 0, w3 = 0; // sb-level fields + if constexpr (F == T_IQ3S) { + w0 = ld32(We, ro + (P + 106)); // scales + w1 = ld32(We, ro + (P + 66)); // qh 0..3 + w2 = ld32(We, ro + (P + 70)); // qh 4..7 + } else if constexpr (F == T_IQ2S) { + w0 = ld32(We, ro + (P + 74)); // scales 0..3 + w1 = ld32(We, ro + (P + 78)); // scales 4..7 + w2 = ld32(We, ro + (P + 66)); // qh 0..3 + w3 = ld32(We, ro + (P + 70)); // qh 4..7 + } +#pragma unroll 1 + for (int ib = 0; ib < 8; ++ib) { + const int kb = sb * 8 + ib; + simd fr0 = 0x01010101u, fr1 = 0u; + simd sw0 = 1.f, sw1 = 1.f; + if (!(a.dbg & 1)) { + if constexpr (F == T_IQ3S) { + simd q0 = ld32(We, ro + (P + 2 + 8 * ib)); + simd q1 = ld32(We, ro + (P + 6 + 8 * ib)); + simd sg = ld32(We, ro + (P + 74 + 4 * ib)); + simd qhv = (((ib < 4) ? w1 : w2) >> (8 * (ib & 3))) & 0xffu; + simd scn = ((w0 >> (8 * (ib >> 1))) >> (4 * (ib & 1))) & 0xfu; + sw0 = d * simd(simd(scn * 2u + 1u)); +#pragma unroll + for (int r = 0; r < 8; ++r) { + simd qsw = r < 4 ? q0 : q1; + simd idx = ((qsw >> (8 * (r & 3))) & 0xffu) | (((qhv >> r) & 1u) << 8); + simd g = gather(T + O_IQ3S, idx << 2); + simd 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 q0 = ld32(We, ro + (P + 2 + 8 * ib)); + simd q1 = ld32(We, ro + (P + 6 + 8 * ib)); + simd aux = ld32(We, ro + (P + 66 + 4 * ib)); + sw0 = d * simd(simd((aux >> 28) * 2u + 1u)) * 0.25f; +#pragma unroll + for (int il = 0; il < 4; ++il) { + simd sbyte = gather(T + O_KSIGNS, ((aux >> (7 * il)) & 127u) << 2); +#pragma unroll + for (int hh = 0; hh < 2; ++hh) { + const int r = 2 * il + hh; + simd qsw = r < 4 ? q0 : q1; + simd idx = (qsw >> (8 * (r & 3))) & 0xffu; + simd g = gather(T + O_IQ3XXS, idx << 2); + fr0.template select<16, 1>(16 * r) = apply_signs(g, (sbyte >> (4 * hh)) & 0xfu); + } + } + } else if constexpr (F == T_IQ2S) { + simd idw = ld32(We, ro + (P + 2 + 4 * ib)); + simd sgw = ld32(We, ro + (P + 34 + 4 * ib)); + simd qhb = (((ib < 4) ? w2 : w3) >> (8 * (ib & 3))) & 0xffu; + simd scb = (((ib < 4) ? w0 : w1) >> (8 * (ib & 3))) & 0xffu; + sw0 = d * simd(simd((scb & 0xfu) * 2u + 1u)) * 0.125f; + sw1 = d * simd(simd((scb >> 4) * 2u + 1u)) * 0.125f; +#pragma unroll + for (int il = 0; il < 4; ++il) { + simd idx = ((idw >> (8 * il)) & 0xffu) | ((qhb << (8 - 2 * il)) & 0x300u); + simd gl = gather(T + O_IQ2S, (idx << 3)); + simd gh = gather(T + O_IQ2S, (idx << 3) + 4u); + simd sbyte = (sgw >> (8 * il)) & 0xffu; + simd vl = apply_signs(gl, sbyte & 0xfu); + simd 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 holds values 0..15 (dwords 0..3, the rest zero), fr1 values 16..31 (dwords 4..7) + 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 av = 0x01010101; + simd dxv = 1.f; + if (!(a.dbg & 2)) { + av = block_load(Xi + ((size_t) (tbase + i) * a.nkb + kb) * 64); + dxv = block_load(a.dx + ((size_t) (tbase + i) * a.nkb + kb) * 8); + } + simd 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 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); + } + } + } + } + } + } +#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(a.Y + ((size_t) (pk.row0 + rl)) * a.ldy + 16 * nt, acc.template select<16, 1>(128 * i + 16 * r)); + } + } + } + }); + }); +} + +// ------------------------------------------------------------------------------------------------ down +template +void launch_dn(sycl::queue& q, const GArgs a, int nrowblocks) { + auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size}; + q.submit([&](sycl::handler& h) { + h.parallel_for>(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; + 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; + simd lane(0, 1); + simd ro = (lane + (uint32_t) (16 * nt)) * (uint32_t) a.rowb + a.sec_off; + simd acc = 0.f; + const int* Xi = reinterpret_cast(a.Xq); + for (int kb = 0; kb < ((a.dbg & 8) ? 0 : a.nkb); ++kb) { + simd sw0 = 1.f; + simd 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 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 dwords + simd t0 = gather(T + O_IQ4, (qd & 0xffu) << 2); + simd t1 = gather(T + O_IQ4, ((qd >> 8) & 0xffu) << 2); + simd t2 = gather(T + O_IQ4, ((qd >> 16) & 0xffu) << 2); + simd t3 = gather(T + O_IQ4, (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: 64 values per block (2 + 16 bytes), two 32-blocks per block, one table lookup per byte + const uint32_t P = (uint32_t) (kb >> 1) * 18; + const int hb = kb & 1; + sw0 = half_of(ld16(We, ro + P)); + simd q0 = ld32c(We, ro + (P + 2 + 8 * hb), a.lim); + simd q1 = ld32c(We, ro + (P + 6 + 8 * hb), a.lim); +#pragma unroll + for (int r = 0; r < 8; ++r) { + simd qb = ((r < 4 ? q0 : q1) >> (8 * (r & 3))) & 0xffu; + fr0.template select<16, 1>(16 * r) = gather(T + O_Q2, qb << 2); + } + } + } +#pragma unroll + for (int i = 0; i < MT; ++i) { + if (i < nvalid) { + simd av = 0x01010101; + simd dxv = 1.f; + if (!(a.dbg & 2)) { + av = block_load(Xi + ((size_t) (tbase + i) * a.nkb + kb) * 64); + dxv = block_load(a.dx + ((size_t) (tbase + i) * a.nkb + kb) * 8); + } + simd 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); + } + } + } + } +#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(a.Y + ((size_t) (pk.row0 + rl)) * a.ldy + 16 * nt, acc.template select<16, 1>(128 * i + 16 * r)); + } + } + } + }); + }); +} + +// ------------------------------------------------------------------------------------------------ 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 constexpr int tab_bytes() { + return F == T_IQ3S ? 2048 : F == T_IQ3XXS ? 1536 : F == T_IQ2S ? 8192 : 1024; // IQ3XXS: grid 1024 + ksigns 512 +} + +template +struct WgLayout { + static constexpr int TB = tab_bytes(); + 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(src_ + 64 * k, kAl16); \ + if (s_part == 0) stg_dx = block_load(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(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(base_ + L::ASZ + s_tile * 128, stg_dx, kAl16); \ + } + +template struct TagGuW; +template struct TagDnW; + +template +void launch_gu_wg(sycl::queue& q, const GArgs a, int nrowblocks) { + using L = WgLayout; + auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size}; + constexpr int NS = (F == T_IQ2S) ? 2 : 1; + q.submit([&](sycl::handler& h) { + h.parallel_for>(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(); + 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(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() / WGT / 64; ++k) + slm_block_store(lt * (tab_bytes() / WGT) + 64 * k, block_load(T + O_IQ3S + (lt * (tab_bytes() / 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(lt * (1024 / WGT) + 64 * k, block_load(T + O_IQ3XXS + (lt * (1024 / WGT) + 64 * k) / 4, kAl16), kAl16); + slm_block_store(1024 + lt * (512 / WGT), block_load(T + O_KSIGNS + lt * (512 / WGT) / 4, kAl16), kAl16); + } else { // IQ2_S +#pragma unroll + for (int k = 0; k < tab_bytes() / WGT / 64; ++k) + slm_block_store(lt * (tab_bytes() / WGT) + 64 * k, block_load(T + O_IQ2S + (lt * (tab_bytes() / 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 stg; + simd stg_dx; + simd lane(0, 1); + simd ro = (lane & 1u) * a.sec_off + ((lane >> 1) + (uint32_t) (8 * nt)) * (uint32_t) a.rowb; + simd 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 d = 0.f; + simd 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(); + 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(); +#pragma unroll 1 + for (int ib4 = 0; ib4 < 4; ++ib4) { + const int ib = ((c & 1) << 2) + ib4; + simd fr0 = 0x01010101u, fr1 = 0u; + simd sw0 = 1.f, sw1 = 1.f; + if (!(a.dbg & 1)) { + if constexpr (F == T_IQ3S) { + simd q0 = ld32(We, ro + (P + 2 + 8 * ib)); + simd q1 = ld32(We, ro + (P + 6 + 8 * ib)); + simd sg = ld32(We, ro + (P + 74 + 4 * ib)); + simd qhv = (((ib < 4) ? w1 : w2) >> (8 * (ib & 3))) & 0xffu; + simd scn = ((w0 >> (8 * (ib >> 1))) >> (4 * (ib & 1))) & 0xfu; + sw0 = d * simd(simd(scn * 2u + 1u)); +#pragma unroll + for (int r = 0; r < 8; ++r) { + simd qsw = r < 4 ? q0 : q1; + simd idx = ((qsw >> (8 * (r & 3))) & 0xffu) | (((qhv >> r) & 1u) << 8); + simd g = slm_gather(idx << 2); + simd 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 q0 = ld32(We, ro + (P + 2 + 8 * ib)); + simd q1 = ld32(We, ro + (P + 6 + 8 * ib)); + simd aux = ld32(We, ro + (P + 66 + 4 * ib)); + sw0 = d * simd(simd((aux >> 28) * 2u + 1u)) * 0.25f; +#pragma unroll + for (int il = 0; il < 4; ++il) { + simd sbyte = slm_gather(1024u + (((aux >> (7 * il)) & 127u) << 2)); +#pragma unroll + for (int hh = 0; hh < 2; ++hh) { + const int r = 2 * il + hh; + simd qsw = r < 4 ? q0 : q1; + simd idx = (qsw >> (8 * (r & 3))) & 0xffu; + simd g = slm_gather(idx << 2); + fr0.template select<16, 1>(16 * r) = apply_signs(g, (sbyte >> (4 * hh)) & 0xfu); + } + } + } else if constexpr (F == T_IQ2S) { + simd idw = ld32(We, ro + (P + 2 + 4 * ib)); + simd sgw = ld32(We, ro + (P + 34 + 4 * ib)); + simd qhb = (((ib < 4) ? w2 : w3) >> (8 * (ib & 3))) & 0xffu; + simd scb = (((ib < 4) ? w0 : w1) >> (8 * (ib & 3))) & 0xffu; + sw0 = d * simd(simd((scb & 0xfu) * 2u + 1u)) * 0.125f; + sw1 = d * simd(simd((scb >> 4) * 2u + 1u)) * 0.125f; +#pragma unroll + for (int il = 0; il < 4; ++il) { + simd idx = ((idw >> (8 * il)) & 0xffu) | ((qhb << (8 - 2 * il)) & 0x300u); + simd gl = slm_gather(idx << 3); + simd gh = slm_gather((idx << 3) + 4u); + simd sbyte = (sgw >> (8 * il)) & 0xffu; + simd vl = apply_signs(gl, sbyte & 0xfu); + simd 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 av = 0x01010101; + simd dxv = 1.f; + if (!(a.dbg & 2)) { + av = slm_block_load(stage_off + i * 1024 + ib4 * 256, kAl16); + dxv = slm_block_load(stage_off + L::ASZ + i * 128 + ib4 * 32, kAl16); + } + simd 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 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(a.Y + ((size_t) (pk.row0 + rl)) * a.ldy + 16 * nt, acc.template select<16, 1>(128 * i + 16 * r)); + } + } + } + }); + }); +} + +template +void launch_dn_wg(sycl::queue& q, const GArgs a, int nrowblocks) { + using L = WgLayout; + auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size}; + q.submit([&](sycl::handler& h) { + h.parallel_for>(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(); + 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(a.Xq); + constexpr uint32_t TOFF = (F == T_IQ4NL) ? O_IQ4 : O_Q2; +#pragma unroll + for (int k = 0; k < tab_bytes() / WGT / 64; ++k) + slm_block_store(lt * (tab_bytes() / WGT) + 64 * k, block_load(T + TOFF + (lt * (tab_bytes() / WGT) + 64 * k) / 4, kAl16), kAl16); + const int s_tile = lt / L::SPLIT, s_part = lt % L::SPLIT; + simd stg; + simd stg_dx; + simd lane(0, 1); + simd ro = (lane + (uint32_t) (16 * nt)) * (uint32_t) a.rowb + a.sec_off; + simd 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 sw0 = 1.f; + simd 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 qd = ld32c(We, ro + (P + 2 + 4 * j), a.lim); + simd t0 = slm_gather((qd & 0xffu) << 2); + simd t1 = slm_gather(((qd >> 8) & 0xffu) << 2); + simd t2 = slm_gather(((qd >> 16) & 0xffu) << 2); + simd t3 = slm_gather((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 q0 = ld32c(We, ro + (P + 2 + 8 * hb), a.lim); + simd q1 = ld32c(We, ro + (P + 6 + 8 * hb), a.lim); +#pragma unroll + for (int r = 0; r < 8; ++r) { + simd qb = ((r < 4 ? q0 : q1) >> (8 * (r & 3))) & 0xffu; + fr0.template select<16, 1>(16 * r) = slm_gather(qb << 2); + } + } + } +#pragma unroll + for (int i = 0; i < MT; ++i) { + if (i < nvalid) { + simd av = 0x01010101; + simd dxv = 1.f; + if (!(a.dbg & 2)) { + av = slm_block_load(stage_off + i * 1024 + ib4 * 256, kAl16); + dxv = slm_block_load(stage_off + L::ASZ + i * 128 + ib4 * 32, kAl16); + } + simd 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(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; + if (mean <= 2.0) return 2; + if (mean <= 4.0) return 4; + return 8; +} +int dbg_flags() { + static const int v = [] { const char* s = std::getenv("STRATA_I8_DBG"); return s ? std::atoi(s) : 0; }(); + return v; +} +int mt_for(const Layout& lo) { + static const int mo = [] { const char* s = std::getenv("STRATA_I8_MT"); return s ? std::atoi(s) : 0; }(); + 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 +bool dispatch_mt(int mt, F&& f) { + switch (mt) { + case 2: f(std::integral_constant{}); return true; + case 4: f(std::integral_constant{}); return true; + case 8: f(std::integral_constant{}); return true; + default: return false; + } +} + +struct QArgs { + int n; + int row0[kMaxGroup + 1]; + int tile0[kMaxGroup + 1]; + int nkb; + int ld; // row length in elements of the source +}; +class QuantTag; +class SwigluTag; + +} // namespace + +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; +} + +namespace { +bool bmg_arch(const sycl::device& d) { + namespace ex = sycl::ext::oneapi::experimental; + if (!d.is_gpu()) return false; + const auto a = d.get_info(); + return a == ex::architecture::intel_gpu_bmg_g21 || a == ex::architecture::intel_gpu_bmg_g31; +} +} // namespace + +bool battlemage(void* stream) { + sycl::queue& q = *strata::q_of(stream); + return bmg_arch(q.get_device()); +} + +bool any_battlemage() { + static const bool v = [] { + try { + for (const auto& d : sycl::device::get_devices(sycl::info::device_type::gpu)) + if (bmg_arch(d)) return true; + } catch (...) {} + return false; + }(); + return v; +} + +bool available(void* stream) { + sycl::queue& q = *strata::q_of(stream); + static std::mutex mu; + static std::unordered_map per_dev; + std::lock_guard 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; + if (!d.has(sycl::aspect::ext_intel_esimd)) return false; + namespace mx = sycl::ext::oneapi::experimental::matrix; + bool s8 = false; + for (const auto& c : d.get_info()) + 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; +} + +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& lo, int K, int n_ff, Workspace& ws, void* stream) { + sycl::queue& q = *strata::q_of(stream); + static std::mutex mu; + struct St { Workspace cur; size_t cap_x = 0, cap_h = 0; }; + static std::unordered_map per_dev; + std::lock_guard 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(); + if (cur.xq) { sycl::free(cur.xq, q); sycl::free(cur.dx, q); sycl::free(cur.hq, q); sycl::free(cur.dh, q); } + cap_x = std::max(nx, cap_x + cap_x / 4); + cap_h = std::max(nh, cap_h + cap_h / 4); + cur.xq = sycl::malloc_device(cap_x, q); + cur.dx = sycl::malloc_device(cap_x / 32 / 8 * 8 + 64, q); // rows * K/32 floats = bytes / 32 + cur.hq = sycl::malloc_device(cap_h, q); + cur.dh = sycl::malloc_device(cap_h / 32 + 64, q); + if (!cur.xq || !cur.dx || !cur.hq || !cur.dh) { cap_x = cap_h = 0; cur = Workspace{}; ws = Workspace{}; return false; } + } + ws = cur; + return true; +} + +void quantize_rows(const uint16_t* X, const Layout& lo, int K, int8_t* Xq, float* dx, void* stream) { + if (lo.tile0[lo.n] == 0) return; + sycl::queue& q = *strata::q_of(stream); + QArgs a{}; + a.n = lo.n; + for (int i = 0; i <= lo.n; ++i) { a.row0[i] = lo.row0[i]; a.tile0[i] = lo.tile0[i]; } + a.nkb = K / 32; + a.ld = K; + const size_t nthreads = (size_t) lo.tile0[lo.n] * a.nkb; + const half* Xh = reinterpret_cast(X); + uint32_t* Xd = reinterpret_cast(Xq); + q.submit([&](sycl::handler& h) { + h.parallel_for(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]; + // 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 dxv = 0.f; +#pragma unroll + for (int r = 0; r < 8; ++r) { + const int rl = (T - t0e) * 8 + r; + simd qd = 0u; + if (rl < cnt) { + simd xh = block_load(Xh + ((size_t) (r0e + rl)) * a.ld + kb * 32); + simd x = xh; + float amax = hmax(abs(x)); + const float dd = amax / 127.f; + const float id127 = amax > 0.f ? 127.f / amax : 0.f; + simd y = x * id127; + simd adj = 0.5f; + adj.merge(simd(-0.5f), y < 0.f); + simd qi = convert(y + adj); + simd q8 = convert(qi); + qd = q8.template bit_cast_view(); + dxv[r] = dd; + } + block_store(Xd + ((size_t) T * a.nkb + kb) * 64 + r * 8, qd); + } + block_store(dx + ((size_t) T * a.nkb + kb) * 8, dxv); + }); + }); +} + +void swiglu_quantize(const float* GU, const Layout& lo, int n_ff, int8_t* Hq, float* dh, void* stream) { + if (lo.tile0[lo.n] == 0) return; + sycl::queue& q = *strata::q_of(stream); + QArgs a{}; + a.n = lo.n; + for (int i = 0; i <= lo.n; ++i) { a.row0[i] = lo.row0[i]; a.tile0[i] = lo.tile0[i]; } + a.nkb = n_ff / 32; + a.ld = 2 * n_ff; + const size_t nthreads = (size_t) lo.tile0[lo.n] * a.nkb; + uint32_t* Hd = reinterpret_cast(Hq); + q.submit([&](sycl::handler& h) { + h.parallel_for(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]; + // 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 dxv = 0.f; +#pragma unroll + for (int r = 0; r < 8; ++r) { + const int rl = (T - t0e) * 8 + r; + simd qd = 0u; + if (rl < cnt) { + simd v = block_load(GU + ((size_t) (r0e + rl)) * a.ld + kb * 64); + simd g = v.template select<32, 2>(0); + simd u = v.template select<32, 2>(1); + simd x = g * u / (1.f + exp(-g)); + float amax = hmax(abs(x)); + const float dd = amax / 127.f; + const float id127 = amax > 0.f ? 127.f / amax : 0.f; + simd y = x * id127; + simd adj = 0.5f; + adj.merge(simd(-0.5f), y < 0.f); + simd qi = convert(y + adj); + simd q8 = convert(qi); + qd = q8.template bit_cast_view(); + dxv[r] = dd; + } + block_store(Hd + ((size_t) T * a.nkb + kb) * 64 + r * 8, qd); + } + block_store(dh + ((size_t) T * a.nkb + kb) * 8, dxv); + }); + }); +} + +bool gate_up(int gu_type, const uint8_t* const* blob, size_t up_off, int n_ff, const Layout& lo, int K, const int8_t* Xq, + const float* dx, float* GU, void* stream) { + if (lo.n == 0 || lo.tile0[lo.n] == 0) return true; + if ((gu_type != T_IQ3S && gu_type != T_IQ3XXS && gu_type != T_IQ2S) || K % 256 != 0 || (2 * n_ff) % 16 != 0 || + (up_off & 3) != 0 || lo.n > kMaxGroup) + return false; + sycl::queue& q = *strata::q_of(stream); + GArgs a{}; + for (int i = 0; i < lo.n; ++i) a.blob[i] = blob[i]; + a.sec_off = (uint32_t) up_off; + a.Xq = Xq; a.dx = dx; a.Y = GU; + a.tab = tables(q); + a.ntiles = 2 * n_ff / 16; + a.nkb = K / 32; + a.rowb = (K / 256) * block_bytes_of(gu_type); + a.ldy = 2 * n_ff; + 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 (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(q, a, rb); + else if (gu_type == T_IQ3XXS) launch_gu_wg(q, a, rb); + else launch_gu_wg(q, a, rb); + } else if (grf_for(MT) == 128) { + if (gu_type == T_IQ3S) launch_gu(q, a, rb); + else if (gu_type == T_IQ3XXS) launch_gu(q, a, rb); + else launch_gu(q, a, rb); + } else { + if (gu_type == T_IQ3S) launch_gu(q, a, rb); + else if (gu_type == T_IQ3XXS) launch_gu(q, a, rb); + else launch_gu(q, a, rb); + } + }); +} + +bool down(int d_type, const uint8_t* const* blob, size_t down_off, int n_embd, const Layout& lo, int n_ff, const int8_t* Hq, + const float* dh, float* Dm, void* stream) { + if (lo.n == 0 || lo.tile0[lo.n] == 0) return true; + if ((d_type != T_IQ4NL && d_type != T_Q2_0) || n_ff % block_vals_of(d_type) != 0 || n_embd % 16 != 0 || (down_off & 3) != 0 || + lo.n > kMaxGroup) + return false; + sycl::queue& q = *strata::q_of(stream); + GArgs a{}; + for (int i = 0; i < lo.n; ++i) a.blob[i] = blob[i]; + a.sec_off = (uint32_t) down_off; + a.Xq = Hq; a.dx = dh; a.Y = Dm; + a.tab = tables(q); + a.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 (wg_for() && a.nkb % 4 == 0 && a.ntiles % WGT == 0) { + if (d_type == T_IQ4NL) launch_dn_wg(q, a, rb); + else launch_dn_wg(q, a, rb); + } else if (grf_for(MT) == 128) { + if (d_type == T_IQ4NL) launch_dn(q, a, rb); + else launch_dn(q, a, rb); + } else { + if (d_type == T_IQ4NL) launch_dn(q, a, rb); + else launch_dn(q, a, rb); + } + }); +} + +} // namespace strata::prefill::i8 +#endif // STRATA_I8_NO_ESIMD diff --git a/sycl/src/prefill/iq_tables.inc b/sycl/src/prefill/iq_tables.inc new file mode 100644 index 00000000..98a238ee --- /dev/null +++ b/sycl/src/prefill/iq_tables.inc @@ -0,0 +1,377 @@ +// IQ lookup tables copied from llama.cpp ggml/src/ggml-common.h (MIT License, Copyright (c) 2023-2026 The ggml authors): +// kmask_iq2xs, ksigns_iq2xs, iq3xxs_grid, iq3s_grid, kvalues_iq4nl, iq2s_grid. Same values the dequantize kernels read. +// Included by esimd_moe.dp.cpp after defining GGML_TABLE_BEGIN / GGML_TABLE_END. +GGML_TABLE_BEGIN(uint8_t, kmask_iq2xs, 8) + 1, 2, 4, 8, 16, 32, 64, 128 +GGML_TABLE_END() +GGML_TABLE_BEGIN(uint8_t, ksigns_iq2xs, 128) + 0, 129, 130, 3, 132, 5, 6, 135, 136, 9, 10, 139, 12, 141, 142, 15, + 144, 17, 18, 147, 20, 149, 150, 23, 24, 153, 154, 27, 156, 29, 30, 159, + 160, 33, 34, 163, 36, 165, 166, 39, 40, 169, 170, 43, 172, 45, 46, 175, + 48, 177, 178, 51, 180, 53, 54, 183, 184, 57, 58, 187, 60, 189, 190, 63, + 192, 65, 66, 195, 68, 197, 198, 71, 72, 201, 202, 75, 204, 77, 78, 207, + 80, 209, 210, 83, 212, 85, 86, 215, 216, 89, 90, 219, 92, 221, 222, 95, + 96, 225, 226, 99, 228, 101, 102, 231, 232, 105, 106, 235, 108, 237, 238, 111, + 240, 113, 114, 243, 116, 245, 246, 119, 120, 249, 250, 123, 252, 125, 126, 255, +GGML_TABLE_END() +GGML_TABLE_BEGIN(uint32_t, iq3xxs_grid, 256) + 0x04040404, 0x04040414, 0x04040424, 0x04040c0c, 0x04040c1c, 0x04040c3e, 0x04041404, 0x04041414, + 0x04041c0c, 0x04042414, 0x04043e1c, 0x04043e2c, 0x040c040c, 0x040c041c, 0x040c0c04, 0x040c0c14, + 0x040c140c, 0x040c142c, 0x040c1c04, 0x040c1c14, 0x040c240c, 0x040c2c24, 0x040c3e04, 0x04140404, + 0x04140414, 0x04140424, 0x04140c0c, 0x04141404, 0x04141414, 0x04141c0c, 0x04141c1c, 0x04141c3e, + 0x04142c0c, 0x04142c3e, 0x04143e2c, 0x041c040c, 0x041c043e, 0x041c0c04, 0x041c0c14, 0x041c142c, + 0x041c3e04, 0x04240c1c, 0x04241c3e, 0x04242424, 0x04242c3e, 0x04243e1c, 0x04243e2c, 0x042c040c, + 0x042c043e, 0x042c1c14, 0x042c2c14, 0x04341c2c, 0x04343424, 0x043e0c04, 0x043e0c24, 0x043e0c34, + 0x043e241c, 0x043e340c, 0x0c04040c, 0x0c04041c, 0x0c040c04, 0x0c040c14, 0x0c04140c, 0x0c04141c, + 0x0c041c04, 0x0c041c14, 0x0c041c24, 0x0c04243e, 0x0c042c04, 0x0c0c0404, 0x0c0c0414, 0x0c0c0c0c, + 0x0c0c1404, 0x0c0c1414, 0x0c14040c, 0x0c14041c, 0x0c140c04, 0x0c140c14, 0x0c14140c, 0x0c141c04, + 0x0c143e14, 0x0c1c0404, 0x0c1c0414, 0x0c1c1404, 0x0c1c1c0c, 0x0c1c2434, 0x0c1c3434, 0x0c24040c, + 0x0c24042c, 0x0c242c04, 0x0c2c1404, 0x0c2c1424, 0x0c2c2434, 0x0c2c3e0c, 0x0c34042c, 0x0c3e1414, + 0x0c3e2404, 0x14040404, 0x14040414, 0x14040c0c, 0x14040c1c, 0x14041404, 0x14041414, 0x14041434, + 0x14041c0c, 0x14042414, 0x140c040c, 0x140c041c, 0x140c042c, 0x140c0c04, 0x140c0c14, 0x140c140c, + 0x140c1c04, 0x140c341c, 0x140c343e, 0x140c3e04, 0x14140404, 0x14140414, 0x14140c0c, 0x14140c3e, + 0x14141404, 0x14141414, 0x14141c3e, 0x14142404, 0x14142c2c, 0x141c040c, 0x141c0c04, 0x141c0c24, + 0x141c3e04, 0x141c3e24, 0x14241c2c, 0x14242c1c, 0x142c041c, 0x142c143e, 0x142c240c, 0x142c3e24, + 0x143e040c, 0x143e041c, 0x143e0c34, 0x143e242c, 0x1c04040c, 0x1c040c04, 0x1c040c14, 0x1c04140c, + 0x1c04141c, 0x1c042c04, 0x1c04342c, 0x1c043e14, 0x1c0c0404, 0x1c0c0414, 0x1c0c1404, 0x1c0c1c0c, + 0x1c0c2424, 0x1c0c2434, 0x1c14040c, 0x1c14041c, 0x1c140c04, 0x1c14142c, 0x1c142c14, 0x1c143e14, + 0x1c1c0c0c, 0x1c1c1c1c, 0x1c241c04, 0x1c24243e, 0x1c243e14, 0x1c2c0404, 0x1c2c0434, 0x1c2c1414, + 0x1c2c2c2c, 0x1c340c24, 0x1c341c34, 0x1c34341c, 0x1c3e1c1c, 0x1c3e3404, 0x24040424, 0x24040c3e, + 0x24041c2c, 0x24041c3e, 0x24042c1c, 0x24042c3e, 0x240c3e24, 0x24141404, 0x24141c3e, 0x24142404, + 0x24143404, 0x24143434, 0x241c043e, 0x241c242c, 0x24240424, 0x24242c0c, 0x24243424, 0x242c142c, + 0x242c241c, 0x242c3e04, 0x243e042c, 0x243e0c04, 0x243e0c14, 0x243e1c04, 0x2c040c14, 0x2c04240c, + 0x2c043e04, 0x2c0c0404, 0x2c0c0434, 0x2c0c1434, 0x2c0c2c2c, 0x2c140c24, 0x2c141c14, 0x2c143e14, + 0x2c1c0414, 0x2c1c2c1c, 0x2c240c04, 0x2c24141c, 0x2c24143e, 0x2c243e14, 0x2c2c0414, 0x2c2c1c0c, + 0x2c342c04, 0x2c3e1424, 0x2c3e2414, 0x34041424, 0x34042424, 0x34042434, 0x34043424, 0x340c140c, + 0x340c340c, 0x34140c3e, 0x34143424, 0x341c1c04, 0x341c1c34, 0x34242424, 0x342c042c, 0x342c2c14, + 0x34341c1c, 0x343e041c, 0x343e140c, 0x3e04041c, 0x3e04042c, 0x3e04043e, 0x3e040c04, 0x3e041c14, + 0x3e042c14, 0x3e0c1434, 0x3e0c2404, 0x3e140c14, 0x3e14242c, 0x3e142c14, 0x3e1c0404, 0x3e1c0c2c, + 0x3e1c1c1c, 0x3e1c3404, 0x3e24140c, 0x3e24240c, 0x3e2c0404, 0x3e2c0414, 0x3e2c1424, 0x3e341c04, +GGML_TABLE_END() +GGML_TABLE_BEGIN(uint32_t, iq3s_grid, 512) + 0x01010101, 0x01010103, 0x01010105, 0x0101010b, 0x0101010f, 0x01010301, 0x01010303, 0x01010305, + 0x01010309, 0x0101030d, 0x01010501, 0x01010503, 0x0101050b, 0x01010707, 0x01010901, 0x01010905, + 0x0101090b, 0x0101090f, 0x01010b03, 0x01010b07, 0x01010d01, 0x01010d05, 0x01010f03, 0x01010f09, + 0x01010f0f, 0x01030101, 0x01030103, 0x01030105, 0x01030109, 0x01030301, 0x01030303, 0x0103030b, + 0x01030501, 0x01030507, 0x0103050f, 0x01030703, 0x0103070b, 0x01030909, 0x01030d03, 0x01030d0b, + 0x01030f05, 0x01050101, 0x01050103, 0x0105010b, 0x0105010f, 0x01050301, 0x01050307, 0x0105030d, + 0x01050503, 0x0105050b, 0x01050701, 0x01050709, 0x01050905, 0x0105090b, 0x0105090f, 0x01050b03, + 0x01050b07, 0x01050f01, 0x01050f07, 0x01070107, 0x01070303, 0x0107030b, 0x01070501, 0x01070505, + 0x01070703, 0x01070707, 0x0107070d, 0x01070909, 0x01070b01, 0x01070b05, 0x01070d0f, 0x01070f03, + 0x01070f0b, 0x01090101, 0x01090307, 0x0109030f, 0x01090503, 0x01090509, 0x01090705, 0x01090901, + 0x01090907, 0x01090b03, 0x01090f01, 0x010b0105, 0x010b0109, 0x010b0501, 0x010b0505, 0x010b050d, + 0x010b0707, 0x010b0903, 0x010b090b, 0x010b090f, 0x010b0d0d, 0x010b0f07, 0x010d010d, 0x010d0303, + 0x010d0307, 0x010d0703, 0x010d0b05, 0x010d0f03, 0x010f0101, 0x010f0105, 0x010f0109, 0x010f0501, + 0x010f0505, 0x010f050d, 0x010f0707, 0x010f0b01, 0x010f0b09, 0x03010101, 0x03010103, 0x03010105, + 0x03010109, 0x03010301, 0x03010303, 0x03010307, 0x0301030b, 0x0301030f, 0x03010501, 0x03010505, + 0x03010703, 0x03010709, 0x0301070d, 0x03010b09, 0x03010b0d, 0x03010d03, 0x03010f05, 0x03030101, + 0x03030103, 0x03030107, 0x0303010d, 0x03030301, 0x03030309, 0x03030503, 0x03030701, 0x03030707, + 0x03030903, 0x03030b01, 0x03030b05, 0x03030f01, 0x03030f0d, 0x03050101, 0x03050305, 0x0305030b, + 0x0305030f, 0x03050501, 0x03050509, 0x03050705, 0x03050901, 0x03050907, 0x03050b0b, 0x03050d01, + 0x03050f05, 0x03070103, 0x03070109, 0x0307010f, 0x03070301, 0x03070307, 0x03070503, 0x0307050f, + 0x03070701, 0x03070709, 0x03070903, 0x03070d05, 0x03070f01, 0x03090107, 0x0309010b, 0x03090305, + 0x03090309, 0x03090703, 0x03090707, 0x03090905, 0x0309090d, 0x03090b01, 0x03090b09, 0x030b0103, + 0x030b0301, 0x030b0307, 0x030b0503, 0x030b0701, 0x030b0705, 0x030b0b03, 0x030d0501, 0x030d0509, + 0x030d050f, 0x030d0909, 0x030d090d, 0x030f0103, 0x030f0107, 0x030f0301, 0x030f0305, 0x030f0503, + 0x030f070b, 0x030f0903, 0x030f0d05, 0x030f0f01, 0x05010101, 0x05010103, 0x05010107, 0x0501010b, + 0x0501010f, 0x05010301, 0x05010305, 0x05010309, 0x0501030d, 0x05010503, 0x05010507, 0x0501050f, + 0x05010701, 0x05010705, 0x05010903, 0x05010907, 0x0501090b, 0x05010b01, 0x05010b05, 0x05010d0f, + 0x05010f01, 0x05010f07, 0x05010f0b, 0x05030101, 0x05030105, 0x05030301, 0x05030307, 0x0503030f, + 0x05030505, 0x0503050b, 0x05030703, 0x05030709, 0x05030905, 0x05030b03, 0x05050103, 0x05050109, + 0x0505010f, 0x05050503, 0x05050507, 0x05050701, 0x0505070f, 0x05050903, 0x05050b07, 0x05050b0f, + 0x05050f03, 0x05050f09, 0x05070101, 0x05070105, 0x0507010b, 0x05070303, 0x05070505, 0x05070509, + 0x05070703, 0x05070707, 0x05070905, 0x05070b01, 0x05070d0d, 0x05090103, 0x0509010f, 0x05090501, + 0x05090507, 0x05090705, 0x0509070b, 0x05090903, 0x05090f05, 0x05090f0b, 0x050b0109, 0x050b0303, + 0x050b0505, 0x050b070f, 0x050b0901, 0x050b0b07, 0x050b0f01, 0x050d0101, 0x050d0105, 0x050d010f, + 0x050d0503, 0x050d0b0b, 0x050d0d03, 0x050f010b, 0x050f0303, 0x050f050d, 0x050f0701, 0x050f0907, + 0x050f0b01, 0x07010105, 0x07010303, 0x07010307, 0x0701030b, 0x0701030f, 0x07010505, 0x07010703, + 0x07010707, 0x0701070b, 0x07010905, 0x07010909, 0x0701090f, 0x07010b03, 0x07010d07, 0x07010f03, + 0x07030103, 0x07030107, 0x0703010b, 0x07030309, 0x07030503, 0x07030507, 0x07030901, 0x07030d01, + 0x07030f05, 0x07030f0d, 0x07050101, 0x07050305, 0x07050501, 0x07050705, 0x07050709, 0x07050b01, + 0x07070103, 0x07070301, 0x07070309, 0x07070503, 0x07070507, 0x0707050f, 0x07070701, 0x07070903, + 0x07070907, 0x0707090f, 0x07070b0b, 0x07070f07, 0x07090107, 0x07090303, 0x0709030d, 0x07090505, + 0x07090703, 0x07090b05, 0x07090d01, 0x07090d09, 0x070b0103, 0x070b0301, 0x070b0305, 0x070b050b, + 0x070b0705, 0x070b0909, 0x070b0b0d, 0x070b0f07, 0x070d030d, 0x070d0903, 0x070f0103, 0x070f0107, + 0x070f0501, 0x070f0505, 0x070f070b, 0x09010101, 0x09010109, 0x09010305, 0x09010501, 0x09010509, + 0x0901050f, 0x09010705, 0x09010903, 0x09010b01, 0x09010f01, 0x09030105, 0x0903010f, 0x09030303, + 0x09030307, 0x09030505, 0x09030701, 0x0903070b, 0x09030907, 0x09030b03, 0x09030b0b, 0x09050103, + 0x09050107, 0x09050301, 0x0905030b, 0x09050503, 0x09050707, 0x09050901, 0x09050b0f, 0x09050d05, + 0x09050f01, 0x09070109, 0x09070303, 0x09070307, 0x09070501, 0x09070505, 0x09070703, 0x0907070b, + 0x09090101, 0x09090105, 0x09090509, 0x0909070f, 0x09090901, 0x09090f03, 0x090b010b, 0x090b010f, + 0x090b0503, 0x090b0d05, 0x090d0307, 0x090d0709, 0x090d0d01, 0x090f0301, 0x090f030b, 0x090f0701, + 0x090f0907, 0x090f0b03, 0x0b010105, 0x0b010301, 0x0b010309, 0x0b010505, 0x0b010901, 0x0b010909, + 0x0b01090f, 0x0b010b05, 0x0b010d0d, 0x0b010f09, 0x0b030103, 0x0b030107, 0x0b03010b, 0x0b030305, + 0x0b030503, 0x0b030705, 0x0b030f05, 0x0b050101, 0x0b050303, 0x0b050507, 0x0b050701, 0x0b05070d, + 0x0b050b07, 0x0b070105, 0x0b07010f, 0x0b070301, 0x0b07050f, 0x0b070909, 0x0b070b03, 0x0b070d0b, + 0x0b070f07, 0x0b090103, 0x0b090109, 0x0b090501, 0x0b090705, 0x0b09090d, 0x0b0b0305, 0x0b0b050d, + 0x0b0b0b03, 0x0b0b0b07, 0x0b0d0905, 0x0b0f0105, 0x0b0f0109, 0x0b0f0505, 0x0d010303, 0x0d010307, + 0x0d01030b, 0x0d010703, 0x0d010707, 0x0d010d01, 0x0d030101, 0x0d030501, 0x0d03050f, 0x0d030d09, + 0x0d050305, 0x0d050709, 0x0d050905, 0x0d050b0b, 0x0d050d05, 0x0d050f01, 0x0d070101, 0x0d070309, + 0x0d070503, 0x0d070901, 0x0d09050b, 0x0d090907, 0x0d090d05, 0x0d0b0101, 0x0d0b0107, 0x0d0b0709, + 0x0d0b0d01, 0x0d0d010b, 0x0d0d0901, 0x0d0f0303, 0x0d0f0307, 0x0f010101, 0x0f010109, 0x0f01010f, + 0x0f010501, 0x0f010505, 0x0f01070d, 0x0f010901, 0x0f010b09, 0x0f010d05, 0x0f030105, 0x0f030303, + 0x0f030509, 0x0f030907, 0x0f03090b, 0x0f050103, 0x0f050109, 0x0f050301, 0x0f05030d, 0x0f050503, + 0x0f050701, 0x0f050b03, 0x0f070105, 0x0f070705, 0x0f07070b, 0x0f070b07, 0x0f090103, 0x0f09010b, + 0x0f090307, 0x0f090501, 0x0f090b01, 0x0f0b0505, 0x0f0b0905, 0x0f0d0105, 0x0f0d0703, 0x0f0f0101, +GGML_TABLE_END() +GGML_TABLE_BEGIN(int8_t, kvalues_iq4nl, 16) + -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113, +GGML_TABLE_END() +GGML_TABLE_BEGIN(uint64_t, iq2s_grid, 1024) + 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, + 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b, + 0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919, + 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b, + 0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919, + 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x08080808192b192b, + 0x08080808192b2b19, 0x080808082b080808, 0x080808082b08082b, 0x080808082b081919, + 0x080808082b082b08, 0x080808082b190819, 0x080808082b191908, 0x080808082b2b0808, + 0x080808082b2b1919, 0x080808082b2b2b2b, 0x0808081908080819, 0x0808081908081908, + 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808, 0x080808190819082b, + 0x0808081908191919, 0x0808081908192b08, 0x08080819082b0819, 0x08080819082b1908, + 0x0808081919080808, 0x080808191908082b, 0x0808081919081919, 0x0808081919082b08, + 0x0808081919190819, 0x0808081919191908, 0x080808191919192b, 0x0808081919192b19, + 0x08080819192b0808, 0x08080819192b1919, 0x08080819192b2b08, 0x080808192b080819, + 0x080808192b081908, 0x080808192b190808, 0x080808192b19082b, 0x080808192b191919, + 0x080808192b2b0819, 0x080808192b2b1908, 0x0808082b08080808, 0x0808082b0808082b, + 0x0808082b08081919, 0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, + 0x0808082b082b0808, 0x0808082b082b2b2b, 0x0808082b19080819, 0x0808082b19081908, + 0x0808082b1908192b, 0x0808082b19082b19, 0x0808082b19190808, 0x0808082b19191919, + 0x0808082b2b080808, 0x0808082b2b081919, 0x0808082b2b082b2b, 0x0808082b2b191908, + 0x0808082b2b2b082b, 0x0808190808080819, 0x0808190808081908, 0x080819080808192b, + 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b, 0x0808190808191919, + 0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908, 0x08081908082b192b, + 0x08081908082b2b19, 0x0808190819080808, 0x080819081908082b, 0x0808190819081919, + 0x0808190819082b08, 0x0808190819082b2b, 0x0808190819190819, 0x0808190819191908, + 0x080819081919192b, 0x0808190819192b19, 0x08081908192b0808, 0x08081908192b082b, + 0x08081908192b1919, 0x080819082b080819, 0x080819082b081908, 0x080819082b08192b, + 0x080819082b082b19, 0x080819082b190808, 0x080819082b191919, 0x080819082b192b08, + 0x080819082b2b0819, 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, + 0x0808191908081919, 0x0808191908082b08, 0x0808191908082b2b, 0x0808191908190819, + 0x0808191908191908, 0x080819190819192b, 0x0808191908192b19, 0x08081919082b0808, + 0x08081919082b1919, 0x08081919082b2b08, 0x0808191919080819, 0x0808191919081908, + 0x080819191908192b, 0x0808191919082b19, 0x0808191919190808, 0x080819191919082b, + 0x0808191919191919, 0x0808191919192b08, 0x08081919192b0819, 0x08081919192b1908, + 0x080819192b080808, 0x080819192b08082b, 0x080819192b081919, 0x080819192b082b08, + 0x080819192b190819, 0x080819192b191908, 0x080819192b2b0808, 0x0808192b08080819, + 0x0808192b08081908, 0x0808192b0808192b, 0x0808192b08082b19, 0x0808192b08190808, + 0x0808192b08191919, 0x0808192b19080808, 0x0808192b19081919, 0x0808192b19082b08, + 0x0808192b19190819, 0x0808192b19191908, 0x0808192b192b0808, 0x0808192b2b080819, + 0x0808192b2b081908, 0x0808192b2b190808, 0x08082b0808080808, 0x08082b080808082b, + 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808190819, 0x08082b0808191908, + 0x08082b080819192b, 0x08082b0808192b19, 0x08082b08082b0808, 0x08082b08082b1919, + 0x08082b08082b2b2b, 0x08082b0819080819, 0x08082b0819081908, 0x08082b081908192b, + 0x08082b0819082b19, 0x08082b0819190808, 0x08082b081919082b, 0x08082b0819191919, + 0x08082b0819192b08, 0x08082b08192b0819, 0x08082b08192b1908, 0x08082b082b080808, + 0x08082b082b081919, 0x08082b082b191908, 0x08082b082b2b2b2b, 0x08082b1908080819, + 0x08082b1908081908, 0x08082b1908190808, 0x08082b190819082b, 0x08082b1908191919, + 0x08082b1908192b08, 0x08082b19082b0819, 0x08082b1919080808, 0x08082b1919081919, + 0x08082b1919082b08, 0x08082b1919190819, 0x08082b1919191908, 0x08082b19192b0808, + 0x08082b192b080819, 0x08082b192b190808, 0x08082b2b08080808, 0x08082b2b08190819, + 0x08082b2b08191908, 0x08082b2b082b082b, 0x08082b2b082b2b08, 0x08082b2b082b2b2b, + 0x08082b2b19190808, 0x08082b2b2b192b19, 0x0819080808080819, 0x0819080808081908, + 0x081908080808192b, 0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, + 0x0819080808191919, 0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908, + 0x08190808082b192b, 0x0819080819080808, 0x081908081908082b, 0x0819080819081919, + 0x0819080819082b08, 0x0819080819190819, 0x0819080819191908, 0x081908081919192b, + 0x0819080819192b19, 0x08190808192b0808, 0x08190808192b082b, 0x08190808192b1919, + 0x08190808192b2b08, 0x081908082b080819, 0x081908082b081908, 0x081908082b08192b, + 0x081908082b190808, 0x081908082b191919, 0x081908082b192b08, 0x081908082b2b0819, + 0x081908082b2b1908, 0x0819081908080808, 0x081908190808082b, 0x0819081908081919, + 0x0819081908082b08, 0x0819081908082b2b, 0x0819081908190819, 0x0819081908191908, + 0x081908190819192b, 0x0819081908192b19, 0x08190819082b0808, 0x08190819082b082b, + 0x08190819082b1919, 0x08190819082b2b08, 0x0819081919080819, 0x0819081919081908, + 0x081908191908192b, 0x0819081919082b19, 0x0819081919190808, 0x081908191919082b, + 0x0819081919191919, 0x0819081919192b08, 0x08190819192b0819, 0x08190819192b1908, + 0x081908192b080808, 0x081908192b08082b, 0x081908192b081919, 0x081908192b082b08, + 0x081908192b190819, 0x081908192b191908, 0x0819082b08080819, 0x0819082b08081908, + 0x0819082b08082b19, 0x0819082b08190808, 0x0819082b08191919, 0x0819082b082b0819, + 0x0819082b082b1908, 0x0819082b19080808, 0x0819082b19081919, 0x0819082b19190819, + 0x0819082b19191908, 0x0819082b2b080819, 0x0819082b2b081908, 0x0819082b2b190808, + 0x0819190808080808, 0x081919080808082b, 0x0819190808081919, 0x0819190808082b08, + 0x0819190808190819, 0x0819190808191908, 0x081919080819192b, 0x0819190808192b19, + 0x08191908082b0808, 0x08191908082b1919, 0x08191908082b2b08, 0x0819190819080819, + 0x0819190819081908, 0x081919081908192b, 0x0819190819082b19, 0x0819190819190808, + 0x081919081919082b, 0x0819190819191919, 0x0819190819192b08, 0x08191908192b0819, + 0x08191908192b1908, 0x081919082b080808, 0x081919082b08082b, 0x081919082b081919, + 0x081919082b082b08, 0x081919082b190819, 0x081919082b191908, 0x081919082b2b0808, + 0x0819191908080819, 0x0819191908081908, 0x081919190808192b, 0x0819191908082b19, + 0x0819191908190808, 0x081919190819082b, 0x0819191908191919, 0x0819191908192b08, + 0x08191919082b0819, 0x08191919082b1908, 0x0819191919080808, 0x081919191908082b, + 0x0819191919081919, 0x0819191919082b08, 0x0819191919190819, 0x0819191919191908, + 0x08191919192b0808, 0x081919192b080819, 0x081919192b081908, 0x081919192b190808, + 0x0819192b08080808, 0x0819192b08081919, 0x0819192b08082b08, 0x0819192b08190819, + 0x0819192b08191908, 0x0819192b082b0808, 0x0819192b19080819, 0x0819192b19081908, + 0x0819192b19190808, 0x0819192b2b080808, 0x0819192b2b2b2b2b, 0x08192b0808080819, + 0x08192b0808081908, 0x08192b080808192b, 0x08192b0808082b19, 0x08192b0808190808, + 0x08192b0808191919, 0x08192b0808192b08, 0x08192b08082b0819, 0x08192b0819080808, + 0x08192b081908082b, 0x08192b0819081919, 0x08192b0819082b08, 0x08192b0819190819, + 0x08192b0819191908, 0x08192b08192b0808, 0x08192b082b080819, 0x08192b082b081908, + 0x08192b1908080808, 0x08192b190808082b, 0x08192b1908081919, 0x08192b1908082b08, + 0x08192b1908190819, 0x08192b1908191908, 0x08192b19082b0808, 0x08192b1919080819, + 0x08192b1919081908, 0x08192b1919190808, 0x08192b19192b2b19, 0x08192b192b2b082b, + 0x08192b2b08081908, 0x08192b2b08190808, 0x08192b2b19080808, 0x08192b2b1919192b, + 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919, 0x082b080808082b08, + 0x082b080808190819, 0x082b080808191908, 0x082b08080819192b, 0x082b080808192b19, + 0x082b0808082b0808, 0x082b0808082b1919, 0x082b0808082b2b2b, 0x082b080819080819, + 0x082b080819081908, 0x082b080819190808, 0x082b08081919082b, 0x082b080819191919, + 0x082b0808192b1908, 0x082b08082b080808, 0x082b08082b082b2b, 0x082b08082b191908, + 0x082b08082b2b2b2b, 0x082b081908080819, 0x082b081908081908, 0x082b081908190808, + 0x082b08190819082b, 0x082b081908191919, 0x082b0819082b0819, 0x082b081919080808, + 0x082b08191908082b, 0x082b081919081919, 0x082b081919190819, 0x082b081919191908, + 0x082b0819192b0808, 0x082b08192b080819, 0x082b08192b081908, 0x082b08192b190808, + 0x082b082b08080808, 0x082b082b08082b2b, 0x082b082b082b082b, 0x082b082b082b2b08, + 0x082b082b082b2b2b, 0x082b082b19081908, 0x082b082b19190808, 0x082b082b2b082b08, + 0x082b082b2b082b2b, 0x082b082b2b2b2b08, 0x082b190808080819, 0x082b190808081908, + 0x082b19080808192b, 0x082b190808082b19, 0x082b190808190808, 0x082b190808191919, + 0x082b190808192b08, 0x082b1908082b0819, 0x082b1908082b1908, 0x082b190819080808, + 0x082b19081908082b, 0x082b190819081919, 0x082b190819082b08, 0x082b190819190819, + 0x082b190819191908, 0x082b1908192b0808, 0x082b19082b080819, 0x082b19082b081908, + 0x082b19082b190808, 0x082b191908080808, 0x082b191908081919, 0x082b191908082b08, + 0x082b191908190819, 0x082b191908191908, 0x082b1919082b0808, 0x082b191919080819, + 0x082b191919081908, 0x082b191919190808, 0x082b1919192b192b, 0x082b19192b080808, + 0x082b192b08080819, 0x082b192b08081908, 0x082b192b08190808, 0x082b192b19080808, + 0x082b192b19192b19, 0x082b2b0808080808, 0x082b2b0808081919, 0x082b2b0808190819, + 0x082b2b0808191908, 0x082b2b0819080819, 0x082b2b0819081908, 0x082b2b0819190808, + 0x082b2b082b082b2b, 0x082b2b082b2b2b2b, 0x082b2b1908080819, 0x082b2b1908081908, + 0x082b2b1908190808, 0x082b2b192b191919, 0x082b2b2b08082b2b, 0x082b2b2b082b082b, + 0x082b2b2b192b1908, 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819, + 0x1908080808081908, 0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, + 0x190808080819082b, 0x1908080808191919, 0x1908080808192b08, 0x1908080808192b2b, + 0x19080808082b0819, 0x19080808082b1908, 0x19080808082b192b, 0x1908080819080808, + 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08, 0x1908080819082b2b, + 0x1908080819190819, 0x1908080819191908, 0x190808081919192b, 0x1908080819192b19, + 0x19080808192b0808, 0x19080808192b082b, 0x19080808192b1919, 0x190808082b080819, + 0x190808082b081908, 0x190808082b190808, 0x190808082b191919, 0x190808082b192b08, + 0x190808082b2b0819, 0x190808082b2b1908, 0x1908081908080808, 0x190808190808082b, + 0x1908081908081919, 0x1908081908082b08, 0x1908081908190819, 0x1908081908191908, + 0x190808190819192b, 0x1908081908192b19, 0x19080819082b0808, 0x19080819082b082b, + 0x19080819082b1919, 0x1908081919080819, 0x1908081919081908, 0x190808191908192b, + 0x1908081919082b19, 0x1908081919190808, 0x190808191919082b, 0x1908081919191919, + 0x1908081919192b08, 0x19080819192b0819, 0x19080819192b1908, 0x190808192b080808, + 0x190808192b08082b, 0x190808192b081919, 0x190808192b082b08, 0x190808192b190819, + 0x190808192b191908, 0x190808192b2b0808, 0x1908082b08080819, 0x1908082b08081908, + 0x1908082b08190808, 0x1908082b0819082b, 0x1908082b08191919, 0x1908082b08192b08, + 0x1908082b082b1908, 0x1908082b19080808, 0x1908082b19081919, 0x1908082b19082b08, + 0x1908082b19190819, 0x1908082b19191908, 0x1908082b192b0808, 0x1908082b2b080819, + 0x1908082b2b081908, 0x1908190808080808, 0x190819080808082b, 0x1908190808081919, + 0x1908190808082b08, 0x1908190808082b2b, 0x1908190808190819, 0x1908190808191908, + 0x190819080819192b, 0x1908190808192b19, 0x19081908082b0808, 0x19081908082b082b, + 0x19081908082b1919, 0x19081908082b2b08, 0x1908190819080819, 0x1908190819081908, + 0x190819081908192b, 0x1908190819082b19, 0x1908190819190808, 0x190819081919082b, + 0x1908190819191919, 0x1908190819192b08, 0x19081908192b0819, 0x19081908192b1908, + 0x190819082b080808, 0x190819082b08082b, 0x190819082b081919, 0x190819082b082b08, + 0x190819082b190819, 0x190819082b191908, 0x190819082b2b0808, 0x1908191908080819, + 0x1908191908081908, 0x190819190808192b, 0x1908191908082b19, 0x1908191908190808, + 0x190819190819082b, 0x1908191908191919, 0x1908191908192b08, 0x19081919082b0819, + 0x19081919082b1908, 0x1908191919080808, 0x190819191908082b, 0x1908191919081919, + 0x1908191919082b08, 0x1908191919190819, 0x1908191919191908, 0x19081919192b0808, + 0x19081919192b2b2b, 0x190819192b080819, 0x190819192b081908, 0x190819192b190808, + 0x1908192b08080808, 0x1908192b0808082b, 0x1908192b08081919, 0x1908192b08082b08, + 0x1908192b08190819, 0x1908192b08191908, 0x1908192b082b0808, 0x1908192b19080819, + 0x1908192b19081908, 0x1908192b19190808, 0x1908192b2b080808, 0x1908192b2b2b1919, + 0x19082b0808080819, 0x19082b0808081908, 0x19082b0808082b19, 0x19082b0808190808, + 0x19082b080819082b, 0x19082b0808191919, 0x19082b0808192b08, 0x19082b08082b0819, + 0x19082b08082b1908, 0x19082b0819080808, 0x19082b081908082b, 0x19082b0819081919, + 0x19082b0819082b08, 0x19082b0819190819, 0x19082b0819191908, 0x19082b08192b0808, + 0x19082b082b081908, 0x19082b082b190808, 0x19082b1908080808, 0x19082b190808082b, + 0x19082b1908081919, 0x19082b1908082b08, 0x19082b1908190819, 0x19082b1908191908, + 0x19082b19082b0808, 0x19082b1919080819, 0x19082b1919081908, 0x19082b1919190808, + 0x19082b192b080808, 0x19082b192b19192b, 0x19082b2b08080819, 0x19082b2b08081908, + 0x19082b2b08190808, 0x19082b2b19080808, 0x1919080808080808, 0x191908080808082b, + 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819, 0x1919080808191908, + 0x191908080819192b, 0x1919080808192b19, 0x19190808082b0808, 0x19190808082b082b, + 0x19190808082b1919, 0x19190808082b2b08, 0x1919080819080819, 0x1919080819081908, + 0x191908081908192b, 0x1919080819082b19, 0x1919080819190808, 0x191908081919082b, + 0x1919080819191919, 0x1919080819192b08, 0x19190808192b0819, 0x19190808192b1908, + 0x191908082b080808, 0x191908082b08082b, 0x191908082b081919, 0x191908082b082b08, + 0x191908082b190819, 0x191908082b191908, 0x1919081908080819, 0x1919081908081908, + 0x191908190808192b, 0x1919081908082b19, 0x1919081908190808, 0x191908190819082b, + 0x1919081908191919, 0x1919081908192b08, 0x19190819082b0819, 0x19190819082b1908, + 0x1919081919080808, 0x191908191908082b, 0x1919081919081919, 0x1919081919082b08, + 0x1919081919190819, 0x1919081919191908, 0x19190819192b0808, 0x191908192b080819, + 0x191908192b081908, 0x191908192b190808, 0x1919082b08080808, 0x1919082b08081919, + 0x1919082b08082b08, 0x1919082b08190819, 0x1919082b08191908, 0x1919082b082b0808, + 0x1919082b19080819, 0x1919082b19081908, 0x1919082b19190808, 0x1919082b192b2b19, + 0x1919082b2b080808, 0x1919190808080819, 0x1919190808081908, 0x191919080808192b, + 0x1919190808082b19, 0x1919190808190808, 0x191919080819082b, 0x1919190808191919, + 0x1919190808192b08, 0x19191908082b0819, 0x19191908082b1908, 0x1919190819080808, + 0x191919081908082b, 0x1919190819081919, 0x1919190819082b08, 0x1919190819190819, + 0x1919190819191908, 0x19191908192b0808, 0x191919082b080819, 0x191919082b081908, + 0x191919082b190808, 0x1919191908080808, 0x191919190808082b, 0x1919191908081919, + 0x1919191908082b08, 0x1919191908190819, 0x1919191908191908, 0x19191919082b0808, + 0x1919191919080819, 0x1919191919081908, 0x1919191919190808, 0x191919192b080808, + 0x1919192b08080819, 0x1919192b08081908, 0x1919192b08190808, 0x1919192b082b192b, + 0x1919192b19080808, 0x19192b0808080808, 0x19192b080808082b, 0x19192b0808081919, + 0x19192b0808082b08, 0x19192b0808190819, 0x19192b0808191908, 0x19192b08082b0808, + 0x19192b0819080819, 0x19192b0819081908, 0x19192b0819190808, 0x19192b0819192b2b, + 0x19192b082b080808, 0x19192b1908080819, 0x19192b1908081908, 0x19192b1908190808, + 0x19192b1919080808, 0x19192b2b08080808, 0x19192b2b08192b19, 0x19192b2b2b081919, + 0x19192b2b2b2b2b08, 0x192b080808080819, 0x192b080808081908, 0x192b08080808192b, + 0x192b080808190808, 0x192b08080819082b, 0x192b080808191919, 0x192b080808192b08, + 0x192b0808082b0819, 0x192b0808082b1908, 0x192b080819080808, 0x192b080819081919, + 0x192b080819082b08, 0x192b080819190819, 0x192b080819191908, 0x192b0808192b0808, + 0x192b08082b081908, 0x192b08082b190808, 0x192b081908080808, 0x192b08190808082b, + 0x192b081908081919, 0x192b081908082b08, 0x192b081908190819, 0x192b081908191908, + 0x192b0819082b0808, 0x192b081919080819, 0x192b081919081908, 0x192b081919190808, + 0x192b08192b080808, 0x192b08192b192b19, 0x192b082b08081908, 0x192b082b08190808, + 0x192b082b19080808, 0x192b082b1919192b, 0x192b082b2b2b0819, 0x192b190808080808, + 0x192b190808081919, 0x192b190808082b08, 0x192b190808190819, 0x192b190808191908, + 0x192b1908082b0808, 0x192b190819080819, 0x192b190819081908, 0x192b190819190808, + 0x192b19082b080808, 0x192b191908080819, 0x192b191908081908, 0x192b191908190808, + 0x192b191919080808, 0x192b191919082b2b, 0x192b1919192b2b08, 0x192b19192b19082b, + 0x192b192b08080808, 0x192b192b2b191908, 0x192b2b0808080819, 0x192b2b0808081908, + 0x192b2b0808190808, 0x192b2b08192b1919, 0x192b2b082b192b08, 0x192b2b1908080808, + 0x192b2b19082b2b2b, 0x192b2b2b1908082b, 0x192b2b2b2b2b0819, 0x2b08080808080808, + 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, 0x2b08080808190819, + 0x2b08080808191908, 0x2b08080808192b19, 0x2b080808082b0808, 0x2b080808082b1919, + 0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808081919082b, + 0x2b08080819191919, 0x2b08080819192b08, 0x2b080808192b0819, 0x2b0808082b080808, + 0x2b0808082b081919, 0x2b0808082b190819, 0x2b0808082b191908, 0x2b08081908080819, + 0x2b08081908081908, 0x2b08081908082b19, 0x2b08081908190808, 0x2b0808190819082b, + 0x2b08081908191919, 0x2b08081908192b08, 0x2b080819082b0819, 0x2b080819082b1908, + 0x2b08081919080808, 0x2b0808191908082b, 0x2b08081919081919, 0x2b08081919082b08, + 0x2b08081919190819, 0x2b08081919191908, 0x2b0808192b080819, 0x2b0808192b081908, + 0x2b0808192b190808, 0x2b0808192b2b2b19, 0x2b08082b08080808, 0x2b08082b08081919, + 0x2b08082b08082b2b, 0x2b08082b08190819, 0x2b08082b08191908, 0x2b08082b19080819, + 0x2b08082b19081908, 0x2b08082b19190808, 0x2b08190808080819, 0x2b08190808081908, + 0x2b0819080808192b, 0x2b08190808082b19, 0x2b08190808190808, 0x2b0819080819082b, + 0x2b08190808191919, 0x2b08190808192b08, 0x2b081908082b0819, 0x2b08190819080808, + 0x2b0819081908082b, 0x2b08190819081919, 0x2b08190819082b08, 0x2b08190819190819, + 0x2b08190819191908, 0x2b081908192b0808, 0x2b0819082b080819, 0x2b0819082b081908, + 0x2b0819082b190808, 0x2b08191908080808, 0x2b0819190808082b, 0x2b08191908081919, + 0x2b08191908082b08, 0x2b08191908190819, 0x2b08191908191908, 0x2b081919082b0808, + 0x2b08191919080819, 0x2b08191919081908, 0x2b08191919190808, 0x2b0819192b080808, + 0x2b0819192b082b2b, 0x2b08192b08080819, 0x2b08192b08081908, 0x2b08192b08190808, + 0x2b08192b082b2b19, 0x2b08192b19080808, 0x2b082b0808080808, 0x2b082b0808081919, + 0x2b082b0808190819, 0x2b082b0808191908, 0x2b082b0819080819, 0x2b082b0819081908, + 0x2b082b0819190808, 0x2b082b082b2b082b, 0x2b082b1908080819, 0x2b082b1908081908, + 0x2b082b1919080808, 0x2b082b19192b1919, 0x2b082b2b082b082b, 0x2b082b2b19192b08, + 0x2b082b2b19192b2b, 0x2b082b2b2b08082b, 0x2b082b2b2b2b082b, 0x2b19080808080819, + 0x2b19080808081908, 0x2b19080808082b19, 0x2b19080808190808, 0x2b1908080819082b, + 0x2b19080808191919, 0x2b19080808192b08, 0x2b190808082b1908, 0x2b19080819080808, + 0x2b1908081908082b, 0x2b19080819081919, 0x2b19080819082b08, 0x2b19080819190819, + 0x2b19080819191908, 0x2b190808192b0808, 0x2b1908082b080819, 0x2b1908082b081908, + 0x2b1908082b190808, 0x2b19081908080808, 0x2b19081908081919, 0x2b19081908190819, + 0x2b19081908191908, 0x2b19081919080819, 0x2b19081919081908, 0x2b19081919190808, + 0x2b19081919192b2b, 0x2b19082b08080819, 0x2b19082b08081908, 0x2b19082b08190808, + 0x2b19082b19080808, 0x2b19082b2b2b192b, 0x2b19190808080808, 0x2b1919080808082b, + 0x2b19190808081919, 0x2b19190808082b08, 0x2b19190808190819, 0x2b19190808191908, + 0x2b191908082b0808, 0x2b19190819080819, 0x2b19190819081908, 0x2b19190819190808, + 0x2b1919082b080808, 0x2b1919082b19192b, 0x2b19191908080819, 0x2b19191908081908, + 0x2b19191908190808, 0x2b19191919080808, 0x2b1919192b192b08, 0x2b1919192b2b0819, + 0x2b19192b08080808, 0x2b19192b1908192b, 0x2b19192b192b1908, 0x2b192b0808080819, + 0x2b192b0808081908, 0x2b192b0808190808, 0x2b192b08082b192b, 0x2b192b0819080808, + 0x2b192b082b2b2b19, 0x2b192b1908080808, 0x2b192b1919082b19, 0x2b192b191919082b, + 0x2b192b2b2b190808, 0x2b2b080808080808, 0x2b2b080808081919, 0x2b2b080808082b2b, + 0x2b2b080808191908, 0x2b2b0808082b082b, 0x2b2b0808082b2b2b, 0x2b2b080819080819, + 0x2b2b080819081908, 0x2b2b080819190808, 0x2b2b08082b2b082b, 0x2b2b08082b2b2b2b, + 0x2b2b081919080808, 0x2b2b0819192b1919, 0x2b2b082b0808082b, 0x2b2b082b08082b2b, + 0x2b2b082b082b082b, 0x2b2b082b082b2b08, 0x2b2b082b082b2b2b, 0x2b2b082b2b08082b, + 0x2b2b082b2b082b08, 0x2b2b082b2b082b2b, 0x2b2b082b2b2b2b08, 0x2b2b190808080819, + 0x2b2b190808081908, 0x2b2b190808190808, 0x2b2b190819080808, 0x2b2b19082b082b19, + 0x2b2b19082b2b1908, 0x2b2b191908080808, 0x2b2b191908192b19, 0x2b2b192b19190819, + 0x2b2b2b0808082b2b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b082b, 0x2b2b2b1919191908, + 0x2b2b2b192b08192b, 0x2b2b2b2b08082b08, 0x2b2b2b2b08082b2b, 0x2b2b2b2b082b0808, + 0x2b2b2b2b082b082b, 0x2b2b2b2b082b2b08, 0x2b2b2b2b2b082b08, 0x2b2b2b2b2b2b2b2b, +GGML_TABLE_END() diff --git a/sycl/src/prefill/prefill.cpp b/sycl/src/prefill/prefill.cpp index 9b7c125b..ca3d0289 100644 --- a/sycl/src/prefill/prefill.cpp +++ b/sycl/src/prefill/prefill.cpp @@ -5,6 +5,7 @@ #include "strata/sycl_queue.hpp" #include "strata/copy_queue.hpp" #include "strata/prefill/xmx_moe.hpp" +#include "strata/prefill/esimd_moe.hpp" #include "strata/prefill/prefill.hpp" #include "strata/core/gguf_expert_source.hpp" #include "../../../src/prefill/mmq_resident_sort.hpp" @@ -41,6 +42,13 @@ #include "strata/prefill/kernels.hpp" #include +#include +#include +#include +#include +#include +#include +#include #include #include #include @@ -230,7 +238,31 @@ inline int ring_slots(size_t T) { } // A770 port: STRATA_PF_XMX=2 holds up to a group of staged experts until its launch, so routed-only staging needs // that many more slots for the lookahead to keep copying (the slots are only reused once the group's event is in) -inline int stage_slots() { return strata::prefill::xmx::mode() == 2 ? STAGE + strata::prefill::xmx::kMaxGroup : STAGE; } +// 151-b70: the fused int8 DPAS expert products (prefill/esimd_moe.dp.cpp, Battlemage). Unset STRATA_PREFILL_MMQ (alias STRATA_PF_I8) is +// auto on a Battlemage GPU (bmg-g21 / bmg-g31 by architecture id) whose kernels are in the binary, the FP16 chain on every other GPU +// (Alchemist included); =0 forces the FP16 chain, =1 the int8 chain everywhere it applies (IQ3_S / IQ3_XXS / IQ2_S gate/up with IQ4_NL / +// Q2_0 down, the 640 x 2560 expert), =auto the per-group choice from the crossover measured on this GPU. The activations are quantized, +// so the bits differ from the FP16 path (docs/INTEL_INT8_EXPERTS.md: KL 0.0002 nats, top-1 99.7%). +static_assert(strata::kernels::kXmxGroupMax <= strata::prefill::i8::kMaxGroup, "the int8 path holds the grouped XMX path's experts: its Layout must be at least as big"); +inline const char* i8_env() { + const char* e = std::getenv("STRATA_PREFILL_MMQ"); + if (e == nullptr || e[0] == 0) e = std::getenv("STRATA_PF_I8"); + return (e != nullptr && e[0] != 0) ? e : nullptr; +} +std::atomic g_i8_failed{false}; // an int8 launch threw: the FP16 chain for the rest of the process +// The chain this queue's prompt experts take: 0 FP16, 1 int8, 2 auto. +inline int i8_mode(void* cs) { + if (g_i8_failed.load(std::memory_order_relaxed)) return 0; + const char* e = i8_env(); + if (e != nullptr) return strata::prefill::i8::choose_mode(e, false, false); + return strata::prefill::i8::choose_mode(nullptr, strata::prefill::i8::battlemage(cs), strata::prefill::i8::available(cs)); +} +// ring sizing happens before any queue is at hand: room for the int8 groups whenever the choice could be on +inline int stage_slots() { + const char* e = i8_env(); + const bool i8 = e != nullptr ? strata::prefill::i8::choose_mode(e, false, false) != 0 : strata::prefill::i8::any_battlemage(); + return (strata::prefill::xmx::mode() == 2 || i8) ? STAGE + strata::prefill::xmx::kMaxGroup : STAGE; +} constexpr int DQ = 2; // dequantized-expert ring (FP16 gate/up + down) // A770 port: STRATA_PF_XMX=1 dequantizes a whole group of experts, then one grouped XMX launch per product inline int dq_slots() { return strata::prefill::xmx::mode() == 1 ? strata::prefill::xmx::kMaxGroup : DQ; } @@ -781,6 +813,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 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 +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() + "|" + + q.get_device().template get_info(); + 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 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(f.bytes + 256, q); + X = sycl::malloc_device(rmax * N, q); + Hh = sycl::malloc_device(rmax * NF, q); + GU = sycl::malloc_device(rmax * 2 * NF, q); + Dm = sycl::malloc_device(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 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 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(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(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 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; +} +} // namespace Prefill::Prefill() : impl_(new Impl) {} Prefill::~Prefill() { release(); } @@ -944,6 +1161,11 @@ bool Prefill::init(const core::WeightTable &wt, const core::ModelGeometry &g, err = "prefill: geometry differs from the artifact's"; return false; } m.device = dpct::get_current_device_id(); + if (static bool said_i8 = false; !said_i8 && i8_mode(m.cs) != 0) { + said_i8 = true; + std::fprintf(stderr, "strata: int8 prompt experts are on (%s); STRATA_PREFILL_MMQ=0 turns them off\n", + i8_env() == nullptr ? "Battlemage default, auto" : "STRATA_PREFILL_MMQ set"); + } if (stage_le_ < 0) stage_le_ = g.n_layers; if (stage_lb_ < 0 || stage_lb_ >= stage_le_ || stage_le_ > g.n_layers || (stage_le_ < g.n_layers) != (next_ != nullptr)) { err = "prefill: the stage's layer range is wrong"; @@ -3945,7 +4167,23 @@ bool Prefill::run_impl(const int64_t *tokens, int64_t n, int64_t pos0, const int gt = lay.fmt[(size_t) l].gu_type, dt = lay.fmt[(size_t) l].d_type; return (gt == 18 || gt == 21 || gt == 22 || gt == 23) && (dt == 20 || dt == 42); }; - const bool xmx2 = strata::prefill::xmx::mode() == 2 && !use_mmq && xmx2_fmt(); + const bool xmx2_only = strata::prefill::xmx::mode() == 2 && !use_mmq && xmx2_fmt(); + // 151-b70: the fused int8 DPAS products (IQ3_S gate/up, IQ4_NL down, the 640 x 2560 expert), the same + // held group of staged experts as above + const int i8m = i8_mode(m.cs); + const bool i8on = !xmx2_only && i8m != 0 && !use_mmq && lay.native && + (lay.fmt[(size_t) l].gu_type == 21 || lay.fmt[(size_t) l].gu_type == 18 || lay.fmt[(size_t) l].gu_type == 22) && + (lay.fmt[(size_t) l].d_type == 20 || lay.fmt[(size_t) l].d_type == 42) && + lay.fmt[(size_t) l].n_ff == 640 && lay.fmt[(size_t) l].n_embd == 2560 && + strata::prefill::i8::available(m.cs); + const bool xmx2 = xmx2_only || i8on; + if (i8_env() != nullptr && i8m != 0 && lay.native) { + static std::set> said_fmt; + const auto& ff = lay.fmt[(size_t) l]; + if (said_fmt.insert({ff.gu_type, ff.d_type, (int) ff.n_ff, (int) ff.n_embd, (int) i8on}).second) + std::fprintf(stderr, "strata: layer %lld experts gate/up type %d, down type %d, n_ff %d, n_embd %d -> int8 path %s\n", + (long long) l, ff.gu_type, ff.d_type, (int) ff.n_ff, (int) ff.n_embd, i8on ? "yes" : "no"); + } if (strata::prefill::xmx::mode() == 2 && !xmx2) { static bool said = false; if (!said) { @@ -3965,13 +4203,86 @@ bool Prefill::run_impl(const int64_t *tokens, int64_t n, int64_t pos0, int64_t xg_r0 = 0; auto xflush = [&]() { if (xg_n == 0) return; + const auto& f = lay.fmt[(size_t) l]; + int64_t nr = 0; + for (int i = 0; i < xg_n; ++i) nr += xg_c[i]; + if (i8on) { + // 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 done8 = false; + try { + bool use_i8 = true; + if (i8m == 2) { + static std::map, 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); + } + } + 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", + i8m == 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); + } + } + } + } catch (const std::exception& ex) { // the kernels are not in this binary for this device, or a launch failed: the FP16 chain, for good + done8 = false; + if (!g_i8_failed.exchange(true)) + std::fprintf(stderr, "strata: the int8 expert kernels failed to launch (%s): the FP16 expert chain is used from here\n", ex.what()); + } + 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]; + dpct::sync_barrier(m.used[rel], m.cs); + for (int i = 0; i < xg_ns; ++i) m.used_of[xg_slots[i]] = rel; + } + xg_n = 0; + xg_ns = 0; + return; + } if (static bool said = false; !said) { said = true; std::fprintf(stderr, "strata: prompt experts on the fused grouped XMX (STRATA_PF_XMX=2)\n"); } - const auto& f = lay.fmt[(size_t) l]; - int64_t nr = 0; - for (int i = 0; i < xg_n; ++i) nr += xg_c[i]; // measured (xmx_group_parity, 16 experts): the fused launch wins below ~200 rows per // expert, dequantize + oneMKL above (gate/up 0.67-0.76x at 320); STRATA_PF_XMX_ROWS moves it static const int xg_max = [] { diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cpp index 5794a27c..d11f2f2d 100644 --- a/sycl/src/program/generate.cpp +++ b/sycl/src/program/generate.cpp @@ -10621,6 +10621,23 @@ int main(int argc, char **argv) try { const DecSnap ds0 = dec_snap(); double dt_run = 0, dt_commit = 0, dt_draft = 0; int64_t dec_windows = 0, dec_T = 0; + // STRATA_FOLLOW= (test path, off by default): this request decodes the token ids in (whitespace + // separated, read and deleted at the request's start) instead of the argmax, through the real verify windows + // with the MTP drafts; STRATA_FOLLOW_LOGPOS= appends, for every valid window row, the teacher-forced + // log-probability of the forced token and the top STRATA_LOGPOS_TOPK log-probabilities + std::vector fol; + if (const char* fp = std::getenv("STRATA_FOLLOW")) { + if (std::FILE* ff = std::fopen(fp, "r")) { + long long v; + while (std::fscanf(ff, "%lld", &v) == 1) fol.push_back((int32_t) v); + std::fclose(ff); + std::remove(fp); + } + } + static std::FILE* fol_lp = [] { + const char* p = std::getenv("STRATA_FOLLOW_LOGPOS"); + return p != nullptr ? std::fopen(p, "ab") : nullptr; + }(); const int64_t decode_hits0 = drive.d.cache_hits; // CS-T: the RAM and file tiers of this request (the mmap source; 0 with the arena) const int64_t ram0 = src.ram_reads(), files0 = src.file_reads(); @@ -11398,8 +11415,20 @@ int main(int argc, char **argv) try { std::printf("ERR %s\n", drive.d.failed && drive.d.fail ? drive.d.fail : err.c_str()); return 1; } + int32_t fol_tgt[16]; + if (!fol.empty()) { // STRATA_FOLLOW: the forced continuation stands in for the argmax + for (int i = 0; i < T && i < 16; ++i) { + const size_t k = (size_t) produced_n + (size_t) i; + fol_tgt[i] = k < fol.size() ? fol[k] : -1; + if (fol_tgt[i] >= 0) outv[(size_t) i] = fol_tgt[i]; + } + } int a = 0; while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a; + if (!fol.empty() && fol_lp != nullptr && !ver.window_logprobs(fol_tgt, a + 1, produced_n, -1, fol_lp, err)) { + std::printf("ERR %s\n", err.c_str()); + return 1; + } if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; } if (chain_n > 0) { ++chain_windows; chain_drafts += chain_n; chain_ok += std::max(0, a - (T_mtp - 1)); } if (strata::core::MtpDrafter::top2_env() && !from_sfx && !first_window && a < T_mtp - 1 && a < 8) { diff --git a/tests/sycl/test_setup_intel_prefill.py b/tests/sycl/test_setup_intel_prefill.py new file mode 100644 index 00000000..0c7a742a --- /dev/null +++ b/tests/sycl/test_setup_intel_prefill.py @@ -0,0 +1,52 @@ +"""sycl/setup_intel.py: the prompt chunk size setup recommends for an Intel card (--prefill). + +A Battlemage card (xe driver, not an A-series) with 24 GB or more and a context over 32K (the prompt borrows cache slots) gets +8192; everything else keeps 4096; a chunk size the user put in the config is kept.""" +import importlib.util +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent.parent +sys.path.insert(0, str(ROOT)) +_spec = importlib.util.spec_from_file_location("setup_intel", ROOT / "sycl" / "setup_intel.py") +si = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(si) + +B70 = dict(vram_gb=32.0, driver="xe", devid="e223") +A770 = dict(vram_gb=16.0, driver="xe", devid="56a0") +A750 = dict(vram_gb=8.0, driver="i915", devid="56a1") + + +def prefill_of(ctx, card, extra=()): + cfg = {"args": ["--max-context", str(ctx), "--kv", "int8", "--prefill", "auto", *extra]} + out = si.to_sycl(cfg, ROOT / "build-sycl-aot" / "strata", 64.0, {}, **card) + return si.flag(out["args"], "--prefill") + + +def test_helper_values(): + assert si.recommended_prefill(32.0, 131072, "xe", "e223")[0] == 8192 + assert si.recommended_prefill(32.0, 131072, "xe", "e223")[1] # a plain line says why + assert si.recommended_prefill(24.0, 65536, "xe", "e221")[0] == 8192 + assert si.recommended_prefill(32.0, 32768, "xe", "e223") == (4096, "") # own prompt buffers: a bigger chunk costs cache slots + assert si.recommended_prefill(16.0, 131072, "xe", "e212")[0] == 4096 # under 24 GB + assert si.recommended_prefill(16.0, 131072, "xe", "56a0")[0] == 4096 # Alchemist + assert si.recommended_prefill(8.0, 131072, "i915", "56a1")[0] == 4096 + + +def test_config_battlemage_long_context(): + assert prefill_of(131072, B70) == "8192" + + +def test_config_battlemage_32k_keeps_4096(): + assert prefill_of(32768, B70) == "4096" + + +def test_config_other_cards_unchanged(): + assert prefill_of(131072, A770) == "4096" + assert prefill_of(131072, A750) == "4096" + + +def test_user_pick_is_kept(): + cfg = {"args": ["--max-context", "131072", "--kv", "int8", "--prefill", "16384"]} + out = si.to_sycl(cfg, ROOT / "build-sycl-aot" / "strata", 64.0, {}, **B70) + assert si.flag(out["args"], "--prefill") == "16384"