okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fd19246dc
main
1 2// src/core/layer.cpp - the GDN layer, composed. See the header for the operation order and its traps. 3#include "strata/core/layer.hpp" 4#include "strata/core/pin_budget.hpp" 5#include "strata/core/native_dense.hpp" 6#include "strata/core/native_head.hpp" 7#include "strata/kernels/bf16_bits.hpp" 8#include "strata/kernels/bf16_gemv.hpp" 9#include "strata/kernels/elementwise.hpp" 10#include "strata/kernels/gdn.hpp" 11#include "strata/kernels/qsa.hpp" 12#include "strata/kernels/kv_q4.hpp" 13#include "strata/kernels/kv_q8.hpp" 14#include "strata/kernels/quantize_act.hpp" 15#include "strata/kernels/fuse_decode.hpp" 16#include "strata/kernels/rope.hpp" 17#include "strata/kernels/router_top10.hpp" 18#include "strata/kernels/s2_gemv_q8.hpp" 19#include "strata/kernels/s_gemv.hpp" 20#include "strata/kernels/shared_expert.hpp" 21#include "strata/kernels/native_mmvq.hpp" 22#include "strata/kernels/native_moe.hpp" 23#include "strata/kernels/native_gdn.hpp" 24#include "strata/kernels/native_gdn_preprocess.hpp" 25#include "strata/kernels/native_router.hpp" 26#include "strata/kernels/native_qsa.hpp" 27#include "strata/kernels/native_qsa_indexer.hpp" 28#include "strata/kernels/mrope.hpp" 29#include "strata/kernels/native_rope.hpp" 30#include "strata/kernels/native_flash_attn.hpp" 31#include "strata/kernels/fused_gr.hpp" 32#include "strata/kernels/cvec.hpp" 33#include "strata/kernels/qsa_decode_attn.hpp" 34#include "strata/kernels/fused_gdn.hpp" 35#include "strata/kernels/qsa_select.hpp" 36#include <algorithm> 37#include <cstdlib> 38#include <exception> 39#include <filesystem> 40#include <cuda_runtime.h> 41#include <cmath> 42#include <cstdio> 43#include <cstring> 44#include <limits> 45#ifndef _WIN32 46#include <sys/mman.h> 47#endif 48#include <memory> 49#include <vector> 50namespace strata::core { 51namespace {bool g_shared_early = true;bool g_fused_gr = false;bool g_fast_attn = true;bool g_publish_kernel = true;bool g_fused_gdn = true;bool g_fast_select = true; } 52namespace {constexpr int Q8K_BYTES_PER_BLOCK = 292 ; 53constexpr int Q8K_ELEMS_PER_BLOCK = 256 ; 54constexpr float RMS_EPS = 1e-6f ; 55const std::string EMBEDDING_NAME = "token_embd.weight" ; 56// qwen4exp.attention.layer_norm_rms_epsilon, used for BOTH norms here 57/// A Q8_K buffer needs `n` a multiple of 256 and `n/256` blocks of 292 bytes. 58uint64_t q8k_bytes (int64_t n ) {return (uint64_t ) (n /Q8K_ELEMS_PER_BLOCK )* Q8K_BYTES_PER_BLOCK ; } 59/// `s_gemv_q8k` takes the canonical-form attributes; a `WeightRef` carries them, and a tensor that is NOT 60/// quantized has none. Returns false and names the tensor rather than building a form out of zeroes - which 61/// would decode every code as `0 + bias` and produce a perfectly finite wrong answer. 62bool sform_of (const WeightRef & r , strata::kernels::SForm & f ,const std::string & name , std::string & err ) {if (!r .quantized ()) {err = name + " is not a quantized tensor, so it has no S-form" ;return false; }f .code_bits = r .code_bits ;f .code_bias = r .code_bias ;f .group_elems = r .group_elems ;f .codebook = r .codebook_iq4nl ? strata::kernels::Codebook ::Iq4Nl : strata::kernels::Codebook ::Affine ;f .has_offset = r .has_offset ;f .act_kind = r .act_kind ; 63// carried, not derived - see the note on `SForm::act_kind` 64return true;} 65/// The three canonical planes of a quantized tensor, located INSIDE the loaded region. 66// 67// 68// **THIS FUNCTION USED TO RE-DERIVE THE LAYOUT, AND THAT IS HOW A WIDTH BUG SURVIVED A ROUND.** It computed 69/// `n_groups = n_in / group_elems` and then `scales_bytes = n_out * n_groups * sizeof(float)` - 4 bytes per 70/// scale for every tensor. 90 of the 303 quantized tensors hold fp16 scales in the pack (all 58 Q2_0 expert 71/// tensors, plus Q4_0, Q5_0, Q8_0 and IQ4_NL), so for those the computed plane was TWICE the real one and the 72/// three planes did not add up to the tensor. The first diagnosis was "the manifest's `group_elems` must be 73/// wrong, the real group is 64"; it is not, and an audit of all 303 tensors against `scales_fp16` found zero 74/// inconsistencies. **The unexamined input was the scale WIDTH, not the group COUNT.** 75// 76// 77// The loader now widens fp16 scales to f32 on the way into the arena and records the resulting plane sizes in 78/// the `WeightRef`, so this function has nothing left to derive - it reads what was loaded. The redundancy is 79/// deliberate: the sizes come from ONE place (the index, checked against the manifest by `pack_index.py` and 80/// against the span by the loader), and this function only checks that they describe the tensor it was given. 81// 82// 83// **THE PLANE KEY IS `offsets`, NOT `mins`, AND THAT COST 136 MiB.** `tools/pack_index.py` and 84/// `tools/pack_budget.py` both looked for `mins` and both therefore omitted the offset plane of 54 Q4_K/Q5_K 85/// tensors - so the arena was sized without it AND the bytes were never copied. Two tools agreeing is only 86/// evidence when they do not share the assumption that is wrong. This function refuses rather than guessing, 87/// which is what caught it. 88struct Planes {const uint8_t * codes = nullptr ;const float * scales = nullptr ;const float * offset = nullptr ; 89///< null when the form has none 90}; 91bool plane_ptrs (const WeightRef & r ,const std::string & name ,Planes & out , std::string & err ) { 92// S2, S4 AND S8 ALL SPLIT THE SAME WAY. The plane LOCATION does not depend on the code width - the three 93// sizes come from the index and are checked against the tensor below - so the guard is here to catch a 94// tensor that is not quantized at all, not to pick a decoder. WHICH KERNEL reads the planes is the 95// caller's choice and the two differ: an S2 tensor's activation contract is Q8_0 (`s2_gemv_q8`) while a 96// K-quant's is Q8_K (`s_gemv_q8k`). This used to accept only 4 and 8, which refused `attn_q` - a Q2_0 97// tensor and the reason the QSA layer could not be composed at all. 98if (r .code_bits != 2 && r .code_bits != 4 && r .code_bits != 8 ) {err = name + ": code_bits " + std::to_string (r .code_bits )+ " is not an S2/S4/S8 form" ;return false; }const uint64_t end = r .codes_bytes + r .scales_bytes + r .offset_bytes ;if (r .codes_bytes == 0 || r .scales_bytes == 0 || end != r .bytes ) {char buf [320 ]; std::snprintf (buf ,sizeof buf ,"%s: the planes add up to %llu B but the tensor is %llu B (codes %llu, scales %llu, " "offsets %llu) - what the loader recorded is not the layout that was loaded" ,name .c_str (), (unsigned long long )end , (unsigned long long )r .bytes , (unsigned long long )r .codes_bytes , (unsigned long long )r .scales_bytes , (unsigned long long )r .offset_bytes );err = buf ;return false; }if (r .has_offset != (r .offset_bytes != 0 )) {err = name + ": has_offset is " + std::to_string (r .has_offset ?1 :0 )+ " but the offset plane is " + std::to_string (r .offset_bytes )+ " B" ;return false; }const uint8_t * base = (const uint8_t * )r .data ;out .codes = base ;out .scales = (const float * ) (base + r .codes_bytes );out .offset = r .offset_bytes ? (const float * ) (base + r .codes_bytes + r .scales_bytes ) :nullptr ;return true;} 99constexpr int TPR = 32 ; 100bool native_bf16_projections = false; 101bool native_flash_attn_short = false; 102 103void project_bf16 (const float * x ,const uint16_t * x_bf16 ,const uint16_t * weights ,float * out , 104int64_t n_in ,int64_t n_out ,bool split ,void * stream ) { 105using namespace strata::kernels ; 106if (native_bf16_projections )bf16_gemv_fp32_mmvf (x ,weights ,out ,n_in ,n_out ,stream ); 107else if (split )bf16_gemv_split (x_bf16 ,weights ,out ,n_in ,n_out ,TPR ,stream ); 108else bf16_gemv (x_bf16 ,weights ,out ,n_in ,n_out ,stream ); 109} 110#if defined(STRATA_EXPERIMENTAL_SM60 ) 111// TWO BF16 projections of the SAME x in ONE kernel (`ssm_alpha`/`ssm_beta`, `indexer.q`/`indexer.k`). 112// `bf16_gemv_pair` reproduces the warp-per-row accumulation, which is what `bf16_gemv_split` at TPR 32 113// always runs and what plain `bf16_gemv` runs at n_out >= 64 - below that the plain entry uses the naive 114// one-thread-per-row sum and the pair would round differently, so those shapes keep two calls. 115void project_bf16_pair (const float * x ,const uint16_t * x_bf16 ,const uint16_t * w1 ,float * o1 ,int64_t n_out1 , 116const uint16_t * w2 ,float * o2 ,int64_t n_out2 ,int64_t n_in ,bool split ,void * stream ) { 117using namespace strata::kernels ; 118if (native_bf16_projections ) { 119bf16_gemv_fp32_mmvf (x ,w1 ,o1 ,n_in ,n_out1 ,stream ); 120bf16_gemv_fp32_mmvf (x ,w2 ,o2 ,n_in ,n_out2 ,stream ); 121 }else if (split || (n_out1 >=64 && n_out2 >=64 )) { 122bf16_gemv_pair (x_bf16 ,w1 ,o1 ,n_out1 ,w2 ,o2 ,n_out2 ,n_in ,stream ); 123 }else { 124bf16_gemv (x_bf16 ,w1 ,o1 ,n_in ,n_out1 ,stream ); 125bf16_gemv (x_bf16 ,w2 ,o2 ,n_in ,n_out2 ,stream ); 126 } 127} 128#endif 129///< threads per row for the row-split GEMVs. 130/// **MEASURED, NOT ASSUMED, AND 64 IS NOT BETTER.** `dense_pass.exe` drives the same split kernels at 131/// threads_per_row 64 and reports 248.5 GB/s, so matching it looked like free performance. It is not: 132/// TPR=64 gives 11.75 tok/s against 32's 11.99 with experts, and 20.19 against 20.26 without - identical 133/// inside noise and marginally worse on both. That is also what the stage table predicts, because the GEMVs 134/// are only ~16% of a token, so a few percent there cannot move the total. Kept at 32; the sweep that would 135/// actually settle it is per-tensor, not global, and belongs with the fusion work rather than before it. 136///< threads per row for the row-split GEMVs 137/// Writes the sequence number into MAPPED PINNED memory. A KERNEL, not cudaEventRecord - round 199 found 138/// that an event record inside a capture is silently dropped, while this is captured normally and the host can 139/// read its result MID-GRAPH. One thread: it is a store. 140// (the ring kernel lives in src/kernels/cuda/elementwise.cu; this file is HOST code) 141/// WHICH ACTIVATION A QUANTIZED WEIGHT WANTS, AND IT IS A PROPERTY OF THE **TENSOR**, NOT OF ITS ROLE. 142// 143// 144// Rounds 205-215 ran `gdn_layer` and `qsa_layer` on the assumption that a name implies a family: `attn_qkv` is 145/// a K-quant, `attn_q` is Q2_0, and so on. **The pack does not work that way.** The same name is quantized 146/// per LAYER, and the spread is wide: 147// 148// 149// attn_qkv IQ4_XS x13, Q3_K x18, Q2_0 x1, Q4_K x4 (36 GDN layers) 150/// attn_gate Q3_K x25, IQ4_XS x4, Q4_K x3, Q2_0 x4 151/// attn_q Q3_K x6, IQ4_XS x4, Q2_0 x2 (12 QSA layers) 152// 153// 154// `docs/activation-contract.md` fixes the rule per TYPE, and it is short: 155// 156// 157// code_bits == 2 -> Q8_0, via `quantize_q8_0` + `s2_gemv_q8` 158/// anything else quantized -> Q8_K, via `quantize_q8_K` + `s_gemv_q8k_split` 159// 160// 161// Getting it wrong is worth 0.6-1.4% on the GEMV - a plausible vector, not a broken one - which is exactly 162/// what Gate C1 exists to find and what nothing before C1 would have. `s_gemv_q8k`'s own guard is what caught 163/// it here (`code_bits 2 has no Q8_K contract`). 164// 165// 166// `x80` and `xq8k` are the two quantized images of the SAME activation; a caller produces both once and this 167/// picks. Producing only the one it thinks it needs is how the assumption gets baked in again. 168bool gemv_quantized (const WeightRef & w ,const Planes & p ,const strata::kernels::SForm & f ,const uint8_t * x80 ,const uint8_t * xq8k ,float * y ,int64_t n_in ,int64_t n_out ,const std::string & name ,void * stream , std::string & err ,const float * x_f32 = nullptr ,bool x_q8_1_ready = false) { 169using namespace strata::kernels ; 170if (w .native_data ) { 171if (!x_f32 || !w .native_q8_1 || !stream || n_in != w .ne0 || n_out != w .ne1 ) { 172err = name + ": native projection requires matching FP32 input and session scratch" ; 173return false; 174 } 175try { 176// Plan v0.3 P3: a caller whose previous native projection quantized the SAME x into the shared 177// scratch, with no native projection in between, passes x_q8_1_ready and the quantize is skipped. 178if (!x_q8_1_ready )native_quantize_q8_1 (x_f32 ,w .native_q8_1 , (int )n_in ,1 ,stream ); 179native_mmvq (w .native_type ,w .native_data ,w .native_q8_1 ,y , 180 (int )n_in , (int )n_out ,1 ,stream ); 181 }catch (const std::exception & error ) { 182err = name + ": " + error .what (); 183return false; 184 } 185return true; 186 } 187if ((w .code_bits == 2 || !w .wants_q8k ()) ? !x80 : !xq8k ) { 188err = name + ": missing canonical quantized activation" ; 189return false; 190 } 191if (w .code_bits == 2 ) { 192// S2 carries no offset plane and no SForm: its attributes are fixed (2 bits, group 64, bias -1), which 193// is why `s2_gemv_q8` takes neither. 194if (w .has_offset || p .offset != nullptr ) {err = name + ": an S2 form must have no offset plane" ;return false; }if (w .group_elems != 64 || w .code_bias != -1 ) {err = name + ": an S2 form must be group 64 with bias -1, this one is group " + std::to_string (w .group_elems )+ " with bias " + std::to_string (w .code_bias );return false; }s2_gemv_q8 (x80 ,p .codes ,p .scales ,y ,n_in ,n_out ,TPR ,stream );return true; } 195// **A LEGACY 4/8-BIT FORM WANTS Q8_0, NOT Q8_K, AND `code_bits` CANNOT TELL YOU WHICH.** This used to be 196// `code_bits == 2 ? Q8_0 : Q8_K`, which is CORRECT ONLY BY LUCK: every legacy tensor in this pack apart 197// from `ffn_down_shexp` is Q2_0, whose attributes happen to be S2's. Q5_0 and Q5_K are both 8-bit with 198// bias -16 and differ only in `has_offset`; IQ4_NL and IQ4_XS differ in NOTHING the S-form carries. The 199// kind therefore comes from the manifest's `source_type`, through the index (LEDGER L54/L55). 200if (((uintptr_t )p .codes < ((uintptr_t )1 <<30 ))|| ((uintptr_t )p .scales < ((uintptr_t )1 <<30 ))) { 201 std::fprintf (stderr ,"gemv_quantized SMALL PTR: %s codes=%p scales=%p off=%p n_in=%lld n_out=%lld cb=%d g=%d\n" , 202name .c_str (), (const void * )p .codes , (const void * )p .scales , (const void * )p .offset , 203 (long long )n_in , (long long )n_out , (int )w .code_bits , (int )w .group_elems ); 204 std::fflush (stderr ); 205 } 206if (!w .wants_q8k ()) {s_gemv_q8_0_split (x80 ,p .codes ,p .scales ,p .offset ,y ,n_in ,n_out ,f ,stream );return true; }s_gemv_q8k_split (xq8k ,p .codes ,p .scales ,p .offset ,y ,n_in ,n_out ,f ,stream );return true;}} 207// namespace 208void layer_set_native_bf16 (bool enabled ) {native_bf16_projections = enabled ; } 209void layer_set_native_flash_attn_short (bool enabled ) {native_flash_attn_short = enabled ; } 210namespace {bool g_kv_int8 = false,g_kv_q4 = false,g_kv_hybrid = false,g_kv_int8_rot = false; } 211void qsa_set_kv_int8 (bool enabled ) {g_kv_int8 = enabled ; } 212void qsa_set_kv_int8_rotate (bool enabled ) {g_kv_int8_rot = enabled ; } 213bool qsa_kv_int8 () {return g_kv_int8 ; } 214void qsa_set_kv_q4 (bool enabled ) {g_kv_q4 = enabled ; } 215bool qsa_kv_q4 () {return g_kv_q4 ; } 216void qsa_set_kv_hybrid (bool enabled ) {g_kv_hybrid = enabled ; } 217bool qsa_kv_hybrid () {return g_kv_hybrid ; } 218uint64_t gdn_buffers_bytes (const ModelGeometry & g ) {const int64_t C = g .ssm_conv_channels ;const int64_t V = g .ssm_value_dim ;const uint64_t parts []= {q8k_bytes (g .n_embd ), 219// x_q8k 220(uint64_t ) (g .n_embd /32 )* 34 , 221// x_q8_0 222(uint64_t )g .n_embd * 2 , 223// x_bf16 224(uint64_t )C * 4 , 225// qkv 226(uint64_t )C * 4 , 227// conv_out 228(uint64_t )C * 4 , 229// h 230(uint64_t )g .ssm_v_heads * 4 , 231// alpha 232(uint64_t )g .ssm_v_heads * 4 , 233// beta 234(uint64_t )g .ssm_v_heads * 4 , 235// gate 236(uint64_t )g .ssm_v_heads * g .ssm_state_size * 4 , 237// o 238(uint64_t )V * 4 , 239// z 240(uint64_t )V * 4 , 241// y 242q8k_bytes (V ), 243// y_q8k 244(uint64_t ) (V /32 )* 34 , 245// y_q8_0 246(uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size * 4 , 247// state 248(uint64_t )C * (g .ssm_d_conv - 1 )* 4 , 249// conv_state 250};uint64_t total = 0 ;for (uint64_t v :parts )total += (v + 15 )& ~(uint64_t )15 ;return total ;} 251uint64_t gdn_buffers_init (const ModelGeometry & g ,void * base ,GdnBuffers & b ) {const int64_t C = g .ssm_conv_channels ;const int64_t V = g .ssm_value_dim ;const uint64_t parts []= {q8k_bytes (g .n_embd ), (uint64_t ) (g .n_embd /32 )* 34 , (uint64_t )g .n_embd * 2 , (uint64_t )C * 4 , (uint64_t )C * 4 , (uint64_t )C * 4 , (uint64_t )g .ssm_v_heads * 4 , (uint64_t )g .ssm_v_heads * 4 , (uint64_t )g .ssm_v_heads * 4 , (uint64_t )g .ssm_v_heads * g .ssm_state_size * 4 , (uint64_t )V * 4 , (uint64_t )V * 4 ,q8k_bytes (V ), (uint64_t ) (V /32 )* 34 , (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size * 4 , (uint64_t )C * (g .ssm_d_conv - 1 )* 4 , };uint8_t * p = (uint8_t * )base ;void * ptr [16 ];uint64_t total = 0 ;for (int i = 0 ;i < 16 ;++ i ) {ptr [i ]= p ;const uint64_t al = (parts [i ]+ 15 )& ~(uint64_t )15 ;p += al ;total += al ; }b .x_q8k = (uint8_t * )ptr [0 ];b .x_q8_0 = (uint8_t * )ptr [1 ];b .x_bf16 = (uint16_t * )ptr [2 ];b .qkv = (float * )ptr [3 ];b .conv_out = (float * )ptr [4 ];b .h = (float * )ptr [5 ];b .alpha = (float * )ptr [6 ];b .beta = (float * )ptr [7 ];b .gate = (float * )ptr [8 ];b .o = (float * )ptr [9 ];b .z = (float * )ptr [10 ];b .y = (float * )ptr [11 ];b .y_q8k = (uint8_t * )ptr [12 ];b .y_q8_0 = (uint8_t * )ptr [13 ];b .state = (float * )ptr [14 ];b .conv_state = (float * )ptr [15 ];return total ;} 252void gdn_buffers_zero_state (const GdnBuffers & b ,const ModelGeometry & g ,void * stream ) {const uint64_t st = (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size * sizeof (float );const uint64_t cs = (uint64_t )g .ssm_conv_channels * (g .ssm_d_conv - 1 )* sizeof (float );cudaMemsetAsync (b .state ,0 ,st , (cudaStream_t )stream );cudaMemsetAsync (b .conv_state ,0 ,cs , (cudaStream_t )stream );} 253// Forward-declared because `gdn_layer` and `qsa_layer` are both defined above the timer's own definition, and 254// the sub-stage marks live inside them. 255static void st_begin (int64_t layer ,int slot ,void * stream ); 256static void st_end (int64_t layer ,int slot ,void * stream ); 257bool gdn_layer (const WeightTable & tables ,const ModelGeometry & g ,int64_t layer ,const GdnBuffers & b ,const float * mixed ,float * out ,void * stream , std::string & err ) {const LayerView v (tables ,layer );const int64_t C = g .ssm_conv_channels ; 258// ---- resolve. Every one of these was shape-checked by `check_layer` at load time, so a miss here is a 259// NAME problem and not a geometry one, and the message says which name. 260const WeightRef * w_qkv = v .get ("attn_qkv.weight" );const WeightRef * w_gate = v .get ("attn_gate.weight" );const WeightRef * w_out = v .get ("ssm_out.weight" );const WeightRef * w_alpha = v .get ("ssm_alpha.weight" );const WeightRef * w_beta = v .get ("ssm_beta.weight" );const WeightRef * w_conv = v .get ("ssm_conv1d.weight" );const WeightRef * w_norm = v .get ("ssm_norm.weight" );const WeightRef * w_dt = v .get ("ssm_dt.bias" );const WeightRef * w_a = v .get ("ssm_a" );const char * missing = !w_qkv ?"attn_qkv.weight" : !w_gate ?"attn_gate.weight" : !w_out ?"ssm_out.weight" : !w_alpha ?"ssm_alpha.weight" : !w_beta ?"ssm_beta.weight" : !w_conv ?"ssm_conv1d.weight" : !w_norm ?"ssm_norm.weight" : !w_dt ?"ssm_dt.bias" : !w_a ?"ssm_a" :nullptr ;if (missing ) {err = v .name (missing )+ " is missing" ;return false; } 261// The conv kernel and the two norms are F32 source types, and the loader copied them verbatim - so their 262// device bytes ARE f32 and can be handed straight to the kernels that want `const float*`. 263const float * conv_kernel = (const float * )w_conv -> data ;const float * ssm_norm = (const float * )w_norm -> data ;const float * dt = (const float * )w_dt -> data ;const float * ssm_a = (const float * )w_a -> data ; strata::kernels::SForm f_qkv ,f_gate ,f_out ;if (!sform_of (* w_qkv ,f_qkv ,v .name ("attn_qkv.weight" ),err ))return false;if (!sform_of (* w_gate ,f_gate ,v .name ("attn_gate.weight" ),err ))return false;if (!sform_of (* w_out ,f_out ,v .name ("ssm_out.weight" ),err ))return false;Planes p_qkv ,p_gate ,p_out ;if (!plane_ptrs (* w_qkv ,v .name ("attn_qkv.weight" ),p_qkv ,err ))return false;if (!plane_ptrs (* w_gate ,v .name ("attn_gate.weight" ),p_gate ,err ))return false;if (!plane_ptrs (* w_out ,v .name ("ssm_out.weight" ),p_out ,err ))return false;using namespace strata::kernels ;cudaStream_t st = (cudaStream_t )stream ; 264// ---- 1. the activation, in EVERY format a weight on this layer might ask for. BOTH quantized images are 265// produced, because which one is wanted is a property of the TENSOR and the pack mixes them by 266// layer - producing only the "right" one is how the per-role assumption gets baked back in. 267st_begin (layer ,8 ,stream ); 268// Plan v0.3 P3: the canonical activation images only when a canonical projection reads them. 269if (!w_qkv -> native_data || !w_gate -> native_data ) { 270#if defined(STRATA_EXPERIMENTAL_SM60 ) 271if (strata::kernels::fuse_decode ()) { 272quantize_act_images (mixed ,g .n_embd ,b .x_q8_0 ,b .x_q8k ,nullptr ,stream );// ONE pass, was two kernels 273 }else 274#endif 275 { 276quantize_q8_K (mixed ,b .x_q8k ,g .n_embd ,stream ); 277quantize_q8_0 (mixed ,b .x_q8_0 ,g .n_embd ,stream ); 278 } 279 } 280st_end (layer ,8 ,stream ); 281// ---- 2. qkv = wqkv @ x, with the activation THIS layer's `attn_qkv` asks for 282st_begin (layer ,9 ,stream );if (!gemv_quantized (* w_qkv ,p_qkv ,f_qkv ,b .x_q8_0 ,b .x_q8k ,b .qkv ,g .n_embd ,C ,v .name ("attn_qkv.weight" ),stream ,err ,mixed ))return false;st_end (layer ,9 ,stream ); 283// ---- 3. conv, then SiLU on the WHOLE conv output - before the q|k|v split, which is what 284// `ref/gdn.py` L262 says and what makes the split a reshape rather than a copy. 285st_begin (layer ,10 ,stream ); 286// Plan v0.3 P3: under the native contract, conv + SiLU + both L2 norms are one kernel, and alpha/beta with their 287// epilogues another (`fused_gdn.hpp`). 288const bool fused_pre = g_fused_gdn && native_gdn_enabled ()&& native_bf16_projections && g .ssm_d_conv == 4 && 289g .ssm_state_size == 128 ; 290if (fused_pre ) { 291fused_gdn_conv_l2 (b .conv_state ,b .qkv ,conv_kernel ,b .h , (int )C , (int ) (2 * g .ssm_k_heads ),RMS_EPS ,stream ); 292}else 293try { 294if (native_gdn_enabled ())native_gdn_conv_silu (b .conv_state ,b .qkv ,conv_kernel ,b .conv_out ,b .h ,C ,g .ssm_d_conv ,stream ); 295else { 296gdn_conv_step (b .conv_state ,b .qkv ,conv_kernel ,b .conv_out ,C ,g .ssm_d_conv ,stream ); 297cudaMemcpyAsync (b .h ,b .conv_out , (size_t )C * 4 ,cudaMemcpyDeviceToDevice ,st ); 298silu_inplace (b .h ,C ,stream ); 299 } 300}catch (const std::exception & error ) {err = v .name ("gdn_conv_silu" )+ ": " + error .what ();return false; } 301st_end (layer ,10 ,stream ); 302// ---- 4. q,k = l2_norm; v is NOT normalised. The three views are contiguous runs of the same buffer: 303// q at [0, 2048), k at [2048, 4096), v at [4096, 10240), each 128-wide heads. const 304st_begin (layer ,11 ,stream );int64_t qk = g .ssm_state_size * g .ssm_k_heads ; 305if (!fused_pre )try { 306if (native_gdn_enabled ()) { 307native_gdn_l2_norm (b .h ,g .ssm_k_heads ,g .ssm_state_size ,RMS_EPS ,stream ); 308native_gdn_l2_norm (b .h + qk ,g .ssm_k_heads ,g .ssm_state_size ,RMS_EPS ,stream ); 309 }else { 310gdn_l2_norm (b .h ,g .ssm_k_heads ,g .ssm_state_size ,RMS_EPS ,stream ); 311gdn_l2_norm (b .h + qk ,g .ssm_k_heads ,g .ssm_state_size ,RMS_EPS ,stream ); 312 } 313}catch (const std::exception & error ) {err = v .name ("gdn_l2_norm" )+ ": " + error .what ();return false; } 314// The recurrence needs another 1/sqrt(S) beyond Q/K normalization. The legacy 315// recurrence consumes prescaled Q; pinned CUDA applies it after the readout dot. 316// Keep the scale at that backend-specific boundary to preserve rounding order. 317if (!native_gdn_enabled ())scale_inplace (b .h ,qk ,1.0f / std::sqrt ((float )g .ssm_state_size ),stream ); 318st_end (layer ,11 ,stream ); 319// ---- 5. beta and the gate. The weights are BF16. Native single-token CUDA MMVF 320// consumes F32 activations; the legacy path rounds them to BF16 first. 321// 322// THE ROW-SPLIT FORM, and here the case is stronger than the router's: `ssm_v_heads` is **48**, so 323// the plain one-thread-per-row form puts 48 threads on a 48-SM GPU and each walks 2,560 elements 324// alone. Measured 0.1072 ms each, against 0.0277 for the split - and there are two of them, in all 325// 36 GDN layers. 326st_begin (layer ,12 ,stream ); 327if (fused_pre ) { 328fused_gdn_ab (mixed , (const uint16_t * )w_alpha -> data , (const uint16_t * )w_beta -> data ,dt ,ssm_a ,b .gate ,b .beta , 329 (int )g .n_embd , (int )g .ssm_v_heads ,stream ); 330 }else { 331if (!native_bf16_projections )f32_to_bf16_bulk (mixed ,b .x_bf16 ,g .n_embd ,stream ); 332#if defined(STRATA_EXPERIMENTAL_SM60 ) 333if (strata::kernels::fuse_decode ()) { 334project_bf16_pair (mixed ,b .x_bf16 , (const uint16_t * )w_alpha -> data ,b .alpha ,g .ssm_v_heads , 335 (const uint16_t * )w_beta -> data ,b .beta ,g .ssm_v_heads ,g .n_embd , true,stream ); 336 }else 337#endif 338 { 339project_bf16 (mixed ,b .x_bf16 , (const uint16_t * )w_alpha -> data ,b .alpha ,g .n_embd ,g .ssm_v_heads , true,stream ); 340project_bf16 (mixed ,b .x_bf16 , (const uint16_t * )w_beta -> data ,b .beta ,g .n_embd ,g .ssm_v_heads , true,stream ); 341 } 342 } 343if (!fused_pre )try { 344if (native_gdn_enabled ()) { 345native_gdn_beta_gate (b .beta ,g .ssm_v_heads ,stream ); 346native_gdn_gate (b .alpha ,dt ,ssm_a ,b .gate ,g .ssm_v_heads ,stream ); 347 }else { 348gdn_beta_gate (b .beta ,g .ssm_v_heads ,stream ); 349gdn_gate (b .alpha ,dt ,ssm_a ,b .gate ,1 ,g .ssm_v_heads ,stream ); 350 } 351 }catch (const std::exception & error ) {err = v .name ("gdn_gate" )+ ": " + error .what ();return false; } 352st_end (layer ,12 ,stream );st_begin (layer ,13 ,stream ); 353GdnShapes gs {g .ssm_state_size ,g .ssm_k_heads ,g .ssm_v_heads }; 354// Plan v0.3 P3: with the native contract the step and the output norm are one kernel (after the z GEMV). 355const bool fused_gdn = g_fused_gdn && native_gdn_enabled ()&& g .ssm_state_size == 128 ; 356if (!fused_gdn )try { 357if (native_gdn_enabled ())native_gdn_step (b .state ,b .h ,b .h + qk ,b .h + 2 * qk ,b .gate ,b .beta ,b .o ,gs ,stream ); 358else gdn_step (b .state ,b .h ,b .h + qk ,b .h + 2 * qk ,b .gate ,b .beta ,b .o ,gs ,stream ); 359 }catch (const std::exception & error ) { 360err = v .name ("gdn_step" )+ ": " + error .what (); 361return false; 362 } 363st_end (layer ,13 ,stream );st_begin (layer ,14 ,stream ); 364// ---- 6. the recurrence. q and k are the (16, 128) views; v is the (48, 128) view. The stage marks for 365// it live at the end of the alpha/beta/gate line above, because the gate and the step are one sequence. 366// ---- 7. z, then y = rms_norm(o) * ssm_norm * sigmoid(z). SIGMOID, not SiLU. 367// qkv's native quantize of `mixed` is still in the shared q8_1 scratch: nothing native ran in between. 368if (!gemv_quantized (* w_gate ,p_gate ,f_gate ,b .x_q8_0 ,b .x_q8k ,b .z ,g .n_embd ,g .ssm_value_dim ,v .name ("attn_gate.weight" ),stream ,err ,mixed , 369w_qkv -> native_data != nullptr && w_gate -> native_data != nullptr ))return false; 370try { 371if (fused_gdn )fused_gdn_step_norm (b .state ,b .h ,b .h + qk ,b .h + 2 * qk ,b .gate ,b .beta ,b .z ,ssm_norm ,RMS_EPS ,b .y , 372 (int )g .ssm_k_heads , (int )g .ssm_v_heads ,stream ); 373else if (native_gdn_enabled ())native_gdn_out_norm (b .o ,b .z ,ssm_norm ,b .y ,g .ssm_v_heads ,g .ssm_state_size ,RMS_EPS ,stream ); 374else gdn_out_norm (b .o ,b .z ,ssm_norm ,b .y ,g .ssm_v_heads ,g .ssm_state_size ,RMS_EPS ,stream ); 375}catch (const std::exception & error ) {err = v .name ("gdn_out_norm" )+ ": " + error .what ();return false; } 376st_end (layer ,14 ,stream ); 377// ---- 8. out = ssm_out @ y, whose activation is whatever THIS layer's `ssm_out` asks for 378st_begin (layer ,15 ,stream ); 379if (!w_out -> native_data ) { 380#if defined(STRATA_EXPERIMENTAL_SM60 ) 381if (strata::kernels::fuse_decode ()) { 382quantize_act_images (b .y ,g .ssm_value_dim ,b .y_q8_0 ,b .y_q8k ,nullptr ,stream );// ONE pass, was two 383 }else 384#endif 385 { 386quantize_q8_K (b .y ,b .y_q8k ,g .ssm_value_dim ,stream ); 387quantize_q8_0 (b .y ,b .y_q8_0 ,g .ssm_value_dim ,stream ); 388 } 389 }if (!gemv_quantized (* w_out ,p_out ,f_out ,b .y_q8_0 ,b .y_q8k ,out ,g .ssm_value_dim ,g .n_embd ,v .name ("ssm_out.weight" ),stream ,err ,b .y ))return false;st_end (layer ,15 ,stream );return true;} 390// ================================ the MoE block ================================ 391uint64_t moe_buffers_bytes (const ModelGeometry & g ,int64_t k ) {const uint64_t parts []= { (uint64_t )g .n_embd * 2 , 392// x_bf16 393(uint64_t )g .n_embd * 2 , 394// x_f16 395(uint64_t )g .n_expert * 4 , 396// logits 397(uint64_t )k * 4 , 398// ids (int32) 399(uint64_t )k * 4 , 400// weights 401(uint64_t )g .n_embd * 4 , 402// shared 403strata::kernels::shared_expert_scratch_bytes (g .n_ff ), 404// the shared expert's own scratch 405(uint64_t ) (g .n_embd /32 )* 34 , 406// x_q8_0 407q8k_bytes (g .n_embd ), 408// x_q8k 409};uint64_t total = 0 ;for (uint64_t v :parts )total += (v + 15 )& ~(uint64_t )15 ;return total ;} 410uint64_t moe_buffers_init (const ModelGeometry & g ,int64_t k ,void * base ,MoEBuffers & b ) {const uint64_t parts []= { (uint64_t )g .n_embd * 2 , (uint64_t )g .n_embd * 2 , (uint64_t )g .n_expert * 4 , (uint64_t )k * 4 , (uint64_t )k * 4 , (uint64_t )g .n_embd * 4 , strata::kernels::shared_expert_scratch_bytes (g .n_ff ), (uint64_t ) (g .n_embd /32 )* 34 ,q8k_bytes (g .n_embd ), };uint8_t * p = (uint8_t * )base ;void * ptr [9 ];uint64_t total = 0 ;for (int i = 0 ;i < 9 ;++ i ) {ptr [i ]= p ;const uint64_t al = (parts [i ]+ 15 )& ~(uint64_t )15 ;p += al ;total += al ; }b .x_bf16 = (uint16_t * )ptr [0 ];b .x_f16 = (uint16_t * )ptr [1 ];b .logits = (float * )ptr [2 ];b .ids = (int * )ptr [3 ];b .weights = (float * )ptr [4 ];b .shared = (float * )ptr [5 ];b .sh_scratch = (float * )ptr [6 ];b .x_q8_0 = (uint8_t * )ptr [7 ];b .x_q8k = (uint8_t * )ptr [8 ];return total ;} 411bool moe_route (const WeightTable & tables ,const ModelGeometry & g ,int64_t layer ,int64_t k ,const MoEBuffers & b ,const float * x ,void * stream , std::string & err ,const Doorbell * db ) {using namespace strata::kernels ;const LayerView v (tables ,layer );const WeightRef * w_router = v .get ("ffn_gate_inp.weight" );if (w_router == nullptr ) {err = v .name ("ffn_gate_inp.weight" )+ " is missing" ;return false; }if (k < 1 || k > 64 ) {err = "moe_route: k must be 1..64" ;return false; } 412// ---- the router's activation. The router's weight is BF16 and that is the one `ref/moe.py` singles out. 413if (!native_bf16_projections )f32_to_bf16_bulk (x ,b .x_bf16 ,g .n_embd ,stream ); 414// ---- logits = ffn_gate_inp @ bf16(x). The weight is BF16, so this is `bf16_gemv` and not `s_gemv` - 415// and using the fp16 activation here instead is the 8.100e-03 error that flips a selection. 416// 417// **THE ROW-SPLIT VARIANT, BECAUSE THE PLAIN ONE'S PARALLELISM IS THE OUTPUT WIDTH.** `bf16_gemv` is 418// one thread per output row: for the router that is 512 threads over 48 SMs, each walking 2,560 419// elements sequentially, and it measured **0.2711 ms for a 2.6 MB weight** - about 65x its 420// memory-bound floor and the largest single item left inside the MoE after the top-10 was fixed. 421// `bf16_gemv_split` exists for precisely this case; its own header says so. Measured here: 422// LEDGER L41 -> L42. 423project_bf16 (x ,b .x_bf16 , (const uint16_t * )w_router -> data ,b .logits ,g .n_embd ,g .n_expert , true,stream ); 424// ---- routing: softmax over ALL experts, stable descending argsort with ties by index, gather, renormalise 425// the native fused router is canonical-512x10 only; anything else takes the generic top-k kernel 426if (native_router_enabled ()&& g .n_expert == 512 && k == 10 ) { 427try {native_router_top10 (b .logits ,b .ids ,b .weights ,stream ); } 428catch (const std::exception & error ) {err = v .name ("router" )+ ": " + error .what ();return false; } 429}else router_top10 (b .logits ,1 , (int )g .n_expert , (int )k ,b .ids ,b .weights ,stream ); 430// ---- THE DOORBELL, AND IT IS THE WHOLE POINT OF THE PROTOCOL. The routed experts' INPUT (`x`) and the 431// miss list (`ids`, `weights`) are published to the host HERE, before anything that depends on them, 432// so a CPU pool can start on them while the GPU keeps working. Both the copy and the ring are 433// captured into `G[l]` like anything else - a kernel writing mapped pinned memory, which round 209 434// measured the host seeing 0.050 ms into a 39.8 ms graph. 435if (db != nullptr && g_publish_kernel ) { 436 strata::kernels::doorbell_publish (x ,b .ids ,b .weights ,g .n_embd ,k ,db -> d_x_f ,db -> d_ids ,db -> d_weights ,db -> d_seq , 437stream ); 438}else if (db != nullptr ) {if (cudaMemcpyAsync (db -> d_x_f ,x , (size_t )g .n_embd * 4 ,cudaMemcpyDeviceToDevice , (cudaStream_t )stream )!= cudaSuccess || cudaMemcpyAsync (db -> d_ids ,b .ids , (size_t )k * 4 ,cudaMemcpyDeviceToDevice , (cudaStream_t )stream )!= cudaSuccess || cudaMemcpyAsync (db -> d_weights ,b .weights , (size_t )k * 4 ,cudaMemcpyDeviceToDevice , (cudaStream_t )stream )!= cudaSuccess ) {err = "moe_route: the doorbell handoff copy failed" ;return false; } 439// THE RING IS LAST, so a host that sees it knows every byte above is in place. Ordering within a 440// stream is what makes that true; it is not a timing assumption. 441// THE RING LIVES IN A .cu: this file is compiled by the HOST compiler, where `__global__` and `<<<>>>` do 442// not exist. The sequence value is read from the HOST copy and incremented, which is what makes the 443// write idempotent across replays of the same graph - a captured literal would ring the same number 444// forever and the host would never see a change. 445strata::kernels::doorbell_ring (db -> d_seq ,stream ); }return true;} 446// The verify window's routing: n tokens' logits in one BF16 projection and their top-k in one launch, each token 447// bitwise what `moe_route` gives it (the projection is the same kernel per column, the top-k kernel is per token). 448// Anything else (a native router, the canonical BF16 GEMVs, a doorbell) takes the per-token `moe_route`. 449bool moe_route_window (const WeightTable & tables ,const ModelGeometry & g ,int64_t layer ,int64_t k ,const MoEBuffers & b , 450const float * x ,float * logits ,int32_t * ids ,float * weights ,int n ,void * stream , std::string & err ) { 451using namespace strata::kernels ; 452const bool batched = native_bf16_projections && !(native_router_enabled ()&& g .n_expert == 512 && k == 10 )&& 453 !std::getenv ("STRATA_ROUTE_PER_TOKEN" ); 454if (!batched || n == 1 ) { 455for (int t = 0 ;t < n ;++ t ) { 456MoEBuffers mb = b ; 457mb .logits = logits + t * g .n_expert ;mb .ids = ids + t * k ;mb .weights = weights + t * k ; 458if (!moe_route (tables ,g ,layer ,k ,mb ,x + t * g .n_embd ,stream ,err ,nullptr ))return false; 459 } 460return true; 461 } 462const LayerView v (tables ,layer ); 463const WeightRef * w_router = v .get ("ffn_gate_inp.weight" ); 464if (w_router == nullptr ) {err = v .name ("ffn_gate_inp.weight" )+ " is missing" ;return false; } 465if (std::getenv ("STRATA_ROUTE_PROJ_PER_TOKEN" )) 466for (int t = 0 ;t < n ;++ t ) 467bf16_gemv_fp32_mmvf (x + t * g .n_embd , (const uint16_t * )w_router -> data ,logits + t * g .n_expert ,g .n_embd , 468g .n_expert ,stream ); 469else 470bf16_gemv_fp32_mmvf_cols (x , (const uint16_t * )w_router -> data ,logits ,g .n_embd ,g .n_expert ,n ,stream ); 471router_top10 (logits ,n , (int )g .n_expert , (int )k ,ids ,weights ,stream ); 472return true; 473} 474bool moe_shared (const WeightTable & tables ,const ModelGeometry & g ,int64_t layer ,const MoEBuffers & b ,const float * x ,void * stream , std::string & err ) {using namespace strata::kernels ;const LayerView v (tables ,layer );const WeightRef * w_ginp = v .get ("ffn_gate_inp_shexp.weight" );const WeightRef * w_sgate = v .get ("ffn_gate_shexp.weight" );const WeightRef * w_sup = v .get ("ffn_up_shexp.weight" );const WeightRef * w_sdown = v .get ("ffn_down_shexp.weight" );const char * missing = !w_ginp ?"ffn_gate_inp_shexp.weight" : !w_sgate ?"ffn_gate_shexp.weight" : !w_sup ?"ffn_up_shexp.weight" : !w_sdown ?"ffn_down_shexp.weight" :nullptr ;if (missing ) {err = v .name (missing )+ " is missing" ;return false; } 475// ---- the shared expert. Its three weights are quantized, so they need their planes. 476SForm f_gate ,f_up ,f_down ;if (!sform_of (* w_sgate ,f_gate ,v .name ("ffn_gate_shexp.weight" ),err ))return false;if (!sform_of (* w_sup ,f_up ,v .name ("ffn_up_shexp.weight" ),err ))return false;if (!sform_of (* w_sdown ,f_down ,v .name ("ffn_down_shexp.weight" ),err ))return false;Planes p_gate ,p_up ,p_down ;if (!plane_ptrs (* w_sgate ,v .name ("ffn_gate_shexp.weight" ),p_gate ,err ))return false;if (!plane_ptrs (* w_sup ,v .name ("ffn_up_shexp.weight" ),p_up ,err ))return false;if (!plane_ptrs (* w_sdown ,v .name ("ffn_down_shexp.weight" ),p_down ,err ))return false; 477// `ffn_gate_inp_shexp` is a 1-D BF16 vector, so THE ARENA HOLDS 2 BYTES PER ELEMENT, not 4 - the loader 478// re-rounded it to the engine form like any other BF16 tensor. Reading it as f32 is 5120 bytes past the 479// end of a 5120-byte tensor inside a 4.5 GiB arena, where nothing faults. Refuse here rather than trust 480// the layout check to have run: this function is reachable without it. 481if (w_ginp -> kind != WeightKind ::Bf16InF32 ) {err = v .name ("ffn_gate_inp_shexp.weight" )+ " is engine form " + std::to_string ((int )w_ginp -> kind )+ " (" + std::to_string (w_ginp -> bytes )+ " B); the scalar gate reads it as bf16, so it must be form 1 (" + std::to_string ((uint64_t )g .n_embd * 2 )+ " B)" ;return false; } 482// THE SHARED EXPERT'S WEIGHTS ARE NOT ONE FAMILY: `ffn_gate_shexp` is Q2_0 on 21 layers and a K-quant on 483// the rest, `ffn_up_shexp` Q2_0 on 13, and `ffn_down_shexp` is LEGACY in every layer (IQ4_NL/Q4_0/Q5_0/ 484// Q8_0/Q2_0, `n_in` 640 so Q8_K is impossible). So BOTH quantized images of the activation are produced 485// and each projection takes the one its own form asks for. 486// ONE pass over `x` produces the bf16 image and both quantized images (was three kernels): which quantized 487// one is wanted is a property of the TENSOR and the pack mixes them by layer, so both are produced. 488if (!w_sgate -> native_data || !w_sup -> native_data ) { 489#if defined(STRATA_EXPERIMENTAL_SM60 ) 490if (strata::kernels::fuse_decode ()) { 491quantize_act_images (x ,g .n_embd ,b .x_q8_0 ,b .x_q8k ,b .x_bf16 ,stream );// ONE pass, was three kernels 492 }else 493#endif 494 { 495f32_to_bf16_bulk (x ,b .x_bf16 ,g .n_embd ,stream ); 496quantize_q8_K (x ,b .x_q8k ,g .n_embd ,stream ); 497quantize_q8_0 (x ,b .x_q8_0 ,g .n_embd ,stream ); 498 } 499 }else { 500f32_to_bf16_bulk (x ,b .x_bf16 ,g .n_embd ,stream ); 501 } 502NativeSharedWeights native ; 503native .gate_type = w_sgate -> native_type ;native .gate_data = w_sgate -> native_data ; 504native .up_type = w_sup -> native_type ;native .up_data = w_sup -> native_data ; 505native .down_type = w_sdown -> native_type ;native .down_data = w_sdown -> native_data ; 506// The NativeDense owner publishes one shared workspace for this ordered session stream. 507native .q8_1 = w_sgate -> native_q8_1 ?w_sgate -> native_q8_1 : 508w_sup -> native_q8_1 ?w_sup -> native_q8_1 :w_sdown -> native_q8_1 ; 509try { 510shared_expert (b .x_q8_0 ,b .x_q8k ,b .x_bf16 ,f_gate ,p_gate .codes ,p_gate .scales ,p_gate .offset , 511f_up ,p_up .codes ,p_up .scales ,p_up .offset ,f_down ,p_down .codes ,p_down .scales , 512p_down .offset , (const uint16_t * )w_ginp -> data ,b .sh_scratch ,b .shared , 513g .n_embd ,g .n_ff ,/*tpr=*/ 32 ,stream ,x ,& native ); 514 }catch (const std::exception & error ) { 515err = v .name ("shared_expert" )+ ": " + error .what (); 516return false; 517 } 518return true; 519} 520bool moe_combine_parts (const ModelGeometry & g ,int64_t layer ,int64_t k ,const MoEBuffers & b ,const float * parts , 521float * out ,void * stream , std::string & err ) { 522using namespace strata::kernels ; 523if (k < 1 || k > 64 ) {err = "moe_finish: k must be 1..64" ;return false; } 524// ---- the combination: sum of w[i] * parts[i], plus the shared output ADDED PLAIN. 525// 526// **`parts` IS COMBINED WITH `b.weights`, WHICH `moe_route` WROTE FOR *THIS* LAYER.** That is the whole 527// reason this is a separate function: a caller that passes the previous layer's expert vectors gets 528// `sum_j w_l[j] * expert_{ids_{l-1},j}(x_{l-1})`, which is finite, fluent and not the model. 529try { 530if (native_moe_combine_enabled ())native_moe_combine (parts ,b .weights ,b .shared ,out ,g .n_embd ,k ,stream ); 531else moe_combine (parts ,b .weights ,b .shared ,out ,g .n_embd ,k ,stream ); 532}catch (const std::exception & error ) { 533err = "blk." + std::to_string (layer )+ ".moe_combine" + ": " + error .what (); 534return false; 535} 536return true;} 537bool moe_finish (const WeightTable & tables ,const ModelGeometry & g ,int64_t layer ,int64_t k ,const MoEBuffers & b , 538const float * x ,const float * parts ,float * out ,void * stream , std::string & err ) { 539if (k < 1 || k > 64 ) {err = "moe_finish: k must be 1..64" ;return false; } 540if (!moe_shared (tables ,g ,layer ,b ,x ,stream ,err ))return false; 541return moe_combine_parts (g ,layer ,k ,b ,parts ,out ,stream ,err ); 542} 543bool layer_verify_compatible (std::string & why ) { 544// Plan v0.3 P6: the verify window reproduces exactly this configuration's per-token arithmetic. 545if (!native_bf16_projections )why = "the native BF16 projections are off" ; 546else if (!g_fused_gr )why = "the fused hyper-connection read is off" ; 547else if (!g_fused_gdn || !strata::kernels::native_gdn_enabled ())why = "the fused native GDN kernels are off" ; 548else if (!g_fast_attn || native_flash_attn_short )why = "the split-K decode attention is off" ; 549else if (!g_fast_select )why = "the block top-k selection is off" ; 550else if (!strata::kernels::native_qsa_indexer_enabled ())why = "the native QSA indexer is off" ; 551else return true; 552return false; 553} 554void layer_set_publish_kernel (bool enabled ) {g_publish_kernel = enabled ; } 555void layer_set_fused_gdn (bool enabled ) {g_fused_gdn = enabled ; } 556void layer_set_fast_select (bool enabled ) {g_fast_select = enabled ; } 557void layer_set_fast_attn (bool enabled ) {g_fast_attn = enabled ; } 558void layer_set_fused_gr (bool enabled ) {g_fused_gr = enabled ; } 559bool layer_fused_gr () {return g_fused_gr ; } 560void layer_set_shared_early (bool enabled ) {g_shared_early = enabled ; } 561bool layer_shared_early () {return g_shared_early ; } 562bool moe_layer (const WeightTable & tables ,const ModelGeometry & g ,int64_t layer ,int64_t k ,const MoEBuffers & b ,const float * x ,const float * parts ,float * out ,void * stream , std::string & err ,const Doorbell * db ) { 563// The two halves in sequence. `moe_route` publishes `ids`/`weights` for THIS layer and `moe_finish` 564// combines `parts` with them, so a caller of this wrapper must have `parts` ready BEFORE the call - which 565// is what `session_token` (the uncaptured path) does and what the captured loop CANNOT, which is why the 566// loop uses the halves separately. 567if (!moe_route (tables ,g ,layer ,k ,b ,x ,stream ,err ,db ))return false;return moe_finish (tables ,g ,layer ,k ,b ,x ,parts ,out ,stream ,err );} 568// ================================ the QSA mixer ================================ 569namespace {using strata::kernels::QsaIndexerBuffers ;using strata::kernels::QsaShapes ; 570// `qsa_shapes(g)` (layout.hpp): the geometry the QSA kernels want, every field from the model's geometry 571uint64_t align_up16 (uint64_t n ) {return (n + 15 )& ~15ull ; } 572/// One cursor over an arena, so every region is 16-byte aligned without a list of hand-added offsets. 573struct Cursor {uint8_t * p ;uint64_t used = 0 ;template < typename T > T * take (uint64_t count ) {T * r = (T * ) (p + used );used = align_up16 (used + count * sizeof (T ));return r ; }uint8_t * take_bytes (uint64_t n ) {uint8_t * r = p + used ;used = align_up16 (used + n );return r ; }}; 574// `TPR` and `gemv_quantized` live in the FIRST anonymous namespace, above, because `gdn_layer` needs the 575// dispatch too and the two must not be able to drift. 576} 577// namespace 578namespace { 579// KV streaming (docs/kv-streaming-design.md): 0 keeps every cell in VRAM. 580int64_t g_kv_resident = 0 ; 581uint64_t g_kv_host_bytes = 0 ; 582 583// The KV host copy: pinned and device-mapped. cudaHostAlloc is the default, but under WSL2 the driver caps what 584// cudaHostAlloc(Mapped) may pin at about 1 GiB in all, while cudaHostRegister of ordinary memory is not capped there: 585// the expert arena registers tens of GiB the same way (pinned.cu). So under WSL2, detected as generate.cpp's 586// under_wddm() does (/dev/dxg, the device its GPU goes through to the Windows driver), the copy is anonymous memory 587// registered Portable|Mapped before any page is touched, which also leaves WSL's small cudaHostAlloc budget to the 588// staging buffers. Elsewhere cudaHostAlloc stays first. Either way the other method is the fallback when the first 589// is refused. STRATA_KV_HOST_REGISTER=1/0 forces registering first or cudaHostAlloc first. Like the cudaHostAlloc 590// copy it lives as long as the process. 591uint8_t * kv_host_alloc (uint64_t bytes ) { 592auto host_alloc = [](uint64_t n )-> uint8_t * { 593uint8_t * h = nullptr ; 594if (strata::core::host_alloc_guarded ((void ** )& h ,n ,cudaHostAllocMapped |cudaHostAllocPortable )== cudaSuccess )return h ; 595 (void )cudaGetLastError (); 596return nullptr ; 597 }; 598#ifdef _WIN32 599return host_alloc (bytes ); 600#else 601static const bool register_first = [] { 602const char * e = std::getenv ("STRATA_KV_HOST_REGISTER" ); 603if (e != nullptr && (e [0 ]== '0' || e [0 ]== '1' ))return e [0 ]== '1' ; 604return std::filesystem::exists ("/dev/dxg" ); 605 }(); 606auto register_anon = [](uint64_t n )-> uint8_t * { 607void * m = mmap (nullptr , (size_t )n ,PROT_READ |PROT_WRITE ,MAP_PRIVATE |MAP_ANONYMOUS ,-1 ,0 ); 608if (m == MAP_FAILED )return nullptr ; 609if (cudaHostRegister (m , (size_t )n ,cudaHostRegisterPortable |cudaHostRegisterMapped )!= cudaSuccess ) { 610 (void )cudaGetLastError (); 611munmap (m , (size_t )n ); 612return nullptr ; 613 } 614static bool said = false; 615if (!said ) { 616 std::fprintf (stderr ,"strata: KV streaming: the host copy is pinned with cudaHostRegister\n" ); 617said = true; 618 } 619return (uint8_t * )m ; 620 }; 621if (register_first ) { 622if (uint8_t * m = register_anon (bytes ))return m ; 623return host_alloc (bytes ); 624 } 625if (uint8_t * h = host_alloc (bytes ))return h ; 626return register_anon (bytes ); 627#endif 628} 629 630// ---- the elastic K/V (--kv-grow): one VMM range per state, each pool array at a chunk boundary in it 631bool g_kv_elastic = false; 632int64_t g_kv_elastic_init = 16384 ; 633struct ElasticPool { 634 strata::core::VmmRange range ; 635 std::vector < uint64_t > off ,per_slot ;// each array's offset in the range (whole chunks) and bytes per page slot 636int64_t n_slots = 0 ,page_size = 0 ; 637}; 638std::vector < std::unique_ptr < ElasticPool >> g_pools ; 639 640int64_t pool_chunks (const ElasticPool & p ,size_t a ,int64_t slots ) { 641const uint64_t G = strata::core::vmm_granularity (); 642return (int64_t ) (((uint64_t )slots * p .per_slot [a ]+ G - 1 ) /G ); 643} 644int64_t pool_slots (const ElasticPool & p ,int64_t cells ) { 645return std::min < int64_t > (p .n_slots , std::max < int64_t > ((cells + p .page_size - 1 ) /p .page_size ,1 )); 646} 647/// Whole page slots every array of the pool has mapped. 648int64_t pool_slots_mapped (const ElasticPool & p ) { 649const uint64_t G = strata::core::vmm_granularity (); 650int64_t slots = p .n_slots ; 651for (size_t a = 0 ;a < p .off .size ();++ a ) { 652const int64_t c0 = (int64_t ) (p .off [a ] /G ); 653const int64_t end = a + 1 < p .off .size () ? (int64_t ) (p .off [a + 1 ] /G ) :p .range .chunks (); 654int64_t c = 0 ; 655while (c0 + c < end && p .range .mapped (c0 + c ))++ c ; 656slots = std::min < int64_t > (slots , (int64_t ) ((uint64_t )c * G /p .per_slot [a ])); 657 } 658return slots ; 659} 660bool pool_grow (ElasticPool & p ,int64_t cells ,const std::function < strata::core::VmmChunk ()>& take ) { 661const uint64_t G = strata::core::vmm_granularity (); 662const int64_t slots = pool_slots (p ,cells ); 663for (size_t a = 0 ;a < p .off .size ();++ a ) { 664const int64_t c0 = (int64_t ) (p .off [a ] /G ),c1 = c0 + pool_chunks (p ,a ,slots ); 665 std::vector < int64_t > fresh ; 666for (int64_t c = c0 ;c < c1 ;++ c ) 667if (!p .range .mapped (c ))fresh .push_back (c ); 668if (fresh .empty ())continue ; 669if (!p .range .map_range (c0 ,c1 ,take )) { 670 std::fprintf (stderr ,"strata: the elastic K/V could not map %zu chunks (the driver has no VRAM left)\n" , 671fresh .size ()); 672return false; 673 } 674// what the chunk held before (another pool's cells, an expert) is not K/V: zeroed, as a new session is 675for (const int64_t c :fresh ) 676if (cudaMemset (p .range .base ()+ (uint64_t )c * G ,0 , (size_t )G )!= cudaSuccess ) { 677 std::fprintf (stderr ,"strata: the elastic K/V could not clear a chunk: %s\n" , 678cudaGetErrorString (cudaGetLastError ())); 679return false; 680 } 681 } 682return true; 683} 684}// namespace 685 686void qsa_set_kv_elastic (bool enabled ,int64_t init_cells ) { 687g_kv_elastic = enabled && strata::core::vmm_available (); 688if (init_cells > 0 )g_kv_elastic_init = init_cells ; 689} 690bool qsa_kv_elastic () {return g_kv_elastic ; } 691int64_t qsa_kv_elastic_cells () { 692int64_t cells = std::numeric_limits < int64_t > ::max (); 693for (const auto & p :g_pools )cells = std::min < int64_t > (cells ,pool_slots_mapped (* p )* p -> page_size ); 694return cells ; 695} 696int64_t qsa_kv_elastic_need (int64_t cells ) { 697const uint64_t G = strata::core::vmm_granularity (); 698int64_t n = 0 ; 699for (const auto & p :g_pools ) { 700const int64_t slots = pool_slots (* p ,cells ); 701for (size_t a = 0 ;a < p -> off .size ();++ a ) { 702const int64_t c0 = (int64_t ) (p -> off [a ] /G ),c1 = c0 + pool_chunks (* p ,a ,slots ); 703for (int64_t c = c0 ;c < c1 ;++ c )n += !p -> range .mapped (c ); 704 } 705 } 706return n ; 707} 708bool qsa_kv_elastic_grow (int64_t cells ,const std::function < strata::core::VmmChunk ()>& take ) { 709for (auto & p :g_pools ) 710if (!pool_grow (* p ,cells ,take ))return false; 711return cudaDeviceSynchronize ()== cudaSuccess ; 712} 713int64_t qsa_kv_elastic_shrink (int64_t cells ,const std::function < void (strata::core::VmmChunk )>& give ) { 714const uint64_t G = strata::core::vmm_granularity (); 715int64_t n = 0 ; 716for (auto & p :g_pools ) { 717const int64_t slots = pool_slots (* p ,cells ); 718for (size_t a = 0 ;a < p -> off .size ();++ a ) { 719const int64_t c0 = (int64_t ) (p -> off [a ] /G ),c1 = c0 + pool_chunks (* p ,a ,slots ); 720const int64_t end = a + 1 < p -> off .size () ? (int64_t ) (p -> off [a + 1 ] /G ) :p -> range .chunks (); 721for (int64_t c = c1 ;c < end ;++ c ) 722if (const strata::core::VmmChunk h = p -> range .unmap (c )) {give (h );++ n ; } 723 } 724 } 725return n ; 726} 727uint64_t qsa_kv_elastic_mapped_bytes () { 728uint64_t n = 0 ; 729for (const auto & p :g_pools )n += (uint64_t )p -> range .mapped_count ()* strata::core::vmm_granularity (); 730return n ; 731} 732uint64_t qsa_kv_elastic_full_bytes () { 733uint64_t n = 0 ; 734for (const auto & p :g_pools )n += (uint64_t )p -> range .chunks ()* strata::core::vmm_granularity (); 735return n ; 736} 737namespace { 738 739/// How one state holds its K/V: `mode` as in QsaState::kv_mode, `slots` VRAM pages of `pages` logical ones. 740struct KvPlan { 741int mode = 0 ; 742int64_t pages = 0 ,slots = 0 ,pooled_rows = 0 ; 743}; 744KvPlan kv_plan (const QsaShapes & s ,int64_t max_cells ,int64_t ring_cells ) { 745KvPlan p ; 746p .pages = (max_cells + s .page_size - 1 ) /s .page_size ; 747p .slots = p .pages ; 748p .pooled_rows = max_cells /s .idx_block + 2 ; 749if (g_kv_resident <=0 || ring_cells < 0 )return p ;// ring_cells < 0: always fully resident 750// A/B only: STRATA_KV_RING_OFF keeps the drafter fully resident, STRATA_KV_MAIN_OFF the main layers 751static const bool ring_off = std::getenv ("STRATA_KV_RING_OFF" )!= nullptr ; 752static const bool main_off = std::getenv ("STRATA_KV_MAIN_OFF" )!= nullptr ; 753if (ring_cells > 0 ?ring_off :main_off )return p ; 754if (ring_cells > 0 ) { 755const int64_t r = (ring_cells + s .page_size - 1 ) /s .page_size ; 756if (r < p .pages ) {p .mode = 2 ;p .slots = r ;p .pooled_rows = 2 ; }// the drafter has no indexer 757 }else { 758const int64_t r = (std::max (g_kv_resident ,qsa_kv_resident_min ())+ s .page_size - 1 ) /s .page_size ; 759if (r < p .pages ) {p .mode = 1 ;p .slots = r ; } 760 } 761return p ; 762} 763uint64_t kv_pool_bytes (const QsaShapes & s ,int64_t pages ,bool hybrid ,bool int8 ) { 764if (hybrid ) {// K8V4: the INT8 K half (codes + scales) plus the Q4_0 V half (kv_q4.hpp's rotation) 765const uint64_t rows = (uint64_t )pages * s .page_size * s .n_head_kv ; 766return rows * (uint64_t )s .head_dim + rows * (uint64_t ) (s .head_dim / strata::kernels::KV_Q8_GROUP )* 2 + 767rows * strata::kernels::kv_q4_bytes_per_head ((int )s .head_dim )+ 64 ; 768 } 769if (g_kv_q4 )return (uint64_t )pages * s .page_size * strata::kernels::kv_q4_bytes_per_cell (s )+ 64 ; 770return int8 ? (uint64_t )pages * s .page_size * strata::kernels::kv_q8_bytes_per_cell (s )+ 64 771 : (uint64_t )pages * s .n_head_kv * s .page_size * s .head_dim * 2 * 2 ; 772} 773}// namespace 774 775void qsa_set_kv_resident (int64_t cells ) {g_kv_resident = cells > 0 ?cells :0 ; } 776int64_t qsa_kv_resident () {return g_kv_resident ; } 777// The least KV window a streamed session keeps in VRAM (cells): 4096 (was 20480; a window of 4096 and of 8192 gave the same tokens as 20480 with the cache fixed and route tail 778// skip off, 2 requests at 128K, 20K- and 8K-token prompts; setup still writes 32768, fit_start walks 20480 / 8192 / 4096 only on a card that is short). STRATA_KV_RESIDENT_MIN=N overrides (the 779// selection reads at most idx_top_k + idx_block - 1 cells per row, so a window of a few thousand cells holds it; the pool must hold the blocks of every row of a verify window). 780int64_t qsa_kv_resident_min () { 781static const int64_t v = [] { 782const char * e = std::getenv ("STRATA_KV_RESIDENT_MIN" ); 783const long long n = e != nullptr ? std::atoll (e ) :0 ; 784#if defined(STRATA_GPU_METAL ) 785return n >=1024 ? (int64_t )n : (int64_t )20480 ;// a Mac keeps the old floor: its pool is the host's RAM (strata/core/spill_gate.hpp) 786#else 787return n >=1024 ? (int64_t )n : (int64_t )4096 ; 788#endif 789 }(); 790return v ; 791} 792uint64_t qsa_kv_host_bytes () {return g_kv_host_bytes ; } 793 794uint64_t qsa_state_bytes (const ModelGeometry & g ,int64_t max_cells ,bool with_rope ,int64_t ring_cells ) { 795const QsaShapes s = qsa_shapes (g ); 796const KvPlan p = kv_plan (s ,max_cells ,ring_cells ); 797uint64_t n = 0 ; 798if (!(g_kv_elastic && p .mode == 0 ))// the elastic K/V's pools are in their own VMM range 799n += kv_pool_bytes (s ,p .slots ,g_kv_hybrid && ring_cells <=0 , 800g_kv_int8 || g_kv_hybrid )+ 4 * 16 ;// K/V pools (the VRAM slots) 801n += (uint64_t )p .pages * 4 ;// page_table 802if (p .mode == 1 )n += strata::kernels::kv_stream_map_bytes (p .slots )+ 6 * 16 ;// the residency map 803n += (uint64_t ) (s .idx_block - 1 )* s .idx_dim * 4 ;// tail 804n += (uint64_t )s .idx_dim * 4 ;// dead 805n += (uint64_t )p .pooled_rows * s .idx_dim * 4 ;// pooled 806n += 16 ;// block_pos 807if (with_rope )n += (uint64_t )max_cells * (s .n_rot /2 )* 4 * 2 ;// cos + sin tables 808n += strata::kernels::qsa_step_bytes ()+ 16 ;// counts and aligned attention status 809n += (uint64_t )s .n_head * 4 ;// pos_dev 810return align_up16 (n )+ 256 ; 811} 812 813uint64_t qsa_state_init (const ModelGeometry & g ,int64_t max_cells ,void * base ,QsaState & st , 814const QsaState * share_rope ,int64_t ring_cells ) { 815const QsaShapes s = qsa_shapes (g ); 816const KvPlan p = kv_plan (s ,max_cells ,ring_cells ); 817const int64_t pages = p .pages ; 818Cursor c {(uint8_t * )base }; 819st .kv_int8 = g_kv_int8 && !g_kv_q4 ; 820st .kv_q4 = g_kv_q4 ; 821// Hybrid K8V4, main layers only (the drafter's state is created with the globals toggled to INT8 - 822// mtp.cpp). A streamed one keeps its host copy in the same three runs (kv_stream.cu, kKvHybrid). 823if (g_kv_hybrid && ring_cells <=0 ) { 824st .kv_hybrid = true; 825st .kv_int8 = false; 826st .kv_q4 = false; 827 } 828st .kv_rot = st .kv_q4 || (st .kv_int8 && g_kv_int8_rot );// K8V4 rotates only V (below) 829st .kv_mode = p .mode ; 830st .n_slots = p .slots ; 831const uint64_t rows = (uint64_t )p .slots * s .n_head_kv * s .page_size ;// VRAM rows: the slots 832const uint64_t q4_row = strata::kernels::kv_q4_bytes_per_head ((int )s .head_dim ); 833st .kv_elastic = -1 ; 834if (g_kv_elastic && p .mode == 0 ) { 835// the elastic K/V: each array at a chunk boundary of the state's own range, the first cells mapped 836const uint64_t slot_rows = (uint64_t )s .n_head_kv * s .page_size ; 837const uint64_t scale_row = (uint64_t ) (s .head_dim / strata::kernels::KV_Q8_GROUP )* 2 ; 838 std::vector < uint64_t > per ;// bytes per page slot of each array, in the order they are assigned below 839if (st .kv_hybrid )per = {slot_rows * s .head_dim ,slot_rows * scale_row ,slot_rows * q4_row }; 840else if (st .kv_q4 )per = {slot_rows * q4_row ,slot_rows * q4_row }; 841else if (st .kv_int8 )per = {slot_rows * s .head_dim ,slot_rows * s .head_dim ,slot_rows * scale_row ,slot_rows * scale_row }; 842else per = {slot_rows * s .head_dim * 2 ,slot_rows * s .head_dim * 2 }; 843auto pool = std::make_unique < ElasticPool > (); 844const uint64_t G = strata::core::vmm_granularity (); 845uint64_t at = 0 ; 846for (const uint64_t b :per ) { 847pool -> off .push_back (at ); 848at += ((uint64_t )p .slots * b + G - 1 ) /G * G ; 849 } 850pool -> per_slot = per ; 851pool -> n_slots = p .slots ; 852pool -> page_size = s .page_size ; 853if (!pool -> range .reserve (at )|| !pool_grow (* pool ,g_kv_elastic_init , [] {return (strata::core::VmmChunk )0 ; })) { 854 std::fprintf (stderr ,"strata: the elastic K/V could not reserve or map its pools\n" ); 855return 0 ; 856 } 857uint8_t * b = pool -> range .base (); 858const uint64_t * o = pool -> off .data (); 859if (st .kv_hybrid ) {st .k_q = (int8_t * ) (b + o [0 ]);st .k_scale = (uint16_t * ) (b + o [1 ]);st .v_q4 = b + o [2 ]; } 860else if (st .kv_q4 ) {st .k_q4 = b + o [0 ];st .v_q4 = b + o [1 ]; } 861else if (st .kv_int8 ) { 862st .k_q = (int8_t * ) (b + o [0 ]); 863st .v_q = (int8_t * ) (b + o [1 ]); 864st .k_scale = (uint16_t * ) (b + o [2 ]); 865st .v_scale = (uint16_t * ) (b + o [3 ]); 866 }else {st .k_pool = (uint16_t * ) (b + o [0 ]);st .v_pool = (uint16_t * ) (b + o [1 ]); } 867st .kv_elastic = (int32_t )g_pools .size (); 868g_pools .push_back (std::move (pool )); 869 }else if (st .kv_hybrid ) { 870st .k_q = c .take < int8_t > (rows * s .head_dim ); 871st .k_scale = c .take < uint16_t > (rows * (s .head_dim / strata::kernels::KV_Q8_GROUP )); 872st .v_q4 = c .take < uint8_t > (rows * q4_row ); 873 }else if (st .kv_q4 ) { 874st .k_q4 = c .take < uint8_t > (rows * q4_row ); 875st .v_q4 = c .take < uint8_t > (rows * q4_row ); 876 }else if (st .kv_int8 ) {// st, not the global: the drafter's ring is INT8 under --kv k8v4 too 877st .k_q = c .take < int8_t > (rows * s .head_dim ); 878st .v_q = c .take < int8_t > (rows * s .head_dim ); 879st .k_scale = c .take < uint16_t > (rows * (s .head_dim / strata::kernels::KV_Q8_GROUP )); 880st .v_scale = c .take < uint16_t > (rows * (s .head_dim / strata::kernels::KV_Q8_GROUP )); 881 }else { 882st .k_pool = c .take < uint16_t > (rows * s .head_dim ); 883st .v_pool = c .take < uint16_t > (rows * s .head_dim ); 884 } 885st .page_table = c .take < int32_t > ((uint64_t )pages ); 886st .n_pages = pages ; 887st .max_cells = max_cells ; 888st .map = strata::kernels::KvStreamMap {}; 889st .map .page_table = st .page_table ; 890st .map .n_blocks = pages ; 891st .map .n_slots = p .slots ; 892if (p .mode == 1 ) { 893st .map .slot_block = c .take < int32_t > ((uint64_t )p .slots ); 894st .map .slot_stamp = c .take < int32_t > ((uint64_t )p .slots ); 895st .map .slot_ref = c .take < int32_t > ((uint64_t )p .slots ); 896st .map .miss_block = c .take < int32_t > ((uint64_t )p .slots ); 897st .map .miss_slot = c .take < int32_t > ((uint64_t )p .slots ); 898st .map .ctl = c .take < int32_t > ((uint64_t ) strata::kernels::kKvCtlInts ); 899 } 900st .idx_tail = c .take < float > ((uint64_t ) (s .idx_block - 1 )* s .idx_dim ); 901st .idx_dead = c .take < float > ((uint64_t )s .idx_dim ); 902st .idx_pooled_rows = p .pooled_rows ; 903st .idx_pooled = c .take < float > ((uint64_t )p .pooled_rows * s .idx_dim ); 904st .idx_block_pos = c .take < int32_t > (1 ); 905if (share_rope != nullptr ) { 906st .cos_tab = share_rope -> cos_tab ; 907st .sin_tab = share_rope -> sin_tab ; 908 }else { 909st .cos_tab = c .take < float > ((uint64_t )max_cells * (s .n_rot /2 )); 910st .sin_tab = c .take < float > ((uint64_t )max_cells * (s .n_rot /2 )); 911 } 912st .step = c .take < int32_t > ((uint64_t ) strata::kernels::kStepCount ); 913st .attention_status = c .take < int32_t > (1 ); 914st .pos_dev = c .take < int32_t > ((uint64_t )s .n_head ); 915// the pinned staging the uploads copy FROM - see the note on `host_step` in the header 916if (strata::core::host_alloc_guarded ((void ** )& st .host_step , strata::kernels::qsa_step_bytes ()+ sizeof (int32_t ), 917cudaHostAllocMapped |cudaHostAllocPortable )!= cudaSuccess || 918 strata::core::host_alloc_guarded ((void ** )& st .host_pos , (size_t )s .n_head * 4 ,cudaHostAllocMapped |cudaHostAllocPortable )!= 919cudaSuccess ) { 920return 0 ;// the caller sees a zero byte count; a half-built state is worse than none 921 } 922st .host_step [strata::kernels::kStepCount ]= 0 ; 923// KV streaming: the authoritative K/V of every cell, pinned and device-mapped, in the identity layout 924st .host = strata::kernels::KvHostPools {}; 925if (p .mode != 0 ) { 926const uint64_t hrows = (uint64_t )pages * s .n_head_kv * s .page_size ; 927const uint64_t bytes = (uint64_t )pages * strata::kernels::kv_block_bytes (s ,qsa_kv_format (st ))+ 4 * 256 ; 928uint8_t * h = nullptr ; 929uint8_t * d = nullptr ; 930if ((h = kv_host_alloc (bytes ))== nullptr || 931cudaHostGetDevicePointer ((void ** )& d ,h ,0 )!= cudaSuccess ) { 932// both cudaHostRegister and cudaHostAlloc were refused (kv_host_alloc): usually not enough free RAM 933if (p .mode == 1 ) std::fprintf (stderr ,"strata: KV streaming: cannot pin %.2f GiB of RAM for a layer's KV copy " 934"(%.2f GiB pinned so far): RAM or the driver refused to pin it - lower the context, " 935"or run without --kv-resident\n" , (double )bytes /1073741824.0 , 936 (double )g_kv_host_bytes /1073741824.0 ); 937return 0 ; 938 } 939g_kv_host_bytes += bytes ; 940Cursor hc {d }; 941if (st .kv_hybrid ) { 942st .host .k_q = hc .take < int8_t > (hrows * s .head_dim ); 943st .host .k_scale = hc .take < uint16_t > (hrows * (s .head_dim / strata::kernels::KV_Q8_GROUP )); 944st .host .v_q4 = hc .take < uint8_t > (hrows * q4_row ); 945 }else if (st .kv_q4 ) { 946st .host .k_q4 = hc .take < uint8_t > (hrows * q4_row ); 947st .host .v_q4 = hc .take < uint8_t > (hrows * q4_row ); 948 }else if (st .kv_int8 ) { 949st .host .k_q = hc .take < int8_t > (hrows * s .head_dim ); 950st .host .v_q = hc .take < int8_t > (hrows * s .head_dim ); 951st .host .k_scale = hc .take < uint16_t > (hrows * (s .head_dim / strata::kernels::KV_Q8_GROUP )); 952st .host .v_scale = hc .take < uint16_t > (hrows * (s .head_dim / strata::kernels::KV_Q8_GROUP )); 953 }else { 954st .host .k_pool = hc .take < uint16_t > (hrows * s .head_dim ); 955st .host .v_pool = hc .take < uint16_t > (hrows * s .head_dim ); 956 } 957 } 958// THE ROPE TABLE IS BUILT ON THE HOST IN FLOAT64 and uploaded once, because the reference computes its 959// frequencies in float64 and reproducing that on device means double-precision `pow`/`cos` that need not 960// agree with the host's libm. A table shorter than the sequence would have the rotation read past it. 961// The process's rope scaling (none by default) is INSIDE the table - the rotation kernels cannot tell. 962if (share_rope == nullptr ) { 963 std::vector < float > hc ((size_t )max_cells * (s .n_rot /2 )),hs ((size_t )max_cells * (s .n_rot /2 )); 964 strata::kernels::build_rope_table ((int )s .n_rot , strata::kernels::rope_scaling (), (int )max_cells , 965hc .data (),hs .data ()); 966cudaMemcpy (st .cos_tab ,hc .data (),hc .size ()* 4 ,cudaMemcpyHostToDevice ); 967cudaMemcpy (st .sin_tab ,hs .data (),hs .size ()* 4 ,cudaMemcpyHostToDevice ); 968st .owns_rope = true; 969if (s .n_rot == 64 )// the native and prompt-path rope kernels read it (mrope.hpp, STRATA_ROPE_TABLE=1) 970 strata::kernels::rope_table_set (st .cos_tab ,st .sin_tab , (int )max_cells , strata::kernels::rope_scaling ()); 971 } 972// the page table starts as the IDENTITY, which is the simplest legal mapping and what a caller that does 973// not page at all wants; a streamed state starts with nothing resident, a ring at `block % n_slots`. 974if (p .mode == 0 ) { 975 std::vector < int32_t > tab ((size_t )pages ); 976for (int64_t i = 0 ;i < pages ;++ i )tab [(size_t )i ]= (int32_t )i ; 977cudaMemcpy (st .page_table ,tab .data (),tab .size ()* 4 ,cudaMemcpyHostToDevice ); 978 }else if (p .mode == 1 ) { 979 strata::kernels::kv_stream_reset (st .map ,nullptr ); 980 }else { 981 strata::kernels::kv_ring_table (st .page_table ,pages ,p .slots ,nullptr ); 982 } 983cudaDeviceSynchronize (); 984return c .used ; 985} 986 987void qsa_state_zero (const QsaState & st ,const ModelGeometry & g ,void * stream ) { 988const QsaShapes s = qsa_shapes (g ); 989cudaStream_t cs = (cudaStream_t )stream ; 990// an elastic state zeroes what is mapped (the rest is zeroed when it is mapped) 991const int64_t live_slots = st .kv_elastic >=0 ?pool_slots_mapped (* g_pools [(size_t )st .kv_elastic ]) :st .n_slots ; 992const size_t rows = (size_t )live_slots * s .n_head_kv * s .page_size ; 993if (st .kv_hybrid ) { 994cudaMemsetAsync (st .k_q ,0 ,rows * s .head_dim ,cs ); 995cudaMemsetAsync (st .k_scale ,0 ,rows * (s .head_dim / strata::kernels::KV_Q8_GROUP )* 2 ,cs ); 996cudaMemsetAsync (st .v_q4 ,0 ,rows * strata::kernels::kv_q4_bytes_per_head ((int )s .head_dim ),cs ); 997 }else if (st .kv_q4 ) { 998cudaMemsetAsync (st .k_q4 ,0 ,rows * strata::kernels::kv_q4_bytes_per_head ((int )s .head_dim ),cs ); 999cudaMemsetAsync (st .v_q4 ,0 ,rows * strata::kernels::kv_q4_bytes_per_head ((int )s .head_dim ),cs ); 1000 }else if (st .kv_int8 ) { 1001cudaMemsetAsync (st .k_q ,0 ,rows * s .head_dim ,cs ); 1002cudaMemsetAsync (st .v_q ,0 ,rows * s .head_dim ,cs ); 1003cudaMemsetAsync (st .k_scale ,0 ,rows * (s .head_dim / strata::kernels::KV_Q8_GROUP )* 2 ,cs ); 1004cudaMemsetAsync (st .v_scale ,0 ,rows * (s .head_dim / strata::kernels::KV_Q8_GROUP )* 2 ,cs ); 1005 }else { 1006cudaMemsetAsync (st .k_pool ,0 ,rows * s .head_dim * 2 ,cs ); 1007cudaMemsetAsync (st .v_pool ,0 ,rows * s .head_dim * 2 ,cs ); 1008 } 1009// A streamed state starts over with nothing resident. Its host copy is not cleared (GBs over PCIe per new 1010// conversation): no reader names a cell before this sequence has written it, and a block copied in whole 1011// carries the unwritten cells past the end, which nothing reads. 1012if (st .kv_mode == 1 ) strata::kernels::kv_stream_reset (st .map ,stream ); 1013cudaMemsetAsync (st .idx_tail ,0 , (size_t ) (s .idx_block - 1 )* s .idx_dim * 4 ,cs ); 1014cudaMemsetAsync (st .idx_dead ,0 , (size_t )s .idx_dim * 4 ,cs ); 1015cudaMemsetAsync (st .idx_pooled ,0 , (size_t )st .idx_pooled_rows * s .idx_dim * 4 ,cs ); 1016} 1017 1018strata::kernels::QsaAttnPools qsa_attn_pools (const QsaState & st ) { 1019 strata::kernels::QsaAttnPools pools ; 1020pools .page_table = st .page_table ; 1021if (st .kv_hybrid ) {pools .k_q = st .k_q ;pools .k_scale = st .k_scale ;pools .v_q4 = st .v_q4 ; } 1022else if (st .kv_q4 ) {pools .k_q4 = st .k_q4 ;pools .v_q4 = st .v_q4 ; } 1023else if (st .kv_int8 ) {pools .k_q = st .k_q ;pools .v_q = st .v_q ;pools .k_scale = st .k_scale ;pools .v_scale = st .v_scale ; } 1024else {pools .k_pool = st .k_pool ;pools .v_pool = st .v_pool ; } 1025return pools ; 1026} 1027 1028void qsa_kv_resolve (const QsaState & st ,const ModelGeometry & g ,const int32_t * ids ,const int32_t * steps ,int64_t n_q , 1029int64_t cap ,void * stream ) { 1030if (st .kv_mode != 1 )return ; 1031 strata::kernels::kv_stream_resolve (st .map ,qsa_attn_pools (st ),st .host ,qsa_kv_format (st ),ids ,steps ,n_q ,cap , 1032qsa_shapes (g ),stream ); 1033} 1034 1035uint64_t qsa_buffers_bytes (const ModelGeometry & g ,int64_t max_cells ) {const QsaShapes s = qsa_shapes (g );const int64_t cap = strata::kernels::qsa_selection_width (strata::kernels::kTopkMaxCells ,s );uint64_t n = 0 ;n += (uint64_t )q8k_bytes (g .n_embd );n += (uint64_t ) (g .n_embd /32 )* 34 ; 1036// block_q8_0 1037n += (uint64_t )g .n_embd * 2 ;n += (uint64_t )g .n_head * 2 * g .head_dim * 4 ;n += (uint64_t )g .n_head * g .head_dim * 4 ;n += (uint64_t )g .n_head_kv * g .head_dim * 4 * 2 ;n += (uint64_t )g .idx_key_dim * 4 ;n += (uint64_t )g .idx_q_heads * g .idx_key_dim * 4 ;n += (uint64_t )max_cells * 4 ;n += (uint64_t )cap * 4 ;n += (uint64_t )cap * g .n_head_kv * g .head_dim * 2 * 2 ;n += (uint64_t )g .n_head * g .head_dim * 4 ; 1038// attn 1039n += (uint64_t )g .n_head * g .head_dim * 2 ; 1040// attn16 1041n += (uint64_t )g .n_head * g .head_dim * 4 ; 1042// attn32 1043n += (uint64_t )q8k_bytes (g .n_head * g .head_dim ); 1044// attn_q8k 1045n += strata::kernels::qsa_decode_attn_scratch_floats (cap ,s )* 4 + 16 ; 1046// attn_scratch 1047return align_up16 (n )+ 256 ;} 1048uint64_t qsa_buffers_init (const ModelGeometry & g ,int64_t max_cells ,void * base ,QsaBuffers & b ) {const QsaShapes s = qsa_shapes (g );const int64_t cap = strata::kernels::qsa_selection_width (strata::kernels::kTopkMaxCells ,s );Cursor c {(uint8_t * )base };b .x_q8k = c .take_bytes (q8k_bytes (g .n_embd ));b .x_q8_0 = c .take_bytes ((uint64_t ) (g .n_embd /32 )* 34 );b .x_bf16 = c .take < uint16_t > ((uint64_t )g .n_embd );b .q_full = c .take < float > ((uint64_t )g .n_head * 2 * g .head_dim );b .qcur = c .take < float > ((uint64_t )g .n_head * g .head_dim );b .kcur = c .take < float > ((uint64_t )g .n_head_kv * g .head_dim );b .vcur = c .take < float > ((uint64_t )g .n_head_kv * g .head_dim );b .idx_raw = c .take < float > ((uint64_t )g .idx_key_dim );b .q_idx = c .take < float > ((uint64_t )g .idx_q_heads * g .idx_key_dim );b .cell_scores = c .take < float > ((uint64_t )max_cells );b .ids = c .take < int32_t > ((uint64_t )cap );b .k_scratch = c .take < uint16_t > ((uint64_t )cap * g .n_head_kv * g .head_dim );b .v_scratch = c .take < uint16_t > ((uint64_t )cap * g .n_head_kv * g .head_dim );b .attn = c .take < float > ((uint64_t )g .n_head * g .head_dim );b .attn16 = c .take < uint16_t > ((uint64_t )g .n_head * g .head_dim );b .attn32 = c .take < float > ((uint64_t )g .n_head * g .head_dim );b .attn_q8k = c .take_bytes (q8k_bytes (g .n_head * g .head_dim ));b .attn_scratch = c .take < float > (strata::kernels::qsa_decode_attn_scratch_floats (cap ,s ));return c .used ;} 1049// ================================ PER-STAGE TIMING, DEBUG ONLY ================================ 1050// 1051// **THE ENGINE SPENDS 1.047 ms PER LAYER WITH THE EXPERTS OFF, AND EVERY COST MODEL IN `bench/` PREDICTS LESS 1052// THAN HALF OF THAT.** `dense_pass.exe` puts all 302 dense GEMVs at 11.64 ms/token and the 1.377 GiB of 1053// BF16/F32 weights they exclude at another ~5.9, so ~17.5 ms of the 50.25 ms captured no-pool floor is 1054// accounted for and ~33 ms is not. Arithmetic has already discounted the obvious candidates - the GDN 1055// recurrence moves 6.2 MB of state per token, the QSA attention at 1,024 tokens is 75M MACs over twelve 1056// layers, and `gr_norm_kernel`'s 4-block launch moves 40 KB - so the attribution has to come from the engine. 1057// 1058// Event pairs are recorded per (layer, stage) and read once at the end, so **NOTHING IS SYNCHRONISED DURING 1059// THE RUN** and the measurement does not perturb what it measures. That matters here more than usual: a 1060// per-stage `cudaEventSynchronize` would serialise the pipeline and report the serialised time. 1061// 1062// **IT CANNOT BE USED WITH CAPTURED GRAPHS.** An event record inside a stream capture is silently dropped 1063// (round 199: 2 nodes for two kernels plus an event record, and the event never completed across a 41 ms 1064// graph), so this is gated on the `--no-capture` path where the layers are ordinary launches. 1065constexpr int STAGE_SLOTS = 20 ; 1066 1067struct StageTimer { 1068bool on = false; 1069cudaEvent_t a [64 ][STAGE_SLOTS ]= {}; 1070cudaEvent_t b [64 ][STAGE_SLOTS ]= {}; 1071const char * names [STAGE_SLOTS ]= {}; 1072int nslots = 0 ; 1073}; 1074 1075static StageTimer g_st ; 1076 1077bool stage_timing_enable () { 1078if (g_st .on )return true; 1079for (int l = 0 ;l < 64 ;++ l ) { 1080for (int s = 0 ;s < STAGE_SLOTS ;++ s ) { 1081if (cudaEventCreate (& g_st .a [l ][s ])!= cudaSuccess )return false; 1082if (cudaEventCreate (& g_st .b [l ][s ])!= cudaSuccess )return false; 1083 } 1084 } 1085g_st .on = true; 1086return true; 1087} 1088 1089void stage_timing_name (int slot ,const char * name ) { 1090if (slot >=0 && slot < STAGE_SLOTS ) { 1091g_st .names [slot ]= name ; 1092if (slot + 1 > g_st .nslots )g_st .nslots = slot + 1 ; 1093 } 1094} 1095 1096void stage_mark_begin (int64_t layer ,int slot ,void * stream ) {st_begin (layer ,slot ,stream ); } 1097void stage_mark_end (int64_t layer ,int slot ,void * stream ) {st_end (layer ,slot ,stream ); } 1098 1099static void st_begin (int64_t layer ,int slot ,void * stream ) { 1100if (g_st .on && layer < 64 )cudaEventRecord (g_st .a [layer ][slot ], (cudaStream_t )stream ); 1101} 1102 1103static void st_end (int64_t layer ,int slot ,void * stream ) { 1104if (g_st .on && layer < 64 )cudaEventRecord (g_st .b [layer ][slot ], (cudaStream_t )stream ); 1105} 1106 1107void stage_timing_report (int64_t n_layers ) { 1108if (!g_st .on )return ; 1109cudaDeviceSynchronize (); 1110double tot [STAGE_SLOTS ]= {}; 1111for (int s = 0 ;s < g_st .nslots ;++ s ) { 1112for (int64_t l = 0 ;l < n_layers && l < 64 ;++ l ) { 1113float ms = 0.0f ; 1114if (cudaEventElapsedTime (& ms ,g_st .a [l ][s ],g_st .b [l ][s ])== cudaSuccess )tot [s ]+= (double )ms ; 1115 } 1116 } 1117double sum = 0 ; 1118for (int s = 0 ;s < g_st .nslots ;++ s )sum += tot [s ]; 1119 std::fprintf (stderr ,"\nper-stage GPU time, summed over %lld layers (one token):\n" , (long long )n_layers ); 1120for (int s = 0 ;s < g_st .nslots ;++ s ) { 1121 std::fprintf (stderr ," %-22s %8.3f ms/token %6.3f ms/layer %5.1f%%\n" , 1122g_st .names [s ] ?g_st .names [s ] :"(unnamed)" ,tot [s ],tot [s ] / (double )n_layers , 1123sum > 0 ?100.0 * tot [s ] /sum :0.0 ); 1124 } 1125 std::fprintf (stderr ," %-22s %8.3f ms/token\n" ,"sum of stages" ,sum ); 1126// ---- THE PER-LAYER SPLIT, because the attention block is 55% of the token and the engine mixes two 1127// entirely different attention implementations: GDN on 36 layers and QSA on the twelve where 1128// `full_attention_interval` divides the index. A single total cannot say which one is expensive, and the 1129// two have nothing in common to optimise. 1130 std::fprintf (stderr ,"\nper-layer, the attention block (ms). A `*` marks a QSA layer:\n" ); 1131double gdn = 0 ,qsa = 0 ; 1132int ng = 0 ,nq = 0 ; 1133for (int64_t l = 0 ;l < n_layers && l < 64 ;++ l ) { 1134float ms = 0.0f ; 1135if (cudaEventElapsedTime (& ms ,g_st .a [l ][1 ],g_st .b [l ][1 ])!= cudaSuccess )continue ; 1136const bool is_qsa = (l %4 )== 3 ; 1137if (is_qsa ) {qsa += ms ;++ nq ; }else {gdn += ms ;++ ng ; } 1138 std::fprintf (stderr ," %s%2lld %7.3f%s" ,is_qsa ?"*" :" " , (long long )l , (double )ms , 1139 ((l + 1 ) %8 == 0 ) ?"\n" :"" ); 1140 } 1141 std::fprintf (stderr ,"\n GDN: %d layers, %.3f ms total, %.4f ms/layer\n" ,ng ,gdn ,ng ?gdn /ng :0.0 ); 1142 std::fprintf (stderr ," QSA: %d layers, %.3f ms total, %.4f ms/layer\n" ,nq ,qsa ,nq ?qsa /nq :0.0 ); 1143} 1144 1145// Declared here because `qsa_layer` is defined above `block_layer_pre`, where the body lives. The dump buffer 1146// is a plain host pointer and the copy is a graph node of whichever layer's capture is running, so the helper 1147// needs nothing from the layer it is called for beyond its index. 1148static void dump_slot (float * dump ,const ModelGeometry & g ,int64_t layer ,const float * src ,uint64_t off , 1149uint64_t n ,void * stream ); 1150bool qsa_layer (const WeightTable & tables ,const ModelGeometry & g ,int64_t layer ,int64_t pos ,int32_t pos_base ,const QsaState & st ,const QsaBuffers & b ,const float * x ,float * out ,void * stream , std::string & err ,float * dump ) {using namespace strata::kernels ;const QsaShapes s = qsa_shapes (g );const LayerView v (tables ,layer );const int64_t n_kv = pos + 1 ;/* P7 audit: RoPE reads cos/sin row pos_base + pos, and the table holds max_cells rows. */ if ((int64_t )pos_base + pos >=st .max_cells || pos_base < 0 ) {err = "qsa_layer: position " + std::to_string ((long long )pos_base + pos )+ " is outside the RoPE table (" + std::to_string ((long long )st .max_cells )+ " rows)" ;return false; }const int64_t cap = qsa_selection_width (kTopkMaxCells ,s ); 1151const auto normalize_rotate = [& ](float * data ,const WeightRef * norm ,int rows ,int cols ) { 1152try { 1153if (native_qsa_enabled ())native_qsa_rms_norm_weighted (data , (const float * )norm -> data ,data ,cols ,rows ,RMS_EPS ,stream ); 1154else rms_norm_weighted (data , (const float * )norm -> data ,rows ,cols ,RMS_EPS ,stream ); 1155if (native_rope_enabled ())native_rope_apply (data ,data ,rows ,cols , (int )s .n_rot ,rope_scaling (),st .pos_dev ,stream ); 1156else rope_neox_apply (data ,data ,rows ,cols , (int )s .n_rot ,st .cos_tab ,st .sin_tab ,st .pos_dev ,stream ); 1157return true; 1158 }catch (const std::exception & error ) { 1159err = v .name ("qsa_norm_rope" )+ ": " + error .what (); 1160return false; 1161 } 1162}; 1163// ---- resolve every tensor by name, and REFUSE rather than reading a null. `check_layer` has already 1164// asserted the shapes at load time; a missing name here is a wiring mistake. 1165struct Req {const char * suf ; };const WeightRef * w_idxk = v .get ("indexer.k_proj.weight" );const WeightRef * w_attnq = v .get ("attn_q.weight" );const WeightRef * w_attnk = v .get ("attn_k.weight" );const WeightRef * w_attnv = v .get ("attn_v.weight" );const WeightRef * w_attno = v .get ("attn_output.weight" );const WeightRef * w_idxq = v .get ("indexer.q_proj.weight" );const WeightRef * w_qn = v .get ("attn_q_norm.weight" );const WeightRef * w_kn = v .get ("attn_k_norm.weight" );const WeightRef * w_iqn = v .get ("indexer.q_norm.weight" );const WeightRef * w_ikn = v .get ("indexer.k_norm.weight" );const char * missing = !w_idxk ?"indexer.k_proj.weight" : !w_attnq ?"attn_q.weight" : !w_attnk ?"attn_k.weight" : !w_attnv ?"attn_v.weight" : !w_attno ?"attn_output.weight" : !w_idxq ?"indexer.q_proj.weight" : !w_qn ?"attn_q_norm.weight" : !w_kn ?"attn_k_norm.weight" : !w_iqn ?"indexer.q_norm.weight" : !w_ikn ?"indexer.k_norm.weight" :nullptr ;if (missing ) {err = v .name (missing )+ " is missing" ;return false; }if (pos < 0 || pos >=st .max_cells ) {err = "qsa_layer: pos " + std::to_string (pos )+ " is outside the state's 0.." + std::to_string (st .max_cells - 1 );return false; } 1166// THE TWO BF16 PROJECTIONS: the arena holds them re-rounded to 2 B/elem, which is what `bf16_gemv` wants. 1167// Reading one as f32 would walk 2x its length inside the arena without faulting. 1168if (w_idxk -> kind != WeightKind ::Bf16InF32 || w_idxq -> kind != WeightKind ::Bf16InF32 ) {err = v .name ("indexer.*_proj.weight" )+ " must be engine form 1 (bf16); they are " + std::to_string ((int )w_idxk -> kind )+ " and " + std::to_string ((int )w_idxq -> kind );return false; } 1169// ---- 1. the three activation formats, once each 1170bool images_fused = false; 1171#if defined(STRATA_EXPERIMENTAL_SM60 ) 1172if (strata::kernels::fuse_decode ()&& (!w_attnk -> native_data || !w_attnv -> native_data || !w_attnq -> native_data )) { 1173quantize_act_images (x ,g .n_embd ,b .x_q8_0 ,b .x_q8k , 1174native_bf16_projections ?nullptr :b .x_bf16 ,stream );// ONE pass, was two or three 1175images_fused = true; 1176} 1177#endif 1178if (!images_fused ) { 1179if (!w_attnk -> native_data || !w_attnv -> native_data || !w_attnq -> native_data ) { 1180quantize_q8_K (x ,b .x_q8k ,g .n_embd ,stream ); 1181quantize_q8_0 (x ,b .x_q8_0 ,g .n_embd ,stream ); 1182 } 1183if (!native_bf16_projections )f32_to_bf16_bulk (x ,b .x_bf16 ,g .n_embd ,stream ); 1184} 1185// ---- 2. the step state: ONE H2D carries every per-token count the kernels need. Nothing below passes a 1186// per-token scalar as an argument, which is what keeps this layer capturable. 1187// 1188// THE SOURCES ARE `st.host_step`/`st.host_pos`, WHICH LIVE AS LONG AS THE STATE DOES. A stack array or a 1189// local vector here would be captured as a dangling POINTER and replayed as garbage - see the note in 1190// `layer.hpp`. That is a silent failure, not a fault: the copy succeeds, the counts are wrong, and the 1191// token that comes out is plausible. 1192{qsa_step_fill (st .host_step ,pos ,s );for (int64_t h = 0 ;h < g .n_head ;++ h )st .host_pos [h ]= (int32_t ) (pos_base + pos ); 1193int32_t * m_step = nullptr ; 1194int32_t * m_pos = nullptr ; 1195if (g_publish_kernel && cudaHostGetDevicePointer ((void ** )& m_step ,st .host_step ,0 )== cudaSuccess && 1196cudaHostGetDevicePointer ((void ** )& m_pos ,st .host_pos ,0 )== cudaSuccess ) { 1197 strata::kernels::copy_i32_from_mapped (st .step ,m_step , strata::kernels::kStepCount ,stream ); 1198 strata::kernels::copy_i32_from_mapped (st .pos_dev ,m_pos ,g .n_head ,stream ); 1199 }else 1200if (cudaMemcpyAsync (st .step ,st .host_step ,qsa_step_bytes (),cudaMemcpyHostToDevice , (cudaStream_t )stream )!= cudaSuccess || cudaMemcpyAsync (st .pos_dev ,st .host_pos , (size_t )g .n_head * 4 ,cudaMemcpyHostToDevice , (cudaStream_t )stream )!= cudaSuccess ) {err = "qsa_layer: the step-state upload failed" ;return false; } } 1201// ---- 3. the indexer's RAW key (and, with the V100 switch, its QUERY in the same kernel; was two launches) 1202bool idx_pair = false; 1203#if defined(STRATA_EXPERIMENTAL_SM60 ) 1204if (strata::kernels::fuse_decode ()) { 1205// two BF16 projections of the same x in ONE kernel: the query is needed only at step 7 and nothing in between 1206// touches it, so computing it here changes no order that matters; `idx_raw` is still appended at step 5. 1207project_bf16_pair (x ,b .x_bf16 , (const uint16_t * )w_idxk -> data ,b .idx_raw ,g .idx_key_dim , 1208 (const uint16_t * )w_idxq -> data ,b .q_idx ,g .idx_q_heads * g .idx_key_dim ,g .n_embd , 1209 false,stream ); 1210idx_pair = true; 1211} 1212#endif 1213if (!idx_pair ) 1214project_bf16 (x ,b .x_bf16 , (const uint16_t * )w_idxk -> data ,b .idx_raw ,g .n_embd ,g .idx_key_dim , false,stream ); 1215// ---- 4. K and V, in Q8_K, then norm and rotate K only 1216SForm f_k ,f_v ,f_o ,f_q ;if (!sform_of (* w_attnk ,f_k ,v .name ("attn_k.weight" ),err ))return false;if (!sform_of (* w_attnv ,f_v ,v .name ("attn_v.weight" ),err ))return false;if (!sform_of (* w_attno ,f_o ,v .name ("attn_output.weight" ),err ))return false;if (!sform_of (* w_attnq ,f_q ,v .name ("attn_q.weight" ),err ))return false;Planes p_k ,p_v ,p_o ,p_q ;if (!plane_ptrs (* w_attnk ,v .name ("attn_k.weight" ),p_k ,err ))return false;if (!plane_ptrs (* w_attnv ,v .name ("attn_v.weight" ),p_v ,err ))return false;if (!plane_ptrs (* w_attno ,v .name ("attn_output.weight" ),p_o ,err ))return false;if (!plane_ptrs (* w_attnq ,v .name ("attn_q.weight" ),p_q ,err ))return false; 1217// k and v, with the activation THIS layer's tensors ask for. Both are K-quants in every QSA layer of this 1218// artifact, but the dispatch is here for the same reason it is in `gdn_layer`: the pack decides per tensor, 1219// and "it happens to be uniform here" is the assumption that was wrong for `attn_q`. 1220if (!gemv_quantized (* w_attnk ,p_k ,f_k ,b .x_q8_0 ,b .x_q8k ,b .kcur ,g .n_embd ,g .n_head_kv * g .head_dim ,v .name ("attn_k.weight" ),stream ,err ,x ))return false; 1221if (!gemv_quantized (* w_attnv ,p_v ,f_v ,b .x_q8_0 ,b .x_q8k ,b .vcur ,g .n_embd ,g .n_head_kv * g .head_dim ,v .name ("attn_v.weight" ),stream ,err ,x ,w_attnk -> native_data && w_attnv -> native_data ))return false;dump_slot (dump ,g ,layer ,b .vcur , (uint64_t )2 * g .n_embd + 2 * g .hc + (uint64_t )g .n_head * g .head_dim , (uint64_t )g .n_head_kv * g .head_dim ,stream ); 1222if (!normalize_rotate (b .kcur ,w_kn , (int )g .n_head_kv , (int )g .head_dim ))return false; 1223// ---- 5. into the cache, and the indexer's append (which pools AND rotates on a block completion). 1224// EVERY ENTRY POINT FROM HERE ON IS THE CAPTURABLE ONE: the per-token counts come from `st.step` and every 1225// launch is sized from a capacity in `st`/`b`, so this sequence can be captured and replayed. The 1226// host-scalar wrappers would be correct here today and silently wrong in a graph. 1227if (st .kv_hybrid ) { 1228// K8V4: only V is rotated (kv_q4.hpp's H); the scores pair unrotated q with unrotated INT8 K, and the 1229// output - a mix of rotated values - is rotated back after attention. Each append/gather call folds the 1230// unused half's lanes onto the used pool (a bit-identical duplicate write), so no kernel variants exist. 1231// Streamed (--kv-resident), each half also writes its part of the host copy (kv_hybrid_*_half). 1232 strata::kernels::fwht256_inplace_cuda (b .vcur ,g .n_head_kv ,stream ); 1233const strata::kernels::KvHostPools hk = strata::kernels::kv_hybrid_k_half (st .host ), 1234hv = strata::kernels::kv_hybrid_v_half (st .host ); 1235const bool mirror = st .host .present (); 1236kv_append_q8_step (st .k_q ,st .k_q ,st .k_scale ,st .k_scale ,st .page_table ,st .step ,b .kcur ,b .kcur ,s ,stream , 1237mirror ?& hk :nullptr ); 1238 strata::kernels::kv_append_q4_step (st .v_q4 ,st .v_q4 ,st .page_table ,st .step ,b .vcur ,b .vcur ,s ,stream , 1239mirror ?& hv :nullptr ); 1240}else { 1241if (st .kv_rot ) {// rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1 1242 strata::kernels::fwht256_inplace_cuda (b .kcur ,g .n_head_kv ,stream ); 1243 strata::kernels::fwht256_inplace_cuda (b .vcur ,g .n_head_kv ,stream ); 1244} 1245if (st .kv_q4 ) { 1246 strata::kernels::kv_append_q4_step (st .k_q4 ,st .v_q4 ,st .page_table ,st .step ,b .kcur ,b .vcur ,s ,stream ,& st .host ); 1247}else if (st .kv_int8 )kv_append_q8_step (st .k_q ,st .v_q ,st .k_scale ,st .v_scale ,st .page_table ,st .step ,b .kcur ,b .vcur ,s ,stream ,& st .host );else kv_append_step (st .k_pool ,st .v_pool ,st .page_table ,st .step ,b .kcur ,b .vcur ,s ,stream ,& st .host ); }/* not K8V4 */ {const uint64_t nvk = (uint64_t )g .n_head_kv * g .head_dim ;const uint64_t base = (uint64_t )2 * g .n_embd + 2 * g .hc + (uint64_t )g .n_head * g .head_dim + 2 * nvk + 8 ;if (!st .kv_int8 && !st .kv_hybrid )dump_slot (dump ,g ,layer , (const float * )st .k_pool ,base ,nvk /2 ,stream );if (!st .kv_int8 && !st .kv_hybrid )dump_slot (dump ,g ,layer , (const float * )st .v_pool ,base + nvk /2 ,nvk /2 ,stream );dump_slot (dump ,g ,layer ,b .vcur ,base + nvk ,nvk ,stream );dump_slot (dump ,g ,layer ,b .kcur ,base + 2 * nvk ,nvk ,stream ); } {const QsaIndexerBuffers ib {st .idx_tail ,st .idx_dead ,st .idx_pooled ,st .idx_block_pos };if (native_qsa_indexer_enabled ()) { 1248try { 1249native_qsa_indexer_append (b .idx_raw ,st .step + kStepPos ,pos_base , 1250 (const float * )w_ikn -> data ,RMS_EPS ,ib ,s ,st .max_cells ,rope_scaling (),stream ); 1251 }catch (const std::exception & error ) {err = v .name ("native_indexer" )+ ": " + error .what ();return false; } 1252}else indexer_key_append (b .idx_raw ,st .pos_dev ,pos_base , (const float * )w_ikn -> data ,RMS_EPS ,ib ,s , 1253st .cos_tab ,st .sin_tab ,stream ); } 1254// ---- 6. the query projection, and the HALF-SPLIT into q and gate. 1255// 1256// **`attn_q` IS *NOT* ALWAYS Q2_0.** It is Q2_0 on TWO of the twelve QSA layers, Q3_K on six and IQ4_XS on 1257// four, and this line used to call `s2_gemv_q8` unconditionally - so TEN of the twelve layers decoded an 1258// S4 code plane with a Q8_0 activation. Both are "a quantized activation", both produce a plausible 1259// vector, and the difference is 0.6-1.4%. 1260if (!gemv_quantized (* w_attnq ,p_q ,f_q ,b .x_q8_0 ,b .x_q8k ,b .q_full ,g .n_embd ,g .n_head * 2 * g .head_dim ,v .name ("attn_q.weight" ),stream ,err ,x ,w_attnv -> native_data && w_attnq -> native_data ))return false; 1261// `per_head[:, :head_dim]` - the FIRST half of each head's 2*head_dim block, copied out contiguously so 1262// the norm and the rotation see whole rows. A 2-D copy is a memcpy node, which captures (`pinned_capture` 1263// case A) and needs no kernel. 1264if (cudaMemcpy2DAsync (b .qcur , (size_t )g .head_dim * 4 ,b .q_full , (size_t )g .head_dim * 2 * 4 , (size_t )g .head_dim * 4 , (size_t )g .n_head ,cudaMemcpyDeviceToDevice , (cudaStream_t )stream )!= cudaSuccess ) {err = "qsa_layer: the q/gate split failed" ;return false; }if (!normalize_rotate (b .qcur ,w_qn , (int )g .n_head , (int )g .head_dim ))return false; 1265// ---- 7. the indexer's query: with the V100 switch it was projected at step 3 (paired with the raw key); 1266// the trunk projects it here. Either way, norm and rotate it now. 1267if (!idx_pair )project_bf16 (x ,b .x_bf16 , (const uint16_t * )w_idxq -> data ,b .q_idx ,g .n_embd ,g .idx_q_heads * g .idx_key_dim , 1268 false,stream ); 1269if (!normalize_rotate (b .q_idx ,w_iqn , (int )g .idx_q_heads , (int )g .idx_key_dim ))return false; 1270// ---- 8. score, select, gather, attend. `max_blocks` and `cap` are CAPACITIES from the state, not this 1271// token's counts: a grid or a shared-memory size that follows the sequence length is baked into a captured 1272// graph, and the kernels guard for the surplus. const 1273int64_t max_blocks = (st .max_cells /s .idx_block )+ 2 ; 1274if (g_fast_select ) { 1275// Plan v0.3 P7: block-level FP32 scores and a radix selection over blocks (qsa_select.hpp). 1276qsa_block_scores (st .idx_pooled ,st .idx_dead ,b .q_idx ,st .step ,1 ,max_blocks ,s ,b .cell_scores ,stream ); 1277qsa_block_topk (b .cell_scores ,st .step ,1 ,max_blocks ,cap ,s ,b .ids ,stream ); 1278 }else { 1279qsa_index_step (st .idx_pooled ,b .q_idx ,nullptr ,s ,st .step ,max_blocks ,b .cell_scores ,stream );topk_512_step (b .cell_scores ,s ,cap ,st .step ,b .ids ,stream ); 1280 } 1281// KV streaming: every block the selection names is made resident before anything reads it 1282qsa_kv_resolve (st ,g ,b .ids ,st .step ,1 ,cap ,stream ); 1283if (st .kv_rot ) strata::kernels::fwht256_inplace_cuda (b .qcur ,g .n_head ,stream );// <Hq, Hk> = <q, k> 1284if (g_fast_attn && !native_flash_attn_short && dump == nullptr ) { 1285const strata::kernels::QsaAttnPools pools = qsa_attn_pools (st ); 1286 strata::kernels::qsa_decode_attn_step (b .qcur ,pools ,b .ids ,st .step ,cap ,s ,b .attn_scratch ,b .attn ,stream ); 1287 }else { 1288if (st .kv_hybrid ) { 1289kv_gather_q8_step (st .k_q ,st .k_q ,st .k_scale ,st .k_scale ,st .page_table ,b .ids ,st .step ,cap ,s , 1290b .k_scratch ,b .k_scratch ,stream ); 1291 strata::kernels::kv_gather_q4_step (st .v_q4 ,st .v_q4 ,st .page_table ,b .ids ,st .step ,cap ,s , 1292b .v_scratch ,b .v_scratch ,stream ); 1293 } 1294else if (st .kv_q4 ) strata::kernels::kv_gather_q4_step (st .k_q4 ,st .v_q4 ,st .page_table ,b .ids ,st .step ,cap ,s ,b .k_scratch ,b .v_scratch ,stream ); 1295else if (st .kv_int8 )kv_gather_q8_step (st .k_q ,st .v_q ,st .k_scale ,st .v_scale ,st .page_table ,b .ids ,st .step ,cap ,s ,b .k_scratch ,b .v_scratch ,stream ); 1296else kv_gather_step (st .k_pool ,st .v_pool ,st .page_table ,b .ids ,st .step ,cap ,s ,b .k_scratch ,b .v_scratch ,stream ); 1297if (native_flash_attn_short ) { 1298if (st .max_cells < 1 || st .max_cells > 256 || !st .attention_status || !st .host_step ) { 1299err = v .name ("native_flash_attn" )+ ": short adapter requires context <=256 and persistent status storage" ; 1300return false; 1301 } 1302try { 1303native_flash_attn_short_step (b .qcur ,b .k_scratch ,b .v_scratch ,st .step ,cap , 1304 (int )st .max_cells ,s ,b .attn ,st .attention_status ,nullptr ,stream ); 1305 }catch (const std::exception & error ) {err = v .name ("native_flash_attn" )+ ": " + error .what ();return false; } 1306if (cudaMemcpyAsync (st .host_step + kStepCount ,st .attention_status ,sizeof (int32_t ), 1307cudaMemcpyDeviceToHost , (cudaStream_t )stream )!= cudaSuccess ) { 1308err = v .name ("native_flash_attn" )+ ": status readback failed" ;return false; 1309 } 1310}else qsa_attend_step (b .qcur ,b .k_scratch ,b .v_scratch ,st .step ,cap ,s ,b .attn ,nullptr ,stream ); 1311 } 1312if (st .kv_rot || st .kv_hybrid ) strata::kernels::fwht256_inplace_cuda (b .attn ,g .n_head ,stream );// the output back: H is self-inverse 1313dump_slot (dump ,g ,layer ,b .attn , (uint64_t )2 * g .n_embd + 2 * g .hc , (uint64_t )g .n_head * g .head_dim ,stream ); {const uint64_t vs = (uint64_t )2 * g .n_embd + 2 * g .hc + (uint64_t )g .n_head * g .head_dim + (uint64_t )2 * g .n_head_kv * g .head_dim ;dump_slot (dump ,g ,layer , (const float * )b .v_scratch ,vs , (uint64_t )g .n_head_kv * g .head_dim /2 ,stream );dump_slot (dump ,g ,layer , (const float * )b .ids ,vs + (uint64_t )g .n_head_kv * g .head_dim /2 ,4 ,stream );dump_slot (dump ,g ,layer , (const float * )st .step ,vs + (uint64_t )g .n_head_kv * g .head_dim /2 + 4 ,4 ,stream ); } 1314// ---- 9. Gate the attention output before its projection. Native CUDA keeps F32 1315// sigmoid/multiply arithmetic and uses Q8_1 for the native quantized projection. 1316// The canonical fallback retains its prior FP64 gate and Q8_K projection. 1317try { 1318if (native_qsa_enabled ())native_qsa_gate_apply (b .attn ,b .q_full ,b .attn32 , (int )g .n_head , (int )g .head_dim ,stream ); 1319else qsa_gate_apply_f32 (b .attn ,b .q_full ,s ,b .attn32 ,stream ); 1320}catch (const std::exception & error ) {err = v .name ("qsa_gate" )+ ": " + error .what ();return false; } 1321if (!w_attno -> native_data )quantize_q8_K (b .attn32 ,b .attn_q8k ,g .n_head * g .head_dim ,stream ); 1322if (w_attno -> native_data ) { 1323if (!gemv_quantized (* w_attno ,p_o ,f_o ,nullptr ,b .attn_q8k ,out , 1324g .n_head * g .head_dim ,g .n_embd ,v .name ("attn_output.weight" ),stream ,err ,b .attn32 ))return false; 1325}else { 1326s_gemv_q8k_split (b .attn_q8k ,p_o .codes ,p_o .scales ,p_o .offset ,out , 1327g .n_head * g .head_dim ,g .n_embd ,f_o ,stream ); 1328}return true;} 1329// ================================ THE DOORBELL ================================ 1330namespace {} 1331// namespace 1332uint64_t doorbell_init (const ModelGeometry & g ,int64_t k ,Doorbell & db ) {db .n_embd = g .n_embd ;db .k = k ;uint64_t bytes = 0 ; 1333// ONE region per field, each MAPPED PINNED, so the device and the host have different pointers to the same 1334// bytes and no copy is needed to publish them. 1335auto alloc = [& ](size_t n ,void ** h ,void ** d ,const char * what ) {if (cudaHostAlloc (h ,n ,cudaHostAllocMapped )!= cudaSuccess ) { std::fprintf (stderr ,"doorbell_init: cudaHostAlloc(%s) failed\n" ,what );return false; }if (cudaHostGetDevicePointer (d ,* h ,0 )!= cudaSuccess ) { std::fprintf (stderr ,"doorbell_init: cudaHostGetDevicePointer(%s) failed\n" ,what );return false; } std::memset (* h ,0 ,n );bytes += n ;return true; };if (!alloc ((size_t )g .n_embd * 4 , (void ** )& db .h_x_f , (void ** )& db .d_x_f ,"x_f" ))return 0 ;if (!alloc ((size_t )k * 4 , (void ** )& db .h_ids , (void ** )& db .d_ids ,"ids" ))return 0 ;if (!alloc ((size_t )k * 4 , (void ** )& db .h_weights , (void ** )& db .d_weights ,"weights" ))return 0 ;if (!alloc (4 , (void ** )& db .h_seq , (void ** )& db .d_seq ,"seq" ))return 0 ;if (!alloc (4 , (void ** )& db .h_flag , (void ** )& db .d_flag ,"flag" ))return 0 ;return bytes ;} 1336void doorbell_free (Doorbell & db ) {if (db .h_x_f ) (void )cudaFreeHost (db .h_x_f );if (db .h_ids ) (void )cudaFreeHost (db .h_ids );if (db .h_weights ) (void )cudaFreeHost (db .h_weights );if (db .h_seq ) (void )cudaFreeHost (db .h_seq );if (db .h_flag ) (void )cudaFreeHost (db .h_flag );db = Doorbell {};} 1337void doorbell_reset (const Doorbell & db ) { 1338if (db .h_seq )* db .h_seq = 0 ; 1339if (db .h_flag )* (volatile uint32_t * )db .h_flag = 0 ; 1340} 1341// ================================ THE TWO ENDS OF A TOKEN ================================ 1342bool embed_row (const WeightTable & tables ,const ModelGeometry & g ,int64_t token ,float * out_dev , 1343void * stream , std::string & err ) { 1344if (const NativeEmbed * ne = native_embed ()) {// plan v0.3 P6: the GGUF-form table (IQ model files) 1345if (token < 0 || out_dev == nullptr ) {err = "embed_row: invalid token or output" ;return false; } 1346ne -> gather_one (token ,out_dev ,stream ); 1347return true; 1348 } 1349const WeightRef * w = tables .find (EMBEDDING_NAME ); 1350if (w == nullptr ) {err = "token_embd.weight is missing" ;return false; } 1351if (w -> code_bits != 2 && w -> code_bits != 4 && w -> code_bits != 8 ) { 1352err = "embed_row: token_embd.weight is not an S2/S4/S8 tensor" ; 1353return false; 1354 } 1355if (w -> codebook_iq4nl ) { 1356err = "embed_row: an IQ4NL embedding is not supported" ; 1357return false; 1358 } 1359if (w -> data == nullptr || out_dev == nullptr || w -> ne0 <=0 || w -> ne1 <=0 || 1360w -> ne0 != g .n_embd || w -> group_elems <=0 || 1361w -> ne0 %w -> group_elems != 0 || w -> ne0 % (8 /w -> code_bits )!= 0 ) { 1362err = "embed_row: invalid embedding pointers, dimensions or group size" ; 1363return false; 1364 } 1365if (token < 0 || token >=w -> ne1 ) { 1366err = "embed_row: token " + std::to_string (token )+ " is outside 0.." + std::to_string (w -> ne1 - 1 ); 1367return false; 1368 } 1369 1370const uint64_t row_codes = (uint64_t ) (w -> ne0 / (8 /w -> code_bits )); 1371const uint64_t row_groups = (uint64_t ) (w -> ne0 /w -> group_elems ); 1372const uint64_t rows = (uint64_t )w -> ne1 ; 1373// Division-based checks avoid overflow in rows * row_bytes and reject partial 1374// code/group rows before any device pointer arithmetic. 1375if (w -> codes_bytes > w -> bytes || w -> scales_bytes > w -> bytes - w -> codes_bytes || 1376w -> offset_bytes != w -> bytes - w -> codes_bytes - w -> scales_bytes || 1377w -> codes_bytes %row_codes != 0 || w -> codes_bytes /row_codes != rows || 1378w -> codes_bytes % alignof(float )!= 0 || w -> scales_bytes %sizeof (float )!= 0 || 1379 (w -> scales_bytes /sizeof (float )) %row_groups != 0 || 1380 (w -> scales_bytes /sizeof (float )) /row_groups != rows || 1381w -> has_offset != (w -> offset_bytes != 0 )|| 1382 (w -> has_offset && w -> offset_bytes != w -> scales_bytes )) { 1383err = "embed_row: embedding planes do not match the loaded tensor shape" ; 1384return false; 1385 } 1386 1387const auto * codes = static_cast < const uint8_t *> (w -> data ); 1388const auto * scales = reinterpret_cast < const float *> (codes + w -> codes_bytes ); 1389const auto * offsets = w -> has_offset ?reinterpret_cast < const float *> (codes + w -> codes_bytes + w -> scales_bytes ) 1390 :nullptr ; 1391const uint64_t group_offset = (uint64_t )token * row_groups ; 1392 strata::kernels::embedding_gather (codes + (uint64_t )token * row_codes ,scales + group_offset , 1393offsets ?offsets + group_offset :nullptr ,w -> ne0 , 1394w -> code_bits ,w -> code_bias ,w -> group_elems ,out_dev ,stream ); 1395return true; 1396} 1397bool lm_head_mix (const WeightTable & tables ,const ModelGeometry & g ,const BlockBuffers & bb , 1398void * stream , std::string & err ) { 1399const WeightRef * wn = tables .find ("output_hc_norm.weight" ); 1400const WeightRef * wd = tables .find ("output_hc_down.weight" ); 1401const WeightRef * wu = tables .find ("output_hc_up.weight" ); 1402if (!wn || !wd || !wu ) { 1403err = "lm_head: an output_hc_* weight is missing" ; 1404return false; 1405 } 1406if (wn -> kind != WeightKind ::F32 || wd -> kind != WeightKind ::Bf16InF32 || 1407wu -> kind != WeightKind ::Bf16InF32 ) { 1408err = "lm_head: the output_hc_* weights have the wrong engine forms" ; 1409return false; 1410 } 1411const strata::kernels::GrShapes gs {g .n_embd ,g .hc ,g .hc_lr }; 1412 strata::kernels::gr_read (bb .R , (const float * )wn -> data , (const uint16_t * )wd -> data , 1413 (const uint16_t * )wu -> data ,nullptr ,RMS_EPS ,gs ,bb .gr , 1414bb .mixed ,bb .inject ,stream ); 1415return true; 1416} 1417 1418bool lm_head (const WeightTable & tables ,const ModelGeometry & g ,const BlockBuffers & bb , 1419float * logits ,void * stream , std::string & err ) { 1420const WeightRef * wo = tables .find ("output.weight" ); 1421if (!wo ) {err = "output.weight is missing" ;return false; } 1422 strata::kernels::SForm form ; 1423Planes planes ; 1424if (!sform_of (* wo ,form ,"output.weight" ,err )|| 1425 !plane_ptrs (* wo ,"output.weight" ,planes ,err ))return false; 1426if (g .n_embd %Q8K_ELEMS_PER_BLOCK != 0 ) { 1427err = "lm_head: n_embd is not a multiple of 256" ; 1428return false; 1429 } 1430if (!lm_head_mix (tables ,g ,bb ,stream ,err ))return false; 1431 strata::kernels::quantize_q8_K (bb .mixed ,bb .head_q8k ,g .n_embd ,stream ); 1432return gemv_quantized (* wo ,planes ,form ,bb .head_q8k ,bb .head_q8k ,logits , 1433g .n_embd ,wo -> ne1 ,"output.weight" ,stream ,err ); 1434} 1435// ================================ ONE WHOLE BLOCK ================================ 1436uint64_t block_buffers_bytes (const ModelGeometry & g ) {const strata::kernels::GrShapes s {g .n_embd ,g .hc ,g .hc_lr };uint64_t n = 0 ;n += (uint64_t )g .hc * g .n_embd * 4 ; 1437// R 1438n += (uint64_t )g .n_embd * 4 ; 1439// mixed 1440n += (uint64_t )g .n_embd * 4 ; 1441// block_out 1442n += (uint64_t )g .hc * 4 ; 1443// inject 1444n += (uint64_t )g .hc * 4 * 2 + 32 ; 1445// inject2, gr_rs 1446n += q8k_bytes (g .n_embd ); 1447// head_q8k 1448n += strata::kernels::gr_workspace_bytes (s );return align_up16 (n )+ 256 ;} 1449uint64_t block_buffers_init (const ModelGeometry & g ,void * base ,BlockBuffers & b ) {const strata::kernels::GrShapes s {g .n_embd ,g .hc ,g .hc_lr };Cursor c {(uint8_t * )base };b .R = c .take < float > ((uint64_t )g .hc * g .n_embd );b .mixed = c .take < float > ((uint64_t )g .n_embd );b .block_out = c .take < float > ((uint64_t )g .n_embd );b .inject = c .take < float > ((uint64_t )g .hc );b .inject2 = c .take < float > ((uint64_t )g .hc );b .gr_rs = c .take < float > ((uint64_t )g .hc );b .head_q8k = c .take_bytes (q8k_bytes (g .n_embd ));uint8_t * grw = c .take_bytes (strata::kernels::gr_workspace_bytes (s )); strata::kernels::gr_workspace_init (s ,grw ,b .gr );return c .used ;} 1450// ---- THE HALF-LEVEL C1 ORACLE. `dump` is a HOST buffer of `2 * n_embd + 2 * hc + n_head * head_dim` floats 1451// per layer; this enqueues one slice of it as a device-to-host copy. **IT RUNS INSIDE THE CAPTURE**, which is 1452// the point: the copy becomes a node of that layer's graph and replays with it, so the layer functions stay one 1453// function each and no per-layer plumbing reaches `generate.cpp`. A null `dump` is the default and skips the 1454// enqueue entirely, so the fast path records no extra node. 1455uint64_t dump_stride_floats (const ModelGeometry & g ) { 1456// Layout per layer, all in floats: 1457// [0, 2*n_embd) the two halves' block_out 1458// [2*n_embd, +2*hc) the two halves' inject 1459// [+NH*HD) the QSA pre-gate attention 1460// [+2*NKV*HD) the QSA RAW vcur (as floats) 1461// [+NKV*HD/2) the gathered v_scratch, as fp16 pairs 1462// [+4) [+4) ids[0..3], then step[0..3] 1463// [+NKV*HD/2) the v_pool prefix, as fp16 pairs 1464// [+NKV*HD) the post-norm POST-ROPE kcur 1465// The last four are what separate a wrong projection from a wrong pool round trip. 1466const uint64_t nvk = (uint64_t )g .n_head_kv * g .head_dim ; 1467return (uint64_t )2 * g .n_embd + (uint64_t )2 * g .hc + (uint64_t )g .n_head * g .head_dim + 5 * nvk + 8 ; 1468} 1469static void dump_slot (float * dump ,const ModelGeometry & g ,int64_t layer ,const float * src ,uint64_t off , 1470uint64_t n ,void * stream ) { 1471if (dump == nullptr || src == nullptr || n == 0 )return ; 1472cudaMemcpyAsync (dump + (size_t )layer * dump_stride_floats (g )+ off ,src ,n * sizeof (float ), 1473cudaMemcpyDeviceToHost , (cudaStream_t )stream ); 1474} 1475static void dump_half (const BlockBuffers & bb ,const ModelGeometry & g ,int64_t layer ,const float * src , 1476uint64_t off ,uint64_t n ,void * stream ) { 1477dump_slot (bb .dump ,g ,layer ,src ,off ,n ,stream ); 1478} 1479bool block_layer_pre (const WeightTable & tables ,const ModelGeometry & g ,int64_t layer ,int64_t pos ,int32_t pos_base ,const GdnBuffers & gb ,const QsaState & qst ,const QsaBuffers & qb ,const MoEBuffers & mb ,int64_t k ,const BlockBuffers & bb ,void * stream , std::string & err ,const Doorbell * db ,const PleRun * ple ,int half ,int stage_prefix ) { 1480// ================================ THE PLE, AT LAYER 1 ONLY ================================ 1481// 1482// **THIS IS THE CALL WHOSE ABSENCE FAILED GATE C1.** Layer 1 carries the six `blk.1.ple_*` tensors and no 1483// other layer does; every part of the module was built and parity-tested and none of it was reachable from 1484// here. The block's output is `hidden + gated + silu(conv)` on the RESIDUAL STACK ITSELF, so it is a 1485// residual update applied BEFORE layer 1's own `gr_read` - which is what the architecture means by the 1486// gathered rows arriving "before layer 2". 1487// 1488// **THE HASH AND THE GATHER ARE *NOT* HERE, AND THAT IS THE WHOLE REASON `ple_stage_token` EXISTS.** Both 1489// are HOST operations - the hash is 64-bit multiply/xor that `qwen4exp.cpp` says is host-side because "ggml 1490// has no int64 and no xor", and the table is a host mapping. This function is CAPTURED, so anything host 1491// side in it runs ONCE, at capture time, and the graph then replays that result for every token: the engine 1492// would gather the capture-time token's rows forever and produce a perfectly finite, perfectly stable, 1493// completely wrong answer. It is the same bug as the doorbell's cloned literal, and it is silent. 1494// 1495// So the driver calls `ple_stage_token` once per token, BEFORE the graphs, and what is captured here is only 1496// the device half: `ple_block` reading `emb_dev`, and the history shift. 1497const bool fused = g_fused_gr && stage_prefix == 0 && half == 0 && 1498 strata::kernels::fused_gr_supported (g .n_embd ,g .hc ,g .hc_lr ); 1499// layer-1's FFN write has not been applied to R yet - unless a control vector follows it, which needs R 1500bool pending_ffn = fused && layer > 0 && !strata::kernels::cvec ().covers (layer - 1 ); 1501if (ple != nullptr && ple -> ready ()&& layer == 1 && (half == 0 || half == 1 )) { 1502if (pending_ffn ) { 1503const strata::kernels::GrShapes gs0 {g .n_embd ,g .hc ,g .hc_lr }; 1504gr_write (bb .R ,bb .block_out ,bb .inject2 ,gs0 ,bb .R ,stream ); 1505pending_ffn = false; 1506 } 1507const int64_t hcd = strata::kernels::NG_HC_DIM ; 1508 strata::kernels::PleOut po ; 1509// Exports must not alias the block's internal workspace. The previous diagnostic views used a 1510// different layout inside that workspace: exporting gated values overwrote normalized values 1511// before the latter were copied to history. Allocate only the one export the recurrence needs. 1512po .normalized = (float * ) ((uint8_t * )ple -> scratch + strata::kernels::ple_block_scratch_bytes ()); 1513// `result` IS THE RESIDUAL, in place: the block computes `hidden[i] + gated[i] + conv[i]` elementwise, 1514// so reading and writing `R` at the same index is well-defined. 1515po .result = bb .R ; 1516try { 1517 strata::kernels::ple_block (ple -> emb_dev ,bb .R ,ple -> hist ,ple -> w ,po ,ple -> scratch ,stream ); 1518 }catch (const std::exception & error ) { 1519err = std::string ("block_layer_pre PLE: " )+ error .what (); 1520return false; 1521 } 1522 1523// ---- AND THE HISTORY ADVANCES, ONCE PER TOKEN, WHICH IS WHAT MAKES IT A CONV HISTORY. 1524// 1525// `ple_block` deliberately does NOT write back to the history - "the caller keeps ownership of its 1526// state and this stays a pure function of its inputs, which is what makes the chunked-versus-single-shot 1527// property testable" - so the shift is here. The layout is ROW-FASTEST (`hist[row + NG_HIST*channel]`, 1528// from `ggml_reshape_3d(state, d_conv-1, conv_channels, n_seqs)`), so a row shift is a STRIDED copy of 1529// NG_HIST-1 elements per channel and an append is a strided copy of one - not a flat memmove, which 1530// would be the natural reading and would scramble the channels. 1531 strata::kernels::ple_history_advance (ple -> hist ,po .normalized ,stream ); 1532if (cudaPeekAtLastError ()!= cudaSuccess ) { 1533err = "block_layer_pre: the PLE history shift failed" ; 1534return false; 1535 } 1536 } 1537const bool qsa = is_qsa_layer (g ,layer );const LayerView v (tables ,layer );const strata::kernels::GrShapes gs {g .n_embd ,g .hc ,g .hc_lr }; 1538// ---- the two halves' GR tensors. Both halves have the same four names with a different prefix, and the 1539// prefix is the ONLY thing that distinguishes them - so it is built rather than written twice. 1540const char * pre [2 ]= {"hc_attn_" ,"hc_ffn_" };const WeightRef * w_norm [2 ];const WeightRef * w_down [2 ];const WeightRef * w_up [2 ];const WeightRef * w_inject [2 ];for (int h = 0 ;h < 2 ;++ h ) {const std::string a = std::string (pre [h ])+ "norm.weight" ;const std::string d = std::string (pre [h ])+ "down.weight" ;const std::string u = std::string (pre [h ])+ "up.weight" ;const std::string i = std::string (pre [h ])+ "inject.weight" ;w_norm [h ]= v .get (a .c_str ());w_down [h ]= v .get (d .c_str ());w_up [h ]= v .get (u .c_str ());w_inject [h ]= v .get (i .c_str ());if (!w_norm [h ]|| !w_down [h ]|| !w_up [h ]|| !w_inject [h ]) {err = v .name ((std::string (pre [h ])+ "{norm,down,up,inject}.weight" ).c_str ())+ " is missing" ;return false; } 1541// The GR weights are BF16 and the arena holds them re-rounded to 2 B/elem. `gr_read` wants exactly 1542// that; handing it f32 bytes would walk 2x the tensor inside the arena without faulting. 1543if (w_down [h ]-> kind != WeightKind ::Bf16InF32 || w_up [h ]-> kind != WeightKind ::Bf16InF32 || w_inject [h ]-> kind != WeightKind ::Bf16InF32 || w_norm [h ]-> kind != WeightKind ::F32 ) {err = v .name (pre [h ])+ "has the wrong engine forms (norm must be F32, the other three bf16)" ;return false; } } 1544// ---- half 1: the mixer 1545float * R = bb .R ; 1546// R0.11: WHICH STAGES TO RUN. `stage_prefix == 0` means "as `half` says", so every caller that predates 1547// this parameter is bit-for-bit unaffected; `stage_prefix == k` runs stages 0..k-1 and ignores `half`. 1548const bool run0 = stage_prefix > 0 ? (stage_prefix >=1 ) : (half == 0 || half == 1 ); 1549const bool run1 = stage_prefix > 0 ? (stage_prefix >=2 ) : (half == 0 || half == 1 ); 1550const bool run2 = stage_prefix > 0 ? (stage_prefix >=3 ) : (half == 0 || half == 1 ); 1551const bool run3 = stage_prefix > 0 ? (stage_prefix >=4 ) : (half == 0 || half == 2 ); 1552const bool run4 = stage_prefix > 0 ? (stage_prefix >=5 ) : (half == 0 || half == 2 );// R0.9: this is the MIXER half, and `half == 2` skips it entirely. A `half` of 1 or 0 runs it, 1553// and 0 is what every caller before this used. 1554if (run0 ) { 1555st_begin (layer ,0 ,stream ); 1556if (fused ) { 1557 strata::kernels::FusedGrArgs fa ; 1558fa .R = R ;fa .R_out = R ;fa .apply = pending_ffn ;fa .bo_prev = bb .block_out ;fa .inj_prev = bb .inject2 ; 1559fa .w_norm = (const float * )w_norm [0 ]-> data ;fa .w_down = NativeDense ::hc_bf16_view (* w_down [0 ],stream ,0 ,1 ); 1560fa .w_up = NativeDense ::hc_bf16_view (* w_up [0 ],stream ,1 ,1 );fa .s_down = w_down [0 ]-> q8_scale ;fa .s_up = w_up [0 ]-> q8_scale ;fa .w_inject = (const uint16_t * )w_inject [0 ]-> data ; 1561fa .eps = RMS_EPS ;fa .lo = bb .gr .lo ;fa .rs = bb .gr_rs ;fa .inject_out = bb .inject ;fa .mixed = bb .mixed ; 1562 strata::kernels::fused_gr_read (fa ,stream ); 1563 }else { 1564if (w_down [0 ]-> q8_scale || w_up [0 ]-> q8_scale ) {err = "STRATA_HC_REQ8 needs the fused hyper-connection read" ;return false; }gr_read (R , (const float * )w_norm [0 ]-> data ,NativeDense ::hc_bf16_view (* w_down [0 ],stream ,0 ,1 ),NativeDense ::hc_bf16_view (* w_up [0 ],stream ,1 ,1 ), (const uint16_t * )w_inject [0 ]-> data ,RMS_EPS ,gs ,bb .gr ,bb .mixed ,bb .inject ,stream ); 1565 } 1566st_end (layer ,0 ,stream );dump_half (bb ,g ,layer ,bb .inject ,2 * g .n_embd ,g .hc ,stream ); } 1567if (run1 ) { 1568st_begin (layer ,1 ,stream );if (qsa ) {if (!qsa_layer (tables ,g ,layer ,pos ,pos_base ,qst ,qb ,bb .mixed ,bb .block_out ,stream ,err ,bb .dump ))return false; }else {if (!gdn_layer (tables ,g ,layer ,gb ,bb .mixed ,bb .block_out ,stream ,err ))return false; }st_end (layer ,1 ,stream );dump_half (bb ,g ,layer ,bb .block_out ,0 ,g .n_embd ,stream ); } 1569if (run2 ) { 1570st_begin (layer ,2 ,stream );if (!fused )gr_write (R ,bb .block_out ,bb .inject ,gs ,R ,stream );st_end (layer ,2 ,stream ); 1571// ---- half 2, UP TO AND INCLUDING THE ROUTER. `gr_read` leaves the normed activation in `bb.mixed` and 1572// the per-stream injection in `bb.inject`, and BOTH must survive until `block_layer_post` runs - which is 1573// the contract the two functions have with each other and with the host loop's ordering. 1574 } 1575// R0.9: the FFN front and the ROUTER. It reads `bb.mixed`/`bb.inject`, which the mixer left - 1576// the same contract `block_layer_post` has, and the reason the two are only meaningful in order. 1577if (run3 ) { 1578st_begin (layer ,3 ,stream ); 1579if (fused ) { 1580 strata::kernels::FusedGrArgs fa ; 1581fa .R = R ;fa .R_out = R ;fa .apply = true;fa .bo_prev = bb .block_out ;fa .inj_prev = bb .inject ; 1582fa .w_norm = (const float * )w_norm [1 ]-> data ;fa .w_down = NativeDense ::hc_bf16_view (* w_down [1 ],stream ,0 ,1 ); 1583fa .w_up = NativeDense ::hc_bf16_view (* w_up [1 ],stream ,1 ,1 );fa .s_down = w_down [1 ]-> q8_scale ;fa .s_up = w_up [1 ]-> q8_scale ;fa .w_inject = (const uint16_t * )w_inject [1 ]-> data ; 1584fa .eps = RMS_EPS ;fa .lo = bb .gr .lo ;fa .rs = bb .gr_rs ;fa .inject_out = bb .inject2 ;fa .mixed = bb .mixed ; 1585 strata::kernels::fused_gr_read (fa ,stream ); 1586 }else { 1587if (w_down [1 ]-> q8_scale || w_up [1 ]-> q8_scale ) {err = "STRATA_HC_REQ8 needs the fused hyper-connection read" ;return false; }gr_read (R , (const float * )w_norm [1 ]-> data ,NativeDense ::hc_bf16_view (* w_down [1 ],stream ,0 ,1 ),NativeDense ::hc_bf16_view (* w_up [1 ],stream ,1 ,1 ), (const uint16_t * )w_inject [1 ]-> data ,RMS_EPS ,gs ,bb .gr ,bb .mixed ,bb .inject ,stream ); 1588 } 1589st_end (layer ,3 ,stream ); } 1590if (run4 ) { 1591st_begin (layer ,4 ,stream ); {const bool ok = moe_route (tables ,g ,layer ,k ,mb ,bb .mixed ,stream ,err ,db );st_end (layer ,4 ,stream );if (!ok )return false; } 1592// Plan v0.3 P3: after the ring, so the GPU computes the shared expert while the host runs the pool. 1593if (g_shared_early && !moe_shared (tables ,g ,layer ,mb ,bb .mixed ,stream ,err ))return false; 1594 } 1595// Every stage this call was asked to run has run. There is no other way out: the old `return ok;` 1596// lived inside the stage-4 block and restructuring that left the function with no return at all. 1597return true; 1598} 1599bool ple_issue_token (const PleRun & p , std::string & err ) { 1600if (!p .ready ()) {err = "ple_issue_token: the PLE run is not ready" ;return false; } 1601uint32_t rows [strata::kernels::PLE_N_HEADS ]; 1602 strata::kernels::ngram_rows (p .token ,p .prev ,1 ,p .consts ,rows ); 1603if (!p .table -> issue (rows )) {err = "ple_issue_token: the previous token's rows were never collected" ;return false; } 1604return true; 1605} 1606 1607bool ple_finish_token (const PleRun & p ,void * stream , std::string & err ) { 1608if (!p .ready ()) {err = "ple_finish_token: the PLE run is not ready" ;return false; } 1609if (!p .table -> collect (p .emb_host ,err )) {err = "ple_finish_token: " + err ;return false; } 1610if (cudaMemcpyAsync (p .emb_dev ,p .emb_host , (size_t ) strata::kernels::NG_N_EMBD * sizeof (float ), 1611cudaMemcpyHostToDevice , (cudaStream_t )stream )!= cudaSuccess ) { 1612err = "ple_finish_token: the row upload failed" ; 1613return false; 1614 } 1615return true; 1616} 1617 1618bool ple_stage_token (const PleRun & p ,void * stream , std::string & err ) { 1619if (!ple_issue_token (p ,err ))return false; 1620return ple_finish_token (p ,stream ,err ); 1621} 1622 1623uint64_t ple_run_scratch_bytes () { 1624// Internal workspace followed by a disjoint normalized export used for the next history row. 1625return strata::kernels::ple_block_scratch_bytes ()+ strata::kernels::NG_HC_DIM * sizeof (float ); 1626} 1627 1628bool block_layer_post (const WeightTable & tables ,const ModelGeometry & g ,int64_t layer ,int64_t k ,const MoEBuffers & mb ,const BlockBuffers & bb ,const float * parts ,void * stream , std::string & err ) {const strata::kernels::GrShapes gs {g .n_embd ,g .hc ,g .hc_lr }; 1629// `bb.mixed` and `bb.inject` are what `block_layer_pre` left, and NOTHING between the two calls may touch 1630// them - that is what makes `post[l]` safe to launch after the host has run the pool. 1631st_begin (layer ,5 ,stream ); 1632if (g_shared_early ? !moe_combine_parts (g ,layer ,k ,mb ,parts ,bb .block_out ,stream ,err ) 1633 : !moe_finish (tables ,g ,layer ,k ,mb ,bb .mixed ,parts ,bb .block_out ,stream ,err ))return false; 1634st_end (layer ,5 ,stream );dump_half (bb ,g ,layer ,bb .block_out , (uint64_t )g .n_embd ,g .n_embd ,stream );dump_half (bb ,g ,layer ,bb .inject , (uint64_t )2 * g .n_embd + g .hc ,g .hc ,stream );st_begin (layer ,6 ,stream ); 1635const bool steer = strata::kernels::cvec ().covers (layer );// --control-vector-scaled: after this write 1636try { 1637if (!(g_fused_gr && strata::kernels::fused_gr_supported (g .n_embd ,g .hc ,g .hc_lr ))) { 1638gr_write (bb .R ,bb .block_out ,bb .inject ,gs ,bb .R ,stream ); 1639if (steer ) strata::kernels::cvec_apply (bb .R ,layer ,1 ,g .hc * g .n_embd ,nullptr ,0 ,nullptr ,0 , false,stream ); 1640 }else if (layer == g .n_layers - 1 ) { 1641gr_write (bb .R ,bb .block_out ,bb .inject2 ,gs ,bb .R ,stream );// materialise R for the head 1642if (steer ) strata::kernels::cvec_apply (bb .R ,layer ,1 ,g .hc * g .n_embd ,nullptr ,0 ,nullptr ,0 , false,stream ); 1643 }else if (steer ) { 1644// the write the next layer's fused read would have folded, then the vector 1645 strata::kernels::cvec_apply (bb .R ,layer ,1 ,g .hc * g .n_embd ,bb .block_out ,g .n_embd ,bb .inject2 ,g .hc , 1646 true,stream ); 1647 } 1648 }catch (const std::exception & e ) { 1649err = std::string ("block_layer_post: " )+ e .what (); 1650return false; 1651 } 1652st_end (layer ,6 ,stream );return true;} 1653bool block_layer (const WeightTable & tables ,const ModelGeometry & g ,int64_t layer ,int64_t pos ,int32_t pos_base ,const GdnBuffers & gb ,const QsaState & qst ,const QsaBuffers & qb ,const MoEBuffers & mb ,int64_t k ,const BlockBuffers & bb ,const float * parts ,void * stream , std::string & err ,const Doorbell * db ,const PleRun * ple ) { 1654// The two halves back to back. `parts` must be THIS layer's experts and must be ready before the call - 1655// which holds for `session_token`, where the caller supplies them, and does NOT hold for a host loop that 1656// has only just seen the router. That is why the captured path calls the halves separately. 1657if (!block_layer_pre (tables ,g ,layer ,pos ,pos_base ,gb ,qst ,qb ,mb ,k ,bb ,stream ,err ,db ,ple ))return false;return block_layer_post (tables ,g ,layer ,k ,mb ,bb ,parts ,stream ,err );}} 1658// namespace strata::core