okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
28ce98bf1
main
1// tools/trellis/tqenc_test.cpp - tests of the trellis encoder (tqenc.hpp) against Strata's own CPU decoder 2// (src/kernels/cpu/tq_states.hpp, tq_cpu.cpp: scalar / AVX2 / AVX-512 kernels). Build and run: tools/trellis/build.sh test. 3// 4// T1 fp16 conversion (all 65536 halves, random floats vs the hardware where F16C exists) 5// T2 the encoder's codebook == the decoder's state table (bit for bit, 32768 x 4) 6// T3 random streams: block_state (bit by bit) == tq_states.hpp; every window obeys the shift-trellis relation, 7// circularly (so a legal path = the chain relation + the closure state(31) -> state(0)); pack(unpack(s)) == s 8// T4 the Viterbi pass == a naive DP written from the legality relation (every state, every predecessor), for a fixed 9// start group (tail-biting), a free start and a rotated start, with importance weights 10// T5 exhaustive: every symbol value at every stream position round-trips through pack/decode 11// T6 planted solutions: weights decoded from a random legal stream and scale; exact search at that scale must find 12// error 0 and bit-identical weights; the approximate search is reported (recovery rate) 13// T7 encode -> decode: the encoder's reconstruction == the decoder's weights bit for bit (tq_states + state table), 14// and the CPU kernels' dot products against Q8_0 activations == the dense dot of those weights 15// T8 specials: zero blocks, tiny / huge / extreme scales, constants, spikes, NaN / Inf, determinism over threads 16// T9 quality on Gaussian blocks: SQNR against the rate-distortion bound 6.02 * K/4 dB; approximate vs exact search 17#include "tqenc.hpp" 18 19#include "strata/kernels/cpu/tq_cpu.hpp" 20#include "tq_states.hpp" 21 22#include <algorithm> 23#include <chrono> 24#include <cmath> 25#include <cstdio> 26#include <cstdlib> 27#include <cstring> 28#include <random> 29#include <string> 30#include <vector> 31 32#if defined(__F16C__ ) 33#include <immintrin.h> 34#endif 35 36namespace strata::kernels::cpu { 37bool cpu_avx512_ok () {return __builtin_cpu_supports ("avx512f" )&& __builtin_cpu_supports ("avx512bw" )&& __builtin_cpu_supports ("avx512vl" )&& __builtin_cpu_supports ("avx512vbmi" )&& __builtin_cpu_supports ("avx512vnni" ); } 38bool cpu_avx2_ok () {return __builtin_cpu_supports ("avx2" )&& __builtin_cpu_supports ("fma" ); } 39}// namespace strata::kernels::cpu 40 41using namespace tqenc ; 42namespace kc= strata::kernels::cpu; 43 44static int g_fail = 0 ,g_checks = 0 ; 45#define CHECK (cond , ...) \ 46 do { \ 47 ++g_checks; \ 48 if (!(cond)) { \ 49 ++g_fail; \ 50 std::printf(" FAIL %s:%d %s ", __FILE__, __LINE__, #cond); \ 51 std::printf(__VA_ARGS__); \ 52 std::printf("\n"); \ 53 } \ 54 } while (0) 55 56static const int kTypes [7 ]= {TQ2_T ,TQK6 ,TQK7 ,TQK5X ,TQK4X ,TQK5T ,TQK4T }; 57static const char * tname (int t ) { 58return t == TQ2_T ?"TQ2_T" :t == TQK6 ?"TQK6" :t == TQK7 ?"TQK7" :t == TQK5X ?"TQK5X" :t == TQK4X ?"TQK4X" :t == TQK5T ?"TQK5T" :"TQK4T" ; 59} 60 61template < int KB > 62static void states_repo (const uint8_t * qs ,uint32_t * st ) { kc::tq_detail::tq_states < KB > (qs ,st ); } 63static void states_repo_k (int K ,const uint8_t * qs ,uint32_t * st ) { 64switch (K ) { 65case 8 :states_repo < 8 > (qs ,st );break ; 66case 7 :states_repo < 7 > (qs ,st );break ; 67case 6 :states_repo < 6 > (qs ,st );break ; 68case 5 :states_repo < 5 > (qs ,st );break ; 69default :states_repo < 4 > (qs ,st );break ; 70 } 71} 72 73static std::mt19937_64 rng (12345 ); 74static float gauss () {static std::normal_distribution < float > n (0.f ,1.f );return n (rng ); } 75 76// chain relation between consecutive steps, circularly: returns true when state(t) and state(t') obey the shift trellis 77static bool chain_ok (int type ,const uint32_t * st ) { 78const int K = type_kbits (type ); 79for (int t = 0 ;t < 32 ;++ t ) { 80if (type == TQ2_T ) {// state(t) = ((state(t-1) & 0x7f) << 8) | byte 81const int tp = (t + 31 )& 31 ; 82if ((st [t ] >>8 )!= (st [tp ]& 0x7f ))return false; 83 }else {// u = 31 - t; state(u+1) low (15-K) bits = state(u) >> K, i.e. step t-1 follows step t 84const int tp = (t + 31 )& 31 ; 85if ((st [tp ]& ((1u << (15 - K ))- 1u ))!= (st [t ] >>K ))return false; 86 } 87 } 88return true; 89} 90 91static void t1 () { 92 std::printf ("T1 fp16\n" ); 93for (uint32_t h = 0 ;h < 65536 ;++ h ) { 94const float f = half_to_float ((uint16_t )h ); 95if (std::isnan (f ))continue ; 96CHECK (float_to_half (f )== (uint16_t )h || (h == 0x8000 && float_to_half (f )== 0x8000 ),"half %04x" ,h ); 97 } 98#if defined(__F16C__ ) 99int bad = 0 ; 100 std::uniform_real_distribution < float > u (-1.f ,1.f ); 101for (int i = 0 ;i < 4000000 ;++ i ) { 102float f = u (rng )* std::pow (2.f , (float ) (int ) (rng () %50 )- 30.f ); 103if (i %7 == 0 )f = std::ldexp (u (rng ),-25 + (int ) (rng () %6 ));// subnormal range and its ties 104if (i %11 == 0 )f = std::ldexp (u (rng ),14 + (int ) (rng () %3 ));// the overflow edge 105const uint16_t hw = _cvtss_sh (f ,_MM_FROUND_TO_NEAREST_INT ); 106bad += float_to_half (f )!= hw ; 107 } 108CHECK (bad == 0 ,"float_to_half vs F16C: %d differ" ,bad ); 109#endif 110} 111 112static void t2 () { 113 std::printf ("T2 codebook == decoder table\n" ); 114for (int type :kTypes ) { 115const int16_t * a = codebook_table (type ); 116const int16_t * b = kc::tq_state_table_for (type ); 117CHECK (std::memcmp (a ,b ,32768 * 4 * sizeof (int16_t ))== 0 ,"%s: encoder and decoder tables differ" ,tname (type )); 118 } 119// the computed codebook: its own definition, evaluated bit by bit here (not through tq_computed.hpp), is what both use 120 { 121const int16_t * c = codebook_table (TQK5X ); 122int bad = 0 ,big = 0 ; 123for (uint32_t s = 0 ;s < 32768 ;++ s ) 124for (int i = 0 ;i < 2 ;++ i ) { 125const uint32_t A [2 ]= {89226354u ,0x9E3779B1u },B [2 ]= {64248484u ,0x7F4A7C15u }; 126const uint32_t r = ((s * A [i ]+ B [i ])& 0x8FFF8FFFu ) ^0x3B603B60u ; 127for (int hw = 0 ;hw < 2 ;++ hw ) { 128const uint16_t h = (uint16_t ) (hw ?r >>16 :r & 0xffff ); 129const float v = half_to_float (h )* 8192.0f ; 130bad += c [4 * s + 2 * i + hw ]!= (int16_t )v || v != std::floor (v ); 131big += std::fabs (v ) >=16384.0f || std::fabs (v )< 1023.0f ; 132 } 133 } 134CHECK (bad == 0 ,"computed codebook differs from its definition (%d)" ,bad ); 135CHECK (big == 0 ,"computed codebook value out of [0.125, 2) (%d)" ,big ); 136// the distribution: rms and the share of the weights below / above one 137double ss = 0 ; 138for (int i = 0 ;i < 32768 * 4 ;++ i )ss += (double )c [i ]* c [i ]; 139 std::printf (" computed codebook: rms %.4f (table: %.4f), all values exact integers at 2^13\n" , std::sqrt (ss / (32768.0 * 4 )) /8192.0 ,1.072 ); 140 } 141} 142 143static void t3 () { 144 std::printf ("T3 states of random streams\n" ); 145for (int type :kTypes ) { 146const int K = type_kbits (type ),nb = 4 * K ; 147int bad_states = 0 ,bad_chain = 0 ,bad_pack = 0 ; 148for (int it = 0 ;it < 20000 ;++ it ) { 149uint8_t qs [32 ]; 150for (int i = 0 ;i < nb ;++ i )qs [i ]= (uint8_t )rng (); 151uint32_t sr [32 ]; 152states_repo_k (K ,qs ,sr ); 153uint32_t sm [32 ]; 154for (int t = 0 ;t < 32 ;++ t )sm [t ]= block_state (type ,qs ,t ); 155bad_states += std::memcmp (sr ,sm ,sizeof sr )!= 0 ; 156bad_chain += !chain_ok (type ,sm ); 157// pack(unpack): processing order p -> step t 158uint16_t by_pos [32 ]; 159for (int p = 0 ;p < 32 ;++ p )by_pos [p ]= (uint16_t )sm [type == TQ2_T ?p :31 - p ]; 160uint8_t q2 [32 ]; 161debug_pack (type ,by_pos ,q2 ); 162// TQ2_T's bit 7 of each byte is part of the stream but the state uses only 15 bits of two bytes: bit 7 of 163// qs[t] is in state(t) (bit 7), so it survives; every stream bit is in some state 164bad_pack += std::memcmp (qs ,q2 ,nb )!= 0 ; 165 } 166 std::printf (" %-6s states vs tq_states.hpp: %d bad, chain relation: %d bad, pack(unpack): %d bad\n" ,tname (type ), 167bad_states ,bad_chain ,bad_pack ); 168CHECK (bad_states == 0 && bad_chain == 0 && bad_pack == 0 ,"%s" ,tname (type )); 169 } 170} 171 172// naive DP from the legality relation, one pass; same conventions as debug_viterbi 173static float naive (int type ,const float (* T )[4 ],const float (* H )[4 ],int rot ,int fixed_c ,uint16_t * st_out ) { 174const int K = type_kbits (type ); 175const bool t2 = type == TQ2_T ; 176const int G = debug_groups (type ); 177 std::vector < std::vector < float >> D (32 , std::vector < float > (32768 ,1e30f )); 178 std::vector < std::vector < int >> B (32 , std::vector < int > (32768 ,-1 )); 179auto cost = [& ](int p ,uint32_t s ) { 180const float * c = codebook_state (type ,s ); 181float e = 0 ; 182for (int j = 0 ;j < 4 ;++ j ) {const float d = T [p ][j ]- c [j ];e += H [p ][j ]* d * d ; } 183return e ; 184 }; 185auto legal = [& ](uint32_t prev ,uint32_t next ) {// next may follow prev 186return t2 ? (next >>8 )== (prev & 0x7f ) : (next & (uint32_t ) (G - 1 ))== (prev >>K ); 187 }; 188for (uint32_t s = 0 ;s < 32768 ;++ s ) { 189const bool ok = fixed_c < 0 || (t2 ? (int ) (s >>8 )== fixed_c : (int ) (s & (G - 1 ))== fixed_c ); 190if (ok )D [0 ][s ]= cost (rot & 31 ,s ); 191 } 192for (int q = 1 ;q < 32 ;++ q ) 193for (uint32_t s = 0 ;s < 32768 ;++ s ) { 194float best = 1e30f ; 195int arg = -1 ; 196// enumerate the predecessors from the relation (all prev with legal(prev, s)): scan the 2^K candidates 197const int n = 1 <<K ; 198for (int y = 0 ;y < (t2 ?256 :n );++ y ) { 199const uint32_t prev = t2 ? ((uint32_t )y <<7 ) | (s >>8 ) : (((s & (uint32_t ) (G - 1 )) <<K ) | (uint32_t )y ); 200if (!legal (prev ,s ))continue ; 201if (D [q - 1 ][prev ]< best ) {best = D [q - 1 ][prev ];arg = (int )prev ; } 202 } 203if (arg >=0 ) {D [q ][s ]= best + cost ((rot + q )& 31 ,s );B [q ][s ]= arg ; } 204 } 205float best = 1e30f ; 206int bs = -1 ; 207for (uint32_t s = 0 ;s < 32768 ;++ s ) { 208const bool ok = fixed_c < 0 || (t2 ? (int ) (s & 0x7f )== fixed_c : (int ) (s >>K )== fixed_c ); 209if (ok && D [31 ][s ]< best ) {best = D [31 ][s ];bs = (int )s ; } 210 } 211if (bs < 0 )return 1e30f ; 212int s = bs ; 213for (int q = 31 ;q >=0 ;-- q ) { 214st_out [(rot + q )& 31 ]= (uint16_t )s ; 215if (q > 0 )s = B [q ][s ]; 216 } 217return best ; 218} 219 220static void t4 () { 221 std::printf ("T4 Viterbi vs naive DP\n" ); 222for (int type :kTypes ) { 223const int G = debug_groups (type ); 224double worst = 0 ; 225int cases = 0 ; 226for (int trial = 0 ;trial < 3 ;++ trial ) { 227float T [32 ][4 ],H [32 ][4 ]; 228for (int p = 0 ;p < 32 ;++ p ) 229for (int j = 0 ;j < 4 ;++ j ) { 230T [p ][j ]= gauss ()* (trial == 2 ?2.5f :1.0f ); 231H [p ][j ]= trial == 0 ?1.f :0.1f + std::fabs (gauss ()); 232 } 233struct Case {int rot ,c ; }; 234Case cs [3 ]= {{0 , (int ) (rng () %G )}, {0 ,-1 }, {13 ,-1 }}; 235for (const Case & cc :cs ) { 236uint16_t sa [32 ],sb [32 ]; 237const float a = debug_viterbi (type ,T ,H ,cc .rot ,cc .c ,sa ); 238const float b = naive (type ,T ,H ,cc .rot ,cc .c ,sb ); 239const double rel = std::fabs (a - b ) / std::max (1e-6f ,b ); 240worst = std::max (worst ,rel ); 241CHECK (rel < 2e-5 ,"%s trial %d rot %d c %d: viterbi %.6f naive %.6f" ,tname (type ),trial ,cc .rot ,cc .c ,a ,b ); 242// the returned path is legal and its own cost is the reported cost 243uint32_t sm [32 ]; 244uint8_t qs [32 ]; 245debug_pack (type ,sa ,qs ); 246for (int t = 0 ;t < 32 ;++ t )sm [t ]= block_state (type ,qs ,t ); 247bool same = true; 248for (int p = 0 ;p < 32 ;++ p ) { 249const uint32_t d = sm [type == TQ2_T ?p :31 - p ]; 250if (cc .rot == 0 || cc .c < 0 ) { 251// a free rotated pass is a legal chain only if the stream closes; compare only closed ones 252 } 253same = same && (cc .c < 0 ? true :d == sa [p ]); 254 } 255if (cc .c >=0 )CHECK (same ,"%s tail-biting path does not decode to its own states" ,tname (type )); 256double sum = 0 ; 257for (int q = 0 ;q < 32 ;++ q ) { 258const int p = (cc .rot + q )& 31 ; 259const float * c = codebook_state (type ,sa [p ]); 260for (int j = 0 ;j < 4 ;++ j ) {const double d = T [p ][j ]- c [j ];sum += H [p ][j ]* d * d ; } 261 } 262CHECK (std::fabs (sum - a )< 1e-3 * std::max (1.0 , (double )a ),"path cost %.6f vs reported %.6f" ,sum ,a ); 263++ cases ; 264 } 265 } 266 std::printf (" %-6s %d cases, worst relative cost difference %.2e\n" ,tname (type ),cases ,worst ); 267 } 268} 269 270static void t5 () { 271 std::printf ("T5 every symbol value at every position\n" ); 272for (int type :kTypes ) { 273const int K = type_kbits (type ),nb = 4 * K ; 274long bad = 0 ,n = 0 ; 275if (type == TQ2_T ) { 276for (int pos = 0 ;pos < 32 ;++ pos ) 277for (int x = 0 ;x < 256 ;++ x ) { 278uint8_t qs [32 ]; 279for (int i = 0 ;i < nb ;++ i )qs [i ]= (uint8_t )rng (); 280qs [pos ]= (uint8_t )x ; 281uint32_t sm [32 ]; 282for (int t = 0 ;t < 32 ;++ t )sm [t ]= block_state (type ,qs ,t ); 283uint16_t bp [32 ]; 284for (int p = 0 ;p < 32 ;++ p )bp [p ]= (uint16_t )sm [p ]; 285uint8_t q2 [32 ]; 286debug_pack (type ,bp ,q2 ); 287bad += std::memcmp (qs ,q2 ,nb )!= 0 || !chain_ok (type ,sm ); 288++ n ; 289 } 290 }else { 291for (int u = 0 ;u < 32 ;++ u ) 292for (int x = 0 ;x < (1 <<K );++ x ) { 293uint8_t qs [32 ]; 294for (int i = 0 ;i < nb ;++ i )qs [i ]= (uint8_t )rng (); 295// overwrite symbol u 296for (int b = 0 ;b < K ;++ b ) { 297const int bit = u * K + b ; 298qs [bit >>3 ]= (uint8_t ) ((qs [bit >>3 ]& ~(1u << (bit & 7 ))) | (((x >>b )& 1u ) << (bit & 7 ))); 299 } 300uint32_t sm [32 ]; 301for (int t = 0 ;t < 32 ;++ t )sm [t ]= block_state (type ,qs ,t ); 302// symbol u is the low K bits of the state of step 31 - u 303bad += (int ) (sm [31 - u ]& ((1u <<K )- 1u ))!= x ; 304uint16_t bp [32 ]; 305for (int p = 0 ;p < 32 ;++ p )bp [p ]= (uint16_t )sm [31 - p ]; 306uint8_t q2 [32 ]; 307debug_pack (type ,bp ,q2 ); 308bad += std::memcmp (qs ,q2 ,nb )!= 0 || !chain_ok (type ,sm ); 309++ n ; 310 } 311 } 312 std::printf (" %-6s %ld cases, %ld bad\n" ,tname (type ),n ,bad ); 313CHECK (bad == 0 ,"%s" ,tname (type )); 314 } 315} 316 317static void t6 () { 318 std::printf ("T6 planted solutions\n" ); 319for (int type :kTypes ) { 320const int K = type_kbits (type ),nb = 4 * K ,bb = block_bytes (type ); 321const int N = (type == TQK4X ?12 :30 ); 322int exact_ok = 0 ,approx_ok1 = 0 ,approx_ok3 = 0 ; 323double approx_err_sum = 0 ,wsum = 0 ; 324for (int it = 0 ;it < N ;++ it ) { 325 std::vector < uint8_t > blk (bb ); 326const float dsc = std::ldexp (0.5f + (float ) (rng () %1000 ) /1000.f ,-6 + (int ) (rng () %10 )); 327const uint16_t dh = float_to_half (dsc ); 328blk [0 ]= (uint8_t ) (dh & 255 ); 329blk [1 ]= (uint8_t ) (dh >>8 ); 330// a legal stream: any bytes are legal (every stream is a closed cycle by construction); for TQ2_T too 331for (int i = 0 ;i < nb ;++ i )blk [2 + i ]= (uint8_t )rng (); 332 std::vector < float > w (128 ); 333decode_blocks (type ,blk .data (),1 ,w .data ()); 334for (float x :w )wsum += (double )x * x ; 335Params p ; 336p .fixed_scale = dh ; 337 std::vector < uint8_t > out (bb ); 338p .exact = 1 ; 339BlockResult r = encode_block (type ,w .data (),nullptr ,out .data (),p ); 340 std::vector < float > w2 (128 ); 341decode_blocks (type ,out .data (),1 ,w2 .data ()); 342const bool same = std::memcmp (w .data (),w2 .data (),512 )== 0 ; 343exact_ok += (r .err == 0.0 && same ); 344CHECK (r .err == 0.0 && same ,"%s exact search missed a planted solution (err %g)" ,tname (type ),r .err ); 345p .exact = 0 ; 346p .ncand = 1 ; 347r = encode_block (type ,w .data (),nullptr ,out .data (),p ); 348approx_ok1 += r .err == 0.0 ; 349approx_err_sum += r .err ; 350p .ncand = 3 ; 351r = encode_block (type ,w .data (),nullptr ,out .data (),p ); 352approx_ok3 += r .err == 0.0 ; 353 } 354 std::printf (" %-6s exact: %d/%d recovered; approximate (rotation 16): %d/%d (err/energy %.2e); best of 3 rotations: %d/%d\n" , 355tname (type ),exact_ok ,N ,approx_ok1 ,N ,approx_err_sum /wsum ,approx_ok3 ,N ); 356 } 357} 358 359static uint16_t q8_scale (const std::vector < float >& x ,int b ) { 360float amax = 0 ; 361for (int j = 0 ;j < 32 ;++ j )amax = std::max (amax , std::fabs (x [32 * b + j ])); 362return float_to_half (amax /127.f ); 363} 364 365static void t7 () { 366 std::printf ("T7 encoder reconstruction == decoder, kernels vs dense\n" ); 367for (int type :kTypes ) { 368const int K = type_kbits (type ),bb = block_bytes (type ); 369const int rows = 24 ,n = 512 ,nbr = n /128 ; 370 std::vector < float > w ((size_t )rows * n ); 371for (int r = 0 ;r < rows ;++ r ) 372for (int i = 0 ;i < n ;++ i ) { 373float v = gauss ()* 0.02f * (1.f + (r %5 )); 374if (r == 3 )v = (i %97 == 0 ) ?1.5f :0.001f * gauss ();// spiky row 375if (r == 4 )v = 0.f ;// zero row 376if (r == 5 )v *=300.f ;// big 377w [(size_t )r * n + i ]= v ; 378 } 379 std::vector < uint8_t > enc ((size_t )rows * nbr * bb ); 380int64_t nf = 0 ,zb = 0 ; 381 std::vector < double > errs ((size_t )rows * nbr ); 382Params p ; 383const double tot = encode_blocks (type ,w .data (),nullptr , (int64_t )rows * nbr ,enc .data (),p ,8 ,errs .data (),& nf ,& zb ); 384 (void )tot ; 385// decoder reference: tq_states.hpp + the state table 386const int16_t * tab = kc::tq_state_table_for (type ); 387 std::vector < float > ref ((size_t )rows * n ),ours ((size_t )rows * n ); 388for (int64_t b = 0 ;b < (int64_t )rows * nbr ;++ b ) { 389const uint8_t * blk = enc .data ()+ b * bb ; 390const float d = kc::tq_detail::tq_half_to_float (kc::tq_detail::tq_ld16 (blk )); 391uint32_t st [32 ]; 392states_repo_k (K ,blk + 2 ,st ); 393for (int t = 0 ;t < 32 ;++ t ) 394for (int j = 0 ;j < 4 ;++ j )ref [b * 128 + 4 * t + j ]= d * ((float )tab [4 * st [t ]+ j ]* (1.0f /8192.0f )); 395 } 396decode_blocks (type ,enc .data (), (int64_t )rows * nbr ,ours .data ()); 397CHECK (std::memcmp (ref .data (),ours .data (),ref .size ()* 4 )== 0 ,"%s decode != tq_states + state table" ,tname (type )); 398// the encoder's own error equals the error of the decoded weights 399double worst = 0 ; 400for (int64_t b = 0 ;b < (int64_t )rows * nbr ;++ b ) { 401double e = 0 ; 402for (int i = 0 ;i < 128 ;++ i ) {const double d = (double )w [b * 128 + i ]- ref [b * 128 + i ];e += d * d ; } 403worst = std::max (worst , std::fabs (e - errs [b ]) / std::max (1e-30 ,e + errs [b ])); 404 } 405CHECK (worst < 1e-9 ,"%s encoder error != decoded error (%.3e)" ,tname (type ),worst ); 406// kernels (scalar, AVX2, AVX-512 where present) vs the dense dot with the dequantized Q8_0 activation 407 std::vector < float > x (n ); 408for (auto & v :x )v = gauss (); 409 std::vector < uint8_t > q8 ((size_t ) (n /32 )* 34 ); 410 std::vector < float > xd (n ); 411for (int b = 0 ;b < n /32 ;++ b ) { 412const uint16_t dh = q8_scale (x ,b ); 413const float d = half_to_float (dh ); 414q8 [34 * b ]= (uint8_t ) (dh & 255 ); 415q8 [34 * b + 1 ]= (uint8_t ) (dh >>8 ); 416for (int j = 0 ;j < 32 ;++ j ) { 417const int q = d == 0.f ?0 : (int ) std::lround (x [32 * b + j ] /d ); 418q8 [34 * b + 2 + j ]= (uint8_t ) (int8_t ) std::max (-127 , std::min (127 ,q )); 419xd [32 * b + j ]= d * (float ) (int8_t )q8 [34 * b + 2 + j ]; 420 } 421 } 422const void * ap [1 ]= {q8 .data ()}; 423for (kc::TqIsa isa : {kc::TqIsa ::scalar , kc::TqIsa ::avx2 , kc::TqIsa ::avx512 }) { 424if (!kc::tq_isa_ok (isa ))continue ; 425 std::vector < float > out (rows ); 426float * op [1 ]= {out .data ()}; 427 kc::tq_rows (isa ,type ,enc .data (), (size_t )nbr * bb ,n ,ap ,1 ,op ,0 ,rows ); 428double worst_rel = 0 ; 429for (int r = 0 ;r < rows ;++ r ) { 430double dsum = 0 ,mag = 0 ; 431for (int i = 0 ;i < n ;++ i ) { 432dsum += (double )ref [(size_t )r * n + i ]* xd [i ]; 433mag += std::fabs ((double )ref [(size_t )r * n + i ]* xd [i ]); 434 } 435worst_rel = std::max (worst_rel , std::fabs (dsum - out [r ]) / (mag + 1e-30 )); 436 } 437 std::printf (" %-6s %-6s kernel vs dense dot of the decoded weights: worst error %.2e of sum|w a|\n" ,tname (type ), 438 kc::tq_isa_name (isa ),worst_rel ); 439CHECK (worst_rel < 1e-5 ,"%s %s" ,tname (type ), kc::tq_isa_name (isa )); 440 } 441 std::printf (" %-6s decode == tq_states+table: bit-exact, %zu weights; zero blocks %lld\n" ,tname (type ),ref .size (), (long long )zb ); 442 } 443} 444 445static void t8 () { 446 std::printf ("T8 specials\n" ); 447for (int type :kTypes ) { 448const int bb = block_bytes (type ); 449 std::vector < uint8_t > out (bb ),z (bb ,0 ); 450 std::vector < float > w (128 ),dec (128 ); 451Params p ; 452// zero block 453 std::fill (w .begin (),w .end (),0.f ); 454BlockResult r = encode_block (type ,w .data (),nullptr ,out .data (),p ); 455CHECK (r .status == 1 && out == z ,"%s zero block must be canonical all-zero bytes" ,tname (type )); 456w [5 ]= -0.f ; 457r = encode_block (type ,w .data (),nullptr ,out .data (),p ); 458CHECK (r .status == 1 && out == z ,"%s negative zero" ,tname (type )); 459decode_blocks (type ,out .data (),1 ,dec .data ()); 460for (float v :dec )CHECK (v == 0.f ,"zero block decodes to 0" ); 461// scales: from the smallest subnormal weights to beyond fp16 462const float mags []= {1e-9f ,3e-8f ,1e-7f ,6e-5f ,1e-3f ,1.f ,100.f ,3000.f ,30000.f ,60000.f ,65000.f ,1e5f ,1e7f }; 463for (float mag :mags ) { 464for (int i = 0 ;i < 128 ;++ i )w [i ]= mag * gauss (); 465r = encode_block (type ,w .data (),nullptr ,out .data (),p ); 466const uint16_t dh = (uint16_t ) (out [0 ] | (out [1 ] <<8 )); 467const float d = half_to_float (dh ); 468CHECK (std::isfinite (d )&& d >=0.f ,"%s scale %g not finite for magnitude %g" ,tname (type ),d ,mag ); 469decode_blocks (type ,out .data (),1 ,dec .data ()); 470double e = 0 ,en = 0 ; 471bool fin = true; 472for (int i = 0 ;i < 128 ;++ i ) {fin &= std::isfinite (dec [i ]);e += (w [i ]- dec [i ])* (double ) (w [i ]- dec [i ]);en += (double )w [i ]* w [i ]; } 473CHECK (fin ,"decoded nonfinite" ); 474 std::printf (" %-6s magnitude %-8g d=%-12g rel err %.3f status %d\n" ,tname (type ),mag ,d ,e / std::max (en ,1e-300 ),r .status ); 475if (mag >=1e-3f && mag <=60000.f )CHECK (e /en < 0.5 ,"%s error too large at magnitude %g (%.3f)" ,tname (type ),mag ,e /en ); 476 } 477// constant, spike, alternating, power of two 478for (int variant = 0 ;variant < 4 ;++ variant ) { 479for (int i = 0 ;i < 128 ;++ i ) 480w [i ]= variant == 0 ?0.37f :variant == 1 ? (i == 77 ?5.f :0.f ) :variant == 2 ? (i & 1 ?1.f :-1.f ) : std::ldexp (1.f ,-3 ); 481r = encode_block (type ,w .data (),nullptr ,out .data (),p ); 482decode_blocks (type ,out .data (),1 ,dec .data ()); 483double e = 0 ,en = 0 ; 484for (int i = 0 ;i < 128 ;++ i ) {e += (w [i ]- dec [i ])* (double ) (w [i ]- dec [i ]);en += (double )w [i ]* w [i ]; } 485 std::printf (" %-6s pattern %d rel err %.4f\n" ,tname (type ),variant ,e /en ); 486CHECK (e /en < 0.8 ,"%s pattern %d" ,tname (type ),variant ); 487 } 488// non-finite input 489for (int i = 0 ;i < 128 ;++ i )w [i ]= gauss (); 490w [17 ]= INFINITY ; 491r = encode_block (type ,w .data (),nullptr ,out .data (),p ); 492CHECK (r .status == 2 && out == z ,"%s inf input" ,tname (type )); 493w [17 ]= NAN ; 494r = encode_block (type ,w .data (),nullptr ,out .data (),p ); 495CHECK (r .status == 2 && out == z ,"%s nan input" ,tname (type )); 496 } 497// determinism over thread counts 498 { 499const int type = TQK6 ,nbl = 64 ,bb = block_bytes (type ); 500 std::vector < float > w ((size_t )nbl * 128 ); 501for (auto & v :w )v = gauss (); 502 std::vector < uint8_t > a ((size_t )nbl * bb ),b (a .size ()); 503Params p ; 504encode_blocks (type ,w .data (),nullptr ,nbl ,a .data (),p ,1 ,nullptr ,nullptr ,nullptr ); 505encode_blocks (type ,w .data (),nullptr ,nbl ,b .data (),p ,7 ,nullptr ,nullptr ,nullptr ); 506CHECK (a == b ,"1 thread vs 7 threads differ" ); 507 } 508} 509 510static void t9 () { 511 std::printf ("T9 quality on N(0,1) blocks (SQNR in dB; the rate-distortion limit of the K/4 bits per weight is 6.02 * K/4)\n" ); 512for (int type :kTypes ) { 513const int K = type_kbits (type ),bb = block_bytes (type ); 514const int nbl = (type == TQ2_T || type == TQK7 ) ?256 :384 ; 515 std::vector < float > w ((size_t )nbl * 128 ); 516for (auto & v :w )v = gauss (); 517 std::vector < uint8_t > out ((size_t )nbl * bb ); 518double en = 0 ; 519for (float v :w )en += (double )v * v ; 520struct Cfg {const char * name ;Params p ;int th ; }; 521Cfg cfgs [5 ]; 522cfgs [0 ]= {"1 pass, scale from rms" ,Params {0 ,1 ,0 ,1 ,0 },8 }; 523cfgs [1 ]= {"default (rot 16, 3 scale rounds)" ,Params {},8 }; 524cfgs [2 ]= {"3 rotations, 3 scale rounds" ,Params {3 ,3 ,0 ,1 ,0 },8 }; 525cfgs [3 ]= {"3 rotations, 3 starting scales" ,Params {3 ,3 ,0 ,3 ,0 },8 }; 526int ncfg = 4 ; 527for (int i = 0 ;i < ncfg ;++ i ) { 528const auto t0 = std::chrono::steady_clock::now (); 529const double e = encode_blocks (type ,w .data (),nullptr ,nbl ,out .data (),cfgs [i ].p ,cfgs [i ].th ,nullptr ,nullptr ,nullptr ); 530const double sec = std::chrono::duration < double > (std::chrono::steady_clock::now ()- t0 ).count (); 531const double sq = 10.0 * std::log10 (en /e ); 532 std::printf (" %-6s %-34s SQNR %.3f dB (limit %.2f, gap %.2f dB) %.0f weights/s (%d threads)\n" ,tname (type ), 533cfgs [i ].name ,sq ,6.0206 * K /4.0 ,6.0206 * K /4.0 - sq , (double )nbl * 128 /sec ,cfgs [i ].th ); 534 } 535// approximate vs exact start group at the default scale rounds on a few blocks 536 { 537const int nb2 = type == TQK4X ?2 :8 ; 538Params pe ; 539pe .exact = 1 ; 540pe .iters = 0 ; 541Params pa ; 542pa .iters = 0 ; 543const double ee = encode_blocks (type ,w .data (),nullptr ,nb2 ,out .data (),pe ,8 ,nullptr ,nullptr ,nullptr ); 544const double ea = encode_blocks (type ,w .data (),nullptr ,nb2 ,out .data (),pa ,8 ,nullptr ,nullptr ,nullptr ); 545 std::printf (" %-6s tail-biting search, %d blocks, one scale: approximate error / exact error = %.4f\n" ,tname (type ),nb2 ,ea /ee ); 546CHECK (ea >=ee * (1 - 1e-6 ),"approximate beat exact?" ); 547 } 548 } 549} 550 551int main (int argc ,char ** argv ) { 552const bool quick = argc > 1 && std::strcmp (argv [1 ],"--quick" )== 0 ; 553t1 (); 554t2 (); 555t3 (); 556t5 (); 557t4 (); 558t6 (); 559t7 (); 560t8 (); 561if (!quick )t9 (); 562 std::printf ("\n%d checks, %d failures\n" ,g_checks ,g_fail ); 563return g_fail ?1 :0 ; 564}