okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0d2ee8def
main
1// src/kernels/cpu/native_hadamard_test.cpp - APR port, stage 3: one Hadamard-folded trellis expert (TQ2_T / TQK6 / 2// TQK7, ggml types 144-146) on Strata's CPU path against llama.cpp's own graph for the same weights and input. 3// 4// Strata's path: native_quant_act (signs, FWHT, Q8_0) -> native_gu_rows (ggml-cpu vec_dot + SwiGLU) 5// -> native_quant_h (signs, FWHT, Q8_0) -> native_down_rows 6// The reference: the ops llama.cpp's build_lora_mm_id builds for a prism.hadamard weight - ggml_mul(x, signs), 7// llama_mul_mat_hadamard (reshape to [128, n/128], ggml_mul_mat(rot, .)), ggml_mul_mat(W', .) - 8// computed by ggml-cpu from the same checkout (STRATA_GGML_DIR = the agention llama.cpp fork). 9// The rotation itself is computed two different ways (FWHT here, a dense 128x128 matmul there), so the two outputs 10// agree to float rounding plus the odd Q8_0 rounding flip, not bit for bit; the test bounds the relative error. 11// 12// native_hadamard_test synthetic: random W, rotated and quantized here; also checks the 13// folded expert against the UNROTATED float expert (W x) and that 14// skipping the rotation is caught 15// native_hadamard_test --pack <dir> --gguf <file> [layer expert]... real experts of a prism.hadamard GGUF 16// (Gyro-S / Gyro-M) through the pack tools/iq_pack.py made of it 17#include "strata/kernels/cpu/hadamard.hpp" 18#include "strata/kernels/cpu/native_expert.hpp" 19#include "strata/kernels/cpu/expert_layout.hpp" 20#include "strata/kernels/cpu/pool.hpp" 21#include "strata/artifact/gguf_reader.hpp" 22 23#include "ggml.h" 24#include "ggml-cpu.h" 25 26#include <cmath> 27#include <cstdio> 28#include <cstdlib> 29#include <cstring> 30#include <algorithm> 31#include <random> 32#include <string> 33#include <vector> 34#if defined(_MSC_VER )// MSVC has no __builtin_popcount 35#include <intrin.h> 36#define __builtin_popcount (x ) __popcnt((unsigned) (x)) 37#endif 38 39using namespace strata::kernels::cpu ; 40 41namespace { 42 43constexpr int H = 2560 ,FF = 640 ,B = 128 ; 44 45struct Expert { 46int gu_type = 0 ,d_type = 0 ; 47 std::vector < uint8_t > gate ,up ,down ;// ggml rows: gate/up [FF rows of H], down [H rows of FF] 48 std::vector < float > s_h ,s_ff ;// sign vectors (empty: identity) 49}; 50 51double rel (const std::vector < float >& a ,const std::vector < float >& b ) { 52double num = 0 ,den = 0 ; 53for (size_t i = 0 ;i < a .size ();++ i ) { 54num += (double ) (a [i ]- b [i ])* (a [i ]- b [i ]); 55den += (double )b [i ]* b [i ]; 56 } 57return std::sqrt (num / (den > 0 ?den :1 )); 58} 59 60float silu (float g ) {return g / (1.f + std::exp (- g )); } 61 62// Strata's CPU path for one token; `loaded` = the layer's NativeFmt as expert_layout_load made it from a pack 63std::vector < float > strata_expert (const Expert & e ,const std::vector < float >& x ,bool rotate , 64const NativeFmt * loaded = nullptr ) { 65NativeFmt f ; 66 std::string err ; 67if (!native_fmt (e .gu_type ,e .d_type ,H ,FF ,f ,err )) { std::fprintf (stderr ,"native_fmt: %s\n" ,err .c_str ()); std::exit (1 ); } 68if (rotate && loaded ) { 69f = * loaded ; 70 }else if (rotate ) { 71f .had_block = B ; 72f .had_gu = f .had_d = true; 73f .gu_signs = e .s_h .empty () ?nullptr :e .s_h .data (); 74f .d_signs = e .s_ff .empty () ?nullptr :e .s_ff .data (); 75 } 76 std::vector < uint8_t > blob (f .bytes ); 77 std::memcpy (blob .data (),e .gate .data (),e .gate .size ()); 78 std::memcpy (blob .data ()+ f .up_off ,e .up .data (),e .up .size ()); 79 std::memcpy (blob .data ()+ f .down_off ,e .down .data (),e .down .size ()); 80 std::vector < uint8_t > act (kNativeActBytes ),hq (kNativeHBytes ); 81 std::vector < float > ff (FF ),out (H ); 82native_quant_act (f ,x .data (),act .data ()); 83const void * a [1 ]= {act .data ()}; 84float * ffp [1 ]= {ff .data ()}; 85native_gu_rows (f ,blob .data (),a ,1 ,ffp ,0 ,FF ); 86native_quant_h (f ,ff .data (),hq .data ()); 87const void * hp [1 ]= {hq .data ()}; 88float * op [1 ]= {out .data ()}; 89native_down_rows (f ,blob .data (),hp ,1 ,op ,0 ,H ); 90return out ; 91} 92 93// llama.cpp's graph for the same expert (the fork's build_lora_mm + llama_mul_mat_hadamard), one token 94std::vector < float > llama_expert (const Expert & e ,const std::vector < float >& x ) { 95ggml_init_params ip = {(size_t )256 <<20 ,nullptr , false}; 96ggml_context * ctx = ggml_init (ip ); 97// the normalized Sylvester-Walsh-Hadamard matrix exactly as llama_model_base builds prism.hadamard.128 98ggml_tensor * rot = ggml_new_tensor_2d (ctx ,GGML_TYPE_F32 ,B ,B ); 99float * R = (float * )rot -> data ; 100const float scale = 1.0f /sqrtf ((float )B ); 101for (uint32_t r = 0 ;r < (uint32_t )B ;++ r ) 102for (uint32_t c = 0 ;c < (uint32_t )B ;++ c ) { 103uint32_t p = r & c ; 104p ^=p >>16 ;p ^=p >>8 ;p ^=p >>4 ;p ^=p >>2 ;p ^=p >>1 ; 105R [r * B + c ]= (p & 1 ) ?- scale :scale ; 106 } 107auto hadamard = [& ](ggml_tensor * cur ,const std::vector < float >& signs ) { 108if (!signs .empty ()) { 109ggml_tensor * s = ggml_new_tensor_1d (ctx ,GGML_TYPE_F32 , (int64_t )signs .size ()); 110 std::memcpy (s -> data ,signs .data (),signs .size ()* sizeof (float )); 111cur = ggml_mul (ctx ,cur ,s ); 112 } 113ggml_tensor * res = ggml_reshape_2d (ctx ,cur ,B ,ggml_nelements (cur ) /B ); 114res = ggml_mul_mat (ctx ,rot ,res ); 115return ggml_reshape_4d (ctx ,res ,cur -> ne [0 ],cur -> ne [1 ],cur -> ne [2 ],cur -> ne [3 ]); 116 }; 117ggml_tensor * wg = ggml_new_tensor_2d (ctx , (ggml_type )e .gu_type ,H ,FF ); 118ggml_tensor * wu = ggml_new_tensor_2d (ctx , (ggml_type )e .gu_type ,H ,FF ); 119ggml_tensor * wd = ggml_new_tensor_2d (ctx , (ggml_type )e .d_type ,FF ,H ); 120 std::memcpy (wg -> data ,e .gate .data (),e .gate .size ()); 121 std::memcpy (wu -> data ,e .up .data (),e .up .size ()); 122 std::memcpy (wd -> data ,e .down .data (),e .down .size ()); 123ggml_tensor * xt = ggml_new_tensor_1d (ctx ,GGML_TYPE_F32 ,H ); 124 std::memcpy (xt -> data ,x .data (),H * sizeof (float )); 125ggml_tensor * xr = hadamard (xt ,e .s_h ); 126ggml_tensor * g = ggml_mul_mat (ctx ,wg ,xr ); 127ggml_tensor * u = ggml_mul_mat (ctx ,wu ,xr ); 128ggml_tensor * h = ggml_mul (ctx ,ggml_silu (ctx ,g ),u ); 129ggml_tensor * out = ggml_mul_mat (ctx ,wd ,hadamard (h ,e .s_ff )); 130ggml_cgraph * gf = ggml_new_graph (ctx ); 131ggml_build_forward_expand (gf ,out ); 132ggml_graph_compute_with_ctx (ctx ,gf ,4 ); 133 std::vector < float > y (H ); 134 std::memcpy (y .data (),out -> data ,H * sizeof (float )); 135ggml_free (ctx ); 136return y ; 137} 138 139// W' = W diag(s) H^T per 128-column block (what the APR encoder folds), then quantized with ggml 140std::vector < uint8_t > fold_and_quantize (const std::vector < float >& w ,int rows ,int cols ,const std::vector < float >& s , 141int type , std::vector < float >& folded ) { 142folded .assign (w .begin (),w .end ()); 143for (int r = 0 ;r < rows ;++ r )hadamard_rotate (folded .data ()+ (size_t )r * cols ,cols ,B ,s .data ()); 144// (H symmetric and orthonormal: row-wise H (s * w_r) is exactly the fold W diag(s) H^T) 145 std::vector < uint8_t > q (ggml_row_size ((ggml_type )type ,cols )* rows ); 146ggml_quantize_chunk ((ggml_type )type ,folded .data (),q .data (),0 ,rows ,cols ,nullptr ); 147return q ; 148} 149 150int synthetic (int gu_type ,int d_type ) { 151 std::mt19937 rng (1234 + gu_type * 7 + d_type ); 152 std::normal_distribution < float > nd (0.f ,1.f ); 153 std::uniform_int_distribution < int > coin (0 ,1 ); 154Expert e ; 155e .gu_type = gu_type ; 156e .d_type = d_type ; 157 std::vector < float > wg ((size_t )FF * H ),wu ((size_t )FF * H ),wd ((size_t )H * FF ),x (H ); 158for (auto & v :wg )v = nd (rng )* 0.02f ; 159for (auto & v :wu )v = nd (rng )* 0.02f ; 160for (auto & v :wd )v = nd (rng )* 0.02f ; 161for (auto & v :x )v = nd (rng ); 162x [17 ]= 40.f ;// a massive channel, as the real residual stream has: the case the rotation exists for 163e .s_h .resize (H ); 164e .s_ff .resize (FF ); 165for (auto & v :e .s_h )v = coin (rng ) ?1.f :-1.f ; 166for (auto & v :e .s_ff )v = coin (rng ) ?1.f :-1.f ; 167 std::vector < float > fg ,fu ,fd ; 168e .gate = fold_and_quantize (wg ,FF ,H ,e .s_h ,gu_type ,fg ); 169e .up = fold_and_quantize (wu ,FF ,H ,e .s_h ,gu_type ,fu ); 170e .down = fold_and_quantize (wd ,H ,FF ,e .s_ff ,d_type ,fd ); 171 172// the unrotated float expert W x: what the folded, quantized expert must approximate 173 std::vector < float > h (FF ),ref (H ); 174for (int r = 0 ;r < FF ;++ r ) { 175double g = 0 ,u = 0 ; 176for (int c = 0 ;c < H ;++ c ) {g += (double )wg [(size_t )r * H + c ]* x [c ];u += (double )wu [(size_t )r * H + c ]* x [c ]; } 177h [r ]= silu ((float )g )* (float )u ; 178 } 179for (int r = 0 ;r < H ;++ r ) { 180double o = 0 ; 181for (int c = 0 ;c < FF ;++ c )o += (double )wd [(size_t )r * FF + c ]* h [c ]; 182ref [r ]= (float )o ; 183 } 184const auto ours = strata_expert (e ,x , true); 185const auto llama = llama_expert (e ,x ); 186const auto unrot = strata_expert (e ,x , false); 187const double e_ll = rel (ours ,llama ),e_ref = rel (ours ,ref ),e_llref = rel (llama ,ref ),e_un = rel (unrot ,ref ); 188 std::printf ("synthetic %s/%s: strata vs llama.cpp graph %.2e | vs unrotated float expert: strata %.4f, llama.cpp " 189"%.4f | strata WITHOUT the rotation %.4f\n" ,ggml_type_name ((ggml_type )gu_type ), 190ggml_type_name ((ggml_type )d_type ),e_ll ,e_ref ,e_llref ,e_un ); 191// strata == llama.cpp to rounding, and both approximate W x equally well. With Q8_0 weights the quantization 192// error is ~1%, so the fold's convention itself is checked: the rotated path must reproduce the unrotated float 193// expert and the unrotated path must not. (The trellis types' own error at 1.6-2.1 bpw on Gaussian weights, 194// compounded through SwiGLU, is large with this test's placeholder ggml encoder; there only agreement counts.) 195const bool hi = gu_type == 8 && d_type == 8 ; 196const bool ok = e_ll < 2e-3 && std::fabs (e_ref - e_llref )< 0.01 && (!hi || (e_ref < 0.03 && e_un > 0.8 )); 197 std::printf (" %s\n" ,ok ?"ok" :"FAILED" ); 198return ok ?0 :1 ; 199} 200 201// A real expert, the pack's loader path: expert_layout_load(<pack>) reads native_experts.txt v5 + hadamard.txt (from 202// tools/iq_pack.py), and the layer's NativeFmt is what the engine's CPU pool would use. (The signs come from the 203// pack: strata::GgufFile keeps only the first 64 items of a metadata array, so it cannot read sign_values.) 204int real (const char * pack ,const char * path ,int layer ,int expert ) { 205 std::string err ; 206if (!expert_layout_load (pack ,48 ,512 ,err )) { std::fprintf (stderr ,"expert_layout_load: %s\n" ,err .c_str ());return 1 ; } 207const ExpertLayout & lay = expert_layout (); 208const HadamardSpec & hs = hadamard_spec (); 209if (!lay .native || !hs .any ()|| lay .version != 5 ) { std::fprintf (stderr ,"%s: not a v5 (Hadamard) native pack\n" ,pack );return 1 ; } 210const NativeFmt & lf = lay .fmt [(size_t )layer ]; 211if (lf .had_block != B || !lf .had_gu || !lf .had_d ) { std::fprintf (stderr ,"layer %d is not folded in the pack\n" ,layer );return 1 ; } 212 strata::GgufFile g (path ); 213Expert e ; 214if (const float * sh = hadamard_signs (H ))e .s_h .assign (sh ,sh + H ); 215if (const float * sf = hadamard_signs (FF ))e .s_ff .assign (sf ,sf + FF ); 216auto slice = [& ](const char * role , std::vector < uint8_t >& dst ,int & type ) { 217const std::string name = "blk." + std::to_string (layer )+ ".ffn_" + role + "_exps.weight" ; 218const strata::TensorInfo * t = g .find (name ); 219if (!t || t -> shape .size ()!= 3 ) { std::fprintf (stderr ,"missing %s\n" ,name .c_str ()); std::exit (1 ); } 220type = (int )t -> type ; 221const size_t per = ggml_row_size ((ggml_type )type , (int64_t )t -> shape [0 ])* t -> shape [1 ]; 222const uint8_t * p = g .tensor_data (* t )+ per * (size_t )expert ; 223dst .assign (p ,p + per ); 224 }; 225int dt = 0 ,ut = 0 ; 226slice ("gate" ,e .gate ,e .gu_type ); 227slice ("up" ,e .up ,ut ); 228slice ("down" ,e .down ,dt ); 229e .d_type = dt ; 230if (e .gu_type != lf .gu_type || e .d_type != lf .d_type ) { std::fprintf (stderr ,"the pack and the GGUF disagree\n" );return 1 ; } 231 std::mt19937 rng (99 ); 232 std::normal_distribution < float > nd (0.f ,1.f ); 233 std::vector < float > x (H ); 234for (auto & v :x )v = nd (rng ); 235x [17 ]= 40.f ; 236const auto ours = strata_expert (e ,x , true,& lf ); 237const auto llama = llama_expert (e ,x ); 238const auto unrot = strata_expert (e ,x , false); 239const double e_ll = rel (ours ,llama ),e_un = rel (unrot ,llama ); 240 std::printf ("%s layer %d expert %d (%s/%s, signs %s): strata vs llama.cpp graph %.2e | without the rotation %.3f\n" , 241path ,layer ,expert ,ggml_type_name ((ggml_type )e .gu_type ),ggml_type_name ((ggml_type )e .d_type ), 242e .s_h .empty () ?"identity" :"explicit" ,e_ll ,e_un ); 243bool ok = e_ll < 2e-3 && e_un > 0.3 ; 244 std::printf (" %s\n" ,ok ?"ok" :"FAILED" ); 245 246// the engine's CPU entry point: ExpertPool::run_split_multi_native with the pack's NativeFmt, three tokens 247// routed to this expert (x quantized by native_quant_act, as expert_source.cpp does for the doorbell copy) 248 { 249constexpr int NT = 3 ; 250ExpertPool pool (4 , false, false); 251 std::vector < uint8_t > blob (lf .bytes ); 252 std::memcpy (blob .data (),e .gate .data (),e .gate .size ()); 253 std::memcpy (blob .data ()+ lf .up_off ,e .up .data (),e .up .size ()); 254 std::memcpy (blob .data ()+ lf .down_off ,e .down .data (),e .down .size ()); 255 std::vector < std::vector < float >> xs (NT , std::vector < float > (H )),outs (NT , std::vector < float > (H )); 256 std::vector < std::vector < uint8_t >> acts (NT , std::vector < uint8_t > (kNativeActBytes )); 257ExpertJobMulti job ; 258job .blob = blob .data (); 259job .nt = NT ; 260for (int t = 0 ;t < NT ;++ t ) { 261for (auto & v :xs [t ])v = nd (rng ); 262xs [t ][(size_t ) (101 * t + 5 )]= 30.f ; 263native_quant_act (lf ,xs [t ].data (),acts [t ].data ()); 264job .nact [t ]= acts [t ].data (); 265job .out [t ]= outs [t ].data (); 266 } 267pool .run_split_multi_native (lf ,& job ,1 ); 268double worst = 0 ; 269for (int t = 0 ;t < NT ;++ t )worst = std::max (worst ,rel (outs [t ],llama_expert (e ,xs [t ]))); 270const bool pok = worst < 2e-3 ; 271 std::printf (" ExpertPool::run_split_multi_native, %d tokens: worst vs llama.cpp graph %.2e %s\n" ,NT ,worst , 272pok ?"ok" :"FAILED" ); 273ok = ok && pok ; 274 } 275return ok ?0 :1 ; 276} 277 278// the FWHT against the dense matrix llama.cpp builds, on one block 279int fwht_check () { 280 std::mt19937 rng (7 ); 281 std::normal_distribution < float > nd (0.f ,1.f ); 282 std::vector < float > x (B ),y (B ),s (B ); 283for (auto & v :x )v = nd (rng ); 284for (int i = 0 ;i < B ;++ i )s [i ]= (i * 37 %5 )< 2 ?-1.f :1.f ; 285y = x ; 286hadamard_rotate (y .data (),B ,B ,s .data ()); 287double worst = 0 ; 288for (int r = 0 ;r < B ;++ r ) { 289double acc = 0 ; 290for (int c = 0 ;c < B ;++ c )acc += ((__builtin_popcount (r & c )& 1 ) ?-1.0 :1.0 )* s [c ]* x [c ]; 291worst = std::max (worst , std::fabs (acc / std::sqrt ((double )B )- y [r ])); 292 } 293 std::printf ("FWHT vs dense normalized Sylvester matrix: max abs diff %.2e %s\n" ,worst ,worst < 1e-5 ?"ok" :"FAILED" ); 294return worst < 1e-5 ?0 :1 ; 295} 296 297}// namespace 298 299int main (int argc ,char ** argv ) { 300if (!native_experts_available ()) { std::fprintf (stderr ,"built without native experts\n" );return 1 ; } 301int rc = fwht_check (); 302if (argc >=5 && std::strcmp (argv [1 ],"--pack" )== 0 && std::strcmp (argv [3 ],"--gguf" )== 0 ) { 303for (int i = 5 ;i + 1 < argc || i == 5 ;i += 2 ) {// [layer expert]... 304const int layer = argc > i ? std::atoi (argv [i ]) :0 ,expert = argc > i + 1 ? std::atoi (argv [i + 1 ]) :0 ; 305rc |=real (argv [2 ],argv [4 ],layer ,expert ); 306 } 307return rc ; 308 } 309// ggml type ids of the agention fork: 144 TQ2_T, 145 TQK6, 146 TQK7 310if (GGML_TYPE_COUNT <=146 ) { std::fprintf (stderr ,"this ggml has no trellis types (build with STRATA_GGML_DIR = the agention fork): skipped\n" );return 77 ; }// 77: ctest SKIP_RETURN_CODE (#3358) 311rc |=synthetic (8 ,8 );// Q8_0: the fold's convention, against the unrotated float expert 312rc |=synthetic (145 ,146 );// Gyro-S 313rc |=synthetic (144 ,144 );// Gyro-M 314return rc ; 315}