Skip to content

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

C++

cpu: AVX1 128-bit expert kernels (iq_avx1) - the i-quant rows on CPUs with no AVX2

bossmandd7b0b5f0769
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 3e1f9f470..d4f34778b 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1245,7 +1245,7 @@ if(STRATA_NATIVE_EXPERTS)
# one-pass static linking has no cycle to resolve)
target_sources(strata_kernels_cpu PRIVATE src/kernels/cpu/native_expert.cpp src/kernels/cpu/iq_avx512.cpp
src/kernels/cpu/iq_avx2.cpp src/kernels/cpu/kq_avx2.cpp
- src/kernels/cpu/kq_avx1.cpp src/kernels/cpu/q2_avx1.cpp)
+ src/kernels/cpu/kq_avx1.cpp src/kernels/cpu/q2_avx1.cpp src/kernels/cpu/iq_avx1.cpp)
target_include_directories(strata_kernels_cpu PRIVATE third_party/ggml)
if(MSVC)
set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512")
@@ -1256,6 +1256,8 @@ if(STRATA_NATIVE_EXPERTS)
# the older CPUs' Q2_0 rows and activation quantizer (q2_avx1.cpp, issue #1699): 128-bit integer lanes,
# no FMA/F16C, its own #error guard; called only behind cpu_avx1_ok() && !cpu_avx2_ok()
set_source_files_properties(src/kernels/cpu/q2_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX")
+ # the older CPUs' i-quant expert rows (iq_avx1.hpp): 128-bit SSSE3/SSE2 integer, SSE2 float, no FMA/F16C
+ set_source_files_properties(src/kernels/cpu/iq_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX")
else()
set_source_files_properties(src/kernels/cpu/iq_avx512.cpp PROPERTIES COMPILE_OPTIONS
"-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mf16c;-mfma")
@@ -1267,6 +1269,10 @@ if(STRATA_NATIVE_EXPERTS)
# runs on a Sandy Bridge Xeon
set_source_files_properties(src/kernels/cpu/q2_avx1.cpp PROPERTIES COMPILE_OPTIONS
"-msse4.2;-mavx;-mno-avx2;-mno-fma;-mno-f16c")
+ # the older CPUs' i-quant expert rows (iq_avx1.hpp): SSE4.2 + AVX with AVX2/FMA/F16C explicitly off, so a
+ # -march=native build host cannot leak AVX2 code into the file that runs on a Sandy Bridge Xeon
+ set_source_files_properties(src/kernels/cpu/iq_avx1.cpp PROPERTIES COMPILE_OPTIONS
+ "-msse4.2;-mavx;-mno-avx2;-mno-fma;-mno-f16c")
endif()
set_property(SOURCE src/kernels/cpu/iq_avx2.cpp APPEND PROPERTY COMPILE_DEFINITIONS ${_strata_avxvnni})
if(STRATA_ISA_FLOOR STREQUAL "avx")
@@ -1301,6 +1307,14 @@ if(STRATA_NATIVE_EXPERTS)
add_test(NAME iq_avx2_parity COMMAND iq_avx2_parity)
add_test(NAME iq_avx2_parity_iq3s_mt1 COMMAND ${CMAKE_COMMAND} -E env STRATA_IQ3S_MT1=1 $<TARGET_FILE:iq_avx2_parity>)
endif()
+ # the older CPUs' AVX1 expert rows (iq_avx1.cpp) against ggml-cpu's dots and against their own one-token
+ # rows at every width; --bench: ms per expert, the weights streamed from DRAM. Runs on any AVX CPU:
+ # on an AVX2 machine it checks the older-CPU path as an AVX-only machine would run it.
+ add_executable(iq_avx1_parity src/kernels/cpu/iq_avx1_parity.cpp)
+ target_link_libraries(iq_avx1_parity PRIVATE strata_kernels_cpu)
+ if(STRATA_BUILD_TESTS)
+ add_test(NAME iq_avx1_parity COMMAND iq_avx1_parity)
+ endif()
# the AVX-2 Q8_K activation quantizer against ggml's, byte for byte (--bench: its time)
add_executable(q8k_quant_parity src/kernels/cpu/q8k_quant_parity.cpp)
target_link_libraries(q8k_quant_parity PRIVATE strata_kernels_cpu)
diff --git a/include/strata/kernels/cpu/iq_avx1.hpp b/include/strata/kernels/cpu/iq_avx1.hpp
new file mode 100644
index 000000000..c160acc2b
--- /dev/null
+++ b/include/strata/kernels/cpu/iq_avx1.hpp
@@ -0,0 +1,37 @@
+// include/strata/kernels/cpu/iq_avx1.hpp - AVX1 (SSE4.2 + AVX, no AVX2/FMA) multi-token expert rows
+// for the older-CPU builds (STRATA_ISA_FLOOR=avx: Sandy/Ivy Bridge, Xeon E5 v1/v2, Bulldozer).
+//
+// The sibling of kq_avx1.cpp for the expert kernels: without these, every CPU expert on such a CPU runs on
+// ggml-cpu's scalar `_generic` dots (every x86 i-quant dot is #if defined(__AVX2__)). Everything these
+// kernels need exists in 128-bit on that ISA: pshufb, sign_epi8 and maddubs are SSSE3, madd_epi16 is SSE2;
+// the float accumulation is 128-bit SSE2 (no FMA). No gathered variants: the non-gather Fmt32 decode of
+// iq_avx2.cpp is the template and it is 128-bit-portable.
+//
+// Compiled for AVX (-mavx / /arch:AVX, see CMakeLists.txt) and called only behind cpu_avx1_ok(), so a CPU
+// without AVX never reaches it. The arithmetic is ggml's (the `_generic` references): a multi-token row is
+// bit for bit the same kernel's single-token row for that token (#152), and rows match ggml-cpu's dot to
+// rel <= 1e-5 (iq_avx1_parity checks both).
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+namespace strata::kernels::cpu {
+
+/// gate/up formats with an AVX1 kernel: IQ3_XXS (18), IQ3_S (21), IQ2_S (22), IQ4_XS (23).
+bool iq128_supported(int ggml_type) noexcept;
+/// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]), rows [r0, r1); gate rows at blob, up rows at blob + up_off.
+/// Activations are ggml's quantized form for the format (Q8_K for every format here), as in native_gu_rows.
+void iq128_gu_rows(int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act,
+ int nt, float* const* ff, int r0, int r1);
+
+/// down formats with an AVX1 kernel: IQ4_NL (20), Q2_0 (42, the fork's type). Activations: Q8_0 for both.
+bool iq128_down_supported(int ggml_type) noexcept;
+void iq128_down_rows(int ggml_type, const uint8_t* w, size_t row_bytes, int n, const void* const* hq, int nt,
+ float* const* out, int r0, int r1);
+
+/// ggml's quantize_row_q8_K (x86 runs the scalar reference), byte-identical, in SSE4.2/AVX1: the older CPUs'
+/// copy of q8k_quant_avx2 (no 256-bit integer ops, no FMA). q8k_quant_parity checks the bytes.
+void q8k_quant_avx1(const float* x, void* y, int64_t n);
+
+} // namespace strata::kernels::cpu
diff --git a/src/kernels/cpu/iq_avx1.cpp b/src/kernels/cpu/iq_avx1.cpp
new file mode 100644
index 000000000..66bae5d1b
--- /dev/null
+++ b/src/kernels/cpu/iq_avx1.cpp
@@ -0,0 +1,507 @@
+// src/kernels/cpu/iq_avx1.cpp - the i-quant expert rows for CPUs without AVX2 (STRATA_ISA_FLOOR=avx:
+// Sandy/Ivy Bridge, Xeon E5 v1/v2, Bulldozer). See iq_avx1.hpp.
+//
+// iq_avx2.cpp's multi-token scheme in 128-bit lanes: each 32-value chunk is decoded once per verify window
+// (grid lookups, one sign vector, one scale vector) and every token applies it with a load, a sign, a
+// maddubs, a madd and an add - all SSSE3/SSE2, all available since Core 2. The 256-bit integer ops of the
+// AVX2 kernel (pshufb/maddubs/sign_epi8 in __m256i, vpgather, vpdpbusd) have no AVX1 form and no FMA exists
+// there, so the float accumulation is a plain SSE2 mul+add. Without these kernels such a CPU runs every
+// expert on ggml-cpu's scalar `_generic` dots (every x86 i-quant dot is #if defined(__AVX2__)).
+//
+// The arithmetic is ggml's (ggml-cpu/quants.c, the `_generic` references) - only the order of the float
+// additions differs; the integer sums are exact. iq_avx1_parity checks: rows vs ggml-cpu's dot rel <= 1e-5,
+// and a multi-token row bit for bit the same kernel's single-token row for that token (#152).
+//
+// Formats: gate/up IQ3_XXS (18), IQ3_S (21), IQ2_S (22), IQ4_XS (23); down IQ4_NL (20) and Q2_0 (42, the
+// fork's type). IQ2_XXS/IQ2_XS have no layer in the packs that need this and stay on ggml-cpu's dot.
+//
+// This file is compiled for SSE4.2 + AVX with AVX2/FMA/F16C explicitly off (CMakeLists.txt), and the engine
+// calls it only behind cpu_avx1_ok(). No static constructors at namespace scope (#391): the tables below
+// are constexpr, like iq_avx2.cpp's.
+#include "strata/kernels/cpu/iq_avx1.hpp"
+
+#include "ggml.h"
+
+#define GGML_COMMON_DECL_CPP
+#define GGML_COMMON_IMPL_CPP
+#include "ggml-common.h"
+
+#include <immintrin.h>
+
+#include <cmath>
+#include <cstdlib>
+#include <cstring>
+
+#if !defined(__AVX__)
+#error "iq_avx1.cpp must be compiled with AVX enabled (see the per-source flags in CMakeLists.txt)"
+#endif
+#if defined(__FMA__) || defined(__F16C__)
+#error "iq_avx1.cpp must be compiled without FMA/F16C: it runs on CPUs (Sandy/Ivy Bridge) that lack them"
+#endif
+
+namespace strata::kernels::cpu {
+namespace {
+
+// fp16 -> fp32 without F16C (expert.cpp's h2f: the conversion written out, subnormals included).
+inline float h2f(uint16_t h) {
+ const uint32_t sign = (uint32_t) (h >> 15) & 1u;
+ uint32_t exp = (h >> 10) & 0x1Fu, man = h & 0x3FFu, f;
+ if (exp == 0) {
+ if (man == 0) {
+ f = sign << 31;
+ } else {
+ exp = 127 - 15 + 1;
+ while (!(man & 0x400u)) { man <<= 1; --exp; }
+ man &= 0x3FFu;
+ f = (sign << 31) | (exp << 23) | (man << 13);
+ }
+ } else if (exp == 31) {
+ f = (sign << 31) | 0x7F800000u | (man << 13);
+ } else {
+ f = (sign << 31) | ((exp - 15 + 127) << 23) | (man << 13);
+ }
+ float out;
+ std::memcpy(&out, &f, 4);
+ return out;
+}
+
+inline uint32_t u32(const uint8_t* p) { uint32_t v; std::memcpy(&v, p, 4); return v; }
+inline uint16_t u16(const uint8_t* p) { uint16_t v; std::memcpy(&v, p, 2); return v; }
+inline uint64_t u64(const uint8_t* p) { uint64_t v; std::memcpy(&v, p, 8); return v; }
+
+// The sign-vector pattern of iq_avx2.cpp's sgn_vec_at in 128-bit: 16 values from two sign bytes.
+// bits = the two bytes broadcast over the 16 lanes, sel = bit k of each byte per lane, -> 16 bytes of
+// -1 (bit set) / +1. ggml's bit_selector pattern, same bits.
+inline __m128i sgn16(uint32_t w, int byte_pair) { // byte_pair 0: bytes 0-1 (values 0-15), 1: bytes 2-3
+ const __m128i bits = _mm_shuffle_epi8(_mm_set1_epi32((int) w),
+ byte_pair ? _mm_setr_epi8(2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3)
+ : _mm_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1));
+ const __m128i sel = _mm_setr_epi8(1, 2, 4, 8, 16, 32, 64, (char) 0x80, 1, 2, 4, 8, 16, 32, 64, (char) 0x80);
+ return _mm_or_si128(_mm_cmpeq_epi8(_mm_and_si128(bits, sel), sel), _mm_set1_epi8(1));
+}
+
+// keven_signs_q2xs as a constexpr table (iq_avx2.cpp's EvenSigns; byte k = 0xFF when bit k of
+// ksigns_iq2xs[i] is set, 0x01 otherwise). constexpr, not a runtime constructor (#391).
+struct EvenSigns {
+ uint64_t v[128];
+ constexpr EvenSigns() : v{} {
+ for (int i = 0; i < 128; ++i) {
+ int par = 0;
+ for (int k = 0; k < 7; ++k) par ^= (i >> k) & 1;
+ const int s = i | (par << 7); // == ksigns_iq2xs[i]
+ uint64_t r = 0;
+ for (int k = 0; k < 8; ++k) r |= (uint64_t) (((s >> k) & 1) ? 0xFF : 0x01) << (8 * k);
+ v[i] = r;
+ }
+ }
+};
+static constexpr EvenSigns even_signs{};
+static_assert(even_signs.v[0] == 0x0101010101010101ull && even_signs.v[1] == 0xFF010101010101FFull,
+ "keven_signs_q2xs: byte k = 0xFF when bit k of ksigns_iq2xs[i] is set");
+
+// The high index bits of a 32-value half spread one per byte (iq_avx2.cpp's HiSpread): punpcklbw puts them
+// next to the low index bytes, so every grid index is a 16-bit load. IQ3_S: byte k = bit k (the 9th bit of
+// index k). IQ2_S: byte k = bits 2k,2k+1 (bits 8-9 of index k), k < 4.
+struct HiSpread {
+ uint64_t iq3s[256];
+ uint64_t iq2s[256];
+ constexpr HiSpread() : iq3s{}, iq2s{} {
+ for (int h = 0; h < 256; ++h) {
+ uint64_t r3 = 0, r2 = 0;
+ for (int k = 0; k < 8; ++k) r3 |= (uint64_t) ((h >> k) & 1) << (8 * k);
+ for (int k = 0; k < 4; ++k) r2 |= (uint64_t) ((h >> (2 * k)) & 3) << (8 * k);
+ iq3s[h] = r3;
+ iq2s[h] = r2;
+ }
+ }
+};
+static constexpr HiSpread hi_spread{};
+static_assert(hi_spread.iq3s[0x81] == 0x0100000000000001ull && hi_spread.iq2s[0xE4] == 0x0000000003020100ull,
+ "hi_spread: one high-bit group per index byte");
+
+// The low index bytes interleaved with the spread high bits: eight 16-bit grid indices in one register.
+// (iq_avx2.cpp's grid_indices stores them to memory; on Ivy Bridge that store -> narrow-load round trip
+// costs a forwarding stall per index, so the decoders below read the lanes with _mm_extract_epi16 instead.)
+inline __m128i grid_idx(const uint8_t* q, uint64_t hi) {
+ return _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i*) q), _mm_cvtsi64_si128((long long) hi));
+}
+
+inline float hsum4(__m128 v) {
+ __m128 s = _mm_add_ps(v, _mm_movehl_ps(v, v));
+ s = _mm_add_ss(s, _mm_movehdup_ps(s));
+ return _mm_cvtss_f32(s);
+}
+
+// E-2 prefetching, the same knob as the AVX-2/512 kernels: STRATA_IQ_PREFETCH is the distance in bytes.
+int prefetch_distance() {
+ static const int d = [] {
+ const char* v = std::getenv("STRATA_IQ_PREFETCH");
+ return v ? std::atoi(v) : 2048;
+ }();
+ return d;
+}
+
+inline void rows_ahead(const uint8_t* blk, int pf) {
+ if (pf <= 0) return;
+ _mm_prefetch((const char*) blk + pf, _MM_HINT_T0);
+ _mm_prefetch((const char*) blk + pf + 64, _MM_HINT_T0);
+}
+
+// ---- per format: one 32-value half (values 64*j + 32*half .. +31) -> grid magnitudes, sign vector and
+// scales as TWO 16-value halves (g0/g1, s0/s1, c0/c1).
+template <int TY> struct Fmt128;
+
+template <> struct Fmt128<18> { // IQ3_XXS: d, qs[64] grid bytes, 8 x u32 (4 x 7-bit sign index + 4-bit scale)
+ static constexpr int bytes = 98;
+ static constexpr float K = 0.25f;
+ static inline void decode(const uint8_t* b, int j, int half,
+ __m128i& g0, __m128i& g1, __m128i& s0, __m128i& s1, __m128i& c0, __m128i& c1) {
+ const uint8_t* q = b + 2 + 16 * j + 8 * half;
+ g0 = _mm_set_epi32((int) iq3xxs_grid[q[3]], (int) iq3xxs_grid[q[2]],
+ (int) iq3xxs_grid[q[1]], (int) iq3xxs_grid[q[0]]);
+ g1 = _mm_set_epi32((int) iq3xxs_grid[q[7]], (int) iq3xxs_grid[q[6]],
+ (int) iq3xxs_grid[q[5]], (int) iq3xxs_grid[q[4]]);
+ const uint32_t w = u32(b + 2 + 64 + 8 * j + 4 * half);
+ s0 = _mm_set_epi64x((long long) even_signs.v[(w >> 7) & 127], (long long) even_signs.v[w & 127]);
+ s1 = _mm_set_epi64x((long long) even_signs.v[(w >> 21) & 127], (long long) even_signs.v[(w >> 14) & 127]);
+ c0 = c1 = _mm_set1_epi16((short) (2 * (int) (w >> 28) + 1));
+ }
+};
+
+template <> struct Fmt128<21> { // IQ3_S: d, qs[64], qh[8], signs[32], scales[4]
+ static constexpr int bytes = 110;
+ static constexpr float K = 1.0f;
+ static inline void decode(const uint8_t* b, int j, int half,
+ __m128i& g0, __m128i& g1, __m128i& s0, __m128i& s1, __m128i& c0, __m128i& c1) {
+ const uint8_t* q = b + 2 + 16 * j + 8 * half;
+ const __m128i idx = grid_idx(q, hi_spread.iq3s[b[66 + 2 * j + half]]);
+#define G3(k) (int) iq3s_grid[_mm_extract_epi16(idx, k)]
+ g0 = _mm_set_epi32(G3(3), G3(2), G3(1), G3(0));
+ g1 = _mm_set_epi32(G3(7), G3(6), G3(5), G3(4));
+#undef G3
+ const uint32_t sg = u32(b + 74 + 8 * j + 4 * half);
+ s0 = sgn16(sg, 0);
+ s1 = sgn16(sg, 1);
+ const uint8_t s = b[106 + j];
+ c0 = c1 = _mm_set1_epi16((short) (2 * (int) (half ? s >> 4 : s & 15) + 1));
+ }
+};
+
+template <> struct Fmt128<22> { // IQ2_S: d, qs[64] (32 grid bytes, 32 sign bytes), qh[8], scales[8]
+ static constexpr int bytes = 82;
+ static constexpr float K = 0.125f;
+ static inline void decode(const uint8_t* b, int j, int half,
+ __m128i& g0, __m128i& g1, __m128i& s0, __m128i& s1, __m128i& c0, __m128i& c1) {
+ // only the first 4 index bytes are this half's (the load's rest stays inside the block)
+ const __m128i idx = grid_idx(b + 2 + 8 * j + 4 * half, hi_spread.iq2s[b[66 + 2 * j + half]]);
+ g0 = _mm_set_epi64x((long long) iq2s_grid[_mm_extract_epi16(idx, 1)],
+ (long long) iq2s_grid[_mm_extract_epi16(idx, 0)]);
+ g1 = _mm_set_epi64x((long long) iq2s_grid[_mm_extract_epi16(idx, 3)],
+ (long long) iq2s_grid[_mm_extract_epi16(idx, 2)]);
+ const uint32_t sg = u32(b + 2 + 32 + 8 * j + 4 * half);
+ s0 = sgn16(sg, 0);
+ s1 = sgn16(sg, 1);
+ const uint8_t sb = b[74 + 2 * j + half];
+ c0 = _mm_set1_epi16((short) (2 * (sb & 15) + 1));
+ c1 = _mm_set1_epi16((short) (2 * (sb >> 4) + 1));
+ }
+};
+
+template <> struct Fmt128<23> { // IQ4_XS: d, scales_h, scales_l[4], qs[128] - 136 B, 8 signed sub-scales
+ // ggml's ggml_vec_dot_iq4_xs_q8_K: the same 16-value codebook as IQ4_NL, one 6-bit scale per 32-value
+ // sub-block read as two nibbles of scales_l plus two bits of scales_h, used SIGNED as (ls - 32): the
+ // scale folds into the int16 operand of madd_epi16. The codebook sign rides on sign_epi8, |w| is the
+ // unsigned maddubs operand (a pair is at most 2 * 127 * 128, no saturation).
+ static constexpr int bytes = 136;
+ static constexpr float K = 1.0f;
+ static inline void decode(const uint8_t* b, int j, int half,
+ __m128i& g0, __m128i& g1, __m128i& s0, __m128i& s1, __m128i& c0, __m128i& c1) {
+ const int H = 2 * j + half;
+ const __m128i values = _mm_loadu_si128((const __m128i*) kvalues_iq4nl);
+ const __m128i bits = _mm_loadu_si128((const __m128i*) (b + 8 + 16 * H));
+ const __m128i m4 = _mm_set1_epi8(0x0f);
+ const __m128i v0 = _mm_shuffle_epi8(values, _mm_and_si128(bits, m4));
+ const __m128i v1 = _mm_shuffle_epi8(values, _mm_and_si128(_mm_srli_epi16(bits, 4), m4));
+ g0 = _mm_sign_epi8(v0, v0);
+ g1 = _mm_sign_epi8(v1, v1);
+ s0 = _mm_sign_epi8(_mm_set1_epi8(1), v0);
+ s1 = _mm_sign_epi8(_mm_set1_epi8(1), v1);
+ const int ls = ((b[4 + (H >> 1)] >> (4 * (H & 1))) & 0xf) | (((u16(b + 2) >> (2 * H)) & 3) << 4);
+ c0 = c1 = _mm_set1_epi16((short) (ls - 32));
+ }
+};
+
+// acc + madd(maddubs(g, sign(y, sgn)), sc): the AVX2 kernel's per-token application in 128-bit.
+inline __m128i madd_add(__m128i acc, __m128i g, __m128i sgn, __m128i yv, __m128i sc) {
+ return _mm_add_epi32(acc, _mm_madd_epi16(_mm_maddubs_epi16(g, _mm_sign_epi8(yv, sgn)), sc));
+}
+
+// ---- the row kernels (iq_avx2_rows.inl's row_dot in 128-bit lanes)
+template <int TY, int NT>
+inline void row_dot(const uint8_t* row, int nblocks, const block_q8_K* const* y, float* res) {
+ const int pf = prefetch_distance();
+ __m128 accf[NT];
+ for (int t = 0; t < NT; ++t) accf[t] = _mm_setzero_ps();
+ for (int i = 0; i < nblocks; ++i) {
+ const uint8_t* blk = row + (size_t) i * Fmt128<TY>::bytes;
+ rows_ahead(blk, pf);
+ __m128i acci[NT][2];
+ for (int t = 0; t < NT; ++t) acci[t][0] = acci[t][1] = _mm_setzero_si128();
+ for (int j = 0; j < 4; ++j) {
+ for (int half = 0; half < 2; ++half) {
+ __m128i g0, g1, s0, s1, c0, c1;
+ Fmt128<TY>::decode(blk, j, half, g0, g1, s0, s1, c0, c1);
+ const int off = 64 * j + 32 * half;
+ for (int t = 0; t < NT; ++t) {
+ const uint8_t* q8 = (const uint8_t*) (y[t][i].qs + off);
+ acci[t][0] = madd_add(acci[t][0], g0, s0, _mm_loadu_si128((const __m128i*) q8), c0);
+ acci[t][1] = madd_add(acci[t][1], g1, s1, _mm_loadu_si128((const __m128i*) (q8 + 16)), c1);
+ }
+ }
+ }
+ const float dx = h2f(u16(blk)) * Fmt128<TY>::K;
+ for (int t = 0; t < NT; ++t) {
+ const __m128 f = _mm_add_ps(_mm_cvtepi32_ps(acci[t][0]), _mm_cvtepi32_ps(acci[t][1]));
+ accf[t] = _mm_add_ps(accf[t], _mm_mul_ps(_mm_set1_ps(dx * y[t][i].d), f));
+ }
+ }
+ for (int t = 0; t < NT; ++t) res[t] = hsum4(accf[t]);
+}
+
+template <int TY, int NT>
+inline void gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act,
+ float* const* ff, int r0, int r1) {
+ const block_q8_K* y[NT];
+ for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t];
+ const int nb = n / QK_K;
+ float g[NT], u[NT];
+ for (int r = r0; r < r1; ++r) {
+ row_dot<TY, NT>(blob + (size_t) r * gu_row, nb, y, g);
+ row_dot<TY, NT>(blob + up_off + (size_t) r * gu_row, nb, y, u);
+ for (int t = 0; t < NT; ++t) ff[t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t];
+ }
+}
+
+template <int TY, int NT>
+inline void dot_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out,
+ int r0, int r1) {
+ const block_q8_K* y[NT];
+ for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t];
+ float res[NT];
+ for (int r = r0; r < r1; ++r) {
+ row_dot<TY, NT>(w + (size_t) r * row_bytes, n / QK_K, y, res);
+ for (int t = 0; t < NT; ++t) out[t][r] = res[t];
+ }
+}
+
+template <int TY>
+void gu_rows_nt(int nt, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act,
+ float* const* ff, int r0, int r1) {
+ switch (nt) {
+ case 1: gu_rows<TY, 1>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
+ case 2: gu_rows<TY, 2>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
+ case 3: gu_rows<TY, 3>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
+ case 4: gu_rows<TY, 4>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
+ case 5: gu_rows<TY, 5>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
+ case 6: gu_rows<TY, 6>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
+ case 7: gu_rows<TY, 7>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
+ default: gu_rows<TY, 8>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
+ }
+}
+
+// ---- IQ4_NL (20) down rows against Q8_0: ggml's dot is single-token even where it is vectorized (and
+// scalar here); decode the nibbles once, every token pays a sign, a maddubs, a madd and an fmadd-equivalent.
+template <int NT>
+void iq4nl_rows(const uint8_t* w, size_t row_bytes, int n, const block_q8_0* const* y, float* const* out,
+ int r0, int r1) {
+ const __m128i values = _mm_loadu_si128((const __m128i*) kvalues_iq4nl);
+ const __m128i m4b = _mm_set1_epi8(0x0f);
+ const __m128i ones = _mm_set1_epi16(1);
+ const int nb = n / QK4_NL;
+ const int pf = prefetch_distance();
+ for (int r = r0; r < r1; ++r) {
+ const uint8_t* row = w + (size_t) r * row_bytes;
+ __m128 accf[NT];
+ for (int t = 0; t < NT; ++t) accf[t] = _mm_setzero_ps();
+ for (int ib = 0; ib < nb; ++ib) {
+ const uint8_t* blk = row + (size_t) ib * sizeof(block_iq4_nl);
+ rows_ahead(blk, pf);
+ const __m128i bits = _mm_loadu_si128((const __m128i*) (blk + 2));
+ const __m128i v0 = _mm_shuffle_epi8(values, _mm_and_si128(bits, m4b));
+ const __m128i v1 = _mm_shuffle_epi8(values, _mm_and_si128(_mm_srli_epi16(bits, 4), m4b));
+ const __m128i aq0 = _mm_sign_epi8(v0, v0); // |w|: the unsigned maddubs operand
+ const __m128i aq1 = _mm_sign_epi8(v1, v1);
+ const float dx = h2f(u16(blk));
+ for (int t = 0; t < NT; ++t) {
+ const uint8_t* q8 = (const uint8_t*) y[t][ib].qs;
+ const __m128i p0 = _mm_madd_epi16(_mm_maddubs_epi16(aq0, _mm_sign_epi8(_mm_loadu_si128((const __m128i*) q8), v0)), ones);
+ const __m128i p1 = _mm_madd_epi16(_mm_maddubs_epi16(aq1, _mm_sign_epi8(_mm_loadu_si128((const __m128i*) (q8 + 16)), v1)), ones);
+ const __m128 f = _mm_add_ps(_mm_cvtepi32_ps(p0), _mm_cvtepi32_ps(p1));
+ accf[t] = _mm_add_ps(accf[t], _mm_mul_ps(_mm_set1_ps(dx * h2f(y[t][ib].d)), f));
+ }
+ }
+ for (int t = 0; t < NT; ++t) out[t][r] = hsum4(accf[t]);
+ }
+}
+
+// ---- Q2_0 (42) down rows against Q8_0: ggml-cpu has only the scalar generic dot for this type on x86.
+// Codes {0,1,2,3} map to {c-1}: unpack to unsigned code bytes, dot them with maddubs, and subtract the
+// activation's pair sums - all integer, so the per-block sum is EXACTLY the generic dot's sumi_block.
+template <int NT>
+void q2_0_rows(const uint8_t* w, size_t row_bytes, int n, const block_q8_0* const* y, float* const* out,
+ int r0, int r1) {
+ const __m128i m3 = _mm_set1_epi8(3);
+ const __m128i ones = _mm_set1_epi16(1);
+ const int nb = n / QK2_0;
+ const int pf = prefetch_distance();
+ for (int r = r0; r < r1; ++r) {
+ const uint8_t* row = w + (size_t) r * row_bytes;
+ __m128 accf[NT];
+ for (int t = 0; t < NT; ++t) accf[t] = _mm_setzero_ps();
+ for (int i = 0; i < nb; ++i) {
+ const uint8_t* blk = row + (size_t) i * sizeof(block_q2_0);
+ rows_ahead(blk, pf);
+ const float dx = h2f(u16(blk));
+ const uint8_t* qs = blk + 2;
+ for (int k = 0; k < 2; ++k) {
+ // 8 code bytes -> 32 unsigned codes in order (c0..c3 = the four 2-bit groups of each byte)
+ const __m128i q = _mm_cvtsi64_si128((long long) u64(qs + 8 * k));
+ const __m128i c0 = _mm_and_si128(q, m3);
+ const __m128i c1 = _mm_and_si128(_mm_srli_epi16(q, 2), m3);
+ const __m128i c2 = _mm_and_si128(_mm_srli_epi16(q, 4), m3);
+ const __m128i c3 = _mm_and_si128(_mm_srli_epi32(q, 6), m3);
+ const __m128i t01 = _mm_unpacklo_epi8(c0, c1);
+ const __m128i t23 = _mm_unpacklo_epi8(c2, c3);
+ const __m128i k0 = _mm_unpacklo_epi16(t01, t23); // codes 0..15
+ const __m128i k1 = _mm_unpackhi_epi16(t01, t23); // codes 16..31
+ for (int t = 0; t < NT; ++t) {
+ const uint8_t* q8 = (const uint8_t*) y[t][i * 2 + k].qs;
+ const __m128i y0 = _mm_loadu_si128((const __m128i*) q8);
+ const __m128i y1 = _mm_loadu_si128((const __m128i*) (q8 + 16));
+ // (c-1)*qy per pair: c*qy - qy, both at int16 level (|result| <= 508, no saturation)
+ const __m128i d0 = _mm_sub_epi16(_mm_maddubs_epi16(k0, y0), _mm_maddubs_epi16(_mm_set1_epi8(1), y0));
+ const __m128i d1 = _mm_sub_epi16(_mm_maddubs_epi16(k1, y1), _mm_maddubs_epi16(_mm_set1_epi8(1), y1));
+ const __m128 f = _mm_add_ps(_mm_cvtepi32_ps(_mm_madd_epi16(d0, ones)),
+ _mm_cvtepi32_ps(_mm_madd_epi16(d1, ones)));
+ accf[t] = _mm_add_ps(accf[t], _mm_mul_ps(_mm_set1_ps(dx * h2f(y[t][i * 2 + k].d)), f));
+ }
+ }
+ }
+ for (int t = 0; t < NT; ++t) out[t][r] = hsum4(accf[t]);
+ }
+}
+
+} // namespace
+
+bool iq128_supported(int type) noexcept {
+ return type == 18 || type == 21 || type == 22 || type == 23;
+}
+
+bool iq128_down_supported(int type) noexcept {
+ return type == 20 || type == 42;
+}
+
+void iq128_gu_rows(int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act,
+ int nt, float* const* ff, int r0, int r1) {
+ switch (type) {
+ case 18: gu_rows_nt<18>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
+ case 21: gu_rows_nt<21>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
+ case 22: gu_rows_nt<22>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
+ case 23: gu_rows_nt<23>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
+ default: break;
+ }
+}
+
+void iq128_down_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void* const* hq, int nt,
+ float* const* out, int r0, int r1) {
+ const block_q8_0* y[8];
+ for (int t = 0; t < nt && t < 8; ++t) y[t] = (const block_q8_0*) hq[t];
+ if (type == 20) {
+ for (int t0 = 0; t0 < nt; t0 += 4) {
+ const int k = nt - t0 < 4 ? nt - t0 : 4;
+ switch (k) {
+ case 1: iq4nl_rows<1>(w, row_bytes, n, y + t0, out + t0, r0, r1); break;
+ case 2: iq4nl_rows<2>(w, row_bytes, n, y + t0, out + t0, r0, r1); break;
+ case 3: iq4nl_rows<3>(w, row_bytes, n, y + t0, out + t0, r0, r1); break;
+ default: iq4nl_rows<4>(w, row_bytes, n, y + t0, out + t0, r0, r1); break;
+ }
+ }
+ return;
+ }
+ // Q2_0: the same 4-at-a-time chunking (NT is capped at 8 by the pool; prefill chunks larger than 8
+ // loop here, the per-token rows identical either way).
+ for (int t0 = 0; t0 < nt; t0 += 4) {
+ const int k = nt - t0 < 4 ? nt - t0 : 4;
+ switch (k) {
+ case 1: q2_0_rows<1>(w, row_bytes, n, y + t0, out + t0, r0, r1); break;
+ case 2: q2_0_rows<2>(w, row_bytes, n, y + t0, out + t0, r0, r1); break;
+ case 3: q2_0_rows<3>(w, row_bytes, n, y + t0, out + t0, r0, r1); break;
+ default: q2_0_rows<4>(w, row_bytes, n, y + t0, out + t0, r0, r1); break;
+ }
+ }
+}
+
+// ggml's quantize_row_q8_K_ref in SSE4.2/AVX1: q8k_quant_avx2's arithmetic, 128-bit lanes (its packs need no
+// lane-crossing permute at 128-bit). The same per-value operations as the scalar reference - one IEEE multiply
+// by the same iscale, the same 1.5*2^23 rounding add, the same clamp - so the bytes are identical
+// (q8k_quant_parity checks it), including the NaN and degenerate-block behavior: `ax > amax` is false for a NaN
+// and max_ps returns its second operand for a NaN first one, and a zero block leaves bsums as the reference does.
+void q8k_quant_avx1(const float* x, void* vy, int64_t k) {
+ block_q8_K* y = (block_q8_K*) vy;
+ const int64_t nb = k / QK_K;
+ const __m128 absm = _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff));
+ const __m128 magic = _mm_set1_ps(12582912.f);
+ const __m128i mant = _mm_set1_epi32(0x007fffff), off = _mm_set1_epi32(0x00400000);
+ const __m128i c127 = _mm_set1_epi32(127);
+ for (int64_t i = 0; i < nb; ++i, x += QK_K) {
+ __m128 m = _mm_setzero_ps();
+ for (int j = 0; j < QK_K; j += 4) m = _mm_max_ps(_mm_and_ps(_mm_loadu_ps(x + j), absm), m);
+ __m128 h = _mm_max_ps(m, _mm_movehl_ps(m, m));
+ h = _mm_max_ss(h, _mm_movehdup_ps(h));
+ const float amax = _mm_cvtss_f32(h);
+ if (!amax) {
+ y[i].d = 0;
+ std::memset(y[i].qs, 0, QK_K);
+ continue;
+ }
+ float mx = 0.f;
+ const __m128 va = _mm_set1_ps(amax);
+ for (int j = 0; j < QK_K; j += 4) {
+ const int msk = _mm_movemask_ps(_mm_cmpeq_ps(_mm_and_ps(_mm_loadu_ps(x + j), absm), va));
+ if (msk) {
+ int b = 0;
+ while (!((msk >> b) & 1)) ++b;
+ mx = x[j + b];
+ break;
+ }
+ }
+ const float iscale = -127.f / mx;
+ const __m128 vis = _mm_set1_ps(iscale);
+ for (int j = 0; j < QK_K; j += 16) {
+ __m128i v[4];
+ for (int q = 0; q < 4; ++q) {
+ __m128 p = _mm_mul_ps(vis, _mm_loadu_ps(x + j + 4 * q));
+#if defined(__GNUC__) && !defined(__clang__)
+ // GCC fuses a multiply and an add into an FMA by default (-ffp-contract=fast); the reference
+ // rounds the product before the add, so the product must stay a separate value (no FMA under
+ // -mavx, but the barrier keeps the contract if the file is ever built with a newer floor)
+ __asm__("" : "+x"(p));
+#endif
+ const __m128 t = _mm_add_ps(p, magic);
+ v[q] = _mm_min_epi32(_mm_sub_epi32(_mm_and_si128(_mm_castps_si128(t), mant), off), c127);
+ // the reference stores MIN(127, v) into an int8 (keeps the low byte), and its bsums add those
+ // bytes: the same here, so even a degenerate block (iscale overflowing to inf) gives the same bytes
+ v[q] = _mm_srai_epi32(_mm_slli_epi32(v[q], 24), 24);
+ }
+ __m128i s = _mm_add_epi32(_mm_add_epi32(v[0], v[1]), _mm_add_epi32(v[2], v[3]));
+ s = _mm_add_epi32(s, _mm_shuffle_epi32(s, 0x4E));
+ s = _mm_add_epi32(s, _mm_shuffle_epi32(s, 0xB1));
+ y[i].bsums[j / 16] = (int16_t) _mm_cvtsi128_si32(s);
+ _mm_storeu_si128((__m128i*) (y[i].qs + j),
+ _mm_packs_epi16(_mm_packs_epi32(v[0], v[1]), _mm_packs_epi32(v[2], v[3])));
+ }
+ y[i].d = 1 / iscale;
+ }
+}
+
+} // namespace strata::kernels::cpu
diff --git a/src/kernels/cpu/iq_avx1_parity.cpp b/src/kernels/cpu/iq_avx1_parity.cpp
new file mode 100644
index 000000000..2f83251f9
--- /dev/null
+++ b/src/kernels/cpu/iq_avx1_parity.cpp
@@ -0,0 +1,291 @@
+// src/kernels/cpu/iq_avx1_parity.cpp - the AVX1 expert kernels (iq_avx1.cpp) against ggml-cpu's dots and
+// against themselves at every token count. No GPU, no model: random blocks (every grid index and sign
+// pattern occurs) and random activations quantized the way the engine quantizes them.
+//
+// iq_avx1_parity IQ3_XXS/IQ3_S/IQ2_S/IQ4_XS gate/up rows and IQ4_NL/Q2_0 down rows:
+// every row bit for bit the same kernel's one-token row (#152), and rel <= 1e-5
+// against ggml-cpu's vec_dot (the scalar _generic the engine runs without these).
+// iq_avx1_parity --bench [--mb 128] [--nt 1,2,4] [--cpu N]
+// ms per expert on one thread: ggml-cpu's per-token dot vs the iq128 kernel over
+// --mb MB of expert blobs (more than any L3: the weights stream from DRAM as in
+// decode), for the nt in --nt.
+//
+// Runs on any CPU with AVX (the kernels are compiled for SSE4.2 + AVX); on an AVX2 machine it checks the
+// older-CPU path exactly as an AVX-only machine runs it (the engine's dispatch gate is separate: this calls
+// the kernels directly).
+#include "strata/kernels/cpu/iq_avx1.hpp"
+#include "strata/kernels/cpu/native_expert.hpp"
+#include "strata/kernels/cpu/expert_layout.hpp"
+
+#include "ggml.h"
+#include "ggml-cpu.h"
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <string>
+#include <vector>
+
+#if !defined(_WIN32)
+#include <sched.h>
+#endif
+
+namespace cpu = strata::kernels::cpu;
+using Clock = std::chrono::steady_clock;
+
+namespace {
+
+constexpr int kH = 2560, kFF = 640; // the experts' geometry: n_embd, expert width (as iq_avx2_parity)
+constexpr int kMaxT = 8;
+
+uint64_t mix(uint64_t& s) { // splitmix64
+ uint64_t z = (s += 0x9E3779B97F4A7C15ull);
+ z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
+ z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
+ return z ^ (z >> 31);
+}
+
+const ggml_type_traits_cpu* traits_cpu(int type) { return ggml_get_type_traits_cpu((ggml_type) type); }
+
+// random bytes, then a sane fp16 scale at the front of every block (iq_avx2_parity's)
+void fill_blocks(uint8_t* p, size_t bytes, int type, uint64_t& seed) {
+ for (size_t i = 0; i < bytes; i += 8) {
+ const uint64_t v = mix(seed);
+ std::memcpy(p + i, &v, std::min<size_t>(8, bytes - i));
+ }
+ const size_t bs = ggml_type_size((ggml_type) type);
+ for (size_t o = 0; o + bs <= bytes; o += bs) {
+ const float d = (0.5f + (float) (mix(seed) >> 40) * (1.f / 16777216.f)) * 1e-3f;
+ const ggml_fp16_t h = ggml_fp32_to_fp16(d);
+ std::memcpy(p + o, &h, 2);
+ }
+}
+
+void fill_blob(uint8_t* blob, const cpu::NativeFmt& f, uint64_t& seed) {
+ fill_blocks(blob, f.down_off, f.gu_type, seed); // the gate and up rows
+ fill_blocks(blob + f.down_off, f.bytes - f.down_off, f.d_type, seed); // the down rows
+}
+
+struct Case {
+ int gu, dn;
+ const char* name;
+};
+
+const Case kCases[] = {
+ {18, 20, "iq3_xxs/iq4_nl"}, {21, 20, "iq3_s/iq4_nl"}, {22, 20, "iq2_s/iq4_nl"}, {23, 20, "iq4_xs/iq4_nl"},
+ {18, 42, "iq3_xxs/q2_0"}, {21, 42, "iq3_s/q2_0"}, {22, 42, "iq2_s/q2_0"}, {23, 42, "iq4_xs/q2_0"},
+};
+
+// one expert, nt tokens of quantized activations, and the reference rows
+struct Fixture {
+ cpu::NativeFmt f;
+ std::vector<uint8_t> blob;
+ std::vector<std::vector<uint8_t>> act, hq; // per token
+ std::vector<std::vector<float>> x, h;
+ std::vector<float> ff_ref, out_ref; // [t][row]
+};
+
+void make_fixture(Fixture& fx, int gu, int dn, int nt, uint64_t& seed) {
+ std::string err;
+ if (!cpu::native_fmt(gu, dn, kH, kFF, fx.f, err)) { std::fprintf(stderr, "native_fmt: %s\n", err.c_str()); std::exit(1); }
+ fx.blob.resize(fx.f.bytes);
+ fill_blob(fx.blob.data(), fx.f, seed);
+ fx.act.resize(nt); fx.hq.resize(nt); fx.x.resize(nt); fx.h.resize(nt);
+ for (int t = 0; t < nt; ++t) {
+ fx.act[t].resize(fx.f.act_bytes); fx.hq[t].resize(fx.f.h_bytes);
+ fx.x[t].resize(kH); fx.h[t].resize(kFF);
+ for (int i = 0; i < kH; ++i) fx.x[t][i] = (float) ((mix(seed) >> 40) * 0x1p-24 * 2.0 - 1.0);
+ for (int i = 0; i < kFF; ++i) fx.h[t][i] = (float) ((mix(seed) >> 40) * 0x1p-24 * 2.0 - 1.0);
+ cpu::native_quant_act(fx.f, fx.x[t].data(), fx.act[t].data());
+ cpu::native_quant_h(fx.f, fx.h[t].data(), fx.hq[t].data());
+ }
+ // reference rows: ggml-cpu's own dots, per token (what the engine runs without the iq128 kernels)
+ const ggml_vec_dot_t gu_dot = traits_cpu(gu)->vec_dot;
+ const ggml_vec_dot_t dn_dot = traits_cpu(dn)->vec_dot;
+ fx.ff_ref.resize((size_t) nt * kFF); fx.out_ref.resize((size_t) nt * kH);
+ for (int t = 0; t < nt; ++t) {
+ for (int r = 0; r < kFF; ++r) {
+ float g = 0.f, u = 0.f;
+ gu_dot(kH, &g, 0, fx.blob.data() + (size_t) r * fx.f.gu_row, 0, fx.act[t].data(), 0, 1);
+ gu_dot(kH, &u, 0, fx.blob.data() + fx.f.up_off + (size_t) r * fx.f.gu_row, 0, fx.act[t].data(), 0, 1);
+ fx.ff_ref[(size_t) t * kFF + r] = (g / (1.f + std::exp(-g))) * u;
+ }
+ for (int r = 0; r < kH; ++r) {
+ float s = 0.f;
+ dn_dot(kFF, &s, 0, fx.blob.data() + fx.f.down_off + (size_t) r * fx.f.d_row, 0, fx.hq[t].data(), 0, 1);
+ fx.out_ref[(size_t) t * kH + r] = s;
+ }
+ }
+}
+
+int failures = 0;
+
+void check(const char* what, const std::vector<float>& got, const std::vector<float>& ref, bool exact) {
+ if (exact) { // bit-exact (iq_avx2_parity's rows_differ)
+ size_t d = 0;
+ for (size_t i = 0; i < ref.size(); ++i) d += std::memcmp(&got[i], &ref[i], sizeof(float)) != 0;
+ if (d) { std::printf(" FAIL %s: %zu of %zu rows differ\n", what, d, ref.size()); ++failures; }
+ return;
+ }
+ // the repo's bar (iq_avx2_parity's rel): aggregate sum|diff| / sum|ref| <= 1e-5
+ double num = 0, den = 0;
+ for (size_t i = 0; i < ref.size(); ++i) {
+ num += std::fabs((double) got[i] - (double) ref[i]);
+ den += std::fabs((double) ref[i]);
+ }
+ const double r = num / (den + 1e-30);
+ if (!(r <= 1e-5)) { std::printf(" FAIL %s: rel %.3e > 1e-5 vs ggml-cpu\n", what, r); ++failures; }
+}
+
+// ---- the checks
+void run_checks() {
+ for (const Case& c : kCases) {
+ uint64_t seed = 0x5EED1234u + (uint64_t) c.gu * 1000 + (uint64_t) c.dn;
+ Fixture fx;
+ make_fixture(fx, c.gu, c.dn, kMaxT, seed);
+ const void* actp[kMaxT]; const void* hqp[kMaxT];
+ std::vector<float> ff[kMaxT], out[kMaxT];
+ float* ffp[kMaxT]; float* outp[kMaxT];
+ for (int t = 0; t < kMaxT; ++t) {
+ actp[t] = fx.act[t].data(); hqp[t] = fx.hq[t].data();
+ ff[t].resize(kFF); out[t].resize(kH);
+ ffp[t] = ff[t].data(); outp[t] = out[t].data();
+ }
+ // gate/up: nt = 1..8, every width bit-identical to that token's nt = 1 row (#152), all rel <= 1e-5 vs ggml
+ std::vector<std::vector<float>> ff1(kMaxT), out1(kMaxT);
+ for (int nt = 1; nt <= kMaxT; ++nt) {
+ cpu::iq128_gu_rows(c.gu, fx.blob.data(), fx.f.gu_row, fx.f.up_off, kH, actp, nt, ffp, 0, kFF);
+ for (int t = 0; t < nt; ++t) {
+ char what[96];
+ std::snprintf(what, sizeof what, "%s gu nt=%d vs ggml", c.name, nt);
+ check(what, ff[t], std::vector<float>(fx.ff_ref.begin() + (size_t) t * kFF,
+ fx.ff_ref.begin() + (size_t) (t + 1) * kFF), false);
+ if (nt == 1) ff1[t] = ff[t];
+ else {
+ std::snprintf(what, sizeof what, "%s gu nt=%d token %d vs its nt=1 row", c.name, nt, t);
+ check(what, ff[t], ff1[t], true);
+ }
+ }
+ }
+ // down
+ for (int nt = 1; nt <= kMaxT; ++nt) {
+ cpu::iq128_down_rows(c.dn, fx.blob.data() + fx.f.down_off, fx.f.d_row, kFF, hqp, nt, outp, 0, kH);
+ for (int t = 0; t < nt; ++t) {
+ char what[96];
+ std::snprintf(what, sizeof what, "%s down nt=%d vs ggml", c.name, nt);
+ check(what, out[t], std::vector<float>(fx.out_ref.begin() + (size_t) t * kH,
+ fx.out_ref.begin() + (size_t) (t + 1) * kH), false);
+ if (nt == 1) out1[t] = out[t];
+ else {
+ std::snprintf(what, sizeof what, "%s down nt=%d token %d vs its nt=1 row", c.name, nt, t);
+ check(what, out[t], out1[t], true);
+ }
+ }
+ }
+ std::printf(" %-16s checked (gu %d, down %d)\n", c.name, c.gu, c.dn);
+ }
+}
+
+// ---- the bench: ms per expert, the weights streamed from DRAM
+void run_bench(int mb, const std::vector<int>& nts) {
+ for (const Case& c : kCases) {
+ uint64_t seed = 0xBEEF0000u + (uint64_t) c.gu * 1000 + (uint64_t) c.dn;
+ Fixture fx;
+ make_fixture(fx, c.gu, c.dn, 1, seed);
+ const size_t per = fx.f.bytes;
+ const int nexp = (int) ((size_t) mb * 1024 * 1024 / per);
+ std::vector<uint8_t> blob((size_t) nexp * per);
+ for (int e = 0; e < nexp; ++e) std::memcpy(blob.data() + (size_t) e * per, fx.blob.data(), per);
+ // vary the blocks a little so the run is not one blob repeated (the same bytes hit the same caches)
+ for (int e = 1; e < nexp; ++e) {
+ uint64_t s2 = seed + (uint64_t) e * 7919;
+ const size_t o = (size_t) e * per;
+ for (size_t i = 0; i + 8 <= per; i += 128) {
+ const uint64_t v = mix(s2);
+ std::memcpy(blob.data() + o + i, &v, 8); // keep block scales (first 2 bytes of each block)
+ }
+ }
+ for (int nt : nts) {
+ if (nt > kMaxT) continue;
+ const void* actp[kMaxT]; const void* hqp[kMaxT];
+ float* ffp[kMaxT]; float* outp[kMaxT];
+ std::vector<std::vector<float>> ff(kMaxT, std::vector<float>(kFF)), out(kMaxT, std::vector<float>(kH));
+ Fixture fx8; // nt tokens of activations
+ uint64_t s8 = seed + 0x1234;
+ make_fixture(fx8, c.gu, c.dn, nt, s8);
+ for (int t = 0; t < nt; ++t) {
+ actp[t] = fx8.act[t].data(); hqp[t] = fx8.hq[t].data();
+ ffp[t] = ff[t].data(); outp[t] = out[t].data();
+ }
+ const ggml_vec_dot_t gu_dot = traits_cpu(c.gu)->vec_dot, dn_dot = traits_cpu(c.dn)->vec_dot;
+ // ggml-cpu's path (what the engine runs today on this CPU): per-token dots over every row
+ auto t0 = Clock::now();
+ for (int e = 0; e < nexp; ++e) {
+ for (int r = 0; r < kFF; ++r) {
+ for (int t = 0; t < nt; ++t) {
+ float g = 0.f, u = 0.f;
+ gu_dot(kH, &g, 0, blob.data() + (size_t) e * per + (size_t) r * fx.f.gu_row, 0, (const uint8_t*) actp[t], 0, 1);
+ gu_dot(kH, &u, 0, blob.data() + (size_t) e * per + fx.f.up_off + (size_t) r * fx.f.gu_row, 0, (const uint8_t*) actp[t], 0, 1);
+ ff[t][r] = (g / (1.f + std::exp(-g))) * u;
+ }
+ }
+ for (int r = 0; r < kH; ++r) {
+ for (int t = 0; t < nt; ++t) {
+ float s = 0.f;
+ dn_dot(kFF, &s, 0, blob.data() + (size_t) e * per + fx.f.down_off + (size_t) r * fx.f.d_row, 0, (const uint8_t*) hqp[t], 0, 1);
+ out[t][r] = s;
+ }
+ }
+ }
+ const double ms_ggml = std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
+ t0 = Clock::now();
+ for (int e = 0; e < nexp; ++e) {
+ cpu::iq128_gu_rows(c.gu, blob.data() + (size_t) e * per, fx.f.gu_row, fx.f.up_off, kH, actp, nt, ffp, 0, kFF);
+ cpu::iq128_down_rows(c.dn, blob.data() + (size_t) e * per + fx.f.down_off, fx.f.d_row, kFF, hqp, nt, outp, 0, kH);
+ }
+ const double ms_iq = std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
+ std::printf(" %-16s nt=%d ggml %8.2f ms/expert iq128 %6.2f ms/expert %.1fx\n",
+ c.name, nt, ms_ggml / nexp, ms_iq / nexp, ms_ggml / ms_iq);
+ }
+ }
+}
+
+} // namespace
+
+int main(int argc, char** argv) {
+ bool bench = false;
+ int mb = 128, cpu_pin = -1;
+ std::vector<int> nts = {1, 2, 4};
+ for (int i = 1; i < argc; ++i) {
+ std::string a = argv[i];
+ if (a == "--bench") bench = true;
+ else if (a == "--mb" && i + 1 < argc) mb = std::atoi(argv[++i]);
+ else if (a == "--cpu" && i + 1 < argc) cpu_pin = std::atoi(argv[++i]);
+ else if (a == "--nt" && i + 1 < argc) {
+ nts.clear();
+ const char* p = argv[++i];
+ while (*p) { nts.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p == ',') ++p; }
+ } else {
+ std::printf("usage: iq_avx1_parity [--bench [--mb N] [--nt 1,2,4] [--cpu N]]\n");
+ return 2;
+ }
+ }
+#if !defined(_WIN32)
+ if (cpu_pin >= 0) {
+ cpu_set_t set;
+ CPU_ZERO(&set);
+ CPU_SET(cpu_pin, &set);
+ if (sched_setaffinity(0, sizeof set, &set) != 0) std::fprintf(stderr, "pinning to CPU %d failed\n", cpu_pin);
+ }
+#endif
+ if (!cpu::cpu_avx1_ok()) { std::printf("iq_avx1_parity: no AVX here, the kernels would not run\n"); return 0; }
+ std::printf("iq_avx1_parity: %s\n", cpu::cpu_avx1_ok() ? "AVX1 kernels checked (128-bit lanes)" : "");
+ if (bench) { run_bench(mb, nts); return failures != 0; }
+ run_checks();
+ std::printf(failures ? "iq_avx1_parity: %d FAILURES\n" : "iq_avx1_parity: all rows match\n", failures);
+ return failures != 0;
+}
diff --git a/src/kernels/cpu/native_expert.cpp b/src/kernels/cpu/native_expert.cpp
index 8baead060..78e3cbaa0 100644
--- a/src/kernels/cpu/native_expert.cpp
+++ b/src/kernels/cpu/native_expert.cpp
@@ -5,6 +5,7 @@
#include "strata/kernels/cpu/expert.hpp"
#include "strata/kernels/cpu/iq_avx512.hpp"
#include "strata/kernels/cpu/iq_avx2.hpp"
+#include "strata/kernels/cpu/iq_avx1.hpp"
#include "strata/kernels/cpu/kq_avx2.hpp"
#include "strata/kernels/cpu/expert_layout.hpp"
@@ -91,15 +92,23 @@ bool q8k_avx2(int type) {
static const bool on = cpu_avx2_ok() && std::getenv("STRATA_NO_Q8K_AVX2") == nullptr;
return on && type == (int) GGML_TYPE_Q8_K;
}
+// the older CPUs' copy (iq_avx1.cpp): byte-identical like the AVX-2 one, and only where AVX2 is absent (same
+// policy as STRATA_NO_IQ128 above; STRATA_NO_Q8K_AVX1=1 keeps ggml's scalar reference on those CPUs).
+bool q8k_avx1(int type) {
+ static const bool on = !cpu_avx2_ok() && cpu_avx1_ok() && std::getenv("STRATA_NO_Q8K_AVX1") == nullptr;
+ return on && type == (int) GGML_TYPE_Q8_K;
+}
} // namespace
void native_quant_act(const NativeFmt& f, const float* x, void* dst) {
if (q8k_avx2(f.gu_act)) { q8k_quant_avx2(x, dst, f.n_embd); return; }
+ if (q8k_avx1(f.gu_act)) { q8k_quant_avx1(x, dst, f.n_embd); return; }
traits(f.gu_act)->from_float(x, dst, f.n_embd);
}
void native_quant_h(const NativeFmt& f, const float* h, void* dst) {
if (q8k_avx2(f.d_act)) { q8k_quant_avx2(h, dst, f.n_ff); return; }
+ if (q8k_avx1(f.d_act)) { q8k_quant_avx1(h, dst, f.n_ff); return; }
traits(f.d_act)->from_float(h, dst, f.n_ff);
}
@@ -138,6 +147,14 @@ void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const*
// baseline the build selected (AVX1 here) and covers the same types - IQ2_XXS and IQ2_S among
// them. That path loops over tokens itself, so it is correct for any `nt`, not just one.
static const bool avx2 = cpu_avx2_ok() && std::getenv("STRATA_NO_IQ256") == nullptr;
+ // The older-CPU tier (STRATA_ISA_FLOOR=avx builds): without it every expert on such a CPU runs on ggml-cpu's
+ // scalar _generic dots. Only where AVX2 is absent, so a modern CPU's rounding never moves (and
+ // STRATA_NO_IQ256=1 there still means ggml, as before). iq_avx1.cpp is compiled for AVX and gated on
+ // cpu_avx1_ok(). Measured on an E5-2470 v2 (iq_avx1_parity --bench): 1.2-3.1x ggml's dot from two tokens on,
+ // at one token ggml's auto-vectorized generic loop matches the 128-bit kernel - so the same #152 mt_min rule
+ // as the AVX-2 kernels, and STRATA_IQ_MT_MIN=1 takes the kernel for one token too (its rows are then
+ // independent of the drafting: iq_avx1_parity checks every width bit for bit).
+ static const bool avx1 = !cpu_avx2_ok() && cpu_avx1_ok() && std::getenv("STRATA_NO_IQ128") == nullptr;
const int mt_min = native_gu_mt_min(f.gu_type); // #152
// Unsloth UD-Q4_K_XL's Q4_K gate/up: the multi-token kernel is bit-exact against ggml's per-token dot (any group
// size, no #152 rule). Opt-in, STRATA_KQ256=1: measured no faster in the engine (a window's expert groups hold
@@ -161,6 +178,10 @@ void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const*
return;
}
}
+ if (avx1 && nt >= mt_min && iq128_supported(f.gu_type)) {
+ iq128_gu_rows(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1);
+ return;
+ }
const ggml_vec_dot_t dot = traits(f.gu_type)->vec_dot;
const int n = (int) f.n_embd;
for (int r = r0; r < r1; ++r) {
@@ -193,6 +214,12 @@ void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const
iq4nl256_down_rows(blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1);
return;
}
+ // the older-CPU tier: IQ4_NL and Q2_0 down rows in 128-bit (ggml-cpu's dots for both are scalar here)
+ static const bool avx1 = !cpu_avx2_ok() && cpu_avx1_ok() && std::getenv("STRATA_NO_IQ128") == nullptr;
+ if (avx1 && iq128_down_supported(f.d_type)) {
+ iq128_down_rows(f.d_type, blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1);
+ return;
+ }
const ggml_vec_dot_t dot = traits(f.d_type)->vec_dot;
const int n = (int) f.n_ff;
for (int r = r0; r < r1; ++r) {
diff --git a/src/kernels/cpu/q8k_quant_parity.cpp b/src/kernels/cpu/q8k_quant_parity.cpp
index 535b1881e..dc24e652f 100644
--- a/src/kernels/cpu/q8k_quant_parity.cpp
+++ b/src/kernels/cpu/q8k_quant_parity.cpp
@@ -7,6 +7,7 @@
// q8k_quant_parity --bench ns per 2560-value row, ggml-cpu's and the AVX-2 copy
#include "strata/kernels/cpu/expert_layout.hpp"
#include "strata/kernels/cpu/iq_avx2.hpp"
+#include "strata/kernels/cpu/iq_avx1.hpp"
#include "strata/kernels/cpu/native_expert.hpp"
#include "ggml.h"
@@ -93,6 +94,7 @@ int main(int argc, char** argv) {
const ggml_from_float_t ref = quantize_row_q8_K_ref;
const ggml_from_float_t gcpu = ggml_get_type_traits_cpu(GGML_TYPE_Q8_K)->from_float;
const bool avx2 = cpu::cpu_avx2_ok();
+ const bool avx1 = !avx2 && cpu::cpu_avx1_ok(); // the older CPUs' copy (checked wherever AVX exists)
int failures = 0, checked = 0;
for (const int n : {256, 512, 2560, 6144}) {
const size_t bytes = ggml_row_size(GGML_TYPE_Q8_K, n);
@@ -100,6 +102,7 @@ int main(int argc, char** argv) {
for (int ci = 0; ci < (int) cs.size(); ++ci) {
failures += !same("ggml-cpu vs reference", n, ci, ref, gcpu, cs[(size_t) ci], bytes);
if (avx2) failures += !same("AVX-2 vs reference", n, ci, ref, cpu::q8k_quant_avx2, cs[(size_t) ci], bytes);
+ if (avx1) failures += !same("AVX1 vs reference", n, ci, ref, cpu::q8k_quant_avx1, cs[(size_t) ci], bytes);
++checked;
}
}
@@ -115,9 +118,10 @@ int main(int argc, char** argv) {
failures += !same("native_quant_act", 2560, 0, ref, via_act, x, ggml_row_size(GGML_TYPE_Q8_K, 2560));
for (const auto& x : cases(512))
failures += !same("native_quant_h", 512, 0, ref, via_h, x, ggml_row_size(GGML_TYPE_Q8_K, 512));
- std::printf("q8k_quant_parity: %d rows x 4 sizes, AVX-2 copy %s: %s\n", checked / 4,
- avx2 ? "checked" : "skipped (no AVX2, or STRATA_FORCE_ISA)", failures ? "FAILED" : "identical");
- if (bench && avx2) {
+ std::printf("q8k_quant_parity: %d rows x 4 sizes, AVX-2 copy %s, AVX1 copy %s: %s\n", checked / 4,
+ avx2 ? "checked" : "skipped (no AVX2, or STRATA_FORCE_ISA)",
+ avx1 ? "checked" : "skipped (AVX2 present, no AVX, or STRATA_FORCE_ISA)", failures ? "FAILED" : "identical");
+ if (bench && (avx2 || avx1)) {
std::mt19937 rng(3);
std::normal_distribution<float> nd(0.f, 1.f);
const int n = 2560, rows = 4096;
@@ -137,7 +141,7 @@ int main(int argc, char** argv) {
return best;
};
const double a = time("ggml-cpu", gcpu);
- const double b = time("AVX-2", cpu::q8k_quant_avx2);
+ const double b = avx2 ? time("AVX-2", cpu::q8k_quant_avx2) : time("AVX1", cpu::q8k_quant_avx1);
std::printf(" %.1fx\n", a / b);
}
return failures ? 1 : 0;
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index 45d5350d6..7f76ca12c 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -2618,7 +2618,10 @@ int main(int argc, char** argv) {
else if (!strata::kernels::cpu::cpu_avx512_ok())
std::fprintf(stderr, "strata generate: this CPU has no AVX-512: the expert kernels run on %s "
"(multi-token for the i-quant gate/up rows)\n",
- !strata::kernels::cpu::cpu_avx2_ok() ? "ggml-cpu vec_dot (no AVX2: the older-CPU build)"
+ !strata::kernels::cpu::cpu_avx2_ok()
+ ? (strata::kernels::cpu::cpu_avx1_ok() && std::getenv("STRATA_NO_IQ128") == nullptr
+ ? "AVX1 128-bit (iq_avx1, the older-CPU build)"
+ : "ggml-cpu vec_dot (no AVX2: the older-CPU build)")
: std::getenv("STRATA_NO_IQ256") == nullptr ? "AVX-2" : "ggml-cpu vec_dot (STRATA_NO_IQ256 set)");
strata::core::ModelGeometry g; // canonical defaults; the model file overrides the MoE shape below
int64_t K = 10;