okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
c2b701be3
main
1// tools/vision/own/vit_ref.cpp - see vit_ref.h 2#include "vit_ref.h" 3 4#include <algorithm> 5#include <atomic> 6#include <cmath> 7#include <cstdlib> 8#include <cstring> 9#include <thread> 10 11namespace strata_vit { 12 13namespace { 14 15template < class F > 16void parallel_for (int n ,int nth ,F f ) { 17if (nth <=1 || n <=1 ) { 18for (int i = 0 ;i < n ;++ i )f (i ); 19return ; 20 } 21nth = std::min (nth ,n ); 22 std::atomic < int > next {0 }; 23auto worker = [& ]() { 24for (int i ; (i = next .fetch_add (1 ))< n ;)f (i ); 25 }; 26 std::vector < std::thread > ts ; 27ts .reserve ((size_t )nth - 1 ); 28for (int t = 1 ;t < nth ;++ t )ts .emplace_back (worker ); 29worker (); 30for (auto & t :ts )t .join (); 31} 32 33// R rows of A against two rows of W: out[r][c] = dot(a_r, w_c) 34template < int R > 35inline void tile (const float * a ,size_t lda ,const float * w0 ,const float * w1 ,int K ,float out [R ][2 ]) { 36float acc [R ][2 ][8 ]; 37for (int r = 0 ;r < R ;++ r ) 38for (int c = 0 ;c < 2 ;++ c ) 39for (int l = 0 ;l < 8 ;++ l )acc [r ][c ][l ]= 0.0f ; 40int k = 0 ; 41for (;k + 8 <=K ;k += 8 ) { 42for (int r = 0 ;r < R ;++ r ) { 43const float * ar = a + (size_t )r * lda + k ; 44for (int l = 0 ;l < 8 ;++ l ) { 45acc [r ][0 ][l ]+= ar [l ]* w0 [k + l ]; 46acc [r ][1 ][l ]+= ar [l ]* w1 [k + l ]; 47 } 48 } 49 } 50for (int r = 0 ;r < R ;++ r ) 51for (int c = 0 ;c < 2 ;++ c ) { 52float s = ((acc [r ][c ][0 ]+ acc [r ][c ][4 ])+ (acc [r ][c ][1 ]+ acc [r ][c ][5 ]))+ ((acc [r ][c ][2 ]+ acc [r ][c ][6 ])+ (acc [r ][c ][3 ]+ acc [r ][c ][7 ])); 53const float * w = c ?w1 :w0 ; 54for (int kk = k ;kk < K ;++ kk )s += a [(size_t )r * lda + kk ]* w [kk ]; 55out [r ][c ]= s ; 56 } 57} 58 59// C[M][N] = A[M][K] * W[N][K]^T (+ bias[N]); A rows lda apart, C rows ldc apart 60void gemm (const float * A ,size_t lda ,int M ,int K ,const float * W ,int N ,const float * bias ,float * C ,size_t ldc ,int nth ) { 61const int chunk = std::max (4 , ((M + nth * 2 - 1 ) / (nth * 2 )+ 3 ) /4 * 4 ); 62const int nchunks = (M + chunk - 1 ) /chunk ; 63parallel_for (nchunks ,nth , [& ](int ci ) { 64const int m0 = ci * chunk ,m1 = std::min (M ,m0 + chunk ); 65for (int n0 = 0 ;n0 < N ;n0 += 8 ) { 66const int n1 = std::min (N ,n0 + 8 ); 67for (int n = n0 ;n < n1 ;n += 2 ) { 68const bool two = n + 1 < N ; 69const float * w0 = W + (size_t )n * K ; 70const float * w1 = two ?w0 + K :w0 ; 71int m = m0 ; 72for (;m + 4 <=m1 ;m += 4 ) { 73float o [4 ][2 ]; 74tile < 4 > (A + (size_t )m * lda ,lda ,w0 ,w1 ,K ,o ); 75for (int r = 0 ;r < 4 ;++ r ) { 76C [(size_t ) (m + r )* ldc + n ]= o [r ][0 ]+ (bias ?bias [n ] :0.0f ); 77if (two )C [(size_t ) (m + r )* ldc + n + 1 ]= o [r ][1 ]+ (bias ?bias [n + 1 ] :0.0f ); 78 } 79 } 80for (;m < m1 ;++ m ) { 81float o [1 ][2 ]; 82tile < 1 > (A + (size_t )m * lda ,lda ,w0 ,w1 ,K ,o ); 83C [(size_t )m * ldc + n ]= o [0 ][0 ]+ (bias ?bias [n ] :0.0f ); 84if (two )C [(size_t )m * ldc + n + 1 ]= o [0 ][1 ]+ (bias ?bias [n + 1 ] :0.0f ); 85 } 86 } 87 } 88 }); 89} 90 91// y = LayerNorm(x) * w + b, per row of D, the sums in double (as ggml's norm) 92void layer_norm (const float * x ,float * y ,int rows ,int D ,const float * w ,const float * b ,float eps ,int nth ) { 93parallel_for (rows ,nth , [& ](int r ) { 94const float * xr = x + (size_t )r * D ; 95double s = 0 ; 96for (int i = 0 ;i < D ;++ i )s += xr [i ]; 97const float mean = (float ) (s /D ); 98double v = 0 ; 99for (int i = 0 ;i < D ;++ i ) {const double d = xr [i ]- mean ;v += d * d ; } 100const float scale = 1.0f / std::sqrt ((float ) (v /D )+ eps ); 101float * yr = y + (size_t )r * D ; 102for (int i = 0 ;i < D ;++ i )yr [i ]= (xr [i ]- mean )* scale * w [i ]+ b [i ]; 103 }); 104} 105 106inline float gelu_tanh (float x ) { 107return 0.5f * x * (1.0f + std::tanh (0.79788456080286535587989211986876f * x * (1.0f + 0.044715f * x * x ))); 108} 109 110void gelu_inplace (float * x ,size_t n ,int nth ) { 111const int blocks = (int ) ((n + 4095 ) /4096 ); 112parallel_for (blocks ,nth , [& ](int bi ) { 113const size_t i0 = (size_t )bi * 4096 ,i1 = std::min (n ,i0 + 4096 ); 114for (size_t i = i0 ;i < i1 ;++ i )x [i ]= gelu_tanh (x [i ]); 115 }); 116} 117 118inline float dot (const float * a ,const float * b ,int n ) { 119float acc [8 ]= {0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 }; 120int i = 0 ; 121for (;i + 8 <=n ;i += 8 ) 122for (int l = 0 ;l < 8 ;++ l )acc [l ]+= a [i + l ]* b [i + l ]; 123float s = ((acc [0 ]+ acc [4 ])+ (acc [1 ]+ acc [5 ]))+ ((acc [2 ]+ acc [6 ])+ (acc [3 ]+ acc [7 ])); 124for (;i < n ;++ i )s += a [i ]* b [i ]; 125return s ; 126} 127 128// round to nearest even to BF16 / F16 and back (the values a 16-bit GEMM input has) 129inline float round_bf16 (float f ) { 130uint32_t u ; 131 std::memcpy (& u ,& f ,4 ); 132if ((u & 0x7fffffffu )> 0x7f800000u )return f ; 133u += 0x7fffu + ((u >>16 )& 1u ); 134u &=0xffff0000u ; 135 std::memcpy (& f ,& u ,4 ); 136return f ; 137} 138 139inline float round_f16 (float f ) { 140uint32_t u ; 141 std::memcpy (& u ,& f ,4 ); 142const uint32_t sign = u & 0x80000000u ; 143const float a = std::fabs (f ); 144if (!(a < 65520.0f ))return f ;// inf, nan, and what rounds to inf are left alone (not met in a tower) 145if (a < 6.103515625e-05f ) {// subnormal half: a multiple of 2^-24 146const float q = std::nearbyint (a * 16777216.0f ) /16777216.0f ; 147return sign ?- q :q ; 148 } 149int e ; 150 std::frexp (a ,& e );// a = m * 2^e, m in [0.5, 1): the half's ulp is 2^(e-11) 151const float ulp = std::ldexp (1.0f ,e - 11 ); 152const float q = std::nearbyint (a /ulp )* ulp ; 153return sign ?- q :q ; 154} 155 156void round_inplace (float * p ,size_t n ,int kind ,int nth ) { 157if (kind == 0 )return ; 158const int blocks = (int ) ((n + 8191 ) /8192 ); 159parallel_for (blocks ,nth , [& ](int bi ) { 160const size_t i0 = (size_t )bi * 8192 ,i1 = std::min (n ,i0 + 8192 ); 161for (size_t i = i0 ;i < i1 ;++ i )p [i ]= kind == 1 ?round_bf16 (p [i ]) :round_f16 (p [i ]); 162 }); 163} 164 165bool read_t (const Gguf & gg ,const std::string & name , std::vector < float >& dst , std::string & err ) { 166const GgufTensorInfo * t = gg .tensor (name ); 167if (!t ) {err = "the mmproj file lacks the tensor " + name ;return false; } 168dst .resize ((size_t )t -> nelem ()); 169return gg .read_f32 (* t ,dst .data (),err ); 170} 171 172}// namespace 173 174double cosine (const float * a ,const float * b ,size_t n ) { 175double ab = 0 ,aa = 0 ,bb = 0 ; 176for (size_t i = 0 ;i < n ;++ i ) {ab += (double )a [i ]* b [i ];aa += (double )a [i ]* a [i ];bb += (double )b [i ]* b [i ]; } 177return aa > 0 && bb > 0 ?ab / std::sqrt (aa * bb ) :0.0 ; 178} 179 180bool VitRef ::load (const Gguf & gg ,const VitGeometry & g , std::string & err ) { 181g_ = g ; 182 std::string why ; 183if (!vit_geometry_supported (g ,why )) {err = "this tower is not supported: " + why ;return false; } 184// the two temporal taps of the patch embedding are summed: a still picture is fed to both 185 std::vector < float > w0 ,w1 ; 186if (!read_t (gg ,"v.patch_embd.weight" ,w0 ,err ))return false; 187if (g .patch_taps == 2 ) { 188if (!read_t (gg ,"v.patch_embd.weight.1" ,w1 ,err ))return false; 189for (size_t i = 0 ;i < w0 .size ();++ i )w0 [i ]+= w1 [i ]; 190 } 191patch_w_ = std::move (w0 ); 192if (!read_t (gg ,"v.patch_embd.bias" ,patch_b_ ,err )|| !read_t (gg ,"v.position_embd.weight" ,pos_ ,err )|| 193 !read_t (gg ,"v.post_ln.weight" ,post_w_ ,err )|| !read_t (gg ,"v.post_ln.bias" ,post_b_ ,err )|| 194 !read_t (gg ,"mm.0.weight" ,mm0_w_ ,err )|| !read_t (gg ,"mm.0.bias" ,mm0_b_ ,err )|| 195 !read_t (gg ,"mm.2.weight" ,mm2_w_ ,err )|| !read_t (gg ,"mm.2.bias" ,mm2_b_ ,err )) 196return false; 197act_round_ = 0 ; 198if (const char * e = std::getenv ("STRATA_VIT_REF_ROUND" );e && std::atoi (e )!= 0 ) { 199const GgufTensorInfo * t = gg .tensor ("v.blk.0.attn_qkv.weight" ); 200act_round_ = t && t -> type == GT_BF16 ?1 :t && t -> type == GT_F16 ?2 :0 ; 201 } 202layers_ .assign ((size_t )g .layers ,Layer {}); 203for (int il = 0 ;il < g .layers ;++ il ) { 204Layer & L = layers_ [(size_t )il ]; 205const std::string p = "v.blk." + std::to_string (il )+ "." ; 206if (!read_t (gg ,p + "ln1.weight" ,L .ln1_w ,err )|| !read_t (gg ,p + "ln1.bias" ,L .ln1_b ,err )|| 207 !read_t (gg ,p + "ln2.weight" ,L .ln2_w ,err )|| !read_t (gg ,p + "ln2.bias" ,L .ln2_b ,err )|| 208 !read_t (gg ,p + "attn_qkv.weight" ,L .qkv_w ,err )|| !read_t (gg ,p + "attn_qkv.bias" ,L .qkv_b ,err )|| 209 !read_t (gg ,p + "attn_out.weight" ,L .o_w ,err )|| !read_t (gg ,p + "attn_out.bias" ,L .o_b ,err )|| 210 !read_t (gg ,p + "ffn_up.weight" ,L .up_w ,err )|| !read_t (gg ,p + "ffn_up.bias" ,L .up_b ,err )|| 211 !read_t (gg ,p + "ffn_down.weight" ,L .down_w ,err )|| !read_t (gg ,p + "ffn_down.bias" ,L .down_b ,err )) 212return false; 213 } 214return true; 215} 216 217bool VitRef ::encode (const PreparedImage & img ,int threads , std::vector < float >& rows ,int & nx ,int & ny , std::string & err )const { 218const VitGeometry & g = g_ ; 219const int P = g .patch ,D = g .width ,H = g .heads ,HD = g .head_dim ,F = g .ffn ; 220if (layers_ .empty ()) {err = "the tower is not loaded" ;return false; } 221if (HD > 128 ) {err = "head size above 128 is not handled by the reference" ;return false; } 222if (img .w <=0 || img .h <=0 || img .w %g .align ()!= 0 || img .h %g .align ()!= 0 ) {err = "the picture size is not a multiple of patch * merge" ;return false; } 223const int nth = threads > 0 ?threads : (int ) std::max (1u , std::thread::hardware_concurrency ()); 224const int pw = img .w /P ,ph = img .h /P ,N = pw * ph ,nbx = pw /2 ; 225nx = pw /2 ; 226ny = ph /2 ; 227 228// ---- positions of the tokens (merge order: 2x2 blocks row by row, inside a block dy outer, dx inner) ---- 229 std::vector < int > ty ((size_t )N ),tx ((size_t )N ); 230for (int t = 0 ;t < N ;++ t ) { 231const int b = t /4 ,r = t %4 ; 232ty [(size_t )t ]= 2 * (b /nbx )+ r /2 ; 233tx [(size_t )t ]= 2 * (b %nbx )+ r %2 ; 234 } 235 236// ---- patch embedding: im2col in merge order, one GEMM ---- 237const int K0 = 3 * P * P ; 238 std::vector < float > A ((size_t )N * K0 ); 239const size_t plane = (size_t )img .w * img .h ; 240parallel_for (N ,nth , [& ](int t ) { 241float * a = & A [(size_t )t * K0 ]; 242const int py = ty [(size_t )t ],px = tx [(size_t )t ]; 243for (int c = 0 ;c < 3 ;++ c ) 244for (int ky = 0 ;ky < P ;++ ky ) 245 std::memcpy (a + (size_t )c * P * P + (size_t )ky * P ,& img .chw [c * plane + (size_t ) (py * P + ky )* img .w + (size_t )px * P ], (size_t )P * sizeof (float )); 246 }); 247 std::vector < float > x ((size_t )N * D ); 248gemm (A .data (), (size_t )K0 ,N ,K0 ,patch_w_ .data (),D ,patch_b_ .data (),x .data (), (size_t )D ,nth ); 249A .clear (); 250A .shrink_to_fit (); 251 252// ---- the position table resized to the patch grid (bilinear, align corners: ggml's upscale with the same float maths), added ---- 253 { 254const int G = g .pos_grid ; 255float sfx = (float )pw /G ,sfy = (float )ph /G ; 256if (pw > 1 && G > 1 )sfx = (float ) (pw - 1 ) / (G - 1 ); 257if (ph > 1 && G > 1 )sfy = (float ) (ph - 1 ) / (G - 1 ); 258parallel_for (N ,nth , [& ](int t ) { 259const float fy = (float )ty [(size_t )t ] /sfy ,fx = (float )tx [(size_t )t ] /sfx ; 260int y0 = (int ) std::floor (fy ),x0 = (int ) std::floor (fx ); 261int y1 = y0 + 1 ,x1 = x0 + 1 ; 262y0 = std::max (0 , std::min (y0 ,G - 1 ));y1 = std::max (0 , std::min (y1 ,G - 1 )); 263x0 = std::max (0 , std::min (x0 ,G - 1 ));x1 = std::max (0 , std::min (x1 ,G - 1 )); 264const float dy = std::max (0.0f , std::min (fy - (float )y0 ,1.0f )),dx = std::max (0.0f , std::min (fx - (float )x0 ,1.0f )); 265const float * a = & pos_ [((size_t )y0 * G + x0 )* D ]; 266const float * b = & pos_ [((size_t )y0 * G + x1 )* D ]; 267const float * c = & pos_ [((size_t )y1 * G + x0 )* D ]; 268const float * d = & pos_ [((size_t )y1 * G + x1 )* D ]; 269float * xr = & x [(size_t )t * D ]; 270for (int i = 0 ;i < D ;++ i )xr [i ]+= a [i ]* (1 - dx )* (1 - dy )+ b [i ]* dx * (1 - dy )+ c [i ]* (1 - dx )* dy + d [i ]* dx * dy ; 271 }); 272 } 273 274// ---- rotary tables: pair j of a head (elements j and j + HD/2), j < HD/4 turns with the row, the rest with the column ---- 275const int half = HD /2 ,quarter = HD /4 ; 276 std::vector < float > inv_freq ((size_t )quarter ); 277 { 278const float theta_scale = std::pow (g .rope_theta ,-2.0f / (float )half ); 279float th = 1.0f ; 280for (int j = 0 ;j < quarter ;++ j ) {inv_freq [(size_t )j ]= th ;th *=theta_scale ; } 281 } 282 std::vector < float > rcos ((size_t )N * half ),rsin ((size_t )N * half ); 283parallel_for (N ,nth , [& ](int t ) { 284for (int j = 0 ;j < half ;++ j ) { 285const float pos = (float ) (j < quarter ?ty [(size_t )t ] :tx [(size_t )t ]); 286const float ang = pos * inv_freq [(size_t ) (j %quarter )]; 287rcos [(size_t )t * half + j ]= std::cos (ang ); 288rsin [(size_t )t * half + j ]= std::sin (ang ); 289 } 290 }); 291 292// ---- the layers ---- 293 std::vector < float > h ((size_t )N * D ),qkv ((size_t )N * 3 * D ),ctx ((size_t )N * D ),tmp ((size_t )N * D ),up ((size_t )N * F ); 294const float kq_scale = 1.0f / std::sqrt ((float )HD ); 295for (const Layer & L :layers_ ) { 296layer_norm (x .data (),h .data (),N ,D ,L .ln1_w .data (),L .ln1_b .data (),g .eps ,nth ); 297round_inplace (h .data (),h .size (),act_round_ ,nth ); 298gemm (h .data (), (size_t )D ,N ,D ,L .qkv_w .data (),3 * D ,L .qkv_b .data (),qkv .data (), (size_t )3 * D ,nth ); 299// rotary on q and k 300parallel_for (N ,nth , [& ](int t ) { 301float * row = & qkv [(size_t )t * 3 * D ]; 302const float * cs = & rcos [(size_t )t * half ]; 303const float * sn = & rsin [(size_t )t * half ]; 304for (int part = 0 ;part < 2 ;++ part ) 305for (int hh = 0 ;hh < H ;++ hh ) { 306float * v = row + (size_t )part * D + (size_t )hh * HD ; 307for (int j = 0 ;j < half ;++ j ) { 308const float a = v [j ],b = v [j + half ]; 309v [j ]= a * cs [j ]- b * sn [j ]; 310v [j + half ]= a * sn [j ]+ b * cs [j ]; 311 } 312 } 313 }); 314round_inplace (qkv .data (),qkv .size (),act_round_ ?2 :0 ,nth );// (diagnostic) mtmd's flash attention holds q, k, v in F16 315// global attention, 4 queries at a time per head 316static constexpr int QB = 4 ;// static constexpr, not const: MSVC does not treat a const local used inside the lambda as a constant (C2131 at acc[QB][128]) 317const int nqb = (N + QB - 1 ) /QB ; 318parallel_for (H * nqb ,nth , [& ](int task ) { 319const int hh = task /nqb ,q0 = (task %nqb )* QB ,nq = std::min (QB ,N - q0 ); 320 std::vector < float > sc ((size_t )QB * N ); 321const size_t stride = (size_t )3 * D ; 322const float * qb = qkv .data ()+ (size_t )hh * HD ; 323const float * kb = qkv .data ()+ (size_t )D + (size_t )hh * HD ; 324const float * vb = qkv .data ()+ (size_t )2 * D + (size_t )hh * HD ; 325for (int j = 0 ;j < N ;++ j ) { 326const float * kj = kb + (size_t )j * stride ; 327for (int qi = 0 ;qi < nq ;++ qi )sc [(size_t )qi * N + j ]= dot (qb + (size_t ) (q0 + qi )* stride ,kj ,HD )* kq_scale ; 328 } 329for (int qi = 0 ;qi < nq ;++ qi ) { 330float * s = & sc [(size_t )qi * N ]; 331float mx = s [0 ]; 332for (int j = 1 ;j < N ;++ j )mx = std::max (mx ,s [j ]); 333double den = 0 ; 334for (int j = 0 ;j < N ;++ j ) {s [j ]= std::exp (s [j ]- mx );den += s [j ]; } 335const float inv = (float ) (1.0 /den ); 336for (int j = 0 ;j < N ;++ j )s [j ] *=inv ; 337 } 338float acc [QB ][128 ]; 339for (int qi = 0 ;qi < nq ;++ qi )for (int i = 0 ;i < HD ;++ i )acc [qi ][i ]= 0.0f ; 340for (int j = 0 ;j < N ;++ j ) { 341const float * vj = vb + (size_t )j * stride ; 342for (int qi = 0 ;qi < nq ;++ qi ) { 343const float p = sc [(size_t )qi * N + j ]; 344for (int i = 0 ;i < HD ;++ i )acc [qi ][i ]+= p * vj [i ]; 345 } 346 } 347for (int qi = 0 ;qi < nq ;++ qi ) std::memcpy (& ctx [(size_t ) (q0 + qi )* D + (size_t )hh * HD ],acc [qi ], (size_t )HD * sizeof (float )); 348 }); 349round_inplace (ctx .data (),ctx .size (),act_round_ ,nth ); 350gemm (ctx .data (), (size_t )D ,N ,D ,L .o_w .data (),D ,L .o_b .data (),tmp .data (), (size_t )D ,nth ); 351for (size_t i = 0 ;i < x .size ();++ i )x [i ]+= tmp [i ]; 352layer_norm (x .data (),h .data (),N ,D ,L .ln2_w .data (),L .ln2_b .data (),g .eps ,nth ); 353round_inplace (h .data (),h .size (),act_round_ ,nth ); 354gemm (h .data (), (size_t )D ,N ,D ,L .up_w .data (),F ,L .up_b .data (),up .data (), (size_t )F ,nth ); 355gelu_inplace (up .data (),up .size (),nth ); 356round_inplace (up .data (),up .size (),act_round_ ,nth ); 357gemm (up .data (), (size_t )F ,N ,F ,L .down_w .data (),D ,L .down_b .data (),tmp .data (), (size_t )D ,nth ); 358for (size_t i = 0 ;i < x .size ();++ i )x [i ]+= tmp [i ]; 359 } 360 361// ---- post norm and the merger ---- 362layer_norm (x .data (),h .data (),N ,D ,post_w_ .data (),post_b_ .data (),g .eps ,nth ); 363const int M = N /4 ,Kin = 4 * D ,Hid = g .merger_hidden ,O = g .out_dim ; 364 std::vector < float > m1 ((size_t )M * Hid ); 365round_inplace (h .data (),h .size (),act_round_ ,nth ); 366gemm (h .data (), (size_t )Kin ,M ,Kin ,mm0_w_ .data (),Hid ,mm0_b_ .data (),m1 .data (), (size_t )Hid ,nth ); 367gelu_inplace (m1 .data (),m1 .size (),nth ); 368rows .assign ((size_t )M * O ,0.0f ); 369round_inplace (m1 .data (),m1 .size (),act_round_ ,nth ); 370gemm (m1 .data (), (size_t )Hid ,M ,Hid ,mm2_w_ .data (),O ,mm2_b_ .data (),rows .data (), (size_t )O ,nth ); 371return true; 372} 373 374}// namespace strata_vit