okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
8ac8ce32e
main
1// Strata. The trellis routed experts of the DeepSeek-V4.1 path (ds4_tq.cu on the device, ds4_tq_cpu.cpp on the CPU lane) against 2// a double reference on host-decoded weights (tools/trellis/tqenc: decode_blocks), for the six types (TQK6 / TQK7 / TQK5X / 3// TQK4X / TQK5T / TQK4T): the token path, the window path (grouped entries), the prompt sets (gate/up and down) and the CPU 4// lane, plus the two lanes against each other. Random legal streams: any bit pattern is one. 5// tq_expert_test [--type 145,146,...] 6#include "../../src/dsv41/ds4_gguf_cpu.hpp" 7#include "../../src/dsv41/ds4_iq.cuh" 8#include "../../tools/trellis/tqenc.hpp" 9 10#include "strata/dsv41/hip_or_cuda.h" // HIP names on a HIP build, the CUDA runtime otherwise 11 12#include <algorithm> 13#include <cmath> 14#include <cstdio> 15#include <cstdlib> 16#include <cstring> 17#include <random> 18#include <string> 19#include <vector> 20 21namespace iq= strata::ds4::gguf::iq; 22namespace gg= strata::ds4::gguf; 23#define CK (x ) do { hipError_t e_ = (x); if (e_ != hipSuccess) { std::printf("HIP error %s at %d\n", hipGetErrorString(e_), __LINE__); std::exit(2); } } while (0) 24 25template < typename T > static T * up (const std::vector < T >& v ) { 26T * d ;CK (hipMalloc (& d , std::max < size_t > (1 ,v .size ()* sizeof (T ))));CK (hipMemcpy (d ,v .data (),v .size ()* sizeof (T ),hipMemcpyHostToDevice ));return d ; 27} 28template < typename T > static std::vector < T > down_ (const T * d ,size_t n ) { 29 std::vector < T > v (n );CK (hipMemcpy (v .data (),d ,n * sizeof (T ),hipMemcpyDeviceToHost ));return v ; 30} 31static float h2f (uint16_t h ) { 32const int s = h >>15 ,e = (h >>10 )& 31 ,m = h & 1023 ; 33float f = e == 0 ? std::ldexp ((float )m ,-24 ) : std::ldexp (1.0f + m /1024.0f ,e - 15 ); 34return s ?- f :f ; 35} 36static uint16_t f2h (float f ) {// round to nearest even, normal range 37uint32_t u ; std::memcpy (& u ,& f ,4 ); 38const uint32_t s = (u >>16 )& 0x8000u ;int e = (int ) ((u >>23 )& 0xff )- 127 + 15 ;uint32_t m = u & 0x7fffffu ; 39uint32_t hm = m >>13 ;const uint32_t rem = m & 0x1fffu ; 40uint32_t v = ((uint32_t )e <<10 ) |hm ; 41if (rem > 0x1000u || (rem == 0x1000u && (v & 1 )))++ v ; 42return (uint16_t ) (s |v ); 43} 44 45struct Q8 { std::vector < int8_t > q ; std::vector < float > d ; std::vector < float > xhat ; }; 46// the engine's q8_quant: sc = max|x| / 127 per 32, q = round-half-even(x / sc) 47static Q8 quant (const float * x ,int k ) { 48Q8 r ;r .q .resize (k );r .d .resize (k /32 );r .xhat .resize (k ); 49for (int b = 0 ;b < k /32 ;++ b ) { 50float am = 0 ;for (int j = 0 ;j < 32 ;++ j )am = std::max (am , std::fabs (x [b * 32 + j ])); 51const float sc = am /127.0f ;r .d [b ]= sc ; 52for (int j = 0 ;j < 32 ;++ j ) {const int q = am > 0 ? (int ) std::nearbyint (x [b * 32 + j ] /sc ) :0 ;r .q [b * 32 + j ]= (int8_t )q ;r .xhat [b * 32 + j ]= (float )q * sc ; } 53 } 54return r ; 55} 56static double swiglu (double g ,double u ,double lim ) { 57if (lim > 0 ) {g = std::min (g ,lim );u = std::min (std::max (u ,- lim ),lim ); } 58return g / (1.0 + std::exp (- g ))* u ; 59} 60 61struct Mat { std::vector < uint8_t > bytes ; std::vector < float > w ;int rows ,k ; }; 62static Mat make_mat (std::mt19937_64 & rng ,int type ,int K ,int rows ,int k ) { 63Mat m ;m .rows = rows ;m .k = k ; 64const int bsz = 2 + 4 * K ,nblk = k /128 ; 65m .bytes .resize ((size_t )rows * nblk * bsz ); 66for (auto & b :m .bytes )b = (uint8_t )rng (); 67for (int64_t b = 0 ;b < (int64_t )rows * nblk ;++ b ) {const uint16_t d = f2h (0.05f + 0.0005f * (float ) (rng () %600 )); std::memcpy (& m .bytes [(size_t )b * bsz ],& d ,2 ); } 68m .w .resize ((size_t )rows * k ); 69 tqenc::decode_blocks (type ,m .bytes .data (), (int64_t )rows * nblk ,m .w .data ()); 70return m ; 71} 72static double dotd (const float * w ,const float * x ,int k ,double * sabs = nullptr ) { 73double s = 0 ,sa = 0 ;for (int i = 0 ;i < k ;++ i ) {const double t = (double )w [i ]* x [i ];s += t ;sa += std::fabs (t ); }if (sabs )* sabs = sa ;return s ; 74} 75 76// one decode token of the DeepSeek shape (n_embd 5120, n_ff 2304, top-6 experts, distinct blobs) through the token path: gate/up + 77// down launches, hipEvent time per layer; and a 5-entry verify window of one expert group 78static void bench (int type ) { 79const int K = iq::tq_kbits (type ),E = 5120 ,FF = 2304 ,NE = 6 ; 80const size_t rb_g = (size_t ) (E /128 )* (2 + 4 * K ),rb_d = (size_t ) (FF /128 )* (2 + 4 * K ); 81auto al = [](size_t n ) {return (n + 255 ) /256 * 256 ; }; 82const size_t off [3 ]= {0 ,al (FF * rb_g ),al (FF * rb_g )* 2 },blob = off [2 ]+ al ((size_t )E * rb_d ); 83 std::mt19937_64 rng (5 ); 84 std::vector < uint8_t > one (blob ); 85for (auto & b :one )b = (uint8_t )rng (); 86 std::vector < unsigned long long > plan (NE ); 87for (int e = 0 ;e < NE ;++ e ) {uint8_t * d ;CK (hipMalloc (& d ,blob ));CK (hipMemcpy (d ,one .data (),blob ,hipMemcpyHostToDevice ));plan [e ]= (unsigned long long )d ; } 88 std::vector < int8_t > xq (E ,3 ),hq ((size_t )NE * FF ,3 ); std::vector < float > xd (E /32 ,0.01f ),hd ((size_t )NE * FF /32 ,0.01f ); 89 iq::Args a {}; 90a .plan_ptr = up (plan );a .n_embd = E ;a .n_ff = FF ;a .limit = 10.0f ;a .xq = up (xq );a .xd = up (xd );a .hq = up (hq );a .hd = up (hd );a .tg = a .td = type ; 91for (int r = 0 ;r < 3 ;++ r )a .tr [r ]= off [r ]; 92float * dh ,* dp ;CK (hipMalloc (& dh , (size_t )NE * FF * 4 ));CK (hipMalloc (& dp , (size_t )NE * E * 4 ));a .h = dh ;a .part = dp ; 93hipEvent_t e0 ,e1 ;hipEventCreate (& e0 );hipEventCreate (& e1 ); 94for (int rep = 0 ;rep < 5 ;++ rep ) { iq::gate_up (a ,NE ,1 ,0 ); iq::down (a ,NE ,1 ,0 ); } 95CK (hipDeviceSynchronize ()); 96float ms_gu = 0 ,ms_dn = 0 ; 97for (int part = 0 ;part < 2 ;++ part ) { 98hipEventRecord (e0 ); 99for (int rep = 0 ;rep < 100 ;++ rep ) {if (part == 0 ) iq::gate_up (a ,NE ,1 ,0 );else iq::down (a ,NE ,1 ,0 ); } 100hipEventRecord (e1 );hipEventSynchronize (e1 ); 101float ms ;hipEventElapsedTime (& ms ,e0 ,e1 ); 102 (part == 0 ?ms_gu :ms_dn )= ms /100 ; 103 } 104const double bytes = (double )NE * blob ; 105 std::printf ("bench %-6s token path, 6 experts: gate/up %.0f us, down %.0f us, layer %.0f us (%.0f GB/s, %.2f Tw/s), x40 = %.1f ms per token\n" , iq::name (type ),ms_gu * 1e3 , 106ms_dn * 1e3 , (ms_gu + ms_dn )* 1e3 ,bytes / ((ms_gu + ms_dn )* 1e-3 ) /1e9 , (double )NE * 3 * FF * E / ((ms_gu + ms_dn )* 1e-3 ) /1e12 ,40.0 * (ms_gu + ms_dn )); 107} 108 109int main (int argc ,char ** argv ) { 110 std::vector < int > types = {145 ,146 ,224 ,225 ,226 ,227 }; 111for (int i = 1 ;i < argc ;++ i ) 112if (std::string (argv [i ])== "--bench" ) {for (int t : {225 ,224 ,145 ,146 })bench (t );return 0 ; } 113else if (std::string (argv [i ])== "--type" && i + 1 < argc ) {types .clear ();for (const char * p = argv [++ i ];* p ;) {types .push_back (std::atoi (p ));while (* p && * p != ',' )++ p ;if (* p )++ p ; } } 114 std::mt19937_64 rng (11 ); 115 std::normal_distribution < float > nd (0.f ,1.f ); 116int fails = 0 ; 117auto report = [& ](const char * what ,int type ,double worst ,double tol ) { 118const bool ok = worst <=tol ; 119 std::printf ("%-6s %-22s worst %.2e (tol %.0e) %s\n" , iq::name (type ),what ,worst ,tol ,ok ?"ok" :"FAIL" ); 120fails += !ok ; 121 }; 122for (int type :types ) { 123const int K = iq::tq_kbits (type ); 124const int E = 512 ,FF = 256 ,NEXP = 3 ,T = 4 ; 125const float lim = 7.0f ; 126const size_t rb_g = (size_t ) (E /128 )* (2 + 4 * K ),rb_d = (size_t ) (FF /128 )* (2 + 4 * K ); 127// experts: blob = gate | up | down, each 256-aligned 128auto al = [](size_t n ) {return (n + 255 ) /256 * 256 ; }; 129const size_t off [3 ]= {0 ,al (FF * rb_g ),al (FF * rb_g )* 2 },blob = off [2 ]+ al ((size_t )E * rb_d ); 130 std::vector < Mat > G (NEXP ),U (NEXP ),D (NEXP ); 131// h of row r of expert e for the input xv (F32 values), and the size of the operands it was made of 132auto refh = [& ](int e ,int r ,const float * xv ,double & scale ) { 133double sg ,su ; 134const double g = dotd (& G [e ].w [(size_t )r * E ],xv ,E ,& sg ),u = dotd (& U [e ].w [(size_t )r * E ],xv ,E ,& su ); 135scale = sg + su + 1e-30 ; 136return swiglu (g ,u ,lim ); 137 }; 138 std::vector < uint8_t > blobs ((size_t )NEXP * blob ,0 ); 139for (int e = 0 ;e < NEXP ;++ e ) { 140G [e ]= make_mat (rng ,type ,K ,FF ,E );U [e ]= make_mat (rng ,type ,K ,FF ,E );D [e ]= make_mat (rng ,type ,K ,E ,FF ); 141 std::memcpy (& blobs [e * blob + off [0 ]],G [e ].bytes .data (),G [e ].bytes .size ()); 142 std::memcpy (& blobs [e * blob + off [1 ]],U [e ].bytes .data (),U [e ].bytes .size ()); 143 std::memcpy (& blobs [e * blob + off [2 ]],D [e ].bytes .data (),D [e ].bytes .size ()); 144 } 145uint8_t * dblob = up (blobs ); 146// tokens 147 std::vector < float > x ((size_t )T * E ); 148for (auto & v :x )v = nd (rng )* (1.0f + 3.0f * (rng () %7 == 0 )); 149 std::vector < Q8 > qx (T ); 150 std::vector < int8_t > xq ((size_t )T * E ); std::vector < float > xd ((size_t )T * E /32 ); 151for (int t = 0 ;t < T ;++ t ) {qx [t ]= quant (& x [(size_t )t * E ],E ); std::memcpy (& xq [(size_t )t * E ],qx [t ].q .data (),E ); std::memcpy (& xd [(size_t )t * E /32 ],qx [t ].d .data (),E /32 * 4 ); } 152const int8_t * dxq = up (xq );const float * dxd = up (xd ); 153 154// ---- token path: plan = 3 experts, input row 0 155 { 156 std::vector < unsigned long long > plan (NEXP ); 157for (int e = 0 ;e < NEXP ;++ e )plan [e ]= (unsigned long long ) (dblob + e * blob ); 158 iq::Args a {}; 159a .plan_ptr = up (plan );a .n_embd = E ;a .n_ff = FF ;a .limit = lim ;a .xq = dxq ;a .xd = dxd ;a .tg = a .td = type ; 160for (int r = 0 ;r < 3 ;++ r )a .tr [r ]= off [r ]; 161float * dh ;CK (hipMalloc (& dh , (size_t )NEXP * FF * 4 ));a .h = dh ; 162if (!iq::gate_up (a ,NEXP ,1 ,0 )) { std::printf ("gate_up refused\n" );return 1 ; } 163CK (hipDeviceSynchronize ()); 164const auto h = down_ (dh , (size_t )NEXP * FF ); 165double worst = 0 ; 166 std::vector < float > href ((size_t )NEXP * FF ); 167for (int e = 0 ;e < NEXP ;++ e ) 168for (int r = 0 ;r < FF ;++ r ) { 169double sc ; 170const double ref = refh (e ,r ,qx [0 ].xhat .data (),sc ); 171href [(size_t )e * FF + r ]= (float )ref ; 172worst = std::max (worst , std::fabs (h [(size_t )e * FF + r ]- ref ) /sc ); 173 } 174report ("token gate_up" ,type ,worst ,1e-5 ); 175// down over the reference h, quantized 176 std::vector < int8_t > hq ((size_t )NEXP * FF ); std::vector < float > hd ((size_t )NEXP * FF /32 ); 177 std::vector < Q8 > qh (NEXP ); 178for (int e = 0 ;e < NEXP ;++ e ) {qh [e ]= quant (& href [(size_t )e * FF ],FF ); std::memcpy (& hq [(size_t )e * FF ],qh [e ].q .data (),FF ); std::memcpy (& hd [(size_t )e * FF /32 ],qh [e ].d .data (),FF /32 * 4 ); } 179a .hq = up (hq );a .hd = up (hd ); 180float * dp ;CK (hipMalloc (& dp , (size_t )NEXP * E * 4 ));a .part = dp ; 181if (!iq::down (a ,NEXP ,1 ,0 )) { std::printf ("down refused\n" );return 1 ; } 182CK (hipDeviceSynchronize ()); 183const auto part = down_ (dp , (size_t )NEXP * E ); 184worst = 0 ; 185for (int e = 0 ;e < NEXP ;++ e ) 186for (int r = 0 ;r < E ;++ r ) { 187double sa ;const double ref = dotd (& D [e ].w [(size_t )r * FF ],qh [e ].xhat .data (),FF ,& sa ); 188worst = std::max (worst , std::fabs (part [(size_t )e * E + r ]- ref ) / (sa + 1e-30 )); 189 } 190report ("token down" ,type ,worst ,1e-6 ); 191 192// ---- the CPU lane on the same experts and inputs; against the reference and the device 193 gg::IqCpu fm ; std::string err ; 194if (!gg::iq_cpu_fmt (type ,type ,E ,FF ,fm ,err )) { std::printf ("cpu fmt: %s\n" ,err .c_str ());++ fails ; } 195else { 196 std::vector < uint8_t > act (fm .act_bytes ),hact (fm .h_bytes ); 197 gg::iq_cpu_quant (fm .gu_act ,x .data (),E ,act .data ()); 198bool same = std::memcmp (act .data (),qx [0 ].d .data (),E /32 * 4 )== 0 && std::memcmp (act .data ()+ E /32 * 4 ,qx [0 ].q .data (),E )== 0 ; 199 std::printf ("%-6s cpu activation == device quantizer: %s\n" , iq::name (type ),same ?"ok" :"FAIL" ); 200fails += !same ; 201double wg = 0 ,wd = 0 ,wx = 0 ; 202for (int e = 0 ;e < NEXP ;++ e ) { 203 std::vector < float > hc (FF ),yc (E ); 204float * hp [1 ]= {hc .data ()};float * yp [1 ]= {yc .data ()}; 205const void * ap [1 ]= {act .data ()}; 206 gg::iq_cpu_gate_up (fm ,& blobs [e * blob + off [0 ]],& blobs [e * blob + off [1 ]],ap ,1 ,hp ,0 ,FF ,lim ); 207for (int r = 0 ;r < FF ;++ r ) {double sc ;refh (e ,r ,qx [0 ].xhat .data (),sc );wg = std::max (wg , std::fabs (hc [r ]- href [(size_t )e * FF + r ]) /sc );wx = std::max (wx , std::fabs (hc [r ]- h [(size_t )e * FF + r ]) /sc ); } 208 gg::iq_cpu_quant (fm .d_act ,& href [(size_t )e * FF ],FF ,hact .data ()); 209const void * hpp [1 ]= {hact .data ()}; 210 gg::iq_cpu_down (fm ,& blobs [e * blob + off [2 ]],hpp ,1 ,yp ,0 ,E ); 211for (int r = 0 ;r < E ;++ r ) {double sa ;const double ref = dotd (& D [e ].w [(size_t )r * FF ],qh [e ].xhat .data (),FF ,& sa );wd = std::max (wd , std::fabs (yc [r ]- ref ) / (sa + 1e-30 )); } 212 } 213report ("cpu gate_up vs ref" ,type ,wg ,1e-5 ); 214report ("cpu down vs ref" ,type ,wd ,1e-6 ); 215report ("cpu vs device gate_up" ,type ,wx ,1e-5 ); 216 } 217 } 218 219// ---- window path: groups of entries (entry e = t * 8 + i reads input row e >> 3) 220 { 221 std::vector < unsigned long long > grp = {(unsigned long long ) (dblob + 0 * blob ), (unsigned long long ) (dblob + 2 * blob )}; 222 std::vector < int > start = {0 ,3 ,5 },ent = {1 ,10 ,19 ,2 ,8 },ng = {2 }; 223 iq::Args a {}; 224a .grp_ptr = up (grp );a .grp_start = up (start );a .grp_ent = up (ent );a .n_groups = up (ng ); 225a .n_embd = E ;a .n_ff = FF ;a .limit = lim ;a .xq = dxq ;a .xd = dxd ;a .tg = a .td = type ; 226for (int r = 0 ;r < 3 ;++ r )a .tr [r ]= off [r ]; 227const int NE = 24 ; 228float * dh ;CK (hipMalloc (& dh , (size_t )NE * FF * 4 ));CK (hipMemset (dh ,0 , (size_t )NE * FF * 4 ));a .h = dh ; 229 iq::gate_up (a ,2 ,3 ,0 ); 230CK (hipDeviceSynchronize ()); 231const auto h = down_ (dh , (size_t )NE * FF ); 232double worst = 0 ; 233for (int gi = 0 ;gi < 2 ;++ gi ) 234for (int j = start [gi ];j < start [gi + 1 ];++ j ) { 235const int en = ent [j ],t = en >>3 ,e = gi == 0 ?0 :2 ; 236for (int r = 0 ;r < FF ;++ r ) { 237double sc ; 238const double ref = refh (e ,r ,qx [t ].xhat .data (),sc ); 239worst = std::max (worst , std::fabs (h [(size_t )en * FF + r ]- ref ) /sc ); 240 } 241 } 242report ("window gate_up" ,type ,worst ,1e-5 ); 243 } 244 245// ---- the prompt sets: expert 0 owns sorted rows [0, 37), expert 2 rows [37, 42); input rows idx[sorted] 246 { 247const int NR = 42 ; 248 std::vector < int > bounds = {0 ,37 ,37 ,42 },idx (NR ); 249for (int i = 0 ;i < NR ;++ i )idx [i ]= i %T ; 250 iq::SetArgs q {}; 251q .wbase = dblob ;q .stride = blob ;for (int r = 0 ;r < 3 ;++ r )q .tr [r ]= off [r ]; 252q .bounds = up (bounds );q .row0 = 0 ;q .max_rows = 37 ;q .n_exp = 3 ;q .n_embd = E ;q .n_ff = FF ;q .limit = lim ; 253q .tg = q .td = type ;q .xf = up (x );q .idx = up (idx );q .ldx = E ; 254uint16_t * dh16 ;CK (hipMalloc (& dh16 , (size_t )NR * FF * 2 ));q .h = dh16 ;q .ldo = FF ; 255 iq::set_gate_up (q ,0 ); 256CK (hipDeviceSynchronize ()); 257const auto h16 = down_ (dh16 , (size_t )NR * FF ); 258double worst = 0 ; 259for (int e = 0 ;e < 3 ;++ e ) 260for (int lr = bounds [e ];lr < bounds [e + 1 ];++ lr ) 261for (int r = 0 ;r < FF ;++ r ) { 262double sc ; 263const double ref = refh (e ,r ,& x [(size_t )idx [lr ]* E ],sc ); 264worst = std::max (worst , std::fabs (h2f (h16 [(size_t )lr * FF + r ])- ref ) /sc ); 265 } 266report ("set gate_up (f16 out)" ,type ,worst ,1e-3 ); 267// down over those f16 h rows 268q .xh = dh16 ;q .ldx = FF ; 269float * dy ;CK (hipMalloc (& dy , (size_t )NR * E * 4 ));q .y = dy ;q .ldo = E ; 270 iq::set_down (q ,0 ); 271CK (hipDeviceSynchronize ()); 272const auto y = down_ (dy , (size_t )NR * E ); 273worst = 0 ; 274for (int e = 0 ;e < 3 ;++ e ) 275for (int lr = bounds [e ];lr < bounds [e + 1 ];++ lr ) { 276 std::vector < float > hf (FF ); 277for (int c = 0 ;c < FF ;++ c )hf [c ]= h2f (h16 [(size_t )lr * FF + c ]); 278for (int r = 0 ;r < E ;++ r ) { 279double sa ;const double ref = dotd (& D [e ].w [(size_t )r * FF ],hf .data (),FF ,& sa ); 280worst = std::max (worst , std::fabs (y [(size_t )lr * E + r ]- ref ) / (sa + 1e-30 )); 281 } 282 } 283report ("set down" ,type ,worst ,1e-6 ); 284 } 285 } 286 std::printf ("%s\n" ,fails ?"FAILED" :"ALL OK" ); 287return fails ; 288}