okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7f46672a4
main
1// metal/src/engine/window.cpp - the decode window on Metal: Verifier::init/run/commit's Metal side (the one backend 2// hook, src/core/verify.cpp under STRATA_GPU_METAL). Everything above it - the decode loop, MTP control, the serve 3// protocol, the PLE table reads, the file tier - is the shared host code. 4// 5// The window is mac-kern's chain (metal/kernels, tests/token_chain.cpp) on the model GGUF itself: shard 1 is mmapped 6// and wrapped no-copy as one MTLBuffer, every weight is read where it lies (unified memory: no upload, no expert 7// cache), and one window is encoded as a dependency graph in one command buffer. Its own state lives here (the GDN 8// recurrence and conv history, the int8 K/V and the indexer per QSA layer, the PLE history): the engine's 9// SessionState buffers are not used by it, except the PLE token window (ss.ple_prev) and table. 10// 11// First version (MAC-PLAN Phase 3 start): windows of one token (no MTP drafts yet: --mtp-max-t 1), greedy. The PLE 12// block's projections run on the GPU; its norms, gate and conv (10240 values) on the CPU between two command buffers 13// (layer 0 | layers 1..47 + head). 14#include "gguf_lite.h" 15#include "mtl_rt.h" 16#include "resource_path.h" 17#include "ref_quant.h" 18#include "arena_budget.h" 19#include "stream.h" 20#include "geo.h" 21#include "msl_libs.h" 22#include "../../tests/coop_probe.h" 23 24#include "strata/artifact/gguf_reader.hpp" 25#include "strata/core/weights.hpp" 26#include "strata/core/dflash2.hpp" 27#include "strata/core/layer.hpp" 28#include "strata/core/conversation_cache.hpp" 29#include "strata/core/session.hpp" 30#include "strata/kernels/ngram.hpp" 31#include "strata/kernels/sampler.hpp" 32namespace strata::gpu {void * host_view (const void * device_pointer ); } 33#include "strata/kernels/cpu/hadamard.hpp" 34#include "strata/kernels/cpu/expert_layout.hpp" 35 36#include <algorithm> 37#include <chrono> 38#include <cmath> 39#include <cstdio> 40#include <cstdlib> 41#include <cstring> 42#include <cctype> 43#include <cerrno> 44#include <filesystem> 45#include <functional> 46#include <future> 47#include <signal.h> 48#include <unistd.h> 49#include <map> 50#include <memory> 51#include <numeric> 52#include <set> 53#include <string> 54#include <sys/mman.h> 55#include <sys/sysctl.h> 56#include <mach/mach.h> 57#include <thread> 58#include <vector> 59 60namespace strata::gpu {uint64_t purge_device_allocations (size_t min_bytes ); }// metal/src/gpu/runtime.cpp 61 62namespace { 63std::string engine_msl_dir () {return strata_metal::resource ("STRATA_METAL_ENGINE_KERNELS" ,"engine-msl" ,STRATA_METAL_ENGINE_KERNELS_DEFAULT ); } 64}// namespace 65 66namespace strata::metal_engine { 67 68// The prompt GDN scan kernel, chosen by chip and prompt length (gdn_prompt.metal, gdn_scan_r<IB, TB>; every choice is 69// bit-identical to gdn_scanr_4: the token order and the arithmetic are the same, only the staged block size TB changes, which 70// changes the threadgroup memory a core can hold at once). Measured by metal/tests/gdn_chunk_bench: 71// Apple M4 (the base chip): gdn_scanr_4_8, 1.16x on the scan, 1.11x on the GDN prompt stage, T 512..32K 72// Apple M5 Max: gdn_scanr_4_4 from T >= 4096 (1.04x at 4K, 1.10x at 16K); below that the default is as fast 73// anything else (other chips, unknown names): gdn_scanr_4 as before 74// STRATA_METAL_GDN_SCAN=<gdn_scanr_4 | gdn_scanr_4_8 | gdn_scanr_4_4 | gdn_scanr_4_2> forces a kernel (A/B and diagnosis). 75static const char * gdn_scan_name (const std::string & device ,int T ) { 76static const std::string forced = [] { 77const char * e = std::getenv ("STRATA_METAL_GDN_SCAN" ); 78const std::string s = e ?e :"" ; 79return (s == "gdn_scanr_4" || s == "gdn_scanr_4_8" || s == "gdn_scanr_4_4" || s == "gdn_scanr_4_2" ) ?s : std::string (); 80 }(); 81if (!forced .empty ())return forced .c_str (); 82if (device == "Apple M4" )return "gdn_scanr_4_8" ; 83if (device == "Apple M5 Max" && T >=4096 )return "gdn_scanr_4_4" ; 84return "gdn_scanr_4" ; 85} 86 87// The M5 family's dense GEMM tiles for the prompt (bit-identical to the 64 x 64 tile: the tile only splits the output; measured on 88// an M5 Max, T = 2048 / 4096): the GDN out projection (N 2560, K 6144) 64 x 128 (1.17 -> 0.99 ms), the wide input projections 89// (N >= 6144) 128 x 64. Other chips keep 64 x 64 (M4: no gain). STRATA_METAL_GEMM_TILES=0 keeps the old tiles everywhere. 90static void gemm_tile (const std::string & device ,int Nn ,int K ,int & tm ,int & tn ) { 91static const bool off = [] {const char * e = std::getenv ("STRATA_METAL_GEMM_TILES" );return e && std::string (e )== "0" ; }(); 92if (off || device .rfind ("Apple M5" ,0 )!= 0 )return ; 93if (Nn == strata_metal::geo::N && K == strata_metal::geo::ZV ) {tm = 64 ;tn = 128 ; } 94else if (Nn >=6144 ) {tm = 128 ;tn = 64 ; } 95} 96// The four GDN input projections (qkv, z, alpha, beta) as ONE GEMM with a 16480 float output row (M5 family: 3.09 -> 2.87 ms a layer at 97// T = 2048; gdn_pre / gdn_post read the pieces at that stride, function constant 7). Bit-identical to the separate GEMMs. 98// STRATA_METAL_GDN_FUSE=0 keeps the separate ones. 99static bool gdn_fused_inputs (const std::string & device ) { 100static const bool off = [] {const char * e = std::getenv ("STRATA_METAL_GDN_FUSE" );return e && std::string (e )== "0" ; }(); 101return !off && device .rfind ("Apple M5" ,0 )== 0 ; 102} 103 104namespace { 105 106int g_slot_cap = 0 ;// --batch N: the window keeps N + 1 sequences' running states side by side (set_batch_slots) 107 108// Q4-KQ: the kernel sources define STRATA_KQ_DOWN to instantiate the K-quant / IQ4_XS / IQ3_S down experts (moe.metal, moe_mm.metal). 109// The host asks for them only when a layer's down tensor has one of those types, so a Flash-Next set (Q5_1 / Q5_0 / Q8_0 / IQ4_NL / Q2_0 110// downs) compiles the same kernel text as before and pays nothing for them. 111std::string kq_down_prelude (const gguf::File & f ) { 112for (int l = 0 ;l < 128 ;++ l ) { 113const gguf::Tensor * t = f .find ("blk." + std::to_string (l )+ ".ffn_down_exps.weight" ); 114if (!t )continue ; 115if (t -> type == ref::Q3_K || t -> type == ref::Q4_K || t -> type == ref::Q5_K || t -> type == ref::Q6_K || t -> type == ref::IQ3_S || 116t -> type == ref::IQ4_XS ) 117return "#define STRATA_KQ_DOWN 1\n" ; 118 } 119return "" ; 120} 121 122namespace geo= strata_metal::geo;// engine/geo.h: the shape this build is compiled for (kCompiledGeometry); Flash-Next's numbers by default 123constexpr int N = geo::N ,HC = geo::HC ,LR = geo::LR ,NFF = geo::NFF ,TOPK = geo::TOPK ,NEXP = geo::NEXP ,MAXT = 8 ,NVOCAB_MAX = 248320 ; 124constexpr int G_NL = geo::NL ,G_QI = geo::QI ,G_NGDN = geo::NGDN ,G_SS = geo::SS ,G_HK = geo::HK ,G_HV = geo::HV ,G_CONV = geo::CONV , 125G_ZV = geo::ZV ,G_GDNF = geo::GDN_FUSED ,G_QH = geo::QH ,G_QKV = geo::QKV ,G_QD = geo::QD ,G_IH = geo::IH ,G_ID = geo::ID , 126G_BUD = geo::BUD ,G_QCHUNKS = geo::QCHUNKS ,G_QCHUNKS2 = geo::QCHUNKS2 ,G_QPREP = geo::QPREP ,G_HCD = geo::HCD ,G_QFULL = geo::QFULL ,G_QOUT = geo::QOUT , 127G_KV = geo::KV ,G_IQR = geo::IQR ; 128// bytes of the running state of one sequence, per layer 129constexpr size_t GST_B = (size_t )4 * G_SS * G_HV * G_SS ;// GDN recurrence 130constexpr size_t HIST_B = (size_t )4 * G_CONV * 3 ;// GDN conv history 131constexpr size_t PLEH_B = (size_t )4 * strata::kernels::NG_HIST * G_HCD ;// PLE history 132constexpr size_t TAIL_B = (size_t )4 * 4 * G_ID ;// indexer raw tail (4 cells) 133constexpr size_t DEAD_B = (size_t )4 * G_ID ;// indexer tail-block key 134constexpr int P_MAXE = 128 ,P_GEXP = 16 ,P_GSTART = P_GEXP + P_MAXE ,P_ETOK = P_GSTART + P_MAXE + 4 , 135P_EW = P_ETOK + P_MAXE ,P_TOKENT = P_EW + P_MAXE ,P_INTS = P_TOKENT + P_MAXE ,P_IGU = 4 ,P_IDN = 8 ; 136struct GemvArgs {uint32_t n_in ,n_out ,n_tok ,row_bytes ,x_stride ,y_stride ; }; 137struct GrArgs {uint32_t n_embd ,hc ,hc_lr ,n_tok ,apply ;float eps ; }; 138struct MoeArgs { 139uint64_t gate_off ,up_off ,down_off ,gu_stride ,d_stride ; 140uint32_t gu_row ,d_row ,n_embd ,n_ff ,n_tok ,topk ,n_expert ,gx_gu ,gx_dn ,pad ; 141}; 142struct GdnArgs {uint32_t h_k ,h_v ,channels ,commit ;float eps ;uint32_t plane ; }; 143struct QsaArgs {uint32_t pos0 ,pos_base ,max_cells ,n_tok ;float eps ; }; 144struct GlueArgs {uint32_t n ,n_tok ,n_embd ,topk ; }; 145struct ArgArgs {uint32_t n_vocab ,parts ; }; 146// the routed gate/up's i-quant grids from constant memory (QUANT_CTAB, function constant 23 of quant.metal): bitwise 147// the threadgroup copy's values, 3-7% faster on the M5 Max; STRATA_METAL_CTAB=0 turns it off 148bool metal_ctab () { 149static const bool on = [] { 150const char * e = std::getenv ("STRATA_METAL_CTAB" ); 151return !(e && std::string (e )== "0" ); 152 }(); 153return on ; 154} 155// STRATA_METAL_F16=1 (opt-in): the decode windows' (resident model, with the head) dense GEMVs of Q2_0, the K-quants and IQ4_XS on the fp16 path - 156// the weights decoded into half, the window's x as half planes the writers of x add (function constant 25), the 157// products of a half unit summed in half, the scales and the units' sum in float (gemv.metal gemv16) 158// Unset (owner yes 2026-11-07; was strata_control/mac_fit.py engine_env): on for a resident IQ3_S or Q2_0 pack, found from the file name the launcher's 159// models carry ("...-IQ3_S-0000N-of-0000M.gguf", "...-Q2_0-..."), decided once the model is open (f16_auto_for). M5 Max: decode +9 to +15% 160// (Q2_0) and +9 to +12% (IQ3_S), top-1 agreement 97.1% / 96.2%, mean KL 0.009 / 0.016, 61-task suite the same. STRATA_METAL_F16=0 turns it off, 161// =1 turns it on for any pack. 162bool g_f16_auto = false; 163bool metal_f16 () { 164static const int mode = [] {const char * e = std::getenv ("STRATA_METAL_F16" );return e == nullptr || * e == '\0' ?-1 : (std::string (e )== "1" ?1 :0 ); }(); 165return mode == 1 || (mode < 0 && g_f16_auto ); 166} 167bool f16_auto_for (const std::string & path ,bool streaming ) { 168if (streaming )return false; 169const size_t k = path .find_last_of ("/\\" ); 170 std::string n = k == std::string::npos ?path :path .substr (k + 1 ); 171for (char & c :n )c = (char ) std::toupper ((unsigned char )c ); 172return n .find ("-IQ3_S-" )!= std::string::npos || n .find ("-Q2_0-" )!= std::string::npos ; 173} 174// the half plane a format reads: 0 raw, 1 x * 4^-(i % 4), 2 x * 2^-8 at odd i; -1 no fp16 decode 175int x16_kind (int ty ) { 176switch (ty ) { 177case ref::IQ4_XS :return 0 ; 178case ref::Q2_0 :return 1 ; 179case ref::Q3_K :case ref::Q4_K :case ref::Q5_K :case ref::Q6_K :return 2 ; 180default :return -1 ; 181 } 182} 183// the tiles gemv.metal instantiates gemv16 on (GV16_SET) 184bool gemv16_tile (int L ,int R ,int S ,int K ) { 185static const std::array < int ,4 > t16 []= {{32 ,1 ,4 ,1 }, {32 ,2 ,4 ,1 }, {16 ,1 ,4 ,1 }, {16 ,2 ,4 ,1 }, {8 ,1 ,4 ,1 }, {8 ,2 ,4 ,1 }, {4 ,2 ,4 ,1 }, 186 {4 ,1 ,4 ,1 }, {32 ,1 ,8 ,2 }, {16 ,1 ,8 ,4 }, {2 ,1 ,4 ,1 }, {2 ,2 ,4 ,1 }, {1 ,1 ,4 ,1 }}; 187return std::find (std::begin (t16 ), std::end (t16 ), std::array < int ,4 > {L ,R ,S ,K })!= std::end (t16 ); 188} 189// the writers of the window's x: their pipelines with the half planes (function constant 25) under STRATA_METAL_F16 190mtl::Constants x16c (mtl::Constants c = {}) { return metal_f16 () ? c . b ( 25 , true) : c ; } 191std::string x16k ( const std::string & k ) { return metal_f16 () ? k + "#h" : k ; } 192 193int xkind (int t ) { 194switch ( t ) { 195case ref:: Q2_0 : return 1 ; 196case ref:: Q4_K : case ref:: Q5_K : return 2 ; 197case ref:: Q6_K : case ref:: Q3_K : return 3 ; 198default : return 0 ; 199} 200} 201 202// a prepared activation: 4 planes of MAXT rows of n, then the per-16 sums 203struct Act { 204mtl::Buffer b ; 205int n = 0 ; 206size_t plane_bytes () const { return (size_t) 4 * MAXT * n ; } 207size_t x16_bytes () const { return plane_bytes () * 4 + plane_bytes () / 16 ; } // the half planes' start (STRATA_METAL_F16) 208}; 209 210double now_ms () { return std::chrono:: duration < double, std::milli > (std::chrono::steady_clock:: now (). time_since_epoch ()). count (); } 211 212} // namespace 213 214// the prompt chain's state (prompt_chain.inc): kernel libraries, the variant, buffers for chunks of C rows 215struct PromptBufs { 216int lib = -1 , lgdn = -1 , lqsa = -1 ; 217bool k4 = false; 218bool v3e = false; 219bool v6 = false; // ragged expert tiles (mm_gu6 / mm_down6): groups of ms 16-row subtiles share one weight decode 220int ms = 1 ; 221bool fused = false; // the GDN input projections as one GEMM (gdn_fused_inputs) // the M5's expert kernels (v3): not for the trellis types, which have only v2 222int C = 0 , maxrows = 0 , tm = 16 ; // tm: the expert plan's tile height 223double gpu_ms = 0 , host_ms = 0 , mtp_ms = 0 , hidden_ms = 0 , emb_ms = 0 , ple_ms = 0 ; // hidden_ms: the host rows computed beside the GPU (pc_host_rows) 224int gu3 [ 4 ] = {}, dn3 [ 4 ] = {}; 225mtl::Buffer R , R2 , bo , inj [ 2 ], xn , xnh , V , loh , mixed , mixh , qkv , z , al , be , yg , ygh , gqn , gkn , gvc , ggb , gkq , go , qfull , 226kcur , vcur , iqr , ikr , qcur , qcurh , qidx , scores , qids , part , XQ , xqh , logits , ids , wts , bcnt , boff , eoff , tiles , meta , 227stok , sw , pos , XS , HS , YE , yr , gsh , ush , hh , ys , sgv , WD , WU , Wqkv , Wz , Wal , Wbe , Wout , Wq , Wk , Wv , Wiq , Wik , Wr , 228Wsg , Wshg , Wshu , Wshd , yf , Wcat , pemb , pembh , pkey , pval , keyn , qn , gated , normW , Wpk , Wpv , mixr ; 229}; 230 231// The vision path (--vision, GENI requests), from the shared host code: the image rows of the prompt being read 232// (host rows by absolute position, null = embed the token; set by prompt_run for its duration) and the M-RoPE table 233// (int32 [cells][3] (t, h, w); mrope_table_set: the host view of the device table the server fills per request). 234const float * const * g_embd_rows = nullptr ; 235const int32_t * g_mrope_host = nullptr ; 236const int32_t * g_mrope_dev = nullptr ; 237 238class Window { 239public : 240bool init ( const strata::core::ModelGeometry & g , strata::core::SessionState & ss , const std::string & shard1 , int max_t , 241int64_t max_cells , std::string & err ); 242bool run (int T , const int32_t * tokens , int64_t pos0 , bool head , int32_t * out , std::string & err ); 243bool commit (int n_keep , std::string & err ); 244bool finish (int Tn , const int32_t * tokens , int64_t pos0 , bool head , int32_t * out , double t0 ); 245// The request's sampling for the head rows of the windows that follow (sample.metal): null = greedy, the in-graph argmax. `hist` is the penalty 246// history, Tn rows of hist_len tokens (the last penalty_last_n of a row count, -1 = unused), read when the window's rows are sampled. 247void set_sampling ( const strata::kernels::SamplerParams * sp , const int32_t * hist , int hist_len ); 248bool sample_rows (int Tn , int32_t * out , std::string & err ); 249bool sample_slot_row (int row , const strata::kernels::SamplerParams & sp , const int32_t * hist , int hist_len , int32_t * tok , std::string & err ); // one slot's row of a batch window, its own params 250bool sample_run (int row0 , int n , const strata::kernels::SamplerParams & sp , const int32_t * hist , int hl , std::string & err ); // after run(): replaces out[0..Tn) (and tokout_) by the sampled tokens 251bool copy_logits (int t , float * host ) const ; 252int64_t vocab () const { return n_vocab_ ; } 253bool ready () const { return cx_ != nullptr ; } 254bool streaming () const { return stream_ ; } 255// --serve's conversation checkpoints: the window's running state (the GDN recurrences and conv histories, the 256// PLE history, each QSA layer's indexer tail and tail-block key); the KV and pooled keys are positional 257bool checkpoint_save (strata::core::ConversationCheckpoint & c , std::string & err ); 258bool checkpoint_restore ( const strata::core::ConversationCheckpoint & c , std::string & err ); 259// Conversation parking reads the K/V from the session's QsaStates. On Metal the K/V lives only in this window's buffers 260// (the session's own pools are never written), so each owned QsaState is pointed at the window's buffers: the same 261// cell-major layout the generic snapshot copies as byte prefixes (kq/vq cells*512 B, scales cells*16 B, pooled rows*512 B). 262void bind_session (strata::core::SessionState & ss ); 263void bind_draft (strata::core::QsaState & st ); 264bool mtp_ready () const { return mtp_on_ ; } 265void reset (); // a new sequence (session_zero): the running state zeroed 266// ---- batch slots (--batch N): each slot is another sequence's running state (GDN recurrence and conv history, the PLE 267// history, each QSA layer's K/V, indexer tail and pooled keys). The live members always hold ONE sequence's state (the 268// main one between calls); a slot's lives in a stash and is swapped in for its window (activate): the buffer objects stay 269// where they are (the cached dispatches point at them), only their contents are exchanged. 270bool slots_init ( const std::vector < strata::core::SessionState *>& slots , std::string & err ); 271int n_slots () const { return sets_ . empty () ? 0 : (int) sets_ . size () - 1 ; } 272int set_of ( const strata::core::SessionState * s ) const { 273auto it = set_of_ss_ . find ( s ); 274return it == set_of_ss_ . end () ? 0 : it -> second ; 275} 276// one window of S one-token rows, row t = slot rows[t] at position pos[t]: each runs and commits in its own state 277bool run_slots ( const int * rows , int S , const int32_t * tokens , const int64_t * pos , int32_t * out , std::string & err ); 278// slot b's state <-> the main one (the GPU is idle between windows): the running state and the first `upto` cells of K/V 279bool slot_copy (bool into_slot , int b , int64_t upto , bool kv_only , std::string & err ); 280void activate (int set ); 281void set_max_t (int t ) { max_t_ = std:: min ( t , MAXT ); } 282// ---- the MTP draft layer (mtp.hpp's math on mac-kern's kernels; the MTP GGUF from tools/mtp_pack.py) 283bool mtp_load ( const std::string & gguf , int max_t , std::string & err ); 284bool mtp_prefill ( const int32_t * next_tokens , int64_t n , int64_t cell0 , std::string & err ); 285bool mtp_draft (int T , const int32_t * tokens , int64_t p , int a , int max_steps , int32_t * drafts , float * probs , 286float min_p , int * n_drafts , std::string & err ); 287bool mtp_loaded () const { return mtp_on_ ; } 288// ---- DFlash2 (dflash2.inc): the taps of the tapped layers and the drafter 289bool taps_enable ( const std::vector < int >& layers , std::string & err ); 290void taps_set_cb (int64_t first_pos , const std::function < bool( const float * , int64_t, int64_t, std::string & ) >& cb ) { tap_first_ = first_pos ; tap_cb_ = cb ; } 291const float * tap_dec_ptr () const { return tap_dec_ . as < float > (); } 292bool tap_deliver ( const mtl::Buffer & buf , int rows , int64_t pos0 , std::string & err ); 293bool tap_deliver_dec (int rows , int64_t pos0 , std::string & err ) { return tap_deliver ( tap_dec_ , rows , pos0 , err ); } 294bool df2_ensure ( const std::string & path , std::string & err ); 295bool df2_bind ( const std::string & vocab_file , std::string & err ); 296bool df2_context_ptr ( const float * taps , int64_t n , int64_t pos0 , std::string & err ); 297bool df2_prepare (std::string & err ); 298void df2_set_cap (int n ); 299void df2_set_floor (int64_t pos ); 300int64_t df2_restore_lineage ( const std::vector < int32_t >& cur_hist , int64_t cur_hi , const int32_t * ids , int64_t resume , std::string & err ); 301void df2_kv_list (std::vector < mtl::Dispatch >& ds , int n , const mtl::Buffer & pos , size_t pos_off , const mtl::Buffer & rt , size_t rt_off ); 302int64_t df2_floor () const ; 303bool df2_draft (int n_new , int64_t pos0 , int32_t anchor , int32_t * drafts , float * probs , std::string & err ); 304uint64_t df2_bytes () const ; 305double df2_gpu_ms () const ; 306double df2_last_build_ms () const ; 307// the prompt through mac-kern's prompt kernels (prompt_chain.inc) 308bool prompt ( const int64_t * tokens , int64_t n , int64_t pos0 , 309const std::function < bool( const float * , int64_t, int64_t, std::string & ) >& on_chunk , std::string & err ); 310 311private : 312const gguf::Tensor & T ( const std::string & name ) const { 313const gguf::Tensor * t = f_ . find ( name ); 314if (! t ) { std:: fprintf ( stderr , "strata metal: the model has no tensor %s\n" , name . c_str ()); std:: exit ( 2 ); } 315return * t ; 316} 317const mtl::Pipeline * P (int lib , const std::string & fn , const mtl::Constants & c , const std::string & key ) { 318auto it = pcache_ . find ( key ); 319if ( it == pcache_ . end ()) { 320it = pcache_ . emplace ( key , cx_ -> pipeline ( lib , fn , c )). first ; 321pkey_of_ [ & it -> second ] = key ; 322} 323return & it -> second ; 324} 325void push (std::vector < mtl::Dispatch >& ds , mtl::Dispatch d ) { 326d . barrier = ! nb_ ; 327nb_ = false; 328// timing only (WRONG answers): STRATA_METAL_SKIP=a,b,... runs the dispatches whose pipeline name contains one 329// of the words as empty grids (the marginal cost of a kernel class by leaving it out) 330static const std::vector < std::string > skip = [] { 331std::vector < std::string > v ; 332if ( const char * e = std:: getenv ( "STRATA_METAL_SKIP" )) { 333std::string s = e , w ; 334for (char c : s + "," ) { if ( c == ',' ) { if (! w . empty ()) v . push_back ( w ); w . clear (); } else w += c ; } 335} 336return v ; 337}(); 338if (! skip . empty ()) { 339const std::string & k = pkey_of_ [ d . p ]; 340for ( const auto & w : skip ) 341if ( k . find ( w ) != std::string:: npos ) { d . indirect = nullptr ; d . grid [ 0 ] = 0 ; break ; } 342} 343mtl:: require_fit ( d , "engine dispatch (graph build)" ); // a kernel Metal would skip silently: stop at the build, not at the first wrong answer 344ds . push_back (std:: move ( d )); 345} 346std::map < const mtl::Pipeline * , std::string > pkey_of_ ; 347void gemv (std::vector < mtl::Dispatch >& ds , const gguf::Tensor & t , const Act & x , const mtl::Buffer & y , size_t y_stride , 348int ntok , size_t y_off = 0 , const mtl::Buffer * wb = nullptr ); 349void xprep (std::vector < mtl::Dispatch >& ds , const mtl::Buffer & x , const Act & out , int n ); 350void gr_read (std::vector < mtl::Dispatch >& ds , const std::string & pre , bool apply , const Act & out , bool final_ , int ntok ); 351void layer (std::vector < mtl::Dispatch >& ds , int l , int ntok , int64_t pos0 ); 352void ple_cpu (int T ); 353// the MTP layer: the input branches + attention HC read + K/V append for `n` rows (srcR rows, host tokens) at 354// cells cell0..; with `full` (n == 1) the rest of the layer too and the draft head into mlm_/tokout_. The 355// embedding rows go to memb_ rows erow..; tokens == nullptr: memb_ row erow already holds the embedding (put 356// there by mtp_embed on the GPU). `slot`: the dense attention's cell list (one per draft step of a round). 357void mtp_encode (std::vector < mtl::Dispatch >& ds , const mtl::Buffer & srcR , size_t src_off , int n , const int32_t * tokens , 358int64_t cell0 , bool full , int erow = 0 , int slot = 0 ); 359// a draft round's step j on the GPU: the pick and its probability (dout_/dprob_ [j]), and with `embed` the picked 360// token's embedding into memb_ row 0 (the next step's input) 361void mtp_pick (std::vector < mtl::Dispatch >& ds , int j , bool embed ); 362void gr_read_m (std::vector < mtl::Dispatch >& ds , const std::string & pre , mtl::Buffer & Rb , const mtl::Buffer & bo , 363const mtl::Buffer & inj_in , const mtl::Buffer & inj_out , bool apply , const Act & out , bool final_ , int ntok ); 364const gguf::Tensor & TM ( const std::string & name ) const { 365const gguf::Tensor * x = fm_ . find ( name ); 366if (! x ) { std:: fprintf ( stderr , "strata metal: the MTP model has no tensor %s\n" , name . c_str ()); std:: exit ( 2 ); } 367return * x ; 368} 369size_t NM ( const std::string & name ) const { // the folded (1 + w) copy of an F32 norm of the MTP model 370auto it = mnorm_off_ . find ( name ); 371if ( it == mnorm_off_ . end ()) { std:: fprintf ( stderr , "strata metal: no MTP norm %s\n" , name . c_str ()); std:: exit ( 2 ); } 372return it -> second ; 373} 374 375strata::core::SessionState * ss_ = nullptr ; // the session whose sequence the live state is (the main one, or a batch slot's) 376strata::core::SessionState * main_ss_ = nullptr ; // the main session: it owns the PLE table (read by every slot) 377gguf::File f_ ; 378std::unique_ptr < mtl::Context > cx_ ; 379mtl::Buffer W_ ; 380// a model wrapped in chunks (mtl::Context::wrap): the routed experts are bound at the layer's first expert tensor, 381// their offsets made relative to it; returns that binding offset (0 when W_ is one buffer or the experts stream) 382size_t moe_rebase (uint64_t & g , uint64_t & u , uint64_t & d ) const { 383if ( stream_ || ! W_ . chunks ) return 0 ; 384const uint64_t b = std:: min ({ g , u , d }); 385g -= b ; u -= b ; d -= b ; 386return (size_t) b ; 387} 388int lib_ = -1 , lgdn_ = -1 , lqsa_ = -1 , lsmp_ = -1 , lple_ = -1 ; 389bool samp_on_ = false; 390strata::kernels::SamplerParams samp_ ; 391const int32_t * samp_hist_ = nullptr ; 392int samp_hist_len_ = 0 ; 393mtl::Buffer sbias_ , shist_ , scv_ , sci_ ; 394size_t shist_cap_ = 0 , sbias_cap_ = 0 ; 395uint64_t samp_windows_ = 0 ; 396std::map < std::string, mtl::Pipeline > pcache_ ; 397bool nb_ = false; 398// ---- DFlash2 (dflash2.inc) 399struct Df2; 400Df2 * df2_ = nullptr ; 401bool df2_open ( const std::string & path , std::string & err ); 402bool df2_load_pack (std::string & err ); 403bool df2_context ( const mtl::Buffer & taps , size_t taps_off , int64_t n , int64_t pos0 , std::string & err ); 404void df2_ctx_list (std::vector < mtl::Dispatch >& ds , const mtl::Buffer & taps , size_t taps_off , int n , const mtl::Buffer & pos , size_t pos_off , const mtl::Buffer & rt , size_t rt_off ); 405void df2_block_list (std::vector < mtl::Dispatch >& ds ); 406void df2_mm (std::vector < mtl::Dispatch >& ds , const mtl::Buffer & qs , size_t qs_off , const mtl::Buffer & sc , size_t sc_off , uint32_t K , uint32_t rows , const mtl::Buffer & x , size_t x_off , uint32_t x_stride , const mtl::Buffer & y , size_t y_off , uint32_t y_stride , int ncol ); 407void df2_mmn (std::vector < mtl::Dispatch >& ds , const std::string & name , const mtl::Buffer & x , size_t x_off , uint32_t x_stride , const mtl::Buffer & y , uint32_t y_stride , int ncol , bool reuse = false); 408void df2_mm4 (std::vector < mtl::Dispatch >& ds , const mtl::Buffer & qs , size_t qs_off , const mtl::Buffer & sc , size_t sc_off , uint32_t K , uint32_t rows , const mtl::Buffer & x , size_t x_off , const mtl::Buffer & y , uint32_t y_stride , int ncol , bool reuse ); 409void df2_rms (std::vector < mtl::Dispatch >& ds , const mtl::Buffer & x , const mtl::Buffer & y , const char * wname , int rows ); 410void df2_free (); 411void df2_dump_rows ( const mtl::Buffer & taps , size_t taps_off , int64_t n , int64_t pos0 ); 412void df2_dump_write (int64_t s , int32_t anchor ); 413void df2_prof ( const std::vector < mtl::Dispatch >& ds ); 414bool taps_on_ = false; 415std::vector < int > tap_layers_ ; 416int tap_slot_ [ 64 ] = {}; 417int ldf2_ = -1 ; 418mtl::Buffer tap_dec_ , tap_pro_ , df2_stage_ ; 419int tap_pro_rows_ = 0 ; 420int64_t df2_stage_rows_ = 0 ; 421int64_t tap_first_ = 0 ; 422std::function < bool( const float * , int64_t, int64_t, std::string & ) > tap_cb_ ; 423void tap_dispatch (std::vector < mtl::Dispatch >& ds , int l , const mtl::Buffer & R , const mtl::Buffer & bo , const mtl::Buffer & inj , const mtl::Buffer & out , int rows ); 424mtl::Buffer & tap_pro_buf (int rows ); 425int max_t_ = 1 ; 426int nexp_ = NEXP ; // the trunk's routed experts per layer (512, or 256 for the Coder); the MTP layer is always NEXP 427int64_t max_cells_ = 0 ; 428int64_t n_vocab_ = 0 ; 429float eps_ = 1e-6f ; 430// buffers 431mtl::Buffer R_ , bo_ , inj_ [ 2 ], xn_ , lo_ , qkv_ , z_ , al_ , be_ , yg_ , logits_ , ids_ , wts_ , plan_ , h_ , ye_ , gsh_ , ush_ , 432ysh_ , sg_ , qfull_ , kcur_ , vcur_ , iqr_ , ikr_ , qcur_ , qidx_ , scores_ , qids_ , part_ , cs_ , lm_ , apv_ , api_ , tokout_ , 433emb_ , pkey_ , pval_ , qkvL_ , alL_ , beL_ , zL_ , ydump_ , keyn_ , qn_ , gated_ , normW_ , pleHist_ ; 434Act XA_ , XF_ , XY_ , XQ_ , XH_ , XE_ ; 435mtl::Buffer h16_ ; // STRATA_METAL_F16: the routed gate/up's h as half, for the down 436int cur_inj_ = 0 ; 437// state 438std::vector < mtl::Buffer > gst_ , ghist_ [ 2 ], kq_ , vq_ , ksc_ , vsc_ , tail_ , dead_ , pooled_ ; 439// --batch N: every one of those is a view of set 0 in a bigger buffer holding all N + 1 sets (the slots' running states side 440// by side), so ONE dispatch can address any slot (rinfo_: the strides and each row's slot / cell / history parity) 441bool bigs_ok_ = false; 442std::vector < mtl::Buffer > gstBig_ , hbBig_ , kqBig_ , vqBig_ , kscBig_ , vscBig_ , tailBig_ , deadBig_ , pooledBig_ ; 443mtl::Buffer pleBig_ , rinfo_ ; 444size_t st_gst_ = 0 , st_hist_ = 0 , st_kq_ = 0 , st_sc_ = 0 , st_tail_ = 0 , st_dead_ = 0 , st_pooled_ = 0 , st_ple_ = 0 ; // bytes between sets 445bool rows_ = false; // the window being built / run holds one token of each of rows_n_ DIFFERENT sequences (batch slots) 446int rows_n_ = 0 ; 447strata::core::SessionState * rows_ss_ [ MAXT ] = {}; 448int rows_set_ [ MAXT ] = {}; 449static mtl::Buffer view_of ( const mtl::Buffer & big , size_t off , size_t bytes ) { 450mtl::Buffer v = big ; 451v . ptr = (char * ) big . ptr + off ; 452v . bias = big . bias + off ; 453v . bytes = bytes ; 454return v ; 455} 456bool run_rows ( const int * rows , int S , const int32_t * tokens , const int64_t * pos , int32_t * out , std::string & err ); 457bool finish_rows (int S , const int32_t * tokens , int32_t * out , double t0 ); 458struct SeqSet { 459std::vector < mtl::Buffer > gst , gh0 , gh1 , kq , vq , ksc , vsc , tail , dead , pooled ; 460mtl::Buffer pleHist ; 461std::vector < float > ple_hist ; 462std::vector < float > last_norm ; 463int hp = 0 , pend_fold = 0 , last_T = 0 ; 464bool last_head = true; 465int32_t last_tokens [ MAXT ] = {}; 466strata::core::SessionState * ss = nullptr ; 467}; 468std::vector < std::unique_ptr < SeqSet >> sets_ ; // [0] the spare the main state is exchanged with, [b + 1] slot b 469std::map < const strata::core::SessionState * , int > set_of_ss_ ; 470int active_ = 0 ; 471void swap_state (SeqSet & o ); 472void alloc_set (SeqSet & o , bool real , int idx = 0 ); 473int hp_ = 0 ; // which of the two history buffers holds the committed conv history (all layers) 474// commit(n) of a window of several tokens: the GDN fold of the kept prefix waits for the next window and runs at 475// the start of its command buffer (one submit and wait less a round). Nothing else reads the GDN state between 476// the two (the drafter reads the window's rows and its own caches). STRATA_METAL_LAZY_FOLD=0: at commit. 477int pend_fold_ = 0 ; 478bool win_head_ = true; // the window being encoded has the head 479bool last_head_ = true; // the last window had it 480// token_chain's --fuse (mac-kern): the GDN step writes the prepared y planes itself (no xprep), and a window whose 481// context is within the selection budget skips the QSA score and top-k (the cell list is the identity: qids_ 482// holds it from init, restored after a window that selected). STRATA_METAL_FUSE=0: off. 483// gr_norm2 / moe_combine_sh2 (gr.metal, glue.metal): the same arithmetic with the loads batched ahead of the stores / sums (the 484// originals wait one memory latency per loop iteration). Bitwise the same outputs. STRATA_METAL_LDB=0: the original kernels. 485bool ldb_ = !(std:: getenv ( "STRATA_METAL_LDB" ) && std:: string (std:: getenv ( "STRATA_METAL_LDB" )) == "0" ); 486const char * k_norm () const { return ldb_ ? "gr_norm2" : "gr_norm" ; } 487const char * k_comb () const { return ldb_ ? "moe_combine_sh2" : "moe_combine_sh" ; } 488bool fuse_ = !(std:: getenv ( "STRATA_METAL_FUSE" ) && std:: string (std:: getenv ( "STRATA_METAL_FUSE" )) == "0" ); 489bool qdirty_ = false; 490// STRATA_METAL_KPROF=T (test tooling): once, after the 20th cached window of T tokens with the head, the GPU time 491// of each kernel class alone (the window's own dispatches of that pipeline + weight role, run by themselves) 492void kprof ( const std::vector < mtl::Dispatch >& ds , int Tn ); 493// STRATA_METAL_STEPPROF=T (measurement, round 0215): once, after the 20th cached head window of T tokens, where one decode step's GPU time 494// goes IN SITU, by part: the window's dispatch list is run as prefixes ending at every barrier group (STRATA_METAL_STEPPROF_REPS runs each, 495// default 5, median); a group's time is the difference of two prefixes, so the gaps between dispatches and the overlap of the groups that 496// share a barrier are inside the numbers. Also the weight bytes read per part (dense from the tensor table, experts from the routed ids of 497// every layer: the distinct experts) and the GB/s each part reaches. STRATA_METAL_STEPPROF_OUT=path: one line per group. 498void stepprof ( const std::vector < mtl::Dispatch >& ds , int Tn ); 499void fold (std::vector < mtl::Dispatch >& ds , int n_keep , int hp ); 500// the encoded window per (T, head, hp_): built once, then only the positions are patched (the host's encode cost) 501struct Cached { 502std::vector < mtl::Dispatch > ds ; 503std::vector < int > cuts ; // SSD streaming: the segment ends (one per layer, before its experts) 504std::vector < std::pair < int, int >> qsa ; // (dispatch, kind): 0 QsaArgs n_tok = T, 1 the merge (MAXT), 2 the scores 505}; 506std::map < int, Cached > wcache_ ; 507bool f16_enc_ = false; // STRATA_METAL_F16: a decode window is being encoded (the MTP layer stays fp32) 508std::vector < std::pair < int, int >>* rec_ = nullptr ; 509// ---- SSD streaming (stream.h): the dense weights in W_, the routed experts in the arena 510std::unique_ptr < ExpertStream > st_ ; 511bool stream_ = false, st_pred_ = false; 512std::vector < int >* cuts_ = nullptr ; 513mtl::Buffer predL_ , predL2_ ; // 48 x MAXT x 512: layer l + 1's (l + 2's) router logits from layer l's FFN input 514int seg_T_ = 0 ; 515bool stream_arena (std::string & err ); 516double run_ds (Cached & c ); 517// prompts on the matrix units (prompt_chunk below) 518struct PromptGemm; 519PromptGemm * pg_ = nullptr ; 520const int32_t * cut_ids_ = nullptr ; // the routed ids the handshake reads (a prompt chunk's; else ids_) 521const mtl::Buffer * mtp_src_ = nullptr ; // the rows the draft layer's prompt K/V read (a prompt chunk's; else R_) 522double pg_ms_ = 0 ; 523int64_t pg_tok_ = 0 ; 524public : 525bool prompt_gemm_on (int64_t n ) const ; 526bool prompt_gemm_init (std::string & err ); 527bool prompt_chunk ( const int32_t * tokens , int Tn , int64_t pos0 , std::string & err ); 528int prompt_chunk_rows () const ; 529void prompt_region (bool hold ) { if ( stream_ && st_ && st_ -> ready ()) st_ -> hold_region ( hold ); } 530void stream_report (FILE * f ) const { 531if (! st_ ) return ; 532st_ -> report ( f ); 533for (int t = 1 ; t <= MAXT ; ++ t ) 534if ( win_n_ [ t ]) 535std:: fprintf ( f , "stream windows T=%d %d (%s): %.2f ms each (GPU incl. the host's turns %.2f ms)\n" , t , win_n_ [ t ], 536t == 8 ? "prompt rows" : "decode" , win_ms_ [ t ] / win_n_ [ t ], win_gpu_ [ t ] / win_n_ [ t ]); 537} 538int win_n_ [ MAXT + 1 ] = {}; 539double win_ms_ [ MAXT + 1 ] = {}, win_gpu_ [ MAXT + 1 ] = {}; 540void at_cut (int s ) { 541st_ -> at_layer ( s , seg_T_ , TOPK , cut_ids_ ? cut_ids_ : ids_ . as < int32_t > (), st_pred_ && ! cut_ids_ ? predL_ . as < float > () + (size_t) s * MAXT * 512 : nullptr , 542predL2_ . ptr && ! cut_ids_ ? predL2_ . as < float > () + (size_t) s * MAXT * 512 : nullptr ); 543} 544private : 545std::vector < float > ple_hist_ ; // NG_HIST x hc_dim normalized rows, row-fastest 546bool ple_on_ = false; 547int last_T_ = 0 ; 548double last_gpu_ms_ = 0 ; 549int last_n_disp_ = 0 ; 550int32_t last_tokens_ [ MAXT ] = {}; 551std::vector < float > last_norm_ ; // the window's normalized PLE rows (T x hc_dim), for commit 552// STRATA_METAL_LOGPOS=<path> (test tooling, one-token windows): per decode position the log-probability of the 553// token that came next (the next window's input: with --spec-follow, the forced text) and the top 64, in the 554// KL harness's row format (phaseA-tests cuda_p0/cuda_kl.py load_lp): pos, target, lp, argmax, 4 x 0, id:lp ... 555std::FILE * logpos_ = nullptr ; 556bool lp_pend_ = false; 557int64_t lp_pos_ = 0 , lp_first_ = -1 ; 558int32_t lp_arg_ = 0 ; 559double lp_lse_ = 0.0 ; 560std::vector < float > lp_row_ ; 561std::vector < std::pair < float, int32_t >> lp_top_ ; 562void logpos (int Tn , const int32_t * tokens , int64_t pos0 , bool head ); 563// STRATA_METAL_PROFILE=1: where a window's time goes, per window size (printed when the window goes away) 564struct Prof { int64_t n = 0 ; double pre = 0 , rg = 0 , gpu = 0 , fin = 0 , all = 0 ; }; 565std::map < int, Prof > prof_ ; 566Prof cprof_ , dprof_ ; // commit (folds), the draft rounds 567double tp_pre_ = 0 , tp_rg_ = 0 ; 568bool prof_printed_ = false; 569public : 570void print_prof (bool periodic = false); 571~ Window (); 572void prof_add (bool draft , double ms ) { Prof & x = draft ? dprof_ : cprof_ ; ++ x . n ; x . all += ms ; } 573private : 574// the Q8_0 copies of the hyper-connection matrices (the default; STRATA_HC_Q8=0: the BF16 originals) 575// Gyro (agentionai's Hadamard-folded trellis experts, native_experts.txt v5 + hadamard.txt): the gate/up input is 576// H (s * x) and the down input H h, per block of 128; XR_ holds the rotated rows, hsx_/hsh_ the +/-1 signs 577bool had_on_ = false; 578int had_block_ = 128 ; 579bool gyro_dense_ = false; // a trellis-expert file: its dense K-quants get their own GEMV tiles (gemv() below) 580bool had_gu (int l ) const { return had_on_ && strata::kernels::cpu:: hadamard_spec (). gu ( l ); } 581bool had_dn (int l ) const { return had_on_ && strata::kernels::cpu:: hadamard_spec (). down ( l ); } 582mtl::Buffer XR_ , hsx_ , hsh_ ; 583// one rotation dispatch: rows of `width` values (a multiple of 128) in place or from x to y; f16 = half rows 584void had_rows (std::vector < mtl::Dispatch >& ds , int lib , const std::string & pfx , const mtl::Buffer & x , size_t x_off , 585const mtl::Buffer & y , size_t y_off , int rows , int width , const mtl::Buffer * signs , bool f16 ); 586// the prompt's h rows (half, padded rows of the expert tiles, their count in meta[8]): rotated in place, one 587// threadgroup a row through the indirect grid 588void had_rows_ind (std::vector < mtl::Dispatch >& ds , int lib , const std::string & pfx , const mtl::Buffer & h , const mtl::Buffer & meta ); 589bool hc_q8_ = false; 590mtl::Buffer Q8_ ; 591std::map < std::string, size_t > q8off_ ; 592// MTP 593bool mtp_on_ = false; 594int lmtp_ = -1 ; 595gguf::File fm_ ; 596mtl::Buffer Wm_ , mnorm_ , mR_ , memb_ , men_ , me2_ , mhn_ , mh2_ , midx_ , mbo_ , minj_ [ 2 ], mqids_ , mlm_ ; 597std::map < std::string, size_t > mnorm_off_ ; 598std::vector < mtl::Buffer > mkq_ , mvq_ , mksc_ , mvsc_ , mtail_ , mdead_ , mpooled_ ; 599// the draft head over a token subset (data/draft_vocab.bin, as the CUDA drafter): its rows gathered from the head 600mtl::Buffer mhead_ ; 601gguf::Tensor mhead_t_ ; 602std::vector < int32_t > dvocab_ ; 603// the draft layer's BF16 matrices in Q8_0 (half the bytes a draft step reads; drafts only: the verify window 604// decides every token). STRATA_METAL_MTP_Q8=0 keeps BF16. 605mtl::Buffer mq8_ ; 606std::map < std::string, gguf::Tensor > mq8t_ ; 607const mtl::Buffer & MB ( const std::string & name ) const { return mq8t_ . count ( name ) ? mq8_ : Wm_ ; } 608const gguf::Tensor & TQ ( const std::string & name ) const { 609auto it = mq8t_ . find ( name ); 610return it != mq8t_ . end () ? it -> second : TM ( name ); 611} 612Act XEn_ , XHn_ ; 613PromptBufs pb_ ; 614// The drafter's K/V rows of a prompt chunk run on a second queue while the next chunk's main work runs on the first (the two touch 615// different buffers: the chunk's final residual rows are double-buffered, pb_.R / pb_.R2). The drafter's rows of chunk c+1 wait for 616// chunk c's (they share the drafter's cache and scratch). STRATA_METAL_MTP_OVERLAP=0: each chunk's rows run before the next chunk. 617bool mtp_ovl_ = !(std:: getenv ( "STRATA_METAL_MTP_OVERLAP" ) && std:: string (std:: getenv ( "STRATA_METAL_MTP_OVERLAP" )) == "0" ); 618void * mtp_async_ = nullptr ; 619void mtp_wait () { if ( mtp_async_ ) { cx_ -> wait_async ( mtp_async_ ); mtp_async_ = nullptr ; } } 620mtl::Buffer mpemb_ ; // the drafter's prompt embedding rows (mtp_prefill, one command buffer) 621size_t mpemb_rows_ = 0 ; 622const mtl::Buffer * membp_ = nullptr ; // mtp_encode's embedding rows (nullptr: memb_) 623const mtl::Buffer * mpsrc_ = nullptr ; // the drafter's prompt rows (nullptr: R_) 624bool coop_k4 (); 625// the vision path: the embedding row of an absolute position (an image row, or null), the M-RoPE table rows a 626// window reads copied into mrope_ (qsa_prep's buffer 20, function constant 24) 627const float * img_row (int64_t pos ) const { return g_embd_rows ? g_embd_rows [ pos ] : nullptr ; } 628mtl::Buffer mrope_ ; 629// the PLE conv kernel as F16 (ple_conv_add reads half): the file's own F16 tensor, or an F32 one (Unsloth's) 630// narrowed with round-to-nearest-even as the host loader does 631mtl::Buffer plekw_ ; 632bool plekw_own_ = false; 633mtl::Arg kw_arg () { return plekw_own_ ? mtl::Arg:: B ( plekw_ ) : mtl::Arg:: B ( W_ , T ( "blk.1.ple_conv1d.weight" ). offset ); } 634const uint16_t * kw_host () { 635return plekw_own_ ? plekw_ . as < uint16_t > () 636: ( const uint16_t * ) (( const uint8_t * ) W_ . ptr + T ( "blk.1.ple_conv1d.weight" ). offset ); 637} 638bool mrope_on () const { return g_mrope_host != nullptr ; } 639void mrope_sync (int64_t c0 , int64_t n ) { 640if (! mrope_on ()) return ; 641const int64_t a = std:: max < int64_t > ( 0 , c0 & ~(int64_t) 3 ), b = std:: min < int64_t > ( max_cells_ , c0 + n ); 642if ( b > a ) std:: memcpy ( mrope_ . as < int32_t > () + a * 3 , g_mrope_host + a * 3 , (size_t) ( b - a ) * 12 ); 643} 644mtl::Constants qsa_c () const { return mrope_on () ? mtl:: Constants (). b ( 24 , true) : mtl:: Constants (); } 645std::string qsa_k () const { return mrope_on () ? "qsa_prep#mrope" : "qsa_prep" ; } 646int m5_layout_ = -1 ; // the M5's matmul2d layout (coop_k4), asked once: the M4's tiles differ 647bool m5_layout () { if ( m5_layout_ < 0 ) m5_layout_ = coop_k4 () ? 1 : 0 ; return m5_layout_ == 1 ; } 648bool pc_setup (int C ); 649void pc_kprof ( const std::vector < mtl::Dispatch >& ds , int nT , int64_t pos0 ); 650// the chunk's host rows (the embedding rows and the PLE table rows): computed on a thread while the GPU runs the previous 651// chunk (STRATA_METAL_PROMPT_HOSTPIPE=0 computes them inline before each chunk) 652struct PcHost { 653int nT = 0 ; 654int64_t pos0 = -1 ; 655std::vector < float > emb , ple ; 656double ms = 0 , ms_emb = 0 ; 657bool ok = true; 658std::string err ; 659}; 660bool pc_host_rows ( const int64_t * tokens , int nT , int64_t pos0 , const int32_t prev_in [ 2 ], PcHost & out ); 661std::future < PcHost > pc_next_ ; 662void pc_drain () { if ( pc_next_ . valid ()) pc_next_ . wait (); } 663bool pc_chunk ( const int64_t * tokens , int nT , int64_t pos0 , std::string & err , const int64_t * next_tokens = nullptr , int next_nT = 0 ); 664// the draft round in one command buffer (msl/mtp_chain.metal): STRATA_METAL_MTP_CHAIN=0 runs a command buffer 665// per step with the host's pick and embedding (as before) 666int lchain_ = -1 ; 667bool chain_ = false; 668mtl::Buffer dout_ , dprob_ , posv_ , dmap_ ; 669}; 670 671namespace { 672// A repack (metal_repack.py: <file>.repack.lock) or setup's model preparation (.preparing.lock) beside the GPU's file holds a lock 673// with its pid. The repack and the pack move 100+ GB through the disk and one holds up to 20 GB of memory: an engine of 70-90 GB 674// beside them is what froze the 128 GB M5 Max twice (watchdog panics, 2026-10-13). Returns the pid of a live one, else 0. 675// STRATA_METAL_IGNORE_REPACK=1 starts anyway (your choice). 676long repack_pid_running ( const std::string & model_file ) { 677namespace fs = std::filesystem; 678std::error_code ec ; 679const fs::path dir = fs:: path ( model_file ). parent_path (). empty () ? fs:: path ( "." ) : fs:: path ( model_file ). parent_path (); 680for ( const auto & e : fs:: directory_iterator ( dir , ec )) { 681const std::string n = e . path (). filename (). string (); 682const bool lock = n == ".preparing.lock" || ( n . size () > 12 && n . compare ( n . size () - 12 , 12 , ".repack.lock" ) == 0 ); 683if (! lock ) continue ; 684std::FILE * f = std:: fopen ( e . path (). string (). c_str (), "r" ); 685long pid = 0 ; 686if ( f ) { if (std:: fscanf ( f , "%ld" , & pid ) != 1 ) pid = 0 ; std:: fclose ( f ); } 687if ( pid > 0 && pid != (long) getpid () && ( kill ((pid_t) pid , 0 ) == 0 || errno == EPERM )) return pid ; 688} 689return 0 ; 690} 691} // namespace 692 693bool Window:: init ( const strata::core::ModelGeometry & g , strata::core::SessionState & ss , const std::string & shard1 , 694int max_t , int64_t max_cells , std::string & err ) { 695ss_ = & ss ; 696main_ss_ = & ss ; 697max_t_ = std:: min ( max_t , MAXT ); 698max_cells_ = max_cells ; 699// The 19 fields the CUDA guard compares with the compiled shape (strata::geometry_unsupported, + rms_eps); the two it leaves free are 700// checked here: the routed experts per layer (the router kernels take NL = 16, i.e. 512, and 8, i.e. 256 for the expert-pruned 701// Coder) and the experts per token (the kernels are built for TOPK). 702const bool experts_ok = g . n_expert == NEXP || ( NEXP == 512 && g . n_expert == 256 ); 703if (!strata:: geometry_unsupported ( g ). empty () || ! experts_ok || g . n_expert_used != TOPK ) { 704err = "metal window: the geometry differs from Qwen3.8-Flash-Next's" ; 705return false; 706} 707nexp_ = (int) g . n_expert ; // 512, or 256 (the expert-pruned Coder); the routers' logits rows keep a 512-float stride either way 708eps_ = 1e-6f ; 709const double t0 = now_ms (); 710if ( const long rp = repack_pid_running ( shard1 ); rp > 0 && !(std:: getenv ( "STRATA_METAL_IGNORE_REPACK" ) && std:: string (std:: getenv ( "STRATA_METAL_IGNORE_REPACK" )) == "1" )) { 711err = "metal window: a model repack or setup's preparation is running here (pid " + std:: to_string ( rp ) + "): the engine is not started " 712"beside it (it froze a 128 GB Mac twice); wait for it to finish, or set STRATA_METAL_IGNORE_REPACK=1" ; 713return false; 714} 715if (! f_ . open ( shard1 , err )) return false; 716cx_ = std:: make_unique < mtl::Context > (); 717stream_ = ExpertStream:: wanted ( f_ , * cx_ ); 718g_f16_auto = f16_auto_for ( f_ . path , stream_ ); // STRATA_METAL_F16 unset: a resident IQ3_S / Q2_0 pack takes the fp16 decode windows 719if ( stream_ ) { 720// the model does not fit: the dense weights are read into memory below, the experts stream from the SSD 721st_ = std:: make_unique < ExpertStream > (); 722if (! st_ -> open ( f_ , err )) return false; 723} else { 724{ // read ahead the weights, not the n-gram table: in a Gyro file it is 28.8 GB in the middle of the one file, read by the host from 725// the SSD a few rows at a time (src/ngram/ple_reader.cpp), and must not fill the page cache 726const gguf::Tensor * ple = f_ . find ( "per_layer_token_embd.weight" ); 727if ( ple == nullptr ) { 728madvise ( f_ . map , f_ . map_bytes , MADV_WILLNEED ); 729} else { 730const size_t page = 16384 ; 731const size_t lo = (size_t) ple -> offset / page * page , hi = ((size_t) ( ple -> offset + ple -> bytes ) + page - 1 ) / page * page ; 732if ( lo > 0 ) madvise ( f_ . map , lo , MADV_WILLNEED ); 733if ( hi < f_ . map_bytes ) madvise ((uint8_t * ) f_ . map + hi , f_ . map_bytes - hi , MADV_WILLNEED ); 734} 735} 736// the chunks of a model bigger than one Metal buffer overlap by the largest range bound at one offset: a tensor, 737// or a layer's routed experts (gate, up and down, bound together at the first of them: moe_rebase) 738size_t span = 0 ; 739// (not the n-gram table: the host reads it from the SSD, the GPU never binds it - in a Gyro file it is 28.8 GB of the one file) 740for ( const auto & kv : f_ . tensors ) 741if ( kv . first != "per_layer_token_embd.weight" ) span = std:: max < size_t > ( span , kv . second . bytes ); 742for (int l = 0 ; l < G_NL ; ++ l ) { 743const std::string b = "blk." + std:: to_string ( l ) + "." ; 744const gguf::Tensor * g = f_ . find ( b + "ffn_gate_exps.weight" ), * u = f_ . find ( b + "ffn_up_exps.weight" ), 745* d = f_ . find ( b + "ffn_down_exps.weight" ); 746if (! g || ! u || ! d ) continue ; 747const uint64_t lo = std:: min ({ g -> offset , u -> offset , d -> offset }); 748const uint64_t hi = std:: max ({ g -> offset + g -> bytes , u -> offset + u -> bytes , d -> offset + d -> bytes }); 749span = std:: max < size_t > ( span , hi - lo ); 750} 751W_ = cx_ -> wrap ( f_ . map , f_ . map_bytes , span ); 752if ( W_ . handle == nullptr ) { err = "metal window: cannot wrap " + shard1 + " as a Metal buffer" ; return false; } 753} 754n_vocab_ = (int64_t) T ( "output.weight" ). shape [ 1 ]; 755if ( const gguf::Tensor * e0 = f_ . find ( "blk.0.ffn_gate_exps.weight" )) gyro_dense_ = e0 -> type >= 144 ; 756{ 757using namespace strata_metal ; 758auto cc = [ & ]( const MslLib & L ) { return cx_ -> compile ( L . files , L . prelude ); }; 759lib_ = cc ( lib_core ( metal_f16 (), kq_down_prelude ( f_ ))); 760lgdn_ = cc ( lib_gdn ()); 761lqsa_ = cc ( lib_qsa ()); 762lsmp_ = cc ( lib_sample ()); 763lple_ = cc ( lib_ple ( engine_msl_dir ())); 764} 765 766const int MAXC = (int) std:: max < int64_t > ( 4096 , ( max_cells + 64 ) / 4 * 4 + 64 ), MB = MAXC / 4 + 2 ; 767max_cells_ = MAXC ; 768auto A = [ & ](size_t bytes ) { return cx_ -> alloc ( bytes ); }; 769R_ = A ( 4 * MAXT * HC * N ); bo_ = A ( 4 * MAXT * N ); inj_ [ 0 ] = A ( 4 * MAXT * HC ); inj_ [ 1 ] = A ( 4 * MAXT * HC ); 770xn_ = A ( 4 * MAXT * HC * N ); lo_ = A ( 4 * MAXT * LR ); qkv_ = A ( 4 * MAXT * G_CONV ); z_ = A ( 4 * MAXT * G_ZV ); 771al_ = A ( 4 * MAXT * G_HV ); be_ = A ( 4 * MAXT * G_HV ); yg_ = A ( 4 * MAXT * G_ZV ); logits_ = A ( 4 * MAXT * 512 ); 772ids_ = A ( 4 * MAXT * TOPK ); wts_ = A ( 4 * MAXT * TOPK ); plan_ = A ( 4 * P_INTS ); h_ = A ( 4 * MAXT * TOPK * NFF ); 773ye_ = A ( 4 * MAXT * TOPK * N ); gsh_ = A ( 4 * MAXT * NFF ); ush_ = A ( 4 * MAXT * NFF ); ysh_ = A ( 4 * MAXT * N ); 774sg_ = A ( 4 * MAXT * 4 ); qfull_ = A ( 4 * MAXT * G_QFULL ); kcur_ = A ( 4 * MAXT * G_KV ); vcur_ = A ( 4 * MAXT * G_KV ); 775iqr_ = A ( 4 * MAXT * G_IQR ); ikr_ = A ( 4 * MAXT * G_ID ); qcur_ = A ( 4 * MAXT * G_QOUT ); qidx_ = A ( 4 * MAXT * G_IH * G_ID ); 776scores_ = A ( 4 * (size_t) MAXT * MB ); qids_ = A ( 4 * MAXT * G_BUD ); part_ = A ( 4 * (size_t) MAXT * G_QCHUNKS2 * G_QH * ( G_QD + 2 )); 777cs_ = A ( 8 * (size_t) ( MAXC + 16 ) * 32 ); lm_ = A ( 4 * (size_t) MAXT * n_vocab_ ); apv_ = A ( 4 * MAXT * 120 ); 778api_ = A ( 4 * MAXT * 120 ); tokout_ = A ( 4 * MAXT ); emb_ = A ( 4 * MAXT * N ); pkey_ = A ( 4 * MAXT * G_HCD ); 779pval_ = A ( 4 * MAXT * N ); 780// the GDN layers' window inputs, kept per layer so commit() can fold the accepted prefix into the state 781qkvL_ = A ( 4 * (size_t) G_NGDN * MAXT * G_CONV ); alL_ = A ( 4 * (size_t) G_NGDN * MAXT * G_HV ); beL_ = A ( 4 * (size_t) G_NGDN * MAXT * G_HV ); 782zL_ = A ( 4 * (size_t) G_NGDN * MAXT * G_ZV ); ydump_ = A ( 4 * MAXT * G_ZV ); 783keyn_ = A ( 4 * MAXT * G_HCD ); qn_ = A ( 4 * MAXT * G_HCD ); gated_ = A ( 4 * MAXT * G_HCD ); normW_ = A ( 4 * MAXT * G_HCD ); 784mrope_ = A ( 12 * (size_t) ( MAXC + 16 )); 785bigs_ok_ = g_slot_cap > 0 ; 786const size_t NSET = 1 + (size_t) std:: max ( 0 , g_slot_cap ); 787auto R256 = [](size_t b ) { return ( b + 255 ) / 256 * 256 ; }; 788st_gst_ = R256 ( GST_B ); st_hist_ = R256 ( HIST_B ); st_kq_ = R256 ((size_t) MAXC * G_QKV * G_QD ); 789st_sc_ = R256 ( 2 * (size_t) MAXC * G_QKV * 4 ); st_tail_ = R256 ( TAIL_B ); st_dead_ = R256 ( DEAD_B ); 790st_pooled_ = R256 ( 4 * (size_t) MB * G_ID ); st_ple_ = R256 ( PLEH_B ); 791// the set-0 view of a new buffer of `bytes` per set (or a plain buffer when there are no batch slots) 792auto SV = [ & ](std::vector < mtl::Buffer >& bigs , size_t bytes , size_t stride , size_t per = 1 , size_t which = 0 ) { 793if (! bigs_ok_ ) { bigs . push_back (mtl:: Buffer ()); return A ( bytes ); } 794if ( which == 0 ) bigs . push_back ( A ( stride * per * NSET )); 795return view_of ( bigs . back (), which * stride , bytes ); 796}; 797if ( bigs_ok_ ) { pleBig_ = A ( st_ple_ * NSET ); pleHist_ = view_of ( pleBig_ , 0 , PLEH_B ); } else pleHist_ = A ( PLEH_B ); 798rinfo_ = A ( 4 * ( 8 + 4 * MAXT )); 799auto act = [ & ](int n ) { 800Act a ; 801a . n = n ; 802a . b = A ( 4 * ((size_t) 4 * MAXT * n + (size_t) MAXT * n / 16 ) + ( metal_f16 () ? (size_t) 2 * 3 * MAXT * n : 0 )); 803return a ; 804}; 805XA_ = act ( N ); XF_ = act ( N ); XY_ = act ( G_ZV ); XQ_ = act ( G_QOUT ); XH_ = act ( NFF ); XE_ = act ( N ); 806if ( metal_f16 ()) h16_ = A ( 2 * (size_t) MAXT * TOPK * NFF ); 807{ // Gyro (native_experts.txt v5 + hadamard.txt): the rotation's signs and the rotated gate/up input 808const auto & hs = strata::kernels::cpu:: hadamard_spec (); 809had_on_ = hs . any (); 810if ( had_on_ ) { 811had_block_ = hs . block ; 812if ( had_block_ != 128 ) { 813err = "metal window: the pack's Hadamard block is " + std:: to_string ( had_block_ ) + "; the Metal rotation takes 128" ; 814return false; 815} 816XR_ = A ( 4 * MAXT * N ); 817auto upload = [ & ](int w , mtl::Buffer & b ) { 818if ( const float * sg = strata::kernels::cpu:: hadamard_signs ( w )) { 819b = A ( 4 * (size_t) w ); 820std:: memcpy ( b . ptr , sg , 4 * (size_t) w ); 821} 822}; 823upload ( N , hsx_ ); 824upload ( NFF , hsh_ ); 825std:: fprintf ( stderr , "strata metal: Hadamard-folded experts (block %d): the gate/up and down inputs are rotated on the GPU\n" , 826had_block_ ); 827} 828} 829// RoPE: cos/sin [pos][32] for the first 64 dims, NEOX pairs (i, i + 32), in double as build_rope_table 830const double base = f_ . meta_num . count ( "qwen4exp.rope.freq_base" ) ? f_ . meta_num [ "qwen4exp.rope.freq_base" ] : 1e7 ; 831for (int p = 0 ; p < MAXC + 16 ; ++ p ) 832for (int i = 0 ; i < 32 ; ++ i ) { 833const double th = (double) p * std:: pow ( base , -2.0 * i / 64.0 ); 834cs_ . as < float > ()[( p * 32 + i ) * 2 ] = (float) std:: cos ( th ); 835cs_ . as < float > ()[( p * 32 + i ) * 2 + 1 ] = (float) std:: sin ( th ); 836} 837for (int t = 0 ; t < MAXT ; ++ t ) 838for (int c = 0 ; c < G_BUD ; ++ c ) qids_ . as < int > ()[ t * G_BUD + c ] = c ; 839for (int l = 0 ; l < G_NL ; ++ l ) { 840if ( l % G_QI != G_QI - 1 ) { 841gst_ . push_back ( SV ( gstBig_ , GST_B , st_gst_ )); 842ghist_ [ 0 ]. push_back ( SV ( hbBig_ , HIST_B , st_hist_ , 2 , 0 )); // [set][parity]: the two parities side by side 843ghist_ [ 1 ]. push_back ( SV ( hbBig_ , HIST_B , st_hist_ , 2 , 1 )); 844} else { 845kq_ . push_back ( SV ( kqBig_ , (size_t) MAXC * G_QKV * G_QD , st_kq_ )); 846vq_ . push_back ( SV ( vqBig_ , (size_t) MAXC * G_QKV * G_QD , st_kq_ )); 847ksc_ . push_back ( SV ( kscBig_ , 2 * (size_t) MAXC * G_QKV * 4 , st_sc_ )); 848vsc_ . push_back ( SV ( vscBig_ , 2 * (size_t) MAXC * G_QKV * 4 , st_sc_ )); 849tail_ . push_back ( SV ( tailBig_ , TAIL_B , st_tail_ )); 850dead_ . push_back ( SV ( deadBig_ , DEAD_B , st_dead_ )); 851pooled_ . push_back ( SV ( pooledBig_ , 4 * (size_t) MB * G_ID , st_pooled_ )); 852} 853} 854bind_session ( ss ); 855// ---- the HC read in Q8_0 (the owner's default on Metal, as STRATA_HC_Q8 on gfx12): the BF16 down / up / inject 856// matrices quantized once at load (ggml's q8_0 rule, ref_quant), read by gr_down_q8 / gr_up_q8 857{ 858const char * e = std:: getenv ( "STRATA_HC_Q8" ); 859hc_q8_ = !( e && std:: string ( e ) == "0" ); 860} 861{ 862const double tq = now_ms (); 863size_t tot = 0 ; 864std::vector < std::string > names ; 865for ( const auto & kv : f_ . tensors ) { 866const gguf::Tensor & x = kv . second ; 867// BF16 (when the Q8_0 read is on) and, whatever the setting, the Gyro file's Q6_K / IQ4_NL ones: the decode window's 868// hyper-connection kernels read BF16 or Q8_0 only 869const bool conv = ( x . type == ref:: BF16 && hc_q8_ ) || x . type == ref:: Q6_K || x . type == ref:: IQ4_NL ; 870if (! conv || x . name . find ( "hc_" ) == std::string:: npos || x . name . find ( "_norm" ) != std::string:: npos ) continue ; 871uint64_t ne = 1 ; 872for (uint64_t d : x . shape ) ne *= d ; 873q8off_ [ x . name ] = tot ; 874names . push_back ( x . name ); 875tot += ne / 32 * 34 ; 876} 877Q8_ = cx_ -> alloc (( tot + 4095 ) / 4096 * 4096 + 4096 ); // + a page: a file with Q8_0 HC already has no copies 878std::vector < std::thread > th ; 879const unsigned nth = std:: max ( 1u , std:: min ( 16u , std::thread:: hardware_concurrency ())); 880for (unsigned k = 0 ; k < nth ; ++ k ) 881th . emplace_back ([ & , k ] { 882std::vector < float > tmp ; 883std::vector < uint8_t > raw ; 884for (size_t i = k ; i < names . size (); i += nth ) { 885const gguf::Tensor & x = * f_ . find ( names [ i ]); 886uint64_t ne = 1 ; 887for (uint64_t d : x . shape ) ne *= d ; 888tmp . resize ( ne ); 889const uint8_t * src = ( const uint8_t * ) f_ . map + x . offset ; 890if ( stream_ ) { // F_NOCACHE reads: the page cache is kept for the arena 891raw . resize ( x . bytes ); 892if (! st_ -> read ( raw . data (), x . bytes , x . offset )) { std:: fprintf ( stderr , "strata metal: read failed\n" ); std:: exit ( 6 ); } 893src = raw . data (); 894} 895ref:: dequant ( x . type , src , tmp . data (), ne ); 896// a Q6_K / IQ4_NL matrix (Gyro) goes through BF16 first: the form the pack gives the CUDA engine 897// (tools/iq_pack.py --compat-bf16), so the Q8_0 copy below is made from the same numbers 898if ( x . type != ref:: BF16 ) 899for (uint64_t i = 0 ; i < ne ; ++ i ) tmp [ i ] = ref:: bf16_to_f32 (ref:: f32_to_bf16 ( tmp [ i ])); 900ref:: quantize_q8_0 ( tmp . data (), ne , Q8_ . as < uint8_t > () + q8off_ [ names [ i ]]); 901} 902}); 903for (auto & x : th ) x . join (); 904std:: fprintf ( stderr , "strata metal: HC read in Q8_0 (STRATA_HC_Q8=0: BF16): %zu matrices, %.0f MB, made in %.0f ms\n" , 905names . size (), tot / 1e6 , now_ms () - tq ); 906} 907if ( stream_ ) { 908std::vector < std::string > skip ; // the BF16 originals of the Q8_0 HC copies are not read again 909if ( hc_q8_ ) 910for ( const auto & kv : q8off_ ) skip . push_back ( kv . first ); 911if (! st_ -> load_dense ( f_ , * cx_ , skip , W_ , err )) return false; 912const char * e = std:: getenv ( "STRATA_METAL_PREFETCH" ); 913st_pred_ = !( e && std:: atoi ( e ) <= 0 ); 914if ( st_pred_ ) predL_ = A ( 4 * (size_t) G_NL * MAXT * 512 ); 915if ( st_pred_ && st_ -> ahead2 () > 0 ) predL2_ = A ( 4 * (size_t) G_NL * MAXT * 512 ); 916if ( nexp_ < NEXP ) { // the predictor reads 512 logits a token: the columns past the trunk's experts must never win 917for (mtl::Buffer * pb : { & predL_ , & predL2_ }) 918if ( pb -> ptr ) 919for (size_t r = 0 ; r < (size_t) G_NL * MAXT ; ++ r ) 920for (int c = nexp_ ; c < NEXP ; ++ c ) pb -> as < float > ()[ r * 512 + c ] = - INFINITY ; 921} 922} 923ple_on_ = ss . ple . ready () && f_ . find ( "blk.1.ple_key.weight" ) != nullptr ; 924if ( ple_on_ && T ( "blk.1.ple_conv1d.weight" ). type == ref:: F32 ) { 925const gguf::Tensor & k = T ( "blk.1.ple_conv1d.weight" ); 926const size_t ne = k . bytes / 4 ; 927plekw_ = cx_ -> alloc (( ne * 2 + 4095 ) / 4096 * 4096 ); 928const float * src = ( const float * ) (( const uint8_t * ) W_ . ptr + k . offset ); 929uint16_t * dst = plekw_ . as < uint16_t > (); 930for (size_t i = 0 ; i < ne ; ++ i ) dst [ i ] = ref:: f32_to_f16 ( src [ i ]); 931plekw_own_ = true; 932} 933ple_hist_ . assign ((size_t) strata::kernels:: NG_HIST * strata::kernels:: NG_HC_DIM , 0.0f ); 934last_norm_ . assign ((size_t) MAXT * strata::kernels:: NG_HC_DIM , 0.0f ); 935std:: fprintf ( stderr , "strata metal: decode window on %s: %s %s (%.1f GB), %d cells, PLE %s, ready in %.0f ms\n" , 936cx_ -> device_name (). c_str (), shard1 . c_str (), stream_ ? "streamed from the SSD (experts)" : "wrapped" , 937f_ . file_bytes / 1e9 , MAXC , ple_on_ ? "on" : "OFF" , now_ms () - t0 ); 938return true; 939} 940 941void Window:: gemv (std::vector < mtl::Dispatch >& ds , const gguf::Tensor & t , const Act & x , const mtl::Buffer & y , 942size_t y_stride , int ntok , size_t y_off , const mtl::Buffer * wb ) { 943const int n_in = (int) t . shape [ 0 ], n_out = t . shape . size () > 1 ? (int) t . shape [ 1 ] : 1 ; 944const int ty = t . type ; 945int L = 16 , Rr = 1 , S = 4 , K = 1 ; 946if ( n_in >= 6144 ) { L = 32 ; Rr = 1 ; S = 8 ; K = 2 ; } 947else if ( n_in == 640 ) { L = 8 ; Rr = 1 ; S = 4 ; K = 1 ; } 948else if ( n_out <= 640 || ty == ref:: Q2_0 || ty == ref:: BF16 ) { L = 32 ; Rr = 1 ; S = 4 ; K = 1 ; } 949static const bool gyro_tiles = !(std:: getenv ( "STRATA_METAL_GYRO_TILES" ) && std:: string (std:: getenv ( "STRATA_METAL_GYRO_TILES" )) == "0" ); // off: the A/B arm 950if ( gyro_dense_ && gyro_tiles && ntok >= 2 ) { 951// Gyro's dense weights are Q5_K / Q6_K / Q8_0 (3.6 GB a token). gemv_parity --one on the M4, 2 tokens: Q5_K 2560->10240 952// 261 us with 16,1,4,1 against 210 with 2,1,4,1 (-20%), 2560->6144 158 -> 129, 6144->2560 162 -> 139, 2560->12288 953// 313 -> 247, and the shared down Q8_0 640->2560 36 -> 19 us with 4,2,4,1. (The tile changes the order of the lane sums.) 954if ( ty == ref:: Q5_K && n_in == 2560 && n_out >= 6144 ) { L = 2 ; Rr = 1 ; S = 4 ; K = 1 ; } 955else if ( ty == ref:: Q5_K && n_in == 6144 ) { L = 2 ; Rr = 1 ; S = 4 ; K = 1 ; } 956else if ( ty == ref:: Q8_0 && n_in == 640 ) { L = 4 ; Rr = 2 ; S = 4 ; K = 1 ; } 957} 958{ 959// windows of several tokens: NR rows a lane share each x load (the window's cost is its x traffic). The sums 960// run in the same order for any NR, so the answers do not change. STRATA_METAL_GEMV_NR (1, 2): the tile. 961static const int nr_env = [] { const char * e = std:: getenv ( "STRATA_METAL_GEMV_NR" ); return e ? std:: atoi ( e ) : 1 ; }(); 962if ( ntok > 1 && nr_env == 2 && n_out >= 2048 ) { 963if ( S == 8 && K == 2 ) { S = 4 ; K = 2 ; } 964if ( S == 8 && K == 1 ) S = 4 ; 965if ( K == 1 || ( L == 32 && K == 2 )) Rr = 2 ; 966} 967} 968const int k16 = f16_enc_ && x . n == n_in ? x16_kind ( ty ) : -1 ; 969const bool f16 = k16 >= 0 && gemv16_tile ( L , Rr , S , K ); 970const std::string fn = std:: string ( f16 ? "gemv16_" : "gemv_" ) + std:: to_string ( ty ) + "_" + std:: to_string ( L ) + "_" + 971std:: to_string ( Rr ) + "_" + std:: to_string ( S ) + "_" + std:: to_string ( K ); 972const mtl::Pipeline * p = P ( lib_ , fn , mtl:: Constants (). i ( 0 , ntok ), fn + "#" + std:: to_string ( ntok )); 973GemvArgs 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 , 974(uint32_t) y_stride }; 975mtl::Dispatch d ; 976d . p = p ; 977d . args = {mtl::Arg:: B ( wb ? * wb : W_ , t . offset ), 978f16 ? mtl::Arg:: B ( x . b , x . x16_bytes () + (size_t) k16 * 2 * MAXT * n_in ) : mtl::Arg:: B ( x . b , x . plane_bytes () * xkind ( ty )), 979mtl::Arg:: B ( x . b , x . plane_bytes () * 4 ), mtl::Arg:: B ( y , y_off ), mtl::Arg:: V ( a )}; 980const int rpt = ( S / K ) * ( 32 / L ) * Rr ; 981d . grid [ 0 ] = ( n_out + rpt - 1 ) / rpt ; 982d . tg [ 0 ] = S * 32 ; 983push ( ds , d ); 984} 985 986void Window:: xprep (std::vector < mtl::Dispatch >& ds , const mtl::Buffer & x , const Act & out , int n ) { 987mtl::Dispatch d ; 988d . p = P ( lib_ , "xprep" , x16c (), x16k ( "xprep" )); 989const uint32_t nn = n , nt = MAXT ; 990d . args = {mtl::Arg:: B ( x ), mtl::Arg:: B ( out . b ), mtl::Arg:: V ( nn ), mtl::Arg:: V ( nt )}; 991d . tg [ 0 ] = 256 ; 992d . grid [ 0 ] = ( n / 16 * MAXT + 255 ) / 256 ; 993push ( ds , d ); 994} 995 996// the hyper-connection read (gr.metal, 3 dispatches): the previous sublayer's write folded in when `apply` 997void Window:: gr_read (std::vector < mtl::Dispatch >& ds , const std::string & pre , bool apply , const Act & out , bool final_ , 998int ntok ) { 999const gguf::Tensor & tn = T ( pre + "_norm.weight" ); 1000const gguf::Tensor & tdn = T ( pre + "_down.weight" ); 1001const gguf::Tensor & tup = T ( pre + "_up.weight" ); 1002const gguf::Tensor & tin = final_ ? tdn : T ( pre + "_inject.weight" ); 1003GrArgs a { N , HC , LR , (uint32_t) ntok , apply ? 1u : 0u , eps_ }; 1004mtl::Dispatch d1 ; 1005d1 . p = P ( lib_ , k_norm (), {}, k_norm ()); 1006d1 . 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_ ), 1007mtl::Arg:: V ( a )}; 1008d1 . grid [ 0 ] = HC ; 1009d1 . grid [ 1 ] = ntok ; 1010d1 . tg [ 0 ] = 256 ; 1011push ( ds , d1 ); 1012// each matrix: its load-time Q8_0 copy (q8off_), else the file's own tensor (Unsloth's are Q8_0 already, their 1013// inject rows F32) 1014auto src = [ & ]( const gguf::Tensor & t ) -> std::pair < const mtl::Buffer * , size_t > { 1015auto it = q8off_ . find ( t . name ); 1016return it != q8off_ . end () ? std:: make_pair ( & Q8_ , it -> second ) : std:: make_pair ( & W_ , (size_t) t . offset ); 1017}; 1018auto is_q8 = [ & ]( const gguf::Tensor & t ) { return q8off_ . count ( t . name ) || t . type == ref:: Q8_0 ; }; 1019const auto [ bd , od ] = src ( tdn ); 1020const auto [ bi , oi ] = src ( tin ); 1021const auto [ bu , ou ] = src ( tup ); 1022const bool q8 = is_q8 ( tdn ) && is_q8 ( tup ); 1023const bool injf = q8 && ! final_ && ! q8off_ . count ( tin . name ) && tin . type == ref:: F32 ; 1024mtl::Dispatch d2 ; 1025static const bool hcld = std:: getenv ( "STRATA_METAL_HCLD" ) && std:: string (std:: getenv ( "STRATA_METAL_HCLD" )) == "1" ; // OFF (measured -10.9%, 4 of 4 rounds, M5 Max UD-Q4_K_XL): the HC kernels' units loaded two or three at a time, bitwise the same; registers and occupancy, as the earlier gemvu / moeu unrolls 1026const char * dn = injf ? ( hcld ? "gr_downp_q8f_8_8" : "gr_down_q8f_8_8" ) : q8 ? ( hcld ? "gr_downp_q8_8_8" : "gr_down_q8_8_8" ) : "gr_down_8_8" ; 1027d2 . p = P ( lib_ , dn , mtl:: Constants (). i ( 1 , ntok ), std:: string ( dn ) + "#" + std:: to_string ( ntok )); 1028d2 . args = {mtl::Arg:: B ( * bd , od ), mtl::Arg:: B ( * bi , oi ), mtl::Arg:: B ( xn_ ), mtl::Arg:: B ( lo_ ), 1029mtl::Arg:: B ( inj_ [ 1 - cur_inj_ ]), mtl::Arg:: V ( a )}; 1030d2 . grid [ 0 ] = LR + HC ; 1031d2 . tg [ 0 ] = 256 ; 1032push ( ds , d2 ); 1033mtl::Dispatch d3 ; 1034const char * up = q8 ? ( hcld ? "gr_upp_q8" : "gr_up_q8" ) : "gr_up" ; 1035d3 . p = P ( lib_ , up , x16c (mtl:: Constants (). i ( 1 , ntok )), x16k (std:: string ( up ) + "#" + std:: to_string ( ntok ))); 1036GrArgs au = a ; 1037au . n_tok = MAXT ; // the plane stride of the prepared activation 1038d3 . args = {mtl::Arg:: B ( * bu , ou ), mtl::Arg:: B ( lo_ ), mtl::Arg:: B ( xn_ ), mtl::Arg:: B ( out . b ), mtl::Arg:: V ( au )}; 1039d3 . grid [ 0 ] = N / 16 ; 1040d3 . tg [ 0 ] = 256 ; 1041push ( ds , d3 ); 1042cur_inj_ = 1 - cur_inj_ ; 1043} 1044 1045namespace { 1046struct HadArgs { uint32_t width , x_stride , y_stride ; float scale ; uint32_t has_signs , pad ; }; // quant.metal 1047} 1048// y = H (s * x) per block of 128 values of `rows` rows of `width` (x_off / y_off: byte offsets; f16: half rows, no signs) 1049void Window:: had_rows (std::vector < mtl::Dispatch >& ds , int lib , const std::string & pfx , const mtl::Buffer & x , size_t x_off , 1050const mtl::Buffer & y , size_t y_off , int rows , int width , const mtl::Buffer * signs , bool f16 ) { 1051HadArgs a {(uint32_t) width , (uint32_t) width , (uint32_t) width , 1.0f / std:: sqrt ((float) had_block_ ), signs ? 1u : 0u , 0u }; 1052const char * fn = f16 ? "had128_f16" : "had128_f32" ; 1053mtl::Dispatch d ; 1054d . p = P ( lib , fn , {}, pfx + fn ); 1055d . args = {mtl::Arg:: B ( x , x_off ), mtl::Arg:: B ( y , y_off ), mtl::Arg:: B ( signs ? * signs : x ), mtl::Arg:: V ( a )}; 1056d . grid [ 0 ] = width / 128 ; 1057d . grid [ 1 ] = rows ; 1058d . tg [ 0 ] = 128 ; 1059push ( ds , d ); 1060} 1061 1062void Window:: had_rows_ind (std::vector < mtl::Dispatch >& ds , int lib , const std::string & pfx , const mtl::Buffer & h , 1063const mtl::Buffer & meta ) { 1064HadArgs a {(uint32_t) NFF , (uint32_t) NFF , (uint32_t) NFF , 1.0f / std:: sqrt ((float) had_block_ ), hsh_ . handle ? 1u : 0u , 0u }; 1065mtl::Dispatch d ; 1066d . p = P ( lib , "had128_f16_rows" , {}, pfx + "had128_f16_rows" ); 1067d . args = {mtl::Arg:: B ( h ), mtl::Arg:: B ( h ), mtl::Arg:: B ( hsh_ . handle ? hsh_ : h ), mtl::Arg:: V ( a )}; 1068d . tg [ 0 ] = 128 ; 1069d . indirect = & meta ; 1070d . ind_off = 8 * 4 ; // (rows, 1, 1): the padded rows of the tiles 1071push ( ds , d ); 1072} 1073 1074void Window:: layer (std::vector < mtl::Dispatch >& ds , int l , int ntok , int64_t pos0 ) { 1075const std::string b = "blk." + std:: to_string ( l ) + "." ; 1076// ---- the mixer: layer 1's read after the PLE is not applied again (its pending write was applied before it) 1077gr_read ( ds , b + "hc_attn" , l > 0 && !( l == 1 && ple_on_ ), XA_ , false, ntok ); 1078if ( l % G_QI != G_QI - 1 ) { 1079const int gi = l - l / G_QI ; 1080// a one-token window commits in the step; a longer one leaves the state and commit() folds the kept prefix 1081// from the inputs kept per layer (qkvL_ ...) 1082const bool self_commit = ntok == 1 ; 1083const uint32_t cm = self_commit ? 1u : 0u ; 1084const size_t o_qkv = (size_t) gi * MAXT * G_CONV * 4 , o_ab = (size_t) gi * MAXT * G_HV * 4 , o_z = (size_t) gi * MAXT * G_ZV * 4 ; 1085gemv ( ds , T ( b + "attn_qkv.weight" ), XA_ , qkvL_ , G_CONV , ntok , o_qkv ); 1086nb_ = true; 1087gemv ( ds , T ( b + "attn_gate.weight" ), XA_ , zL_ , G_ZV , ntok , o_z ); 1088nb_ = true; 1089gemv ( ds , T ( b + "ssm_alpha.weight" ), XA_ , alL_ , G_HV , ntok , o_ab ); 1090nb_ = true; 1091gemv ( ds , T ( b + "ssm_beta.weight" ), XA_ , beL_ , G_HV , ntok , o_ab ); 1092GdnArgs a { G_HK , G_HV , G_CONV , cm , eps_ , fuse_ ? (uint32_t) ( MAXT * G_ZV ) : 0u }; 1093mtl::Dispatch d ; 1094d . p = P ( lgdn_ , "gdn_step" , x16c (mtl:: Constants (). i ( 2 , ntok )), x16k ( "gdn_step#" + std:: to_string ( ntok ))); 1095const int hp = hp_ ; 1096if ( rows_ ) { // each row is a different sequence: its own state, parity and conv history (rinfo_), one grid row each 1097d . p = P ( lgdn_ , "gdn_step" , mtl:: Constants (). i ( 2 , 1 ). b ( 31 , true), "gdn_step#rows" ); 1098GdnArgs ar { G_HK , G_HV , G_CONV , 1u , eps_ , fuse_ ? (uint32_t) ( MAXT * G_ZV ) : 0u }; 1099d . args = {mtl::Arg:: B ( gstBig_ [(size_t) gi ]), mtl::Arg:: B ( hbBig_ [(size_t) gi ]), mtl::Arg:: B ( qkvL_ , o_qkv ), 1100mtl::Arg:: B ( alL_ , o_ab ), mtl::Arg:: B ( beL_ , o_ab ), mtl::Arg:: B ( zL_ , o_z ), 1101mtl::Arg:: B ( W_ , T ( b + "ssm_conv1d.weight" ). offset ), 1102mtl::Arg:: B ( W_ , T ( b + "ssm_dt.bias" ). offset ), mtl::Arg:: B ( W_ , T ( b + "ssm_a" ). offset ), 1103mtl::Arg:: B ( W_ , T ( b + "ssm_norm.weight" ). offset ), mtl::Arg:: B ( fuse_ ? XY_ . b : yg_ ), mtl::Arg:: V ( ar ), 1104mtl::Arg:: B ( hbBig_ [(size_t) gi ]), mtl::Arg:: B ( rinfo_ )}; 1105d . grid [ 0 ] = G_HV ; 1106d . grid [ 1 ] = (uint32_t) rows_n_ ; 1107d . tg [ 0 ] = 512 ; 1108push ( ds , d ); 1109if (! fuse_ ) xprep ( ds , yg_ , XY_ , G_ZV ); 1110gemv ( ds , T ( b + "ssm_out.weight" ), XY_ , bo_ , N , ntok ); 1111} else { 1112d . args = {mtl::Arg:: B ( gst_ [(size_t) gi ]), mtl::Arg:: B ( ghist_ [ hp ][(size_t) gi ]), mtl::Arg:: B ( qkvL_ , o_qkv ), 1113mtl::Arg:: B ( alL_ , o_ab ), mtl::Arg:: B ( beL_ , o_ab ), mtl::Arg:: B ( zL_ , o_z ), 1114mtl::Arg:: B ( W_ , T ( b + "ssm_conv1d.weight" ). offset ), 1115mtl::Arg:: B ( W_ , T ( b + "ssm_dt.bias" ). offset ), mtl::Arg:: B ( W_ , T ( b + "ssm_a" ). offset ), 1116mtl::Arg:: B ( W_ , T ( b + "ssm_norm.weight" ). offset ), mtl::Arg:: B ( fuse_ ? XY_ . b : yg_ ), mtl::Arg:: V ( a ), 1117mtl::Arg:: B ( ghist_ [ 1 - hp ][(size_t) gi ])}; 1118d . grid [ 0 ] = G_HV ; 1119d . tg [ 0 ] = 512 ; 1120push ( ds , d ); 1121(void) self_commit ; // the history ping-pong turns after the window (run) or at commit 1122if (! fuse_ ) xprep ( ds , yg_ , XY_ , G_ZV ); 1123gemv ( ds , T ( b + "ssm_out.weight" ), XY_ , bo_ , N , ntok ); 1124} 1125} else { 1126const int qi = l / G_QI ; 1127gemv ( ds , T ( b + "attn_q.weight" ), XA_ , qfull_ , G_QFULL , ntok ); 1128nb_ = true; 1129gemv ( ds , T ( b + "attn_k.weight" ), XA_ , kcur_ , G_KV , ntok ); 1130nb_ = true; 1131gemv ( ds , T ( b + "attn_v.weight" ), XA_ , vcur_ , G_KV , ntok ); 1132nb_ = true; 1133gemv ( ds , T ( b + "indexer.q_proj.weight" ), XA_ , iqr_ , G_IQR , ntok ); 1134nb_ = true; 1135gemv ( ds , T ( b + "indexer.k_proj.weight" ), XA_ , ikr_ , G_ID , ntok ); 1136QsaArgs a {(uint32_t) pos0 , 0 , (uint32_t) max_cells_ , (uint32_t) ntok , eps_ }; 1137mtl::Dispatch d ; 1138const bool rw = rows_ ; // (batch slots: pos0 is the highest row's cell, the rows have their own in rinfo_) 1139const mtl::Constants rc = mtl:: Constants (). b ( 30 , true); 1140const mtl::Buffer & KQ = rw ? kqBig_ [(size_t) qi ] : kq_ [(size_t) qi ]; 1141const mtl::Buffer & VQ = rw ? vqBig_ [(size_t) qi ] : vq_ [(size_t) qi ]; 1142const mtl::Buffer & KS = rw ? kscBig_ [(size_t) qi ] : ksc_ [(size_t) qi ]; 1143const mtl::Buffer & VS = rw ? vscBig_ [(size_t) qi ] : vsc_ [(size_t) qi ]; 1144const mtl::Buffer & TL = rw ? tailBig_ [(size_t) qi ] : tail_ [(size_t) qi ]; 1145const mtl::Buffer & DD = rw ? deadBig_ [(size_t) qi ] : dead_ [(size_t) qi ]; 1146const mtl::Buffer & PL = rw ? pooledBig_ [(size_t) qi ] : pooled_ [(size_t) qi ]; 1147d . p = rw ? P ( lqsa_ , "qsa_prep" , rc , "qsa_prep#rows" ) : P ( lqsa_ , "qsa_prep" , qsa_c (), qsa_k ()); 1148d . args = {mtl::Arg:: B ( qfull_ ), mtl::Arg:: B ( kcur_ ), mtl::Arg:: B ( vcur_ ), mtl::Arg:: B ( iqr_ ), mtl::Arg:: B ( ikr_ ), 1149mtl::Arg:: B ( W_ , T ( b + "attn_q_norm.weight" ). offset ), mtl::Arg:: B ( W_ , T ( b + "attn_k_norm.weight" ). offset ), 1150mtl::Arg:: B ( W_ , T ( b + "indexer.q_norm.weight" ). offset ), mtl::Arg:: B ( W_ , T ( b + "indexer.k_norm.weight" ). offset ), 1151mtl::Arg:: B ( cs_ ), mtl::Arg:: B ( qcur_ ), mtl::Arg:: B ( qidx_ ), mtl::Arg:: B ( KQ ), 1152mtl::Arg:: B ( VQ ), mtl::Arg:: B ( KS ), mtl::Arg:: B ( VS ), 1153mtl::Arg:: B ( TL ), mtl::Arg:: B ( DD ), mtl::Arg:: B ( PL ), 1154mtl::Arg:: V ( a ), mtl::Arg:: B ( mrope_ )}; 1155if ( rw ) d . args . push_back (mtl::Arg:: B ( rinfo_ )); 1156d . grid [ 0 ] = G_QPREP ; 1157d . grid [ 1 ] = ntok ; 1158d . tg [ 0 ] = 256 ; 1159push ( ds , d ); 1160if ( rec_ ) rec_ -> push_back ({(int) ds . size () - 1 , 0 }); 1161mtl::Dispatch s ; 1162s . p = rw ? P ( lqsa_ , "qsa_score" , rc , "qsa_score#rows" ) : P ( lqsa_ , "qsa_score" , {}, "qsa_score" ); 1163s . args = {mtl::Arg:: B ( qidx_ ), mtl::Arg:: B ( PL ), mtl::Arg:: B ( DD ), mtl::Arg:: B ( scores_ ), 1164mtl::Arg:: V ( a )}; 1165if ( rw ) s . args . push_back (mtl::Arg:: B ( rinfo_ )); 1166s . grid [ 0 ] = (uint32_t) ((( pos0 + ntok ) / 4 + 1 + 7 ) / 8 ); 1167s . grid [ 1 ] = ntok ; 1168s . tg [ 0 ] = 256 ; 1169const bool sel = !( fuse_ && pos0 + ntok <= G_BUD ); 1170if ( sel ) { 1171push ( ds , s ); 1172if ( rec_ ) rec_ -> push_back ({(int) ds . size () - 1 , 2 }); 1173} 1174mtl::Dispatch k ; 1175k . p = rw ? P ( lqsa_ , "qsa_topk2" , rc , "qsa_topk#rows" ) : P ( lqsa_ , "qsa_topk2" , {}, "qsa_topk" ); 1176k . args = {mtl::Arg:: B ( scores_ ), mtl::Arg:: B ( qids_ ), mtl::Arg:: V ( a )}; 1177if ( rw ) k . args . push_back (mtl::Arg:: B ( rinfo_ )); 1178k . grid [ 0 ] = ntok ; 1179k . tg [ 0 ] = 1024 ; 1180if ( sel ) { 1181push ( ds , k ); 1182if ( rec_ ) rec_ -> push_back ({(int) ds . size () - 1 , 0 }); 1183} 1184mtl::Dispatch at ; 1185at . p = rw ? P ( lqsa_ , "qsa_attn" , rc , "qsa_attn#rows" ) : P ( lqsa_ , "qsa_attn" , {}, "qsa_attn" ); 1186at . args = {mtl::Arg:: B ( qcur_ ), mtl::Arg:: B ( KQ ), mtl::Arg:: B ( VQ ), mtl::Arg:: B ( KS ), 1187mtl::Arg:: B ( VS ), mtl::Arg:: B ( qids_ ), mtl::Arg:: B ( part_ ), mtl::Arg:: V ( a )}; 1188if ( rw ) at . args . push_back (mtl::Arg:: B ( rinfo_ )); 1189at . grid [ 0 ] = G_QCHUNKS ; 1190at . grid [ 1 ] = G_QKV ; 1191at . grid [ 2 ] = ntok ; 1192at . tg [ 0 ] = 256 ; 1193push ( ds , at ); 1194if ( rec_ ) rec_ -> push_back ({(int) ds . size () - 1 , 0 }); 1195mtl::Dispatch m ; 1196m . p = rw ? P ( lqsa_ , "qsa_merge" , rc , "qsa_merge#rows" ) : P ( lqsa_ , "qsa_merge" , x16c (), x16k ( "qsa_merge" )); 1197QsaArgs am = a ; 1198am . n_tok = MAXT ; // the plane stride 1199m . args = {mtl::Arg:: B ( part_ ), mtl::Arg:: B ( qfull_ ), mtl::Arg:: B ( XQ_ . b ), mtl::Arg:: V ( am )}; 1200if ( rw ) m . args . push_back (mtl::Arg:: B ( rinfo_ )); 1201m . grid [ 0 ] = G_QH ; 1202m . grid [ 1 ] = ntok ; 1203m . tg [ 0 ] = 256 ; 1204push ( ds , m ); 1205if ( rec_ ) rec_ -> push_back ({(int) ds . size () - 1 , 1 }); 1206gemv ( ds , T ( b + "attn_output.weight" ), XQ_ , bo_ , N , ntok ); 1207} 1208// ---- the MoE 1209gr_read ( ds , b + "hc_ffn" , true, XF_ , false, ntok ); 1210const gguf::Tensor & trt = T ( b + "ffn_gate_inp.weight" ); 1211gemv ( ds , trt , XF_ , logits_ , 512 , ntok ); 1212nb_ = true; 1213if ( stream_ && st_pred_ && l + 1 < G_NL ) { // the next layer's routing guessed from this layer's FFN input 1214nb_ = true; // beside the router GEMV 1215gemv ( ds , T ( "blk." + std:: to_string ( l + 1 ) + ".ffn_gate_inp.weight" ), XF_ , predL_ , 512 , ntok , 1216(size_t) l * MAXT * 512 * 4 ); 1217if ( predL2_ . ptr && l + 2 < G_NL ) { 1218nb_ = true; 1219gemv ( ds , T ( "blk." + std:: to_string ( l + 2 ) + ".ffn_gate_inp.weight" ), XF_ , predL2_ , 512 , ntok , 1220(size_t) l * MAXT * 512 * 4 ); 1221} 1222nb_ = true; 1223} 1224gemv ( ds , T ( b + "ffn_gate_shexp.weight" ), XF_ , gsh_ , NFF , ntok ); 1225nb_ = true; 1226gemv ( ds , T ( b + "ffn_up_shexp.weight" ), XF_ , ush_ , NFF , ntok ); 1227nb_ = true; 1228gemv ( ds , T ( b + "ffn_gate_inp_shexp.weight" ), XF_ , sg_ , 1 , ntok ); 1229{ 1230MoeArgs a {}; 1231const gguf::Tensor & tg_ = T ( b + "ffn_gate_exps.weight" ), & tu = T ( b + "ffn_up_exps.weight" ), 1232& td = T ( b + "ffn_down_exps.weight" ); 1233a . gate_off = tg_ . offset ; 1234a . up_off = tu . offset ; 1235a . down_off = td . offset ; 1236if ( stream_ ) { // offsets inside the expert's arena slot 1237a . gate_off = 0 ; 1238a . up_off = st_ -> up_in_slot ( l ); 1239a . down_off = st_ -> down_in_slot ( l ); 1240} 1241const size_t ebase = moe_rebase ( a . gate_off , a . up_off , a . down_off ); 1242a . gu_row = (uint32_t) ref:: row_bytes ( tg_ . type , N ); 1243a . d_row = (uint32_t) ref:: row_bytes ( td . type , NFF ); 1244a . gu_stride = (uint64_t) a . gu_row * NFF ; 1245a . d_stride = (uint64_t) a . d_row * N ; 1246a . n_embd = N ; 1247a . n_ff = NFF ; 1248a . n_tok = ntok ; 1249a . topk = TOPK ; 1250a . n_expert = nexp_ ; 1251const bool dq2 = td . type == ref:: Q2_0 ; 1252// the trellis gate/up: 16 lanes a row, 2 rows a lane (expert_parity --bench --sweep, M4, TQK6, 10 experts: 166.6 us a layer 1253// against 174.5 for 32,2,4 and 196.8 for 32,1,4; also the fastest at 2 and 3 tokens) 1254const bool tq_ = tg_ . type >= 144 ; 1255int gl = tq_ ? 16 : 32 , gr = tq_ ? 2 : 1 , gs = 4 , ds_ = 4 ; 1256// the down tile: Q2_0 8,1; else 4,2 - but on the M4 (no M5 layout) Q5_1 4,1 and Q8_0 8,1 (4,2 spills there: 1257// 24-36 GB/s, mac-kern 513fc615) 1258const bool m4 = ! m5_layout (); 1259int dl = dq2 || ( m4 && td . type == ref:: Q8_0 ) ? 8 : 4 , 1260dr = dq2 || ( m4 && ( td . type == ref:: Q8_0 || td . type == ref:: Q5_1 || td . type == ref:: Q5_0 )) ? 1 : 2 ; 1261{ // STRATA_METAL_MOE_GU=L,R,S / STRATA_METAL_MOE_DN=L,R,S (tile screens: lanes per row, rows per lane, simdgroups; an instantiated moe_gu_ / moe_down_ combination) 1262static const auto parse = []( const char * name , int * o ) { 1263const char * e = std:: getenv ( name ); 1264return e && std:: sscanf ( e , "%d,%d,%d" , & o [ 0 ], & o [ 1 ], & o [ 2 ]) == 3 ; 1265}; 1266static int gu_o [ 3 ], dn_o [ 3 ]; 1267static const bool gu_e = parse ( "STRATA_METAL_MOE_GU" , gu_o ), dn_e = parse ( "STRATA_METAL_MOE_DN" , dn_o ); 1268if ( gu_e && ! tq_ ) { gl = gu_o [ 0 ]; gr = gu_o [ 1 ]; gs = gu_o [ 2 ]; } 1269if ( dn_e && ! dq2 ) { dl = dn_o [ 0 ]; dr = dn_o [ 1 ]; ds_ = dn_o [ 2 ]; } 1270} 1271const bool m16 = f16_enc_ && ! stream_ && tg_ . type == ref:: Q2_0 && dq2 && ! had_gu ( l ) && ! had_dn ( l ); 1272a . gx_gu = NFF / ( gs * ( 32 / gl ) * gr ); 1273a . gx_dn = N / ( ds_ * ( 32 / dl ) * dr ); 1274mtl::Dispatch r ; 1275r . p = P ( lib_ , "moe_route" , {}, "moe_route" ); 1276r . args = {mtl::Arg:: B ( logits_ ), mtl::Arg:: B ( ids_ ), mtl::Arg:: B ( wts_ ), mtl::Arg:: B ( plan_ ), mtl::Arg:: V ( a )}; 1277r . tg [ 0 ] = 512 ; 1278push ( ds , r ); 1279{ 1280GlueArgs ga { NFF , MAXT , N , TOPK }; 1281mtl::Dispatch d ; 1282d . p = P ( lib_ , "swiglu_prep" , x16c (), x16k ( "swiglu_prep" )); 1283d . args = {mtl::Arg:: B ( gsh_ ), mtl::Arg:: B ( ush_ ), mtl::Arg:: B ( XH_ . b ), mtl::Arg:: V ( ga )}; 1284d . grid [ 0 ] = NFF / 16 ; 1285d . grid [ 1 ] = ntok ; 1286d . tg [ 0 ] = 16 ; 1287nb_ = true; 1288push ( ds , d ); 1289} 1290const std::string gun = std:: string ( m16 ? "moe_gu16_" : "moe_gu_" ) + std:: to_string ( tg_ . type ) + "_" + std:: to_string ( gl ) + 1291"_" + std:: to_string ( gr ) + "_" + std:: to_string ( gs ); 1292const std::string dnn = std:: string ( m16 ? "moe_down16_" : "moe_down_" ) + std:: to_string ( dq2 ? 142 : td . type ) + "_" + 1293std:: to_string ( dl ) + "_" + std:: to_string ( dr ) + "_" + std:: to_string ( ds_ ); 1294mtl::Dispatch g ; 1295const mtl::Buffer & EW = stream_ ? st_ -> chunk ( 0 ) : W_ ; 1296// function constant 23 (QUANT_CTAB): the i-quant grids from constant memory, no threadgroup copy (same values) 1297const bool ct = metal_ctab (); 1298mtl::Constants ac = stream_ ? mtl:: Constants (). b ( 20 , true) : mtl:: Constants (); 1299ac . b ( 23 , ct ); 1300const std::string ak = std:: string ( stream_ ? "#arena" : "" ) + ( ct ? "#ct" : "" ); 1301g . p = m16 ? P ( lib_ , gun , {}, gun ) : P ( lib_ , gun , ac , gun + ak ); 1302const bool hg = had_gu ( l ), hd = had_dn ( l ); 1303if ( hg ) had_rows ( ds , lib_ , "d:" , XF_ . b , 0 , XR_ , 0 , ntok , N , hsx_ . handle ? & hsx_ : nullptr , false); // before the host's turn 1304g . args = {mtl::Arg:: B ( EW , ebase ), hg ? mtl::Arg:: B ( XR_ ) : mtl::Arg:: B ( XF_ . b , XF_ . plane_bytes () * xkind ( tg_ . type )), mtl::Arg:: B ( h_ ), 1305mtl::Arg:: B ( plan_ ), mtl::Arg:: V ( a ), mtl::Arg:: B ( XF_ . b , XF_ . plane_bytes () * 4 )}; 1306if ( m16 ) { // x from the half plane x * 4^-(i % 4), h also as half 1307g . args [ 1 ] = mtl::Arg:: B ( XF_ . b , XF_ . x16_bytes () + (size_t) 2 * MAXT * N ); 1308g . args . push_back (mtl::Arg:: B ( h16_ )); 1309} 1310if ( stream_ ) 1311for (int c = -1 ; c < 3 ; ++ c ) 1312g . args . push_back ( c < 0 ? mtl::Arg:: B ( st_ -> smap (), (size_t) l * 512 * 4 ) : mtl::Arg:: B ( st_ -> chunk ( c + 1 ))); 1313g . tg [ 0 ] = 32 * gs ; 1314g . indirect = & plan_ ; 1315g . ind_off = P_IGU * 4 ; 1316if ( cuts_ ) cuts_ -> push_back ((int) ds . size ()); // the host's turn: this layer's experts put in place 1317push ( ds , g ); 1318nb_ = true; 1319gemv ( ds , T ( b + "ffn_down_shexp.weight" ), XH_ , ysh_ , N , ntok ); 1320if ( hd ) had_rows ( ds , lib_ , "d:" , h_ , 0 , h_ , 0 , ntok * TOPK , NFF , hsh_ . handle ? & hsh_ : nullptr , false); // H h, in place 1321mtl::Dispatch dd ; 1322dd . p = m16 ? P ( lib_ , dnn , {}, dnn ) : P ( lib_ , dnn , ac , dnn + ak ); 1323dd . args = {mtl::Arg:: B ( EW , ebase ), mtl::Arg:: B ( h_ ), mtl::Arg:: B ( ye_ ), mtl::Arg:: B ( plan_ ), mtl::Arg:: V ( a ), mtl::Arg:: B ( h_ )}; 1324if ( m16 ) dd . args = {mtl::Arg:: B ( EW , ebase ), mtl::Arg:: B ( h16_ ), mtl::Arg:: B ( ye_ ), mtl::Arg:: B ( plan_ ), mtl::Arg:: V ( a )}; 1325if ( stream_ ) 1326for (int c = -1 ; c < 3 ; ++ c ) 1327dd . args . push_back ( c < 0 ? mtl::Arg:: B ( st_ -> smap (), (size_t) l * 512 * 4 ) : mtl::Arg:: B ( st_ -> chunk ( c + 1 ))); 1328dd . tg [ 0 ] = 32 * ds_ ; 1329dd . indirect = & plan_ ; 1330dd . ind_off = P_IDN * 4 ; 1331push ( ds , dd ); 1332} 1333{ 1334GlueArgs a { N , (uint32_t) ntok , N , TOPK }; 1335mtl::Dispatch d ; 1336d . p = P ( lib_ , k_comb (), {}, k_comb ()); 1337d . 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 )}; 1338d . grid [ 0 ] = ( ntok * N + 255 ) / 256 ; 1339d . tg [ 0 ] = 256 ; 1340push ( ds , d ); 1341} 1342if ( taps_on_ && tap_slot_ [ l ] >= 0 ) tap_dispatch ( ds , l , R_ , bo_ , inj_ [ cur_inj_ ], tap_dec_ , ntok ); // DFlash2: the layers completed output (dflash2.inc) 1343} 1344 1345namespace { 1346float bf16f (uint16_t h ) { uint32_t i = (uint32_t) h << 16 ; float f ; std:: memcpy ( & f , & i , 4 ); return f ; } 1347// ple.cu's gnorm_kernel: per stream, the squares rounded in f32, summed in double 1348void gnorm ( const float * x , const float * w , float * y , int n_embd , int hc , float eps ) { 1349for (int c = 0 ; c < hc ; ++ c ) { 1350const float * xc = x + (size_t) c * n_embd ; 1351double acc = 0.0 ; 1352for (int d = 0 ; d < n_embd ; ++ d ) { const float sq = xc [ d ] * xc [ d ]; acc += (double) sq ; } 1353const float mean = (float) ( acc / (double) n_embd ); 1354const float scale = 1.0f / std:: sqrt ( mean + eps ); 1355for (int d = 0 ; d < n_embd ; ++ d ) y [(size_t) c * n_embd + d ] = xc [ d ] * scale * w [(size_t) c * n_embd + d ]; 1356} 1357} 1358} // namespace 1359 1360// The PLE block (ple.hpp) for the window's T rows on the CPU, after layer 0 (its pending write applied to R): R += 1361// gated + silu(conv); the normalized rows go to last_norm_ (the history advances at commit). 1362void Window:: ple_cpu (int Tn ) { 1363using namespace strata:: kernels ; 1364const int hc_dim = NG_HC_DIM ; 1365const float * nkey = ( const float * ) (( const uint8_t * ) W_ . ptr + T ( "blk.1.ple_norm_key.weight" ). offset ); 1366const float * nqry = ( const float * ) (( const uint8_t * ) W_ . ptr + T ( "blk.1.ple_norm_query.weight" ). offset ); 1367const float * nconv = ( const float * ) (( const uint8_t * ) W_ . ptr + T ( "blk.1.ple_norm_conv.weight" ). offset ); 1368const uint16_t * kw = kw_host (); 1369std::vector < float > key (hc_dim), query (hc_dim), gated (hc_dim), norm (hc_dim), hist = ple_hist_ ; 1370for (int t = 0 ; t < Tn ; ++ t ) { 1371float * hidden = R_ . as < float > () + (size_t) t * HC * N ; 1372gnorm ( pkey_ . as < float > () + (size_t) t * hc_dim , nkey , key . data (), N , HC , NG_RMS_EPS ); 1373gnorm ( hidden , nqry , query . data (), N , HC , NG_RMS_EPS ); 1374const float * value = pval_ . as < float > () + (size_t) t * N ; 1375float gate [ HC ]; 1376const float inv_sqrt_n = 1.0f / std:: sqrt ((float) N ); 1377for (int c = 0 ; c < HC ; ++ c ) { 1378double acc = 0.0 ; 1379for (int d = 0 ; d < N ; ++ d ) acc += (double) ( key [(size_t) c * N + d ] * query [(size_t) c * N + d ]); 1380const float s = (float) acc * inv_sqrt_n ; 1381const float mag = std:: sqrt (std:: max (std:: fabs ( s ), 1e-6f )); 1382const float sgn = s > 0.0f ? 1.0f : ( s < 0.0f ? -1.0f : 0.0f ); 1383gate [ c ] = 1.0f / ( 1.0f + std:: exp ( - ( sgn * mag ))); 1384} 1385for (int i = 0 ; i < hc_dim ; ++ i ) gated [(size_t) i ] = value [ i % N ] * gate [ i / N ]; 1386gnorm ( gated . data (), nconv , norm . data (), N , HC , NG_RMS_EPS ); 1387for (int c = 0 ; c < hc_dim ; ++ c ) { 1388float acc = 0.0f ; 1389for (int k = 0 ; k < PLE_CONV_KERNEL ; ++ k ) { 1390const int row = NG_HIST - ( PLE_CONV_KERNEL - 1 - k ) * NGRAM_SIZE ; 1391const float v = row == NG_HIST ? norm [(size_t) c ] : hist [(size_t) row + (size_t) NG_HIST * c ]; 1392acc += ref:: f16_to_f32 ( kw [ k + PLE_CONV_KERNEL * c ]) * v ; 1393} 1394const float conv = acc / ( 1.0f + std:: exp ( - acc )); 1395hidden [ c ] = hidden [ c ] + gated [(size_t) c ] + conv ; 1396} 1397std:: memcpy ( last_norm_ . data () + (size_t) t * hc_dim , norm . data (), (size_t) hc_dim * 4 ); 1398// the next row of this window sees this one in its history 1399for (int c = 0 ; c < hc_dim ; ++ c ) { 1400float * col = hist . data () + (size_t) c * NG_HIST ; 1401for (int r = 0 ; r + 1 < NG_HIST ; ++ r ) col [ r ] = col [ r + 1 ]; 1402col [ NG_HIST - 1 ] = norm [(size_t) c ]; 1403} 1404} 1405} 1406 1407bool Window:: run (int Tn , const int32_t * tokens , int64_t pos0 , bool head , int32_t * out , std::string & err ) { 1408mtp_src_ = nullptr ; 1409if ( Tn < 1 || Tn > MAXT || ( head && Tn > max_t_ )) { err = "metal window: window size out of range" ; return false; } 1410if ( pos0 + Tn + 1 >= max_cells_ ) { err = "metal window: the window runs past the context" ; return false; } 1411const double t0 = now_ms (); 1412// ---- the embeddings (CPU dequant of the token rows straight into the shared buffer), broadcast to the streams 1413const gguf::Tensor & te = T ( "token_embd.weight" ); 1414const size_t rb = ref:: row_bytes ( te . type , N ); 1415for (int t = 0 ; t < Tn ; ++ t ) { 1416float * r = R_ . as < float > () + (size_t) t * HC * N ; 1417if ( const float * img = img_row ( pos0 + t )) std:: memcpy ( r , img , (size_t) N * 4 ); 1418else ref:: dequant ( te . type , ( const uint8_t * ) W_ . ptr + te . offset + (size_t) tokens [ t ] * rb , r , N ); 1419for (int c = 1 ; c < HC ; ++ c ) std:: memcpy ( r + (size_t) c * N , r , (size_t) N * 4 ); 1420} 1421// ---- the PLE rows (the table read is the shared host code's), projected on the GPU 1422if ( ple_on_ ) { 1423strata::core::SessionState & ss = * ss_ ; 1424uint32_t rows [ MAXT * strata::kernels:: PLE_N_HEADS ]; 1425int32_t prev [ 2 ] = { ss . ple_prev [ 0 ], ss . ple_prev [ 1 ]}; 1426for (int t = 0 ; t < Tn ; ++ t ) { 1427if ( rows_ ) { prev [ 0 ] = rows_ss_ [ t ] -> ple_prev [ 0 ]; prev [ 1 ] = rows_ss_ [ t ] -> ple_prev [ 1 ]; } // (batch slots: each row its own sequence) 1428strata::kernels:: ngram_rows ( & tokens [ t ], prev , 1 , main_ss_ -> ple . consts , rows + t * strata::kernels:: PLE_N_HEADS ); 1429if (! rows_ ) { prev [ 0 ] = prev [ 1 ]; prev [ 1 ] = tokens [ t ]; } 1430} 1431if (! main_ss_ -> ple . table -> gather_batch ( rows , (size_t) Tn , emb_ . as < float > (), err )) return false; 1432} 1433tp_pre_ = now_ms (); 1434const bool sel = !( fuse_ && pos0 + Tn <= G_BUD ); 1435if ( sel ) qdirty_ = true; 1436else if ( qdirty_ ) { 1437for (int t = 0 ; t < MAXT ; ++ t ) 1438for (int c = 0 ; c < G_BUD ; ++ c ) qids_ . as < int > ()[ t * G_BUD + c ] = c ; 1439qdirty_ = false; 1440} 1441const int key = rows_ ? 1000000 + Tn * 2 + ( sel ? 1 : 0 ) + (int) ( pend_fold_ * 100 ) 1442: ((((( Tn * 2 + ( head ? 1 : 0 )) * 2 + hp_ ) * ( MAXT + 1 )) + pend_fold_ ) * 2 + ( sel ? 1 : 0 )) * 2 + 1443( mrope_on () ? 1 : 0 ); 1444mrope_sync ( pos0 , Tn ); 1445const int fold_n = pend_fold_ ; 1446pend_fold_ = 0 ; 1447win_head_ = head ; 1448auto hit = wcache_ . find ( key ); 1449if ( hit != wcache_ . end ()) { 1450// the same window shape: only the positions change (QSA's cells, the score grid) 1451Cached & c = hit -> second ; 1452for ( const auto & [ i , kind ] : c . qsa ) { 1453mtl::Dispatch & d = c . ds [(size_t) i ]; 1454QsaArgs a {(uint32_t) pos0 , 0 , (uint32_t) max_cells_ , (uint32_t) ( kind == 1 ? MAXT : Tn ), eps_ }; 1455// the QsaArgs: the dispatch's last inline argument (qsa_prep has the M-RoPE table bound after it) 1456mtl::Arg * qa = nullptr ; 1457for (auto & g : d . args ) 1458if (! g . bytes . empty ()) qa = & g ; 1459std:: memcpy ( qa -> bytes . data (), & a , sizeof a ); 1460if ( kind == 2 ) d . grid [ 0 ] = (uint32_t) ((( pos0 + Tn ) / 4 + 1 + 7 ) / 8 ); 1461} 1462seg_T_ = Tn ; 1463const double r0 = now_ms (); 1464last_gpu_ms_ = 1000.0 * run_ds ( c ); 1465{ 1466static const int kt = std:: getenv ( "STRATA_METAL_KPROF" ) ? std:: atoi (std:: getenv ( "STRATA_METAL_KPROF" )) : 0 ; 1467static int seen = 0 ; 1468if ( kt == Tn && head && ++ seen == 20 && ! stream_ ) kprof ( c . ds , Tn ); 1469static const int st = std:: getenv ( "STRATA_METAL_STEPPROF" ) ? std:: atoi (std:: getenv ( "STRATA_METAL_STEPPROF" )) : 0 ; 1470static int seen2 = 0 ; 1471static const int st_at = std:: getenv ( "STRATA_METAL_STEPPROF_AT" ) ? std:: atoi (std:: getenv ( "STRATA_METAL_STEPPROF_AT" )) : 20 ; 1472if ( st == Tn && head && ++ seen2 == st_at && ! stream_ ) stepprof ( c . ds , Tn ); 1473} 1474tp_rg_ = now_ms () - r0 ; 1475last_n_disp_ = (int) c . ds . size (); 1476return rows_ ? finish_rows ( Tn , tokens , out , t0 ) : finish ( Tn , tokens , pos0 , head , out , t0 ); 1477} 1478if ( stream_ && ! st_ -> ready () && ! stream_arena ( err )) return false; 1479Cached & cw = wcache_ [ key ]; 1480rec_ = & cw . qsa ; 1481f16_enc_ = metal_f16 () && head && ! stream_ && ! rows_ ; // decode windows of one resident sequence: not the prompt's, 1482// not streaming, not batch slots 1483cuts_ = stream_ ? & cw . cuts : nullptr ; 1484std::vector < mtl::Dispatch >& ds = cw . ds ; 1485nb_ = false; 1486if ( fold_n > 0 ) fold ( ds , fold_n , 1 - hp_ ); // the last window's commit (hp_ already turned) 1487if ( ple_on_ ) { 1488xprep ( ds , emb_ , XE_ , N ); 1489gemv ( ds , T ( "blk.1.ple_key.weight" ), XE_ , pkey_ , G_HCD , Tn ); 1490nb_ = true; 1491gemv ( ds , T ( "blk.1.ple_value.weight" ), XE_ , pval_ , N , Tn ); 1492} 1493cur_inj_ = 0 ; 1494layer ( ds , 0 , Tn , pos0 ); 1495if ( ple_on_ ) { 1496// layer 0's FFN write applied to R (gr_norm with apply writes R back; its xn is not used) 1497const gguf::Tensor & tn = T ( "blk.1.hc_attn_norm.weight" ); 1498GrArgs a { N , HC , LR , (uint32_t) Tn , 1u , eps_ }; 1499mtl::Dispatch d1 ; 1500d1 . p = P ( lib_ , k_norm (), {}, k_norm ()); 1501d1 . 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_ ), 1502mtl::Arg:: V ( a )}; 1503d1 . grid [ 0 ] = HC ; 1504d1 . grid [ 1 ] = Tn ; 1505d1 . tg [ 0 ] = 256 ; 1506push ( ds , d1 ); 1507// the PLE block on the GPU (msl/ple.metal): norms, gate, conv, the residual update 1508struct PleArgs { uint32_t n_embd , hc ; float eps ; } pa { N , HC , strata::kernels:: NG_RMS_EPS }; 1509auto off = [ & ]( const char * n ) { return T ( n ). offset ; }; 1510mtl::Dispatch g1 , g2 , g3 , g4 ; 1511g1 . p = P ( lple_ , "ple_gnorm" , {}, "ple_gnorm" ); 1512g1 . args = {mtl::Arg:: B ( pkey_ ), mtl::Arg:: B ( W_ , off ( "blk.1.ple_norm_key.weight" )), mtl::Arg:: B ( keyn_ ), mtl::Arg:: V ( pa )}; 1513g1 . grid [ 0 ] = HC ; g1 . grid [ 1 ] = Tn ; g1 . tg [ 0 ] = 256 ; 1514push ( ds , g1 ); 1515g2 . p = g1 . p ; 1516g2 . args = {mtl::Arg:: B ( R_ ), mtl::Arg:: B ( W_ , off ( "blk.1.ple_norm_query.weight" )), mtl::Arg:: B ( qn_ ), mtl::Arg:: V ( pa )}; 1517g2 . grid [ 0 ] = HC ; g2 . grid [ 1 ] = Tn ; g2 . tg [ 0 ] = 256 ; 1518nb_ = true; // beside the key norm 1519push ( ds , g2 ); 1520g3 . p = P ( lple_ , "ple_gate_norm" , {}, "ple_gate_norm" ); 1521g3 . args = {mtl::Arg:: B ( keyn_ ), mtl::Arg:: B ( qn_ ), mtl::Arg:: B ( pval_ ), mtl::Arg:: B ( W_ , off ( "blk.1.ple_norm_conv.weight" )), 1522mtl::Arg:: B ( gated_ ), mtl::Arg:: B ( normW_ ), mtl::Arg:: V ( pa )}; 1523g3 . grid [ 0 ] = HC ; g3 . grid [ 1 ] = Tn ; g3 . tg [ 0 ] = 256 ; 1524push ( ds , g3 ); 1525g4 . p = rows_ ? P ( lple_ , "ple_conv_add" , mtl:: Constants (). b ( 32 , true), "ple_conv_add#rows" ) : P ( lple_ , "ple_conv_add" , {}, "ple_conv_add" ); 1526g4 . args = {mtl::Arg:: B ( rows_ ? pleBig_ : pleHist_ ), mtl::Arg:: B ( normW_ ), kw_arg (), 1527mtl::Arg:: B ( gated_ ), mtl::Arg:: B ( R_ ), mtl::Arg:: V ( pa )}; 1528if ( rows_ ) g4 . args . push_back (mtl::Arg:: B ( rinfo_ )); 1529g4 . grid [ 0 ] = HC * N / 256 ; g4 . grid [ 1 ] = Tn ; g4 . tg [ 0 ] = 256 ; 1530push ( ds , g4 ); 1531} 1532for (int l = 1 ; l < G_NL ; ++ l ) layer ( ds , l , Tn , pos0 ); 1533// ---- the final mixer and the head 1534gr_read ( ds , "output_hc" , true, XA_ , true, Tn ); 1535if ( head ) gemv ( ds , T ( "output.weight" ), XA_ , lm_ , (size_t) n_vocab_ , Tn ); 1536if ( head ) { 1537ArgArgs a {(uint32_t) n_vocab_ , 120 }; 1538mtl::Dispatch d1 , d2 ; 1539d1 . p = P ( lsmp_ , "argmax_part" , {}, "argmax_part" ); 1540d1 . args = {mtl::Arg:: B ( lm_ ), mtl::Arg:: B ( apv_ ), mtl::Arg:: B ( api_ ), mtl::Arg:: V ( a )}; 1541d1 . grid [ 0 ] = 120 ; 1542d1 . grid [ 1 ] = Tn ; 1543d1 . tg [ 0 ] = 256 ; 1544push ( ds , d1 ); 1545d2 . p = P ( lsmp_ , "argmax_final" , {}, "argmax_final" ); 1546d2 . args = {mtl::Arg:: B ( apv_ ), mtl::Arg:: B ( api_ ), mtl::Arg:: B ( tokout_ ), mtl::Arg:: V ( a )}; 1547d2 . grid [ 0 ] = Tn ; 1548d2 . tg [ 0 ] = 256 ; 1549push ( ds , d2 ); 1550} 1551rec_ = nullptr ; 1552f16_enc_ = false; 1553cuts_ = nullptr ; 1554seg_T_ = Tn ; 1555const double r0 = now_ms (); 1556last_gpu_ms_ = 1000.0 * run_ds ( cw ); 1557tp_rg_ = now_ms () - r0 ; 1558last_n_disp_ = (int) ds . size (); 1559return rows_ ? finish_rows ( Tn , tokens , out , t0 ) : finish ( Tn , tokens , pos0 , head , out , t0 ); 1560} 1561 1562bool Window:: run_rows ( const int * rows , int S , const int32_t * tokens , const int64_t * pos , int32_t * out , std::string & err ) { 1563if ( S < 1 || S > MAXT || S > max_t_ ) { err = "metal window: batch window size out of range" ; return false; } 1564if ( active_ != 0 ) activate ( 0 ); 1565uint32_t * ri = rinfo_ . as < uint32_t > () + 8 ; 1566int64_t maxpos = 0 ; 1567for (int t = 0 ; t < S ; ++ t ) { 1568if ( rows [ t ] < 0 || rows [ t ] >= n_slots ()) { err = "metal window: a batch row names a slot that does not exist" ; return false; } 1569for (int u = 0 ; u < t ; ++ u ) 1570if ( rows [ u ] == rows [ t ]) { err = "metal window: two rows of one batch window are the same slot" ; return false; } 1571const int set = rows [ t ] + 1 ; 1572rows_ss_ [ t ] = sets_ [(size_t) set ] -> ss ; 1573rows_set_ [ t ] = set ; 1574ri [ 4 * t ] = (uint32_t) set ; 1575ri [ 4 * t + 1 ] = (uint32_t) pos [ t ]; 1576ri [ 4 * t + 2 ] = (uint32_t) sets_ [(size_t) set ] -> hp ; 1577ri [ 4 * t + 3 ] = 0 ; 1578maxpos = std:: max < int64_t > ( maxpos , pos [ t ]); 1579} 1580rows_ = true; 1581rows_n_ = S ; 1582const bool ok = run ( S , tokens , maxpos , true, out , err ); 1583rows_ = false; 1584return ok ; 1585} 1586 1587// the end of a window of batch slots: the picks, and each slot's commit (a one-token step committed its row: the other history 1588// parity is the committed one; the PLE history takes the row's normalized values; the session's token pair advances) 1589bool Window:: finish_rows (int Tn , const int32_t * tokens , int32_t * out , double t0 ) { 1590++ win_n_ [ Tn ]; 1591win_ms_ [ Tn ] += now_ms () - t0 ; 1592win_gpu_ [ Tn ] += last_gpu_ms_ ; 1593for (int t = 0 ; t < Tn ; ++ t ) out [ t ] = tokout_ . as < int32_t > ()[ t ]; 1594for (int t = 0 ; t < Tn ; ++ t ) { 1595SeqSet & s = * sets_ [(size_t) rows_set_ [ t ]]; 1596s . hp = 1 - s . hp ; 1597if ( ple_on_ ) { 1598const float * norm = normW_ . as < float > () + (size_t) t * strata::kernels:: NG_HC_DIM ; 1599for (int c = 0 ; c < strata::kernels:: NG_HC_DIM ; ++ c ) { 1600float * col = s . pleHist . as < float > () + (size_t) c * strata::kernels:: NG_HIST ; 1601for (int r = 0 ; r + 1 < strata::kernels:: NG_HIST ; ++ r ) col [ r ] = col [ r + 1 ]; 1602col [strata::kernels:: NG_HIST - 1 ] = norm [ c ]; 1603} 1604} 1605s . ss -> ple_prev [ 0 ] = s . ss -> ple_prev [ 1 ]; 1606s . ss -> ple_prev [ 1 ] = tokens [ t ]; 1607} 1608return true; 1609} 1610 1611double Window:: run_ds (Cached & c ) { 1612if (! stream_ ) return cx_ -> run_graph ( c . ds ); 1613return cx_ -> run_graph_seg ( c . ds , c . cuts , [](void * u , int s ) { ((Window * ) u ) -> at_cut ( s ); }, this ); 1614} 1615 1616namespace { 1617Window * g_stream_window = nullptr ; 1618// What the process holds now, all of it (task_info TASK_VM_INFO): phys_footprint is its anonymous + wired + compressed memory 1619// (not the clean file pages it only maps), resident_size is the RSS (those pages too). Bytes; 0 when the call fails. 1620struct ProcMem { 1621double footprint = 0 , rss = 0 ; 1622}; 1623ProcMem proc_mem () { 1624task_vm_info_data_t ti ; 1625mach_msg_type_number_t cnt = TASK_VM_INFO_COUNT ; 1626ProcMem r ; 1627if ( task_info ( mach_task_self (), TASK_VM_INFO , ( task_info_t ) & ti , & cnt ) == KERN_SUCCESS ) { 1628r . footprint = (double) ti . phys_footprint ; 1629r . rss = (double) ti . resident_size ; 1630} 1631return r ; 1632} 1633void stream_atexit () { 1634if ( g_stream_window ) g_stream_window -> stream_report ( stderr ); 1635} 1636} // namespace 1637 1638// The arena, once the rest is allocated (the MTP layer loads after init): what the GPU working set and the RAM leave 1639// with STRATA_METAL_KEEP_FREE_GB kept for macOS (default: 7 GB, or 15% of the RAM when that is more - the M5 Max 1640// froze with an 89 GB arena and 7 GB left beside a 50 GB n-gram table read through the file cache; arena_budget.h); 1641// STRATA_METAL_ARENA_GB sets it. 1642bool Window:: stream_arena (std::string & err ) { 1643uint64_t phys = 0 ; 1644size_t len = sizeof phys ; 1645sysctlbyname ( "hw.memsize" , & phys , & len , nullptr , 0 ); 1646const double gb = 1e9 ; 1647if (!(std:: getenv ( "STRATA_METAL_KEEP_HOST_WEIGHTS" ) && std:: string (std:: getenv ( "STRATA_METAL_KEEP_HOST_WEIGHTS" )) == "1" )) { 1648const uint64_t g = strata::gpu:: purge_device_allocations ( 32u << 20 ); 1649std:: fprintf ( stderr , "strata metal stream: %.2f GB of the host code's device weight copies given back (unused by the " 1650"Metal window)\n" , g / 1e9 ); 1651} 1652const double used = (double) cx_ -> allocated (); 1653// what macOS gives now without paging anything out (arena_avail: free, purgeable, the clean file cache; not other 1654// programs' inactive memory, freed only by compressing or swapping it) 1655auto avail_now = [ & ]() -> double { 1656vm_statistics64_data_t vs ; 1657mach_msg_type_number_t cnt = HOST_VM_INFO64_COUNT ; 1658if ( host_statistics64 ( mach_host_self (), HOST_VM_INFO64 , ( host_info64_t ) & vs , & cnt ) == KERN_SUCCESS ) { 1659const double pg = (double) vm_page_size ; 1660return arena_avail ( vs . free_count * pg , vs . purgeable_count * pg , vs . inactive_count * pg , vs . speculative_count * pg , 1661vs . external_page_count * pg ); 1662} 1663return (double) phys - (double) cx_ -> allocated (); 1664}; 1665ArenaMem am ; // arena_budget.h: the rule, testable 1666am . phys = (double) phys ; 1667am . working_set = (double) cx_ -> recommended_working_set (); 1668am . allocated = used ; 1669const ProcMem pm0 = proc_mem (); // everything the process holds, not only the Metal buffers (the old 67% rule missed it) 1670am . proc_footprint = pm0 . footprint ; 1671{ // the file cache macOS keeps before it compresses anonymous memory (a 4-byte count of pages, read into a zeroed 8) 1672unsigned long long pages = 0 ; 1673size_t pl = sizeof pages ; 1674if ( sysctlbyname ( "vm.vm_page_filecache_min" , & pages , & pl , nullptr , 0 ) == 0 ) am . filecache_min = (double) pages * (double) vm_page_size ; 1675} 1676am . available = avail_now (); 1677if ( main_ss_ && main_ss_ -> ple . table && main_ss_ -> ple . table -> mode () == strata::kernels::PleIo:: Mmap ) 1678am . ple_mapped = (double) ss_ -> ple . table -> rows () * 192.0 ; // a row is at most 192 bytes (Q8_0 + its scale) 1679if ( const char * e = std:: getenv ( "STRATA_METAL_KEEP_FREE_GB" )) am . keep_gb = std:: atof ( e ); 1680if ( const char * e = std:: getenv ( "STRATA_METAL_ARENA_GB" )) am . arena_gb = std:: atof ( e ); 1681if ( const char * e = std:: getenv ( "STRATA_METAL_LEAVE_SHARE" )) am . leave_share = std:: atof ( e ); // for measuring; the default is kLeaveShare 1682const double keep = arena_keep ( am ); 1683const double avail = am . available ; 1684double budget = arena_budget ( am ); 1685if ( budget < 2 * gb ) { 1686std:: fprintf ( stderr , "strata metal stream: only %.1f GB left for the expert arena (the GPU working set %.1f GB, RAM %.1f GB, " 1687"%.1f GB allocated): expect a low hit rate\n" , budget / gb , cx_ -> recommended_working_set () / gb , 1688phys / gb , used / gb ); 1689budget = std:: max ( budget , 1.0 * gb ); 1690} 1691std::string prof ; 1692if ( const char * e = std:: getenv ( "STRATA_METAL_EXPERT_PROFILE" )) prof = e ; 1693else prof = strata_metal:: resource ( nullptr , "data" , STRATA_METAL_DATA_DEFAULT ) + "/expert-profile.bin" ; 1694std:: fprintf ( stderr , "strata metal stream: %.2f GB allocated before the arena (the process holds %.2f GB, %.2f GB resident); " 1695"RAM %.1f GB (%.1f GB available, %.1f GB kept for macOS), GPU working set %.1f GB\n" , used / gb , 1696pm0 . footprint / gb , pm0 . rss / gb , phys / gb , avail / gb , keep / gb , cx_ -> recommended_working_set () / gb ); 1697{ // the planned total: arena + the Metal buffers (or the process's own count when it is more) + the n-gram table's 1698// reserve, against the cap (arena_budget.h: footprint_cap) 1699const FootprintPlan fp = footprint_plan ( am , budget ); 1700std:: fprintf ( stderr , "strata metal stream: planned resident footprint %.1f GB = arena %.1f + %.1f held before it + %.1f " 1701"reserved for the n-gram table; cap %.1f GB = the lesser of the GPU working set %.1f GB and the RAM " 1702"%.1f GB less %.1f GB left to macOS and its file cache%s\n" , 1703fp . total / gb , fp . arena / gb , fp . base / gb , fp . ple / gb , fp . cap / gb , cx_ -> recommended_working_set () / gb , 1704phys / gb , ( am . phys - fp . cap ) / gb , 1705am . arena_gb >= 0 && fp . over () ? " - STRATA_METAL_ARENA_GB is above the cap: kept as set (your choice), but " 1706"a Mac that runs short of memory can freeze (watchdog panics seen at 90+ GB " 1707"resident of 128)" : "" ); 1708} 1709const char * epg = std:: getenv ( "STRATA_METAL_PROMPT_GEMM" ); 1710const bool pg_on = !( epg && std:: string ( epg ) == "0" ); 1711bool minimal = false; // the arena's least layout (the min slots) is not shrunk further: it goes ahead, filled in steps 1712for (int tries = 0 ;; ++ tries ) { 1713const double planned = budget ; 1714std::function < uint64_t() > recheck = [ & ]() -> uint64_t { return (uint64_t) arena_shrink ( am , planned , avail_now ()); }; 1715if ( st_ -> make_arena ( * cx_ , (uint64_t) budget , prof , pg_on ? 576 : 64 , err , minimal ? std:: function < uint64_t() > () : recheck , 1716[ & ](uint64_t step ) { return arena_grow ( am , avail_now (), (double) step ); })) 1717break ; 1718if ( st_ -> shrink_to () == 0 || tries == 4 ) return false; 1719if ((double) st_ -> shrink_to () + 64.0 * ( 1 << 20 ) >= budget ) minimal = true; // no smaller layout than this one 1720std:: fprintf ( stderr , "strata metal stream: less memory is free than when the arena was planned: %.1f -> %.1f GB\n" , 1721budget / gb , st_ -> shrink_to () / gb ); 1722budget = (double) st_ -> shrink_to (); 1723} 1724if ( pg_on && ! prompt_gemm_init ( err )) return false; 1725{ // what the process really holds now, against the plan and the cap (a number that disagrees is a bug in the count) 1726const ProcMem pm1 = proc_mem (); 1727const double cap = footprint_cap ( am ); 1728std:: fprintf ( stderr , "strata metal stream: resident footprint after the fill: the process holds %.1f GB (%.1f GB resident), " 1729"planned %.1f GB, cap %.1f GB%s\n" , pm1 . footprint / gb , pm1 . rss / gb , 1730footprint_plan ( am , (double) st_ -> arena_used_bytes ()). total / gb , cap / gb , 1731pm1 . footprint > cap ? " - OVER THE CAP" : "" ); 1732} 1733g_stream_window = this ; 1734std:: atexit ( stream_atexit ); 1735return true; 1736} 1737 1738void Window:: logpos (int Tn , const int32_t * tokens , int64_t pos0 , bool head ) { 1739static const char * path = std:: getenv ( "STRATA_METAL_LOGPOS" ); 1740if ( path == nullptr || ! head ) return ; 1741if ( logpos_ == nullptr ) logpos_ = std:: fopen ( path , "ab" ); 1742if ( logpos_ == nullptr ) return ; 1743if ( lp_pend_ && Tn >= 1 && pos0 == lp_pos_ + 1 ) { 1744const int32_t tgt = tokens [ 0 ]; 1745std:: fprintf ( logpos_ , "%lld\t%d\t%.6f\t%d\t0\t0\t0\t0" , (long long) ( lp_pos_ - lp_first_ ), tgt , 1746(double) lp_row_ [(size_t) tgt ] - lp_lse_ , lp_arg_ ); 1747for ( const auto & [ v , id ] : lp_top_ ) std:: fprintf ( logpos_ , "\t%d:%.6f" , id , (double) v - lp_lse_ ); 1748std:: fputc ( '\n' , logpos_ ); 1749std:: fflush ( logpos_ ); 1750} 1751lp_pend_ = false; 1752if ( Tn != 1 ) return ; 1753if ( lp_first_ < 0 ) lp_first_ = pos0 ; 1754const float * lg = lm_ . as < float > (); 1755lp_row_ . assign ( lg , lg + n_vocab_ ); 1756float mx = lg [ 0 ]; 1757int32_t am = 0 ; 1758for (int64_t i = 1 ; i < n_vocab_ ; ++ i ) if ( lg [ i ] > mx ) { mx = lg [ i ]; am = (int32_t) i ; } 1759double s = 0.0 ; 1760for (int64_t i = 0 ; i < n_vocab_ ; ++ i ) s += std:: exp ((double) ( lg [ i ] - mx )); 1761lp_lse_ = (double) mx + std:: log ( s ); 1762lp_arg_ = am ; 1763lp_top_ . clear (); 1764for (int64_t i = 0 ; i < n_vocab_ ; ++ i ) lp_top_ . push_back ({ lg [ i ], (int32_t) i }); 1765std:: partial_sort ( lp_top_ . begin (), lp_top_ . begin () + 64 , lp_top_ . end (), 1766[]( const auto & a , const auto & b ) { return a . first > b . first || ( a . first == b . first && a . second < b . second ); }); 1767lp_top_ . resize ( 64 ); 1768lp_pos_ = pos0 ; 1769lp_pend_ = true; 1770} 1771 1772void Window:: kprof ( const std::vector < mtl::Dispatch >& ds , int Tn ) { 1773std::map < const mtl::Pipeline * , std::string > pname ; 1774for ( const auto & [ k , v ] : pcache_ ) pname [ & v ] = k . substr ( 0 , k . find ( '#' )); 1775std::map < uint64_t, std::string > tname ; 1776for ( const auto & [ k , v ] : f_ . tensors ) { 1777std::string n = k ; 1778if ( n . rfind ( "blk." , 0 ) == 0 ) n = n . substr ( n . find ( '.' , 4 ) + 1 ); 1779tname [ v . offset ] = n ; 1780} 1781std::map < size_t, std::string > q8name ; 1782for ( const auto & [ k , v ] : q8off_ ) { 1783std::string n = k ; 1784if ( n . rfind ( "blk." , 0 ) == 0 ) n = n . substr ( n . find ( '.' , 4 ) + 1 ); 1785q8name [ v ] = n ; 1786} 1787std::map < std::string, std::vector < mtl::Dispatch >> by ; 1788for ( const auto & d : ds ) { 1789std::string c = pname . count ( d . p ) ? pname [ d . p ] : "?" ; 1790if (! d . args . empty () && d . args [ 0 ]. buf == & W_ && tname . count ( d . args [ 0 ]. off ) && c . rfind ( "moe_" , 0 ) != 0 ) 1791c += " " + tname [ d . args [ 0 ]. off ]; 1792else if (! d . args . empty () && d . args [ 0 ]. buf == & Q8_ ) c += " " + ( q8name . count ( d . args [ 0 ]. off ) ? q8name [ d . args [ 0 ]. off ] : std:: string ( "Q8" )); 1793mtl::Dispatch x = d ; 1794x . barrier = true; 1795by [ c ]. push_back ( x ); 1796} 1797auto med = [ & ]( const std::vector < mtl::Dispatch >& v ) { 1798std::vector < double > t ; 1799for (int i = 0 ; i < 7 ; ++ i ) t . push_back ( 1000.0 * cx_ -> run_graph ( v )); 1800std:: sort ( t . begin (), t . end ()); 1801return t [ 3 ]; 1802}; 1803const double all = med ( ds ); 1804std::vector < std::pair < double, std::string >> rows ; 1805double sum = 0 ; 1806for ( const auto & [ c , v ] : by ) { 1807const double m = med ( v ); 1808sum += m ; 1809rows . push_back ({ m , c + " x" + std:: to_string ( v . size ())}); 1810} 1811std:: sort ( rows . rbegin (), rows . rend ()); 1812std:: fprintf ( stderr , "strata metal kprof: window T%d, %zu dispatches, GPU %.3f ms; classes alone (serialized) sum %.3f ms:\n" , 1813Tn , ds . size (), all , sum ); 1814for ( const auto & [ m , c ] : rows ) std:: fprintf ( stderr , "strata metal kprof: %8.3f ms %5.1f%% %s\n" , m , 100.0 * m / sum , c . c_str ()); 1815} 1816 1817void Window:: stepprof ( const std::vector < mtl::Dispatch >& ds , int Tn ) { 1818std::map < const mtl::Pipeline * , std::string > pname ; 1819for ( const auto & [ k , v ] : pcache_ ) pname [ & v ] = k . substr ( 0 , k . find ( '#' )); 1820std::map < uint64_t, const gguf::Tensor *> wt ; // W_ offset -> tensor 1821for ( const auto & [ k , v ] : f_ . tensors ) wt [ v . offset ] = & v ; 1822std::map < size_t, const gguf::Tensor *> qt ; // Q8_ offset -> tensor (the load-time Q8_0 copies) 1823for ( const auto & [ k , v ] : q8off_ ) { auto it = f_ . tensors . find ( k ); if ( it != f_ . tensors . end ()) qt [ v ] = & it -> second ; } 1824auto role = []( const std::string & n ) { return n . rfind ( "blk." , 0 ) == 0 ? n . substr ( n . find ( '.' , 4 ) + 1 ) : n ; }; 1825const size_t n = ds . size (); 1826struct Info { std::string part ; double wbytes = 0 ; }; 1827std::vector < Info > info (n); 1828for (size_t i = 0 ; i < n ; ++ i ) { 1829const auto & d = ds [ i ]; 1830const std::string c = pname . count ( d . p ) ? pname [ d . p ] : "?" ; 1831std::string part = "other" , tn ; 1832double wb = 0 ; 1833auto wbuf = [ & ](size_t a ) -> const gguf::Tensor * { 1834if ( a >= d . args . size () || ! d . args [ a ]. buf ) return nullptr ; 1835if ( d . args [ a ]. buf == & W_ ) { auto it = wt . find ( d . args [ a ]. off ); return it == wt . end () ? nullptr : it -> second ; } 1836if ( d . args [ a ]. buf == & Q8_ ) { auto it = qt . find ( d . args [ a ]. off ); return it == qt . end () ? nullptr : it -> second ; } 1837return nullptr ; 1838}; 1839const gguf::Tensor * t0 = wbuf ( 0 ); 1840if ( t0 ) tn = role ( t0 -> name ); 1841auto tsize = [ & ](size_t a ) -> double { 1842const gguf::Tensor * t = wbuf ( a ); 1843if (! t ) return 0 ; 1844if ( d . args [ a ]. buf == & Q8_ ) return (double) ( t -> shape [ 0 ] / 32 * 34 ) * ( t -> shape . size () > 1 ? (double) t -> shape [ 1 ] : 1.0 ); 1845return (double) t -> bytes ; 1846}; 1847if ( c . rfind ( "moe_gu" , 0 ) == 0 ) part = "experts gate+up" ; 1848else if ( c . rfind ( "moe_down" , 0 ) == 0 ) part = "experts down" ; 1849else if ( c . rfind ( "moe_route" , 0 ) == 0 ) part = "router" ; 1850else if ( c . rfind ( "moe_combine" , 0 ) == 0 ) part = "combine" ; 1851else if ( c . rfind ( "gr_" , 0 ) == 0 ) { part = "hc" ; wb = c . rfind ( "gr_down" , 0 ) == 0 ? tsize ( 0 ) + tsize ( 1 ) : c . rfind ( "gr_up" , 0 ) == 0 ? tsize ( 0 ) : 0 ; } 1852else if ( c . rfind ( "gdn_" , 0 ) == 0 ) part = "gdn other" ; 1853else if ( c . rfind ( "qsa_" , 0 ) == 0 ) part = "qsa other" ; 1854else if ( c . rfind ( "ple_" , 0 ) == 0 ) part = "ple" ; 1855else if ( c . rfind ( "argmax" , 0 ) == 0 ) part = "lm head (argmax)" ; 1856else if ( c . rfind ( "swiglu_prep" , 0 ) == 0 ) part = "shared" ; 1857else if ( c . rfind ( "xprep" , 0 ) == 0 ) part = "xprep" ; 1858else if ( c . rfind ( "gemv" , 0 ) == 0 && t0 ) { 1859wb = tsize ( 0 ); 1860if ( tn == "attn_qkv.weight" || tn == "attn_gate.weight" || tn == "ssm_alpha.weight" || tn == "ssm_beta.weight" || tn == "ssm_out.weight" ) part = "gdn dense" ; 1861else if ( tn == "attn_q.weight" || tn == "attn_k.weight" || tn == "attn_v.weight" || tn == "attn_output.weight" || tn . rfind ( "indexer." , 0 ) == 0 ) part = "qsa dense" ; 1862else if ( tn == "ffn_gate_inp.weight" ) part = "router" ; 1863else if ( tn . find ( "shexp" ) != std::string:: npos ) part = "shared" ; 1864else if ( tn == "output.weight" || t0 -> name == "output.weight" ) part = "lm head" ; 1865else if ( tn . find ( "ple_" ) != std::string:: npos ) part = "ple" ; 1866else part = "gemv other " + tn ; 1867} 1868info [ i ] = { part , wb }; 1869} 1870// barrier groups 1871std::vector < size_t > gs ; 1872for (size_t i = 0 ; i < n ; ++ i ) if ( i == 0 || ds [ i ]. barrier ) gs . push_back ( i ); 1873gs . push_back ( n ); 1874const size_t m = gs . size () - 1 ; 1875// the route dispatches (one per layer): the prefix that ends right after one holds that layer's routed ids 1876std::vector < size_t > routes ; 1877for (size_t i = 0 ; i < n ; ++ i ) 1878if ( pname . count ( ds [ i ]. p ) && pname [ ds [ i ]. p ]. rfind ( "moe_route" , 0 ) == 0 ) routes . push_back ( i ); 1879const int reps = std:: getenv ( "STRATA_METAL_STEPPROF_REPS" ) ? std:: max ( 1 , std:: atoi (std:: getenv ( "STRATA_METAL_STEPPROF_REPS" ))) : 5 ; 1880std:: fprintf ( stderr , "strata metal stepprof: T%d, %zu dispatches in %zu barrier groups, %zu layers routed, %d reps per prefix\n" , Tn , n , m , routes . size (), reps ); 1881for (int i = 0 ; i < 40 ; ++ i ) cx_ -> run_graph ( ds ); // clocks up 1882const double full = [ & ] { std::vector < double > t ; for (int i = 0 ; i < 15 ; ++ i ) t . push_back ( 1000.0 * cx_ -> run_graph ( ds )); std:: sort ( t . begin (), t . end ()); return t [ 7 ]; }(); 1883std::vector < std::vector < double >> tp ( m + 1 ); 1884// the GPU heats up during the hundreds of runs: every pass is scaled by (the cool whole-window time / the whole window run at the start of that pass) 1885for (int r = 0 ; r < reps ; ++ r ) { 1886double fr = 0 ; 1887{ std::vector < double > q ; for (int i = 0 ; i < 5 ; ++ i ) q . push_back ( 1000.0 * cx_ -> run_graph ( ds )); std:: sort ( q . begin (), q . end ()); fr = q [ 2 ]; } 1888const double sc = full / fr ; 1889tp [ 0 ]. push_back ( sc * 1000.0 * cx_ -> run_graph ( ds , 0 )); 1890for (size_t j = 1 ; j <= m ; ++ j ) tp [ j ]. push_back ( sc * 1000.0 * cx_ -> run_graph ( ds , gs [ j ])); 1891std:: fprintf ( stderr , "strata metal stepprof: pass %d: whole window %.3f ms (cool %.3f, scale %.3f)\n" , r , fr , full , sc ); 1892} 1893std::vector < double > t ( m + 1 ); 1894for (size_t j = 0 ; j <= m ; ++ j ) { std:: sort ( tp [ j ]. begin (), tp [ j ]. end ()); t [ j ] = tp [ j ][ tp [ j ]. size () / 2 ]; } 1895// distinct experts per layer 1896std::vector < int > distinct ; 1897double expert_total = 0 ; 1898for (size_t li = 0 ; li < routes . size (); ++ li ) { 1899cx_ -> run_graph ( ds , routes [ li ] + 1 ); 1900std::set < int > u ; 1901for (int k = 0 ; k < Tn * TOPK ; ++ k ) { const int v = ids_ . as < int32_t > ()[ k ]; if ( v >= 0 ) u . insert ( v ); } 1902distinct . push_back ((int) u . size ()); 1903} 1904auto expert_bytes = [ & ](size_t layer , bool gu , bool dn ) { 1905const std::string L = "blk." + std:: to_string ( layer ) + "." ; 1906auto eb = [ & ]( const char * nm ) { const gguf::Tensor * tt = f_ . find ( L + nm ); return tt ? (double) tt -> bytes / std:: max ( 1 , nexp_ ) : 0.0 ; }; 1907double b = 0 ; 1908if ( gu ) b += eb ( "ffn_gate_exps.weight" ) + eb ( "ffn_up_exps.weight" ); 1909if ( dn ) b += eb ( "ffn_down_exps.weight" ); 1910return b * ( layer < distinct . size () ? distinct [ layer ] : 0 ); 1911}; 1912for (size_t li = 0 ; li < distinct . size (); ++ li ) expert_total += expert_bytes ( li , true, true); 1913// per group: time, part (the experts if the group has any, else the dispatch with the most weight bytes, else the first), bytes 1914struct Row { double ms = 0 , bytes = 0 ; int groups = 0 , disp = 0 ; }; 1915std::map < std::string, Row > by ; 1916FILE * of = std:: getenv ( "STRATA_METAL_STEPPROF_OUT" ) ? std:: fopen (std:: getenv ( "STRATA_METAL_STEPPROF_OUT" ), "w" ) : nullptr ; 1917size_t layer_gu = 0 , layer_dn = 0 ; 1918for (size_t j = 0 ; j < m ; ++ j ) { 1919const double ms = t [ j + 1 ] - t [ j ]; 1920size_t best = gs [ j ]; 1921double bw = -1 ; 1922for (size_t i = gs [ j ]; i < gs [ j + 1 ]; ++ i ) if ( info [ i ]. wbytes > bw ) { bw = info [ i ]. wbytes ; best = i ; } 1923std::string part = bw > 0 ? info [ best ]. part : info [ gs [ j ]]. part ; 1924double bytes = 0 ; 1925bool has_gu = false, has_dn = false; 1926for (size_t i = gs [ j ]; i < gs [ j + 1 ]; ++ i ) { 1927bytes += info [ i ]. wbytes ; 1928if ( info [ i ]. part == "experts gate+up" ) has_gu = true; 1929if ( info [ i ]. part == "experts down" ) has_dn = true; 1930} 1931if ( has_gu ) { part = "experts gate+up" ; bytes += expert_bytes ( layer_gu ++ , true, false); } 1932if ( has_dn ) { part = has_gu ? part : "experts down" ; bytes += expert_bytes ( layer_dn ++ , false, true); } 1933Row & r = by [ part ]; 1934r . ms += ms ; r . bytes += bytes ; r . groups += 1 ; r . disp += (int) ( gs [ j + 1 ] - gs [ j ]); 1935if ( of ) std:: fprintf ( of , "%zu\t%zu\t%s\t%.4f\t%.0f\t%s\n" , j , gs [ j + 1 ] - gs [ j ], part . c_str (), ms , bytes , pname . count ( ds [ gs [ j ]]. p ) ? pname [ ds [ gs [ j ]]. p ]. c_str () : "?" ); 1936} 1937if ( of ) std:: fclose ( of ); 1938double sum = 0 , sumb = 0 ; 1939for (auto & [ k , r ] : by ) { sum += r . ms ; sumb += r . bytes ; } 1940std:: fprintf ( stderr , "strata metal stepprof: window T%d: whole-window GPU %.3f ms (median of 15), prefix chain %.3f ms (empty-list base %.3f ms), weight bytes %.1f MiB (experts %.1f MiB, distinct per layer avg %.2f)\n" , 1941Tn , full , t [ m ] - t [ 0 ], t [ 0 ], sumb / 1048576.0 , expert_total / 1048576.0 , 1942distinct . empty () ? 0.0 : std:: accumulate ( distinct . begin (), distinct . end (), 0.0 ) / (double) distinct . size ()); 1943std::vector < std::pair < double, std::string >> rows ; 1944for (auto & [ k , r ] : by ) rows . push_back ({ r . ms , k }); 1945std:: sort ( rows . rbegin (), rows . rend ()); 1946for ( const auto & [ ms , k ] : rows ) { 1947const Row & r = by [ k ]; 1948std:: fprintf ( stderr , "strata metal stepprof: %-22s %8.3f ms %5.1f%% %5d disp %5d groups %9.1f MiB %7.1f GB/s\n" , k . c_str (), ms , 100.0 * ms / sum , r . disp , r . groups , 1949r . bytes / 1048576.0 , r . bytes > 0 && ms > 0 ? r . bytes / 1e9 / ( ms / 1000.0 ) : 0.0 ); 1950} 1951std::string ds_str ; 1952for (size_t i = 0 ; i < distinct . size (); ++ i ) ds_str += std:: to_string ( distinct [ i ]) + ( i + 1 < distinct . size () ? "," : "" ); 1953std:: fprintf ( stderr , "strata metal stepprof: distinct experts per layer: %s\n" , ds_str . c_str ()); 1954std:: fflush ( stderr ); 1955} 1956 1957Window::~ Window () { 1958df2_free (); 1959if ( logpos_ ) std:: fclose ( logpos_ ); 1960print_prof (); 1961} 1962 1963// STRATA_METAL_PROFILE=1: the per-window time split. Printed once: at the window's destruction, or at process exit 1964// (the serve loop leaves through exit() without destroying the window) 1965void Window:: print_prof (bool periodic ) { 1966if (( prof_printed_ && ! periodic ) || std:: getenv ( "STRATA_METAL_PROFILE" ) == nullptr ) return ; 1967prof_printed_ = ! periodic ; 1968auto line = []( const char * what , const Prof & x ) { 1969if ( x . n == 0 ) return ; 1970std:: fprintf ( stderr , "strata metal profile: %-10s %6lld x %.3f ms: host before %.3f, run_graph %.3f (GPU %.3f, so " 1971"encode/submit/wait %.3f), patch+finish %.3f\n" , what , (long long) x . n , x . all / x . n , x . pre / x . n , 1972x . rg / x . n , x . gpu / x . n , ( x . rg - x . gpu ) / x . n , x . fin / x . n ); 1973}; 1974for ( const auto & [ k , x ] : prof_ ) { 1975const std::string w = "window T" + std:: to_string ( k / 2 ) + ( k % 2 ? "" : " nohead" ); 1976line ( w . c_str (), x ); 1977} 1978line ( "commit" , cprof_ ); 1979line ( "draft" , dprof_ ); 1980} 1981 1982bool Window:: finish (int Tn , const int32_t * tokens , int64_t pos0 , bool head , int32_t * out , double t0 ) { 1983++ win_n_ [ Tn ]; 1984win_ms_ [ Tn ] += now_ms () - t0 ; 1985win_gpu_ [ Tn ] += last_gpu_ms_ ; 1986static const bool prof = std:: getenv ( "STRATA_METAL_PROFILE" ) != nullptr ; 1987if ( prof ) { 1988Prof & x = prof_ [ Tn * 2 + ( head ? 1 : 0 )]; 1989const double t1 = now_ms (); 1990++ x . n ; x . pre += tp_pre_ - t0 ; x . rg += tp_rg_ ; x . gpu += last_gpu_ms_ ; x . fin += t1 - tp_pre_ - tp_rg_ ; 1991x . all += t1 - t0 ; 1992static int nprof = 0 ; 1993if ( ++ nprof % 100 == 0 ) print_prof (true); // cumulative; the serve loop may leave without a destructor 1994} 1995{ // STRATA_METAL_NFCHECK=1 (test tooling): every head window's logits scanned for non-finite values and the largest |logit| kept; 1996// a line for the first five bad windows, and a count every 500 head windows and at the 5000th (the numeric health of STRATA_METAL_F16 and the like) 1997static const bool nfc = std:: getenv ( "STRATA_METAL_NFCHECK" ) != nullptr ; 1998if ( nfc && head ) { 1999static long long nwin = 0 , nbad_win = 0 , nbad_val = 0 ; 2000static float maxabs = 0.0f ; 2001long long bad = 0 ; 2002for (int t = 0 ; t < Tn ; ++ t ) { 2003const float * row = lm_ . as < float > () + (size_t) t * n_vocab_ ; 2004for (int64_t i = 0 ; i < n_vocab_ ; ++ i ) { 2005if (!std:: isfinite ( row [ i ])) ++ bad ; 2006else maxabs = std:: max ( maxabs , std:: fabs ( row [ i ])); 2007} 2008} 2009++ nwin ; 2010if ( bad ) { 2011++ nbad_win ; nbad_val += bad ; 2012if ( nbad_win <= 5 ) 2013std:: fprintf ( stderr , "strata metal: NFCHECK non-finite logits: %lld values in a %d-token window at position %lld\n" , bad , Tn , (long long) pos0 ); 2014} 2015if ( nwin % 500 == 0 || nwin == 5000 ) 2016std:: fprintf ( stderr , "strata metal: NFCHECK %lld head windows, %lld with non-finite logits (%lld values), largest |logit| %.2f\n" , 2017nwin , nbad_win , nbad_val , (double) maxabs ); 2018} 2019} 2020logpos ( Tn , tokens , pos0 , head ); 2021if ( Tn == 1 ) hp_ = 1 - hp_ ; // the window committed its first row in the step 2022last_head_ = head ; 2023for (int t = 0 ; t < Tn ; ++ t ) out [ t ] = head ? tokout_ . as < int32_t > ()[ t ] : -1 ; 2024last_T_ = Tn ; 2025for (int t = 0 ; t < Tn ; ++ t ) last_tokens_ [ t ] = tokens [ t ]; 2026static const bool trace = std:: getenv ( "STRATA_METAL_TRACE" ) != nullptr ; 2027if ( trace && head ) { 2028// the pick and its margin over the runner-up (a near tie says a backend difference may flip it) 2029const float * lg = lm_ . as < float > (); 2030int i1 = -1 , i2 = -1 ; 2031for (int i = 0 ; i < n_vocab_ ; ++ i ) { 2032if ( i1 < 0 || lg [ i ] > lg [ i1 ]) { i2 = i1 ; i1 = i ; } 2033else if ( i2 < 0 || lg [ i ] > lg [ i2 ]) i2 = i ; 2034} 2035std:: fprintf ( stderr , "strata metal: window pos %lld token %d -> %d (top %d %.4f, 2nd %d %.4f, margin %.4f) %.2f ms (GPU %.2f ms, %d dispatches)\n" , 2036(long long) pos0 , tokens [ 0 ], out [ 0 ], i1 , lg [ i1 ], i2 , lg [ i2 ], lg [ i1 ] - lg [ i2 ], now_ms () - t0 , last_gpu_ms_ , last_n_disp_ ); 2037} 2038return true; 2039} 2040 2041void Window:: fold (std::vector < mtl::Dispatch >& ds , int n_keep , int hp ) { 2042const size_t off = 0 ; 2043for (int l = 0 ; l < G_NL ; ++ l ) { 2044if ( l % G_QI == G_QI - 1 ) continue ; 2045const int gi = l - l / G_QI ; 2046const std::string b = "blk." + std:: to_string ( l ) + "." ; 2047const size_t o_qkv = ((size_t) gi * MAXT + off ) * G_CONV * 4 , o_ab = ((size_t) gi * MAXT + off ) * G_HV * 4 , 2048o_z = ((size_t) gi * MAXT + off ) * G_ZV * 4 ; 2049GdnArgs a { G_HK , G_HV , G_CONV , 1u , eps_ , 0 }; 2050mtl::Dispatch d ; 2051d . p = P ( lgdn_ , "gdn_step" , mtl:: Constants (). i ( 2 , n_keep ), "gdn_step#" + std:: to_string ( n_keep )); 2052d . args = {mtl::Arg:: B ( gst_ [(size_t) gi ]), mtl::Arg:: B ( ghist_ [ hp ][(size_t) gi ]), mtl::Arg:: B ( qkvL_ , o_qkv ), 2053mtl::Arg:: B ( alL_ , o_ab ), mtl::Arg:: B ( beL_ , o_ab ), mtl::Arg:: B ( zL_ , o_z ), 2054mtl::Arg:: B ( W_ , T ( b + "ssm_conv1d.weight" ). offset ), mtl::Arg:: B ( W_ , T ( b + "ssm_dt.bias" ). offset ), 2055mtl::Arg:: B ( W_ , T ( b + "ssm_a" ). offset ), mtl::Arg:: B ( W_ , T ( b + "ssm_norm.weight" ). offset ), 2056mtl::Arg:: B ( ydump_ ), mtl::Arg:: V ( a ), mtl::Arg:: B ( ghist_ [ 1 - hp ][(size_t) gi ])}; 2057d . grid [ 0 ] = G_HV ; 2058d . tg [ 0 ] = 512 ; 2059nb_ = true; // the layers' folds are independent of each other 2060push ( ds , d ); 2061} 2062nb_ = false; // what follows reads the folded state: a barrier 2063} 2064 2065void Window:: swap_state (SeqSet & o ) { 2066auto sw = [](std::vector < mtl::Buffer >& a , std::vector < mtl::Buffer >& b ) { 2067for (size_t i = 0 ; i < a . size () && i < b . size (); ++ i ) std:: swap ( a [ i ], b [ i ]); 2068}; 2069sw ( gst_ , o . gst ); sw ( ghist_ [ 0 ], o . gh0 ); sw ( ghist_ [ 1 ], o . gh1 ); sw ( kq_ , o . kq ); sw ( vq_ , o . vq ); sw ( ksc_ , o . ksc ); sw ( vsc_ , o . vsc ); 2070sw ( tail_ , o . tail ); sw ( dead_ , o . dead ); sw ( pooled_ , o . pooled ); 2071std:: swap ( pleHist_ , o . pleHist ); 2072ple_hist_ . swap ( o . ple_hist ); 2073last_norm_ . swap ( o . last_norm ); 2074std:: swap ( hp_ , o . hp ); std:: swap ( pend_fold_ , o . pend_fold ); std:: swap ( last_T_ , o . last_T ); std:: swap ( last_head_ , o . last_head ); 2075for (int t = 0 ; t < MAXT ; ++ t ) std:: swap ( last_tokens_ [ t ], o . last_tokens [ t ]); 2076std:: swap ( ss_ , o . ss ); 2077} 2078 2079// the buffers of one sequence's running state, shaped like the live ones (real: allocated and zero; else empty placeholders) 2080void Window:: alloc_set (SeqSet & o , bool real , int idx ) { 2081const size_t MAXC = (size_t) max_cells_ , MB = MAXC / 4 + 2 ; 2082if ( real && bigs_ok_ ) { // set idx's part of the big buffers 2083for (size_t i = 0 ; i < gst_ . size (); ++ i ) { 2084o . gst . push_back ( view_of ( gstBig_ [ i ], (size_t) idx * st_gst_ , GST_B )); 2085o . gh0 . push_back ( view_of ( hbBig_ [ i ], ((size_t) idx * 2 + 0 ) * st_hist_ , HIST_B )); 2086o . gh1 . push_back ( view_of ( hbBig_ [ i ], ((size_t) idx * 2 + 1 ) * st_hist_ , HIST_B )); 2087} 2088for (size_t j = 0 ; j < kq_ . size (); ++ j ) { 2089o . kq . push_back ( view_of ( kqBig_ [ j ], (size_t) idx * st_kq_ , MAXC * G_QKV * G_QD )); 2090o . vq . push_back ( view_of ( vqBig_ [ j ], (size_t) idx * st_kq_ , MAXC * G_QKV * G_QD )); 2091o . ksc . push_back ( view_of ( kscBig_ [ j ], (size_t) idx * st_sc_ , 2 * MAXC * G_QKV * 4 )); 2092o . vsc . push_back ( view_of ( vscBig_ [ j ], (size_t) idx * st_sc_ , 2 * MAXC * G_QKV * 4 )); 2093o . tail . push_back ( view_of ( tailBig_ [ j ], (size_t) idx * st_tail_ , TAIL_B )); 2094o . dead . push_back ( view_of ( deadBig_ [ j ], (size_t) idx * st_dead_ , DEAD_B )); 2095o . pooled . push_back ( view_of ( pooledBig_ [ j ], (size_t) idx * st_pooled_ , 4 * MB * G_ID )); 2096} 2097o . pleHist = view_of ( pleBig_ , (size_t) idx * st_ple_ , PLEH_B ); 2098o . ple_hist . assign ( ple_hist_ . size (), 0.0f ); 2099return ; 2100} 2101auto A = [ & ](size_t bytes ) { return real ? cx_ -> alloc ( bytes ) : mtl:: Buffer (); }; 2102for (size_t i = 0 ; i < gst_ . size (); ++ i ) { 2103o . gst . push_back ( A ( GST_B )); 2104o . gh0 . push_back ( A ( HIST_B )); 2105o . gh1 . push_back ( A ( HIST_B )); 2106} 2107for (size_t j = 0 ; j < kq_ . size (); ++ j ) { 2108o . kq . push_back ( A ( MAXC * G_QKV * G_QD )); 2109o . vq . push_back ( A ( MAXC * G_QKV * G_QD )); 2110o . ksc . push_back ( A ( 2 * MAXC * 2 * 4 )); 2111o . vsc . push_back ( A ( 2 * MAXC * 2 * 4 )); 2112o . tail . push_back ( A ( TAIL_B )); 2113o . dead . push_back ( A ( DEAD_B )); 2114o . pooled . push_back ( A ( 4 * MB * G_ID )); 2115} 2116o . pleHist = A ( PLEH_B ); 2117if ( real ) o . ple_hist . assign ( ple_hist_ . size (), 0.0f ); 2118} 2119 2120bool Window:: slots_init ( const std::vector < strata::core::SessionState *>& slots , std::string & err ) { 2121if (! sets_ . empty ()) return true; // (asked once) 2122if ( cx_ == nullptr ) { err = "metal window: slots before the window is up" ; return false; } 2123std::vector < std::unique_ptr < SeqSet >> v ; 2124v . push_back (std:: make_unique < SeqSet > ()); 2125alloc_set ( * v [ 0 ], false); 2126v [ 0 ] -> ss = ss_ ; 2127set_of_ss_ [ ss_ ] = 0 ; 2128uint64_t bytes = 0 ; 2129for (size_t b = 0 ; b < slots . size (); ++ b ) { 2130if ((int) b >= g_slot_cap ) bigs_ok_ = false; // more slots than the window was sized for: serial windows only 2131auto x = std:: make_unique < SeqSet > (); 2132alloc_set ( * x , true, (int) b + 1 ); 2133x -> ss = slots [ b ]; 2134for (auto * vec : { & x -> gst , & x -> gh0 , & x -> gh1 , & x -> kq , & x -> vq , & x -> ksc , & x -> vsc , & x -> tail , & x -> dead , & x -> pooled }) 2135for ( const auto & bf : * vec ) bytes += bf . bytes ; 2136set_of_ss_ [ slots [ b ]] = (int) b + 1 ; 2137v . push_back (std:: move ( x )); 2138} 2139sets_ = std:: move ( v ); 2140active_ = 0 ; 2141if ( bigs_ok_ ) { // the strides the row kernels need (elements of each array's type) 2142uint32_t * h = rinfo_ . as < uint32_t > (); 2143h [ 0 ] = (uint32_t) st_kq_ ; h [ 1 ] = (uint32_t) ( st_sc_ / 2 ); h [ 2 ] = (uint32_t) ( st_tail_ / 4 ); h [ 3 ] = (uint32_t) ( st_dead_ / 4 ); 2144h [ 4 ] = (uint32_t) ( st_pooled_ / 4 ); h [ 5 ] = (uint32_t) ( st_gst_ / 4 ); h [ 6 ] = (uint32_t) ( st_hist_ / 4 ); h [ 7 ] = (uint32_t) ( st_ple_ / 4 ); 2145} 2146std:: fprintf ( stderr , "strata metal: %zu batch slots, each with its own running state and K/V (%.2f GB each, %.2f GB in all)\n" , 2147slots . size (), slots . empty () ? 0.0 : (double) bytes / (double) slots . size () / 1e9 , (double) bytes / 1e9 ); 2148return true; 2149} 2150 2151// Makes `set` the live state. The live members and the stashes exchange contents (two swaps through the active set's own stash). 2152void Window:: activate (int set ) { 2153if ( set == active_ || set < 0 || set >= (int) sets_ . size ()) return ; 2154swap_state ( * sets_ [(size_t) active_ ]); // the stash of the active one now holds its state, the live members the spare 2155swap_state ( * sets_ [(size_t) set ]); // ... and now the wanted one 2156active_ = set ; 2157} 2158 2159bool Window:: run_slots ( const int * rows , int S , const int32_t * tokens , const int64_t * pos , int32_t * out , std::string & err ) { 2160if ( sets_ . empty ()) { err = "metal window: no batch slots" ; return false; } 2161static const bool one_window = !(std:: getenv ( "STRATA_METAL_BATCH_ROWS" ) && std:: string (std:: getenv ( "STRATA_METAL_BATCH_ROWS" )) == "0" ); 2162if ( one_window && bigs_ok_ ) { 2163activate ( 0 ); 2164return run_rows ( rows , S , tokens , pos , out , err ); 2165} 2166bool ok = true; 2167for (int t = 0 ; t < S && ok ; ++ t ) { 2168if ( rows [ t ] < 0 || rows [ t ] >= n_slots ()) { err = "metal window: a batch row names a slot that does not exist" ; ok = false; break ; } 2169activate ( rows [ t ] + 1 ); 2170// a one-token window commits its row in its own step; commit(1) adds the PLE history and the session's token pair, 2171// which read buffers the next window rewrites 2172ok = run ( 1 , tokens + t , pos [ t ], true, out + t , err ) && commit ( 1 , err ); 2173} 2174activate ( 0 ); 2175return ok ; 2176} 2177 2178bool Window:: slot_copy (bool into_slot , int b , int64_t upto , bool kv_only , std::string & err ) { 2179if ( b < 0 || b >= n_slots ()) { err = "metal window: no such batch slot" ; return false; } 2180activate ( 0 ); 2181SeqSet & o = * sets_ [(size_t) b + 1 ]; 2182if ( pend_fold_ > 0 || o . pend_fold > 0 ) { err = "metal window: a slot copy with a fold pending" ; return false; } 2183const size_t cells = (size_t) std:: max < int64_t > ( 0 , std:: min < int64_t > ( upto , max_cells_ )); 2184auto cp = [ & ]( const mtl::Buffer & live , const mtl::Buffer & stash , size_t n ) { 2185n = std:: min ({ n , live . bytes , stash . bytes }); 2186if ( into_slot ) std:: memcpy ( stash . ptr , live . ptr , n ); else std:: memcpy ( live . ptr , stash . ptr , n ); 2187}; 2188const int hs = into_slot ? hp_ : o . hp ; // the committed history parity of the source 2189if (! kv_only ) { 2190if ( into_slot ) o . hp = hp_ ; else hp_ = o . hp ; 2191for (size_t i = 0 ; i < gst_ . size (); ++ i ) { 2192cp ( gst_ [ i ], o . gst [ i ], gst_ [ i ]. bytes ); 2193cp ( ghist_ [ hs ][ i ], hs ? o . gh1 [ i ] : o . gh0 [ i ], ghist_ [ hs ][ i ]. bytes ); 2194} 2195} 2196for (size_t j = 0 ; j < kq_ . size (); ++ j ) { 2197cp ( kq_ [ j ], o . kq [ j ], cells * G_QKV * G_QD ); 2198cp ( vq_ [ j ], o . vq [ j ], cells * G_QKV * G_QD ); 2199cp ( ksc_ [ j ], o . ksc [ j ], cells * G_QKV * 8 ); 2200cp ( vsc_ [ j ], o . vsc [ j ], cells * G_QKV * 8 ); 2201cp ( pooled_ [ j ], o . pooled [ j ], (( cells + 3 ) / 4 + 2 ) * G_ID * 4 ); 2202if ( kv_only ) continue ; 2203cp ( tail_ [ j ], o . tail [ j ], tail_ [ j ]. bytes ); 2204cp ( dead_ [ j ], o . dead [ j ], dead_ [ j ]. bytes ); 2205} 2206if ( kv_only ) return true; 2207cp ( pleHist_ , o . pleHist , pleHist_ . bytes ); 2208if ( into_slot ) { o . ple_hist = ple_hist_ ; o . ss -> ple_prev [ 0 ] = ss_ -> ple_prev [ 0 ]; o . ss -> ple_prev [ 1 ] = ss_ -> ple_prev [ 1 ]; } 2209else { ple_hist_ = o . ple_hist ; ss_ -> ple_prev [ 0 ] = o . ss -> ple_prev [ 0 ]; ss_ -> ple_prev [ 1 ] = o . ss -> ple_prev [ 1 ]; } 2210return true; 2211} 2212 2213namespace { strata::core::QsaState * g_draft_state = nullptr ; } // the drafter's QsaState (MtpDrafter::kv_state), bound once the window has the draft layer 2214 2215static void bind_qsa (strata::core::QsaState & st , const mtl::Buffer & kq , const mtl::Buffer & vq , const mtl::Buffer & ksc , 2216const mtl::Buffer & vsc , const mtl::Buffer * pooled , const mtl::Buffer * tail , const mtl::Buffer * dead , 2217int64_t cells ) { 2218const int64_t page = strata::kernels:: qsa_real_shapes (). page_size ; 2219st . kv_int8 = true; st . kv_q4 = false; st . kv_hybrid = false; st . kv_rot = false; 2220st . k_q = (int8_t * ) kq . ptr ; st . v_q = (int8_t * ) vq . ptr ; 2221st . k_scale = (uint16_t * ) ksc . ptr ; st . v_scale = (uint16_t * ) vsc . ptr ; 2222st . k_pool = nullptr ; st . v_pool = nullptr ; 2223st . kv_mode = 0 ; 2224st . n_pages = cells / page ; st . n_slots = st . n_pages ; 2225st . max_cells = std:: min < int64_t > ( st . max_cells > 0 ? st . max_cells : cells , st . n_pages * page ); 2226if ( pooled ) { st . idx_pooled = (float * ) pooled -> ptr ; st . idx_pooled_rows = (int64_t) ( pooled -> bytes / ( G_ID * 4 )); } 2227if ( tail ) st . idx_tail = (float * ) tail -> ptr ; 2228if ( dead ) st . idx_dead = (float * ) dead -> ptr ; 2229} 2230 2231void Window:: bind_session (strata::core::SessionState & ss ) { 2232if (! ss . qsa_states ) return ; 2233const int64_t n = ss . qsa_alloc , o = ss . qsa_ord0 ; 2234if ( n != (int64_t) kq_ . size () || o != 0 ) return ; // a carved session: not this window's whole model 2235for (int64_t j = 0 ; j < n ; ++ j ) 2236bind_qsa ( ss . qsa_states [(size_t) ( o + j )], kq_ [(size_t) j ], vq_ [(size_t) j ], ksc_ [(size_t) j ], vsc_ [(size_t) j ], 2237& pooled_ [(size_t) j ], & tail_ [(size_t) j ], & dead_ [(size_t) j ], max_cells_ ); 2238} 2239 2240void Window:: bind_draft (strata::core::QsaState & st ) { 2241if ( mkq_ . empty ()) return ; 2242// the draft layer has no indexer (the snapshot saves no pooled rows for it); its tail/dead ring is not part of the image 2243bind_qsa ( st , mkq_ [ 0 ], mvq_ [ 0 ], mksc_ [ 0 ], mvsc_ [ 0 ], nullptr , nullptr , nullptr , max_cells_ ); 2244} 2245 2246bool Window:: checkpoint_save (strata::core::ConversationCheckpoint & c , std::string & err ) { 2247(void) err ; 2248if ( pend_fold_ > 0 ) { // the last commit's fold first: the checkpoint is the state after it 2249std::vector < mtl::Dispatch > ds ; 2250nb_ = false; 2251fold ( ds , pend_fold_ , 1 - hp_ ); 2252cx_ -> run_graph ( ds ); 2253pend_fold_ = 0 ; 2254} 2255// The checkpoint is the shared contract (core/conversation_state.cpp's conversation_state_sizes), the one the CUDA indexer 2256// keeps: the raw tail is idx_block - 1 = 3 rows a layer and block_pos is a scratch int32 a layer. This window's ring has 2257// 4 rows (slot = cell % 4), but row 3 is written by the cell that completes the block before it is read, so it never 2258// has to survive a checkpoint: rows 0..2 are the whole state (the means are identical, qsa.metal qsa_prep). 2259const size_t gs = GST_B , hs = HIST_B , ts = 3 * 4 * G_ID , dsz = DEAD_B ; 2260c . gdn . resize ( gst_ . size () * ( gs + hs )); 2261for (size_t i = 0 ; i < gst_ . size (); ++ i ) { 2262std:: memcpy ( c . gdn . data () + i * ( gs + hs ), gst_ [ i ]. ptr , gs ); 2263std:: memcpy ( c . gdn . data () + i * ( gs + hs ) + gs , ghist_ [ hp_ ][ i ]. ptr , hs ); 2264} 2265c . ple . assign (( const uint8_t * ) pleHist_ . ptr , ( const uint8_t * ) pleHist_ . ptr + PLEH_B ); 2266c . tails . resize ( tail_ . size () * ts ); 2267c . dead . resize ( dead_ . size () * dsz ); 2268for (size_t j = 0 ; j < tail_ . size (); ++ j ) { 2269std:: memcpy ( c . tails . data () + j * ts , tail_ [ j ]. ptr , ts ); // rows 0..2 of the 4-row ring 2270std:: memcpy ( c . dead . data () + j * dsz , dead_ [ j ]. ptr , dsz ); 2271} 2272c . block_pos . assign ( tail_ . size () * sizeof (int32_t), 0 ); // scratch on every backend: written before it is read 2273return true; 2274} 2275 2276void Window:: reset () { 2277pend_fold_ = 0 ; 2278last_T_ = 0 ; 2279auto zero = []( const mtl::Buffer & b , size_t n ) { std:: memset ( b . ptr , 0 , n ); }; 2280for (size_t i = 0 ; i < gst_ . size (); ++ i ) { 2281zero ( gst_ [ i ], GST_B ); 2282zero ( ghist_ [ 0 ][ i ], HIST_B ); 2283zero ( ghist_ [ 1 ][ i ], HIST_B ); 2284} 2285zero ( pleHist_ , PLEH_B ); 2286for (size_t j = 0 ; j < tail_ . size (); ++ j ) { 2287zero ( tail_ [ j ], TAIL_B ); 2288zero ( dead_ [ j ], DEAD_B ); 2289} 2290for (size_t j = 0 ; j < mtail_ . size (); ++ j ) { 2291zero ( mtail_ [ j ], TAIL_B ); 2292zero ( mdead_ [ j ], DEAD_B ); 2293} 2294} 2295 2296bool Window:: checkpoint_restore ( const strata::core::ConversationCheckpoint & c , std::string & err ) { 2297const size_t gs = GST_B , hs = HIST_B , ts = 3 * 4 * G_ID , tsw = TAIL_B , dsz = DEAD_B ; 2298if ( c . gdn . size () != gst_ . size () * ( gs + hs ) || c . ple . size () != (size_t) PLEH_B || 2299( c . tails . size () != tail_ . size () * ts && c . tails . size () != tail_ . size () * tsw ) || c . dead . size () != dead_ . size () * dsz ) { 2300err = "metal window: the checkpoint is not this engine's (sizes differ)" ; 2301return false; 2302} 2303pend_fold_ = 0 ; // the restored state replaces whatever was pending 2304last_T_ = 0 ; 2305for (size_t i = 0 ; i < gst_ . size (); ++ i ) { 2306std:: memcpy ( gst_ [ i ]. ptr , c . gdn . data () + i * ( gs + hs ), gs ); 2307std:: memcpy ( ghist_ [ hp_ ][ i ]. ptr , c . gdn . data () + i * ( gs + hs ) + gs , hs ); 2308} 2309std:: memcpy ( pleHist_ . ptr , c . ple . data (), c . ple . size ()); 2310const size_t cts = c . tails . size () / std:: max < size_t > ( tail_ . size (), 1 ); // 3 rows (the shared contract) or 4 (an older image) 2311for (size_t j = 0 ; j < tail_ . size (); ++ j ) { 2312std:: memset ( tail_ [ j ]. ptr , 0 , tsw ); 2313std:: memcpy ( tail_ [ j ]. ptr , c . tails . data () + j * cts , cts ); 2314std:: memcpy ( dead_ [ j ]. ptr , c . dead . data () + j * dsz , dsz ); 2315} 2316return true; 2317} 2318 2319bool Window:: commit (int n_keep , std::string & err ) { 2320if ( n_keep < 1 || n_keep > last_T_ ) { err = "metal window: commit count out of range" ; return false; } 2321using namespace strata:: kernels ; 2322if ( last_T_ > 1 ) { 2323// the GDN layers: the kept prefix folded into the state (gdn_step over n_keep tokens from the window's own 2324// inputs, with commit; bitwise the window's trajectory). K/V and indexer cells past the prefix are rewritten 2325// when those positions run again, before anything reads them. 2326static const bool lazy = !(std:: getenv ( "STRATA_METAL_LAZY_FOLD" ) && std:: string (std:: getenv ( "STRATA_METAL_LAZY_FOLD" )) == "0" ); 2327int nf = n_keep ; 2328if ( nf > 0 ) { 2329if ( lazy ) { 2330pend_fold_ = nf ; // folded at the start of the next window (from the history parity before the turn) 2331} else { 2332std::vector < mtl::Dispatch > ds ; 2333nb_ = false; 2334fold ( ds , nf , hp_ ); 2335cx_ -> run_graph ( ds ); 2336} 2337hp_ = 1 - hp_ ; 2338} 2339} 2340strata::core::SessionState & ss = * ss_ ; 2341for (int t = 0 ; t < n_keep ; ++ t ) { 2342if ( ple_on_ ) { 2343const float * norm = normW_ . as < float > () + (size_t) t * NG_HC_DIM ; 2344for (int c = 0 ; c < NG_HC_DIM ; ++ c ) { 2345float * col = pleHist_ . as < float > () + (size_t) c * NG_HIST ; 2346for (int r = 0 ; r + 1 < NG_HIST ; ++ r ) col [ r ] = col [ r + 1 ]; 2347col [ NG_HIST - 1 ] = norm [ c ]; 2348} 2349} 2350ss . ple_prev [ 0 ] = ss . ple_prev [ 1 ]; 2351ss . ple_prev [ 1 ] = last_tokens_ [ t ]; 2352} 2353return true; 2354} 2355 2356 2357// ================================================================================================ the MTP draft layer 2358bool Window:: mtp_load ( const std::string & gguf_path , int max_t , std::string & err ) { 2359(void) max_t ; 2360if (! fm_ . open ( gguf_path , err )) return false; 2361madvise ( fm_ . map , fm_ . map_bytes , MADV_WILLNEED ); 2362Wm_ = cx_ -> wrap ( fm_ . map , fm_ . map_bytes ); 2363if ( Wm_ . handle == nullptr ) { err = "metal mtp: cannot wrap " + gguf_path ; return false; } 2364// vLLM's GemmaRMSNorm scales by (1 + w): the F32 norms folded once (tools/mtp_rt.py does the same for CUDA) 2365size_t tot = 0 ; 2366for ( const auto & kv : fm_ . tensors ) 2367if ( kv . second . type == 0 ) { mnorm_off_ [ kv . first ] = tot ; tot += ( kv . second . bytes + 255 ) / 256 * 256 ; } 2368mnorm_ = cx_ -> alloc ( tot + 256 ); 2369for ( const auto & kv : mnorm_off_ ) { 2370const gguf::Tensor & x = fm_ . tensors . at ( kv . first ); 2371const float * src = ( const float * ) (( const uint8_t * ) fm_ . map + x . offset ); 2372float * dst = (float * ) ( mnorm_ . as < uint8_t > () + kv . second ); 2373for (uint64_t i = 0 ; i < x . bytes / 4 ; ++ i ) dst [ i ] = src [ i ] + 1.0f ; 2374} 2375{ 2376const strata_metal::MslLib L = strata_metal:: lib_mtp ( engine_msl_dir ()); 2377lmtp_ = cx_ -> compile ( L . files , L . prelude ); 2378} 2379{ 2380const char * e = std:: getenv ( "STRATA_METAL_MTP_Q8" ); 2381if (!( e && std:: string ( e ) == "0" )) { 2382size_t tot = 0 ; 2383std::vector < std::string > names ; 2384for ( const auto & kv : fm_ . tensors ) { 2385const gguf::Tensor & x = kv . second ; 2386uint64_t ne = 1 ; 2387for (uint64_t d : x . shape ) ne *= d ; 2388if ( x . type != ref:: BF16 || x . shape . size () < 2 || x . shape [ 0 ] % 32 != 0 ) continue ; 2389gguf::Tensor q = x ; 2390q . type = ref:: Q8_0 ; 2391q . offset = tot ; 2392q . bytes = ne / 32 * 34 ; 2393mq8t_ [ x . name ] = q ; 2394names . push_back ( x . name ); 2395tot += ( q . bytes + 255 ) / 256 * 256 ; 2396} 2397mq8_ = cx_ -> alloc ( tot + 4096 ); 2398std::vector < std::thread > th ; 2399const unsigned nth = std:: max ( 1u , std:: min ( 16u , std::thread:: hardware_concurrency ())); 2400for (unsigned k = 0 ; k < nth ; ++ k ) 2401th . emplace_back ([ & , k ] { 2402std::vector < float > tmp ; 2403for (size_t i = k ; i < names . size (); i += nth ) { 2404const gguf::Tensor & x = fm_ . tensors . at ( names [ i ]); 2405const uint64_t ne = x . bytes / 2 ; 2406tmp . resize ( ne ); 2407ref:: dequant (ref:: BF16 , ( const uint8_t * ) fm_ . map + x . offset , tmp . data (), ne ); 2408ref:: quantize_q8_0 ( tmp . data (), ne , mq8_ . as < uint8_t > () + mq8t_ [ names [ i ]]. offset ); 2409} 2410}); 2411for (auto & x : th ) x . join (); 2412} 2413} 2414auto A = [ & ](size_t bytes ) { return cx_ -> alloc ( bytes ); }; 2415const int MAXC = (int) max_cells_ , MB = MAXC / 4 + 2 ; 2416mR_ = A ( 4 * MAXT * HC * N ); memb_ = A ( 4 * MAXT * N ); men_ = A ( 4 * MAXT * N ); me2_ = A ( 4 * MAXT * N ); 2417mhn_ = A ( 4 * MAXT * HC * N ); mh2_ = A ( 4 * HC * MAXT * N ); midx_ = A ( 4 * MAXT * ( G_IQR + G_ID )); mbo_ = A ( 4 * MAXT * N ); 2418minj_ [ 0 ] = A ( 4 * MAXT * HC ); minj_ [ 1 ] = A ( 4 * MAXT * HC ); mqids_ = A ( 4 * MAXT * G_BUD ); mlm_ = A ( 4 * (size_t) n_vocab_ ); 2419auto act = [ & ](int n ) { 2420Act x ; 2421x . n = n ; 2422x . b = A ( 4 * ((size_t) 4 * MAXT * n + (size_t) MAXT * n / 16 ) + ( metal_f16 () ? (size_t) 2 * 3 * MAXT * n : 0 )); 2423return x ; 2424}; 2425XEn_ = act ( N ); XHn_ = act ( N ); 2426mkq_ . push_back ( A ((size_t) MAXC * G_QKV * G_QD )); mvq_ . push_back ( A ((size_t) MAXC * G_QKV * G_QD )); 2427mksc_ . push_back ( A ( 2 * (size_t) MAXC * G_QKV * 4 )); mvsc_ . push_back ( A ( 2 * (size_t) MAXC * G_QKV * 4 )); 2428mtail_ . push_back ( A ( TAIL_B )); mdead_ . push_back ( A ( DEAD_B )); mpooled_ . push_back ( A ( 4 * (size_t) MB * G_ID )); 2429{ 2430std::string vp ; 2431// the subset setup put beside the draft layer (--draft-vocab: <mtp>/rt/draft_vocab.bin, as CUDA reads it), 2432// else the repository's default 2433const std::string beside = gguf_path . substr ( 0 , gguf_path . find_last_of ( '/' ) + 1 ) + "rt/draft_vocab.bin" ; 2434if ( const char * e = std:: getenv ( "STRATA_METAL_DRAFT_VOCAB" )) vp = e ; 2435else if (FILE * t = std:: fopen ( beside . c_str (), "rb" )) { std:: fclose ( t ); vp = beside ; } 2436else vp = strata_metal:: resource ( nullptr , "data" , STRATA_METAL_DATA_DEFAULT ) + "/draft_vocab.bin" ; 2437FILE * f = vp == "full" ? nullptr : std:: fopen ( vp . c_str (), "rb" ); 2438if ( f ) { 2439int32_t id ; 2440while (std:: fread ( & id , 4 , 1 , f ) == 1 ) if ( id >= 0 && id < n_vocab_ ) dvocab_ . push_back ( id ); 2441std:: fclose ( f ); 2442} 2443if (! dvocab_ . empty ()) { 2444const gguf::Tensor & h = T ( "output.weight" ); 2445const size_t rb = ref:: row_bytes ( h . type , N ); 2446mhead_ = A ( dvocab_ . size () * rb + 4096 ); 2447for (size_t i = 0 ; i < dvocab_ . size (); ++ i ) 2448std:: memcpy ( mhead_ . as < uint8_t > () + i * rb , ( const uint8_t * ) W_ . ptr + h . offset + (size_t) dvocab_ [ i ] * rb , rb ); 2449mhead_t_ = h ; 2450mhead_t_ . offset = 0 ; 2451mhead_t_ . shape = {(uint64_t) N , (uint64_t) dvocab_ . size ()}; 2452mhead_t_ . bytes = dvocab_ . size () * rb ; 2453} 2454} 2455mtp_on_ = true; 2456if ( g_draft_state ) bind_draft ( * g_draft_state ); 2457{ 2458const int ty = T ( "token_embd.weight" ). type ; 2459const int ok_types [] = { 30 , 8 , 2 , 6 , 20 , 23 , 42 , 21 , 11 , 12 , 13 , 14 , 18 }; 2460const char * e = std:: getenv ( "STRATA_METAL_MTP_CHAIN" ); 2461chain_ = !( e && std:: string ( e ) == "0" ) && std:: find (std:: begin ( ok_types ), std:: end ( ok_types ), ty ) != std:: end ( ok_types ); 2462if ( chain_ ) { 2463{ 2464const strata_metal::MslLib L = strata_metal:: lib_mtp_chain ( engine_msl_dir ()); 2465lchain_ = cx_ -> compile ( L . files , L . prelude ); 2466} 2467dout_ = A ( 4 * MAXT ); dprob_ = A ( 4 * MAXT ); posv_ = A ( 4 * N ); 2468for (int i = 0 ; i < N ; ++ i ) posv_ . as < float > ()[ i ] = (float) i ; 2469dmap_ = A ( 4 * std:: max < size_t > ( 1 , dvocab_ . size ())); 2470if (! dvocab_ . empty ()) std:: memcpy ( dmap_ . as < int32_t > (), dvocab_ . data (), 4 * dvocab_ . size ()); 2471// parity: a few tokens' embeddings, GPU vs the host's dequant (the per-step path's) 2472const gguf::Tensor & te = T ( "token_embd.weight" ); 2473const size_t rb = ref:: row_bytes ( te . type , N ); 2474const int32_t probe [ MAXT ] = { 0 , 1 , 271 , 760 , 6511 , 11751 , 100000 , (int32_t) n_vocab_ - 1 }; 2475double worst = 0.0 ; 2476std::vector < float > ref_row (N); 2477for (int k = 0 ; k < MAXT ; ++ k ) { 2478dout_ . as < int32_t > ()[ 0 ] = probe [ k ]; 2479std::vector < mtl::Dispatch > ds ; 2480nb_ = false; 2481mtl::Dispatch d ; 2482d . p = P ( lchain_ , "mtp_embed_" + std:: to_string ( ty ), {}, "mtp_embed_" + std:: to_string ( ty )); 2483struct EmbArgs { uint32_t n , row_bytes , j ; } ea {(uint32_t) N , (uint32_t) rb , 0 }; 2484d . args = {mtl::Arg:: B ( W_ , te . offset ), mtl::Arg:: B ( dout_ ), mtl::Arg:: B ( posv_ ), mtl::Arg:: B ( memb_ ), mtl::Arg:: V ( ea )}; 2485d . tg [ 0 ] = 256 ; 2486push ( ds , d ); 2487cx_ -> run_graph ( ds ); 2488ref:: dequant ( te . type , ( const uint8_t * ) W_ . ptr + te . offset + (size_t) probe [ k ] * rb , ref_row . data (), N ); 2489for (int i = 0 ; i < N ; ++ i ) worst = std:: max ( worst , (double) std:: fabs ( ref_row [ i ] - memb_ . as < float > ()[ i ])); 2490} 2491std:: fprintf ( stderr , "strata metal: MTP draft round in one command buffer (embedding type %d on the GPU: max " 2492"|GPU - host| %.3g over %d rows)\n" , ty , worst , MAXT ); 2493if ( worst > 1e-6 ) { 2494std:: fprintf ( stderr , "strata metal: the GPU embedding differs from the host's: a command buffer per step\n" ); 2495chain_ = false; 2496} 2497} 2498} 2499std:: fprintf ( stderr , "strata metal: MTP draft layer from %s (%.2f GB, %zu norms folded), draft head over %s tokens\n" , 2500gguf_path . c_str (), fm_ . file_bytes / 1e9 , mnorm_off_ . size (), 2501dvocab_ . empty () ? "all" : std:: to_string ( dvocab_ . size ()). c_str ()); 2502return true; 2503} 2504 2505void Window:: gr_read_m (std::vector < mtl::Dispatch >& ds , const std::string & pre , mtl::Buffer & Rb , const mtl::Buffer & bo , 2506const mtl::Buffer & inj_in , const mtl::Buffer & inj_out , bool apply , const Act & out , bool final_ , 2507int ntok ) { 2508const gguf::Tensor & tdn = TQ ( pre + ".input_mix_weight_down.weight" ); 2509const gguf::Tensor & tup = TQ ( pre + ".input_mix_weight_up.weight" ); 2510const gguf::Tensor & tin = final_ ? tdn : TQ ( pre + ".block_inject_weight.weight" ); 2511const bool q8 = tdn . type == ref:: Q8_0 && tup . type == ref:: Q8_0 && tin . type == ref:: Q8_0 ; 2512const mtl::Buffer & WB = q8 ? mq8_ : Wm_ ; 2513GrArgs a { N , HC , LR , (uint32_t) ntok , apply ? 1u : 0u , eps_ }; 2514mtl::Dispatch d1 ; 2515d1 . p = P ( lib_ , k_norm (), {}, k_norm ()); 2516d1 . args = {mtl::Arg:: B ( Rb ), mtl::Arg:: B ( bo ), mtl::Arg:: B ( inj_in ), mtl::Arg:: B ( mnorm_ , NM ( pre + ".hc_norm.weight" )), 2517mtl::Arg:: B ( xn_ ), mtl::Arg:: V ( a )}; 2518d1 . grid [ 0 ] = HC ; d1 . grid [ 1 ] = ntok ; d1 . tg [ 0 ] = 256 ; 2519push ( ds , d1 ); 2520mtl::Dispatch d2 ; 2521const char * dn = q8 ? "gr_down_q8_8_8" : "gr_down_8_8" ; 2522d2 . p = P ( lib_ , dn , mtl:: Constants (). i ( 1 , ntok ), std:: string ( dn ) + "#" + std:: to_string ( ntok )); 2523d2 . args = {mtl::Arg:: B ( WB , tdn . offset ), mtl::Arg:: B ( WB , tin . offset ), mtl::Arg:: B ( xn_ ), mtl::Arg:: B ( lo_ ), 2524mtl::Arg:: B ( inj_out ), mtl::Arg:: V ( a )}; 2525d2 . grid [ 0 ] = LR + HC ; d2 . tg [ 0 ] = 256 ; 2526push ( ds , d2 ); 2527mtl::Dispatch d3 ; 2528const char * up = q8 ? "gr_up_q8" : "gr_up" ; 2529d3 . p = P ( lib_ , up , mtl:: Constants (). i ( 1 , ntok ), std:: string ( up ) + "#" + std:: to_string ( ntok )); 2530GrArgs au = a ; 2531au . n_tok = MAXT ; 2532d3 . args = {mtl::Arg:: B ( WB , tup . offset ), mtl::Arg:: B ( lo_ ), mtl::Arg:: B ( xn_ ), mtl::Arg:: B ( out . b ), mtl::Arg:: V ( au )}; 2533d3 . grid [ 0 ] = N / 16 ; d3 . tg [ 0 ] = 256 ; 2534push ( ds , d3 ); 2535} 2536 2537void Window:: mtp_encode (std::vector < mtl::Dispatch >& ds , const mtl::Buffer & srcR , size_t src_off , int n , const int32_t * tokens , 2538int64_t cell0 , bool full , int erow , int slot ) { 2539struct RmsArgs { uint32_t n ; float eps ; }; 2540struct XpArgs { uint32_t n , n_tok , plane_tok , stride ; }; 2541struct CombArgs { uint32_t n , hc , n_tok , h_stride ; }; 2542// ---- the embedding rows (host tokens: dequantized on the CPU into the shared buffer) 2543const gguf::Tensor & te = T ( "token_embd.weight" ); 2544const size_t rb = ref:: row_bytes ( te . type , N ); 2545if ( tokens ) 2546for (int i = 0 ; i < n ; ++ i ) 2547ref:: dequant ( te . type , ( const uint8_t * ) W_ . ptr + te . offset + (size_t) tokens [ i ] * rb , 2548( membp_ ? * membp_ : memb_ ). as < float > () + (size_t) ( erow + i ) * N , N ); 2549const std::string L = "mtp.layers.0." ; 2550auto rms = [ & ]( const mtl::Buffer & x , size_t xo , const std::string & w , mtl::Buffer & y , int width , int rows ) { 2551mtl::Dispatch d ; 2552const char * rk = ldb_ && width == geo:: N && geo:: N == 2560 ? "mtp_rms_b10" : ldb_ && width == geo:: HCD && geo:: HCD == 10240 ? "mtp_rms_b40" : "mtp_rms" ; // (loads batched: same values) 2553d . p = P ( lmtp_ , rk , {}, rk ); 2554RmsArgs a {(uint32_t) width , eps_ }; 2555d . args = {mtl::Arg:: B ( x , xo ), mtl::Arg:: B ( mnorm_ , NM ( w )), mtl::Arg:: B ( y ), mtl::Arg:: V ( a )}; 2556d . grid [ 0 ] = rows ; d . tg [ 0 ] = 256 ; 2557push ( ds , d ); 2558}; 2559auto xp = [ & ]( const mtl::Buffer & x , size_t xo , const Act & out , int width , int rows , int stride ) { 2560mtl::Dispatch d ; 2561d . p = P ( lmtp_ , "mtp_xprep" , {}, "mtp_xprep" ); 2562XpArgs a {(uint32_t) width , (uint32_t) rows , MAXT , (uint32_t) stride }; 2563d . args = {mtl::Arg:: B ( x , xo ), mtl::Arg:: B ( out . b ), mtl::Arg:: V ( a )}; 2564d . grid [ 0 ] = ( width / 16 * rows + 255 ) / 256 ; d . tg [ 0 ] = 256 ; 2565push ( ds , d ); 2566}; 2567auto gm = [ & ]( const std::string & name , const Act & x , const mtl::Buffer & y , size_t y_stride , int rows , size_t y_off = 0 ) { 2568// a GEMV on the MTP model's tensor (the window's gemv() reads the main model's buffer) 2569const gguf::Tensor & tt = TQ ( name ); 2570const int n_in = (int) tt . shape [ 0 ], n_out = tt . shape . size () > 1 ? (int) tt . shape [ 1 ] : 1 , ty = tt . type ; 2571int Lq = 16 , Rr = 1 , S = 4 , K = 1 ; 2572if ( n_in >= 6144 ) { Lq = 32 ; Rr = 1 ; S = 8 ; K = 2 ; } 2573else if ( n_in == 640 ) { Lq = 8 ; Rr = 1 ; S = 4 ; K = 1 ; } 2574else if ( n_out <= 640 || ty == ref:: Q2_0 || ty == ref:: BF16 ) { Lq = 32 ; Rr = 1 ; S = 4 ; K = 1 ; } 2575const std::string fn = "gemv_" + std:: to_string ( ty ) + "_" + std:: to_string ( Lq ) + "_" + std:: to_string ( Rr ) + "_" + 2576std:: to_string ( S ) + "_" + std:: to_string ( K ); 2577GemvArgs a {(uint32_t) n_in , (uint32_t) n_out , (uint32_t) rows , (uint32_t) ref:: row_bytes ( ty , n_in ), (uint32_t) n_in , 2578(uint32_t) y_stride }; 2579mtl::Dispatch d ; 2580d . p = P ( lib_ , fn , mtl:: Constants (). i ( 0 , rows ), fn + "#" + std:: to_string ( rows )); 2581d . args = {mtl::Arg:: B ( MB ( name ), tt . offset ), mtl::Arg:: B ( x . b , x . plane_bytes () * xkind ( ty )), 2582mtl::Arg:: B ( x . b , x . plane_bytes () * 4 ), mtl::Arg:: B ( y , y_off ), mtl::Arg:: V ( a )}; 2583const int rpt = ( S / K ) * ( 32 / Lq ) * Rr ; 2584d . grid [ 0 ] = ( n_out + rpt - 1 ) / rpt ; d . tg [ 0 ] = S * 32 ; 2585push ( ds , d ); 2586}; 2587// ---- e = fc_embedding(rms(embed(tok)) * (1 + w)), h = fc_hidden per stream (rms_10240(R) * (1 + w)), R = h + e 2588rms ( membp_ ? * membp_ : memb_ , (size_t) erow * N * 4 , "mtp.pre_fc_norm_embedding.weight" , men_ , N , n ); 2589xp ( men_ , 0 , XEn_ , N , n , N ); 2590gm ( "mtp.fc_embedding.weight" , XEn_ , me2_ , N , n ); 2591rms ( srcR , src_off , "mtp.pre_fc_norm_hidden.weight" , mhn_ , HC * N , n ); 2592for (int c = 0 ; c < HC ; ++ c ) { 2593xp ( mhn_ , (size_t) c * N * 4 , XHn_ , N , n , HC * N ); 2594gm ( "mtp.fc_hidden.weight" , XHn_ , mh2_ , N , n , (size_t) c * MAXT * N * 4 ); 2595} 2596{ 2597mtl::Dispatch d ; 2598d . p = P ( lmtp_ , "mtp_combine" , {}, "mtp_combine" ); 2599CombArgs a { N , HC , (uint32_t) n , (uint32_t) ( MAXT * N )}; 2600d . args = {mtl::Arg:: B ( mh2_ ), mtl::Arg:: B ( me2_ ), mtl::Arg:: B ( mR_ ), mtl::Arg:: V ( a )}; 2601d . grid [ 0 ] = ( n * HC * N + 255 ) / 256 ; d . tg [ 0 ] = 256 ; 2602push ( ds , d ); 2603} 2604// ---- the attention hyper-connection, K/V (and the indexer keys) into the layer's own cache 2605gr_read_m ( ds , L + "attn_hyper_connection" , mR_ , mbo_ , minj_ [ 1 ], minj_ [ 0 ], false, XA_ , false, n ); 2606gm ( L + "self_attn.k_proj.weight" , XA_ , kcur_ , G_KV , n ); 2607nb_ = true; 2608gm ( L + "self_attn.v_proj.weight" , XA_ , vcur_ , G_KV , n ); 2609nb_ = true; 2610gm ( L + "self_attn.indexer.index_qk_proj.weight" , XA_ , midx_ , G_IQR + G_ID , n ); 2611if ( full ) { 2612nb_ = true; 2613gm ( L + "self_attn.q_proj.weight" , XA_ , qfull_ , G_QFULL , n ); 2614} 2615QsaArgs qa {(uint32_t) cell0 , 0 , (uint32_t) max_cells_ , (uint32_t) n , eps_ }; 2616{ 2617mtl::Dispatch d ; 2618d . p = P ( lqsa_ , "qsa_prep" , qsa_c (), qsa_k ()); 2619d . args = {mtl::Arg:: B ( qfull_ ), mtl::Arg:: B ( kcur_ ), mtl::Arg:: B ( vcur_ ), mtl::Arg:: B ( midx_ ), mtl::Arg:: B ( midx_ , G_IQR * 4 ), 2620mtl::Arg:: B ( mnorm_ , NM ( L + "self_attn.q_norm.weight" )), mtl::Arg:: B ( mnorm_ , NM ( L + "self_attn.k_norm.weight" )), 2621mtl::Arg:: B ( mnorm_ , NM ( L + "self_attn.indexer.q_layernorm.weight" )), 2622mtl::Arg:: B ( mnorm_ , NM ( L + "self_attn.indexer.k_layernorm.weight" )), 2623mtl::Arg:: B ( cs_ ), mtl::Arg:: B ( qcur_ ), mtl::Arg:: B ( qidx_ ), mtl::Arg:: B ( mkq_ [ 0 ]), mtl::Arg:: B ( mvq_ [ 0 ]), 2624mtl::Arg:: B ( mksc_ [ 0 ]), mtl::Arg:: B ( mvsc_ [ 0 ]), mtl::Arg:: B ( mtail_ [ 0 ]), mtl::Arg:: B ( mdead_ [ 0 ]), 2625mtl::Arg:: B ( mpooled_ [ 0 ]), mtl::Arg:: V ( qa ), mtl::Arg:: B ( mrope_ )}; 2626d . grid [ 0 ] = G_QPREP ; d . grid [ 1 ] = n ; d . tg [ 0 ] = 256 ; 2627push ( ds , d ); 2628} 2629if (! full ) return ; 2630// ---- dense attention over the window of cells up to this one (the draft layer's rule), the output gate, o_proj 2631{ 2632int * ids = mqids_ . as < int > () + (size_t) slot * G_BUD ; 2633const int64_t first = std:: max < int64_t > ( 0 , cell0 - 2050 ); 2634for (int64_t c = first ; c <= cell0 ; ++ c ) ids [ c - first ] = (int) c ; 2635mtl::Dispatch at ; 2636at . p = P ( lqsa_ , "qsa_attn" , {}, "qsa_attn" ); 2637at . args = {mtl::Arg:: B ( qcur_ ), mtl::Arg:: B ( mkq_ [ 0 ]), mtl::Arg:: B ( mvq_ [ 0 ]), mtl::Arg:: B ( mksc_ [ 0 ]), mtl::Arg:: B ( mvsc_ [ 0 ]), 2638mtl::Arg:: B ( mqids_ , (size_t) slot * G_BUD * 4 ), mtl::Arg:: B ( part_ ), mtl::Arg:: V ( qa )}; 2639at . grid [ 0 ] = G_QCHUNKS ; at . grid [ 1 ] = G_QKV ; at . grid [ 2 ] = 1 ; at . tg [ 0 ] = 256 ; 2640push ( ds , at ); 2641mtl::Dispatch m ; 2642m . p = P ( lqsa_ , "qsa_merge" , {}, "qsa_merge" ); 2643QsaArgs am = qa ; 2644am . n_tok = MAXT ; 2645m . args = {mtl::Arg:: B ( part_ ), mtl::Arg:: B ( qfull_ ), mtl::Arg:: B ( XQ_ . b ), mtl::Arg:: V ( am )}; 2646m . grid [ 0 ] = G_QH ; m . grid [ 1 ] = 1 ; m . tg [ 0 ] = 256 ; 2647push ( ds , m ); 2648gm ( L + "self_attn.o_proj.weight" , XQ_ , mbo_ , N , 1 ); 2649} 2650// ---- the MLP hyper-connection (the attention write folded in), the MoE, the write + final mixer, the head 2651gr_read_m ( ds , L + "mlp_hyper_connection" , mR_ , mbo_ , minj_ [ 0 ], minj_ [ 1 ], true, XF_ , false, 1 ); 2652gm ( L + "mlp.gate.weight" , XF_ , logits_ , 512 , 1 ); 2653nb_ = true; 2654gm ( L + "mlp.shared_expert.gate_proj.weight" , XF_ , gsh_ , NFF , 1 ); 2655nb_ = true; 2656gm ( L + "mlp.shared_expert.up_proj.weight" , XF_ , ush_ , NFF , 1 ); 2657nb_ = true; 2658gm ( L + "mlp.shared_expert_gate.weight" , XF_ , sg_ , 1 , 1 ); 2659{ 2660MoeArgs a {}; 2661const gguf::Tensor & tgu = TM ( L + "mlp.experts.gate_up_proj" ), & td = TM ( L + "mlp.experts.down_proj" ); 2662a . gu_row = (uint32_t) ref:: row_bytes ( tgu . type , N ); 2663a . d_row = (uint32_t) ref:: row_bytes ( td . type , NFF ); 2664a . gate_off = tgu . offset ; 2665a . up_off = tgu . offset + (uint64_t) NFF * a . gu_row ; // [gate rows | up rows] per expert 2666a . down_off = td . offset ; 2667a . gu_stride = (uint64_t) a . gu_row * 2 * NFF ; 2668a . d_stride = (uint64_t) a . d_row * N ; 2669a . n_embd = N ; a . n_ff = NFF ; a . n_tok = 1 ; a . topk = TOPK ; a . n_expert = NEXP ; // (the draft layer: its own 512 experts) 2670const bool dq2 = td . type == ref:: Q2_0 ; 2671const int gl = 32 , gr = 1 , gs = 4 , ds_ = 4 ; 2672// the down tile: Q2_0 8,1; else 4,2 - but on the M4 (no M5 layout) Q5_1 4,1 and Q8_0 8,1 (4,2 spills there: 2673// 24-36 GB/s, mac-kern 513fc615) 2674const bool m4 = ! m5_layout (); 2675const int dl = dq2 || ( m4 && td . type == ref:: Q8_0 ) ? 8 : 4 , 2676dr = dq2 || ( m4 && ( td . type == ref:: Q8_0 || td . type == ref:: Q5_1 || td . type == ref:: Q5_0 )) ? 1 : 2 ; 2677a . gx_gu = NFF / ( gs * ( 32 / gl ) * gr ); 2678a . gx_dn = N / ( ds_ * ( 32 / dl ) * dr ); 2679mtl::Dispatch r ; 2680r . p = P ( lib_ , "moe_route" , {}, "moe_route" ); 2681r . args = {mtl::Arg:: B ( logits_ ), mtl::Arg:: B ( ids_ ), mtl::Arg:: B ( wts_ ), mtl::Arg:: B ( plan_ ), mtl::Arg:: V ( a )}; 2682r . tg [ 0 ] = 512 ; 2683push ( ds , r ); 2684{ 2685GlueArgs ga { NFF , MAXT , N , TOPK }; 2686mtl::Dispatch d ; 2687d . p = P ( lib_ , "swiglu_prep" , {}, "swiglu_prep" ); 2688d . args = {mtl::Arg:: B ( gsh_ ), mtl::Arg:: B ( ush_ ), mtl::Arg:: B ( XH_ . b ), mtl::Arg:: V ( ga )}; 2689d . grid [ 0 ] = NFF / 16 ; d . grid [ 1 ] = 1 ; d . tg [ 0 ] = 16 ; 2690nb_ = true; 2691push ( ds , d ); 2692} 2693const std::string gun = "moe_gu_" + std:: to_string ( tgu . type ) + "_" + std:: to_string ( gl ) + "_" + std:: to_string ( gr ) + 2694"_" + std:: to_string ( gs ); 2695const std::string dnn = "moe_down_" + std:: to_string ( dq2 ? 142 : td . type ) + "_" + std:: to_string ( dl ) + "_" + 2696std:: to_string ( dr ) + "_" + std:: to_string ( ds_ ); 2697mtl::Dispatch g ; 2698g . p = P ( lib_ , gun , mtl:: Constants (). b ( 23 , metal_ctab ()), gun + ( metal_ctab () ? "#ct" : "" )); 2699g . args = {mtl::Arg:: B ( Wm_ ), mtl::Arg:: B ( XF_ . b , XF_ . plane_bytes () * xkind ( tgu . type )), mtl::Arg:: B ( h_ ), mtl::Arg:: B ( plan_ ), 2700mtl::Arg:: V ( a ), mtl::Arg:: B ( XF_ . b , XF_ . plane_bytes () * 4 )}; 2701g . tg [ 0 ] = 32 * gs ; 2702g . indirect = & plan_ ; 2703g . ind_off = P_IGU * 4 ; 2704push ( ds , g ); 2705nb_ = true; 2706gm ( L + "mlp.shared_expert.down_proj.weight" , XH_ , ysh_ , N , 1 ); 2707mtl::Dispatch dd ; 2708dd . p = P ( lib_ , dnn , {}, dnn ); 2709dd . args = {mtl::Arg:: B ( Wm_ ), mtl::Arg:: B ( h_ ), mtl::Arg:: B ( ye_ ), mtl::Arg:: B ( plan_ ), mtl::Arg:: V ( a ), mtl::Arg:: B ( h_ )}; 2710dd . tg [ 0 ] = 32 * ds_ ; 2711dd . indirect = & plan_ ; 2712dd . ind_off = P_IDN * 4 ; 2713push ( ds , dd ); 2714GlueArgs ca { N , 1 , N , TOPK }; 2715mtl::Dispatch cb ; 2716cb . p = P ( lib_ , k_comb (), {}, k_comb ()); 2717cb . args = {mtl::Arg:: B ( ye_ ), mtl::Arg:: B ( plan_ ), mtl::Arg:: B ( ysh_ ), mtl::Arg:: B ( sg_ ), mtl::Arg:: B ( mbo_ ), mtl::Arg:: V ( ca )}; 2718cb . grid [ 0 ] = ( N + 255 ) / 256 ; cb . tg [ 0 ] = 256 ; 2719push ( ds , cb ); 2720} 2721// the layer's write (R updated in place: the next draft step's input residual) and the final mixer 2722gr_read_m ( ds , "mtp.hyper_connection_mixer" , mR_ , mbo_ , minj_ [ 1 ], minj_ [ 0 ], true, XA_ , true, 1 ); 2723const int64_t nv = dvocab_ . empty () ? n_vocab_ : (int64_t) dvocab_ . size (); 2724if ( dvocab_ . empty ()) gemv ( ds , T ( "output.weight" ), XA_ , mlm_ , (size_t) n_vocab_ , 1 ); 2725else gemv ( ds , mhead_t_ , XA_ , mlm_ , (size_t) nv , 1 , 0 , & mhead_ ); 2726{ 2727ArgArgs a {(uint32_t) nv , 120 }; 2728mtl::Dispatch d1 , d2 ; 2729d1 . p = P ( lsmp_ , "argmax_part" , {}, "argmax_part" ); 2730d1 . args = {mtl::Arg:: B ( mlm_ ), mtl::Arg:: B ( apv_ ), mtl::Arg:: B ( api_ ), mtl::Arg:: V ( a )}; 2731d1 . grid [ 0 ] = 120 ; d1 . grid [ 1 ] = 1 ; d1 . tg [ 0 ] = 256 ; 2732push ( ds , d1 ); 2733d2 . p = P ( lsmp_ , "argmax_final" , {}, "argmax_final" ); 2734d2 . args = {mtl::Arg:: B ( apv_ ), mtl::Arg:: B ( api_ ), mtl::Arg:: B ( tokout_ ), mtl::Arg:: V ( a )}; 2735d2 . grid [ 0 ] = 1 ; d2 . tg [ 0 ] = 256 ; 2736push ( ds , d2 ); 2737} 2738} 2739 2740// the prompt's K/V: cell cell0 + i pairs the main window's final residual row i with the token at cell0 + i + 1 2741bool Window:: mtp_prefill ( const int32_t * next_tokens , int64_t n , int64_t cell0 , std::string & err ) { 2742if (! mtp_on_ ) { err = "metal mtp: not loaded" ; return false; } 2743mtp_wait (); // (the previous chunk's rows share the cache, the scratch and the embedding rows) 2744mrope_sync ( cell0 , n ); 2745// every group of MAXT rows in one command buffer: the embedding rows of all of them in mpemb_ (row c + i) 2746if ((int64_t) mpemb_rows_ < n ) { 2747if ( mpemb_rows_ > 0 ) cx_ -> free ( mpemb_ ); 2748mpemb_rows_ = (size_t) std:: max < int64_t > ( n , 64 ); 2749mpemb_ = cx_ -> alloc ( 4 * mpemb_rows_ * N ); 2750} 2751membp_ = & mpemb_ ; 2752std::vector < mtl::Dispatch > ds ; 2753nb_ = false; 2754for (int64_t c = 0 ; c < n ; c += MAXT ) { 2755const int k = (int) std:: min < int64_t > ( MAXT , n - c ); 2756mtp_encode ( ds , mpsrc_ ? * mpsrc_ : mtp_src_ ? * mtp_src_ : R_ , (size_t) c * HC * N * 4 , k , next_tokens + c , 2757cell0 + c , false, (int) c , 0 ); 2758} 2759membp_ = nullptr ; 2760if ( mtp_ovl_ && mpsrc_ == & pb_ . R && pb_ . R2 . handle != nullptr && ! mrope_on ()) mtp_async_ = cx_ -> run_graph_async ( ds ); 2761else cx_ -> run_graph ( ds ); 2762return true; 2763} 2764 2765void Window:: mtp_pick (std::vector < mtl::Dispatch >& ds , int j , bool embed ) { 2766struct PickArgs { uint32_t nv , j , use_map ; }; 2767const int64_t nv = dvocab_ . empty () ? n_vocab_ : (int64_t) dvocab_ . size (); 2768mtl::Dispatch d ; 2769d . p = P ( lchain_ , "mtp_pick" , {}, "mtp_pick" ); 2770PickArgs pa {(uint32_t) nv , (uint32_t) j , dvocab_ . empty () ? 0u : 1u }; 2771d . args = {mtl::Arg:: B ( mlm_ ), mtl::Arg:: B ( tokout_ ), mtl::Arg:: B ( dmap_ ), mtl::Arg:: B ( dout_ ), mtl::Arg:: B ( dprob_ ), 2772mtl::Arg:: V ( pa )}; 2773d . tg [ 0 ] = 1024 ; 2774push ( ds , d ); 2775if (! embed ) return ; 2776const gguf::Tensor & te = T ( "token_embd.weight" ); 2777struct EmbArgs { uint32_t n , row_bytes , j ; } ea {(uint32_t) N , (uint32_t) ref:: row_bytes ( te . type , N ), (uint32_t) j }; 2778mtl::Dispatch e ; 2779const std::string fn = "mtp_embed_" + std:: to_string ( te . type ); 2780e . p = P ( lchain_ , fn , {}, fn ); 2781e . args = {mtl::Arg:: B ( W_ , te . offset ), mtl::Arg:: B ( dout_ ), mtl::Arg:: B ( posv_ ), mtl::Arg:: B ( memb_ ), mtl::Arg:: V ( ea )}; 2782e . tg [ 0 ] = 256 ; 2783push ( ds , e ); 2784} 2785 2786// One round (mtp.hpp's draft()): the window's rows 0..a-1 caught up (K/V), then the full layer on row a (draft 0) and 2787// on its own output for the next drafts. By default the whole round is one command buffer (the pick, its 2788// probability and the next step's embedding on the GPU); STRATA_METAL_MTP_CHAIN=0: a command buffer per step, the 2789// host picking and dequantizing. The embedding rows: the catch-up's at memb_ rows 0..a-1, draft 0's at row a. 2790bool Window:: mtp_draft (int Tn , const int32_t * tokens , int64_t p , int a , int max_steps , int32_t * drafts , float * probs , 2791float min_p , int * n_drafts , std::string & err ) { 2792if (! mtp_on_ ) { err = "metal mtp: not loaded" ; return false; } 2793(void) Tn ; 2794mrope_sync ( p , a + max_steps + 1 ); 2795int n = 0 ; 2796int32_t tok = tokens [ a ]; 2797if ( chain_ && max_steps > 0 ) { 2798std::vector < mtl::Dispatch > ds ; 2799nb_ = false; 2800if ( a > 0 ) mtp_encode ( ds , R_ , 0 , a , tokens , p , false); 2801mtp_encode ( ds , R_ , (size_t) a * HC * N * 4 , 1 , & tok , p + a , true, a , 0 ); 2802mtp_pick ( ds , 0 , max_steps > 1 ); 2803for (int j = 1 ; j < max_steps ; ++ j ) { 2804mtp_encode ( ds , mR_ , 0 , 1 , nullptr , p + a + j , true, 0 , j ); 2805mtp_pick ( ds , j , j + 1 < max_steps ); 2806} 2807cx_ -> run_graph ( ds ); 2808for (int j = 0 ; j < max_steps ; ++ j ) { 2809const float pj = dprob_ . as < float > ()[ j ]; 2810drafts [ j ] = dout_ . as < int32_t > ()[ j ]; 2811if ( probs ) probs [ j ] = pj ; 2812++ n ; 2813if ( min_p > 0.0f && pj < min_p ) break ; 2814} 2815if ( n_drafts ) * n_drafts = n ; 2816return true; 2817} 2818for (int j = 0 ; j < max_steps ; ++ j ) { 2819std::vector < mtl::Dispatch > ds ; 2820nb_ = false; 2821if ( j == 0 ) { 2822if ( a > 0 ) mtp_encode ( ds , R_ , 0 , a , tokens , p , false); 2823mtp_encode ( ds , R_ , (size_t) a * HC * N * 4 , 1 , & tok , p + a , true, a , 0 ); 2824} else { 2825mtp_encode ( ds , mR_ , 0 , 1 , & tok , p + a + j , true); 2826} 2827cx_ -> run_graph ( ds ); 2828const int32_t di = tokout_ . as < int32_t > ()[ 0 ]; 2829const int32_t d = dvocab_ . empty () ? di : dvocab_ [(size_t) di ]; 2830// the draft's probability: softmax of the draft head's logits at the pick 2831const float * lg = mlm_ . as < float > (); 2832const float mx = lg [ di ]; 2833const int64_t nv = dvocab_ . empty () ? n_vocab_ : (int64_t) dvocab_ . size (); 2834double s = 0.0 ; 2835for (int64_t i = 0 ; i < nv ; ++ i ) s += std:: exp ((double) ( lg [ i ] - mx )); 2836const float pj = (float) ( 1.0 / s ); 2837drafts [ j ] = d ; 2838if ( probs ) probs [ j ] = pj ; 2839tok = d ; 2840++ n ; 2841if ( min_p > 0.0f && pj < min_p ) break ; 2842} 2843if ( n_drafts ) * n_drafts = n ; 2844return true; 2845} 2846 2847bool Window:: copy_logits (int t , float * host ) const { 2848if ( t < 0 || t >= last_T_ ) return false; 2849std:: memcpy ( host , lm_ . as < float > () + (size_t) t * n_vocab_ , (size_t) n_vocab_ * 4 ); 2850return true; 2851} 2852 2853 2854// ================================================================================== prompts through the matrix units 2855// A prompt chunk of T rows (mac-kern's tests/prompt_chain.cpp, on the engine's state): every dense matrix dequantized 2856// to fp16 once a chunk and multiplied on the matrix units (MPP), the GDN scan, QSA over the chunk, the routed experts 2857// as grouped GEMMs (v2 on the M4, v3 on the M5). The GDN state, the conv history, the K/V and indexer cells and the 2858// PLE history are the decode window's own, so decoding goes on from them. With SSD streaming the experts of a layer 2859// are put in place at the layer's handshake (the arena's misses) and the next layer's are streamed in behind it. 2860// STRATA_METAL_PROMPT_GEMM=0: prompts through the decode window (8 rows at a time). Its numerics differ from the 2861// window's (fp16 operands): STRATA_METAL_PROMPT_GEMM_MIN (default 64) keeps shorter prompts on the window path. 2862namespace { 2863struct PgDq { uint32_t n_in , n_out , row_bytes , perm ; }; 2864struct PgGemm { int M , N , K , pad ; }; 2865struct PgEpi { uint32_t n_tok , n_embd , hc , hc_lr ; }; 2866struct PgGdnP { uint32_t n_tok , h_k , h_v , channels ; float eps ; uint32_t f32 ; }; 2867struct PgPlan { uint32_t n_ent , topk , n_expert , tm , n_blocks ; }; 2868struct PgMm { uint64_t gate_off , up_off , down_off , gu_stride , d_stride ; uint32_t gu_row , d_row , n_embd , n_ff ; }; 2869int pg_unit (int t ) { return t == ref:: Q2_0 || t == ref:: IQ3_S || t == ref:: BF16 || t == ref:: F32 ? 16 : 32 ; } 2870// the v2 (M4) expert tiles: the K-quants need TK 128, Q8_0 / IQ4_XS TK 32 (their 32-value units), the rest TK 16 2871std::string gu2_tile (int t ) { 2872if ( t == ref:: Q4_K || t == ref:: Q5_K || t == ref:: Q6_K ) return "_16_16_128_2" ; // the M4's best (513fc615) 2873if ( t == ref:: Q8_0 || t == ref:: IQ4_XS ) return "_16_64_32_2" ; 2874return "_16_64_16_2" ; 2875} 2876std::string dn2_tile (int t ) { 2877if ( t == ref:: Q4_K || t == ref:: Q5_K || t == ref:: Q6_K ) return "_16_16_128_2" ; // Q4-KQ: the K-quants' down experts need TK 128 as their gate/up do 2878if ( t == ref:: Q3_K || t == ref:: IQ4_XS ) return "_16_64_32_2" ; 2879return t == ref:: IQ4_NL || t == ref:: Q5_1 || t == ref:: Q5_0 || t == ref:: Q8_0 ? "_16_64_32_2" : "_16_64_16_2" ; 2880} 2881} // namespace 2882 2883struct Window::PromptGemm { 2884int MT = 0 , QS = 256 , TM = 16 , maxrows = 0 , nblk_max = 0 ; 2885int lib = -1 , lgdn = -1 , lqsa = -1 ; 2886bool k4 = false, gu_v3 = false, dn_v3 = false, flash = false; 2887mtl::Buffer R , bo , inj [ 2 ], xnh , V , loh , mixed , mixh , qkv , z , al , be , ygh , gqn , gkn , gvc , ggb , gkq , go , yg , qfull , kcur , vcur , 2888iqr , ikr , qcur , qcurh , qidx , scores , qids , part , XQ , xqh , logits , ids , wts , bcnt , boff , eoff , tiles , meta , stok , sw , pos , 2889XS , HS , YE , yr , gsh , ush , hh , ys , sgv , emb , embh , pkey , pval , keyn , qn , gated , normW ; 2890mtl::Buffer WD , WU , Wqkv , Wz , Wal , Wbe , Wout , Wq , Wk , Wv , Wiq , Wik , Wr , Wsg , Wshg , Wshu , Wshd , Wpk , Wpv ; 2891mtl::Buffer mixr ; // Gyro: the rotated gate/up input rows [MT][N] 2892}; 2893 2894int Window:: prompt_chunk_rows () const { return pg_ ? pg_ -> MT : 0 ; } 2895 2896bool Window:: prompt_gemm_on (int64_t n ) const { 2897static const bool on = [] { 2898const char * e = std:: getenv ( "STRATA_METAL_PROMPT_GEMM" ); 2899return e ? std:: string ( e ) != "0" : true; 2900}(); 2901static const int64_t mn = [] { 2902const char * e = std:: getenv ( "STRATA_METAL_PROMPT_GEMM_MIN" ); 2903return e ? (int64_t) std:: atoll ( e ) : (int64_t) 64 ; 2904}(); 2905return on && n >= mn && pg_ != nullptr ; 2906} 2907 2908bool Window:: prompt_gemm_init (std::string & err ) { 2909if ( pg_ ) return true; 2910if ( stream_ && ! st_ -> ready ()) return stream_arena ( err ); // it makes the prompt buffers after the arena 2911const char * ec = std:: getenv ( "STRATA_METAL_PROMPT_CHUNK" ); 2912// Streaming: every chunk makes one pass over the layer's experts that are not in the arena, so a longer chunk 2913// streams each expert fewer times. M5 Max, UD-Q5, warm: 1024 -> 700 tok/s at 4K, 2048 -> 920, 4096 -> 1,100 (32K the 2914// same). The longer chunk's buffers (4.3 GB) come out of the arena only while a prompt runs, so it is the default on a 2915// big Mac; a small one keeps 1024 (the buffers would cost it cache). 2916uint64_t phys = 0 ; 2917size_t plen = sizeof phys ; 2918sysctlbyname ( "hw.memsize" , & phys , & plen , nullptr , 0 ); 2919const int stream_chunk = phys >= ( 96ull << 30 ) ? 4096 : 1024 ; 2920const int C = std:: max ( 64 , ec ? std:: atoi ( ec ) : ( stream_ ? stream_chunk : 2048 )) / 64 * 64 ; 2921auto pg = std:: make_unique < PromptGemm > (); 2922PromptGemm & p = * pg ; 2923p . MT = C ; 2924p . QS = std:: min ( C , 256 ); 2925{ 2926using namespace strata_metal ; 2927auto cc = [ & ]( const MslLib & L ) { return cx_ -> compile ( L . files , L . prelude ); }; 2928p . lib = cc ( lib_prompt ( kq_down_prelude ( f_ ))); 2929p . lgdn = cc ( lib_prompt_gdn ()); 2930p . lqsa = cc ( lib_prompt_qsa ()); 2931} 2932p . k4 = :: coop_k4 ( * cx_ ); 2933const char * eg = std:: getenv ( "STRATA_METAL_PROMPT_EXPERTS" ); // v2 | v3 (default: v3 with the M5's layout) 2934p . gu_v3 = p . dn_v3 = eg ? std:: string ( eg ) == "v3" : p . k4 ; 2935if ( T ( "blk.0.ffn_gate_exps.weight" ). type >= 144 ) p . gu_v3 = p . dn_v3 = false; // the trellis experts have the v2 kernels only 2936const char * eq = std:: getenv ( "STRATA_METAL_PROMPT_QSA" ); // v1 | flash (default: flash with the M5's layout) 2937p . flash = eq ? std:: string ( eq ) == "flash" : p . k4 ; 2938const size_t MT = (size_t) C ; 2939p . maxrows = C * TOPK + nexp_ * p . TM ; 2940p . nblk_max = ( C * TOPK + 1023 ) / 1024 ; 2941const int MB = (int) max_cells_ / 4 + 2 ; 2942// the buffers: measured first, then placed - on a streaming Mac inside the expert arena (a region of its slots 2943// reserved only while a prompt runs: the prompt's scratch costs no decode memory), else allocated 2944uint64_t need = 0 ; 2945uint8_t * region = nullptr ; 2946bool measure = true; 2947auto AB = [ & ](size_t bytes ) -> mtl::Buffer { 2948const size_t b = ( bytes + 16383 ) / 16384 * 16384 ; 2949if ( measure ) { need += b ; return mtl::Buffer{}; } 2950if ( region == nullptr ) return cx_ -> alloc ( bytes ); 2951mtl::Buffer r = cx_ -> wrap ( region , b ); 2952region += b ; 2953return r ; 2954}; 2955auto F32 = [ & ](size_t n ) { return AB ( 4 * n ); }; 2956auto F16 = [ & ](size_t n ) { return AB ( 2 * n ); }; 2957auto make = [ & ] { 2958const size_t mr = (size_t) p . maxrows ; 2959p . R = F32 ( MT * HC * N ); p . bo = F32 ( MT * N ); p . inj [ 0 ] = F32 ( MT * HC ); p . inj [ 1 ] = F32 ( MT * HC ); p . xnh = F16 ( MT * HC * N ); 2960p . V = F32 ( MT * ( LR + HC )); p . loh = F16 ( MT * LR ); p . mixed = F32 ( MT * N ); p . mixh = F16 ( MT * N ); 2961p . qkv = F32 ( MT * G_CONV ); p . z = F32 ( MT * G_ZV ); p . al = F32 ( MT * G_HV ); p . be = F32 ( MT * G_HV ); p . yg = F32 ( MT * G_ZV ); 2962p . ygh = F16 ( MT * G_ZV ); p . gqn = F32 ( MT * G_HK * G_SS ); p . gkn = F32 ( MT * G_HK * G_SS ); p . gvc = F32 ( MT * G_ZV ); 2963p . ggb = F32 ( MT * G_HV * 2 ); p . gkq = F32 ( MT * G_HK ); p . go = F32 ( MT * G_ZV ); 2964p . qfull = F32 ( MT * G_QFULL ); p . kcur = F32 ( MT * G_KV ); p . vcur = F32 ( MT * G_KV ); p . iqr = F32 ( MT * G_IQR ); p . ikr = F32 ( MT * G_ID ); 2965p . qcur = F32 ( MT * G_QOUT ); p . qcurh = F16 ( MT * G_QOUT ); p . qidx = F32 ( MT * G_IH * G_ID ); p . scores = F32 ( MT * (size_t) MB ); 2966p . qids = AB ( 4 * MT * G_BUD ); 2967p . part = p . flash ? F32 ( 16 ) : F32 ((size_t) p . QS * G_QCHUNKS * G_QH * ( G_QD + 2 )); 2968p . XQ = F32 ( 4 * MT * G_QOUT + 3 * (size_t) p . QS * G_QOUT + MT * G_QOUT / 16 ); p . xqh = F16 ( MT * G_QOUT ); 2969p . logits = F32 ( MT * nexp_ ); p . ids = AB ( 4 * MT * TOPK ); p . wts = F32 ( MT * TOPK ); 2970p . bcnt = AB ( 4 * (size_t) p . nblk_max * nexp_ ); p . boff = AB ( 4 * (size_t) p . nblk_max * nexp_ ); 2971p . eoff = AB ( 4 * nexp_ ); p . tiles = AB ( 8 * ( mr / p . TM + 1 )); p . meta = AB ( 64 ); 2972p . stok = AB ( 4 * mr ); p . sw = F32 ( mr ); p . pos = AB ( 4 * MT * TOPK ); p . XS = F16 ( mr * N ); p . HS = F16 ( mr * NFF ); 2973p . YE = F32 ( mr * N ); p . yr = F32 ( MT * N ); p . gsh = F32 ( MT * NFF ); p . ush = F32 ( MT * NFF ); p . hh = F16 ( MT * NFF ); 2974p . ys = F32 ( MT * N ); p . sgv = F32 ( MT ); 2975if ( had_on_ ) p . mixr = F32 ( MT * N ); 2976p . WD = F16 ((size_t) ( LR + HC ) * HC * N ); p . WU = F16 ((size_t) HC * N * LR ); p . Wqkv = F16 ((size_t) G_CONV * N ); 2977p . Wz = F16 ((size_t) G_ZV * N ); p . Wal = F16 ((size_t) G_HV * N ); p . Wbe = F16 ((size_t) G_HV * N ); p . Wout = F16 ((size_t) N * G_QOUT ); 2978p . Wq = F16 ((size_t) G_QFULL * N ); p . Wk = F16 ((size_t) G_KV * N ); p . Wv = F16 ((size_t) G_KV * N ); p . Wiq = F16 ((size_t) G_IQR * N ); 2979p . Wik = F16 ((size_t) G_ID * N ); p . Wr = F16 ((size_t) nexp_ * N ); p . Wsg = F16 ((size_t) N ); p . Wshg = F16 ((size_t) NFF * N ); 2980p . Wshu = F16 ((size_t) NFF * N ); p . Wshd = F16 ((size_t) N * NFF ); 2981if ( ple_on_ ) { 2982p . emb = F32 ( MT * N ); p . embh = F16 ( MT * N ); p . pkey = F32 ( MT * G_HCD ); p . pval = F32 ( MT * N ); p . keyn = F32 ( MT * G_HCD ); 2983p . qn = F32 ( MT * G_HCD ); p . gated = F32 ( MT * G_HCD ); p . normW = F32 ( MT * G_HCD ); 2984p . Wpk = F16 ((size_t) G_HCD * N ); p . Wpv = F16 ((size_t) N * N ); 2985} 2986}; 2987make (); 2988measure = false; 2989if ( stream_ ) { 2990region = st_ -> region ( need ); 2991if ( region == nullptr ) { err = "metal prompt: no arena region for the prompt buffers" ; return false; } 2992} 2993make (); 2994pg_ = pg . release (); 2995std:: fprintf ( stderr , "strata metal: prompts on the matrix units in chunks of %d (experts %s, QSA %s, matmul2d layout %s; " 2996"%.2f GB of buffers%s)\n" , C , p . gu_v3 ? "v3" : "v2" , p . flash ? "flash" : "v1" , p . k4 ? "K4" : "other" , 2997need / 1e9 , stream_ ? ", in the expert arena while a prompt runs" : "" ); 2998(void) err ; 2999return true; 3000} 3001 3002bool Window:: prompt_chunk ( const int32_t * tokens , int Tn , int64_t pos0 , std::string & err ) { 3003PromptGemm & p = * pg_ ; 3004p . meta . as < uint32_t > ()[ 2 ] = p . gu_v3 ? NFF / ( 32 * 4 ) : NFF / 64 ; 3005p . meta . as < uint32_t > ()[ 5 ] = p . dn_v3 ? N / ( 64 * 2 ) : N / 64 ; 3006auto TN = [ this ]( const std::string & n ) -> const gguf::Tensor & { return this -> T ( n ); }; 3007if ( Tn < 1 || Tn > p . MT ) { err = "metal prompt: chunk size out of range" ; return false; } 3008if ( pos0 + Tn + 1 >= max_cells_ ) { err = "metal prompt: the chunk runs past the context" ; return false; } 3009if ( stream_ && ! st_ -> ready () && ! stream_arena ( err )) return false; 3010if ( pend_fold_ > 0 ) { // the last decode window's commit, still pending 3011std::vector < mtl::Dispatch > fd ; 3012nb_ = false; 3013fold ( fd , pend_fold_ , 1 - hp_ ); 3014cx_ -> run_graph ( fd ); 3015pend_fold_ = 0 ; 3016} 3017const int T = Tn ; 3018// ---- the embeddings into every stream, the PLE rows 3019{ 3020const gguf::Tensor & te = TN ( "token_embd.weight" ); 3021const size_t rb = ref:: row_bytes ( te . type , N ); 3022mrope_sync ( pos0 , T ); 3023for (int t = 0 ; t < T ; ++ t ) { 3024float * r = p . R . as < float > () + (size_t) t * HC * N ; 3025if ( const float * img = img_row ( pos0 + t )) std:: memcpy ( r , img , (size_t) N * 4 ); 3026else ref:: dequant ( te . type , ( const uint8_t * ) W_ . ptr + te . offset + (size_t) tokens [ t ] * rb , r , N ); 3027for (int c = 1 ; c < HC ; ++ c ) std:: memcpy ( r + (size_t) c * N , r , (size_t) N * 4 ); 3028} 3029} 3030strata::core::SessionState & ss = * ss_ ; 3031if ( ple_on_ ) { 3032std::vector < uint32_t > rows ((size_t) T * strata::kernels:: PLE_N_HEADS ); 3033int32_t prev [ 2 ] = { ss . ple_prev [ 0 ], ss . ple_prev [ 1 ]}; 3034for (int t = 0 ; t < T ; ++ t ) { 3035strata::kernels:: ngram_rows ( & tokens [ t ], prev , 1 , ss . ple . consts , rows . data () + (size_t) t * strata::kernels:: PLE_N_HEADS ); 3036prev [ 0 ] = prev [ 1 ]; 3037prev [ 1 ] = tokens [ t ]; 3038} 3039if (! ss . ple . table -> gather_batch ( rows . data (), (size_t) T , p . emb . as < float > (), err )) return false; 3040} 3041std::vector < mtl::Dispatch > ds ; 3042std::vector < int > cuts ; 3043nb_ = false; 3044auto D = [ & ]( const mtl::Pipeline * pp , std::vector < mtl::Arg > a , uint32_t gx , uint32_t gy , uint32_t tg , uint32_t gz = 1 ) { 3045mtl::Dispatch d ; 3046d . p = pp ; 3047d . args = std:: move ( a ); 3048d . grid [ 0 ] = gx ; d . grid [ 1 ] = gy ; d . grid [ 2 ] = gz ; 3049d . tg [ 0 ] = tg ; 3050push ( ds , d ); 3051}; 3052auto PP = [ & ](int lib , const std::string & fn , const mtl::Constants & c = {}, const std::string & key = "" ) { 3053return P ( lib , fn , c , "pg:" + ( key . empty () ? fn : key )); 3054}; 3055auto gemm = [ & ]( const mtl::Buffer & A , const mtl::Buffer & B , const mtl::Buffer & Y , int M , int Nn , int K ) { 3056const int tm = 64 , tn = Nn <= 64 ? 32 : 64 ; 3057const std::string fn = "gemm_f16_" + std:: to_string ( tm ) + "_" + std:: to_string ( tn ) + "_4" ; 3058PgGemm g { M , Nn , K , 0 }; 3059D ( PP ( p . lib , fn ), {mtl::Arg:: B ( A ), mtl::Arg:: B ( B ), mtl::Arg:: B ( Y ), mtl::Arg:: V ( g )}, ( Nn + tn - 1 ) / tn , ( M + tm - 1 ) / tm , 128 ); 3060}; 3061auto dqb = [ & ]( const mtl::Buffer & src , size_t off , int type , int n_in , int n_out , const mtl::Buffer & out , size_t out_off = 0 , 3062uint32_t perm = 0 ) { 3063PgDq a {(uint32_t) n_in , (uint32_t) n_out , (uint32_t) ref:: row_bytes ( type , n_in ), perm }; 3064D ( PP ( p . lib , "dq_f16_" + std:: to_string ( type )), {mtl::Arg:: B ( src , off ), mtl::Arg:: B ( out , out_off ), mtl::Arg:: V ( a )}, 3065( n_in / pg_unit ( type ) + 63 ) / 64 , n_out , 64 ); 3066}; 3067auto dq = [ & ]( const gguf::Tensor & t , const mtl::Buffer & out , size_t out_off = 0 , uint32_t perm = 0 ) { 3068const int n_in = (int) t . shape [ 0 ], n_out = t . shape . size () > 1 ? (int) t . shape [ 1 ] : 1 ; 3069if ( hc_q8_ && q8off_ . count ( t . name )) dqb ( Q8_ , q8off_ . at ( t . name ), ref:: Q8_0 , n_in , n_out , out , out_off , perm ); 3070else dqb ( W_ , t . offset , t . type , n_in , n_out , out , out_off , perm ); 3071}; 3072auto act16 = [ & ]( const mtl::Buffer & x , const mtl::Buffer & xh , size_t n ) { 3073const uint32_t nn = (uint32_t) n ; 3074D ( PP ( p . lib , "act_f16" ), {mtl::Arg:: B ( x ), mtl::Arg:: B ( xh ), mtl::Arg:: V ( nn )}, ( nn + 255 ) / 256 , 1 , 256 ); 3075}; 3076int ci = 0 ; 3077auto hc_read = [ & ]( const std::string & pre , bool apply ) { 3078const gguf::Tensor & tn = TN ( pre + "_norm.weight" ), & tdn = TN ( pre + "_down.weight" ), & tin = TN ( pre + "_inject.weight" ), 3079& tup = TN ( pre + "_up.weight" ); 3080dq ( tdn , p . WD ); 3081dq ( tin , p . WD , (size_t) 2 * LR * HC * N ); 3082dq ( tup , p . WU , 0 , HC ); 3083GrArgs a { N , HC , LR , (uint32_t) T , apply ? 1u : 0u , eps_ }; 3084PgEpi ea {(uint32_t) T , N , HC , LR }; 3085D ( PP ( p . lib , "gr_norm_h" ), {mtl::Arg:: B ( p . R ), mtl::Arg:: B ( p . bo ), mtl::Arg:: B ( p . inj [ ci ]), mtl::Arg:: B ( W_ , tn . offset ), 3086mtl::Arg:: B ( p . xnh ), mtl::Arg:: V ( a )}, HC , T , 256 ); 3087gemm ( p . xnh , p . WD , p . V , T , LR + HC , HC * N ); 3088D ( PP ( p . lib , "gr_epi_down" ), {mtl::Arg:: B ( p . V ), mtl::Arg:: B ( p . loh ), mtl::Arg:: B ( p . inj [ 1 - ci ]), mtl::Arg:: V ( ea )}, 3089( T * ( LR + HC ) + 255 ) / 256 , 1 , 256 ); 3090PgGemm g { T , HC * N , LR , 0 }; 3091D ( PP ( p . lib , "gemm_hc_up_64_64_4" ), {mtl::Arg:: B ( p . loh ), mtl::Arg:: B ( p . WU ), mtl::Arg:: B ( p . xnh ), mtl::Arg:: B ( p . mixed ), 3092mtl::Arg:: B ( p . mixh ), mtl::Arg:: V ( g ), mtl::Arg:: V ( ea )}, HC * N / 64 , ( T + 63 ) / 64 , 128 ); 3093ci = 1 - ci ; 3094}; 3095// the PLE projections (the window's gemv pair as GEMMs) 3096if ( ple_on_ ) { 3097act16 ( p . emb , p . embh , (size_t) T * N ); 3098dq ( TN ( "blk.1.ple_key.weight" ), p . Wpk ); 3099dq ( TN ( "blk.1.ple_value.weight" ), p . Wpv ); 3100gemm ( p . embh , p . Wpk , p . pkey , T , G_HCD , N ); 3101gemm ( p . embh , p . Wpv , p . pval , T , N , N ); 3102} 3103const int MB = (int) max_cells_ / 4 + 2 ; 3104(void) MB ; 3105for (int l = 0 ; l < G_NL ; ++ l ) { 3106const std::string b = "blk." + std:: to_string ( l ) + "." ; 3107hc_read ( b + "hc_attn" , l > 0 && !( l == 1 && ple_on_ )); 3108if ( l % 4 != 3 ) { 3109const int gi = l - l / 4 ; 3110dq ( TN ( b + "attn_qkv.weight" ), p . Wqkv ); 3111dq ( TN ( b + "attn_gate.weight" ), p . Wz ); 3112dq ( TN ( b + "ssm_alpha.weight" ), p . Wal ); 3113dq ( TN ( b + "ssm_beta.weight" ), p . Wbe ); 3114dq ( TN ( b + "ssm_out.weight" ), p . Wout ); 3115gemm ( p . mixh , p . Wqkv , p . qkv , T , G_CONV , N ); 3116gemm ( p . mixh , p . Wz , p . z , T , G_ZV , N ); 3117gemm ( p . mixh , p . Wal , p . al , T , G_HV , N ); 3118gemm ( p . mixh , p . Wbe , p . be , T , G_HV , N ); 3119PgGdnP ga {(uint32_t) T , G_HK , G_HV , G_CONV , eps_ , 0 }; 3120D ( PP ( p . lgdn , "gdn_pre" ), 3121{mtl::Arg:: B ( p . qkv ), mtl::Arg:: B ( ghist_ [ hp_ ][(size_t) gi ]), mtl::Arg:: B ( W_ , TN ( b + "ssm_conv1d.weight" ). offset ), 3122mtl::Arg:: B ( p . al ), mtl::Arg:: B ( p . be ), mtl::Arg:: B ( W_ , TN ( b + "ssm_dt.bias" ). offset ), mtl::Arg:: B ( W_ , TN ( b + "ssm_a" ). offset ), 3123mtl::Arg:: B ( p . gqn ), mtl::Arg:: B ( p . gkn ), mtl::Arg:: B ( p . gvc ), mtl::Arg:: B ( p . ggb ), mtl::Arg:: B ( p . gkq ), 3124mtl::Arg:: B ( ghist_ [ 1 - hp_ ][(size_t) gi ]), mtl::Arg:: V ( ga )}, G_HK + G_HV / 2 , T , 256 ); 3125D ( PP ( p . lgdn , gdn_scan_name ( cx_ -> device_name (), T ), mtl:: Constants (). i ( 6 , 0 ), gdn_scan_name ( cx_ -> device_name (), T )), 3126{mtl::Arg:: B ( gst_ [(size_t) gi ]), mtl::Arg:: B ( p . gqn ), mtl::Arg:: B ( p . gkn ), mtl::Arg:: B ( p . gvc ), mtl::Arg:: B ( p . ggb ), 3127mtl::Arg:: B ( p . gkq ), mtl::Arg:: B ( p . go ), mtl::Arg:: V ( ga )}, G_HV * 4 , 1 , 32 * 4 ); 3128D ( PP ( p . lgdn , "gdn_post" ), {mtl::Arg:: B ( p . go ), mtl::Arg:: B ( p . z ), mtl::Arg:: B ( W_ , TN ( b + "ssm_norm.weight" ). offset ), 3129mtl::Arg:: B ( p . ygh ), mtl::Arg:: B ( p . yg ), mtl::Arg:: V ( ga )}, G_HV , T , 128 ); 3130gemm ( p . ygh , p . Wout , p . bo , T , N , G_ZV ); 3131} else { 3132const int qi = l / 4 ; 3133dq ( TN ( b + "attn_q.weight" ), p . Wq ); 3134dq ( TN ( b + "attn_k.weight" ), p . Wk ); 3135dq ( TN ( b + "attn_v.weight" ), p . Wv ); 3136dq ( TN ( b + "indexer.q_proj.weight" ), p . Wiq ); 3137dq ( TN ( b + "indexer.k_proj.weight" ), p . Wik ); 3138dq ( TN ( b + "attn_output.weight" ), p . Wout ); 3139gemm ( p . mixh , p . Wq , p . qfull , T , G_QFULL , N ); 3140gemm ( p . mixh , p . Wk , p . kcur , T , 512 , N ); 3141gemm ( p . mixh , p . Wv , p . vcur , T , 512 , N ); 3142gemm ( p . mixh , p . Wiq , p . iqr , T , 512 , N ); 3143gemm ( p . mixh , p . Wik , p . ikr , T , 128 , N ); 3144QsaArgs a {(uint32_t) pos0 , 0 , (uint32_t) max_cells_ , (uint32_t) T , eps_ }; 3145D ( PP ( p . lqsa , "qsa_prep" , qsa_c (), qsa_k ()), 3146{mtl::Arg:: B ( p . qfull ), mtl::Arg:: B ( p . kcur ), mtl::Arg:: B ( p . vcur ), mtl::Arg:: B ( p . iqr ), mtl::Arg:: B ( p . ikr ), 3147mtl::Arg:: B ( W_ , TN ( b + "attn_q_norm.weight" ). offset ), mtl::Arg:: B ( W_ , TN ( b + "attn_k_norm.weight" ). offset ), 3148mtl::Arg:: B ( W_ , TN ( b + "indexer.q_norm.weight" ). offset ), mtl::Arg:: B ( W_ , TN ( b + "indexer.k_norm.weight" ). offset ), 3149mtl::Arg:: B ( cs_ ), mtl::Arg:: B ( p . qcur ), mtl::Arg:: B ( p . qidx ), mtl::Arg:: B ( kq_ [(size_t) qi ]), mtl::Arg:: B ( vq_ [(size_t) qi ]), 3150mtl::Arg:: B ( ksc_ [(size_t) qi ]), mtl::Arg:: B ( vsc_ [(size_t) qi ]), mtl::Arg:: B ( tail_ [(size_t) qi ]), 3151mtl::Arg:: B ( dead_ [(size_t) qi ]), mtl::Arg:: B ( pooled_ [(size_t) qi ]), mtl::Arg:: V ( a ), mtl::Arg:: B ( mrope_ )}, G_QPREP , T , 256 ); 3152if ( pos0 + T > G_BUD ) 3153D ( PP ( p . lqsa , "qsa_score_mm" ), {mtl::Arg:: B ( p . qidx ), mtl::Arg:: B ( pooled_ [(size_t) qi ]), mtl::Arg:: B ( dead_ [(size_t) qi ]), 3154mtl::Arg:: B ( p . scores ), mtl::Arg:: V ( a )}, 3155(uint32_t) ((( pos0 + T ) / 4 + 1 + 63 ) / 64 ), ( T + 15 ) / 16 , 128 ); 3156D ( PP ( p . lqsa , "qsa_topk" ), {mtl::Arg:: B ( p . scores ), mtl::Arg:: B ( p . qids ), mtl::Arg:: V ( a )}, T , 1 , 1024 ); 3157if ( p . flash ) { 3158const uint32_t nq = (uint32_t) T * G_QOUT ; 3159D ( PP ( p . lqsa , "qsa_q_f16" ), {mtl::Arg:: B ( p . qcur ), mtl::Arg:: B ( p . qcurh ), mtl::Arg:: V ( nq )}, ( nq + 255 ) / 256 , 1 , 256 ); 3160D ( PP ( p . lqsa , "qsa_flash" , mtl:: Constants (). b ( 7 , p . k4 ), "qsa_flash" ), 3161{mtl::Arg:: B ( p . qcurh ), mtl::Arg:: B ( kq_ [(size_t) qi ]), mtl::Arg:: B ( vq_ [(size_t) qi ]), mtl::Arg:: B ( ksc_ [(size_t) qi ]), 3162mtl::Arg:: B ( vsc_ [(size_t) qi ]), mtl::Arg:: B ( p . qids ), mtl::Arg:: B ( p . qfull ), mtl::Arg:: B ( p . xqh ), mtl::Arg:: V ( a )}, 31632 , T , 128 ); 3164} else { 3165// v1 attention + merge in slices of QS rows (the partials of a slice only) 3166for (int t0 = 0 ; t0 < T ; t0 += p . QS ) { 3167const int ns = std:: min ( p . QS , T - t0 ); 3168QsaArgs as {(uint32_t) ( pos0 + t0 ), 0 , (uint32_t) max_cells_ , (uint32_t) ns , eps_ }; 3169D ( PP ( p . lqsa , "qsa_attn" ), {mtl::Arg:: B ( p . qcur , (size_t) t0 * G_QOUT * 4 ), mtl::Arg:: B ( kq_ [(size_t) qi ]), 3170mtl::Arg:: B ( vq_ [(size_t) qi ]), mtl::Arg:: B ( ksc_ [(size_t) qi ]), mtl::Arg:: B ( vsc_ [(size_t) qi ]), 3171mtl::Arg:: B ( p . qids , (size_t) t0 * G_BUD * 4 ), mtl::Arg:: B ( p . part ), mtl::Arg:: V ( as )}, 3172G_QCHUNKS , G_QKV , 256 , (uint32_t) ns ); 3173D ( PP ( p . lqsa , "qsa_merge" ), {mtl::Arg:: B ( p . part ), mtl::Arg:: B ( p . qfull , (size_t) t0 * G_QFULL * 4 ), 3174mtl::Arg:: B ( p . XQ , (size_t) t0 * G_QOUT * 4 ), mtl::Arg:: V ( as )}, G_QH , ns , 256 ); 3175} 3176act16 ( p . XQ , p . xqh , (size_t) T * G_QOUT ); 3177} 3178gemm ( p . xqh , p . Wout , p . bo , T , N , G_QOUT ); 3179} 3180if ( l == 0 && ple_on_ ) { 3181// layer 0's attention write applied to R happens in the FFN read below; the PLE block comes after the FFN 3182} 3183// ---- the MoE 3184hc_read ( b + "hc_ffn" , true); 3185const gguf::Tensor & tr = TN ( b + "ffn_gate_inp.weight" ), & tsg = TN ( b + "ffn_gate_inp_shexp.weight" ), 3186& tg_ = TN ( b + "ffn_gate_shexp.weight" ), & tu_ = TN ( b + "ffn_up_shexp.weight" ), 3187& td_ = TN ( b + "ffn_down_shexp.weight" ), & eg = TN ( b + "ffn_gate_exps.weight" ), 3188& ed = TN ( b + "ffn_down_exps.weight" ); 3189dq ( tr , p . Wr ); 3190dq ( tsg , p . Wsg ); 3191dq ( tg_ , p . Wshg ); 3192dq ( tu_ , p . Wshu ); 3193dq ( td_ , p . Wshd ); 3194gemm ( p . mixh , p . Wr , p . logits , T , nexp_ , N ); 3195const uint32_t nt = (uint32_t) T ; 3196D ( PP ( p . lib , "route_topk" ), {mtl::Arg:: B ( p . logits ), mtl::Arg:: B ( p . ids ), mtl::Arg:: B ( p . wts ), mtl::Arg:: V ( nt ), mtl::Arg:: V ((uint32_t) nexp_ )}, ( T + 7 ) / 8 , 1 , 256 ); 3197const int nent = T * TOPK , nblk = ( nent + 1023 ) / 1024 ; 3198PgPlan pa {(uint32_t) nent , TOPK , (uint32_t) nexp_ , (uint32_t) p . TM , (uint32_t) nblk }; 3199const uint32_t nclr = (uint32_t) p . maxrows ; 3200D ( PP ( p . lib , "mm_clear" ), {mtl::Arg:: B ( p . stok ), mtl::Arg:: V ( nclr )}, ( p . maxrows + 255 ) / 256 , 1 , 256 ); 3201D ( PP ( p . lib , "mm_hist" ), {mtl::Arg:: B ( p . ids ), mtl::Arg:: B ( p . bcnt ), mtl::Arg:: V ( pa )}, nblk , 1 , 1024 ); 3202D ( PP ( p . lib , "mm_scan" ), {mtl::Arg:: B ( p . bcnt ), mtl::Arg:: B ( p . boff ), mtl::Arg:: B ( p . eoff ), mtl::Arg:: B ( p . tiles ), 3203mtl::Arg:: B ( p . meta ), mtl::Arg:: V ( pa )}, 1 , 1 , nexp_ ); 3204D ( PP ( p . lib , "mm_place" ), {mtl::Arg:: B ( p . ids ), mtl::Arg:: B ( p . wts ), mtl::Arg:: B ( p . boff ), mtl::Arg:: B ( p . eoff ), 3205mtl::Arg:: B ( p . stok ), mtl::Arg:: B ( p . sw ), mtl::Arg:: B ( p . pos ), mtl::Arg:: V ( pa )}, nblk , 1 , 1024 ); 3206PgMm ma { eg . offset , TN ( b + "ffn_up_exps.weight" ). offset , ed . offset , 0 , 0 , (uint32_t) ref:: row_bytes ( eg . type , N ), 3207(uint32_t) ref:: row_bytes ( ed . type , NFF ), N , NFF }; 3208ma . gu_stride = (uint64_t) ma . gu_row * NFF ; 3209ma . d_stride = (uint64_t) ma . d_row * N ; 3210if ( stream_ ) { ma . gate_off = 0 ; ma . up_off = st_ -> up_in_slot ( l ); ma . down_off = st_ -> down_in_slot ( l ); } 3211const size_t ebase = moe_rebase ( ma . gate_off , ma . up_off , ma . down_off ); 3212const uint32_t ne_ = N ; 3213const bool hg = had_gu ( l ), hd = had_dn ( l ); 3214if ( hg ) had_rows ( ds , p . lib , "pg:" , p . mixed , 0 , p . mixr , 0 , T , N , hsx_ . handle ? & hsx_ : nullptr , false); 3215{ 3216mtl::Dispatch g ; 3217g . p = PP ( p . lib , "mm_gather" ); 3218g . args = {mtl::Arg:: B ( hg ? p . mixr : p . mixed ), mtl::Arg:: B ( p . stok ), mtl::Arg:: B ( p . XS ), mtl::Arg:: V ( ne_ )}; 3219g . tg [ 0 ] = 256 ; 3220g . indirect = & p . meta ; 3221g . ind_off = 8 * 4 ; 3222push ( ds , g ); 3223} 3224const mtl::Buffer & EW = stream_ ? st_ -> chunk ( 0 ) : W_ ; 3225auto arena_args = [ & ](mtl::Dispatch & d ) { 3226if (! stream_ ) return ; 3227d . args . push_back (mtl::Arg:: B ( st_ -> smap (), (size_t) l * 512 * 4 )); 3228for (int c = 1 ; c < 4 ; ++ c ) d . args . push_back (mtl::Arg:: B ( st_ -> chunk ( c ))); 3229}; 3230const std::string ak = stream_ ? "#arena" : "" ; 3231mtl::Dispatch gu ; 3232if ( p . gu_v3 ) { 3233const std::string fn = "mm_gu3_" + std:: to_string ( eg . type ) + "_16_32_32_4" ; 3234mtl::Constants c = mtl:: Constants (). b ( 7 , p . k4 ); 3235if ( stream_ ) c . b ( 20 , true); 3236gu . p = PP ( p . lib , fn , c , fn + ak ); 3237gu . tg [ 0 ] = 32 * 4 ; 3238} else { 3239const std::string fn = "mm_gu2_" + std:: to_string ( eg . type ) + gu2_tile ( eg . type ); 3240mtl::Constants c = mtl:: Constants (). i ( 5 , 0 ); 3241if ( stream_ ) c . b ( 20 , true); 3242gu . p = PP ( p . lib , fn , c , fn + ak ); 3243gu . tg [ 0 ] = 64 ; 3244} 3245gu . args = {mtl::Arg:: B ( EW , ebase ), mtl::Arg:: B ( p . XS ), mtl::Arg:: B ( p . HS ), mtl::Arg:: B ( p . tiles ), mtl::Arg:: V ( ma )}; 3246arena_args ( gu ); 3247gu . indirect = & p . meta ; 3248gu . ind_off = 2 * 4 ; 3249if ( stream_ ) cuts . push_back ((int) ds . size ()); // the host's turn: this layer's experts put in place 3250push ( ds , gu ); 3251if ( hd ) had_rows_ind ( ds , p . lib , "pg:" , p . HS , p . meta ); 3252mtl::Dispatch dn ; 3253if ( p . dn_v3 ) { 3254const std::string fn = "mm_down3_" + std:: to_string ( ed . type ) + "_16_64_32_2" ; 3255mtl::Constants c = mtl:: Constants (). b ( 7 , p . k4 ); 3256if ( stream_ ) c . b ( 20 , true); 3257dn . p = PP ( p . lib , fn , c , fn + ak ); 3258dn . tg [ 0 ] = 32 * 2 ; 3259} else { 3260const std::string fn = "mm_down2_" + std:: to_string ( ed . type ) + dn2_tile ( ed . type ); 3261mtl::Constants c ; 3262if ( stream_ ) c . b ( 20 , true); 3263dn . p = PP ( p . lib , fn , c , fn + ak ); 3264dn . tg [ 0 ] = 64 ; 3265} 3266dn . args = {mtl::Arg:: B ( EW , ebase ), mtl::Arg:: B ( p . HS ), mtl::Arg:: B ( p . YE ), mtl::Arg:: B ( p . tiles ), mtl::Arg:: V ( ma )}; 3267arena_args ( dn ); 3268dn . indirect = & p . meta ; 3269dn . ind_off = 5 * 4 ; 3270push ( ds , dn ); 3271const uint32_t ca [ 4 ] = {(uint32_t) T , N , TOPK , 0 }; 3272D ( PP ( p . lib , "mm_combine" ), {mtl::Arg:: B ( p . YE ), mtl::Arg:: B ( p . pos ), mtl::Arg:: B ( p . sw ), mtl::Arg:: B ( p . yr ), mtl::Arg:: V ( ca )}, 3273( T * N + 255 ) / 256 , 1 , 256 ); 3274gemm ( p . mixh , p . Wshg , p . gsh , T , NFF , N ); 3275gemm ( p . mixh , p . Wshu , p . ush , T , NFF , N ); 3276const uint32_t nh = (uint32_t) T * NFF ; 3277D ( PP ( p . lib , "swiglu_h" ), {mtl::Arg:: B ( p . gsh ), mtl::Arg:: B ( p . ush ), mtl::Arg:: B ( p . hh ), mtl::Arg:: V ( nh )}, ( nh + 255 ) / 256 , 1 , 256 ); 3278gemm ( p . hh , p . Wshd , p . ys , T , N , NFF ); 3279gemm ( p . mixh , p . Wsg , p . sgv , T , 1 , N ); 3280const uint32_t oa [ 2 ] = {(uint32_t) T , N }; 3281D ( PP ( p . lib , "moe_out" ), {mtl::Arg:: B ( p . yr ), mtl::Arg:: B ( p . ys ), mtl::Arg:: B ( p . sgv ), mtl::Arg:: B ( p . bo ), mtl::Arg:: V ( oa )}, 3282( T * N + 255 ) / 256 , 1 , 256 ); 3283if ( taps_on_ && tap_slot_ [ l ] >= 0 ) tap_dispatch ( ds , l , p . R , p . bo , p . inj [ ci ], tap_pro_buf (std:: max ( p . MT , T ) + MAXT ), T ); // DFlash2 3284if ( l == 0 && ple_on_ ) { 3285// layer 0's FFN write applied to R, then the PLE block (as the window, for T rows) 3286const gguf::Tensor & tn = TN ( "blk.1.hc_attn_norm.weight" ); 3287GrArgs a { N , HC , LR , (uint32_t) T , 1u , eps_ }; 3288D ( P ( lib_ , "gr_norm" , {}, "gr_norm" ), {mtl::Arg:: B ( p . R ), mtl::Arg:: B ( p . bo ), mtl::Arg:: B ( p . inj [ ci ]), mtl::Arg:: B ( W_ , tn . offset ), 3289mtl::Arg:: B ( p . YE ), mtl::Arg:: V ( a )}, HC , T , 256 ); 3290struct PleArgs { uint32_t n_embd , hc ; float eps ; } pl { N , HC , strata::kernels:: NG_RMS_EPS }; 3291auto off = [ & ]( const char * n ) { return TN ( n ). offset ; }; 3292D ( P ( lple_ , "ple_gnorm" , {}, "ple_gnorm" ), {mtl::Arg:: B ( p . pkey ), mtl::Arg:: B ( W_ , off ( "blk.1.ple_norm_key.weight" )), 3293mtl::Arg:: B ( p . keyn ), mtl::Arg:: V ( pl )}, HC , T , 256 ); 3294nb_ = true; 3295D ( P ( lple_ , "ple_gnorm" , {}, "ple_gnorm" ), {mtl::Arg:: B ( p . R ), mtl::Arg:: B ( W_ , off ( "blk.1.ple_norm_query.weight" )), 3296mtl::Arg:: B ( p . qn ), mtl::Arg:: V ( pl )}, HC , T , 256 ); 3297D ( P ( lple_ , "ple_gate_norm" , {}, "ple_gate_norm" ), 3298{mtl::Arg:: B ( p . keyn ), mtl::Arg:: B ( p . qn ), mtl::Arg:: B ( p . pval ), mtl::Arg:: B ( W_ , off ( "blk.1.ple_norm_conv.weight" )), 3299mtl::Arg:: B ( p . gated ), mtl::Arg:: B ( p . normW ), mtl::Arg:: V ( pl )}, HC , T , 256 ); 3300D ( P ( lple_ , "ple_conv_add" , {}, "ple_conv_add" ), 3301{mtl::Arg:: B ( pleHist_ ), mtl::Arg:: B ( p . normW ), kw_arg (), mtl::Arg:: B ( p . gated ), 3302mtl::Arg:: B ( p . R ), mtl::Arg:: V ( pl )}, HC * N / 256 , T , 256 ); 3303} 3304} 3305// the last layer's write applied to R (the draft layer's K/V read the final residual rows) 3306{ 3307const gguf::Tensor & tn = TN ( "output_hc_norm.weight" ); 3308GrArgs a { N , HC , LR , (uint32_t) T , 1u , eps_ }; 3309D ( P ( lib_ , "gr_norm" , {}, "gr_norm" ), {mtl::Arg:: B ( p . R ), mtl::Arg:: B ( p . bo ), mtl::Arg:: B ( p . inj [ ci ]), mtl::Arg:: B ( W_ , tn . offset ), 3310mtl::Arg:: B ( p . YE ), mtl::Arg:: V ( a )}, HC , T , 256 ); 3311} 3312const double t0 = now_ms (); 3313if ( stream_ ) { 3314seg_T_ = T ; 3315cut_ids_ = p . ids . as < int32_t > (); 3316cx_ -> run_graph_seg ( ds , cuts , [](void * u , int s ) { ((Window * ) u ) -> at_cut ( s ); }, this ); 3317cut_ids_ = nullptr ; 3318} else { 3319cx_ -> run_graph ( ds ); 3320} 3321pg_ms_ += now_ms () - t0 ; 3322pg_tok_ += T ; 3323static const bool trace = std:: getenv ( "STRATA_METAL_TRACE" ) != nullptr ; 3324if ( trace ) std:: fprintf ( stderr , "strata metal: prompt chunk pos %lld, %d rows: %.0f ms\n" , (long long) pos0 , T , now_ms () - t0 ); 3325// the window's state after the chunk: the conv history turned, the PLE history and token window advanced 3326hp_ = 1 - hp_ ; 3327if ( ple_on_ ) { 3328using namespace strata:: kernels ; 3329float * hist = pleHist_ . as < float > (); 3330const float * nw = p . normW . as < float > (); 3331for (int c = 0 ; c < NG_HC_DIM ; ++ c ) { 3332float col [ NG_HIST ]; 3333for (int r = 0 ; r < NG_HIST ; ++ r ) { 3334const int src = T - NG_HIST + r ; // row r of the new history: chunk row src, or the old history 3335col [ r ] = src >= 0 ? nw [(size_t) src * NG_HC_DIM + c ] : hist [(size_t) c * NG_HIST + (size_t) ( r + T )]; 3336} 3337std:: memcpy ( hist + (size_t) c * NG_HIST , col , sizeof col ); 3338} 3339} 3340if ( T >= 2 ) { ss . ple_prev [ 0 ] = tokens [ T - 2 ]; ss . ple_prev [ 1 ] = tokens [ T - 1 ]; } 3341else { ss . ple_prev [ 0 ] = ss . ple_prev [ 1 ]; ss . ple_prev [ 1 ] = tokens [ 0 ]; } 3342mtp_src_ = & p . R ; // the draft layer's prompt K/V read this chunk's final rows 3343if ( taps_on_ && ! tap_deliver ( tap_pro_ , T , pos0 , err )) return false; // DFlash2: the prompt rows the drafter looks at 3344return true; 3345} 3346 3347// ---- the request's sampling (sample.metal): the chain over the window's head rows, after run() has left the logits in lm_ 3348void Window:: set_sampling ( const strata::kernels::SamplerParams * sp , const int32_t * hist , int hist_len ) { 3349samp_on_ = sp != nullptr ; 3350if ( sp ) samp_ = * sp ; 3351samp_hist_ = hist ; 3352samp_hist_len_ = hist_len ; 3353} 3354 3355bool Window:: sample_rows (int Tn , int32_t * out , std::string & err ) { 3356if (! samp_on_ || Tn < 1 || Tn > MAXT ) return true; 3357if (! sample_run ( 0 , Tn , samp_ , samp_hist_ , samp_hist_len_ , err )) return false; 3358for (int t = 0 ; t < Tn ; ++ t ) out [ t ] = tokout_ . as < int32_t > ()[ t ]; 3359return true; 3360} 3361 3362bool Window:: sample_slot_row (int row , const strata::kernels::SamplerParams & sp , const int32_t * hist , int hist_len , int32_t * tok , std::string & err ) { 3363if ( row < 0 || row >= MAXT ) return true; 3364if (! sample_run ( row , 1 , sp , hist , hist_len , err )) return false; 3365* tok = tokout_ . as < int32_t > ()[ row ]; 3366return true; 3367} 3368 3369// the chain over logits rows [row0, row0 + n) of lm_, written to tokout_[row0 ..]; row r's draw is Philox(seed, counter + r - row0) 3370bool Window:: sample_run (int row0 , int n , const strata::kernels::SamplerParams & sp , const int32_t * hist_in , int hl , std::string & err ) { 3371const int Tn = n ; 3372const int64_t V = n_vocab_ ; 3373constexpr uint32_t PARTS = 64 ; 3374if ( V > (int64_t) PARTS * 4096 ) { err = "metal sampler: the vocabulary is wider than 64 parts of 4096" ; return false; } 3375if (! scv_ . handle ) { 3376scv_ = cx_ -> alloc ( 4 * (size_t) MAXT * PARTS * 64 ); 3377sci_ = cx_ -> alloc ( 4 * (size_t) MAXT * PARTS * 64 ); 3378} 3379const bool greedy = sp . greedy || sp . temperature <= 0.0f ; 3380uint32_t flags = greedy ? 2u : 0u ; 3381// the logit bias: a device array of n_vocab floats (unified memory: read as it is, copied into the sampler's own buffer) 3382if ( sp . logit_bias != nullptr ) { 3383if ( sbias_cap_ < 4 * (size_t) V ) { // (an earlier request without a bias left the 16-byte stand-in) 3384if ( sbias_ . handle ) cx_ -> free ( sbias_ ); 3385sbias_ = cx_ -> alloc ( 4 * (size_t) V ); 3386sbias_cap_ = 4 * (size_t) V ; 3387} 3388std:: memcpy ( sbias_ . ptr , strata::gpu:: host_view ( sp . logit_bias ), 4 * (size_t) V ); // (a cudaMalloc'd array: the runtime's CPU view) 3389flags |= 1u ; 3390} else if (! sbias_ . handle ) { 3391sbias_ = cx_ -> alloc ( 16 ); 3392sbias_cap_ = 16 ; 3393} 3394uint32_t pen_n = 0 ; 3395if ( hist_in != nullptr && hl > 0 && sp . penalty_last_n > 0 ) { 3396pen_n = (uint32_t) std:: min ( sp . penalty_last_n , hl ); 3397const size_t need = 4 * (size_t) MAXT * (size_t) hl ; 3398if ( shist_cap_ < need ) { if ( shist_ . handle ) cx_ -> free ( shist_ ); shist_ = cx_ -> alloc ( need ); shist_cap_ = need ; } 3399std:: memcpy ( shist_ . ptr , strata::gpu:: host_view ( hist_in ), 4 * (size_t) Tn * (size_t) hl ); 3400flags |= 4u ; 3401} else if (! shist_ . handle ) { 3402shist_ = cx_ -> alloc ( 16 ); shist_cap_ = 16 ; 3403} 3404struct SampArgs { 3405uint32_t n_vocab , parts , k , hist_len , pen_n , min_keep , flags ; 3406float top_p , min_p , inv_t , rep , freq , pres ; 3407uint32_t seed_lo , seed_hi , ctr_lo , ctr_hi ; 3408} a {}; 3409a . n_vocab = (uint32_t) V ; 3410a . parts = PARTS ; 3411a . k = greedy ? 1u : (uint32_t) (( sp . top_k > 0 && sp . top_k < 64 ) ? sp . top_k : 64 ); 3412a . hist_len = ( flags & 4u ) ? (uint32_t) hl : 0u ; 3413a . pen_n = pen_n ; 3414a . min_keep = (uint32_t) std:: max ( 1 , sp . min_keep ); 3415a . flags = flags ; 3416a . top_p = sp . top_p ; 3417a . min_p = sp . min_p ; 3418a . inv_t = greedy ? 1.0f : 1.0f / sp . temperature ; 3419a . rep = sp . penalty_repeat ; 3420a . freq = sp . penalty_freq ; 3421a . pres = sp . penalty_present ; 3422a . seed_lo = (uint32_t) sp . seed ; a . seed_hi = (uint32_t) ( sp . seed >> 32 ); 3423a . ctr_lo = (uint32_t) sp . counter ; a . ctr_hi = (uint32_t) ( sp . counter >> 32 ); 3424mtl::Dispatch d1 , d2 ; 3425d1 . p = P ( lsmp_ , "samp_part" , {}, "samp_part" ); 3426const size_t cand_off = 4 * (size_t) row0 * PARTS * 64 ; 3427d1 . args = {mtl::Arg:: B ( lm_ , 4 * (size_t) row0 * (size_t) V ), mtl::Arg:: B ( sbias_ ), mtl::Arg:: B ( shist_ ), mtl::Arg:: B ( scv_ , cand_off ), mtl::Arg:: B ( sci_ , cand_off ), mtl::Arg:: V ( a )}; 3428d1 . grid [ 0 ] = PARTS ; d1 . grid [ 1 ] = (uint32_t) Tn ; d1 . tg [ 0 ] = 256 ; 3429d2 . p = P ( lsmp_ , "samp_pick" , {}, "samp_pick" ); 3430d2 . args = {mtl::Arg:: B ( scv_ , cand_off ), mtl::Arg:: B ( sci_ , cand_off ), mtl::Arg:: B ( tokout_ , 4 * (size_t) row0 ), mtl::Arg:: V ( a )}; 3431d2 . grid [ 0 ] = (uint32_t) Tn ; d2 . tg [ 0 ] = 256 ; 3432const double t0 = now_ms (); 3433cx_ -> run_graph ({ d1 , d2 }); 3434++ samp_windows_ ; 3435static const bool st = std:: getenv ( "STRATA_METAL_SAMPLE_STATS" ) != nullptr ; 3436if ( st && samp_windows_ % 200 == 0 ) 3437std:: fprintf ( stderr , "strata metal: sampler %llu windows, last %d rows in %.2f ms\n" , (unsigned long long) samp_windows_ , Tn , now_ms () - t0 ); 3438return true; 3439} 3440 3441// ---------------------------------------------------------------------------------------------- the hook's entry points 3442namespace { 3443std::string g_shard1 ; 3444} 3445void window_register (void * w ); 3446bool mtp_load_pending (Window * w , std::string & err ); 3447void set_model_shard ( const char * shard1 ) { g_shard1 = shard1 ? shard1 : "" ; } 3448void set_batch_slots (int n ) { g_slot_cap = n > 0 ? std:: min ( n , 8 ) : 0 ; } 3449 3450// The draft vocabulary the build ships (data/draft_vocab.bin beside the build, else the compiled-in data folder): what a DFlash2-alone start without <mtp>/draft_vocab.bin 3451// uses (generate.cpp), and what Window::df2_bind falls back to. STRATA_METAL_DRAFT_VOCAB names another file, or "full" for the whole head. 3452std::string draft_vocab_default () { 3453const char * e = std:: getenv ( "STRATA_METAL_DRAFT_VOCAB" ); 3454if ( e != nullptr && e [ 0 ] != 0 && std:: string ( e ) != "full" ) return e ; 3455return strata_metal:: resource ( nullptr , "data" , STRATA_METAL_DATA_DEFAULT ) + "/draft_vocab.bin" ; 3456} 3457bool draft_vocab_whole_head () { 3458const char * e = std:: getenv ( "STRATA_METAL_DRAFT_VOCAB" ); 3459return e != nullptr && std:: string ( e ) == "full" ; 3460} 3461 3462// One decode window per process: the prompt path (Prefill::init) may bring it up before the Verifier does. 3463namespace { 3464Window * g_the_window = nullptr ; 3465} 3466void * window_create () { 3467if ( g_the_window == nullptr ) { 3468g_the_window = new Window(); 3469if (std:: getenv ( "STRATA_METAL_PROFILE" )) std:: atexit ([] { if ( g_the_window ) g_the_window -> print_prof (); }); 3470} 3471return g_the_window ; 3472} 3473void window_destroy (void * w ) { 3474if ( w != nullptr && w == g_the_window ) { 3475if ( g_stream_window == g_the_window ) { 3476g_the_window -> stream_report ( stderr ); 3477g_stream_window = nullptr ; 3478} 3479delete g_the_window ; 3480g_the_window = nullptr ; 3481window_register ( nullptr ); 3482} 3483} 3484bool window_init (void * w , const strata::core::ModelGeometry & g , strata::core::SessionState & ss , int max_t , int64_t max_cells , 3485int64_t * n_vocab , std::string & err ) { 3486Window * x = (Window * ) w ; 3487if (! x -> ready ()) { 3488if ( g_shard1 . empty ()) { err = "metal window: the model shard is not set (--native SHARD1)" ; return false; } 3489if (! x -> init ( g , ss , g_shard1 , MAXT , max_cells , err )) return false; 3490window_register ( w ); 3491if (! mtp_load_pending ( x , err )) return false; 3492} 3493x -> set_max_t ( max_t ); 3494* n_vocab = x -> vocab (); 3495return true; 3496} 3497bool window_ensure ( const strata::core::ModelGeometry & g , strata::core::SessionState & ss , int64_t max_cells , std::string & err ) { 3498int64_t nv = 0 ; 3499return window_init ( window_create (), g , ss , MAXT , max_cells , & nv , err ); 3500} 3501bool window_sample_slot_row (void * w , int row , const strata::kernels::SamplerParams & sp , const int32_t * hist , int hist_len , int32_t * tok , std::string & err ) { 3502return ((Window * ) w ) -> sample_slot_row ( row , sp , hist , hist_len , tok , err ); 3503} 3504void window_set_sampling (void * w , const strata::kernels::SamplerParams * sp , const int32_t * hist , int hist_len ) { 3505((Window * ) w ) -> set_sampling ( sp , hist , hist_len ); 3506} 3507bool window_run (void * w , int T , const int32_t * tokens , int64_t pos0 , bool head , int32_t * out , std::string & err ) { 3508// STRATA_LOGPOS (the quant yardstick, the KL harness): every window's head logits are read, also the prompt's 3509// windows that sample nothing (head_sampling off) 3510static const bool logpos = std:: getenv ( "STRATA_LOGPOS" ) != nullptr ; 3511Window * win = (Window * ) w ; 3512if (! win -> run ( T , tokens , pos0 , head || logpos , out , err )) return false; 3513return ! head || win -> sample_rows ( T , out , err ); // a sampled / penalised / biased request: the head rows' tokens by the sampler chain (nothing to do for greedy) 3514} 3515void window_reset ( const strata::core::SessionState * ss ) { 3516if ( g_the_window == nullptr || ! g_the_window -> ready ()) return ; 3517g_the_window -> activate ( g_the_window -> set_of ( ss )); 3518g_the_window -> reset (); 3519g_the_window -> activate ( 0 ); 3520} 3521bool window_checkpoint_save (strata::core::ConversationCheckpoint & c , const strata::core::SessionState * ss , std::string & err ) { 3522if ( g_the_window == nullptr || ! g_the_window -> ready ()) { err = "metal window: not up" ; return false; } 3523g_the_window -> activate ( g_the_window -> set_of ( ss )); // a batch slot's session: that slot's running state 3524const bool ok = g_the_window -> checkpoint_save ( c , err ); 3525g_the_window -> activate ( 0 ); 3526return ok ; 3527} 3528bool window_checkpoint_restore ( const strata::core::ConversationCheckpoint & c , const strata::core::SessionState * ss , std::string & err ) { 3529if ( g_the_window == nullptr || ! g_the_window -> ready ()) { err = "metal window: not up" ; return false; } 3530g_the_window -> activate ( g_the_window -> set_of ( ss )); 3531const bool ok = g_the_window -> checkpoint_restore ( c , err ); 3532g_the_window -> activate ( 0 ); 3533return ok ; 3534} 3535bool window_init_slots (void * w , const std::vector < strata::core::SessionState *>& slots , std::string & err ) { 3536return ((Window * ) w ) -> slots_init ( slots , err ); 3537} 3538bool window_run_slots (void * w , const int * rows , int S , const int32_t * tokens , const int64_t * pos , int32_t * out , std::string & err ) { 3539const double t0 = now_ms (); 3540const bool ok = ((Window * ) w ) -> run_slots ( rows , S , tokens , pos , out , err ); 3541((Window * ) w ) -> prof_add (true, now_ms () - t0 ); 3542return ok ; 3543} 3544bool window_slot_copy_main (bool into_slot , int slot , int64_t upto , bool kv_only , std::string & err ) { 3545if ( g_the_window == nullptr || ! g_the_window -> ready ()) { err = "metal window: not up" ; return false; } 3546return g_the_window -> slot_copy ( into_slot , slot , upto , kv_only , err ); 3547} 3548bool window_commit (void * w , int n_keep , std::string & err ) { 3549const double t0 = now_ms (); 3550const bool ok = ((Window * ) w ) -> commit ( n_keep , err ); 3551((Window * ) w ) -> prof_add (false, now_ms () - t0 ); 3552return ok ; 3553} 3554bool window_copy_logits (void * w , int t , float * host ) { return ((Window * ) w ) -> copy_logits ( t , host ); } 3555 3556// the MTP hook (src/core/mtp.cpp under STRATA_GPU_METAL): the drafter lives beside the decode window it reads 3557namespace { 3558Window * g_window = nullptr ; 3559} 3560void window_register (void * w ) { g_window = (Window * ) w ; } 3561// the engine loads the drafter before the decode window exists: the path is kept and the window loads it at its init 3562std::string g_mtp_path ; 3563int g_mtp_max_t = 0 ; 3564bool mtp_load ( const std::string & rt_dir , int max_t , std::string & err ) { 3565(void) err ; 3566// the MTP model in GGUF form (tools/mtp_pack.py) beside the rt directory: STRATA_METAL_MTP_GGUF, else 3567// <rt>/../mtp-q2_0.gguf 3568std::string path ; 3569if ( const char * e = std:: getenv ( "STRATA_METAL_MTP_GGUF" )) path = e ; 3570else { 3571std::string d = rt_dir ; 3572while (! d . empty () && d . back () == '/' ) d . pop_back (); 3573const size_t s = d . rfind ( '/' ); 3574path = ( s == std::string:: npos ? std:: string ( "." ) : d . substr ( 0 , s )) + "/mtp-q2_0.gguf" ; 3575} 3576g_mtp_path = path ; 3577g_mtp_max_t = max_t ; 3578return true; 3579} 3580void mtp_bind_state (strata::core::QsaState & st ) { 3581g_draft_state = & st ; 3582if ( g_the_window && g_the_window -> mtp_ready ()) g_the_window -> bind_draft ( st ); 3583} 3584bool mtp_load_pending (Window * w , std::string & err ) { 3585return g_mtp_path . empty () || w -> mtp_load ( g_mtp_path , g_mtp_max_t , err ); 3586} 3587// Prefill::run's Metal side: the prompt read through the window, MAXT rows at a time (no head), each window 3588// committed; on_chunk (the MTP's K/V) after each, with the window's final residual rows in place. 3589bool prompt_run_rows ( const int64_t * tokens , int64_t n , int64_t pos0 , 3590const std::function < bool( const float * , int64_t, int64_t, std::string & ) >& on_chunk , std::string & err ); 3591bool prompt_run ( const int64_t * tokens , int64_t n , int64_t pos0 , const float * const * embd_rows , 3592const std::function < bool( const float * , int64_t, int64_t, std::string & ) >& on_chunk , std::string & err ) { 3593struct Rows { 3594explicit Rows ( const float * const * r ) { g_embd_rows = r ; } 3595~ Rows () { g_embd_rows = nullptr ; } 3596} rows (embd_rows); 3597return prompt_run_rows ( tokens , n , pos0 , on_chunk , err ); 3598} 3599bool prompt_run_rows ( const int64_t * tokens , int64_t n , int64_t pos0 , 3600const std::function < bool( const float * , int64_t, int64_t, std::string & ) >& on_chunk , std::string & err ) { 3601if ( g_window == nullptr ) { err = "metal prompt: the decode window is not up yet" ; return false; } 3602static const bool windows = std:: getenv ( "STRATA_METAL_PROMPT" ) && std:: string (std:: getenv ( "STRATA_METAL_PROMPT" )) == "window" ; 3603static const int64_t min_rows = std:: getenv ( "STRATA_METAL_PROMPT_MIN" ) ? std:: atoll (std:: getenv ( "STRATA_METAL_PROMPT_MIN" )) : 32 ; 3604if (! windows && ! g_window -> streaming () && n >= min_rows ) return g_window -> prompt ( tokens , n , pos0 , on_chunk , err ); 3605if (! windows && g_window -> streaming ()) { 3606const char * e = std:: getenv ( "STRATA_METAL_PROMPT_GEMM" ); 3607const char * em = std:: getenv ( "STRATA_METAL_PROMPT_GEMM_MIN" ); 3608const int64_t mn = em ? std:: atoll ( em ) : 64 ; 3609if (!( e && std:: string ( e ) == "0" ) && n >= mn ) { 3610if (! g_window -> prompt_gemm_init ( err )) return false; 3611const int C = g_window -> prompt_chunk_rows (); 3612std::vector < int32_t > tk32 ((size_t) C ); 3613g_window -> prompt_region (true); 3614bool ok = true; 3615for (int64_t c = 0 ; c < n && ok ; c += C ) { 3616const int k = (int) std:: min < int64_t > ( C , n - c ); 3617for (int i = 0 ; i < k ; ++ i ) tk32 [(size_t) i ] = (int32_t) tokens [ c + i ]; 3618ok = g_window -> prompt_chunk ( tk32 . data (), k , pos0 + c , err ) && (! on_chunk || on_chunk ( nullptr , k , pos0 + c , err )); 3619} 3620g_window -> prompt_region (false); 3621return ok ; 3622} 3623} 3624int32_t tk [ MAXT ], out [ MAXT ]; 3625for (int64_t c = 0 ; c < n ; c += MAXT ) { 3626const int k = (int) std:: min < int64_t > ( MAXT , n - c ); 3627for (int i = 0 ; i < k ; ++ i ) tk [ i ] = (int32_t) tokens [ c + i ]; 3628if (! g_window -> run ( k , tk , pos0 + c , false, out , err ) || ! g_window -> commit ( k , err )) return false; 3629if (! g_window -> tap_deliver_dec ( k , pos0 + c , err )) return false; // DFlash2 3630if ( on_chunk && ! on_chunk ( nullptr , k , pos0 + c , err )) return false; 3631} 3632return true; 3633} 3634bool mtp_prefill ( const int32_t * next_tokens , int64_t n , int64_t cell0 , std::string & err ) { 3635if ( g_window == nullptr ) { err = "metal mtp: no decode window" ; return false; } 3636return g_window -> mtp_prefill ( next_tokens , n , cell0 , err ); 3637} 3638bool mtp_draft (int T , const int32_t * tokens , int64_t p , int a , int max_steps , int32_t * drafts , float * probs , float min_p , 3639int * n_drafts , std::string & err ) { 3640if ( g_window == nullptr ) { err = "metal mtp: no decode window" ; return false; } 3641const double t0 = now_ms (); 3642const bool ok = g_window -> mtp_draft ( T , tokens , p , a , max_steps , drafts , probs , min_p , n_drafts , err ); 3643g_window -> prof_add (true, now_ms () - t0 ); 3644return ok ; 3645} 3646 3647#include "prompt_chain.inc" 3648#include "dflash2.inc" 3649 3650} // namespace strata::metal_engine 3651namespace strata::gpu { void * host_view ( const void * device_pointer ); } 3652namespace strata::kernels { 3653void mrope_table_set ( const int32_t * device_table ) { 3654strata::metal_engine:: g_mrope_dev = device_table ; 3655strata::metal_engine:: g_mrope_host = 3656device_table ? ( const int32_t * ) strata::gpu:: host_view ( device_table ) : nullptr ; 3657} 3658const int32_t * mrope_table () { return strata::metal_engine:: g_mrope_dev ; } 3659} // namespace strata::kernels 3660namespace strata::metal_engine { 3661 3662} // namespace strata::metal_engine