okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
28ce98bf1
main
1// tools/trellis/tqenc_hip.cpp - the trellis encoder (tqenc.hpp) on a GPU (HIP, gfx1201 / any wave32 RDNA): TQK4X / TQK5X / 2// TQK6 / TQK7 (TQ2_T stays CPU-only: its predecessor groups are strided across threads). 3// 4// One workgroup (512 threads) runs one Viterbi pass over one 128-weight block: thread t keeps the 64 path costs of the states 5// 64 t .. 64 t + 63 in registers. A step is (a) every thread takes the min/argmin of its predecessor groups (a group 6// is 2^K contiguous states, so never crosses a thread for K <= 7) and writes it to LDS plus the argmin to a global 7// back-pointer row, (b) after a barrier every thread sets its new costs D[s] = m[s & (G-1)] + c01[p0(s)] + c23[p1(s)]: 8// the cost of a state is the sum of the costs of its two hashed codebook points (2048 each), tabulated per step in LDS. 9// The same search as the CPU encoder (rotated free pass for the tail-biting start group, constrained pass, fp16 scale 10// refinement by least squares), batched over all blocks: every stage is one kernel over the whole batch. 11// 12// Build: hipcc -O3 --offload-arch=gfx1201 -mavx2 -mfma -mf16c tools/trellis/tqenc_hip.cpp tools/trellis/tqenc.cpp ... 13#include "tqenc.hpp" 14 15#include <hip/hip_runtime.h> 16#include <hip/hip_fp16.h> 17 18#include <algorithm> 19#include <chrono> 20#include <cmath> 21#include <cstdio> 22#include <cstdlib> 23#include <cstring> 24#include <vector> 25 26#define HCHECK (x ) \ 27 do { \ 28 hipError_t e_ = (x); \ 29 if (e_ != hipSuccess) { \ 30 std::fprintf(stderr, "HIP error %s at %s:%d: %s\n", #x, __FILE__, __LINE__, hipGetErrorString(e_)); \ 31 std::abort(); \ 32 } \ 33 } while (0) 34 35namespace { 36 37constexpr int kSL = 6 ;// log2 of the states per thread (64: 512 threads per workgroup) 38constexpr int NT = 32768 >>kSL ; 39constexpr float kInf = 1e30f ; 40 41__device__ __forceinline__ float h2f (uint16_t h ) {return __half2float (__ushort_as_half (h )); } 42__device__ __forceinline__ uint16_t f2h (float f ) {return __half_as_ushort (__float2half_rn (f )); } 43 44// weight index of component j at processing position p (TQK) 45__device__ __forceinline__ int widx_d (int p ,int j ) {return 4 * (31 - p )+ j ; } 46 47// the computed codebook of TQK5X / TQK4X (src/kernels/cpu/tq_computed.hpp): four fp16 from two LCG words, no table 48__device__ __forceinline__ void comp_vals (uint32_t s ,float * w ) { 49const uint32_t r0 = ((s * 89226354u + 64248484u )& 0x8FFF8FFFu ) ^0x3B603B60u ; 50const uint32_t r1 = ((s * 0x9E3779B1u + 0x7F4A7C15u )& 0x8FFF8FFFu ) ^0x3B603B60u ; 51w [0 ]= h2f ((uint16_t ) (r0 & 0xffffu )); 52w [1 ]= h2f ((uint16_t ) (r0 >>16 )); 53w [2 ]= h2f ((uint16_t ) (r1 & 0xffffu )); 54w [3 ]= h2f ((uint16_t ) (r1 >>16 )); 55} 56 57__device__ __forceinline__ float comp_cost (uint32_t s ,const float * t ,const float * h ) { 58float w [4 ]; 59comp_vals (s ,w ); 60const float e0 = t [0 ]- w [0 ],e1 = t [1 ]- w [1 ],e2 = t [2 ]- w [2 ],e3 = t [3 ]- w [3 ]; 61return h [0 ]* e0 * e0 + h [1 ]* e1 * e1 + h [2 ]* e2 * e2 + h [3 ]* e3 * e3 ; 62} 63 64struct Pass { 65const float * w ; 66const float * h ;// null: ones 67const uint16_t * dcur ;// fp16 scale per block 68const uint8_t * active ; 69int64_t nb ; 70int rot ; 71const int * cin ;// null: free pass, else the tail-biting group per block (<0: skip) 72const float2 * lutq ;// 2048 points 73uint16_t * bp_scratch ; 74uint16_t * st_out ;// constrained: [nb][32] by position 75float * cost_out ;// constrained: [nb] 76int * c_out ;// free: junction group [nb] 77}; 78 79template < int K ,int SL ,bool COMP > 80__global__ void __launch_bounds__ (32768 >>SL )pass_kernel (Pass P ) { 81constexpr int SPT = 1 <<SL ;// states per thread 82constexpr int NT = 32768 >>SL ;// threads per workgroup 83constexpr int G = 1 << (15 - K ); 84constexpr int SPAN = 1 <<K ; 85constexpr int GPT = SPT >=SPAN ?SPT /SPAN :1 ;// groups per thread (SPT >= SPAN) 86constexpr int PC = SPT >=SPAN ?1 :SPAN /SPT ;// threads sharing one group (SPAN > SPT) 87constexpr int NP = 2048 /NT ;// codebook points per thread 88__shared__ float tab [2 ][2 ][2048 ]; 89__shared__ float mbuf [2 ][G ]; 90__shared__ float Tt [32 ][4 ],Hh [32 ][4 ]; 91__shared__ float redv [NT /32 ]; 92__shared__ int redi [NT /32 ]; 93 94const int tid = threadIdx .x ; 95uint16_t * bp = P .bp_scratch + (size_t )blockIdx .x * 32 * G ; 96float2 L [NP ]; 97#pragma unroll 98for (int k = 0 ;k < NP ;++ k )L [k ]= P .lutq [tid + NT * k ]; 99const uint32_t kC = 0x9e3779b1u ; 100const uint32_t x0 = (uint32_t ) (SPT * tid )* kC ; 101 102for (int64_t b = blockIdx .x ;b < P .nb ;b += gridDim .x ) { 103if (!P .active [b ])continue ; 104int fc = -1 ; 105if (P .cin ) { 106fc = P .cin [b ]; 107if (fc < 0 )continue ; 108 } 109if (tid < 128 ) { 110const int p = tid >>2 ,j = tid & 3 ; 111const int wi = widx_d (p ,j ); 112const float dd = h2f (P .dcur [b ]); 113Tt [p ][j ]= P .w [b * 128 + wi ] /dd ; 114Hh [p ][j ]= P .h ?P .h [b * 128 + wi ] :1.0f ; 115 } 116__syncthreads (); 117 118float D [SPT ]; 119// tables of step q into parity q & 1 120auto build = [& ](int q ) { 121if constexpr (COMP )return ; 122const int p = (P .rot + q )& 31 ; 123const float t0 = Tt [p ][0 ],t1 = Tt [p ][1 ],t2 = Tt [p ][2 ],t3 = Tt [p ][3 ]; 124const float h0 = Hh [p ][0 ],h1 = Hh [p ][1 ],h2 = Hh [p ][2 ],h3 = Hh [p ][3 ]; 125#pragma unroll 126for (int k = 0 ;k < NP ;++ k ) { 127const float a0 = t0 - L [k ].x ,a1 = t1 - L [k ].y ,a2 = t2 - L [k ].x ,a3 = t3 - L [k ].y ; 128tab [q & 1 ][0 ][tid + NT * k ]= h0 * a0 * a0 + h1 * a1 * a1 ; 129tab [q & 1 ][1 ][tid + NT * k ]= h2 * a2 * a2 + h3 * a3 * a3 ; 130 } 131 }; 132build (0 ); 133__syncthreads (); 134 { 135float tc [4 ],hc [4 ]; 136if constexpr (COMP ) { 137const int p0 = P .rot & 31 ; 138for (int i = 0 ;i < 4 ;++ i ) {tc [i ]= Tt [p0 ][i ];hc [i ]= Hh [p0 ][i ]; } 139 } 140#pragma unroll 141for (int j = 0 ;j < SPT ;++ j ) { 142const uint32_t x = x0 + (uint32_t )j * kC ; 143float v ; 144if constexpr (COMP )v = comp_cost ((uint32_t ) (SPT * tid + j ),tc ,hc ); 145else v = tab [0 ][0 ][x >>21 ]+ tab [0 ][1 ][(x >>10 )& 2047u ]; 146if (fc >=0 && (((SPT * tid + j )& (G - 1 ))!= fc ))v = kInf ; 147D [j ]= v ; 148 } 149 } 150for (int q = 1 ;q < 32 ;++ q ) { 151const int par = q & 1 ; 152build (q ); 153// group minima of the previous column 154uint16_t * bpq = bp + (size_t )q * G ; 155if constexpr (SPT >=SPAN ) { 156#pragma unroll 157for (int g = 0 ;g < GPT ;++ g ) { 158float mv = D [g * SPAN ]; 159int ma = 0 ; 160#pragma unroll 161for (int e = 1 ;e < SPAN ;++ e ) { 162const float v = D [g * SPAN + e ]; 163if (v < mv ) {mv = v ;ma = e ; } 164 } 165const int a = ((SPT * tid ) >>K )+ g ; 166mbuf [par ][a ]= mv ; 167bpq [a ]= (uint16_t ) (SPT * tid + g * SPAN + ma ); 168 } 169 }else { 170// a group spans PC consecutive threads (the same wave): min/argmin of the thread, then across the PC 171float mv = D [0 ]; 172int ma = 0 ; 173#pragma unroll 174for (int e = 1 ;e < SPT ;++ e ) { 175const float v = D [e ]; 176if (v < mv ) {mv = v ;ma = e ; } 177 } 178int st = SPT * tid + ma ; 179#pragma unroll 180for (int off = 1 ;off < PC ;off <<=1 ) { 181const float ov = __shfl_xor (mv ,off ); 182const int os = __shfl_xor (st ,off ); 183if (ov < mv || (ov == mv && os < st )) {mv = ov ;st = os ; } 184 } 185if ((tid & (PC - 1 ))== 0 ) { 186const int a = (SPT * tid ) >>K ; 187mbuf [par ][a ]= mv ; 188bpq [a ]= (uint16_t )st ; 189 } 190 } 191__syncthreads (); 192const float4 * m4 = reinterpret_cast < const float4 *> (& mbuf [par ][(SPT * tid )& (G - 1 )]); 193// keep the compiler from caching the 2 * SPT hashed table addresses across the steps (they are loop invariant, 194// and 128 live registers spill): an empty asm makes x0 "new" every step 195uint32_t x0s = x0 ; 196 asmvolatile ("" :"+v" (x0s )); 197float tc [4 ],hc [4 ]; 198if constexpr (COMP ) { 199const int pq = (P .rot + q )& 31 ; 200for (int i = 0 ;i < 4 ;++ i ) {tc [i ]= Tt [pq ][i ];hc [i ]= Hh [pq ][i ]; } 201 } 202#pragma unroll 203for (int j4 = 0 ;j4 < SPT /4 ;++ j4 ) { 204const float4 mm = m4 [j4 ]; 205const uint32_t xa = x0s + (uint32_t ) (4 * j4 )* kC ; 206const uint32_t xb = xa + kC ,xc = xb + kC ,xd = xc + kC ; 207if constexpr (COMP ) { 208const uint32_t sa = (uint32_t ) (SPT * tid + 4 * j4 ); 209D [4 * j4 + 0 ]= mm .x + comp_cost (sa ,tc ,hc ); 210D [4 * j4 + 1 ]= mm .y + comp_cost (sa + 1 ,tc ,hc ); 211D [4 * j4 + 2 ]= mm .z + comp_cost (sa + 2 ,tc ,hc ); 212D [4 * j4 + 3 ]= mm .w + comp_cost (sa + 3 ,tc ,hc ); 213 }else { 214D [4 * j4 + 0 ]= mm .x + tab [par ][0 ][xa >>21 ]+ tab [par ][1 ][(xa >>10 )& 2047u ]; 215D [4 * j4 + 1 ]= mm .y + tab [par ][0 ][xb >>21 ]+ tab [par ][1 ][(xb >>10 )& 2047u ]; 216D [4 * j4 + 2 ]= mm .z + tab [par ][0 ][xc >>21 ]+ tab [par ][1 ][(xc >>10 )& 2047u ]; 217D [4 * j4 + 3 ]= mm .w + tab [par ][0 ][xd >>21 ]+ tab [par ][1 ][(xd >>10 )& 2047u ]; 218 } 219if ((j4 & 3 )== 3 )__builtin_amdgcn_sched_barrier (0 );// 16 states at a time: do not batch all the gathers 220 } 221 } 222// final state 223const int lo = fc < 0 ?0 : (fc <<K ),hi = fc < 0 ?32768 :lo + SPAN ; 224float bv = 3e38f ; 225int bi = -1 ; 226#pragma unroll 227for (int j = 0 ;j < SPT ;++ j ) { 228const int s = SPT * tid + j ; 229if (s >=lo && s < hi && D [j ]< bv ) {bv = D [j ];bi = s ; } 230 } 231#pragma unroll 232for (int off = 16 ;off >=1 ;off >>=1 ) { 233const float ov = __shfl_xor (bv ,off ); 234const int oi = __shfl_xor (bi ,off ); 235if (ov < bv || (ov == bv && oi >=0 && (bi < 0 || oi < bi ))) {bv = ov ;bi = oi ; } 236 } 237if ((tid & 31 )== 0 ) {redv [tid >>5 ]= bv ;redi [tid >>5 ]= bi ; } 238__syncthreads (); 239if (tid == 0 ) { 240float v = redv [0 ]; 241int i = redi [0 ]; 242for (int w2 = 1 ;w2 < NT /32 ;++ w2 ) 243if (redv [w2 ]< v || (redv [w2 ]== v && redi [w2 ] >=0 && (i < 0 || redi [w2 ]< i ))) {v = redv [w2 ];i = redi [w2 ]; } 244// traceback 245if (i < 0 || v >=kInf * 0.5f ) { 246if (P .cin )P .cost_out [b ]= kInf ;else P .c_out [b ]= 0 ; 247 }else if (!P .cin ) { 248const int qj = (31 - P .rot )& 31 ;// the step that processes position 31 249int s = i ; 250for (int q = 31 ;q > qj ;-- q )s = bp [(size_t )q * G + (s & (G - 1 ))]; 251P .c_out [b ]= s >>K ; 252 }else { 253int s = i ; 254P .st_out [b * 32 + ((P .rot + 31 )& 31 )]= (uint16_t )s ; 255for (int q = 31 ;q >=1 ;-- q ) { 256s = bp [(size_t )q * G + (s & (G - 1 ))]; 257P .st_out [b * 32 + ((P .rot + q - 1 )& 31 )]= (uint16_t )s ; 258 } 259P .cost_out [b ]= v ; 260 } 261 } 262__syncthreads (); 263 } 264} 265 266// ------------------------------------------------------------------------------------------------ per-block stages 267 268__device__ __forceinline__ void state_cb (const float2 * lutq ,int comp ,uint32_t s ,float * c ) { 269if (comp ) {comp_vals (s ,c );return ; } 270const uint32_t x = s * 0x9e3779b1u ; 271const float2 a = lutq [x >>21 ],b = lutq [(x >>10 )& 2047u ]; 272c [0 ]= a .x ;c [1 ]= a .y ;c [2 ]= b .x ;c [3 ]= b .y ; 273} 274 275__global__ void init_kernel (const float * w ,const float * h ,int64_t nb ,uint16_t * dcur ,uint8_t * active ,uint8_t * status , 276double * sumhw2 ,double mult ,int first ,uint16_t fixed_scale ,double cb_rms ) { 277const int64_t b = blockIdx .x * (int64_t )blockDim .x + threadIdx .x ; 278if (b >=nb )return ; 279double s2 = 0 ,sh2 = 0 ,amax = 0 ; 280bool fin = true; 281for (int i = 0 ;i < 128 ;++ i ) { 282const float x = w [b * 128 + i ]; 283const float hi = h ?h [b * 128 + i ] :1.0f ; 284if (!isfinite (x )|| !isfinite (hi ))fin = false; 285s2 += (double )x * x ; 286sh2 += (double )hi * x * x ; 287amax = fmax (amax ,fabs ((double )x )); 288 } 289if (first ) { 290status [b ]= !fin ?2 : (amax == 0.0 ?1 :0 ); 291sumhw2 [b ]= sh2 ; 292 } 293if (status [b ]!= 0 ) {active [b ]= 0 ;return ; } 294const double rms = sqrt (s2 /128.0 ); 295double dd = rms /cb_rms * mult ; 296uint16_t dh = f2h ((float )fmin (dd ,65504.0 )); 297if (dh == 0 )dh = 1 ; 298if (fixed_scale )dh = fixed_scale ; 299dcur [b ]= dh ; 300active [b ]= 1 ; 301} 302 303// error of (states by position st, fp16 scale dh) 304__device__ double fit_d (const float * w ,const float * h ,int64_t b ,const uint16_t * st ,uint16_t dh ,const float2 * lutq ,int comp ) { 305const float d = h2f (dh ); 306double e = 0 ; 307for (int p = 0 ;p < 32 ;++ p ) { 308float c [4 ]; 309state_cb (lutq ,comp ,st [p ],c ); 310for (int j = 0 ;j < 4 ;++ j ) { 311const int wi = widx_d (p ,j ); 312const float rec = d * c [j ]; 313const double df = (double )w [b * 128 + wi ]- rec ; 314e += (h ? (double )h [b * 128 + wi ] :1.0 )* df * df ; 315 } 316 } 317return e ; 318} 319 320// pick the best candidate, then the scale refinement step of encode_block 321__global__ void refine_kernel (const float * w ,const float * h ,int64_t nb ,int nc ,const uint16_t * st_c ,const float * cost_c , 322uint16_t * dcur ,uint8_t * active ,uint16_t * best_d ,double * best_err ,uint16_t * best_st , 323const float2 * lutq ,int fixed_scale ,int comp ) { 324const int64_t b = blockIdx .x * (int64_t )blockDim .x + threadIdx .x ; 325if (b >=nb || !active [b ])return ; 326int bc = -1 ; 327float bcost = kInf * 0.5f ; 328for (int r = 0 ;r < nc ;++ r ) { 329const float c = cost_c [(int64_t )r * nb + b ]; 330if (c < bcost ) {bcost = c ;bc = r ; } 331 } 332if (bc < 0 ) {active [b ]= 0 ;return ; } 333uint16_t st [32 ]; 334for (int p = 0 ;p < 32 ;++ p )st [p ]= st_c [((int64_t )bc * nb + b )* 32 + p ]; 335const uint16_t dh = dcur [b ]; 336const double e = fit_d (w ,h ,b ,st ,dh ,lutq ,comp ); 337if (e < best_err [b ]) { 338best_err [b ]= e ; 339best_d [b ]= dh ; 340for (int p = 0 ;p < 32 ;++ p )best_st [b * 32 + p ]= st [p ]; 341 } 342if (e == 0.0 || fixed_scale ) {active [b ]= 0 ;return ; } 343double num = 0 ,den = 0 ; 344for (int p = 0 ;p < 32 ;++ p ) { 345float c [4 ]; 346state_cb (lutq ,comp ,st [p ],c ); 347for (int j = 0 ;j < 4 ;++ j ) { 348const int wi = widx_d (p ,j ); 349const double hi = h ? (double )h [b * 128 + wi ] :1.0 ,cc = c [j ]; 350num += hi * w [b * 128 + wi ]* cc ; 351den += hi * cc * cc ; 352 } 353 } 354if (den <=0 || num <=0 ) {active [b ]= 0 ;return ; } 355const uint16_t nh = f2h ((float )fmin (num /den ,65504.0 )); 356if (nh == 0 || nh == dh ) {active [b ]= 0 ;return ; } 357const double en = fit_d (w ,h ,b ,st ,nh ,lutq ,comp ); 358if (en < best_err [b ]) { 359best_err [b ]= en ; 360best_d [b ]= nh ; 361for (int p = 0 ;p < 32 ;++ p )best_st [b * 32 + p ]= st [p ]; 362 } 363if (en >=e ) {active [b ]= 0 ;return ; } 364dcur [b ]= nh ; 365} 366 367__global__ void dedupe_kernel (int64_t nb ,int nc ,int * c_all ) { 368const int64_t b = blockIdx .x * (int64_t )blockDim .x + threadIdx .x ; 369if (b >=nb )return ; 370for (int r = 1 ;r < nc ;++ r ) { 371const int c = c_all [(int64_t )r * nb + b ]; 372for (int q = 0 ;q < r ;++ q ) 373if (c_all [(int64_t )q * nb + b ]== c ) {c_all [(int64_t )r * nb + b ]= -1 ;break ; } 374 } 375} 376 377__global__ void pack_kernel (int K ,int64_t nb ,const uint8_t * status ,const double * sumhw2 ,const uint16_t * best_d , 378const double * best_err ,const uint16_t * best_st ,uint8_t * dst ,double * err_out ) { 379const int64_t b = blockIdx .x * (int64_t )blockDim .x + threadIdx .x ; 380if (b >=nb )return ; 381const int bb = 2 + 4 * K ; 382uint8_t * o = dst + b * bb ; 383for (int i = 0 ;i < bb ;++ i )o [i ]= 0 ; 384if (status [b ]== 2 ) {err_out [b ]= NAN ;return ; } 385if (status [b ]== 1 || best_err [b ] >=sumhw2 [b ]) {err_out [b ]= status [b ]== 1 ?0.0 :sumhw2 [b ];return ; } 386o [0 ]= (uint8_t ) (best_d [b ]& 255 ); 387o [1 ]= (uint8_t ) (best_d [b ] >>8 ); 388uint8_t * qs = o + 2 ; 389for (int u = 0 ;u < 32 ;++ u ) { 390const uint32_t x = best_st [b * 32 + u ]& ((1u <<K )- 1u ); 391for (int bit = 0 ;bit < K ;++ bit ) 392if ((x >>bit )& 1u )qs [(u * K + bit ) >>3 ] |= (uint8_t ) (1u << ((u * K + bit )& 7 )); 393 } 394err_out [b ]= best_err [b ]; 395} 396 397__global__ void init_best_kernel (int64_t nb ,double * best_err ,uint8_t * have ) { 398const int64_t b = blockIdx .x * (int64_t )blockDim .x + threadIdx .x ; 399if (b >=nb )return ; 400best_err [b ]= 1e300 ; 401} 402 403template < int K ,bool COMP > 404void launch_pass (const Pass & P ,int grid ) { 405hipLaunchKernelGGL ((pass_kernel < K ,kSL ,COMP > ),dim3 (grid ),dim3 (NT ),0 ,0 ,P ); 406} 407 408void launch_pass_k (int K ,bool comp ,const Pass & P ,int grid ) { 409if (comp ) {// TQK5X / TQK4X 410if (K == 4 )launch_pass < 4 , true> (P ,grid ); 411else launch_pass < 5 , true> (P ,grid ); 412return ; 413 } 414switch (K ) { 415case 4 :launch_pass < 4 , false> (P ,grid );break ; 416case 5 :launch_pass < 5 , false> (P ,grid );break ; 417case 6 :launch_pass < 6 , false> (P ,grid );break ; 418default :launch_pass < 7 , false> (P ,grid );break ; 419 } 420} 421 422struct Dev { 423int device = 0 ; 424int nsm = 0 ; 425float2 * lutq = nullptr ; 426bool ready = false; 427}g_dev ; 428 429void ensure_dev (int device ) { 430if (g_dev .ready && g_dev .device == device )return ; 431HCHECK (hipSetDevice (device )); 432hipDeviceProp_t pr ; 433HCHECK (hipGetDeviceProperties (& pr ,device )); 434g_dev .device = device ; 435g_dev .nsm = pr .multiProcessorCount ; 436// the 2048 codebook points as the decoder sees them: round(fp16 * 8192) / 8192 (tq_cpu.cpp fill_table) 437 std::vector < float2 > pts (2048 ); 438const float * pt = tqenc::point_table (); 439for (int i = 0 ;i < 2048 ;++ i )pts [i ]= make_float2 (pt [2 * i ],pt [2 * i + 1 ]); 440if (g_dev .lutq )HCHECK (hipFree (g_dev .lutq )); 441HCHECK (hipMalloc (& g_dev .lutq ,2048 * sizeof (float2 ))); 442HCHECK (hipMemcpy (g_dev .lutq ,pts .data (),2048 * sizeof (float2 ),hipMemcpyHostToDevice )); 443g_dev .ready = true; 444} 445 446template < typename T > 447T * dalloc (size_t n ) { 448T * p = nullptr ; 449HCHECK (hipMalloc (& p ,n * sizeof (T ))); 450return p ; 451} 452 453}// namespace 454 455extern "C" { 456#if defined(_WIN32 ) 457#define TQH_EXPORT __declspec(dllexport) 458#else 459#define TQH_EXPORT __attribute__((visibility("default"))) 460#endif 461 462// GPU encode of nblocks blocks of TQK4X / 5X / 6 / 7. Same arguments as tqe_encode (iters, ncand, scale_tries; exact 463// search is CPU only). stats[0] = nonfinite blocks, stats[1] = zero blocks; timing[0] = kernel seconds, [1] = passes. 464TQH_EXPORT double tqh_encode (int type ,const float * w ,const float * h ,int64_t nblocks ,uint8_t * dst ,int iters ,int ncand , 465int scale_tries ,int device ,double * err_out ,int64_t * stats ,double * timing , 466int fixed_scale_bits ) { 467const int K = tqenc::type_kbits (type ); 468if (K < 4 || K > 7 )return -1.0 ; 469const bool comp = tqenc::type_computed (type ); 470const double cb_rms = tqenc::codebook_rms (type ); 471ensure_dev (device ); 472const int bb = 2 + 4 * K ,G = 1 << (15 - K ); 473const int nc = std::max (1 , std::min (ncand ,8 )); 474static const int rots [8 ]= {16 ,8 ,24 ,12 ,20 ,4 ,28 ,0 }; 475static const double mult [7 ]= {1.0 ,0.9 ,1.1 ,0.8 ,1.2 ,0.7 ,1.3 }; 476const int tries = fixed_scale_bits ?1 : std::max (1 , std::min (scale_tries ,7 )); 477const int64_t CH = 1 <<16 ; 478const int grid_cap = g_dev .nsm * 4 ; 479uint16_t * bp = dalloc < uint16_t > ((size_t )grid_cap * 32 * G ); 480double tot = 0 ; 481int64_t nf = 0 ,zb = 0 ; 482double ksec = 0 ; 483int64_t npass = 0 ; 484for (int64_t c0 = 0 ;c0 < nblocks ;c0 += CH ) { 485const int64_t nb = std::min (CH ,nblocks - c0 ); 486float * dw = dalloc < float > ((size_t )nb * 128 ); 487float * dh = h ?dalloc < float > ((size_t )nb * 128 ) :nullptr ; 488HCHECK (hipMemcpy (dw ,w + c0 * 128 , (size_t )nb * 128 * 4 ,hipMemcpyHostToDevice )); 489if (h )HCHECK (hipMemcpy (dh ,h + c0 * 128 , (size_t )nb * 128 * 4 ,hipMemcpyHostToDevice )); 490uint16_t * dcur = dalloc < uint16_t > (nb ); 491uint8_t * active = dalloc < uint8_t > (nb ); 492uint8_t * status = dalloc < uint8_t > (nb ); 493double * sumhw2 = dalloc < double > (nb ); 494uint16_t * best_d = dalloc < uint16_t > (nb ); 495double * best_err = dalloc < double > (nb ); 496uint16_t * best_st = dalloc < uint16_t > ((size_t )nb * 32 ); 497uint16_t * st_c = dalloc < uint16_t > ((size_t )nc * nb * 32 ); 498float * cost_c = dalloc < float > ((size_t )nc * nb ); 499int * c_all = dalloc < int > ((size_t )nc * nb ); 500uint8_t * d_dst = dalloc < uint8_t > ((size_t )nb * bb ); 501double * d_err = dalloc < double > (nb ); 502uint8_t * have = nullptr ; 503const int tb = 128 ,gb = (int ) ((nb + tb - 1 ) /tb ); 504hipLaunchKernelGGL (init_best_kernel ,dim3 (gb ),dim3 (tb ),0 ,0 ,nb ,best_err ,have ); 505const auto t0 = std::chrono::steady_clock::now (); 506for (int tr = 0 ;tr < tries ;++ tr ) { 507hipLaunchKernelGGL (init_kernel ,dim3 (gb ),dim3 (tb ),0 ,0 ,dw ,dh ,nb ,dcur ,active ,status ,sumhw2 ,mult [tr ], 508tr == 0 ?1 :0 , (uint16_t )fixed_scale_bits ,cb_rms ); 509for (int it = 0 ;it <= (fixed_scale_bits ?0 :iters );++ it ) { 510Pass P {}; 511P .w = dw ;P .h = dh ;P .dcur = dcur ;P .active = active ;P .nb = nb ;P .lutq = g_dev .lutq ;P .bp_scratch = bp ; 512const int grid = (int ) std::min < int64_t > (nb ,grid_cap ); 513for (int r = 0 ;r < nc ;++ r ) { 514P .rot = rots [r ];P .cin = nullptr ;P .c_out = c_all + (int64_t )r * nb ; 515launch_pass_k (K ,comp ,P ,grid ); 516 } 517hipLaunchKernelGGL (dedupe_kernel ,dim3 (gb ),dim3 (tb ),0 ,0 ,nb ,nc ,c_all ); 518HCHECK (hipMemset (cost_c ,0x7f , (size_t )nc * nb * sizeof (float )));// skipped candidates cost "infinity" 519for (int r = 0 ;r < nc ;++ r ) { 520P .rot = 0 ;P .cin = c_all + (int64_t )r * nb ;P .c_out = nullptr ; 521P .st_out = st_c + (int64_t )r * nb * 32 ;P .cost_out = cost_c + (int64_t )r * nb ; 522launch_pass_k (K ,comp ,P ,grid ); 523 } 524hipLaunchKernelGGL (refine_kernel ,dim3 (gb ),dim3 (tb ),0 ,0 ,dw ,dh ,nb ,nc ,st_c ,cost_c ,dcur ,active , 525best_d ,best_err ,best_st ,g_dev .lutq ,fixed_scale_bits ,comp ?1 :0 ); 526npass += 2 * nc ; 527if (std::getenv ("TQH_DEBUG" )) { 528HCHECK (hipDeviceSynchronize ()); 529int hc [4 ]= {};float hcost [4 ]= {};double he [4 ]= {};uint16_t hd [4 ]= {};uint8_t ha [4 ]= {}; 530HCHECK (hipMemcpy (hc ,c_all ,16 ,hipMemcpyDeviceToHost )); 531HCHECK (hipMemcpy (hcost ,cost_c ,16 ,hipMemcpyDeviceToHost )); 532HCHECK (hipMemcpy (he ,best_err ,32 ,hipMemcpyDeviceToHost )); 533HCHECK (hipMemcpy (hd ,dcur ,8 ,hipMemcpyDeviceToHost )); 534HCHECK (hipMemcpy (ha ,active ,4 ,hipMemcpyDeviceToHost )); 535for (int i = 0 ;i < 4 ;++ i ) 536 std::fprintf (stderr ,"[dbg try %d it %d] block %d: c %d cost %g best_err %g dcur %g active %d\n" ,tr ,it ,i ,hc [i ],hcost [i ],he [i ], 537 tqenc::half_to_float (hd [i ]),ha [i ]); 538 } 539 } 540 } 541hipLaunchKernelGGL (pack_kernel ,dim3 (gb ),dim3 (tb ),0 ,0 ,K ,nb ,status ,sumhw2 ,best_d ,best_err ,best_st ,d_dst ,d_err ); 542HCHECK (hipDeviceSynchronize ()); 543ksec += std::chrono::duration < double > (std::chrono::steady_clock::now ()- t0 ).count (); 544HCHECK (hipMemcpy (dst + (size_t )c0 * bb ,d_dst , (size_t )nb * bb ,hipMemcpyDeviceToHost )); 545 std::vector < double > herr (nb ); 546 std::vector < uint8_t > hst (nb ); 547HCHECK (hipMemcpy (herr .data (),d_err ,nb * 8 ,hipMemcpyDeviceToHost )); 548HCHECK (hipMemcpy (hst .data (),status ,nb ,hipMemcpyDeviceToHost )); 549for (int64_t i = 0 ;i < nb ;++ i ) { 550if (hst [i ]== 2 )++ nf ; 551else tot += herr [i ]; 552if (hst [i ]== 1 )++ zb ; 553if (err_out )err_out [c0 + i ]= herr [i ]; 554 } 555for (void * p : {(void * )dw , (void * )dh , (void * )dcur , (void * )active , (void * )status , (void * )sumhw2 , (void * )best_d , 556 (void * )best_err , (void * )best_st , (void * )st_c , (void * )cost_c , (void * )c_all , (void * )d_dst , 557 (void * )d_err }) 558if (p )HCHECK (hipFree (p )); 559 } 560HCHECK (hipFree (bp )); 561if (stats ) {stats [0 ]= nf ;stats [1 ]= zb ; } 562if (timing ) {timing [0 ]= ksec ;timing [1 ]= (double )npass ; } 563return tot ; 564} 565}