okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f2eedfe9f
main
1// src/kernels/cpu/expert.cpp - P2.S3: the Q2_0 expert kernel, promoted from bench/micro/cpu_s2.cpp. 2// 3// The body is the validated kernel, moved rather than rewritten: it carries the P0.T2 parity result 4// (rel 1.461e-06 against the ggml formula) and the three performance findings recorded in 5// include/strata/kernels/cpu/expert.hpp. Read that header first; it says why each piece is shaped this way. 6#include "strata/kernels/cpu/expert.hpp" 7#include "strata/kernels/cpu/expert_layout.hpp" 8 9#include <immintrin.h> 10#if defined(_MSC_VER ) 11#include <intrin.h> 12#else 13#include <cpuid.h> 14#endif 15 16#include <cmath> 17#include <atomic> 18#include <cstdio> 19#include <cstdlib> 20#include <cstring> 21 22namespace strata::kernels::cpu { 23namespace { 24 25/// fp16 -> fp32, written out rather than using `_cvtsh_ss`, because the F16C intrinsic's behaviour on 26/// subnormals is the one place the two can differ and the scales in this artifact are small. 27inline float h2f (const uint8_t * p ) { 28uint16_t h ; 29 std::memcpy (& h ,p ,2 ); 30const uint32_t sign = (uint32_t ) (h >>15 )& 1u ; 31uint32_t exp = (h >>10 )& 0x1Fu ,man = h & 0x3FFu ,f ; 32if (exp == 0 ) { 33if (man == 0 ) { 34f = sign <<31 ; 35 }else { 36exp = 127 - 15 + 1 ; 37while (!(man & 0x400u )) {man <<=1 ;-- exp ; } 38man &=0x3FFu ; 39f = (sign <<31 ) | (exp <<23 ) | (man <<13 ); 40 } 41 }else if (exp == 31 ) { 42f = (sign <<31 ) |0x7F800000u | (man <<13 ); 43 }else { 44f = (sign <<31 ) | ((exp - 15 + 127 ) <<23 ) | (man <<13 ); 45 } 46float out ; 47 std::memcpy (& out ,& f ,4 ); 48return out ; 49} 50 51// The x86 Q8_0 quantization and generic Q2_0 dot sequences are adapted from llama.cpp 52// 3cf03257f219afbe7334045ff7c6a06ac68c627d, 53// ggml/src/ggml-cpu/arch/x86/quants.c: quantize_row_q8_0 and 54// ggml/src/ggml-cpu/quants.c: ggml_vec_dot_q2_0_q8_0_generic. 55// 56// MIT License 57// Copyright (c) 2023-2026 The ggml authors 58// 59// Permission is hereby granted, free of charge, to any person obtaining a copy 60// of this software and associated documentation files (the "Software"), to deal 61// in the Software without restriction, including without limitation the rights 62// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 63// copies of the Software, and to permit persons to whom the Software is 64// furnished to do so, subject to the following conditions: 65// 66// The above copyright notice and this permission notice shall be included in all 67// copies or substantial portions of the Software. 68// 69// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 70// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 71// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 72// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 73// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 74// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 75// SOFTWARE. 76void quantize_oracle_q8_0 (const float * x ,int n ,ActQ & a ) { 77a .nchunks = n /QKA ; 78for (int chunk = 0 ;chunk < a .nchunks ;++ chunk ) { 79const float * xb = x + chunk * QKA ; 80__m256 v0 = _mm256_loadu_ps (xb ); 81__m256 v1 = _mm256_loadu_ps (xb + 8 ); 82__m256 v2 = _mm256_loadu_ps (xb + 16 ); 83__m256 v3 = _mm256_loadu_ps (xb + 24 ); 84const __m256 sign = _mm256_set1_ps (-0.0f ); 85__m256 maximum = _mm256_andnot_ps (sign ,v0 ); 86maximum = _mm256_max_ps (maximum ,_mm256_andnot_ps (sign ,v1 )); 87maximum = _mm256_max_ps (maximum ,_mm256_andnot_ps (sign ,v2 )); 88maximum = _mm256_max_ps (maximum ,_mm256_andnot_ps (sign ,v3 )); 89__m128 max4 = _mm_max_ps (_mm256_extractf128_ps (maximum ,1 ),_mm256_castps256_ps128 (maximum )); 90max4 = _mm_max_ps (max4 ,_mm_movehl_ps (max4 ,max4 )); 91max4 = _mm_max_ss (max4 ,_mm_movehdup_ps (max4 )); 92const float amax = _mm_cvtss_f32 (max4 ); 93const float d = amax /127.0f ; 94const uint16_t half_d = (uint16_t )_mm_cvtsi128_si32 (_mm_cvtps_ph (_mm_set_ss (d ),0 )); 95const __m256 inverse = _mm256_set1_ps (amax != 0.0f ?127.0f /amax :0.0f ); 96v0 = _mm256_round_ps (_mm256_mul_ps (v0 ,inverse ),_MM_FROUND_TO_NEAREST_INT ); 97v1 = _mm256_round_ps (_mm256_mul_ps (v1 ,inverse ),_MM_FROUND_TO_NEAREST_INT ); 98v2 = _mm256_round_ps (_mm256_mul_ps (v2 ,inverse ),_MM_FROUND_TO_NEAREST_INT ); 99v3 = _mm256_round_ps (_mm256_mul_ps (v3 ,inverse ),_MM_FROUND_TO_NEAREST_INT ); 100__m256i i0 = _mm256_packs_epi32 (_mm256_cvtps_epi32 (v0 ),_mm256_cvtps_epi32 (v1 )); 101const __m256i i2 = _mm256_packs_epi32 (_mm256_cvtps_epi32 (v2 ),_mm256_cvtps_epi32 (v3 )); 102i0 = _mm256_packs_epi16 (i0 ,i2 ); 103i0 = _mm256_permutevar8x32_epi32 (i0 ,_mm256_setr_epi32 (0 ,4 ,1 ,5 ,2 ,6 ,3 ,7 )); 104int8_t * q = a .q + chunk * QKA ; 105_mm256_storeu_si256 ((__m256i * )q ,i0 ); 106int32_t sum = 0 ; 107for (int j = 0 ;j < QKA ;++ j )sum += q [j ]; 108a .scale [chunk ]= h2f ((const uint8_t * )& half_d ); 109a .sum [chunk ]= sum ; 110a .hx [chunk ]= a .scale [chunk ]* float (sum ); 111 } 112} 113 114/// 2-bit unpack via VPMULTISHIFTQB. 115/// 116/// ARGUMENT ORDER IS (control, data) AND WAS DETERMINED EMPIRICALLY (`bench/micro/probe_multishift.cpp`). 117/// The Intel guide states (a=data, b=control); using that produced 43 of 64 wrong codes. `plan.md`'s sketch 118/// passes the shift pattern first, which is correct - so a "fix" that swapped it to match the guide was the 119/// bug, not the fix. Within each 64-bit lane, output byte i is `(u16 >> 2i) & 0xFF`, so AND 3 yields the 120/// eight 2-bit codes in order. 121/// 122/// The result is the 32 codes of ONE ACTIVATION CHUNK (4 qword lanes), which is the unit the Q8_1 scale is 123/// defined on - not the 64-weight block. 124inline __m256i unpack_q2_0 (const uint8_t * codes ) { 125const __m128i packed = _mm_loadl_epi64 ((const __m128i * )codes );// 8 bytes -> 4 u16 in the low half 126const __m256i lanes = _mm256_cvtepu16_epi64 (packed );// 4 qwords, 8 codes each 127const __m256i ctrl = _mm256_set1_epi64x ((long long )0x0E0C0A0806040200ULL ); 128return _mm256_and_si256 (_mm256_multishift_epi64_epi8 (ctrl ,lanes ),_mm256_set1_epi8 (3 )); 129} 130 131/// 32 codes against 32 int8 activations. Codes 0 contribute nothing to `sum(c*xhat)`, so the zero lanes the 132/// narrow load leaves behind are harmless. 133inline __m256i block_dot (const uint8_t * codes ,const int8_t * xq ) { 134return _mm256_dpbusd_epi32 (_mm256_setzero_si256 (),unpack_q2_0 (codes ), 135_mm256_load_si256 ((const __m256i * )xq )); 136} 137 138inline float hsum_ps (__m256 v ) { 139const __m128 s = _mm_add_ps (_mm256_castps256_ps128 (v ),_mm256_extractf128_ps (v ,1 )); 140return _mm_cvtss_f32 (_mm_hadd_ps (_mm_hadd_ps (s ,s ),s )); 141} 142 143// ================================ plan v0.3 P6: the row dot in 512-bit lanes ================================ 144// 145// The 256-bit row dot below spent ~12 cycles per 64-weight block: two unpacks, two VNNI dots, two converts, two 146// scalar scale products broadcast into two FMAs, an fp16 conversion and a scalar correction - compute-bound at 147// ~39 GB/s while the machine streams 52. Here a block is ONE unpack (16 code bytes -> 64 codes), ONE VNNI dot 148// over 64 activations, ONE convert and ONE FMA whose per-chunk scales come from a permute of a vector of scale 149// products built for eight blocks at a time; the weight-independent correction is one FMA per eight blocks. 150// The sum order differs from the 256-bit kernel (last-bit differences); the verify window and plain decode both 151// use this kernel, so speculative decode still reproduces plain decode exactly. 152static const bool kZmm = std::getenv ("STRATA_CPU_YMM" )== nullptr ; 153 154inline __m512i unpack64_q2_0_ms (const uint8_t * codes ) { 155const __m128i packed = _mm_loadu_si128 ((const __m128i * )codes );// 8 u16 = 64 codes 156const __m512i lanes = _mm512_cvtepu16_epi64 (packed );// 8 qwords, 8 codes each 157const __m512i ctrl = _mm512_set1_epi64 ((long long )0x0E0C0A0806040200ULL ); 158return _mm512_and_si512 (_mm512_multishift_epi64_epi8 (ctrl ,lanes ),_mm512_set1_epi8 (3 )); 159} 160 161/// 2-bit unpack WITHOUT VPMULTISHIFTQB (the one VBMI op): byte for byte the multishift's result - output byte j 162/// (code j) is (u16[j/8] >> 2*(j%8)) & 3 - for a CPU with AVX-512 VNNI (dpbusd) but no VBMI (Cascade Lake Xeon; 163/// these used to fall back to the whole AVX-2 kernel). Four vectors of 16 codes (the u16 pairs 2R and 2R+1), each 164/// a VPERMW source-select + VPSRLVD bit-position shift + mask, truncated to bytes and concatenated in order. ~8 165/// more instructions per 64 codes: a part of the block's work. 166template < int R > 167inline __m128i unpack_round (const __m512i words ,const __m512i shift ,const __m512i three ) { 168const __m256i src = _mm256_permutexvar_epi16 (// code j/8's u16 for j = 16R..16R+15 169_mm256_setr_epi16 ((int16_t ) (2 * R ), (int16_t ) (2 * R ), (int16_t ) (2 * R ), (int16_t ) (2 * R ), 170 (int16_t ) (2 * R ), (int16_t ) (2 * R ), (int16_t ) (2 * R ), (int16_t ) (2 * R ), 171 (int16_t ) (2 * R + 1 ), (int16_t ) (2 * R + 1 ), (int16_t ) (2 * R + 1 ), 172 (int16_t ) (2 * R + 1 ), (int16_t ) (2 * R + 1 ), (int16_t ) (2 * R + 1 ), 173 (int16_t ) (2 * R + 1 ), (int16_t ) (2 * R + 1 )), 174_mm512_castsi512_si256 (words ));// the 16 source words 175const __m512i codes_d = _mm512_and_si512 (// 16 codes, shifted their bit 176_mm512_srlv_epi32 (_mm512_cvtepu16_epi32 (src ),shift ),_mm512_set1_epi8 (3 )); 177return _mm512_cvtepi32_epi8 (codes_d );// 16 dwords -> 16 bytes (VL truncate) 178} 179 180inline __m512i unpack64_q2_0_sw (const uint8_t * codes ) { 181const __m512i words = _mm512_inserti32x4 (_mm512_setzero_si512 (),// 8 u16, the rest zero 182_mm_loadu_si128 ((const __m128i * )codes ),0 ); 183const __m512i shift = _mm512_setr_epi32 (0 ,2 ,4 ,6 ,8 ,10 ,12 ,14 ,0 ,2 ,4 ,6 ,8 ,10 ,12 ,14 ); 184const __m512i three = _mm512_set1_epi8 (3 ); 185return _mm512_inserti32x4 ( 186_mm512_inserti32x4 (_mm512_inserti32x4 (_mm512_inserti32x4 (_mm512_setzero_si512 (), 187unpack_round < 0 > (words ,shift ,three ),0 ), 188unpack_round < 1 > (words ,shift ,three ),1 ), 189unpack_round < 2 > (words ,shift ,three ),2 ), 190unpack_round < 3 > (words ,shift ,three ),3 ); 191} 192 193inline __m512i unpack64_q2_0 (const uint8_t * codes ) { 194static const bool vbmi = cpu_vbmi_ok ();// VPMULTISHIFTQB, or the substitute (bit-shifting) one here 195return vbmi ?unpack64_q2_0_ms (codes ) :unpack64_q2_0_sw (codes ); 196} 197 198/// STRATA_CPU_YMM=1 keeps the 256-bit rows (whose unpack keeps the multishift): a machine with VNNI but no VBMI 199/// takes the zmm rows (the substitute unpack above), and anything older takes the AVX-2 kernel (expert_layout.cpp's 200/// dispatch). So one value answers "can this engine's 512-bit q2 path run at all". 201// For blocks [b0, b0+nb) (nb <= 8): p[2i+h] = d_{b0+i} * xscale[2(b0+i)+h], dd[2i+h] = d_{b0+i}. 202inline void scales8 (const uint8_t * wscales ,const ActQ & a ,int b0 ,int nb ,__m512 & p ,__m512 & dd ) { 203const __mmask8 m8 = nb >=8 ? (__mmask8 )0xFF : (__mmask8 ) ((1u <<nb )- 1u ); 204const __m128i h = _mm_maskz_loadu_epi16 (m8 ,wscales + 2 * b0 ); 205const __m512 d8 = _mm512_castps256_ps512 (_mm256_cvtph_ps (h )); 206const __m512i dup = _mm512_setr_epi32 (0 ,0 ,1 ,1 ,2 ,2 ,3 ,3 ,4 ,4 ,5 ,5 ,6 ,6 ,7 ,7 ); 207dd = _mm512_permutexvar_ps (dup ,d8 ); 208const __mmask16 m16 = nb >=8 ? (__mmask16 )0xFFFF : (__mmask16 ) ((1u << (2 * nb ))- 1u ); 209dd = _mm512_maskz_mov_ps (m16 ,dd ); 210p = _mm512_mul_ps (dd ,_mm512_maskz_loadu_ps (m16 ,a .scale + 2 * b0 )); 211} 212 213inline float row_dot_z (const uint8_t * codes ,const uint8_t * scales ,const ActQ & a ,int nblocks ) { 214__m512 acc = _mm512_setzero_ps (),corr = _mm512_setzero_ps (); 215const __m512i base = _mm512_setr_epi32 (0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ); 216for (int b0 = 0 ;b0 < nblocks ;b0 += 8 ) { 217const int nb = nblocks - b0 < 8 ?nblocks - b0 :8 ; 218__m512 p ,dd ; 219scales8 (scales ,a ,b0 ,nb ,p ,dd ); 220const __mmask16 m16 = nb >=8 ? (__mmask16 )0xFFFF : (__mmask16 ) ((1u << (2 * nb ))- 1u ); 221corr = _mm512_fmadd_ps (dd ,_mm512_maskz_loadu_ps (m16 ,a .hx + 2 * b0 ),corr ); 222for (int i = 0 ;i < nb ;++ i ) { 223const int b = b0 + i ; 224const __m512i dot = _mm512_dpbusd_epi32 (_mm512_setzero_si512 (),unpack64_q2_0 (codes + b * 16 ), 225_mm512_load_si512 ((const void * ) (a .q + b * QK ))); 226const __m512 sv = _mm512_permutexvar_ps (_mm512_add_epi32 (base ,_mm512_set1_epi32 (2 * i )),p ); 227acc = _mm512_fmadd_ps (sv ,_mm512_cvtepi32_ps (dot ),acc ); 228 } 229 } 230return _mm512_reduce_add_ps (acc )- _mm512_reduce_add_ps (corr ); 231} 232 233template < int NT > 234inline void row_dot_multi_z (const uint8_t * codes ,const uint8_t * scales ,const ActQ * const * a ,int nblocks , 235float * res ) { 236__m512 acc [NT ],corr [NT ]; 237for (int t = 0 ;t < NT ;++ t ) {acc [t ]= _mm512_setzero_ps ();corr [t ]= _mm512_setzero_ps (); } 238const __m512i base = _mm512_setr_epi32 (0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ); 239for (int b0 = 0 ;b0 < nblocks ;b0 += 8 ) { 240const int nb = nblocks - b0 < 8 ?nblocks - b0 :8 ; 241const __mmask16 m16 = nb >=8 ? (__mmask16 )0xFFFF : (__mmask16 ) ((1u << (2 * nb ))- 1u ); 242__m512 p [NT ]; 243for (int t = 0 ;t < NT ;++ t ) { 244__m512 dd ; 245scales8 (scales ,* a [t ],b0 ,nb ,p [t ],dd ); 246corr [t ]= _mm512_fmadd_ps (dd ,_mm512_maskz_loadu_ps (m16 ,a [t ]-> hx + 2 * b0 ),corr [t ]); 247 } 248for (int i = 0 ;i < nb ;++ i ) { 249const int b = b0 + i ; 250const __m512i w = unpack64_q2_0 (codes + b * 16 ); 251const __m512i idx = _mm512_add_epi32 (base ,_mm512_set1_epi32 (2 * i )); 252for (int t = 0 ;t < NT ;++ t ) { 253const __m512i dot = _mm512_dpbusd_epi32 (_mm512_setzero_si512 (),w , 254_mm512_load_si512 ((const void * ) (a [t ]-> q + b * QK ))); 255acc [t ]= _mm512_fmadd_ps (_mm512_permutexvar_ps (idx ,p [t ]),_mm512_cvtepi32_ps (dot ),acc [t ]); 256 } 257 } 258 } 259for (int t = 0 ;t < NT ;++ t )res [t ]= _mm512_reduce_add_ps (acc [t ])- _mm512_reduce_add_ps (corr [t ]); 260} 261 262/// One weight row against a quantized activation. 263/// 264/// sum_j (c_j - 1) d_w xhat_j d_x == d_w * ( d_x*sum(c*xhat) - d_x*sum(xhat) ) 265/// 266/// split per 32-chunk because `d_x` changes at the chunk boundary while `d_w` does not. 267/// 268/// The accumulator stays a FLOAT VECTOR for the whole row and is reduced once at the end. Reducing per 269/// 64-weight block (two 8-lane horizontal sums: a store plus 16 scalar adds) cost far more than the dot 270/// products themselves - it made the kernel compute-bound at 21 GB/s instead of DRAM-bound at 32. 271inline float row_dot (const uint8_t * codes ,const uint8_t * scales ,const ActQ & a ,int nblocks ) { 272if (kZmm )return row_dot_z (codes ,scales ,a ,nblocks ); 273__m256 acc = _mm256_setzero_ps (); 274// The -sum(xhat) term is a SCALAR: broadcasting it into all 8 lanes and letting hsum_ps add them would 275// apply it eight times per block. 276float corr = 0.f ; 277for (int b = 0 ;b < nblocks ;++ b ) { 278const float d = h2f (scales + 2 * b ); 279const __m256 slo = _mm256_cvtepi32_ps (block_dot (codes + b * 16 ,a .q + b * QK )); 280const __m256 shi = _mm256_cvtepi32_ps (block_dot (codes + b * 16 + 8 ,a .q + b * QK + QKA )); 281acc = _mm256_fmadd_ps (_mm256_set1_ps (d * a .scale [2 * b ]),slo ,acc ); 282acc = _mm256_fmadd_ps (_mm256_set1_ps (d * a .scale [2 * b + 1 ]),shi ,acc ); 283corr += d * (a .hx [2 * b ]+ a .hx [2 * b + 1 ]); 284 } 285return hsum_ps (acc )- corr ; 286} 287 288// VNNI's integer partial sums are exact. Remove the Q2_0 code offset BEFORE 289// conversion to float, then follow the pinned generic CPU dot's two-chunk and 290// per-64-block reduction. Its x86 type trait selects this generic reduction even 291// in the AVX-512 oracle build. The legacy eight-lane FP32 reduction above has a 292// different rounding order and remains the default. 293inline int chunk_dot_oracle (const uint8_t * codes ,const int8_t * q ,int sum ) { 294const __m256i lanes = block_dot (codes ,q ); 295const __m128i halves = _mm_add_epi32 (_mm256_castsi256_si128 (lanes ),_mm256_extracti128_si256 (lanes ,1 )); 296const __m128i pairs = _mm_hadd_epi32 (halves ,halves ); 297return _mm_cvtsi128_si32 (_mm_hadd_epi32 (pairs ,pairs ))- sum ; 298} 299 300inline float row_dot_oracle (const uint8_t * codes ,const uint8_t * scales ,const ActQ & a ,int nblocks ) { 301float result = 0.0f ; 302for (int b = 0 ;b < nblocks ;++ b ) { 303float block = 0.0f ; 304for (int half = 0 ;half < 2 ;++ half ) { 305const int chunk = 2 * b + half ; 306const int dot = chunk_dot_oracle (codes + b * 16 + half * 8 ,a .q + chunk * QKA ,a .sum [chunk ]); 307block += a .scale [chunk ]* float (dot ); 308 } 309result += h2f (scales + 2 * b )* block ; 310 } 311return result ; 312} 313 314/// `row_dot` for NT activations at once: the codes of each block are unpacked once, and each token's 315/// accumulator sees exactly the operations `row_dot` would apply to it, in the same order. 316template < int NT > 317inline void row_dot_multi (const uint8_t * codes ,const uint8_t * scales ,const ActQ * const * a ,int nblocks , 318float * res ) { 319if (kZmm ) {row_dot_multi_z < NT > (codes ,scales ,a ,nblocks ,res );return ; } 320__m256 acc [NT ]; 321float corr [NT ]; 322for (int t = 0 ;t < NT ;++ t ) {acc [t ]= _mm256_setzero_ps ();corr [t ]= 0.f ; } 323for (int b = 0 ;b < nblocks ;++ b ) { 324const float d = h2f (scales + 2 * b ); 325const __m256i lo = unpack_q2_0 (codes + b * 16 ); 326const __m256i hi = unpack_q2_0 (codes + b * 16 + 8 ); 327for (int t = 0 ;t < NT ;++ t ) { 328const __m256 slo = _mm256_cvtepi32_ps ( 329_mm256_dpbusd_epi32 (_mm256_setzero_si256 (),lo ,_mm256_load_si256 ((const __m256i * ) (a [t ]-> q + b * QK )))); 330const __m256 shi = _mm256_cvtepi32_ps ( 331_mm256_dpbusd_epi32 (_mm256_setzero_si256 (),hi , 332_mm256_load_si256 ((const __m256i * ) (a [t ]-> q + b * QK + QKA )))); 333acc [t ]= _mm256_fmadd_ps (_mm256_set1_ps (d * a [t ]-> scale [2 * b ]),slo ,acc [t ]); 334acc [t ]= _mm256_fmadd_ps (_mm256_set1_ps (d * a [t ]-> scale [2 * b + 1 ]),shi ,acc [t ]); 335corr [t ]+= d * (a [t ]-> hx [2 * b ]+ a [t ]-> hx [2 * b + 1 ]); 336 } 337 } 338for (int t = 0 ;t < NT ;++ t )res [t ]= hsum_ps (acc [t ])- corr [t ]; 339} 340 341template < int NT > 342void expert_multi (const uint8_t * blob ,const ActQ * const * a1 ,float * const * out ,ExpertScratchMulti & ws ) { 343float g [NT ],u [NT ]; 344for (int r = 0 ;r < FF ;++ r ) { 345row_dot_multi < NT > (blob + O_GU_CODES + (size_t ) (2 * r )* ROW_GU , 346blob + O_GU_SCALES + (size_t ) (2 * r )* SC_GU * 2 ,a1 ,SC_GU ,g ); 347row_dot_multi < NT > (blob + O_GU_CODES + (size_t ) (2 * r + 1 )* ROW_GU , 348blob + O_GU_SCALES + (size_t ) (2 * r + 1 )* SC_GU * 2 ,a1 ,SC_GU ,u ); 349for (int t = 0 ;t < NT ;++ t )ws .ff [t ][r ]= (g [t ] / (1.f + std::exp (- g [t ])))* u [t ]; 350 } 351const ActQ * a2 [NT ]; 352for (int t = 0 ;t < NT ;++ t ) { 353act_quant_q8_1 (ws .ff [t ],FF ,ws .a2 [t ]); 354a2 [t ]= & ws .a2 [t ]; 355 } 356float o [NT ]; 357for (int r = 0 ;r < H ;++ r ) { 358row_dot_multi < NT > (blob + O_D_CODES + (size_t )r * ROW_D ,blob + O_D_SCALES + (size_t )r * SC_D * 2 ,a2 , 359SC_D ,o ); 360for (int t = 0 ;t < NT ;++ t )out [t ][r ]= o [t ]; 361 } 362} 363 364void expert_oracle_q8_0 (const uint8_t * blob ,const ActQ & a1 ,float * out ,ExpertScratch & ws ) { 365for (int r = 0 ;r < FF ;++ r ) { 366const float g = row_dot_oracle (blob + O_GU_CODES + size_t (2 * r )* ROW_GU , 367blob + O_GU_SCALES + size_t (2 * r )* SC_GU * 2 ,a1 ,SC_GU ); 368const float u = row_dot_oracle (blob + O_GU_CODES + size_t (2 * r + 1 )* ROW_GU , 369blob + O_GU_SCALES + size_t (2 * r + 1 )* SC_GU * 2 ,a1 ,SC_GU ); 370ws .ff [r ]= (g / (1.f + std::exp (- g )))* u ; 371 } 372quantize_oracle_q8_0 (ws .ff ,FF ,ws .a2 ); 373for (int r = 0 ;r < H ;++ r ) 374out [r ]= row_dot_oracle (blob + O_D_CODES + size_t (r )* ROW_D , 375blob + O_D_SCALES + size_t (r )* SC_D * 2 ,ws .a2 ,SC_D ); 376} 377 378bool q2_rows_512_ok () { 379return kZmm && cpu_vnni_ok (); 380} 381}// namespace 382 383// CpuFeatures::reason, cpu_features, cpu_require_expert_support and the oracle flag live in expert_layout.cpp: this 384// file is compiled for AVX-512, and the code that finds out whether the CPU has AVX-512 must not be in it (#795). 385void act_quant_q8_1 (const float * x ,int n ,ActQ & a ) { 386if (expert_oracle_q8_0_enabled ()) { 387quantize_oracle_q8_0 (x ,n ,a ); 388return ; 389 } 390a .nchunks = n /QKA ; 391// Plan v0.3 P6: AVX-512, the same operations per element as the scalar loop below (max of |x|, one multiply, 392// +-0.5 away from zero, truncation, clamp), so the result is bitwise the scalar one. The scalar loop took 393// ~22 us per 2560 values - 3.2 ms of every speculative round. 394 { 395const __m512 half = _mm512_set1_ps (0.5f ),mhalf = _mm512_set1_ps (-0.5f ),zero = _mm512_setzero_ps (); 396const __m512i lo = _mm512_set1_epi32 (-127 ),hi = _mm512_set1_epi32 (127 ); 397const __m512 absmask = _mm512_castsi512_ps (_mm512_set1_epi32 (0x7fffffff )); 398for (int k = 0 ;k < a .nchunks ;++ k ) { 399const float * xb = x + k * QKA ; 400const __m512 x0 = _mm512_loadu_ps (xb ),x1 = _mm512_loadu_ps (xb + 16 ); 401const float amax = _mm512_reduce_max_ps (_mm512_max_ps (_mm512_and_ps (x0 ,absmask ),_mm512_and_ps (x1 ,absmask ))); 402const float s = amax > 0.f ?amax /127.f :0.f ; 403const float inv = s > 0.f ?1.f /s :0.f ; 404const __m512 vinv = _mm512_set1_ps (inv ); 405const __m512 t0 = _mm512_mul_ps (x0 ,vinv ),t1 = _mm512_mul_ps (x1 ,vinv ); 406const __m512 r0 = _mm512_add_ps (t0 ,_mm512_mask_blend_ps (_mm512_cmp_ps_mask (t0 ,zero ,_CMP_GE_OQ ),mhalf ,half )); 407const __m512 r1 = _mm512_add_ps (t1 ,_mm512_mask_blend_ps (_mm512_cmp_ps_mask (t1 ,zero ,_CMP_GE_OQ ),mhalf ,half )); 408__m512i v0 = _mm512_cvttps_epi32 (r0 ),v1 = _mm512_cvttps_epi32 (r1 ); 409v0 = _mm512_min_epi32 (_mm512_max_epi32 (v0 ,lo ),hi ); 410v1 = _mm512_min_epi32 (_mm512_max_epi32 (v1 ,lo ),hi ); 411_mm_storeu_si128 ((__m128i * ) (a .q + k * QKA ),_mm512_cvtepi32_epi8 (v0 )); 412_mm_storeu_si128 ((__m128i * ) (a .q + k * QKA + 16 ),_mm512_cvtepi32_epi8 (v1 )); 413const int32_t sum = _mm512_reduce_add_epi32 (_mm512_add_epi32 (v0 ,v1 )); 414a .scale [k ]= s ; 415a .sum [k ]= sum ; 416a .hx [k ]= s * (float )sum ; 417 } 418return ; 419 } 420for (int k = 0 ;k < a .nchunks ;++ k ) { 421const float * xb = x + k * QKA ; 422float amax = 0.f ; 423for (int j = 0 ;j < QKA ;++ j )amax = std::fmax (amax , std::fabs (xb [j ])); 424const float s = amax > 0.f ?amax /127.f :0.f ; 425const float inv = s > 0.f ?1.f /s :0.f ; 426int32_t sum = 0 ; 427int8_t * q = a .q + k * QKA ; 428for (int j = 0 ;j < QKA ;++ j ) { 429// **`std::lround` IS A FUNCTION CALL AND IT COST 51 us PER LAYER.** Measured: quantizing 2560 430// floats took 51.3 us - 20 ns per element, about 60 cycles for a fabs, a multiply and a round. 431// `lround` respects the current rounding mode, so MSVC cannot inline it to a single instruction 432// and emits a call per element. 48 layers x 51.3 us = 2.46 ms/token, which is 8.6% of the whole 433// CPU expert term and is pure overhead. 434// 435// `t + copysign(0.5, t)` is EXACTLY `lround`'s rule - round half AWAY FROM ZERO - and it is 436// branchless and vectorizable. It is NOT `_mm256_round_ps`, which rounds half to EVEN and would 437// quietly change the activation on the ties. The cast is safe because `|t| <= 127` by construction 438// (`s = amax/127`, so `|x_j|/s <= 127`), well inside int32. 439const float t = xb [j ]* inv ; 440const float r = t + (t >=0.f ?0.5f :-0.5f ); 441int v = (int )r ; 442v = v < -127 ?-127 : (v > 127 ?127 :v ); 443q [j ]= (int8_t )v ; 444sum += v ; 445 } 446a .scale [k ]= s ; 447a .sum [k ]= sum ; 448a .hx [k ]= s * (float )sum ; 449 } 450} 451 452void s2_expert_vnni (const uint8_t * blob ,const float * x ,float * out ,ExpertScratch & ws ) { 453act_quant_q8_1 (x ,H ,ws .a1 ); 454s2_expert_vnni_q (blob ,ws .a1 ,out ,ws ); 455} 456 457void s2_expert_vnni_q (const uint8_t * blob ,const ActQ & a1 ,float * out ,ExpertScratch & ws ) { 458if (expert_oracle_q8_0_enabled ()) { 459expert_oracle_q8_0 (blob ,a1 ,out ,ws ); 460return ; 461 } 462for (int r = 0 ;r < FF ;++ r ) { 463const float g = row_dot (blob + O_GU_CODES + (size_t ) (2 * r )* ROW_GU , 464blob + O_GU_SCALES + (size_t ) (2 * r )* SC_GU * 2 ,a1 ,SC_GU ); 465const float u = row_dot (blob + O_GU_CODES + (size_t ) (2 * r + 1 )* ROW_GU , 466blob + O_GU_SCALES + (size_t ) (2 * r + 1 )* SC_GU * 2 ,a1 ,SC_GU ); 467// SiLU on the GATE, multiplied by up - the same reading `docs/semantics.md` records for the shared 468// expert, and the one that is wrong the other way round in a way that still produces a number. 469ws .ff [r ]= (g / (1.f + std::exp (- g )))* u ; 470 } 471act_quant_q8_1 (ws .ff ,FF ,ws .a2 ); 472for (int r = 0 ;r < H ;++ r ) 473out [r ]= row_dot (blob + O_D_CODES + (size_t )r * ROW_D , 474blob + O_D_SCALES + (size_t )r * SC_D * 2 ,ws .a2 ,SC_D ); 475} 476 477 478void s2_expert_gu_rows (const uint8_t * blob ,const ActQ & a1 ,float * ff ,int r0 ,int r1 ) { 479for (int r = r0 ;r < r1 ;++ r ) { 480const float g = row_dot (blob + O_GU_CODES + (size_t ) (2 * r )* ROW_GU , 481blob + O_GU_SCALES + (size_t ) (2 * r )* SC_GU * 2 ,a1 ,SC_GU ); 482const float u = row_dot (blob + O_GU_CODES + (size_t ) (2 * r + 1 )* ROW_GU , 483blob + O_GU_SCALES + (size_t ) (2 * r + 1 )* SC_GU * 2 ,a1 ,SC_GU ); 484ff [r ]= (g / (1.f + std::exp (- g )))* u ; 485 } 486} 487 488void s2_expert_down_rows (const uint8_t * blob ,const ActQ & a2 ,float * out ,int r0 ,int r1 ) { 489for (int r = r0 ;r < r1 ;++ r ) 490out [r ]= row_dot (blob + O_D_CODES + (size_t )r * ROW_D ,blob + O_D_SCALES + (size_t )r * SC_D * 2 ,a2 ,SC_D ); 491} 492 493namespace { 494template < int NT > 495void gu_rows_multi (const uint8_t * blob ,const ActQ * const * a1 ,float * const * ff ,int r0 ,int r1 ) { 496float g [NT ],u [NT ]; 497for (int r = r0 ;r < r1 ;++ r ) { 498row_dot_multi < NT > (blob + O_GU_CODES + (size_t ) (2 * r )* ROW_GU , 499blob + O_GU_SCALES + (size_t ) (2 * r )* SC_GU * 2 ,a1 ,SC_GU ,g ); 500row_dot_multi < NT > (blob + O_GU_CODES + (size_t ) (2 * r + 1 )* ROW_GU , 501blob + O_GU_SCALES + (size_t ) (2 * r + 1 )* SC_GU * 2 ,a1 ,SC_GU ,u ); 502for (int t = 0 ;t < NT ;++ t )ff [t ][r ]= (g [t ] / (1.f + std::exp (- g [t ])))* u [t ]; 503 } 504} 505template < int NT > 506void down_rows_multi (const uint8_t * blob ,const ActQ * const * a2 ,float * const * out ,int r0 ,int r1 ) { 507float o [NT ]; 508for (int r = r0 ;r < r1 ;++ r ) { 509row_dot_multi < NT > (blob + O_D_CODES + (size_t )r * ROW_D ,blob + O_D_SCALES + (size_t )r * SC_D * 2 ,a2 , 510SC_D ,o ); 511for (int t = 0 ;t < NT ;++ t )out [t ][r ]= o [t ]; 512 } 513} 514}// namespace 515 516void s2_expert_gu_rows_multi (const uint8_t * blob ,const ActQ * const * a1 ,int n_tokens ,float * const * ff ,int r0 , 517int r1 ) { 518switch (n_tokens ) { 519case 1 :gu_rows_multi < 1 > (blob ,a1 ,ff ,r0 ,r1 );break ; 520case 2 :gu_rows_multi < 2 > (blob ,a1 ,ff ,r0 ,r1 );break ; 521case 3 :gu_rows_multi < 3 > (blob ,a1 ,ff ,r0 ,r1 );break ; 522case 4 :gu_rows_multi < 4 > (blob ,a1 ,ff ,r0 ,r1 );break ; 523case 5 :gu_rows_multi < 5 > (blob ,a1 ,ff ,r0 ,r1 );break ; 524case 6 :gu_rows_multi < 6 > (blob ,a1 ,ff ,r0 ,r1 );break ; 525case 7 :gu_rows_multi < 7 > (blob ,a1 ,ff ,r0 ,r1 );break ; 526default :gu_rows_multi < 8 > (blob ,a1 ,ff ,r0 ,r1 );break ; 527 } 528} 529 530void s2_expert_down_rows_multi (const uint8_t * blob ,const ActQ * const * a2 ,int n_tokens ,float * const * out ,int r0 , 531int r1 ) { 532switch (n_tokens ) { 533case 1 :down_rows_multi < 1 > (blob ,a2 ,out ,r0 ,r1 );break ; 534case 2 :down_rows_multi < 2 > (blob ,a2 ,out ,r0 ,r1 );break ; 535case 3 :down_rows_multi < 3 > (blob ,a2 ,out ,r0 ,r1 );break ; 536case 4 :down_rows_multi < 4 > (blob ,a2 ,out ,r0 ,r1 );break ; 537case 5 :down_rows_multi < 5 > (blob ,a2 ,out ,r0 ,r1 );break ; 538case 6 :down_rows_multi < 6 > (blob ,a2 ,out ,r0 ,r1 );break ; 539case 7 :down_rows_multi < 7 > (blob ,a2 ,out ,r0 ,r1 );break ; 540default :down_rows_multi < 8 > (blob ,a2 ,out ,r0 ,r1 );break ; 541 } 542} 543 544// ================================ plan v0.3 P6: Q2_0 rows in the GGUF block layout ================================ 545// 546// The IQ model files keep their down projections in Q2_0 GGUF blocks (fp16 d, then 16 code bytes: 18 bytes per 547// 64 weights, interleaved), which ggml-cpu computes with a scalar loop on x86. This is `row_dot_multi_z` with 548// the block stride of the GGUF layout: the same unpack, the same VNNI dot, the same correction. 549namespace { 550template < int NT > 551inline void q2g_row_multi (const uint8_t * row ,const ActQ * const * a ,int nblocks ,float * res ) { 552__m512 acc [NT ],corr [NT ]; 553for (int t = 0 ;t < NT ;++ t ) {acc [t ]= _mm512_setzero_ps ();corr [t ]= _mm512_setzero_ps (); } 554const __m512i base = _mm512_setr_epi32 (0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ); 555const __m512i dup = _mm512_setr_epi32 (0 ,0 ,1 ,1 ,2 ,2 ,3 ,3 ,4 ,4 ,5 ,5 ,6 ,6 ,7 ,7 ); 556for (int b0 = 0 ;b0 < nblocks ;b0 += 8 ) { 557const int nb = nblocks - b0 < 8 ?nblocks - b0 :8 ; 558const __mmask16 m16 = nb >=8 ? (__mmask16 )0xFFFF : (__mmask16 ) ((1u << (2 * nb ))- 1u ); 559 alignas(16 )uint16_t sc [8 ]= {0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 }; 560for (int i = 0 ;i < nb ;++ i ) std::memcpy (& sc [i ],row + (size_t ) (b0 + i )* 18 ,2 ); 561const __m512 d8 = _mm512_castps256_ps512 (_mm256_cvtph_ps (_mm_load_si128 ((const __m128i * )sc ))); 562const __m512 dd = _mm512_maskz_mov_ps (m16 ,_mm512_permutexvar_ps (dup ,d8 )); 563__m512 p [NT ]; 564for (int t = 0 ;t < NT ;++ t ) { 565p [t ]= _mm512_mul_ps (dd ,_mm512_maskz_loadu_ps (m16 ,a [t ]-> scale + 2 * b0 )); 566corr [t ]= _mm512_fmadd_ps (dd ,_mm512_maskz_loadu_ps (m16 ,a [t ]-> hx + 2 * b0 ),corr [t ]); 567 } 568for (int i = 0 ;i < nb ;++ i ) { 569const int b = b0 + i ; 570const __m512i w = unpack64_q2_0 (row + (size_t )b * 18 + 2 ); 571const __m512i idx = _mm512_add_epi32 (base ,_mm512_set1_epi32 (2 * i )); 572for (int t = 0 ;t < NT ;++ t ) { 573const __m512i dot = _mm512_dpbusd_epi32 (_mm512_setzero_si512 (),w , 574_mm512_load_si512 ((const void * ) (a [t ]-> q + b * QK ))); 575acc [t ]= _mm512_fmadd_ps (_mm512_permutexvar_ps (idx ,p [t ]),_mm512_cvtepi32_ps (dot ),acc [t ]); 576 } 577 } 578 } 579for (int t = 0 ;t < NT ;++ t )res [t ]= _mm512_reduce_add_ps (acc [t ])- _mm512_reduce_add_ps (corr [t ]); 580} 581template < int NT > 582void q2g_rows (const uint8_t * w ,size_t row_bytes ,int nblocks ,const ActQ * const * a ,float * const * out ,int r0 ,int r1 ) { 583float res [NT ]; 584for (int r = r0 ;r < r1 ;++ r ) { 585q2g_row_multi < NT > (w + (size_t )r * row_bytes ,a ,nblocks ,res ); 586for (int t = 0 ;t < NT ;++ t )out [t ][r ]= res [t ]; 587 } 588} 589}// namespace 590 591void q2_0_gguf_rows_multi (const uint8_t * w ,size_t row_bytes ,int nblocks ,const ActQ * const * a ,int nt , 592float * const * out ,int r0 ,int r1 ) { 593switch (nt ) { 594case 1 :q2g_rows < 1 > (w ,row_bytes ,nblocks ,a ,out ,r0 ,r1 );break ; 595case 2 :q2g_rows < 2 > (w ,row_bytes ,nblocks ,a ,out ,r0 ,r1 );break ; 596case 3 :q2g_rows < 3 > (w ,row_bytes ,nblocks ,a ,out ,r0 ,r1 );break ; 597case 4 :q2g_rows < 4 > (w ,row_bytes ,nblocks ,a ,out ,r0 ,r1 );break ; 598case 5 :q2g_rows < 5 > (w ,row_bytes ,nblocks ,a ,out ,r0 ,r1 );break ; 599case 6 :q2g_rows < 6 > (w ,row_bytes ,nblocks ,a ,out ,r0 ,r1 );break ; 600case 7 :q2g_rows < 7 > (w ,row_bytes ,nblocks ,a ,out ,r0 ,r1 );break ; 601default :q2g_rows < 8 > (w ,row_bytes ,nblocks ,a ,out ,r0 ,r1 );break ; 602 } 603} 604 605void s2_expert_vnni_multi (const uint8_t * blob ,const ActQ * const * a1 ,int n_tokens ,float * const * out , 606ExpertScratchMulti & ws ) { 607if (expert_oracle_q8_0_enabled ()|| n_tokens < 1 || n_tokens > MAXT ) { 608for (int t = 0 ;t < n_tokens ;++ t )s2_expert_vnni_q (blob ,* a1 [t ],out [t ],ws .single ); 609return ; 610 } 611switch (n_tokens ) { 612case 1 :expert_multi < 1 > (blob ,a1 ,out ,ws );break ; 613case 2 :expert_multi < 2 > (blob ,a1 ,out ,ws );break ; 614case 3 :expert_multi < 3 > (blob ,a1 ,out ,ws );break ; 615case 4 :expert_multi < 4 > (blob ,a1 ,out ,ws );break ; 616case 5 :expert_multi < 5 > (blob ,a1 ,out ,ws );break ; 617case 6 :expert_multi < 6 > (blob ,a1 ,out ,ws );break ; 618case 7 :expert_multi < 7 > (blob ,a1 ,out ,ws );break ; 619default :expert_multi < 8 > (blob ,a1 ,out ,ws );break ; 620 } 621} 622 623void s2_expert_scalar (const uint8_t * blob ,const float * x_in ,float * out ,bool quant_acts ) { 624// BOTH STAGES, which is what `quant_acts` promises and what `bench/micro/cpu_s2.cpp` does NOT do. 625// 626// The original's comment says the oracle "consume[s] the SAME INT8 activation values the VNNI path uses, 627// at both stages", but its code quantizes only the INTERMEDIATE - the gate/up projections still see raw 628// f32 `x`. Feeding it an already-quantized input (which is what the engine does) makes the two coincide 629// and hides the discrepancy entirely; feeding it a raw f32 input makes the comparison one between two 630// DIFFERENT computations, and the gap measured here was 1.19e-02 - three times P2.S3's tolerance, and 631// read as a kernel bug when it was a fixture bug. 632float xq [H ]; 633const float * x = x_in ; 634if (quant_acts ) { 635ActQ a1 ; 636act_quant_q8_1 (x_in ,H ,a1 ); 637for (int i = 0 ;i < H ;++ i )xq [i ]= a1 .scale [i /QKA ]* (float )a1 .q [i ]; 638x = xq ; 639 } 640float ff [FF ]; 641for (int r = 0 ;r < FF ;++ r ) { 642const uint8_t * gc = blob + O_GU_CODES + (size_t ) (2 * r )* ROW_GU ; 643const uint8_t * gs = blob + O_GU_SCALES + (size_t ) (2 * r )* SC_GU * 2 ; 644const uint8_t * uc = blob + O_GU_CODES + (size_t ) (2 * r + 1 )* ROW_GU ; 645const uint8_t * us = blob + O_GU_SCALES + (size_t ) (2 * r + 1 )* SC_GU * 2 ; 646float sg = 0.f ,su = 0.f ; 647for (int b = 0 ;b < SC_GU ;++ b ) { 648const float dg = h2f (gs + 2 * b ),du = h2f (us + 2 * b ); 649for (int j = 0 ;j < QK ;++ j ) { 650const int o = b * QK + j ; 651sg += (float ) (((gc [b * 16 + (j >>2 )] >> (2 * (j & 3 )))& 3 )- 1 )* dg * x [o ]; 652su += (float ) (((uc [b * 16 + (j >>2 )] >> (2 * (j & 3 )))& 3 )- 1 )* du * x [o ]; 653 } 654 } 655ff [r ]= (sg / (1.f + std::exp (- sg )))* su ; 656 } 657if (quant_acts ) { 658// Replace the exact intermediate with the INT8 values the VNNI path actually sees, so the two differ 659// only by FP32 evaluation order. 660ActQ a2 ; 661act_quant_q8_1 (ff ,FF ,a2 ); 662for (int i = 0 ;i < FF ;++ i )ff [i ]= a2 .scale [i /QKA ]* (float )a2 .q [i ]; 663 } 664for (int r = 0 ;r < H ;++ r ) { 665const uint8_t * dc = blob + O_D_CODES + (size_t )r * ROW_D ; 666const uint8_t * ds = blob + O_D_SCALES + (size_t )r * SC_D * 2 ; 667float acc = 0.f ; 668for (int b = 0 ;b < SC_D ;++ b ) { 669const float d = h2f (ds + 2 * b ); 670for (int j = 0 ;j < QK ;++ j ) 671acc += (float ) (((dc [b * 16 + (j >>2 )] >> (2 * (j & 3 )))& 3 )- 1 )* d * ff [b * QK + j ]; 672 } 673out [r ]= acc ; 674 } 675} 676 677bool q2_rows_512_ok () { 678return kZmm && cpu_vnni_ok (); 679} 680 681}// namespace strata::kernels::cpu