okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
8ac8ce32e
main
1// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). 2// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file. 3// src/ds4/ds4_gguf_cpu.cpp - a GGUF's MXFP4 experts on the CPU lane (see ds4_gguf_cpu.hpp). 4#include "ds4_gguf_cpu.hpp" 5 6#include "strata/dsv41/exl3_cpu.hpp" 7 8#include <algorithm> 9#include <chrono> 10#include <cmath> 11#include <cstdio> 12#include <cstdlib> 13#include <cstring> 14#include <string> 15#include <vector> 16 17#if defined(__x86_64__ )|| defined(_M_X64 ) 18#define MX_X86 1 19#include <immintrin.h> 20#if defined(_MSC_VER ) 21#include <intrin.h> 22#else 23#include <cpuid.h> 24#endif 25#endif 26 27// a function's instruction set (GCC / Clang, clang-cl too; MSVC compiles any intrinsic as it is): the file is built for 28// the baseline x86-64, and each tier's code runs only where detect() says the CPU and the OS take it 29#if defined(MX_X86 )&& (defined(__GNUC__ )|| defined(__clang__ )) 30#define MX_TARGET (s ) __attribute__((target(s))) 31#else 32#define MX_TARGET (s ) 33#endif 34#define MX_AVX2 MX_TARGET("avx2,fma") 35// AVX-VNNI's intrinsics: GCC 11, Clang 12, MSVC 2022 36#if defined(MX_X86 )&& (defined(_MSC_VER )|| (defined(__clang__ )&& __clang_major__ >=12 )|| \ 37 (!defined(__clang__ )&& defined(__GNUC__ )&& __GNUC__ >=11 )) 38#define MX_AVXVNNI 1 39#endif 40 41namespace strata::ds4::gguf { 42namespace { 43 44constexpr int kBlock = 32 ,kBytes = 17 ; 45constexpr float kValues [16 ]= {0.0f ,1.0f ,2.0f ,3.0f ,4.0f ,6.0f ,8.0f ,12.0f , 460.0f ,-1.0f ,-2.0f ,-3.0f ,-4.0f ,-6.0f ,-8.0f ,-12.0f }; 47constexpr int kCodes [16 ]= {0 ,1 ,2 ,3 ,4 ,6 ,8 ,12 ,0 ,-1 ,-2 ,-3 ,-4 ,-6 ,-8 ,-12 }; 48 49float e8m0_half (uint32_t e ) {// 2^(e - 128), as the device's 50const uint32_t bits = e < 2 ?0x00200000u <<e : (e - 1 ) <<23 ; 51float f ; 52 std::memcpy (& f ,& bits ,4 ); 53return f ; 54} 55struct E8m0Table { 56float v [256 ]; 57E8m0Table () { 58for (int e = 0 ;e < 256 ;++ e )v [e ]= e8m0_half ((uint32_t )e ); 59 } 60}; 61const E8m0Table & e8 () { 62static const E8m0Table t ; 63return t ; 64} 65 66void rows_scalar (const uint8_t * w ,size_t rb ,int k ,int r0 ,int r1 ,const float * const * x ,int n ,float * const * y ) { 67for (int r = r0 ;r < r1 ;++ r ) { 68const uint8_t * p = w + (size_t )r * rb ; 69float acc [kMxCpuMaxN ]= {}; 70for (int b = 0 ;b < k /kBlock ;++ b ,p += kBytes ) { 71const float d = e8m0_half (p [0 ]); 72float wv [kBlock ]; 73for (int j = 0 ;j < 16 ;++ j ) { 74wv [j ]= kValues [p [1 + j ]& 15 ]* d ; 75wv [j + 16 ]= kValues [p [1 + j ] >>4 ]* d ; 76 } 77for (int i = 0 ;i < n ;++ i ) { 78const float * xb = x [i ]+ b * kBlock ; 79float s = 0.0f ; 80for (int j = 0 ;j < kBlock ;++ j )s += wv [j ]* xb [j ]; 81acc [i ]+= s ; 82 } 83 } 84for (int i = 0 ;i < n ;++ i )y [i ][r - r0 ]= acc [i ]; 85 } 86} 87 88#if defined(MX_X86 ) 89MX_AVX2 float hsum (__m256 v ) { 90const __m128 a = _mm_add_ps (_mm256_castps256_ps128 (v ),_mm256_extractf128_ps (v ,1 )); 91const __m128 b = _mm_add_ps (a ,_mm_movehl_ps (a ,a )); 92return _mm_cvtss_f32 (_mm_add_ss (b ,_mm_shuffle_ps (b ,b ,1 ))); 93} 94 95// a block: the 16 code bytes -> 32 int8 values through a shuffle table (low nibbles: values 0..15, high: 16..31), 96// widened to F32 in 4 x 8, times the block's scale (exact), FMAs against each activation 97MX_AVX2 void rows_avx2 (const uint8_t * w ,size_t rb ,int k ,int r0 ,int r1 ,const float * const * x ,int n , 98float * const * y ) { 99const __m128i lut = _mm_setr_epi8 (0 ,1 ,2 ,3 ,4 ,6 ,8 ,12 ,0 ,-1 ,-2 ,-3 ,-4 ,-6 ,-8 ,-12 ); 100const __m128i m4 = _mm_set1_epi8 (0x0f ); 101for (int r = r0 ;r < r1 ;++ r ) { 102const uint8_t * p = w + (size_t )r * rb ; 103__m256 acc [kMxCpuMaxN ]; 104for (int i = 0 ;i < n ;++ i )acc [i ]= _mm256_setzero_ps (); 105for (int b = 0 ;b < k /kBlock ;++ b ,p += kBytes ) { 106const __m256 d = _mm256_set1_ps (e8m0_half (p [0 ])); 107const __m128i q = _mm_loadu_si128 ((const __m128i * ) (p + 1 )); 108const __m128i lo = _mm_shuffle_epi8 (lut ,_mm_and_si128 (q ,m4 )); 109const __m128i hi = _mm_shuffle_epi8 (lut ,_mm_and_si128 (_mm_srli_epi16 (q ,4 ),m4 )); 110const __m256 w0 = _mm256_mul_ps (d ,_mm256_cvtepi32_ps (_mm256_cvtepi8_epi32 (lo ))); 111const __m256 w1 = _mm256_mul_ps (d ,_mm256_cvtepi32_ps (_mm256_cvtepi8_epi32 (_mm_srli_si128 (lo ,8 )))); 112const __m256 w2 = _mm256_mul_ps (d ,_mm256_cvtepi32_ps (_mm256_cvtepi8_epi32 (hi ))); 113const __m256 w3 = _mm256_mul_ps (d ,_mm256_cvtepi32_ps (_mm256_cvtepi8_epi32 (_mm_srli_si128 (hi ,8 )))); 114for (int i = 0 ;i < n ;++ i ) { 115const float * xb = x [i ]+ b * kBlock ; 116__m256 a = acc [i ]; 117a = _mm256_fmadd_ps (w0 ,_mm256_loadu_ps (xb ),a ); 118a = _mm256_fmadd_ps (w1 ,_mm256_loadu_ps (xb + 8 ),a ); 119a = _mm256_fmadd_ps (w2 ,_mm256_loadu_ps (xb + 16 ),a ); 120a = _mm256_fmadd_ps (w3 ,_mm256_loadu_ps (xb + 24 ),a ); 121acc [i ]= a ; 122 } 123 } 124for (int i = 0 ;i < n ;++ i )y [i ][r - r0 ]= hsum (acc [i ]); 125 } 126} 127 128// ---- the int8 path's vector tiers (ds4_mx_kern.inc) 129#define MXK_NS mx_avx2 130#define MXK_ATTR MX_TARGET("avx2,fma") 131#define MXK_256 1 132#include "ds4_mx_kern.inc" 133#if defined(MX_AVXVNNI ) 134#define MXK_NS mx_avxvnni 135#define MXK_ATTR MX_TARGET("avx2,fma,avxvnni") 136#define MXK_256 1 137#define MXK_VNNI 1 138#include "ds4_mx_kern.inc" 139#endif 140#define MXK_NS mx_avx512 141#define MXK_ATTR MX_TARGET("avx512f,avx512bw,fma") 142#define MXK_512 1 143#include "ds4_mx_kern.inc" 144#define MXK_NS mx_avx512vnni 145#define MXK_ATTR MX_TARGET("avx512f,avx512bw,avx512vnni,fma") 146#define MXK_512 1 147#define MXK_VNNI 1 148#include "ds4_mx_kern.inc" 149#endif 150 151// ---- the int8 path's scalar tier: ds4_mx_kern.inc's order (8 accumulators, block j of a group of 8 into L(j)), so it 152// gives the vector tiers' bits - also the tests' check on them. The activation's layout (ds4_mx_kern.inc), for any k 153// % 32 == 0: the int8 values in quads (a partial last quad padded), then per group of 8 blocks the scales and the 154// offset corrections in lane order (a partial last group padded) 155inline int act_lane (int b ) {return 8 * (b >>3 )+ ((b & 7 )& 1 )* 4 + ((b & 7 ) >>1 ); } 156inline size_t act_qbytes (int k ) {return (size_t )128 * (size_t ) ((k /kBlock + 3 ) /4 ); } 157inline size_t act_groups (int k ) {return (size_t ) ((k /kBlock + 7 ) /8 ); } 158inline int act_q (const uint8_t * act ,int b ,int j ) {// block b's value j (0..31) 159return ((const int8_t * )act )[(b >>2 )* 128 + (j >=16 ?64 :0 )+ 16 * (b & 3 )+ (j & 15 )]; 160} 161inline float act_d (const uint8_t * act ,int k ,int b ) {return ((const float * ) (act + act_qbytes (k )))[act_lane (b )]; } 162 163void quant_scalar (const float * x ,int b0 ,int b1 ,uint8_t * act ,int k ) { 164int8_t * q = (int8_t * )act ; 165float * dx = (float * ) (act + act_qbytes (k )); 166int32_t * corr = (int32_t * ) (act + act_qbytes (k )+ 32 * act_groups (k )); 167for (int b = b0 ;b < b1 ;++ b ,x += kBlock ) { 168float am = 0.0f ; 169for (int j = 0 ;j < kBlock ;++ j )am = std::max (am , std::fabs (x [j ])); 170const float sc = am /127.0f ; 171int8_t v [kBlock ]; 172int s = 0 ; 173for (int j = 0 ;j < kBlock ;++ j ) { 174v [j ]= am > 0.0f ? (int8_t ) (int ) std::nearbyint (x [j ] /sc ) : (int8_t )0 ; 175s += v [j ]; 176 } 177int8_t * lo = q + (b >>2 )* 128 + 16 * (b & 3 ); 178for (int j = 0 ;j < 16 ;++ j ) { 179lo [j ]= v [j ]; 180lo [64 + j ]= v [16 + j ]; 181 } 182dx [act_lane (b )]= sc ; 183corr [act_lane (b )]= -12 * s ; 184 } 185} 186 187void rows_q_scalar (const uint8_t * w ,size_t rb ,int k ,int r0 ,int r1 ,const void * const * act ,int n ,float * const * y ) { 188const float * t = e8 ().v ; 189for (int r = r0 ;r < r1 ;++ r ) { 190const uint8_t * p = w + (size_t )r * rb ; 191float acc [kMxCpuMaxN ][8 ]= {}; 192for (int b = 0 ;b < k /kBlock ;++ b ,p += kBytes ) { 193int wv [kBlock ]; 194for (int j = 0 ;j < 16 ;++ j ) { 195wv [j ]= kCodes [p [1 + j ]& 15 ]; 196wv [j + 16 ]= kCodes [p [1 + j ] >>4 ]; 197 } 198const int l = act_lane (b )& 7 ; 199for (int i = 0 ;i < n ;++ i ) { 200const uint8_t * a = (const uint8_t * )act [i ]; 201int s = 0 ; 202for (int j = 0 ;j < kBlock ;++ j )s += wv [j ]* act_q (a ,b ,j ); 203acc [i ][l ]= std::fma ((float )s ,t [p [0 ]]* act_d (a ,k ,b ),acc [i ][l ]); 204 } 205 } 206for (int i = 0 ;i < n ;++ i ) { 207const float * A = acc [i ]; 208y [i ][r - r0 ]= ((A [0 ]+ A [4 ])+ (A [2 ]+ A [6 ]))+ ((A [1 ]+ A [5 ])+ (A [3 ]+ A [7 ])); 209 } 210 } 211} 212 213// ---- which tiers this CPU runs 214struct Cpu { 215bool avx2 = false,vnni256 = false,avx512 = false,vnni512 = false,vbmi = false,bmi2 = false; 216}; 217Cpu detect () { 218Cpu c ; 219#if defined(MX_X86 ) 220unsigned r [4 ]= {0 ,0 ,0 ,0 }; 221auto cpuid = [& ](unsigned leaf ,unsigned sub ) { 222#if defined(_MSC_VER ) 223int x [4 ]; 224__cpuidex (x , (int )leaf , (int )sub ); 225for (int i = 0 ;i < 4 ;++ i )r [i ]= (unsigned )x [i ]; 226#else 227__cpuid_count (leaf ,sub ,r [0 ],r [1 ],r [2 ],r [3 ]); 228#endif 229 }; 230cpuid (0 ,0 ); 231const unsigned max_leaf = r [0 ]; 232if (max_leaf < 7 )return c ; 233cpuid (1 ,0 ); 234const bool fma = (r [2 ] >>12 )& 1u ,osxsave = (r [2 ] >>27 )& 1u ,avx = (r [2 ] >>28 )& 1u ; 235if (!fma || !osxsave || !avx )return c ; 236#if defined(_MSC_VER ) 237const unsigned long long xcr0 = _xgetbv (0 ); 238#else 239unsigned lo = 0 ,hi = 0 ; 240 __asm__volatile ("xgetbv" :"=a" (lo ),"=d" (hi ) :"c" (0 )); 241const unsigned long long xcr0 = ((unsigned long long )hi <<32 ) |lo ; 242#endif 243if ((xcr0 & 0x6 )!= 0x6 )return c ;// the OS saves the YMM state 244cpuid (7 ,0 ); 245const unsigned b7 = r [1 ],c7 = r [2 ]; 246c .avx2 = (b7 >>5 )& 1u ; 247const bool zmm_os = (xcr0 & 0xE6 )== 0xE6 ; 248c .avx512 = c .avx2 && zmm_os && ((b7 >>16 )& 1u )&& ((b7 >>30 )& 1u );// F, BW 249c .vnni512 = c .avx512 && ((c7 >>11 )& 1u ); 250c .vbmi = c .avx512 && ((c7 >>1 )& 1u );// AVX-512 VBMI 251c .bmi2 = (b7 >>8 )& 1u ; 252cpuid (7 ,1 ); 253c .vnni256 = c .avx2 && ((r [0 ] >>4 )& 1u );// AVX-VNNI 254#endif 255return c ; 256} 257const Cpu & cpu () { 258static const Cpu c = detect (); 259return c ; 260} 261 262// The tier for this CPU, measured: every vector tier it runs times the same small warm job (64 rows of a 5120-wide 263// matrix, in L2, against 1, 2 and 4 activations - the compute a row takes, which is where the tiers differ; streaming 264// from RAM they all reach the memory's speed) in interleaved rounds, the best round of each counting. The choice never 265// changes an answer (the tiers give the same bits), only the speed. DS4_MX_TIER=<name> picks one by hand. 266std::string g_tier_report ; 267int measure_tier (const std::vector < int >& cand ); 268int pick_tier () { 269if (const char * f = std::getenv ("DS4_MX_TIER" )) 270for (int t = 0 ;t < kMxTiers ;++ t ) 271if (std::string (f )== mx_tier_name (t )&& mx_tier_ok (t )) { 272g_tier_report = std::string ("DS4_MX_TIER=" )+ f ; 273return t ; 274 } 275 std::vector < int > cand ; 276for (int t = 1 ;t < kMxTiers ;++ t ) 277if (mx_tier_ok (t ))cand .push_back (t ); 278if (cand .empty ())return kMxScalar ; 279if (cand .size ()== 1 )return cand [0 ]; 280return measure_tier (cand ); 281} 282int measure_tier (const std::vector < int >& cand ) { 283constexpr int K = 5120 ,R = 64 ,NT = 4 ; 284const size_t rb = (size_t )K /kBlock * kBytes ; 285 std::vector < uint8_t > w (rb * R ),act (mx_act_bytes (K )* NT ); 286uint32_t s = 0x9E3779B9u ; 287for (size_t i = 0 ;i < w .size ();++ i ) { 288s = s * 1664525u + 1013904223u ; 289w [i ]= (uint8_t ) (s >>24 ); 290 } 291for (size_t b = 0 ;b < w .size () /kBytes ;++ b )w [b * kBytes ]= (uint8_t ) (118 + b %6 ); 292 std::vector < float > x (K ); 293for (int i = 0 ;i < NT ;++ i ) { 294for (int j = 0 ;j < K ;++ j ) { 295s = s * 1664525u + 1013904223u ; 296x [(size_t )j ]= (float ) ((int ) (s >>16 )- 32768 ) /32768.0f ; 297 } 298quant_scalar (x .data (),0 ,K /kBlock ,act .data ()+ (size_t )i * mx_act_bytes (K ),K ); 299 } 300const void * ap [NT ]; 301for (int i = 0 ;i < NT ;++ i )ap [i ]= act .data ()+ (size_t )i * mx_act_bytes (K ); 302float y [NT ][R ]; 303float * yp [NT ]= {y [0 ],y [1 ],y [2 ],y [3 ]}; 304 std::vector < double > best (cand .size (),1e30 ); 305for (int round = 0 ;round < 6 ;++ round ) 306for (size_t c = 0 ;c < cand .size ();++ c ) { 307const auto t0 = std::chrono::steady_clock::now (); 308for (int rep = 0 ;rep < 8 ;++ rep ) 309for (int n : {1 ,2 ,4 })mx_rows_tier (cand [c ],w .data (),rb ,K ,0 ,R ,ap ,n ,yp ,0 ); 310const double us = std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count (); 311if (round > 0 )best [c ]= std::min (best [c ],us );// (round 0: the clock and the caches warm) 312 } 313size_t bi = 0 ; 314for (size_t c = 1 ;c < cand .size ();++ c ) 315if (best [c ]< best [bi ])bi = c ; 316char buf [64 ]; 317for (size_t c = 0 ;c < cand .size ();++ c ) { 318 std::snprintf (buf ,sizeof buf ,"%s%s %.0f us" ,c ?", " :"" ,mx_tier_name (cand [c ]),best [c ]); 319g_tier_report += buf ; 320 } 321return cand [bi ]; 322} 323int prefetch_bytes () { 324const char * f = std::getenv ("DS4_MX_PF" ); 325return f != nullptr ? std::max (0 , std::atoi (f )) :0 ; 326} 327 328}// namespace 329 330void q8_round (const float * x ,int k ,float * out ) { 331for (int b = 0 ;b < k /kBlock ;++ b ) { 332const float * xb = x + b * kBlock ; 333float am = 0.0f ; 334for (int j = 0 ;j < kBlock ;++ j )am = std::max (am , std::fabs (xb [j ])); 335const float sc = am /127.0f ; 336for (int j = 0 ;j < kBlock ;++ j ) 337out [b * kBlock + j ]= am > 0.0f ? std::nearbyint (xb [j ] /sc )* sc :0.0f ; 338 } 339} 340 341void mx_cpu_rows (const uint8_t * w ,size_t rb ,int k ,int r0 ,int r1 ,const float * const * x ,int n ,float * const * y ) { 342#if defined(MX_X86 ) 343static const bool avx2 = strata::dsv41k::cpu::exl3_cpu_tier () >=1 ; 344if (avx2 )return rows_avx2 (w ,rb ,k ,r0 ,r1 ,x ,n ,y ); 345#endif 346rows_scalar (w ,rb ,k ,r0 ,r1 ,x ,n ,y ); 347} 348 349// ---- the int8 path 350bool mx_tier_ok (int t ) { 351switch (t ) { 352case kMxScalar :return true; 353case kMxAvx2 :return cpu ().avx2 ; 354#if defined(MX_AVXVNNI ) 355case kMxAvxVnni :return cpu ().vnni256 ; 356#endif 357case kMxAvx512 :return cpu ().avx512 ; 358case kMxAvx512Vnni :return cpu ().vnni512 ; 359default :return false; 360 } 361} 362const char * mx_tier_name (int t ) { 363switch (t ) { 364case kMxScalar :return "scalar" ; 365case kMxAvx2 :return "avx2" ; 366case kMxAvxVnni :return "avxvnni" ; 367case kMxAvx512 :return "avx512" ; 368case kMxAvx512Vnni :return "avx512vnni" ; 369default :return "?" ; 370 } 371} 372int mx_tier () { 373static const int t = pick_tier (); 374return t ; 375} 376const char * mx_tier_report () { 377 (void )mx_tier (); 378return g_tier_report .c_str (); 379} 380 381void mx_quant_blocks (const float * x ,int b0 ,int b1 ,void * act ,int k ) { 382#if defined(MX_X86 ) 383if (cpu ().avx2 && k %256 == 0 )return mx_avx2::quant (x ,b0 ,b1 , (uint8_t * )act ,k ); 384#endif 385quant_scalar (x ,b0 ,b1 , (uint8_t * )act ,k ); 386} 387void mx_quant_blocks_scalar (const float * x ,int b0 ,int b1 ,void * act ,int k ) { 388quant_scalar (x ,b0 ,b1 , (uint8_t * )act ,k ); 389} 390int mx_act_value (const void * act ,int b ,int j ) {return act_q ((const uint8_t * )act ,b ,j ); } 391float mx_act_scale (const void * act ,int k ,int b ) {return act_d ((const uint8_t * )act ,k ,b ); } 392 393void mx_rows_tier (int t ,const uint8_t * w ,size_t rb ,int k ,int r0 ,int r1 ,const void * const * act ,int n , 394float * const * y ,int pf ) { 395if (k %256 != 0 || !mx_tier_ok (t ))t = kMxScalar ;// (the vector tiers take a group of 8 blocks a step) 396const float * tb = e8 ().v ; 397#if defined(MX_X86 ) 398switch (t ) { 399case kMxAvx2 :return mx_avx2::rows (w ,rb ,k ,r0 ,r1 ,act ,n ,y ,tb ,pf ); 400#if defined(MX_AVXVNNI ) 401case kMxAvxVnni :return mx_avxvnni::rows (w ,rb ,k ,r0 ,r1 ,act ,n ,y ,tb ,pf ); 402#endif 403case kMxAvx512 :return mx_avx512::rows (w ,rb ,k ,r0 ,r1 ,act ,n ,y ,tb ,pf ); 404case kMxAvx512Vnni :return mx_avx512vnni::rows (w ,rb ,k ,r0 ,r1 ,act ,n ,y ,tb ,pf ); 405default :break ; 406 } 407#endif 408 (void )tb , (void )pf ; 409for (int i0 = 0 ;i0 < n ;i0 += kMxCpuMaxN ) 410rows_q_scalar (w ,rb ,k ,r0 ,r1 ,act + i0 , std::min (kMxCpuMaxN ,n - i0 ),y + i0 ); 411} 412 413void mx_rows (const uint8_t * w ,size_t rb ,int k ,int r0 ,int r1 ,const void * const * act ,int n ,float * const * y ) { 414static const int pf = prefetch_bytes (); 415mx_rows_tier (mx_tier (),w ,rb ,k ,r0 ,r1 ,act ,n ,y ,pf ); 416} 417 418}// namespace strata::ds4::gguf