okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
28ce98bf1
main
1// tools/trellis/tqenc.cpp - see tqenc.hpp. 2#include "tqenc.hpp" 3 4#include "ggml-common-tq.h" 5#include "tq_computed.hpp" 6 7#include <algorithm> 8#include <atomic> 9#include <cmath> 10#include <cstdlib> 11#include <cstring> 12#include <memory> 13#include <mutex> 14#include <thread> 15#include <vector> 16 17#if defined(__AVX2__ )&& defined(__FMA__ ) 18#include <immintrin.h> 19#define TQENC_AVX2 1 20#endif 21 22namespace tqenc { 23namespace { 24 25constexpr float kInf = 1e30f ; 26 27// --------------------------------------------------------------------------------------------------------------- 28// fp16 29 30}// namespace 31 32float half_to_float (uint16_t h ) { 33const uint32_t sign = (uint32_t ) (h & 0x8000u ) <<16 ; 34uint32_t exp = (h >>10 )& 0x1fu ,man = h & 0x3ffu ,bits ; 35if (exp == 0x1fu ) { 36bits = sign |0x7f800000u | (man <<13 ); 37 }else if (exp != 0 ) { 38bits = sign | ((exp + 112u ) <<23 ) | (man <<13 ); 39 }else if (man == 0 ) { 40bits = sign ; 41 }else { 42const float m = (float )man * (1.0f /16777216.0f ); 43return sign ?- m :m ; 44 } 45float f ; 46 std::memcpy (& f ,& bits ,4 ); 47return f ; 48} 49 50uint16_t float_to_half (float f ) { 51uint32_t x ; 52 std::memcpy (& x ,& f ,4 ); 53const uint32_t sign = (x >>16 )& 0x8000u ; 54const uint32_t ax = x & 0x7fffffffu ; 55if (ax >=0x7f800000u )return (uint16_t ) (sign |0x7c00u | (ax > 0x7f800000u ?0x200u :0u ));// inf / nan 56if (ax >=0x477ff000u )return (uint16_t ) (sign |0x7c00u );// >= 65520 rounds to inf 57if (ax < 0x33000001u )return (uint16_t )sign ;// <= 2^-25: rounds to zero (ties to even) 58int e = (int ) (ax >>23 )- 127 ; 59uint32_t man = (ax & 0x7fffffu ) |0x800000u ; 60if (e < -14 ) {// subnormal half 61const int shift = -14 - e + 13 ;// total right shift of the 24-bit mantissa 62const uint32_t half = 1u << (shift - 1 ),rest = man & ((1u <<shift )- 1 ); 63uint32_t q = man >>shift ; 64if (rest > half || (rest == half && (q & 1 )))++ q ; 65return (uint16_t ) (sign |q ); 66 } 67uint32_t q = ((uint32_t ) (e + 15 ) <<10 ) | ((man >>13 )& 0x3ffu ); 68const uint32_t rest = man & 0x1fffu ; 69if (rest > 0x1000u || (rest == 0x1000u && (q & 1 )))++ q ;// a carry into the exponent is correct 70return (uint16_t ) (sign |q ); 71} 72 73int type_kbits (int type ) { 74switch (type ) { 75case TQ2_T :return 8 ; 76case TQK6 :return 6 ; 77case TQK7 :return 7 ; 78case TQK5X :case TQK5T :return 5 ; 79case TQK4X :case TQK4T :return 4 ; 80default :return 0 ; 81 } 82} 83 84bool type_computed (int type ) {return type == TQK5X || type == TQK4X ; } 85 86double codebook_rms (int type ); 87 88namespace { 89 90// --------------------------------------------------------------------------------------------------------------- 91// codebook: the decoder's int16 table (round half away from zero of fp16 * 8192, as tq_cpu.cpp fill_table), SoA floats 92 93struct Codebook { 94int16_t tab [kStates * 4 ]; 95 alignas(64 )float soa [4 ][kStates ]; 96double rms = 1.072 ;// of the weights: the first scale guess is rms(block) / this 97explicit Codebook (bool computed ) { 98if (computed ) {// tq_computed.hpp 99double ss = 0 ; 100for (uint32_t s = 0 ;s < (uint32_t )kStates ;++ s ) { 101 strata::kernels::cpu::tq_detail::comp_state4 (s ,tab + 4 * s ); 102for (int j = 0 ;j < 4 ;++ j ) { 103soa [j ][s ]= (float )tab [4 * s + j ]* (1.0f /8192.0f ); 104ss += (double )soa [j ][s ]* soa [j ][s ]; 105 } 106 } 107rms = std::sqrt (ss / (4.0 * kStates )); 108return ; 109 } 110double ss = 0 ; 111for (uint32_t s = 0 ;s < (uint32_t )kStates ;++ s ) { 112const uint32_t x = s * 0x9e3779b1u ; 113const uint32_t pts [2 ]= {x >>21 , (x >>10 )& 2047u }; 114for (int h = 0 ;h < 2 ;++ h ) 115for (int j = 0 ;j < 2 ;++ j ) { 116const float v = half_to_float (tq_lut_f16 [2 * pts [h ]+ j ])* 8192.0f ; 117const int16_t q = (int16_t ) (v < 0.0f ?v - 0.5f :v + 0.5f ); 118tab [4 * s + 2 * h + j ]= q ; 119soa [2 * h + j ][s ]= (float )q * (1.0f /8192.0f ); 120ss += (double )soa [2 * h + j ][s ]* soa [2 * h + j ][s ]; 121 } 122 } 123rms = std::sqrt (ss / (4.0 * kStates )); 124 } 125}; 126 127const Codebook & cb (bool computed ) { 128static const Codebook table (false),comp (true); 129return computed ?comp :table ; 130} 131 132struct Geo { 133const Codebook * cbk = nullptr ; 134int K = 0 ; 135bool t2 = false;// TQ2_T (byte stream, the other shift direction) 136int G = 0 ;// predecessor groups 137}; 138 139Geo geo_for (int type ) { 140Geo g ; 141g .cbk = & cb (type_computed (type )); 142g .K = type_kbits (type ); 143g .t2 = type == TQ2_T ; 144g .G = g .t2 ?128 : (1 << (15 - g .K )); 145return g ; 146} 147 148// group of a state as a successor / as a predecessor 149inline int gsucc (const Geo & g ,uint32_t s ) {return g .t2 ? (int ) (s >>8 ) : (int ) (s & (uint32_t ) (g .G - 1 )); } 150inline int gpred (const Geo & g ,uint32_t s ) {return g .t2 ? (int ) (s & 0x7f ) : (int ) (s >>g .K ); } 151 152// weight index (0..127) of component j of processing position p 153inline int widx (const Geo & g ,int p ,int j ) {return g .t2 ?4 * p + j :4 * (31 - p )+ j ; } 154 155struct Scratch { 156 alignas(64 )float D [2 ][kStates ];// the two live columns of the DP 157 alignas(64 )uint16_t bp [32 ][2048 ];// per step and predecessor group: the best predecessor state 158 alignas(64 )float m [2048 ]; 159 alignas(64 )int32_t am [2048 ]; 160 alignas(64 )float zero [kStates ]; 161}; 162 163Scratch & scratch () { 164 thread_local std::unique_ptr < Scratch > s ; 165if (!s ) { 166s .reset (new Scratch ); 167 std::memset (s -> zero ,0 ,sizeof s -> zero ); 168 std::memset (s -> m ,0 ,sizeof s -> m ); 169 } 170return * s ; 171} 172 173inline float min_range (const float * p ,int n ) { 174#if TQENC_AVX2 175if (n >=8 ) { 176__m256 v = _mm256_loadu_ps (p ); 177for (int i = 8 ;i + 8 <=n ;i += 8 )v = _mm256_min_ps (v ,_mm256_loadu_ps (p + i )); 178__m128 a = _mm_min_ps (_mm256_castps256_ps128 (v ),_mm256_extractf128_ps (v ,1 )); 179a = _mm_min_ps (a ,_mm_movehl_ps (a ,a )); 180a = _mm_min_ss (a ,_mm_shuffle_ps (a ,a ,1 )); 181return _mm_cvtss_f32 (a ); 182 } 183#endif 184float m = p [0 ]; 185for (int i = 1 ;i < n ;++ i )m = std::min (m ,p [i ]); 186return m ; 187} 188 189// out[i] = add[i] + sum_j h_j (t_j - cb_j[s0 + i])^2 for i in [0, n) 190inline void step_cost (const Codebook & C ,float * out ,const float * add ,int s0 ,int n ,const float * t ,const float * h ) { 191const float * c0 = C .soa [0 ]+ s0 ,* c1 = C .soa [1 ]+ s0 ,* c2 = C .soa [2 ]+ s0 ,* c3 = C .soa [3 ]+ s0 ; 192int i = 0 ; 193#if TQENC_AVX2 194const __m256 t0 = _mm256_set1_ps (t [0 ]),t1 = _mm256_set1_ps (t [1 ]),t2 = _mm256_set1_ps (t [2 ]),t3 = _mm256_set1_ps (t [3 ]); 195const __m256 h0 = _mm256_set1_ps (h [0 ]),h1 = _mm256_set1_ps (h [1 ]),h2 = _mm256_set1_ps (h [2 ]),h3 = _mm256_set1_ps (h [3 ]); 196for (;i + 8 <=n ;i += 8 ) { 197const __m256 e0 = _mm256_sub_ps (t0 ,_mm256_loadu_ps (c0 + i )),e1 = _mm256_sub_ps (t1 ,_mm256_loadu_ps (c1 + i )); 198const __m256 e2 = _mm256_sub_ps (t2 ,_mm256_loadu_ps (c2 + i )),e3 = _mm256_sub_ps (t3 ,_mm256_loadu_ps (c3 + i )); 199__m256 a = _mm256_fmadd_ps (_mm256_mul_ps (h0 ,e0 ),e0 ,_mm256_loadu_ps (add + i )); 200a = _mm256_fmadd_ps (_mm256_mul_ps (h1 ,e1 ),e1 ,a ); 201a = _mm256_fmadd_ps (_mm256_mul_ps (h2 ,e2 ),e2 ,a ); 202a = _mm256_fmadd_ps (_mm256_mul_ps (h3 ,e3 ),e3 ,a ); 203_mm256_storeu_ps (out + i ,a ); 204 } 205#endif 206for (;i < n ;++ i ) { 207const float e0 = t [0 ]- c0 [i ],e1 = t [1 ]- c1 [i ],e2 = t [2 ]- c2 [i ],e3 = t [3 ]- c3 [i ]; 208out [i ]= add [i ]+ h [0 ]* e0 * e0 + h [1 ]* e1 * e1 + h [2 ]* e2 * e2 + h [3 ]* e3 * e3 ; 209 } 210} 211 212// the broadcast variant: out[i] = a + cost(s0 + i) 213inline void step_cost_bc (const Codebook & C ,float * out ,float a ,int s0 ,int n ,const float * t ,const float * h ) { 214 alignas(32 )float tmp [256 ]; 215for (int i = 0 ;i < n ;++ i )tmp [i ]= a ; 216step_cost (C ,out ,tmp ,s0 ,n ,t ,h ); 217} 218 219// min and first index of the minimum over p[0..n) 220inline float min_arg_range (const float * p ,int n ,int * arg ) { 221const float m = min_range (p ,n ); 222int i = 0 ; 223#if TQENC_AVX2 224const __m256 vm = _mm256_set1_ps (m ); 225for (;i + 8 <=n ;i += 8 ) { 226const int mask = _mm256_movemask_ps (_mm256_cmp_ps (_mm256_loadu_ps (p + i ),vm ,_CMP_EQ_OQ )); 227if (mask ) {* arg = i + __builtin_ctz ((unsigned )mask );return m ; } 228 } 229#endif 230for (;i < n ;++ i ) 231if (p [i ]== m ) {* arg = i ;return m ; } 232* arg = 0 ; 233return m ; 234} 235 236// T[p][4]: targets of processing position p (weights / d), H[p][4]: importance. rot: the sequence is processed from 237// position rot (cyclically); fixed_c >= 0: tail-biting with the successor group of the first state and the predecessor 238// group of the last state both == fixed_c. Writes the states by position into st[32]; returns the path cost. 239float viterbi (const Geo & g ,const float (* T )[4 ],const float (* H )[4 ],int rot ,int fixed_c ,uint16_t * st ) { 240Scratch & sc = scratch (); 241const int K = g .K ,G = g .G ; 242float * cur = sc .D [0 ]; 243// q = 0 244 { 245const int p = rot & 31 ; 246step_cost (* g .cbk ,cur ,sc .zero ,0 ,kStates ,T [p ],H [p ]); 247if (fixed_c >=0 ) { 248if (g .t2 ) {// gsucc(s) = s >> 8 == c: the 256 states [c<<8, c<<8 + 256) allowed 249for (int s = 0 ;s < kStates ;++ s ) 250if ((s >>8 )!= fixed_c )cur [s ]= kInf ; 251 }else {// s & (G-1) == c 252for (int s = 0 ;s < kStates ;++ s ) 253if ((s & (G - 1 ))!= fixed_c )cur [s ]= kInf ; 254 } 255 } 256 } 257for (int q = 1 ;q < 32 ;++ q ) { 258const float * prev = cur ; 259cur = sc .D [q & 1 ]; 260const int p = (rot + q )& 31 ; 261float * m = sc .m ; 262uint16_t * bp = sc .bp [q ]; 263if (g .t2 ) { 264// m[a] = min over h of prev[a + 128 h], argmin h 265for (int a = 0 ;a < 128 ;++ a ) {m [a ]= prev [a ];sc .am [a ]= 0 ; } 266for (int h = 1 ;h < 256 ;++ h ) { 267const float * row = prev + 128 * h ; 268int a = 0 ; 269#if TQENC_AVX2 270const __m256i vh = _mm256_set1_epi32 (h ); 271for (;a + 8 <=128 ;a += 8 ) { 272const __m256 r = _mm256_loadu_ps (row + a ),mm = _mm256_loadu_ps (m + a ); 273const __m256 lt = _mm256_cmp_ps (r ,mm ,_CMP_LT_OQ );// strictly smaller: the first minimum stays 274_mm256_storeu_ps (m + a ,_mm256_blendv_ps (mm ,r ,lt )); 275const __m256i old = _mm256_loadu_si256 ((const __m256i * ) (sc .am + a )); 276_mm256_storeu_si256 ((__m256i * ) (sc .am + a ),_mm256_castps_si256 (_mm256_blendv_ps ( 277_mm256_castsi256_ps (old ),_mm256_castsi256_ps (vh ),lt ))); 278 } 279#endif 280for (;a < 128 ;++ a ) 281if (row [a ]< m [a ]) {m [a ]= row [a ];sc .am [a ]= h ; } 282 } 283for (int a = 0 ;a < 128 ;++ a )bp [a ]= (uint16_t ) (a + 128 * sc .am [a ]); 284for (int b = 0 ;b < 128 ;++ b )step_cost_bc (* g .cbk ,cur + 256 * b ,m [b ],256 * b ,256 ,T [p ],H [p ]); 285 }else { 286const int span = 1 <<K ; 287for (int a = 0 ;a < G ;++ a ) { 288int arg ; 289m [a ]= min_arg_range (prev + (size_t )a * span ,span ,& arg ); 290bp [a ]= (uint16_t ) ((a <<K )+ arg ); 291 } 292for (int base = 0 ;base < kStates ;base += G )step_cost (* g .cbk ,cur + base ,m ,base ,G ,T [p ],H [p ]); 293 } 294 } 295// final state 296const float * last = cur ; 297int best = -1 ; 298float bc = 3e38f ; 299if (fixed_c < 0 ) { 300for (int s = 0 ;s < kStates ;++ s ) 301if (last [s ]< bc ) {bc = last [s ];best = s ; } 302 }else if (g .t2 ) { 303for (int h = 0 ;h < 256 ;++ h ) { 304const int s = fixed_c + 128 * h ; 305if (last [s ]< bc ) {bc = last [s ];best = s ; } 306 } 307 }else { 308for (int i = 0 ;i < (1 <<K );++ i ) { 309const int s = (fixed_c <<K )+ i ; 310if (last [s ]< bc ) {bc = last [s ];best = s ; } 311 } 312 } 313if (best < 0 || bc >=kInf * 0.5f )return kInf ; 314uint32_t s = (uint32_t )best ; 315st [(rot + 31 )& 31 ]= (uint16_t )s ; 316for (int q = 31 ;q >=1 ;-- q ) { 317s = sc .bp [q ][gsucc (g ,s )]; 318st [(rot + q - 1 )& 31 ]= (uint16_t )s ; 319 } 320return bc ; 321} 322 323// junction group of a free pass: gpred of the state at orig position 31 (== gsucc of the state at position 0) 324inline int junction_group (const Geo & g ,const uint16_t * st ) {return gpred (g ,st [31 ]); } 325 326struct Search { 327const Geo * g ; 328const Params * p ; 329float T [32 ][4 ]; 330float H [32 ][4 ]; 331uint16_t st [32 ]; 332int passes = 0 ; 333 334// one tail-biting search at scale d (weights already divided: set_targets); returns the path cost in scaled units 335float run () { 336static const int rots [8 ]= {16 ,8 ,24 ,12 ,20 ,4 ,28 ,0 }; 337float best = kInf ; 338uint16_t tmp [32 ],free_st [32 ]; 339if (p -> exact ) { 340for (int c = 0 ;c < g -> G ;++ c ) { 341const float v = viterbi (* g ,T ,H ,0 ,c ,tmp ); 342++ passes ; 343if (v < best ) {best = v ; std::memcpy (st ,tmp ,sizeof tmp ); } 344 } 345return best ; 346 } 347int seen [8 ],ns = 0 ; 348const int nc = std::max (1 , std::min (p -> ncand ,8 )); 349for (int r = 0 ;r < nc ;++ r ) { 350viterbi (* g ,T ,H ,rots [r ],-1 ,free_st ); 351++ passes ; 352const int c = junction_group (* g ,free_st ); 353bool dup = false; 354for (int i = 0 ;i < ns ;++ i )dup |=seen [i ]== c ; 355if (dup )continue ; 356seen [ns ++ ]= c ; 357const float v = viterbi (* g ,T ,H ,0 ,c ,tmp ); 358++ passes ; 359if (v < best ) {best = v ; std::memcpy (st ,tmp ,sizeof tmp ); } 360 } 361return best ; 362 } 363}; 364 365void pack_stream (const Geo & g ,const uint16_t * st ,uint8_t * qs ) { 366const int K = g .K ; 367 std::memset (qs ,0 , (size_t )4 * K ); 368if (g .t2 ) { 369for (int t = 0 ;t < 32 ;++ t )qs [t ]= (uint8_t ) (st [t ]& 0xff ); 370return ; 371 } 372for (int u = 0 ;u < 32 ;++ u ) { 373const uint32_t x = st [u ]& ((1u <<K )- 1u ); 374for (int b = 0 ;b < K ;++ b ) 375if ((x >>b )& 1u )qs [(u * K + b ) >>3 ] |= (uint8_t ) (1u << ((u * K + b )& 7 )); 376 } 377} 378 379}// namespace 380 381float debug_viterbi (int type ,const float (* T )[4 ],const float (* H )[4 ],int rot ,int fixed_c ,uint16_t * st ) { 382return viterbi (geo_for (type ),T ,H ,rot ,fixed_c ,st ); 383} 384int debug_groups (int type ) {return geo_for (type ).G ; } 385int debug_widx (int type ,int p ,int j ) {return widx (geo_for (type ),p ,j ); } 386void debug_pack (int type ,const uint16_t * st ,uint8_t * qs ) {pack_stream (geo_for (type ),st ,qs ); } 387 388const float * codebook_state (int type ,uint32_t state ) { 389static thread_localfloat v [4 ]; 390for (int j = 0 ;j < 4 ;++ j )v [j ]= cb (type_computed (type )).soa [j ][state & 0x7fff ]; 391return v ; 392} 393 394const int16_t * codebook_table (int type ) {return cb (type_computed (type )).tab ; } 395double codebook_rms (int type ) {return cb (type_computed (type )).rms ; } 396 397const float * point_table () { 398static float pts [4096 ]; 399static std::once_flag once ; 400 std::call_once (once , [] { 401for (int i = 0 ;i < 4096 ;++ i ) { 402const float x = half_to_float (tq_lut_f16 [i ])* 8192.0f ; 403const int16_t q = (int16_t ) (x < 0.0f ?x - 0.5f :x + 0.5f ); 404pts [i ]= (float )q * (1.0f /8192.0f ); 405 } 406 }); 407return pts ; 408} 409 410uint32_t block_state (int type ,const uint8_t * qs ,int t ) { 411const int K = type_kbits (type ); 412if (type == TQ2_T )return (((uint32_t )qs [(t + 31 )& 31 ] <<8 ) |qs [t ])& 0x7fffu ; 413const int total = 32 * K ; 414uint32_t s = 0 ; 415for (int i = 0 ;i < 15 ;++ i ) { 416const int b = ((31 - t )* K + i ) %total ; 417s |= (uint32_t ) ((qs [b >>3 ] >> (b & 7 ))& 1u ) <<i ; 418 } 419return s ; 420} 421 422void decode_blocks (int type ,const uint8_t * src ,int64_t nblocks ,float * out ) { 423const int K = type_kbits (type ),bb = 2 + 4 * K ; 424for (int64_t b = 0 ;b < nblocks ;++ b ) { 425const uint8_t * blk = src + (size_t )b * bb ; 426const uint16_t dh = (uint16_t ) (blk [0 ] | (blk [1 ] <<8 )); 427const float d = half_to_float (dh ); 428for (int t = 0 ;t < 32 ;++ t ) { 429const uint32_t s = block_state (type ,blk + 2 ,t ); 430for (int j = 0 ;j < 4 ;++ j )out [b * 128 + 4 * t + j ]= d * cb (type_computed (type )).soa [j ][s ]; 431 } 432 } 433} 434 435BlockResult encode_block (int type ,const float * w ,const float * h ,uint8_t * dst ,const Params & prm ) { 436BlockResult r ; 437const Geo g = geo_for (type ); 438const int K = g .K ,bb = 2 + 4 * K ; 439 std::memset (dst ,0 , (size_t )bb ); 440double sumw2 = 0 ,sumhw2 = 0 ,amax = 0 ; 441for (int i = 0 ;i < 128 ;++ i ) { 442if (!std::isfinite (w [i ])|| (h && !std::isfinite (h [i ]))) {r .status = 2 ;r .err = NAN ;return r ; } 443const double hi = h ?h [i ] :1.0 ; 444sumw2 += (double )w [i ]* w [i ]; 445sumhw2 += hi * (double )w [i ]* w [i ]; 446amax = std::max (amax , (double ) std::fabs (w [i ])); 447 } 448if (amax == 0.0 ) {r .status = 1 ;return r ; } 449const double rms = std::sqrt (sumw2 /128.0 ); 450// initial scale: the codebook has unit-ish rms 451const double kCbRms = g .cbk -> rms ; 452static const double mult [7 ]= {1.0 ,0.9 ,1.1 ,0.8 ,1.2 ,0.7 ,1.3 }; 453 454Search se ; 455se .g = & g ; 456se .p = & prm ; 457for (int p = 0 ;p < 32 ;++ p ) 458for (int j = 0 ;j < 4 ;++ j )se .H [p ][j ]= h ?h [widx (g ,p ,j )] :1.0f ; 459 460double best_err = 1e300 ; 461uint16_t best_st [32 ]= {}; 462uint16_t best_d = 0 ; 463bool have = false; 464 465auto fit = [& ](const uint16_t * st ,uint16_t dh ,double & err ) { 466// err of (st, dh): sum h (w - d cv)^2 467const float d = half_to_float (dh ); 468double e = 0 ; 469for (int p = 0 ;p < 32 ;++ p ) 470for (int j = 0 ;j < 4 ;++ j ) { 471const int wi = widx (g ,p ,j ); 472const float rec = d * g .cbk -> soa [j ][st [p ]]; 473const double df = (double )w [wi ]- rec ; 474e += (h ?h [wi ] :1.0 )* df * df ; 475 } 476err = e ; 477 }; 478 479const int tries = prm .fixed_scale ?1 : std::max (1 , std::min (prm .scale_tries ,7 )); 480for (int tr = 0 ;tr < tries ;++ tr ) { 481double dd = rms /kCbRms * mult [tr ]; 482uint16_t dh = float_to_half ((float ) std::min (dd ,65504.0 )); 483if (dh == 0 )dh = 1 ;// the smallest subnormal: weights below ~3e-8 are noise at this scale 484if (prm .fixed_scale )dh = prm .fixed_scale ; 485for (int it = 0 ;it <= (prm .fixed_scale ?0 :prm .iters );++ it ) { 486const float d = half_to_float (dh ); 487for (int p = 0 ;p < 32 ;++ p ) 488for (int j = 0 ;j < 4 ;++ j )se .T [p ][j ]= w [widx (g ,p ,j )] /d ; 489if (se .run () >=kInf * 0.5f )break ; 490double e ; 491fit (se .st ,dh ,e ); 492if (e < best_err ) { 493best_err = e ; 494best_d = dh ; 495 std::memcpy (best_st ,se .st ,sizeof best_st ); 496have = true; 497 } 498if (e == 0.0 || prm .fixed_scale )break ; 499// least-squares scale for this path 500double num = 0 ,den = 0 ; 501for (int p = 0 ;p < 32 ;++ p ) 502for (int j = 0 ;j < 4 ;++ j ) { 503const int wi = widx (g ,p ,j ); 504const double hi = h ?h [wi ] :1.0 ,c = g .cbk -> soa [j ][se .st [p ]]; 505num += hi * w [wi ]* c ; 506den += hi * c * c ; 507 } 508if (den <=0 || num <=0 )break ; 509uint16_t nh = float_to_half ((float ) std::min (num /den ,65504.0 )); 510if (nh == 0 || nh == dh )break ; 511double en ; 512fit (se .st ,nh ,en ); 513if (en < best_err ) { 514best_err = en ; 515best_d = nh ; 516 std::memcpy (best_st ,se .st ,sizeof best_st ); 517 } 518if (en >=e )break ;// the scale step did not help this path: stop refining this start 519dh = nh ; 520 } 521r .searches = se .passes ; 522 } 523if (!have || best_err >=sumhw2 ) {// nothing beats a zero block (weights below the fp16 scale resolution) 524 std::memset (dst ,0 , (size_t )bb ); 525r .status = 1 ; 526r .err = sumhw2 ; 527return r ; 528 } 529dst [0 ]= (uint8_t ) (best_d & 0xff ); 530dst [1 ]= (uint8_t ) (best_d >>8 ); 531pack_stream (g ,best_st ,dst + 2 ); 532r .err = best_err ; 533r .scale = half_to_float (best_d ); 534r .searches = se .passes ; 535return r ; 536} 537 538double encode_blocks (int type ,const float * w ,const float * h ,int64_t nblocks ,uint8_t * dst ,const Params & p , 539int nthreads ,double * err_out ,int64_t * nonfinite ,int64_t * zero_blocks ) { 540const int bb = block_bytes (type ); 541if (nthreads <=0 )nthreads = (int ) std::max (1u , std::thread::hardware_concurrency ()); 542nthreads = (int ) std::min < int64_t > (nthreads , std::max < int64_t > (1 ,nblocks )); 543 std::atomic < int64_t > next {0 },nf {0 },zb {0 }; 544 std::vector < double > sums ((size_t )nthreads ,0.0 ); 545auto work = [& ](int ti ) { 546double s = 0 ; 547for (;;) { 548const int64_t b0 = next .fetch_add (4 ); 549if (b0 >=nblocks )break ; 550const int64_t b1 = std::min (nblocks ,b0 + 4 ); 551for (int64_t b = b0 ;b < b1 ;++ b ) { 552const BlockResult r = encode_block (type ,w + b * 128 ,h ?h + b * 128 :nullptr ,dst + (size_t )b * bb ,p ); 553if (r .status == 2 ) {nf .fetch_add (1 ); } 554else s += r .err ; 555if (r .status == 1 )zb .fetch_add (1 ); 556if (err_out )err_out [b ]= r .err ; 557 } 558 } 559sums [ti ]= s ; 560 }; 561 std::vector < std::thread > th ; 562for (int i = 1 ;i < nthreads ;++ i )th .emplace_back (work ,i ); 563work (0 ); 564for (auto & t :th )t .join (); 565if (nonfinite )* nonfinite = nf .load (); 566if (zero_blocks )* zero_blocks = zb .load (); 567double tot = 0 ; 568for (double s :sums )tot += s ; 569return tot ; 570} 571 572}// namespace tqenc 573 574// --------------------------------------------------------------------------------------------------------------- 575// C API for the Python wrapper (tools/tqenc.py, ctypes) 576extern "C" { 577#if defined(_WIN32 ) 578#define TQE_EXPORT __declspec(dllexport) 579#else 580#define TQE_EXPORT __attribute__((visibility("default"))) 581#endif 582TQE_EXPORT int tqe_block_bytes (int type ) {return tqenc::block_bytes (type ); } 583TQE_EXPORT int tqe_kbits (int type ) {return tqenc::type_kbits (type ); } 584TQE_EXPORT void tqe_decode (int type ,const uint8_t * src ,int64_t nblocks ,float * out ) { 585 tqenc::decode_blocks (type ,src ,nblocks ,out ); 586} 587// returns the summed block error; stats[0] = nonfinite blocks, stats[1] = zero blocks 588TQE_EXPORT double tqe_encode (int type ,const float * w ,const float * h ,int64_t nblocks ,uint8_t * dst ,int iters , 589int ncand ,int exact ,int scale_tries ,int nthreads ,double * err_out ,int64_t * stats ) { 590 tqenc::Params p ; 591p .iters = iters ; 592p .ncand = ncand ; 593p .exact = exact ; 594p .scale_tries = scale_tries ; 595int64_t nf = 0 ,zb = 0 ; 596const double e = tqenc::encode_blocks (type ,w ,h ,nblocks ,dst ,p ,nthreads ,err_out ,& nf ,& zb ); 597if (stats ) {stats [0 ]= nf ;stats [1 ]= zb ; } 598return e ; 599} 600TQE_EXPORT const int16_t * tqe_table (int type ) {return tqenc::codebook_table (type ); } 601}