okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1306424be
main
1// metal/tests/token_chain.cpp - one decode step of the whole model, every kernel of metal/ on the REAL weights of a 2// GGUF (mmapped, wrapped no-copy as one MTLBuffer), each layer with its own tensor formats, all dispatches in one 3// command buffer: the GPU time of a decode token (or a verify window) with these kernels, dispatch boundaries 4// included. Not a numerical check (the activations are synthetic): a timing of the real byte stream. 5// 6// token_chain <shard-1.gguf> [--ntok N] [--ctx P] [--reps R] [--skip-qsa] [--only CLASS] 7// 8// Left out: the PLE path (one table row and two small projections at one layer) and the MTP draft. 9#include "gguf_lite.h" 10#include "mtl_rt.h" 11#include "ref_quant.h" 12 13#include <algorithm> 14#include <cmath> 15#include <cstdio> 16#include <cstdlib> 17#include <cstring> 18#include <map> 19#include <string> 20#include <sys/mman.h> 21#include <vector> 22 23namespace { 24 25constexpr int N = 2560 ,HC = 4 ,LR = 320 ,NFF = 640 ,TOPK = 10 ,NEXP = 512 ,MAXT = 8 ; 26constexpr int P_MAXE = 128 ,P_GEXP = 16 ,P_GSTART = P_GEXP + P_MAXE ,P_ETOK = P_GSTART + P_MAXE + 4 , 27P_EW = P_ETOK + P_MAXE ,P_TOKENT = P_EW + P_MAXE ,P_INTS = P_TOKENT + P_MAXE ,P_IGU = 4 ,P_IDN = 8 ; 28struct GemvArgs {uint32_t n_in ,n_out ,n_tok ,row_bytes ,x_stride ,y_stride ; }; 29struct GrArgs {uint32_t n_embd ,hc ,hc_lr ,n_tok ,apply ;float eps ; }; 30struct GrArgs3 {uint32_t n_embd ,hc ,hc_lr ,n_tok ,apply ;float eps ;uint32_t rb_down ,rb_up ,comb ,topk ; }; 31struct MoeArgs { 32uint64_t gate_off ,up_off ,down_off ,gu_stride ,d_stride ; 33uint32_t gu_row ,d_row ,n_embd ,n_ff ,n_tok ,topk ,n_expert ,gx_gu ,gx_dn ,pad ; 34}; 35struct GdnArgs {uint32_t h_k ,h_v ,channels ,commit ;float eps ;uint32_t plane ; }; 36struct QsaArgs {uint32_t pos0 ,pos_base ,max_cells ,n_tok ;float eps ; }; 37struct GlueArgs {uint32_t n ,n_tok ,n_embd ,topk ; }; 38struct HcfArgs {uint32_t n_embd ,hc ;float eps ;uint32_t pad ; }; 39struct ArgArgs {uint32_t n_vocab ,parts ; }; 40 41int xkind (int t ) { 42switch (t ) { 43case ref::Q2_0 :return 1 ; 44case ref::Q4_K :case ref::Q5_K :return 2 ; 45case ref::Q6_K :case ref::Q3_K :return 3 ; 46default :return 0 ; 47 } 48} 49double median (std::vector < double > v ) { std::sort (v .begin (),v .end ());return v [v .size () /2 ]; } 50 51// a prepared activation: 4 planes of n_tok rows of n, then the per-16 sums 52struct Act { 53 mtl::Buffer b ; 54int n = 0 ; 55size_t plane_bytes ()const {return (size_t )4 * MAXT * n ; } 56}; 57 58// CHAIN_DEFS=A,B: a "#define A 1" line for each name ahead of the kernels (probe switches) 59std::string defs_prelude () { 60 std::string out ,w ; 61const char * e = std::getenv ("CHAIN_DEFS" ); 62if (!e )return out ; 63for (const char * p = e ;;++ p ) { 64if (* p == ',' || * p == 0 ) {if (!w .empty ())out += "#define " + w + " 1" + char (10 );w .clear ();if (!* p )break ; } 65else w += * p ; 66 } 67return out ; 68} 69 70}// namespace 71 72int main (int argc ,char ** argv ) { 73if (argc < 2 ) { std::fprintf (stderr ,"usage: token_chain <shard-1.gguf> [--ntok N] [--ctx P] [--reps R]\n" );return 2 ; } 74int ntok = 1 ,ctx = 1000 ,reps = 10 ; 75bool skip_qsa = false,graph = false; 76// the HC read: Q8_0 copies through the 3-dispatch read by default (the owner's decision, as STRATA_HC_Q8 on gfx12); 77// STRATA_HC_Q8=0 selects the exact BF16 path. --hc 3: BF16, 3 dispatches; 2: BF16, 2 dispatches; q8: Q8_0 copies, 78// 2 dispatches; q8_3: Q8_0 copies, 3 dispatches 79const char * hcq8 = std::getenv ("STRATA_HC_Q8" ); 80 std::string hc_mode = hcq8 && std::string (hcq8 )== "0" ?"3" :"q8_3" ; 81bool fuse = false;// the GDN y prep in the step; no QSA score/top-k within the selection budget 82bool fold_comb = false;// the MoE combine folded into the next 2-dispatch HC read (measured slower) 83 std::string only ,skip ; 84for (int i = 2 ;i < argc ;++ i ) { 85 std::string a = argv [i ]; 86if (a == "--ntok" )ntok = std::atoi (argv [++ i ]); 87else if (a == "--ctx" )ctx = std::atoi (argv [++ i ]); 88else if (a == "--reps" )reps = std::atoi (argv [++ i ]); 89else if (a == "--skip-qsa" )skip_qsa = true; 90else if (a == "--graph" )graph = true; 91else if (a == "--hc" )hc_mode = argv [++ i ]; 92else if (a == "--fuse" )fuse = true; 93else if (a == "--fold-comb" )fold_comb = true; 94else if (a == "--only" )only = argv [++ i ]; 95else if (a == "--skip" )skip = argv [++ i ]; 96 } 97 gguf::File f ; 98 std::string err ; 99if (!f .open (argv [1 ],err )) { std::fprintf (stderr ,"%s\n" ,err .c_str ());return 2 ; } 100 mtl::Context cx ; 101 std::printf ("device %s; %s: %zu tensors, %.1f GB; %d token(s), context %d\n" ,cx .device_name ().c_str (), 102argv [1 ],f .tensors .size (),f .file_bytes /1e9 ,ntok ,ctx ); 103// fault the file in (page cache), then wrap it 104 { 105const double t0 = mtl::now_s (); 106madvise (f .map ,f .map_bytes ,MADV_WILLNEED ); 107volatile uint64_t s = 0 ; 108for (size_t o = 0 ;o < f .file_bytes ;o += 16384 )s += ((const uint8_t * )f .map )[o ]; 109 std::printf ("file touched in %.1f s\n" , mtl::now_s ()- t0 ); 110 } 111 mtl::Buffer W = cx .wrap (f .map ,f .map_bytes ); 112auto T = [& ](const std::string & name )-> const gguf::Tensor & { 113const gguf::Tensor * t = f .find (name ); 114if (!t ) { std::fprintf (stderr ,"missing tensor %s\n" ,name .c_str ()); std::exit (2 ); } 115return * t ; 116 }; 117 118const int lib = cx .compile ({"quant.metal" ,"units.metal" ,"moe.metal" ,"gemv.metal" ,"gr.metal" ,"gr2.metal" ,"glue.metal" , 119"router.metal" ,"hcf.metal" ,"gemvu.metal" ,"moeu.metal" }, 120defs_prelude ()); 121const int lgdn = cx .compile ({"gdn.metal" },"#define NO_GGML_COMMON 1\n" ); 122const int lqsa = cx .compile ({"qsa.metal" ,"qsa2.metal" ,"qsab.metal" },"#define NO_GGML_COMMON 1\n" ); 123const int lsmp = cx .compile ({"sample.metal" },"#define NO_GGML_COMMON 1\n" ); 124 std::map < std::string , mtl::Pipeline > pcache ; 125 126// ---- buffers 127const int MAXC = std::max (4096 , (ctx + 64 ) /4 * 4 + 64 ),MB = MAXC /4 + 2 ; 128 mtl::Buffer R = cx .alloc (4 * MAXT * HC * N ),bo = cx .alloc (4 * MAXT * N ),inj [2 ]= {cx .alloc (4 * MAXT * HC ),cx .alloc (4 * MAXT * HC )}, 129xn = cx .alloc (4 * MAXT * HC * N ),lo = cx .alloc (4 * MAXT * LR ),qkv = cx .alloc (4 * MAXT * 10240 ), 130z = cx .alloc (4 * MAXT * 6144 ),al = cx .alloc (4 * MAXT * 48 ),be = cx .alloc (4 * MAXT * 48 ), 131yg = cx .alloc (4 * MAXT * 6144 ),logits = cx .alloc (4 * MAXT * 512 ),ids = cx .alloc (4 * MAXT * TOPK ), 132wts = cx .alloc (4 * MAXT * TOPK ),plan = cx .alloc (4 * P_INTS ),h = cx .alloc (4 * MAXT * TOPK * NFF ), 133ye = cx .alloc (4 * MAXT * TOPK * N ),gsh = cx .alloc (4 * MAXT * NFF ),ush = cx .alloc (4 * MAXT * NFF ), 134ysh = cx .alloc (4 * MAXT * N ),sg = cx .alloc (4 * MAXT * 4 ),qfull = cx .alloc (4 * MAXT * 12288 ), 135kcur = cx .alloc (4 * MAXT * 512 ),vcur = cx .alloc (4 * MAXT * 512 ),iqr = cx .alloc (4 * MAXT * 512 ), 136ikr = cx .alloc (4 * MAXT * 128 ),qcur = cx .alloc (4 * MAXT * 24 * 256 ),qidx = cx .alloc (4 * MAXT * 4 * 128 ), 137scores = cx .alloc (4 * (size_t )MAXT * MB ),qids = cx .alloc (4 * MAXT * 2051 ), 138part = cx .alloc (4 * (size_t )MAXT * 65 * 24 * 258 ),cs = cx .alloc (8 * (size_t )(MAXC + 16 )* 32 ), 139lm = cx .alloc (4 * (size_t )MAXT * 248320 ),apv = cx .alloc (4 * MAXT * 120 ),api = cx .alloc (4 * MAXT * 120 ), 140tokout = cx .alloc (4 * MAXT ); 141auto act = [& ](int n ) {Act a ;a .n = n ;a .b = cx .alloc (4 * ((size_t )4 * MAXT * n + (size_t )MAXT * n /16 ));return a ; }; 142Act XA = act (N ),XF = act (N ),XY = act (6144 ),XQ = act (6144 ),XH = act (NFF ); 143for (size_t i = 0 ;i < R .bytes /4 ;++ i )R .as < float > ()[i ]= 0.01f * (float )((i * 2654435761u ) %200 )- 1.0f ; 144for (int p = 0 ;p < MAXC + 16 ;++ p ) 145for (int i = 0 ;i < 32 ;++ i ) { 146const double th = (double )p * std::pow (1e7 ,-2.0 * i /64.0 ); 147cs .as < float > ()[(p * 32 + i )* 2 ]= (float )std::cos (th ); 148cs .as < float > ()[(p * 32 + i )* 2 + 1 ]= (float )std::sin (th ); 149 } 150// per-layer recurrent state and QSA caches 151 std::vector < mtl::Buffer > gst ,ghist ,ghist2 ,kq ,vq ,ksc ,vsc ,tail ,dead ,pooled ; 152for (int l = 0 ;l < 48 ;++ l ) { 153if (l %4 != 3 ) { 154gst .push_back (cx .alloc (4 * 128 * 48 * 128 )); 155ghist .push_back (cx .alloc (4 * 10240 * 3 )); 156ghist2 .push_back (cx .alloc (4 * 10240 * 3 )); 157 }else { 158kq .push_back (cx .alloc ((size_t )MAXC * 2 * 256 )); 159vq .push_back (cx .alloc ((size_t )MAXC * 2 * 256 )); 160ksc .push_back (cx .alloc (2 * (size_t )MAXC * 2 * 4 )); 161vsc .push_back (cx .alloc (2 * (size_t )MAXC * 2 * 4 )); 162tail .push_back (cx .alloc (4 * 4 * 128 )); 163dead .push_back (cx .alloc (4 * 128 )); 164pooled .push_back (cx .alloc (4 * (size_t )MB * 128 )); 165 } 166 } 167for (int t = 0 ;t < MAXT ;++ t ) 168for (int c = 0 ;c < 2051 ;++ c )qids .as < int > ()[t * 2051 + c ]= c ; 169for (auto & b :vsc )for (size_t i = 0 ;i < b .bytes /2 ;++ i )b .as < uint16_t > ()[i ]= 0x2000 ;// small fp16 scales 170for (auto & b :ksc )for (size_t i = 0 ;i < b .bytes /2 ;++ i )b .as < uint16_t > ()[i ]= 0x2000 ; 171 172 std::vector < mtl::Dispatch > ds ; 173 std::vector < std::string > cls ;// class of each dispatch (for --only) 174 std::map < std::string ,double > bytes_by ; 175bool nb = false;// the next push is independent of the previous dispatch (no barrier before it) 176 std::map < const mtl::Pipeline * , std::string > pname ; 177auto push = [& ](const mtl::Dispatch & d0 ,const std::string & c ,double bytes = 0 ) { 178 mtl::Dispatch d = d0 ; 179d .barrier = !nb ; 180nb = false; 181if (!only .empty ()&& c != only )return ; 182if (const char * sk = std::getenv ("CHAIN_SKIPK" )) {// marginal cost of a kernel: drop every dispatch whose pipeline key contains sk 183auto it = pname .find (d .p ); 184if (it != pname .end ()&& it -> second .find (sk )!= std::string::npos )return ; 185 } 186if (!skip .empty ()&& c == skip )return ; 187ds .push_back (d ); 188cls .push_back (c ); 189bytes_by [c ]+= bytes ; 190 }; 191// pipelines whose names do not match the function (cached by key): create by function name first 192auto Pn = [& ](int l ,const std::string & fn ,const std::string & key ,const mtl::Constants & c )-> const mtl::Pipeline * { 193auto it = pcache .find (key ); 194if (it == pcache .end ())it = pcache .emplace (key ,cx .pipeline (l ,fn ,c )).first ; 195pname [& it -> second ]= key ; 196return & it -> second ; 197 }; 198// ---- SLC prefetch (--prefetch): the next HC read's weights touched concurrently with the first projection GEMV 199// after the current read, so the latency-bound read finds them in the SLC 200const bool prefetch = std::getenv ("CHAIN_PREFETCH" )!= nullptr ; 201const bool albe = std::getenv ("CHAIN_ALBE" )!= nullptr ;// ssm_alpha + ssm_beta as one gemv_cat 202// the router GEMV + moe_route as one router_route (default; CHAIN_ROUTE=0: separate) 203const bool routef = !(std::getenv ("CHAIN_ROUTE" )&& std::string (std::getenv ("CHAIN_ROUTE" ))== "0" ); 204const bool combf = std::getenv ("CHAIN_COMB" )!= nullptr ;// the MoE combine folded into the next gr_norm 205bool comb_pending = false; 206// routed gate/up: the i-quant grids from constant memory (QUANT_CTAB, function constant 23; bitwise; default, 207// CHAIN_CTAB=0: the threadgroup copy) 208const bool ctabf = !(std::getenv ("CHAIN_CTAB" )&& std::string (std::getenv ("CHAIN_CTAB" ))== "0" ); 209 mtl::Buffer rcounter = cx .alloc (16 ); 210struct Range {const mtl::Buffer * b ;size_t off ,bytes ; }; 211 std::vector < Range > pending ; 212 mtl::Buffer sink = cx .alloc (16 ); 213const mtl::Pipeline * ptouch = nullptr ; 214auto push_prefetch = [& ]() { 215for (const Range & r :pending ) { 216const uint32_t n16 = (uint32_t )(r .bytes /16 ); 217 mtl::Dispatch d ; 218d .p = ptouch ; 219d .args = {mtl::Arg ::B (* r .b ,r .off ), mtl::Arg ::B (sink ), mtl::Arg ::V (n16 )}; 220d .grid [0 ]= (n16 + 1023 ) /1024 ; 221d .tg [0 ]= 256 ; 222nb = true; 223push (d ,"prefetch" , (double )r .bytes ); 224 } 225pending .clear (); 226 }; 227// ---- GEMV by tensor, with a tile from the measured table 228auto gemv2 = [& ](const gguf::Tensor & t ,const Act & x ,const mtl::Buffer & y ,size_t y_stride ,const std::string & c , 229int ty_override = -1 ) { 230const int n_in = (int )t .shape [0 ],n_out = t .shape .size ()> 1 ? (int )t .shape [1 ] :1 ; 231const int ty = ty_override >=0 ?ty_override :t .type ; 232int L = 16 ,Rr = 1 ,S = 4 ,K = 1 ; 233if (n_in >=6144 ) {L = 32 ;Rr = 1 ;S = 8 ;K = 2 ; } 234else if (n_in == 640 ) {L = 8 ;Rr = 1 ;S = 4 ;K = 1 ; } 235else if (n_out <=640 || ty == ref::Q2_0 || ty == ref::BF16 ) {L = 32 ;Rr = 1 ;S = 4 ;K = 1 ; } 236const char * gu = std::getenv ("CHAIN_GEMVU" ); 237const std::string fn = std::string (gu ?"gemvu_" :"gemv_" )+ std::to_string (ty )+ "_" + std::to_string (L )+ "_" + std::to_string (Rr )+ "_" + 238 std::to_string (S )+ "_" + std::to_string (K )+ (gu ? std::string ("_" )+ gu : std::string ()); 239const mtl::Pipeline * p = Pn (lib ,fn ,fn + "#" + std::to_string (ntok ), mtl::Constants ().i (0 ,ntok )); 240GemvArgs a {(uint32_t )n_in , (uint32_t )n_out , (uint32_t )ntok , (uint32_t )ref::row_bytes (t .type ,n_in ), (uint32_t )n_in , 241 (uint32_t )y_stride }; 242 mtl::Dispatch d ; 243d .p = p ; 244d .args = {mtl::Arg ::B (W ,t .offset ), mtl::Arg ::B (x .b ,x .plane_bytes ()* xkind (ty )), mtl::Arg ::B (x .b ,x .plane_bytes ()* 4 ), 245 mtl::Arg ::B (y ), mtl::Arg ::V (a )}; 246const int rpt = (S /K )* (32 /L )* Rr ; 247d .grid [0 ]= (n_out + rpt - 1 ) /rpt ; 248d .tg [0 ]= S * 32 ; 249push (d ,c , (double )t .bytes ); 250if (!pending .empty ())push_prefetch (); 251 }; 252const mtl::Pipeline * pnorm = Pn (lib , std::getenv ("CHAIN_NORM2" ) ?"gr_norm2" :"gr_norm" , std::getenv ("CHAIN_NORM2" ) ?"gr_norm2" :"gr_norm" , {}); 253const mtl::Pipeline * pnormc = Pn (lib ,"gr_norm_comb" ,"gr_norm_comb" , {}); 254ptouch = Pn (lib ,"slc_touch" ,"slc_touch" , {}); 255const mtl::Pipeline * pdown = Pn (lib ,"gr_down_8_8" ,"gr_down_8_8" , mtl::Constants ().i (1 ,ntok )); 256const mtl::Pipeline * pup = Pn (lib ,"gr_up" ,"gr_up" , mtl::Constants ().i (1 ,ntok )); 257const mtl::Pipeline * pdownq = Pn (lib ,"gr_down_q8_8_8" ,"gr_down_q8_8_8" , mtl::Constants ().i (1 ,ntok )); 258const mtl::Pipeline * pupq = Pn (lib ,"gr_up_q8" ,"gr_up_q8" , mtl::Constants ().i (1 ,ntok )); 259const mtl::Pipeline * pprep = Pn (lib ,"xprep" ,"xprep" , {}); 260const mtl::Pipeline * proute = Pn (lib ,"moe_route" ,"moe_route" , {}); 261const mtl::Pipeline * pswi = Pn (lib ,"swiglu_prep" ,"swiglu_prep" , {}); 262const mtl::Pipeline * pcomb = Pn (lib , std::getenv ("CHAIN_COMB2" ) ?"moe_combine_sh2" :"moe_combine_sh" , std::getenv ("CHAIN_COMB2" ) ?"moe_combine_sh2" :"moe_combine_sh" , {}); 263const mtl::Pipeline * pgdn = Pn (lgdn ,"gdn_step" ,"gdn_step" , mtl::Constants ().i (2 ,ntok )); 264const mtl::Pipeline * qprep = Pn (lqsa ,"qsa_prep" ,"qsa_prep" , {}); 265const mtl::Pipeline * qscore = Pn (lqsa ,"qsa_score" ,"qsa_score" , {}); 266const int qav = std::getenv ("QSA_ATTN" ) ? std::atoi (std::getenv ("QSA_ATTN" )) :1 ; 267const bool qv2 = qav == 2 ; 268const mtl::Pipeline * qtopk = Pn (lqsa , std::getenv ("QSA_TOPK" ) ?"qsa_topk" :"qsa_topk2" ,"qsa_topk" , {}); 269const mtl::Pipeline * qattn = Pn (lqsa ,qav == 1 ? (std::getenv ("CHAIN_QB" ) ?"qsa_attn_b" :"qsa_attn" ) :qv2 ?"qsa_attn2" :"qsa_attn3" ,"qsa_attn" , {}); 270const mtl::Pipeline * qmerge = Pn (lqsa ,qv2 ?"qsa_merge2" :"qsa_merge" ,"qsa_merge" , {}); 271const mtl::Pipeline * pam1 = Pn (lsmp ,"argmax_part" ,"argmax_part" , {}); 272const mtl::Pipeline * pam2 = Pn (lsmp ,"argmax_final" ,"argmax_final" , {}); 273 274// the 2-dispatch read: residual and partial-dot ping-pong buffers, rs; the Q8_0 copies of the HC matrices 275 mtl::Buffer Rb [2 ]= {R ,cx .alloc (4 * MAXT * HC * N )},Db [2 ]= {cx .alloc (4 * MAXT * (LR + HC )* HC ),cx .alloc (4 * MAXT * (LR + HC )* HC )}, 276rsb = cx .alloc (4 * MAXT * HC ); 277int cur_r = 0 ,cur_d = 0 ; 278 std::map < std::string ,size_t > q8off ; 279 mtl::Buffer Q8 ; 280if (hc_mode == "q8" || hc_mode == "q8_3" ) { 281size_t tot = 0 ; 282for (const auto & kv :f .tensors ) { 283const gguf::Tensor & t = kv .second ; 284if (t .type != ref::BF16 || t .name .find ("hc_" )== std::string::npos || t .name .find ("_norm" )!= std::string::npos )continue ; 285uint64_t ne = 1 ; 286for (uint64_t d :t .shape )ne *=d ; 287q8off [t .name ]= tot ; 288tot += ne /32 * 34 ; 289 } 290Q8 = cx .alloc ((tot + 4095 ) /4096 * 4096 ); 291const double t0 = mtl::now_s (); 292 std::vector < float > tmp ; 293for (const auto & kv :q8off ) { 294const gguf::Tensor & t = * f .find (kv .first ); 295uint64_t ne = 1 ; 296for (uint64_t d :t .shape )ne *=d ; 297tmp .resize (ne ); 298 ref::dequant (ref::BF16 , (const uint8_t * )f .map + t .offset ,tmp .data (),ne ); 299 ref::quantize_q8_0 (tmp .data (),ne ,Q8 .as < uint8_t > ()+ kv .second ); 300 } 301 std::printf ("HC Q8_0 copies: %zu tensors, %.1f MB, quantized in %.1f s\n" ,q8off .size (),tot /1e6 , mtl::now_s ()- t0 ); 302 } 303int cur_inj = 0 ; 304// CHAIN_HCF: gr_norm folded into the producer of bo (hcf.metal): the mixer's output GEMV and the MoE combine apply bo to R 305// and the last threadgroup forms xn; the next read has no gr_norm dispatch 306const bool hcf = std::getenv ("CHAIN_HCF" )!= nullptr && (hc_mode == "q8_3" || hc_mode == "3" ); 307const bool hcf_keep = std::getenv ("CHAIN_KEEPNORM" )!= nullptr ;// timing probe: swap the producers, keep gr_norm 308const std::string hcf_only = std::getenv ("CHAIN_HCF_ONLY" ) ? std::getenv ("CHAIN_HCF_ONLY" ) :"" ;// gemv | comb 309bool hcf_pend = false; 310 mtl::Buffer hcnt = cx .alloc (16 ),sink2 = cx .alloc (256 ); 311auto hcf_args = [& ](const std::string & nextpre ) { 312HcfArgs h {N ,HC ,1e-6f ,0 }; 313return std::vector < mtl::Arg > {mtl::Arg ::B (R ), mtl::Arg ::B (inj [cur_inj ]), mtl::Arg ::B (W ,T (nextpre + "_norm.weight" ).offset ), 314 mtl::Arg ::B (xn ), mtl::Arg ::B (hcnt ), mtl::Arg ::V (h )}; 315 }; 316// a producer GEMV of bo (n_in >= 6144: the 32,1,8,2 tile): gemv2, or with CHAIN_HCF gemvh (R updated, xn formed by the last threadgroup) 317auto gemv_p = [& ](const gguf::Tensor & t ,const Act & x ,const mtl::Buffer & y ,size_t y_stride ,const std::string & c , 318const std::string & nextpre ) { 319const int n_in = (int )t .shape [0 ],n_out = (int )t .shape [1 ]; 320if (!hcf || n_in < 6144 || hcf_only == "comb" ) {gemv2 (t ,x ,y ,y_stride ,c );return ; } 321const std::string fn = "gemvh_" + std::to_string (t .type ); 322const mtl::Pipeline * p = Pn (lib ,fn ,fn + "#" + std::to_string (ntok ), mtl::Constants ().i (0 ,ntok )); 323GemvArgs a {(uint32_t )n_in , (uint32_t )n_out , (uint32_t )ntok , (uint32_t )ref::row_bytes (t .type ,n_in ), (uint32_t )n_in , 324 (uint32_t )y_stride }; 325 mtl::Dispatch d ; 326d .p = p ; 327d .args = {mtl::Arg ::B (W ,t .offset ), mtl::Arg ::B (x .b ,x .plane_bytes ()* xkind (t .type )), mtl::Arg ::B (x .b ,x .plane_bytes ()* 4 ), 328 mtl::Arg ::B (y ), mtl::Arg ::V (a )}; 329for (auto & g :hcf_args (nextpre ))d .args .push_back (g ); 330d .grid [0 ]= (n_out + 3 ) /4 ;// rpt = (S / K) * (32 / L) * Rr = 4 331d .tg [0 ]= 256 ; 332push (d ,c , (double )t .bytes ); 333hcf_pend = !hcf_keep ; 334 }; 335auto gr_read = [& ](const std::string & pre ,bool apply ,const Act & out ,bool final_ ) { 336if (hc_mode != "3" && hc_mode != "q8_3" ) { 337const bool q8 = hc_mode == "q8" ; 338const gguf::Tensor & tn = T (pre + "_norm.weight" ); 339const gguf::Tensor & tdn = T (pre + "_down.weight" ); 340const gguf::Tensor & tup = T (pre + "_up.weight" ); 341const gguf::Tensor & tin = final_ ?tdn :T (pre + "_inject.weight" ); 342const int tt = std::min (ntok ,3 ); 343const std::string dn = std::string ("gr_down3_" )+ (q8 ?"8_" :"30_" )+ std::to_string (tt )+ "_2" ; 344const std::string up = std::string ("gr_up3_" )+ (q8 ?"8" :"30" ); 345// after an MoE (the next layer's mixer read, the final read) the combine is folded in here 346const bool comb = fold_comb && apply && pre .find ("hc_ffn" )== std::string::npos ; 347GrArgs3 a {N ,HC ,LR ,MAXT ,apply ?1u :0u ,1e-6f , (uint32_t )(q8 ?HC * N /32 * 34 :HC * N * 2 ), 348 (uint32_t )(q8 ?LR /32 * 34 :LR * 2 ),comb ?1u :0u , (uint32_t )TOPK }; 349const mtl::Buffer & WB = q8 ?Q8 :W ; 350const size_t od = q8 ?q8off .at (tdn .name ) :tdn .offset ,oi = q8 ?q8off .at (tin .name ) :tin .offset , 351ou = q8 ?q8off .at (tup .name ) :tup .offset ; 352 mtl::Dispatch d ; 353d .p = Pn (lib ,dn ,dn + "#" + std::to_string (ntok ), mtl::Constants ().i (1 ,ntok )); 354d .args = {mtl::Arg ::B (WB ,od ), mtl::Arg ::B (WB ,oi ), mtl::Arg ::B (Rb [cur_r ]), mtl::Arg ::B (Rb [1 - cur_r ]), 355 mtl::Arg ::B (bo ), mtl::Arg ::B (Db [cur_d ]), mtl::Arg ::B (W ,tn .offset ), mtl::Arg ::B (Db [1 - cur_d ]), 356 mtl::Arg ::B (rsb ), mtl::Arg ::V (a ), mtl::Arg ::B (plan ), mtl::Arg ::B (ye ), mtl::Arg ::B (ysh ), mtl::Arg ::B (sg )}; 357d .grid [0 ]= (LR + HC + 15 ) /16 ; 358d .grid [1 ]= HC ; 359d .tg [0 ]= 256 ; 360const double wb = q8 ? (tdn .bytes + (final_ ?0 :tin .bytes ))* 34.0 /64.0 : (double )tdn .bytes + (final_ ?0 :tin .bytes ); 361push (d ,"hc" ,wb ); 362cur_r = 1 - cur_r ; 363cur_d = 1 - cur_d ; 364 mtl::Dispatch u ; 365u .p = Pn (lib ,up ,up + "#" + std::to_string (ntok ), mtl::Constants ().i (1 ,ntok )); 366u .args = {mtl::Arg ::B (WB ,ou ), mtl::Arg ::B (Db [cur_d ]), mtl::Arg ::B (Rb [cur_r ]), mtl::Arg ::B (out .b ), mtl::Arg ::V (a ), 367 mtl::Arg ::B (W ,tn .offset ), mtl::Arg ::B (rsb )}; 368u .grid [0 ]= N /16 ; 369u .tg [0 ]= 256 ; 370push (u ,"hc" ,q8 ?tup .bytes * 34.0 /64.0 : (double )tup .bytes ); 371return ; 372 } 373const gguf::Tensor & tn = T (pre + "_norm.weight" ); 374const gguf::Tensor & tdn = T (pre + "_down.weight" ); 375const gguf::Tensor & tup = T (pre + "_up.weight" ); 376const gguf::Tensor & tin = final_ ?tdn :T (pre + "_inject.weight" ); 377GrArgs a {N ,HC ,LR , (uint32_t )ntok ,apply ?1u :0u ,1e-6f }; 378const bool q83 = hc_mode == "q8_3" ; 379const mtl::Buffer & WB = q83 ?Q8 :W ; 380const size_t od = q83 ?q8off .at (tdn .name ) :tdn .offset ,oi = q83 ?q8off .at (tin .name ) :tin .offset , 381ou = q83 ?q8off .at (tup .name ) :tup .offset ; 382 mtl::Dispatch d1 ; 383d1 .p = pnorm ; 384d1 .args = {mtl::Arg ::B (R ), mtl::Arg ::B (bo ), mtl::Arg ::B (inj [cur_inj ]), mtl::Arg ::B (W ,tn .offset ), mtl::Arg ::B (xn ), 385 mtl::Arg ::V (a )}; 386if (comb_pending ) { 387// the MoE combine folded into this norm (gr_norm_comb; bitwise moe_combine_sh + gr_norm) 388const uint32_t tk = TOPK ; 389d1 .p = pnormc ; 390d1 .args = {mtl::Arg ::B (R ), mtl::Arg ::B (ye ), mtl::Arg ::B (inj [cur_inj ]), mtl::Arg ::B (W ,tn .offset ), mtl::Arg ::B (xn ), 391 mtl::Arg ::V (a ), mtl::Arg ::B (plan ), mtl::Arg ::B (ysh ), mtl::Arg ::B (sg ), mtl::Arg ::V (tk )}; 392comb_pending = false; 393 } 394d1 .grid [0 ]= HC ; 395d1 .grid [1 ]= ntok ; 396d1 .tg [0 ]= 256 ; 397if (!std::getenv ("CHAIN_NONORM" )&& !(hcf_pend && apply ))push (d1 ,"hc" ,0 ); 398if (const char * e = std::getenv ("CHAIN_NOOPS" )) { 399for (int k = 0 ;k < std::atoi (e );++ k ) { 400 mtl::Dispatch z ; 401z .p = Pn (lib ,"noop_k" ,"noop_k" , {}); 402z .args = {mtl::Arg ::B (sink2 )}; 403z .grid [0 ]= 1 ; 404z .tg [0 ]= 32 ; 405push (z ,"hc" ,0 ); 406 } 407 } 408hcf_pend = false;// CHAIN_NONORM: marginal cost of the norm dispatch (timing only) 409 mtl::Dispatch d2 ; 410d2 .p = q83 ?pdownq :pdown ; 411d2 .args = {mtl::Arg ::B (WB ,od ), mtl::Arg ::B (WB ,oi ), mtl::Arg ::B (xn ), mtl::Arg ::B (lo ), 412 mtl::Arg ::B (inj [1 - cur_inj ]), mtl::Arg ::V (a )}; 413d2 .grid [0 ]= LR + HC ; 414d2 .tg [0 ]= 256 ; 415push (d2 ,"hc" , (double )tdn .bytes + (final_ ?0 :tin .bytes )); 416 mtl::Dispatch d3 ; 417d3 .p = q83 ?pupq :pup ; 418d3 .args = {mtl::Arg ::B (WB ,ou ), mtl::Arg ::B (lo ), mtl::Arg ::B (xn ), mtl::Arg ::B (out .b ), mtl::Arg ::V (a )}; 419d3 .grid [0 ]= N /16 ; 420d3 .tg [0 ]= 256 ; 421push (d3 ,"hc" , (double )tup .bytes ); 422cur_inj = 1 - cur_inj ; 423if (prefetch && !final_ ) { 424// the next read: blk.l.hc_attn -> blk.l.hc_ffn -> blk.(l+1).hc_attn ... -> output_hc 425 std::string nx ; 426const size_t at = pre .find (".hc_attn" ); 427if (at != std::string::npos )nx = pre .substr (0 ,at )+ ".hc_ffn" ; 428else { 429const int l = std::atoi (pre .c_str ()+ 4 ); 430nx = l == 47 ? std::string ("output_hc" ) :"blk." + std::to_string (l + 1 )+ ".hc_attn" ; 431 } 432const bool fin = nx == "output_hc" ; 433for (const std::string & part :fin ? std::vector < std::string > {"_down" ,"_up" } 434 : std::vector < std::string > {"_down" ,"_inject" ,"_up" }) { 435const gguf::Tensor & tt = T (nx + part + ".weight" ); 436if (q83 ) { 437uint64_t ne = 1 ; 438for (uint64_t dd :tt .shape )ne *=dd ; 439pending .push_back ({& Q8 ,q8off .at (tt .name ), (size_t )(ne /32 * 34 ) /16 * 16 }); 440 }else { 441pending .push_back ({& W ,tt .offset , (size_t )tt .bytes /16 * 16 }); 442 } 443 } 444 } 445 }; 446auto xprep = [& ](const mtl::Buffer & x ,const Act & out ,int n ,const std::string & c ) { 447 mtl::Dispatch d ; 448d .p = pprep ; 449const uint32_t nn = n ,nt = MAXT ; 450d .args = {mtl::Arg ::B (x ), mtl::Arg ::B (out .b ), mtl::Arg ::V (nn ), mtl::Arg ::V (nt )}; 451d .tg [0 ]= 256 ; 452d .grid [0 ]= (n /16 * MAXT + 255 ) /256 ; 453push (d ,c ,0 ); 454 }; 455// Every prepared activation has planes of MAXT rows (Act::plane_bytes); the producers that take a token count 456// for the plane stride (gr_up, qsa_merge, swiglu_prep, xprep) are given MAXT there. 457 458int gi = 0 ,qi = 0 ; 459for (int l = 0 ;l < 48 ;++ l ) { 460const std::string b = "blk." + std::to_string (l )+ "." ; 461// ---- mixer 462gr_read (b + "hc_attn" ,l > 0 ,XA , false); 463if (l %4 != 3 ) { 464gemv2 (T (b + "attn_qkv.weight" ),XA ,qkv ,10240 ,"gdn proj" ); 465nb = true; 466gemv2 (T (b + "attn_gate.weight" ),XA ,z ,6144 ,"gdn proj" ); 467nb = true; 468if (albe ) { 469// ssm_alpha + ssm_beta in one dispatch (gemv_cat; bitwise the two GEMVs) 470const gguf::Tensor & ta = T (b + "ssm_alpha.weight" ),& tb = T (b + "ssm_beta.weight" ); 471const std::string fn = "gemvc_" + std::to_string (ta .type )+ "_32_1_4" ; 472 mtl::Dispatch d ; 473d .p = Pn (lib ,fn ,fn + "#" + std::to_string (ntok ), mtl::Constants ().i (0 ,ntok )); 474GemvArgs ga {(uint32_t )N ,96 , (uint32_t )ntok , (uint32_t )ref::row_bytes (ta .type ,N ), (uint32_t )N ,48 }; 475const uint32_t sp = 48 ; 476d .args = {mtl::Arg ::B (W ,ta .offset ), mtl::Arg ::B (XA .b ,XA .plane_bytes ()* xkind (ta .type )), 477 mtl::Arg ::B (XA .b ,XA .plane_bytes ()* 4 ), mtl::Arg ::B (al ), mtl::Arg ::V (ga ), mtl::Arg ::B (W ,tb .offset ), 478 mtl::Arg ::B (be ), mtl::Arg ::V (sp )}; 479d .grid [0 ]= 96 /4 ; 480d .tg [0 ]= 128 ; 481push (d ,"gdn proj" , (double )ta .bytes + tb .bytes ); 482 }else { 483gemv2 (T (b + "ssm_alpha.weight" ),XA ,al ,48 ,"gdn proj" ); 484nb = true; 485gemv2 (T (b + "ssm_beta.weight" ),XA ,be ,48 ,"gdn proj" ); 486 } 487GdnArgs a {16 ,48 ,10240 ,1 ,1e-6f ,fuse ? (uint32_t )(MAXT * 6144 ) :0u }; 488 mtl::Dispatch d ; 489d .p = pgdn ; 490d .args = {mtl::Arg ::B (gst [gi ]), mtl::Arg ::B (ghist [gi ]), mtl::Arg ::B (qkv ), mtl::Arg ::B (al ), mtl::Arg ::B (be ), 491 mtl::Arg ::B (z ), mtl::Arg ::B (W ,T (b + "ssm_conv1d.weight" ).offset ), mtl::Arg ::B (W ,T (b + "ssm_dt.bias" ).offset ), 492 mtl::Arg ::B (W ,T (b + "ssm_a" ).offset ), mtl::Arg ::B (W ,T (b + "ssm_norm.weight" ).offset ), mtl::Arg ::B (fuse ?XY .b :yg ), 493 mtl::Arg ::V (a ), mtl::Arg ::B (ghist2 [gi ])}; 494d .grid [0 ]= std::getenv ("CHAIN_GDNGRID" ) ? std::atoi (std::getenv ("CHAIN_GDNGRID" )) :48 ;// timing probe (wrong values) 495d .tg [0 ]= 512 ; 496push (d ,"gdn step" ,2.0 * 4 * 128 * 48 * 128 ); 497if (!fuse )xprep (yg ,XY ,6144 ,"gdn proj" ); 498gemv_p (T (b + "ssm_out.weight" ),XY ,bo ,N ,"gdn proj" ,b + "hc_ffn" ); 499++ gi ; 500 }else if (!skip_qsa ) { 501gemv2 (T (b + "attn_q.weight" ),XA ,qfull ,12288 ,"qsa proj" ); 502nb = true; 503gemv2 (T (b + "attn_k.weight" ),XA ,kcur ,512 ,"qsa proj" ); 504nb = true; 505gemv2 (T (b + "attn_v.weight" ),XA ,vcur ,512 ,"qsa proj" ); 506nb = true; 507gemv2 (T (b + "indexer.q_proj.weight" ),XA ,iqr ,512 ,"qsa proj" ); 508nb = true; 509gemv2 (T (b + "indexer.k_proj.weight" ),XA ,ikr ,128 ,"qsa proj" ); 510QsaArgs a {(uint32_t )ctx ,0 , (uint32_t )MAXC , (uint32_t )ntok ,1e-6f }; 511 mtl::Dispatch d ; 512d .p = qprep ; 513d .args = {mtl::Arg ::B (qfull ), mtl::Arg ::B (kcur ), mtl::Arg ::B (vcur ), mtl::Arg ::B (iqr ), mtl::Arg ::B (ikr ), 514 mtl::Arg ::B (W ,T (b + "attn_q_norm.weight" ).offset ), mtl::Arg ::B (W ,T (b + "attn_k_norm.weight" ).offset ), 515 mtl::Arg ::B (W ,T (b + "indexer.q_norm.weight" ).offset ), mtl::Arg ::B (W ,T (b + "indexer.k_norm.weight" ).offset ), 516 mtl::Arg ::B (cs ), mtl::Arg ::B (qcur ), mtl::Arg ::B (qidx ), mtl::Arg ::B (kq [qi ]), mtl::Arg ::B (vq [qi ]), 517 mtl::Arg ::B (ksc [qi ]), mtl::Arg ::B (vsc [qi ]), mtl::Arg ::B (tail [qi ]), mtl::Arg ::B (dead [qi ]), 518 mtl::Arg ::B (pooled [qi ]), mtl::Arg ::V (a )}; 519d .grid [0 ]= 33 ; 520d .grid [1 ]= ntok ; 521d .tg [0 ]= 256 ; 522push (d ,"qsa attn" ,0 ); 523const bool sel = !(fuse && ctx + ntok <=2051 );// within the budget the selection is the identity 524 mtl::Dispatch s ; 525s .p = qscore ; 526s .args = {mtl::Arg ::B (qidx ), mtl::Arg ::B (pooled [qi ]), mtl::Arg ::B (dead [qi ]), mtl::Arg ::B (scores ), mtl::Arg ::V (a )}; 527s .grid [0 ]= ((ctx + ntok ) /4 + 1 + 7 ) /8 ; 528s .grid [1 ]= ntok ; 529s .tg [0 ]= 256 ; 530if (sel )push (s ,"qsa attn" ,0 ); 531 mtl::Dispatch k ; 532k .p = qtopk ; 533k .args = {mtl::Arg ::B (scores ), mtl::Arg ::B (qids ), mtl::Arg ::V (a )}; 534k .grid [0 ]= ntok ; 535k .tg [0 ]= 1024 ; 536if (sel )push (k ,"qsa attn" ,0 ); 537 mtl::Dispatch at ; 538at .p = qattn ; 539at .args = {mtl::Arg ::B (qcur ), mtl::Arg ::B (kq [qi ]), mtl::Arg ::B (vq [qi ]), mtl::Arg ::B (ksc [qi ]), mtl::Arg ::B (vsc [qi ]), 540 mtl::Arg ::B (qids ), mtl::Arg ::B (part ), mtl::Arg ::V (a )}; 541at .grid [0 ]= qv2 ?65 :33 ; 542at .grid [1 ]= qv2 ?4 :2 ; 543at .grid [2 ]= ntok ; 544at .tg [0 ]= 256 ; 545push (at ,"qsa attn" ,2.0 * 2 * 512 * std::min (ctx ,2051 )); 546 mtl::Dispatch m ; 547m .p = qmerge ; 548QsaArgs am = a ; 549am .n_tok = MAXT ;// the plane stride (see above) 550m .args = {mtl::Arg ::B (part ), mtl::Arg ::B (qfull ), mtl::Arg ::B (XQ .b ), mtl::Arg ::V (am )}; 551m .grid [0 ]= 24 ; 552m .grid [1 ]= ntok ; 553m .tg [0 ]= 256 ; 554push (m ,"qsa attn" ,0 ); 555gemv_p (T (b + "attn_output.weight" ),XQ ,bo ,N ,"qsa proj" ,b + "hc_ffn" ); 556++ qi ; 557 } 558// ---- MoE 559gr_read (b + "hc_ffn" , true,XF , false); 560if (!routef ) { 561gemv2 (T (b + "ffn_gate_inp.weight" ),XF ,logits ,512 ,"router" ); 562nb = true; 563 } 564const bool pair = fuse && std::getenv ("CHAIN_PAIR" );// measured slower (+0.11 ms): opt-in 565if (pair ) { 566// the shared expert's gate + up + SwiGLU in one dispatch, h raw into XH's raw plane 567const gguf::Tensor & tgs = T (b + "ffn_gate_shexp.weight" ),& tus = T (b + "ffn_up_shexp.weight" ); 568const std::string fn = "gemv_pair_" + std::to_string (tgs .type )+ "_" + std::to_string (tus .type ); 569 mtl::Dispatch d ; 570d .p = Pn (lib ,fn ,fn + "#" + std::to_string (ntok ), mtl::Constants ().i (0 ,ntok )); 571GemvArgs ga {(uint32_t )N , (uint32_t )NFF , (uint32_t )ntok , (uint32_t )ref::row_bytes (tgs .type ,N ), (uint32_t )N , 572 (uint32_t )NFF }; 573const uint32_t rbu = (uint32_t )ref::row_bytes (tus .type ,N ); 574d .args = {mtl::Arg ::B (W ,tgs .offset ), mtl::Arg ::B (XF .b ,XF .plane_bytes ()* xkind (tgs .type )), 575 mtl::Arg ::B (W ,tus .offset ), mtl::Arg ::B (XF .b ,XF .plane_bytes ()* xkind (tus .type )), 576 mtl::Arg ::B (XF .b ,XF .plane_bytes ()* 4 ), mtl::Arg ::B (XH .b ), mtl::Arg ::V (ga ), mtl::Arg ::V (rbu )}; 577d .grid [0 ]= NFF /4 ; 578d .tg [0 ]= 128 ; 579push (d ,"shared" , (double )tgs .bytes + tus .bytes ); 580 }else { 581gemv2 (T (b + "ffn_gate_shexp.weight" ),XF ,gsh ,NFF ,"shared" ); 582nb = true; 583gemv2 (T (b + "ffn_up_shexp.weight" ),XF ,ush ,NFF ,"shared" ); 584 } 585nb = true; 586gemv2 (T (b + "ffn_gate_inp_shexp.weight" ),XF ,sg ,1 ,"shared" ); 587 { 588MoeArgs a {}; 589const gguf::Tensor & tg_ = T (b + "ffn_gate_exps.weight" ),& tu = T (b + "ffn_up_exps.weight" ), 590& td = T (b + "ffn_down_exps.weight" ); 591a .gate_off = tg_ .offset ; 592a .up_off = tu .offset ; 593a .down_off = td .offset ; 594a .gu_row = (uint32_t )ref::row_bytes (tg_ .type ,N ); 595a .d_row = (uint32_t )ref::row_bytes (td .type ,NFF ); 596a .gu_stride = (uint64_t )a .gu_row * NFF ; 597a .d_stride = (uint64_t )a .d_row * N ; 598a .n_embd = N ; 599a .n_ff = NFF ; 600a .n_tok = ntok ; 601a .topk = TOPK ; 602a .n_expert = NEXP ; 603// tiles (lanes per row, rows per lane, simdgroups): CHAIN_GU / CHAIN_DN / CHAIN_DN4 override 604const bool dq2 = td .type == ref::Q2_0 ; 605int gl = 32 ,gr = 1 ,gs = 4 ,dl = dq2 ?8 :4 ,dr = dq2 ?1 :2 ,ds_ = 4 ; 606if (const char * e = std::getenv ("CHAIN_GU" )) std::sscanf (e ,"%d,%d,%d" ,& gl ,& gr ,& gs ); 607if (const char * e = std::getenv (dq2 ?"CHAIN_DN" :"CHAIN_DN4" )) std::sscanf (e ,"%d,%d,%d" ,& dl ,& dr ,& ds_ ); 608a .gx_gu = NFF / (gs * (32 /gl )* gr ); 609a .gx_dn = N / (ds_ * (32 /dl )* dr ); 610if (routef ) { 611// the router GEMV + moe_route in one dispatch (router_route; bitwise), concurrent with the shared GEMVs 612const gguf::Tensor & tr = T (b + "ffn_gate_inp.weight" ); 613 mtl::Dispatch r ; 614r .p = Pn (lib ,"router_route_30" ,"router_route#" + std::to_string (ntok ), mtl::Constants ().i (0 ,ntok )); 615GemvArgs ga {(uint32_t )N ,512 , (uint32_t )ntok , (uint32_t )ref::row_bytes (tr .type ,N ), (uint32_t )N ,512 }; 616r .args = {mtl::Arg ::B (W ,tr .offset ), mtl::Arg ::B (XF .b ,0 ), mtl::Arg ::B (XF .b ,XF .plane_bytes ()* 4 ), 617 mtl::Arg ::B (logits ), mtl::Arg ::V (ga ), mtl::Arg ::B (ids ), mtl::Arg ::B (wts ), mtl::Arg ::B (plan ), 618 mtl::Arg ::V (a ), mtl::Arg ::B (rcounter )}; 619r .grid [0 ]= 512 /16 ; 620r .tg [0 ]= 512 ; 621nb = true; 622push (r ,"router" , (double )tr .bytes ); 623 }else { 624 mtl::Dispatch r ; 625r .p = proute ; 626r .args = {mtl::Arg ::B (logits ), mtl::Arg ::B (ids ), mtl::Arg ::B (wts ), mtl::Arg ::B (plan ), mtl::Arg ::V (a )}; 627r .tg [0 ]= 512 ; 628push (r ,"router" ,0 ); 629 } 630 { 631GlueArgs ga {NFF ,MAXT ,N ,TOPK }; 632 mtl::Dispatch d ; 633d .p = pswi ; 634d .args = {mtl::Arg ::B (gsh ), mtl::Arg ::B (ush ), mtl::Arg ::B (XH .b ), mtl::Arg ::V (ga )}; 635d .grid [0 ]= NFF /16 ; 636d .grid [1 ]= ntok ; 637d .tg [0 ]= 16 ; 638nb = true; 639if (!pair )push (d ,"shared" ,0 ); 640nb = false; 641 } 642const char * mu = std::getenv ("CHAIN_MOEU" ); 643const std::string gun = std::string (mu ?"moe_guu_" :"moe_gu_" )+ std::to_string (tg_ .type )+ "_" + std::to_string (gl )+ "_" + 644 std::to_string (gr )+ "_" + std::to_string (gs )+ (mu ? std::string ("_" )+ mu : std::string ()); 645const std::string dnn = std::string (mu ?"moe_dnu_" :"moe_down_" )+ std::to_string (dq2 ?142 :td .type )+ "_" + std::to_string (dl )+ "_" + 646 std::to_string (dr )+ "_" + std::to_string (ds_ )+ (mu ? std::string ("_" )+ mu : std::string ()); 647 mtl::Dispatch g ; 648g .p = Pn (lib ,gun ,gun + (ctabf ?"#ct" :"" ), mtl::Constants ().b (23 ,ctabf )); 649g .args = {mtl::Arg ::B (W ), mtl::Arg ::B (XF .b ,XF .plane_bytes ()* xkind (tg_ .type )), mtl::Arg ::B (h ), mtl::Arg ::B (plan ), 650 mtl::Arg ::V (a ), mtl::Arg ::B (XF .b ,XF .plane_bytes ()* 4 )}; 651g .tg [0 ]= 32 * gs ; 652g .indirect = & plan ; 653g .ind_off = P_IGU * 4 ; 654push (g ,"experts" ,10.0 * ntok * 2 * a .gu_stride ); 655nb = true; 656 { 657const gguf::Tensor & tds = T (b + "ffn_down_shexp.weight" ); 658// with --fuse h is raw: a Q2_0 down reads it through the raw-activation decoder (type 142) 659gemv2 (tds ,XH ,ysh ,N ,"shared" ,pair && tds .type == ref::Q2_0 ?142 :-1 ); 660 } 661 mtl::Dispatch dd ; 662dd .p = Pn (lib ,dnn ,dnn , {}); 663dd .args = {mtl::Arg ::B (W ), mtl::Arg ::B (h ), mtl::Arg ::B (ye ), mtl::Arg ::B (plan ), mtl::Arg ::V (a ), mtl::Arg ::B (h )}; 664dd .tg [0 ]= 32 * ds_ ; 665dd .indirect = & plan ; 666dd .ind_off = P_IDN * 4 ; 667push (dd ,"experts" ,10.0 * ntok * a .d_stride ); 668 } 669 { 670GlueArgs a {N , (uint32_t )ntok ,N ,TOPK }; 671 mtl::Dispatch d ; 672d .p = pcomb ; 673d .args = {mtl::Arg ::B (ye ), mtl::Arg ::B (plan ), mtl::Arg ::B (ysh ), mtl::Arg ::B (sg ), mtl::Arg ::B (bo ), mtl::Arg ::V (a )}; 674d .grid [0 ]= (ntok * N + 255 ) /256 ; 675d .tg [0 ]= 256 ; 676if (hcf && hcf_only != "gemv" ) { 677// the combine applies bo to R and the last threadgroup forms xn for the next read 678d .p = Pn (lib ,"moe_combine_hcf" ,"moe_combine_hcf" , {}); 679d .args = {mtl::Arg ::B (ye ), mtl::Arg ::B (plan ), mtl::Arg ::B (ysh ), mtl::Arg ::B (sg ), mtl::Arg ::B (bo ), mtl::Arg ::V (a )}; 680for (auto & g :hcf_args (l == 47 ? std::string ("output_hc" ) :"blk." + std::to_string (l + 1 )+ ".hc_attn" ))d .args .push_back (g ); 681push (d ,"shared" ,0 ); 682hcf_pend = !hcf_keep ; 683 } 684else if (combf && (hc_mode == "3" || hc_mode == "q8_3" ))comb_pending = true;// folded into the next gr_norm 685else if (!(fold_comb && hc_mode != "3" ))push (d ,"shared" ,0 );// else folded into the next HC read 686 } 687 } 688// ---- the final mixer and the head 689gr_read ("output_hc" , true,XA , true); 690gemv2 (T ("output.weight" ),XA ,lm ,248320 ,"lm head" ); 691 { 692ArgArgs a {248320 ,120 }; 693 mtl::Dispatch d1 ,d2 ; 694d1 .p = pam1 ; 695d1 .args = {mtl::Arg ::B (lm ), mtl::Arg ::B (apv ), mtl::Arg ::B (api ), mtl::Arg ::V (a )}; 696d1 .grid [0 ]= 120 ; 697d1 .grid [1 ]= ntok ; 698d1 .tg [0 ]= 256 ; 699push (d1 ,"lm head" ,0 ); 700d2 .p = pam2 ; 701d2 .args = {mtl::Arg ::B (apv ), mtl::Arg ::B (api ), mtl::Arg ::B (tokout ), mtl::Arg ::V (a )}; 702d2 .grid [0 ]= ntok ; 703d2 .tg [0 ]= 256 ; 704push (d2 ,"lm head" ,0 ); 705 } 706// the producers' plane stride must be MAXT rows: gr_up's and swiglu's args carry n_tok for the stride, so the 707// gr_up launches above use a.n_tok = ntok - patch them to MAXT (the kernels loop over GR_NTOK tokens anyway) 708for (auto & d :ds ) 709if (d .p == pup || d .p == pupq || d .p == pnorm || d .p == pdown || d .p == pdownq ) { 710GrArgs a ; 711 std::memcpy (& a ,d .args .back ().bytes .data (),sizeof a ); 712if (d .p == pup || d .p == pupq )a .n_tok = MAXT ; 713 std::memcpy (d .args .back ().bytes .data (),& a ,sizeof a ); 714 } 715 716double total_bytes = 0 ; 717for (auto & kv :bytes_by )total_bytes += kv .second ; 718 std::printf ("%zu dispatches; weight + state bytes %.1f MB\n" ,ds .size (),total_bytes /1e6 ); 719auto run = [& ] {return graph ?cx .run_graph (ds ) :cx .run (ds ); }; 720run (); 721const double tw = mtl::now_s (); 722while (mtl::now_s ()- tw < 1.0 )run (); 723 std::vector < double > t ; 724for (int i = 0 ;i < reps ;++ i )t .push_back (run ()); 725 std::printf ("HC read: %s\n" ,hc_mode == "3" ?"BF16, 3 dispatches" :hc_mode == "2" ?"BF16, 2 dispatches" :hc_mode == "q8_3" ?"Q8_0, 3 dispatches" :"Q8_0, 2 dispatches" ); 726 std::printf ("encoding: %s\n" ,graph ?"concurrent encoder, barriers at dependencies" :"serial encoder" ); 727const double m = median (t ); 728 std::printf ("decode step (%d token(s)): GPU %.3f ms (min %.3f, max %.3f) -> %.1f GB/s effective; %.1f tok/s if " 729"every token were a window of %d\n" ,ntok ,m * 1e3 ,* std::min_element (t .begin (),t .end ())* 1e3 , 730* std::max_element (t .begin (),t .end ())* 1e3 ,total_bytes /m /1e9 ,ntok /m ,ntok ); 731for (auto & kv :bytes_by ) std::printf (" %-10s %8.1f MB\n" ,kv .first .c_str (),kv .second /1e6 ); 732return 0 ; 733}