okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f2eedfe9f
main
1// src/kernels/cpu/kq_window_bench.cpp - round 0216: the CPU pool's share of a decode window, replayed without a GPU. 2// 3// kq_cpu_bench times one format pair; a decode window is 48 layers back to back, each layer a different format pair, ~12 missed experts a layer 4// of 1-4 token rows each, split over the pool's threads with a join between gate/up and down. This runs that shape on the engine's own entry points 5// (native_gu_rows + native_down_rows) over DRAM-sized expert memory: for every layer the pair is that layer's (native_experts.txt of the pack), the 6// number of distinct missed experts and each one's token rows are drawn to match what the engine logs (STRATA_DECODE_TIMING: "CPU experts X (Y entries)"), 7// and the experts are picked at random from a per-pair arena of several GB, so every expert is a cold read. Output: ms per window and per layer. 8// 9// kq_window_bench --layers PACK/native_experts.txt [--windows 60] [--threads 8] [--distinct 11.6] [--rows 1.7] [--arena-mb 2048] [--reps 3] 10// 11// It is a replay with synthetic routing calibrated on observed means, not an engine run: it says what the kernels do to the pool's time, not what a 12// request's tokens/s do. 13#include "strata/kernels/cpu/expert_layout.hpp" 14#include "strata/kernels/cpu/native_expert.hpp" 15 16#include "ggml.h" 17#include "ggml-cpu.h" 18 19#include <algorithm> 20#include <atomic> 21#include <chrono> 22#include <cmath> 23#include <cstdio> 24#include <cstdlib> 25#include <cstring> 26#include <map> 27#include <memory> 28#include <random> 29#include <string> 30#include <thread> 31#include <vector> 32 33namespace cpu= strata::kernels::cpu; 34 35namespace { 36 37constexpr int64_t kH = 2560 ,kFF = 640 ; 38constexpr int kMaxT = 8 ; 39 40struct Pair { 41 cpu::NativeFmt f ; 42 std::unique_ptr < uint8_t []> mem ; 43uint8_t * blobs = nullptr ; 44size_t E = 0 ; 45}; 46 47struct Barrier {// spinning sense-reversing barrier: the pool's workers spin briefly between phases too 48explicit Barrier (int n ) :n_ (n ) {} 49void wait () { 50const int s = sense_ .load (std::memory_order_acquire ); 51if (count_ .fetch_add (1 , std::memory_order_acq_rel )+ 1 == n_ ) { 52count_ .store (0 , std::memory_order_relaxed ); 53sense_ .fetch_add (1 , std::memory_order_release ); 54 }else { 55while (sense_ .load (std::memory_order_acquire )== s ) { } 56 } 57 } 58int n_ ; 59 std::atomic < int > count_ {0 },sense_ {0 }; 60}; 61 62struct Task {int pair ;size_t blob ;int nt ; }; 63 64}// namespace 65 66int main (int argc ,char ** argv ) { 67setvbuf (stdout ,nullptr ,_IONBF ,0 ); 68 std::string layers_file ,dump_trace ; 69int windows = 60 ,threads = 8 ,reps = 3 ; 70double distinct = 11.6 ,rows_mean = 1.7 ,arena_mb = 2048 ; 71unsigned seed = 7 ; 72for (int i = 1 ;i < argc ;++ i ) { 73const std::string a = argv [i ]; 74const bool more = i + 1 < argc ; 75if (a == "--layers" && more )layers_file = argv [++ i ]; 76else if (a == "--windows" && more )windows = std::atoi (argv [++ i ]); 77else if (a == "--threads" && more )threads = std::atoi (argv [++ i ]); 78else if (a == "--distinct" && more )distinct = std::atof (argv [++ i ]); 79else if (a == "--rows" && more )rows_mean = std::atof (argv [++ i ]); 80else if (a == "--arena-mb" && more )arena_mb = std::atof (argv [++ i ]); 81else if (a == "--reps" && more )reps = std::atoi (argv [++ i ]); 82else if (a == "--dump-trace" && more )dump_trace = argv [++ i ]; 83else if (a == "--seed" && more )seed = (unsigned ) std::atoi (argv [++ i ]); 84else { std::fprintf (stderr ,"usage: kq_window_bench --layers native_experts.txt [--windows 60] [--threads 8] [--distinct 11.6] [--rows 1.7] [--arena-mb 2048] [--reps 3]\n" );return 2 ; } 85 } 86if (layers_file .empty ()) { std::fprintf (stderr ,"kq_window_bench: --layers is required\n" );return 2 ; } 87ggml_cpu_init (); 88// layer -> pair 89 std::vector < int > layer_pair ; 90 std::vector < std::pair < int ,int >> pair_types ; 91 { 92 std::FILE * fp = std::fopen (layers_file .c_str (),"r" ); 93if (!fp ) { std::fprintf (stderr ,"cannot open %s\n" ,layers_file .c_str ());return 2 ; } 94char line [512 ]; 95while (std::fgets (line ,sizeof line ,fp )) { 96int l ,g ,d ; 97if (std::sscanf (line ,"%d %d %d" ,& l ,& g ,& d )== 3 ) { 98auto it = std::find (pair_types .begin (),pair_types .end (), std::make_pair (g ,d )); 99int idx = (int ) (it - pair_types .begin ()); 100if (it == pair_types .end ())pair_types .push_back ({g ,d }); 101if ((int )layer_pair .size () <=l )layer_pair .resize ((size_t )l + 1 ,0 ); 102layer_pair [(size_t )l ]= idx ; 103 } 104 } 105 std::fclose (fp ); 106 } 107const int L = (int )layer_pair .size (); 108 std::vector < Pair > pairs (pair_types .size ()); 109 std::mt19937 rng (1234 ); 110 std::normal_distribution < float > nd (0.f ,0.02f ); 111 std::vector < float > row ((size_t ) std::max (kH ,kFF )); 112const std::vector < float > imatrix ((size_t ) std::max (kH ,kFF ),1.0f ); 113for (size_t p = 0 ;p < pairs .size ();++ p ) { 114 std::string err ; 115Pair & P = pairs [p ]; 116if (!cpu::native_fmt (pair_types [p ].first ,pair_types [p ].second ,kH ,kFF ,P .f ,err )) { std::fprintf (stderr ,"pair %zu: %s\n" ,p ,err .c_str ());return 2 ; } 117ggml_quantize_init ((ggml_type )P .f .gu_type ); 118ggml_quantize_init ((ggml_type )P .f .d_type ); 119P .E = std::max < size_t > (64 , (size_t ) (arena_mb * 1048576.0 ) /P .f .bytes ); 120P .mem .reset (new uint8_t [P .E * P .f .bytes + 4096 ]); 121P .blobs = (uint8_t * ) (((uintptr_t )P .mem .get ()+ 4095 )& ~(uintptr_t )4095 ); 122const size_t U = std::min < size_t > (16 ,P .E ); 123auto quant = [& ](int type ,uint8_t * dst ,int64_t n ) { 124ggml_quantize_chunk ((ggml_type )type ,row .data (),dst ,0 ,1 ,n ,ggml_quantize_requires_imatrix ((ggml_type )type ) ?imatrix .data () :nullptr ); 125 }; 126for (size_t e = 0 ;e < U ;++ e ) { 127uint8_t * b = P .blobs + e * P .f .bytes ; 128for (int64_t r = 0 ;r < 2 * kFF ;++ r ) {for (int64_t i = 0 ;i < kH ;++ i )row [(size_t )i ]= nd (rng );quant (P .f .gu_type ,b + (size_t )r * P .f .gu_row ,kH ); } 129for (int64_t r = 0 ;r < kH ;++ r ) {for (int64_t i = 0 ;i < kFF ;++ i )row [(size_t )i ]= nd (rng );quant (P .f .d_type ,b + P .f .down_off + (size_t )r * P .f .d_row ,kFF ); } 130 } 131for (size_t e = U ;e < P .E ;++ e ) std::memcpy (P .blobs + e * P .f .bytes ,P .blobs + (e %U )* P .f .bytes ,P .f .bytes ); 132 } 133// activations per pair (kMaxT tokens), quantized the way the pool does 134struct Act { std::vector < std::vector < uint8_t >> x ,h ; }; 135 std::vector < Act > acts (pairs .size ()); 136 std::normal_distribution < float > xd (0.f ,1.f ); 137for (size_t p = 0 ;p < pairs .size ();++ p ) { 138acts [p ].x .assign (kMaxT , std::vector < uint8_t > (cpu::kNativeActBytes )); 139acts [p ].h .assign (kMaxT , std::vector < uint8_t > (cpu::kNativeHBytes )); 140for (int t = 0 ;t < kMaxT ;++ t ) { 141 std::vector < float > x (kH ),h (kFF ); 142for (auto & v :x )v = xd (rng ); 143for (auto & v :h )v = 0.3f * xd (rng ); 144 cpu::native_quant_act (pairs [p ].f ,x .data (),acts [p ].x [(size_t )t ].data ()); 145 cpu::native_quant_h (pairs [p ].f ,h .data (),acts [p ].h [(size_t )t ].data ()); 146 } 147 } 148// the windows: per layer a list of (pair, blob, rows) 149 std::mt19937 wr (seed ); 150 std::vector < std::vector < std::vector < Task >>> win ((size_t )windows , std::vector < std::vector < Task >> ((size_t )L )); 151const double q = 1.0 - 1.0 /rows_mean ;// rows - 1 ~ geometric: mean rows = 1 / (1 - q) 152long long n_exp = 0 ,n_rows = 0 ; 153for (int w = 0 ;w < windows ;++ w ) 154for (int l = 0 ;l < L ;++ l ) { 155 std::poisson_distribution < int > pd (distinct ); 156const int ne = std::max (1 , std::min (24 ,pd (wr ))); 157for (int e = 0 ;e < ne ;++ e ) { 158int nt = 1 ; 159 std::uniform_real_distribution < double > u (0.0 ,1.0 ); 160while (nt < 4 && u (wr )< q )++ nt ; 161const int p = layer_pair [(size_t )l ]; 162win [(size_t )w ][(size_t )l ].push_back ({p , (size_t ) (wr () %pairs [(size_t )p ].E ),nt }); 163++ n_exp ; 164n_rows += nt ; 165 } 166 } 167if (!dump_trace .empty ()) {// the synthetic windows in the STRATA_ROUTE_DUMP text form (every expert a miss), for replay_place.py 168 std::FILE * tf = std::fopen (dump_trace .c_str (),"w" ); 169if (tf ) { 170for (int w = 0 ;w < windows ;++ w ) 171for (int l = 0 ;l < L ;++ l ) { 172const auto & tk = win [(size_t )w ][(size_t )l ]; 173int rows = 0 ; 174for (const Task & t :tk )rows += t .nt ; 175 std::fprintf (tf ,"%d %d %d %d |" ,l ,3 , (int )tk .size (), (int )tk .size ()); 176for (size_t i = 0 ;i < tk .size ();++ i ) std::fprintf (tf ," %d:%d:0" , (int )i ,tk [i ].nt ); 177 std::fputc (10 ,tf ); 178 } 179 std::fclose (tf ); 180 } 181 } 182 std::printf ("kq_window_bench: %s, %d layers, %zu format pairs, %d windows, %d threads, %.0f MB arena per pair; %.2f experts/layer, %.2f rows/expert\n" , 183 cpu::cpu_name ().c_str (),L ,pairs .size (),windows ,threads ,arena_mb , (double )n_exp / ((double )windows * L ), (double )n_rows / (double )n_exp ); 184for (size_t p = 0 ;p < pairs .size ();++ p ) { 185int nl = 0 ; 186for (int l = 0 ;l < L ;++ l )nl += layer_pair [(size_t )l ]== (int )p ; 187 std::printf (" pair %s/%s: %d layers\n" ,ggml_type_name ((ggml_type )pairs [p ].f .gu_type ),ggml_type_name ((ggml_type )pairs [p ].f .d_type ),nl ); 188 } 189// the run: every thread takes tasks of a layer phase from a shared counter, a barrier joins the phases 190Barrier bar (threads ); 191 std::atomic < int > next {0 }; 192 std::atomic < int > cur_w {0 }; 193 std::vector < double > ms ; 194constexpr int kGuChunk = 160 ,kDnChunk = 640 ;// rows per task: gate/up 640 rows in 4, down 2560 rows in 4 195for (int rep = 0 ;rep < reps ;++ rep ) { 196 std::atomic < bool > stop {false}; 197double wall = 0 ; 198auto work = [& ](int tid ) { 199 std::vector < float > ffb ((size_t )kMaxT * kFF ),outb ((size_t )kMaxT * kH ); 200float * ff [kMaxT ]; 201float * out [kMaxT ]; 202for (int t = 0 ;t < kMaxT ;++ t ) {ff [t ]= & ffb [(size_t )t * kFF ];out [t ]= & outb [(size_t )t * kH ]; } 203const auto t0 = std::chrono::steady_clock::now (); 204for (int w = 0 ;w < windows ;++ w ) { 205for (int l = 0 ;l < L ;++ l ) { 206const auto & tasks = win [(size_t )w ][(size_t )l ]; 207const int nT = (int )tasks .size (); 208for (int phase = 0 ;phase < 2 ;++ phase ) { 209if (tid == 0 )next .store (0 , std::memory_order_relaxed ); 210bar .wait (); 211const int chunk = phase == 0 ?kGuChunk :kDnChunk ; 212const int rows = phase == 0 ? (int )kFF : (int )kH ; 213const int per = (rows + chunk - 1 ) /chunk ; 214for (;;) { 215const int k = next .fetch_add (1 , std::memory_order_relaxed ); 216if (k >=nT * per )break ; 217const Task & tk = tasks [(size_t ) (k /per )]; 218const int r0 = (k %per )* chunk ,r1 = std::min (rows ,r0 + chunk ); 219Pair & P = pairs [(size_t )tk .pair ]; 220const uint8_t * blob = P .blobs + tk .blob * P .f .bytes ; 221const void * ap [kMaxT ]; 222const void * hp [kMaxT ]; 223for (int t = 0 ;t < tk .nt ;++ t ) {ap [t ]= acts [(size_t )tk .pair ].x [(size_t )t ].data ();hp [t ]= acts [(size_t )tk .pair ].h [(size_t )t ].data (); } 224if (phase == 0 ) cpu::native_gu_rows (P .f ,blob ,ap ,tk .nt ,ff ,r0 ,r1 ); 225else cpu::native_down_rows (P .f ,blob ,hp ,tk .nt ,out ,r0 ,r1 ); 226 } 227bar .wait (); 228 } 229 } 230 } 231if (tid == 0 )wall = std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t0 ).count (); 232volatile float sink = outb [0 ]+ ffb [0 ]; 233 (void )sink ; 234 }; 235 std::vector < std::thread > th ; 236for (int t = 1 ;t < threads ;++ t )th .emplace_back (work ,t ); 237work (0 ); 238for (auto & x :th )x .join (); 239ms .push_back (wall /windows ); 240 std::printf (" rep %d: %.2f ms per window (%.3f ms per layer)\n" ,rep ,wall /windows ,wall /windows /L ); 241 } 242 std::sort (ms .begin (),ms .end ()); 243 std::printf ("median %.2f ms per window\n" ,ms [ms .size () /2 ]); 244 (void )cur_w ; 245return 0 ; 246}