okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
52d2d3ee2
main
1// prefill_expert_paths_bench - one prompt layer of routed experts, timed on every path the engine can take for it, side by side: 2// MMQ llama.cpp's int8 MMQ kernels in prefill.cpp's sequence (gather_native into 16-expert groups, q8_1 of the rows, gate/up, SwiGLU, q8_1 of H, down) 3// (only in a build that has MMQ; prefill_fused_iq_test.cpp's run_mmq, the same calls) 4// FP16 the engine's dequantize + FP16 GEMM path, per expert: iq_dequant_gu_f16 + iq_dequant_f16, Gemm::f16 (gate/up), swiglu_interleaved, 5// Gemm::f16 (down), after one gather_rows16 of the layer's rows. These are the calls of prefill.cpp's `compute` lambda, FP16 branch 6// (src/prefill/prefill.cpp, "const int q = (int) (j % DQ); if (lay.native) { ... iq_dequant_gu_f16 ... m.gemm.f16 ... swiglu_interleaved ... 7// m.gemm.f16 }"), with the engine's two-slot dequantize ring (DQ = 2) and its Gemm set up as Prefill::init sets it (init_external with the 8// 32 MiB workspace, set_f16_io(prompt_f16()), set_act_f16). Nothing of that sequence is re-implemented here: every call is the library's. 9// FP16+FR the same with the few-row experts (fewrows.hpp, STRATA_PF_FEWROWS; the engine's default on a Tesla P100) on the quantized grouped kernels: 10// an expert with 1..kFewRows rows runs fewrows_record + native_expert_grouped on the GGUF blob instead of the dequantize and the two GEMMs 11// (prefill.cpp, "if (fr_env) { ... fewrows_takes(...) ... fewrows_record ... native_expert_grouped(...) }") 12// GRP the whole layer in one native_expert_grouped call (the grouped decode-family kernels on q8_1 activations): what the Qwen3.6 engine 13// (q36_engine.cu) runs for a layer with neither fused kernels nor MMQ, and what the verify window uses. Off unless --grouped or --shape=q36. 14// FUSED Strata's own fused int8 kernels (moe_fused_iq.hpp experts_native; at the Qwen3.6 shape the copy moe_fused_iq_q36.cu's experts_native_ext) 15// where the card has them for the pair. The opt-in switches that select them (STRATA_PF_FUSED=1, _KQ, _Q50, _Q8D, _Q8GU, _Q6K) are set 16// when not already set, so the column shows what the kernels do, not what the engine picks by default on this card. 17// No model file is read. Every path's output is hashed (FNV-1a over the bits, in pair order) and a sample of pairs (default 96) is compared with a 18// CPU FP32 reference (ggml's own to_float of the weights, FP32 activations, double sums): rel RMS and worst row. 19// 20// Synthetic weights are random GGUF blocks with a sane scale (as prefill_fused_iq_test.cpp); 512 / 256 blobs at the engine's stride; routing is K distinct 21// experts per token, uniform (--skew=0, as the timing part of prefill_fused_iq_test.cpp) or Zipf-skewed (--skew=S: expert e has weight (e+1)^-S). 22// 23// prefill_expert_paths_bench [--shape=flash|q36|N,FF,E,K] [--tokens=2048,4096,8192,20000] [--only=NAME]... [--all] [--list] 24// [--repeats=7] [--warm-ms=1000] [--skew=S] [--experts=E] [--sample=96] [--seed=N] [--grouped] [--no-mmq] [--no-fused] [--no-fp16] [--no-ref] [--quick] 25// Exit 0 when it ran, 1 on an error, 77 without a device (ctest skip). One machine-readable line per cell starts with "RESULT ". 26// 27// What it does not capture of a real run: expert streaming (every expert is resident here), the engine's chunking of a long prompt (one chunk of T tokens), 28// attention / GDN / dense layers, the drafter, the KV cache, and the host-side planning between layers. 29// (a HIP build compiles this file as plain C++ against the compat headers: STRATA_USE_HIP comes with strata_hip_runtime, __HIPCC__ only in .cu / HIP-language files) 30#if defined(__HIPCC__ )|| defined(STRATA_USE_HIP ) 31#define FB_HIP 1 32#endif 33#include "strata/kernels/iq_kernels.hpp" 34#include "strata/prefill/fewrows.hpp" 35#include "strata/prefill/gemm.hpp" 36#include "strata/prefill/kernels.hpp" 37#include "strata/prefill/mmq_ids_margin.hpp" 38#include "strata/prefill/moe_fused_iq.hpp" 39#include "strata/prefill/moe_mmq.hpp" 40#if !defined(FB_HIP ) 41#include "strata/prefill/moe_fused_q36.hpp" 42#endif 43 44#include "ggml.h" 45#include "strata/quant/types.hpp" 46#include "../prefill/bench_blob_layout.hpp" 47 48#include <cuda_runtime.h> 49 50#include <algorithm> 51#include <array> 52#include <cmath> 53#include <cstdint> 54#include <cstdio> 55#include <cstdlib> 56#include <cctype> 57#include <cstring> 58#include <fstream> 59#include <functional> 60#include <memory> 61#include <random> 62#include <stdexcept> 63#include <string> 64#include <thread> 65#include <vector> 66 67namespace { 68namespace mmq= strata::prefill::mmq; 69namespace fused= strata::prefill::fused; 70namespace kern= strata::kernels; 71namespace pf= strata::prefill; 72 73constexpr int GROUP = 16 ;// MMQ's expert group (prefill.cpp MMQ_GROUP) 74constexpr int DQ = 2 ;// the engine's dequantized-expert ring (prefill.cpp DQ) 75constexpr int64_t GEMM_SCRATCH = 32ll <<20 ;// prefill.cpp GEMM_SCRATCH / GEMM_WS: the engine's Gemm::init_external sizes 76constexpr size_t GEMM_WS = 32u <<20 ; 77 78void ck (cudaError_t e ,const char * what ) { 79if (e != cudaSuccess )throw std::runtime_error (std::string (what )+ ": " + cudaGetErrorString (e )); 80} 81 82struct Dev { 83void * p = nullptr ; 84size_t n = 0 ; 85explicit Dev (size_t bytes = 0 ) :n (bytes ) {if (bytes )ck (cudaMalloc (& p ,bytes ),"cudaMalloc" ); } 86 ~Dev () {if (p )cudaFree (p ); } 87Dev (const Dev & )= delete ; 88Dev & operator= (const Dev & )= delete ; 89Dev (Dev && o )noexcept :p (o .p ),n (o .n ) {o .p = nullptr ;o .n = 0 ; } 90Dev & operator= (Dev && o )noexcept { 91if (this != & o ) {if (p )cudaFree (p );p = o .p ;n = o .n ;o .p = nullptr ;o .n = 0 ; } 92return * this ; 93 } 94template < typename T > T * as ()const {return (T * )p ; } 95}; 96 97struct Shape { 98int N ,FF ,E ,K ; 99 std::string name ; 100int FF2 ()const {return 2 * FF ; } 101}; 102 103struct Pair { 104ggml_type gu ,d ; 105const char * name ; 106}; 107 108size_t type_size (ggml_type t ) {return ggml_type_size (t ); } 109int64_t blck_size (ggml_type t ) {return ggml_blck_size (t ); } 110size_t row_size (ggml_type t ,int64_t n ) {return (size_t ) (n /blck_size (t ))* type_size (t ); } 111bool fits_blocks (ggml_type t ,int64_t n ) {return n %blck_size (t )== 0 ; } 112 113// NVFP4 (ModelOpt packs: gate/up and down NVFP4): the blob ends with a 16-byte tail {s_gate, s_up, s_down, 0}, the per-expert weight_scale_2 values 114// (cpu::NativeFmt::tail_off = down_off + d_row n_embd). Every path applies them as the engine does: MMQ around its products (swiglu_scaled, scale_down_rows), 115// the FP16 path on the dequantized weights (iq_dequant_gu_f16 / iq_dequant_f16's scale), the fused kernels on their FP32 products. 116bool nvfp4_pair (const Pair & p ) {return p .gu == GGML_TYPE_NVFP4 && p .d == GGML_TYPE_NVFP4 ; } 117 118struct Geo { 119size_t gu_row ,d_row ,up_off ,down_off ,bytes ; 120size_t tail_off = 0 ;// 0: no tail 121Geo (const Pair & p ,const Shape & s ) { 122gu_row = row_size (p .gu ,s .N ); 123d_row = row_size (p .d ,s .FF ); 124up_off = gu_row * (size_t )s .FF ; 125down_off = 2 * up_off ; 126bytes = down_off + d_row * (size_t )s .N ; 127if (nvfp4_pair (p )) { 128tail_off = bytes ; 129bytes += 16 ; 130 } 131 } 132}; 133 134// random blocks with a sane fp16 scale `d` at each block's start (as prefill_fused_iq_test.cpp's fill_matrix), scales chosen so that the weights' 135// typical size is that of a 2-3 bit expert (a few hundredths). IQ1_M has no leading d: its fp16 scale is spread over the top nibbles of its four 136// 16-bit sub-scales (block_iq1_m: qs[32] qh[16] scales[8]). 137void fill_matrix (uint8_t * m ,ggml_type t ,int64_t rows ,int64_t cols , std::mt19937 & rng ) { 138const size_t bs = type_size (t ),nb = (size_t )rows * (size_t ) (cols /blck_size (t )); 139 std::uniform_int_distribution < int > byte (0 ,255 ); 140const float lo = t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q5_K ?0.00004f :t == GGML_TYPE_Q5_1 ?0.0006f 141 :t == GGML_TYPE_Q8_0 ?0.0001f :t == GGML_TYPE_IQ3_S ?0.0004f :t == GGML_TYPE_IQ4_XS ?0.00005f 142 :t == GGML_TYPE_IQ4_NL ?0.0002f :t == GGML_TYPE_Q2_0 ?0.004f :t == GGML_TYPE_Q6_K ?0.000005f 143 :t == GGML_TYPE_IQ1_M ?0.002f :0.0008f ; 144 std::uniform_real_distribution < float > sc (lo ,6.0f * lo ); 145for (size_t i = 0 ;i < nb * bs ;++ i )m [i ]= (uint8_t )byte (rng ); 146if (t == GGML_TYPE_NVFP4 ) {// four UE4M3 scale bytes then 32 bytes of codes: scales 0x28..0x58 (finite, bit 7 clear), the codes as drawn 147 std::uniform_int_distribution < int > ub (0x28 ,0x58 ); 148for (size_t b = 0 ;b < nb ;++ b ) 149for (int k = 0 ;k < 4 ;++ k )m [b * bs + (size_t )k ]= (uint8_t )ub (rng ); 150return ; 151 } 152for (size_t b = 0 ;b < nb ;++ b ) { 153const ggml_fp16_t h = ggml_fp32_to_fp16 (sc (rng )); 154uint8_t * blk = m + b * bs ; 155if (t == GGML_TYPE_IQ1_M ) { 156uint16_t s16 [4 ]; 157 std::memcpy (s16 ,blk + 48 ,8 ); 158for (int k = 0 ;k < 4 ;++ k )s16 [k ]= (uint16_t ) ((s16 [k ]& 0x0fff ) | (((unsigned )h >> (4 * k ))& 0xf ) <<12 ); 159 std::memcpy (blk + 48 ,s16 ,8 ); 160continue ; 161 } 162 std::memcpy (blk + (t == GGML_TYPE_Q6_K ?208 :0 ),& h ,2 );// (Q6_K keeps d at its end; its 16 int8 scales stay random bytes) 163if (t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q5_K || t == GGML_TYPE_Q5_1 ) {// the minimum's scale, either sign 164const ggml_fp16_t h2 = ggml_fp32_to_fp16 (sc (rng )* ((rng ()& 1 ) ?1.0f :-1.0f )* (t == GGML_TYPE_Q5_1 ?4.0f :1.0f )); 165 std::memcpy (blk + 2 ,& h2 ,2 ); 166 } 167 } 168} 169std::vector < uint8_t > make_blob (const Pair & p ,const Geo & g ,const Shape & s , std::mt19937 & rng ) { 170 std::vector < uint8_t > b (g .bytes ); 171fill_matrix (b .data (),p .gu ,2 * s .FF ,s .N ,rng ); 172fill_matrix (b .data ()+ g .down_off ,p .d ,s .N ,s .FF ,rng ); 173if (g .tail_off ) {// the per-expert scales, about 1e-4 .. 1e-3 174 std::uniform_real_distribution < float > ss (2e-4f ,2e-3f ); 175const float t [4 ]= {ss (rng ),ss (rng ),ss (rng ),0.0f }; 176 std::memcpy (b .data ()+ g .tail_off ,t ,16 ); 177 } 178return b ; 179} 180 181// ggml's dequantized weights of one expert: gate [FF][N], up [FF][N] (rows 0..FF-1 and FF..2FF-1 of gu), down [N][FF] 182void dequant (const Pair & p ,const Geo & g ,const Shape & s ,const std::vector < uint8_t >& b , std::vector < float >& gu , std::vector < float >& dn ) { 183gu .resize ((size_t )2 * s .FF * s .N ); 184dn .resize ((size_t )s .N * s .FF ); 185const auto * tg = ggml_get_type_traits (p .gu ); 186const auto * td = ggml_get_type_traits (p .d ); 187for (int r = 0 ;r < 2 * s .FF ;++ r )tg -> to_float (b .data ()+ (size_t )r * g .gu_row ,gu .data ()+ (size_t )r * s .N ,s .N ); 188for (int r = 0 ;r < s .N ;++ r )td -> to_float (b .data ()+ g .down_off + (size_t )r * g .d_row ,dn .data ()+ (size_t )r * s .FF ,s .FF ); 189if (g .tail_off ) {// NVFP4: each projection times its own per-expert scale 190float t [4 ]; 191 std::memcpy (t ,b .data ()+ g .tail_off ,16 ); 192for (int r = 0 ;r < s .FF ;++ r )for (int k = 0 ;k < s .N ;++ k )gu [(size_t )r * s .N + k ] *=t [0 ]; 193for (int r = s .FF ;r < 2 * s .FF ;++ r )for (int k = 0 ;k < s .N ;++ k )gu [(size_t )r * s .N + k ] *=t [1 ]; 194for (size_t i = 0 ;i < dn .size ();++ i )dn [i ] *=t [2 ]; 195 } 196} 197 198// activations: N(0, 1) with a few large values (the hidden state has outliers) 199std::vector < float > make_x (int T ,int N , std::mt19937 & rng ) { 200 std::vector < float > x ((size_t )T * N ); 201 std::normal_distribution < float > nd (0.0f ,1.0f ); 202 std::uniform_int_distribution < int > pick (0 ,199 ); 203for (float & v :x )v = nd (rng )* (pick (rng )== 0 ?12.0f :1.0f ); 204return x ; 205} 206 207// K distinct experts per token; skew > 0: expert e is drawn with weight (e + 1)^-skew (the lowest ids are the hot ones) 208std::vector < int32_t > make_ids (int T ,int E ,int K ,double skew , std::mt19937 & rng ) { 209 std::vector < int32_t > ids ((size_t )T * K ); 210 std::uniform_int_distribution < int > any (0 ,E - 1 ); 211 std::vector < double > w ((size_t )E ); 212for (int e = 0 ;e < E ;++ e )w [(size_t )e ]= std::pow ((double ) (e + 1 ),- skew ); 213 std::discrete_distribution < int > zipf (w .begin (),w .end ()); 214for (int t = 0 ;t < T ;++ t ) 215for (int k = 0 ;k < K ;++ k ) { 216int e ; 217bool dup ; 218do { 219e = skew > 0 ?zipf (rng ) :any (rng ); 220dup = false; 221for (int j = 0 ;j < k ;++ j )dup |=ids [(size_t )t * K + j ]== e ; 222 }while (dup ); 223ids [(size_t )t * K + k ]= e ; 224 } 225return ids ; 226} 227 228struct Routing { 229 std::vector < int32_t > cnt ,off ,src ;// per expert; sorted row -> token (rows in pair order within an expert) 230 std::vector < int32_t > row_of ;// pair -> sorted row 231 std::vector < int32_t > order ;// experts with rows, ascending (the engine's `order`) 232}; 233Routing sort_rows (const std::vector < int32_t >& ids ,int E ,int K ) { 234Routing r ; 235r .cnt .assign ((size_t )E ,0 ); 236for (int32_t e :ids )++ r .cnt [(size_t )e ]; 237r .off .assign ((size_t )E + 1 ,0 ); 238for (int e = 0 ;e < E ;++ e )r .off [(size_t )e + 1 ]= r .off [(size_t )e ]+ r .cnt [(size_t )e ]; 239 std::vector < int32_t > fill (r .off .begin (),r .off .end ()- 1 ); 240r .src .resize (ids .size ()); 241r .row_of .resize (ids .size ()); 242for (size_t i = 0 ;i < ids .size ();++ i ) { 243const int32_t p = fill [(size_t )ids [i ]]++ ; 244r .row_of [i ]= p ; 245r .src [(size_t )p ]= (int32_t ) (i / (size_t )K ); 246 } 247for (int e = 0 ;e < E ;++ e )if (r .cnt [(size_t )e ]> 0 )r .order .push_back (e ); 248return r ; 249} 250 251// --------------------------------------------------------------------------------------------------------------------------------------------- 252// MMQ: prefill_fused_iq_test.cpp's run_mmq (the non-direct form), with the shape at run time. llama.cpp's mul_mat_q and its stream-k fixup read the 253// row-id table up to a J-column tile past the last row: the table takes mmq_ids_table_rows(rows, max_rows) entries (mmq_ids_margin.hpp). 254struct MmqPath { 255const Pair & p ; 256const Shape & s ; 257const Geo & geo ; 258 mmq::Context ctx ; 259Dev xq ,hq ,ident ,bounds ,grp_gu ,grp_d ,tails ;// tails: NVFP4's {s_gate, s_up, s_down, 0} of each expert of the open group 260const Dev & gu ,& h ,& dm ;// shared with the other paths (FP32 [rows][2FF], [rows][FF], [rows][N]) 261const Routing & r ; 262const std::vector < const uint8_t *>& blob ; 263int64_t rows ; 264size_t gub ,db ; 265MmqPath (const Pair & p_ ,const Shape & s_ ,const Geo & g_ ,int64_t rows_ ,const Routing & r_ ,const std::vector < const uint8_t *>& blob_ , 266const Dev & gu_ ,const Dev & h_ ,const Dev & dm_ ) 267 :p (p_ ),s (s_ ),geo (g_ ),xq (mmq::q8_bytes (rows_ ,s_ .N )),hq (mmq::q8_bytes (rows_ ,s_ .FF )), 268ident ((size_t ) mmq::mmq_ids_table_rows ((uint64_t )rows_ , (uint64_t ) (rows_ /s_ .K ))* 4 ), 269bounds ((size_t ) (2 * (s_ .E + s_ .E /GROUP + 2 ))* 4 ), 270grp_gu (GROUP * mmq::matrix_bytes (p_ .gu ,s_ .FF2 (),s_ .N )+ 4096 ),grp_d (GROUP * mmq::matrix_bytes (p_ .d ,s_ .N ,s_ .FF )+ 4096 ), 271tails ((size_t )GROUP * 16 ),gu (gu_ ),h (h_ ),dm (dm_ ),r (r_ ),blob (blob_ ),rows (rows_ ) { 272gub = mmq::matrix_bytes (p .gu ,s .FF2 (),s .N ); 273db = mmq::matrix_bytes (p .d ,s .N ,s .FF ); 274 } 275void run (const float * x_dev ,const int32_t * src_dev ,cudaStream_t st ) { 276const std::vector < int32_t >& order = r .order ; 277const size_t n = order .size (),ng = (n + GROUP - 1 ) /GROUP ; 278 std::vector < int32_t > bh (n + 1 + ng * (GROUP + 1 )); 279for (size_t j = 0 ;j < n ;++ j )bh [j ]= r .off [(size_t )order [j ]]; 280bh [n ]= (int32_t )rows ; 281for (size_t g = 0 ;g < ng ;++ g ) 282for (size_t i = 0 ;i <=GROUP ;++ i )bh [n + 1 + g * (GROUP + 1 )+ i ]= bh [std::min (n ,g * GROUP + i )]- bh [g * GROUP ]; 283ck (cudaMemcpyAsync (bounds .p ,bh .data (),bh .size ()* 4 ,cudaMemcpyHostToDevice ,st ),"bounds" ); 284 mmq::iota (ident .as < int32_t > (), (int64_t ) (ident .n /4 ),st ); 285 mmq::quantize (x_dev ,src_dev ,xq .p , (int )p .gu ,s .N ,s .N ,rows ,st ); 286const int FF = s .FF ,FF2 = s .FF2 (),N = s .N ; 287for (size_t j = 0 ;j < n ;++ j ) { 288const size_t q = j %GROUP ; 289const uint8_t * bl = blob [(size_t )order [j ]]; 290// NVFP4: the expert's tail goes next to its group slot in the same launch, as prefill.cpp's gather 291 mmq::gather_native (bl ,bl + geo .up_off ,gub /2 ,bl + geo .down_off ,db ,grp_gu .as < uint8_t > ()+ q * gub ,grp_d .as < uint8_t > ()+ q * db ,st , 292geo .tail_off ?bl + geo .tail_off :nullptr ,geo .tail_off ?tails .as < uint8_t > ()+ q * 16 :nullptr ); 293if (q + 1 < GROUP && j + 1 < n )continue ; 294const size_t j0 = j - q ,g = j0 /GROUP ; 295const int ngx = (int ) (q + 1 ); 296const int64_t r0 = bh [j0 ],nr = bh [j + 1 ]- r0 ; 297int64_t maxr = 0 ; 298for (size_t i = j0 ;i <=j ;++ i )maxr = std::max < int64_t > (maxr ,r .cnt [(size_t )order [i ]]); 299ck (cudaMemsetAsync (grp_gu .as < uint8_t > ()+ (size_t )ngx * gub ,0 ,4096 ,st ),"tail" ); 300ck (cudaMemsetAsync (grp_d .as < uint8_t > ()+ (size_t )ngx * db ,0 ,4096 ,st ),"tail" ); 301 mmq::Product pg ; 302pg .w = grp_gu .p ;pg .type = (int )p .gu ;pg .w_rows = FF2 ;pg .w_cols = N ;pg .expert_bytes = gub ; 303pg .n = ngx ;pg .xq = xq .p ;pg .bounds = bounds .as < int32_t > ()+ j0 ;pg .ids = ident .as < int32_t > (); 304pg .total_rows = rows ;pg .max_rows = maxr ;pg .dst = gu .as < float > ();pg .ld_dst = FF2 ; 305ctx .run (pg ,st ); 306if (geo .tail_off )// gate/up scales applied as read (prefill.cpp) 307 mmq::swiglu_scaled (gu .as < float > ()+ r0 * FF2 ,h .as < float > ()+ r0 * FF ,nr ,FF ,bounds .as < int32_t > ()+ j0 ,ngx ,tails .as < float > (),r0 ,st ); 308else 309 mmq::swiglu (gu .as < float > ()+ r0 * FF2 ,h .as < float > ()+ r0 * FF ,nr ,FF , false,st ); 310 mmq::quantize (h .as < float > ()+ r0 * FF ,nullptr ,hq .p , (int )p .d ,FF ,FF ,nr ,st ); 311 mmq::Product pd ; 312pd .w = grp_d .p ;pd .type = (int )p .d ;pd .w_rows = N ;pd .w_cols = FF ;pd .expert_bytes = db ; 313pd .n = ngx ;pd .xq = hq .p ;pd .bounds = bounds .as < int32_t > ()+ n + 1 + g * (GROUP + 1 ); 314pd .ids = ident .as < int32_t > ();pd .total_rows = nr ;pd .max_rows = maxr ;pd .dst = dm .as < float > ()+ r0 * N ; 315pd .ld_dst = N ; 316ctx .run (pd ,st ); 317// NVFP4's s_down on the FP32 rows (the engine applies it in the combine; the same product per row) 318if (geo .tail_off ) mmq::scale_down_rows (dm .as < float > ()+ r0 * N ,N ,pd .bounds ,ngx ,tails .as < float > (),nr ,st ); 319 } 320 } 321}; 322 323// --------------------------------------------------------------------------------------------------------------------------------------------- 324// FP16 (and FP16+FR): prefill.cpp's compute lambda, FP16 branch, with the library's own functions. 325struct Fp16Path { 326const Pair & p ; 327const Shape & s ; 328const Geo & geo ; 329 pf::Gemm & gemm ; 330Dev xs ,hh ,dqgu0 ,dqgu1 ,dqd0 ,dqd1 ,fr_rec ,fr_xq ,fr_scr ; 331const Dev & gu ,& dm ; 332const Routing & r ; 333const std::vector < const uint8_t *>& blob ; 334int64_t rows ; 335int T ; 336bool fr_ok ; 337 kern::NativeExpertLayout FL ; 338Fp16Path (const Pair & p_ ,const Shape & s_ ,const Geo & g_ , pf::Gemm & gm ,int T_ ,int64_t rows_ ,const Routing & r_ , 339const std::vector < const uint8_t *>& blob_ ,const Dev & gu_ ,const Dev & dm_ ,bool want_fr ) 340 :p (p_ ),s (s_ ),geo (g_ ),gemm (gm ),xs ((size_t )rows_ * s_ .N * 2 ),hh ((size_t )rows_ * s_ .FF * 2 ), 341dqgu0 ((size_t )s_ .FF2 ()* s_ .N * 2 ),dqgu1 ((size_t )s_ .FF2 ()* s_ .N * 2 ),dqd0 ((size_t )s_ .N * s_ .FF * 2 ),dqd1 ((size_t )s_ .N * s_ .FF * 2 ), 342gu (gu_ ),dm (dm_ ),r (r_ ),blob (blob_ ),rows (rows_ ),T (T_ ),fr_ok (false) { 343fr_ok = want_fr && kern::native_expert_supported ((int )p .gu , (int )p .d ,s .N ,s .FF ); 344if (fr_ok ) { 345FL = kern::native_expert_layout ((int )p .gu , (int )p .d ,s .N ,s .FF ); 346fr_rec = Dev ((size_t )s .E * pf::kFewRowsRecBytes ); 347fr_xq = Dev ((size_t )T * (size_t ) (s .N /32 )* 36 ); 348fr_scr = Dev (kern::native_expert_scratch_bytes (pf::kFewRows ,s .FF )); 349 } 350 } 351int few_rows_experts ()const { 352int c = 0 ; 353for (int e :r .order )c += pf::fewrows_takes (true, true, true, false,r .cnt [(size_t )e ]); 354return c ; 355 } 356void run (bool fr ,const float * x_dev ,const uint16_t * x16_dev ,const int32_t * src_dev ,cudaStream_t st ) { 357const int N = s .N ,FF = s .FF ,FF2 = s .FF2 (); 358 pf::gather_rows16 (x16_dev ,src_dev ,xs .as < uint16_t > (),rows ,N ,st ); 359if (fr && fr_ok ) kern::quantize_q8_1_rows (x_dev ,T ,N ,fr_xq .p ,st );// the layer's T rows as q8_1, once 360size_t j = 0 ; 361for (int32_t e :r .order ) { 362const int64_t o0 = r .off [(size_t )e ],ne = r .cnt [(size_t )e ]; 363const uint8_t * bl = blob [(size_t )e ]; 364if (fr && fr_ok && pf::fewrows_takes (true, true, true, false,ne )) { 365uint8_t * rec = fr_rec .as < uint8_t > ()+ j * pf::kFewRowsRecBytes ; 366 pf::fewrows_record (rec ,bl , (int )ne , (int )o0 ,st ); 367 kern::native_expert_grouped (FL , (const unsigned long long * )rec , (const int32_t * ) (rec + 8 ), (const int32_t * ) (rec + 16 ), 368 (const int32_t * ) (rec + 24 ),src_dev + o0 ,1 ,ne ,fr_xq .p ,fr_scr .p ,dm .as < float > (),st ,1 ); 369 }else { 370const size_t q = j %DQ ; 371uint16_t * dgu = q ?dqgu1 .as < uint16_t > () :dqgu0 .as < uint16_t > (); 372uint16_t * dd = q ?dqd1 .as < uint16_t > () :dqd0 .as < uint16_t > (); 373// (NVFP4: the blob's tail {s_gate, s_up, s_down, 0}: the gate / up rows and the down matrix scaled as prefill.cpp's compute lambda does) 374 kern::iq_dequant_gu_f16 ((int )p .gu ,bl ,bl + geo .up_off ,FF ,N ,dgu ,st ,geo .tail_off ? (const float * ) (bl + geo .tail_off ) :nullptr ); 375 kern::iq_dequant_f16 ((int )p .d ,bl + geo .down_off , (int64_t )N * FF ,dd ,st ,geo .tail_off ? (const float * ) (bl + geo .tail_off )+ 2 :nullptr ); 376gemm .f16 (xs .as < uint16_t > ()+ o0 * N ,dgu ,gu .as < float > ()+ o0 * FF2 ,ne ,FF2 ,N ); 377 pf::swiglu_interleaved (gu .as < float > ()+ o0 * FF2 ,hh .as < uint16_t > ()+ o0 * FF ,ne ,st ); 378gemm .f16 (hh .as < uint16_t > ()+ o0 * FF ,dd ,dm .as < float > ()+ o0 * N ,ne ,N ,FF ); 379 } 380++ j ; 381 } 382 } 383}; 384 385// --------------------------------------------------------------------------------------------------------------------------------------------- 386// GRP: the whole layer in one native_expert_grouped call (q36_engine.cu's fallback for a layer without fused kernels and without MMQ) 387struct GrpPath { 388Dev xq ,scr ,ptr ,start ,ngroups ,dst ,tok ; 389 kern::NativeExpertLayout L ; 390int64_t rows ,n ; 391int T ; 392const Shape & s ; 393const Dev & dm ; 394GrpPath (const Pair & p ,const Shape & s_ ,int T_ ,int64_t rows_ ,const Routing & r ,const std::vector < const uint8_t *>& blob ,const Dev & dm_ ) 395 :xq ((size_t )T_ * (size_t ) (s_ .N /32 )* 36 ),scr (kern::native_expert_scratch_bytes (rows_ ,s_ .FF )), 396ptr (r .order .size ()* 8 ),start ((r .order .size ()+ 1 )* 4 ),ngroups (4 ),dst ((size_t )rows_ * 4 ),tok ((size_t )rows_ * 4 ), 397rows (rows_ ),n ((int64_t )r .order .size ()),T (T_ ),s (s_ ),dm (dm_ ) { 398L = kern::native_expert_layout ((int )p .gu , (int )p .d ,s .N ,s .FF ); 399 std::vector < unsigned long long > hp ((size_t )n ); 400 std::vector < int32_t > hs ((size_t )n + 1 ),hd ((size_t )rows ); 401for (int64_t j = 0 ;j < n ;++ j ) { 402hp [(size_t )j ]= (unsigned long long ) (uintptr_t )blob [(size_t )r .order [(size_t )j ]]; 403hs [(size_t )j ]= r .off [(size_t )r .order [(size_t )j ]]; 404 } 405hs [(size_t )n ]= (int32_t )rows ; 406for (int64_t i = 0 ;i < rows ;++ i )hd [(size_t )i ]= (int32_t )i ; 407const int32_t ng = (int32_t )n ; 408ck (cudaMemcpy (ptr .p ,hp .data (),hp .size ()* 8 ,cudaMemcpyHostToDevice ),"grp ptr" ); 409ck (cudaMemcpy (start .p ,hs .data (),hs .size ()* 4 ,cudaMemcpyHostToDevice ),"grp start" ); 410ck (cudaMemcpy (ngroups .p ,& ng ,4 ,cudaMemcpyHostToDevice ),"grp n" ); 411ck (cudaMemcpy (dst .p ,hd .data (),hd .size ()* 4 ,cudaMemcpyHostToDevice ),"grp dst" ); 412ck (cudaMemcpy (tok .p ,r .src .data (),r .src .size ()* 4 ,cudaMemcpyHostToDevice ),"grp tok" ); 413 } 414void run (const float * x_dev ,cudaStream_t st ) { 415 kern::quantize_q8_1_rows (x_dev ,T ,s .N ,xq .p ,st ); 416 kern::native_expert_grouped (L ,ptr .as < unsigned long long > (),start .as < int32_t > (),ngroups .as < int32_t > (),dst .as < int32_t > (),tok .as < int32_t > (),n ,rows , 417xq .p ,scr .p ,dm .as < float > (),st ); 418 } 419}; 420 421static void set_i8_tm (int tm ) {// research: STRATA_I8_TM for the next native_expert_i8 calls (0 = unset: the call's own choice) 422#if defined(_WIN32 ) 423_putenv_s ("STRATA_I8_TM" ,tm > 0 ? std::to_string (tm ).c_str () :"" ); 424#else 425if (tm > 0 )setenv ("STRATA_I8_TM" , std::to_string (tm ).c_str (),1 );else unsetenv ("STRATA_I8_TM" ); 426#endif 427} 428 429// I8: the same layer through native_expert_i8 (our own int8 dot-product tile kernels, src/kernels/cuda/i8_expert.cuh); the same tables and activations as GRP 430struct I8Path :GrpPath { 431using GrpPath ::GrpPath ; 432void run_i8 (const float * x_dev ,cudaStream_t st ) { 433 kern::native_expert_i8_quantize (x_dev ,T ,s .N ,xq .p ,st ); 434 kern::native_expert_i8 (L ,ptr .as < unsigned long long > (),start .as < int32_t > (),ngroups .as < int32_t > (),dst .as < int32_t > (),tok .as < int32_t > (),n ,rows ,xq .p ,scr .p , 435dm .as < float > (),st ); 436// what the call really asked its launches for (the tile code, the dynamic shared memory passed to each launch, each launch's status), once per distinct request 437const auto la = kern::native_expert_i8_last_launch (); 438static std::vector < std::array < long long ,7 >> seen ; 439const std::array < long long ,7 > key = {(long long )L .gu_type , (long long )L .d_type , (long long )T , (long long )la .tile , (long long )la .gu_bytes , (long long )la .down_bytes , 440 (long long )la .gu_err * 1000 + la .down_err }; 441if (std::find (seen .begin (),seen .end (),key )== seen .end ()) { 442seen .push_back (key ); 443 std::printf ("I8-LAUNCH gu_type=%d d_type=%d tokens=%d tile=%d gu_dyn_smem_bytes=%zu down_dyn_smem_bytes=%zu gu_launch=%s down_launch=%s\n" , (int )L .gu_type , (int )L .d_type , 444 (int )T ,la .tile ,la .gu_bytes ,la .down_bytes ,la .gu_err == 0 ?"accepted" :"ERROR" ,la .down_err == 0 ?"accepted" :"ERROR" ); 445 std::fflush (stdout ); 446 } 447 } 448}; 449 450// --------------------------------------------------------------------------------------------------------------------------------------------- 451// FUSED: moe_fused_iq.hpp's native entry points (the compiled geometry's copy), or the Qwen3.6 copy's. 452struct FusedFlash { 453using Batch = fused::Batch ; 454using Geom = fused::NativeGeom ; 455static constexpr int kMaxB = fused::kMaxBatch ; 456static bool supported (int g ,int d ) {return fused::native_supported (g ,d ); } 457static void quant (const float * x ,int64_t rows ,int64_t cols ,void * xa ,void * st ) { fused::quantize_act_native (x ,rows ,cols ,xa ,st ); } 458static void experts (const Batch & b ,const Geom & g ,int ne ,int64_t n ,const void * scr ,const void * xa ,const int32_t * src ,void * ha ,float * dm ,void * st ) { 459 fused::experts_native (b ,g ,ne ,n ,scr ,xa ,src ,ha ,dm ,st ); 460 } 461}; 462#if !defined(FB_HIP ) 463namespace fq= strata::prefill::fused_q36; 464struct FusedQ36 { 465using Batch = fq::Batch ; 466using Geom = fq::NativeGeom ; 467static constexpr int kMaxB = fq::kQ36MaxBatch ; 468static bool supported (int g ,int d ) {return fq::native_supported_ext (g ,d ); } 469static void quant (const float * x ,int64_t rows ,int64_t cols ,void * xa ,void * st ) { fq::quantize_act_native (x ,rows ,cols ,xa ,st ); } 470static void experts (const Batch & b ,const Geom & g ,int ne ,int64_t n ,const void * scr ,const void * xa ,const int32_t * src ,void * ha ,float * dm ,void * st ) { 471 fq::experts_native_ext (b ,g ,ne ,n ,scr ,xa ,src ,ha ,dm ,st ); 472 } 473}; 474#endif 475 476struct FusedBase { 477virtual ~FusedBase ()= default ; 478virtual void run (const float * x_dev ,cudaStream_t st )= 0 ; 479virtual const Dev & slot ()const = 0 ; 480}; 481template < class F > 482struct FusedPath :FusedBase { 483Dev xa ,ha ,scratch ,slot_ ,src_ ,ids ; 484typename F ::Geom ng ; 485const Shape & s ; 486const std::vector < const uint8_t *>& blob ; 487const Dev & dm ; 488int T ; 489int64_t rows ; 490FusedPath (const Pair & p ,const Geo & geo ,const Shape & s_ ,int T_ ,int64_t rows_ ,const std::vector < int32_t >& ids_h , 491const std::vector < const uint8_t *>& blob_ ,const Dev & dm_ ) 492 :xa (fused::act_bytes (T_ ,s_ .N )),ha (fused::act_bytes (rows_ ,s_ .FF )),scratch (fused::group_bytes (rows_ ,s_ .E )),slot_ ((size_t )rows_ * 4 ), 493src_ ((size_t )rows_ * 4 ),ids ((size_t )rows_ * 4 ),s (s_ ),blob (blob_ ),dm (dm_ ),T (T_ ),rows (rows_ ) { 494ng = {}; 495ng .gu_type = (int )p .gu ;ng .d_type = (int )p .d ;ng .gu_row = geo .gu_row ;ng .d_row = geo .d_row ;ng .up_off = geo .up_off ;ng .down_off = geo .down_off ; 496ck (cudaMemcpy (ids .p ,ids_h .data (),ids_h .size ()* 4 ,cudaMemcpyHostToDevice ),"ids" ); 497 } 498void run (const float * x_dev ,cudaStream_t st )override { 499F ::quant (x_dev ,T ,s .N ,xa .p ,st ); 500 fused::group (ids .as < int32_t > (),rows ,s .K ,s .E ,scratch .p ,slot_ .as < int32_t > (),src_ .as < int32_t > (),st ); 501for (int e0 = 0 ;e0 < s .E ;e0 += F ::kMaxB ) { 502typename F ::Batch bt ; 503bt .e0 = e0 ; 504bt .e1 = std::min (s .E ,e0 + F ::kMaxB ); 505for (int e = bt .e0 ;e < bt .e1 ;++ e )bt .blob [e - bt .e0 ]= blob [(size_t )e ]; 506F ::experts (bt ,ng ,s .E ,rows ,scratch .p ,xa .p ,src_ .as < int32_t > (),ha .p ,dm .as < float > (),st ); 507 } 508 } 509const Dev & slot ()const override {return slot_ ; } 510}; 511 512// --------------------------------------------------------------------------------------------------------------------------------------------- 513struct Err { 514double rms = -1 ,worst = -1 ;// RMS error / RMS of the reference; the worst row's max |error| / its max |ref| (-1: not measured) 515}; 516Err compare (const std::vector < float >& a ,const std::vector < float >& ref ,size_t pairs ,int N ) { 517double e2 = 0 ,r2 = 0 ; 518Err out ; 519out .worst = 0 ; 520for (size_t i = 0 ;i < pairs ;++ i ) { 521double me = 0 ,mr = 0 ; 522for (int o = 0 ;o < N ;++ o ) { 523const double ya = a [i * (size_t )N + (size_t )o ],yb = ref [i * (size_t )N + (size_t )o ]; 524const double d = std::isfinite (ya ) ?ya - yb :1e30 ; 525e2 += d * d ; 526r2 += yb * yb ; 527me = std::max (me , std::fabs (d )); 528mr = std::max (mr , std::fabs (yb )); 529 } 530out .worst = std::max (out .worst ,mr > 0 ?me /mr : (me > 0 ?1e30 :0.0 )); 531 } 532out .rms = r2 > 0 ? std::sqrt (e2 /r2 ) :0 ; 533return out ; 534} 535 536struct Out {// one path's output, read back: per pair order 537uint64_t hash = 0 ; 538int64_t nonfinite_rows = 0 ; 539 std::vector < float > sample ;// the sampled pairs' rows 540}; 541// reads the [rows][N] FP32 outputs in chunks (host RAM stays small): a hash per row, folded in pair order; the sampled pairs' rows kept 542Out read_back (const Dev & dm ,int64_t rows ,int N ,const std::vector < int32_t >& row_of_pair ,const std::vector < size_t >& pick ) { 543Out o ; 544o .sample .assign (pick .size ()* (size_t )N ,0.0f ); 545 std::vector < uint64_t > rh ((size_t )rows ); 546 std::vector < int32_t > want ((size_t )rows ,-1 );// row -> sample index 547for (size_t j = 0 ;j < pick .size ();++ j )want [(size_t )row_of_pair [pick [j ]]]= (int32_t )j ; 548const int64_t chunk = std::max < int64_t > (1 , (64ll <<20 ) / ((int64_t )N * 4 )); 549 std::vector < float > buf ((size_t )chunk * (size_t )N ); 550for (int64_t r0 = 0 ;r0 < rows ;r0 += chunk ) { 551const int64_t n = std::min (chunk ,rows - r0 ); 552ck (cudaMemcpy (buf .data (),dm .as < uint8_t > ()+ (size_t )r0 * (size_t )N * 4 , (size_t )n * (size_t )N * 4 ,cudaMemcpyDeviceToHost ),"download" ); 553for (int64_t i = 0 ;i < n ;++ i ) { 554const uint32_t * u = (const uint32_t * ) (buf .data ()+ (size_t )i * (size_t )N ); 555uint64_t h = 1469598103934665603ull ; 556bool bad = false; 557for (int c = 0 ;c < N ;++ c ) { 558h = (h ^u [c ])* 1099511628211ull ; 559bad |= !std::isfinite (buf [(size_t )i * (size_t )N + (size_t )c ]); 560 } 561rh [(size_t ) (r0 + i )]= h ; 562o .nonfinite_rows += bad ; 563if (const int32_t j = want [(size_t ) (r0 + i )];j >=0 ) 564 std::memcpy (o .sample .data ()+ (size_t )j * (size_t )N ,buf .data ()+ (size_t )i * (size_t )N , (size_t )N * 4 ); 565 } 566 } 567uint64_t hsh = 1469598103934665603ull ; 568for (size_t i = 0 ;i < row_of_pair .size ();++ i )hsh = (hsh ^rh [(size_t )row_of_pair [i ]])* 1099511628211ull ; 569o .hash = hsh ; 570return o ; 571} 572 573float median (std::vector < float > v ) { 574 std::sort (v .begin (),v .end ()); 575return v [v .size () /2 ]; 576} 577 578struct PathRow { 579const char * name ; 580 std::function < void ()> run ; 581 std::function < std::vector < int32_t > ()> rows_of_pair ;// pair -> output row of this path 582 std::vector < float > t ; 583Out out ; 584Err err ; 585float first_ms = 0 ; 586}; 587 588struct Opts { 589Shape shape {2560 ,640 ,512 ,10 ,"flash" }; 590 std::vector < int > tokens = {2048 ,4096 ,8192 ,20000 }; 591 std::vector < std::string > only ; 592 std::vector < int > i8_tms ;// --i8-tm=2,3,4: one extra I8 column per tile-row count (STRATA_I8_TM set around each run) 593bool dense = false,tokens_set = false,all = false,list = false,grouped = false,i8 = false,no_grp = false,no_mmq = false,no_fused = false,no_fp16 = false,no_ref = false,quick = false; 594int repeats = 7 ,sample = 96 ,experts = 0 ; 595float warm_ms = 1000.0f ; 596double skew = 0 ; 597unsigned seed = 1360 ; 598 std::string dense_type = "Q8_0" ; 599// --real=DIR --real-pack=native_experts.txt --real-gguf=SHARD.gguf [--real-layers=0,1,...]: real rows (the engine's STRATA_DUMP_MOE_INPUT=DIR/moe STRATA_DUMP_MOE_LAYER=all files DIR/moe.L<l>: 600// a layer's MoE input and routing) through that layer's real experts (read from the GGUF at the offsets of the pack's native_experts.txt), one cell per layer, the pair taken from the pack's types 601 std::string real_dir ,real_pack ,real_gguf ; 602 std::vector < int > real_layers ; 603}; 604 605// one real layer: the engine's own MoE input rows of the first chunk, its routing, and the layer's expert blobs (gate | up | down per expert, the engine's blob layout) 606struct RealLayer { 607int layer = 0 ,T = 0 ; 608 std::vector < float > x ; 609 std::vector < int32_t > ids ; 610 std::vector < std::vector < uint8_t >> blob ;// per expert 611}; 612 613void defenv (const char * name ,const char * val ) { 614if (std::getenv (name )!= nullptr )return ; 615#ifdef _WIN32 616_putenv_s (name ,val ); 617#else 618setenv (name ,val ,0 ); 619#endif 620} 621 622std::string arg_after (const char * a ,const char * key ) { 623const size_t n = std::strlen (key ); 624return std::strncmp (a ,key ,n )== 0 ? std::string (a + n ) : std::string (); 625} 626std::string nospace (const char * s ) { 627 std::string r ; 628for (;* s ;++ s )if (* s != ' ' )r += (char ) std::tolower ((unsigned char )* s );// (case and spaces ignored) 629return r ; 630} 631std::vector < int > parse_ints (const std::string & s ) { 632 std::vector < int > v ; 633for (const char * c = s .c_str ();* c ;) { 634v .push_back (std::atoi (c )); 635while (* c && * c != ',' )++ c ; 636if (* c == ',' )++ c ; 637 } 638return v ; 639} 640 641const std::vector < Pair >& all_pairs () { 642static const std::vector < Pair > pairs = { 643// the IQ2_XS pack's layers (34 of 48 IQ2_S / Q2_0, 11 IQ2_XXS / Q2_0), the IQ3_S pack's most common (IQ3_S / IQ4_NL), IQ3_XXS's: the default set 644 {GGML_TYPE_IQ2_S ,GGML_TYPE_Q2_0 ,"IQ2_S / Q2_0" }, {GGML_TYPE_IQ2_XXS ,GGML_TYPE_Q2_0 ,"IQ2_XXS / Q2_0" }, 645 {GGML_TYPE_IQ3_S ,GGML_TYPE_IQ4_NL ,"IQ3_S / IQ4_NL" }, {GGML_TYPE_IQ3_XXS ,GGML_TYPE_IQ4_NL ,"IQ3_XXS / IQ4_NL" }, 646 {GGML_TYPE_IQ2_XS ,GGML_TYPE_IQ4_NL ,"IQ2_XS / IQ4_NL" }, {GGML_TYPE_IQ4_XS ,GGML_TYPE_Q2_0 ,"IQ4_XS / Q2_0" }, 647 {GGML_TYPE_IQ2_S ,GGML_TYPE_IQ4_NL ,"IQ2_S / IQ4_NL" }, {GGML_TYPE_IQ3_XXS ,GGML_TYPE_Q2_0 ,"IQ3_XXS / Q2_0" }, 648 {GGML_TYPE_IQ3_S ,GGML_TYPE_Q2_0 ,"IQ3_S / Q2_0" }, {GGML_TYPE_IQ4_XS ,GGML_TYPE_IQ4_NL ,"IQ4_XS / IQ4_NL" }, 649 {GGML_TYPE_IQ2_XXS ,GGML_TYPE_IQ4_NL ,"IQ2_XXS / IQ4_NL" }, 650// the Coder IQ1_M pack: IQ1_M gate/up (the down pairing is not verified against a pack here) 651 {GGML_TYPE_IQ1_M ,GGML_TYPE_IQ4_NL ,"IQ1_M / IQ4_NL" }, {GGML_TYPE_IQ1_M ,GGML_TYPE_Q2_0 ,"IQ1_M / Q2_0" }, 652 {GGML_TYPE_IQ3_XXS ,GGML_TYPE_Q5_0 ,"IQ3_XXS / Q5_0" }, {GGML_TYPE_IQ4_XS ,GGML_TYPE_Q5_0 ,"IQ4_XS / Q5_0" }, 653 {GGML_TYPE_Q2_0 ,GGML_TYPE_Q2_0 ,"Q2_0 / Q2_0" }, 654// the K-quant sets: UD-Q4_K_XL (47 layers Q4_K / Q5_1, 4 Q4_K / Q8_0, one Q5_K layer), UD-IQ4_XS's Q8_0 downs, the Q8_0 set, UD-Q6_K_XL 655 {GGML_TYPE_Q4_K ,GGML_TYPE_Q5_1 ,"Q4_K / Q5_1" }, {GGML_TYPE_Q4_K ,GGML_TYPE_Q8_0 ,"Q4_K / Q8_0" }, 656 {GGML_TYPE_Q5_K ,GGML_TYPE_Q5_1 ,"Q5_K / Q5_1" }, {GGML_TYPE_Q5_K ,GGML_TYPE_Q8_0 ,"Q5_K / Q8_0" }, 657 {GGML_TYPE_IQ3_S ,GGML_TYPE_Q8_0 ,"IQ3_S / Q8_0" }, {GGML_TYPE_IQ4_XS ,GGML_TYPE_Q8_0 ,"IQ4_XS / Q8_0" }, 658 {GGML_TYPE_Q8_0 ,GGML_TYPE_Q8_0 ,"Q8_0 / Q8_0" }, {GGML_TYPE_Q6_K ,GGML_TYPE_Q8_0 ,"Q6_K + Q8_0" }, 659// Qwen3.6's K-quant downs (n_ff 512 is a whole number of 256-value blocks) 660 {GGML_TYPE_Q4_K ,GGML_TYPE_Q5_K ,"Q4_K / Q5_K" }, {GGML_TYPE_Q4_K ,GGML_TYPE_Q6_K ,"Q4_K / Q6_K" }, 661 {GGML_TYPE_Q5_K ,GGML_TYPE_Q6_K ,"Q5_K / Q6_K" }, 662// NVFP4 (ModelOpt packs: Strata's GPTQ pack, NVIDIA's): NVFP4 gate/up and down, the blob's tail = the per-expert scales 663 {GGML_TYPE_NVFP4 ,GGML_TYPE_NVFP4 ,"NVFP4 / NVFP4" }}; 664return pairs ; 665} 666constexpr int kDefaultPairs = 4 ;// pairs[0..3] 667 668// --------------------------------------------------------------------------------------------------------------------------------------------- 669struct Card { 670 std::string name ,arch ; 671int major = 0 ,minor = 0 ; 672size_t total = 0 ; 673bool hip = false; 674}; 675 676void run_cell (const Pair & p ,const Shape & s ,int T ,const Opts & o ,const Card & card , pf::Gemm & gemm ,cudaStream_t st ,bool fp16_shape_ok ,bool fewrows_dflt ,const RealLayer * real = nullptr ) { 677const Geo geo (p ,s ); 678const int N = s .N ,FF = s .FF ,FF2 = s .FF2 (),K = s .K ,E = s .E ; 679const int64_t rows = (int64_t )T * K ; 680size_t free0 = 0 ,tot = 0 ; 681cudaMemGetInfo (& free0 ,& tot ); 682 683// blobs at the engine's stride (a whole number of blocks of both formats), identical but for one quant byte of the gate matrix's first row: 684// strata::bench_blob::perturb_offset skips every byte that carries scale bits in the gate/up type's block (fixed offsets 4..19 reached block 1's 685// fp16 scale on Q2_0's 18-byte blocks and gave some experts scales of +-12,992 or NaN) 686 strata::bench_blob::BlockLayout gu_lay ; 687if (!real && !strata::bench_blob::layout_of ((int )p .gu ,gu_lay )) { 688 std::printf (" %s: no block layout for gate/up type %d in bench_blob_layout.hpp: pair skipped\n" ,p .name , (int )p .gu ); 689return ; 690 } 691// checked against the engine's own type table (strata::quant::type_info), not ggml's: a build without MMQ links no ggml for this 692const strata::quant::TypeInfo * gu_ti = real ?nullptr : strata::quant::type_info ((int )p .gu ); 693if (!real && (gu_ti == nullptr || gu_lay .bytes != (int )gu_ti -> bytes || gu_lay .values != gu_ti -> blck || strata::bench_blob::perturb_offset (gu_lay ,15 ) >=geo .gu_row )) { 694 std::fprintf (stderr ,"bench_blob_layout.hpp: type %d has %d bytes / %d values per block there, strata::quant::type_info says %zu / %d\n" , (int )p .gu , 695gu_lay .bytes ,gu_lay .values ,gu_ti ?gu_ti -> bytes : (size_t )0 ,gu_ti ?gu_ti -> blck :0 ); 696 std::exit (1 ); 697 } 698 std::mt19937 rng (o .seed + (unsigned )p .gu * 7 + (unsigned )p .d ); 699size_t unit = type_size (p .gu ); 700while (unit %type_size (p .d )!= 0 || unit %16 != 0 )unit += type_size (p .gu ); 701const size_t stride = (geo .bytes + unit - 1 ) /unit * unit ; 702Dev blobs ((size_t )E * stride + 4096 ); 703ck (cudaMemset (blobs .p ,0 ,blobs .n ),"zero" ); 704const std::vector < uint8_t > base = real ? std::vector < uint8_t > () :make_blob (p ,geo ,s ,rng ); 705auto blob_bytes = [& ](int e )-> std::vector < uint8_t > { 706if (real ) { std::vector < uint8_t > rb = real -> blob [(size_t )e ];rb .resize (geo .bytes ,0 );return rb ; }// (an expert no row routes to is not loaded: zeros) 707 std::vector < uint8_t > b = base ; 708b [strata::bench_blob::perturb_offset (gu_lay ,e )] ^= (uint8_t )e ; 709return b ; 710 }; 711for (int e = 0 ;e < E ;++ e ) { 712const std::vector < uint8_t > b = blob_bytes (e ); 713ck (cudaMemcpy (blobs .as < uint8_t > ()+ (size_t )e * stride ,b .data (),geo .bytes ,cudaMemcpyHostToDevice ),"blob" ); 714 } 715 std::vector < const uint8_t *> blob ((size_t )E ); 716for (int e = 0 ;e < E ;++ e )blob [(size_t )e ]= blobs .as < uint8_t > ()+ (size_t )e * stride ; 717 718 std::vector < float > x = real ?real -> x :make_x (T ,N ,rng ); 719const std::vector < int32_t > ids = real ?real -> ids :make_ids (T ,E ,K ,o .skew ,rng ); 720const Routing r = sort_rows (ids ,E ,K ); 721int max_rows = 0 ,few = 0 ; 722for (int e = 0 ;e < E ;++ e ) { 723max_rows = std::max < int > (max_rows ,r .cnt [(size_t )e ]); 724few += r .cnt [(size_t )e ] >=1 && r .cnt [(size_t )e ] <= pf::kFewRows ; 725 } 726 727Dev x_dev ((size_t )T * N * 4 ),x16_dev ((size_t )T * N * 2 ),src_dev ((size_t )rows * 4 ); 728 { 729ck (cudaMemcpy (x_dev .p ,x .data (),x .size ()* 4 ,cudaMemcpyHostToDevice ),"x" ); 730 std::vector < uint16_t > x16 (x .size ()); 731for (size_t i = 0 ;i < x .size ();++ i )x16 [i ]= ggml_fp32_to_fp16 (x [i ]); 732ck (cudaMemcpy (x16_dev .p ,x16 .data (),x16 .size ()* 2 ,cudaMemcpyHostToDevice ),"x16" ); 733ck (cudaMemcpy (src_dev .p ,r .src .data (),r .src .size ()* 4 ,cudaMemcpyHostToDevice ),"src" ); 734 } 735Dev gu ((size_t )rows * FF2 * 4 ),hmq ((size_t )rows * FF * 4 ),dm ((size_t )rows * N * 4 );// shared by the paths (one runs at a time) 736 737const bool mmq_ok = !o .no_mmq && mmq::built ()&& mmq::supported ((int )p .gu )&& mmq::supported ((int )p .d )&& mmq::fits ((int )p .gu ,FF2 )&& mmq::fits ((int )p .d ,N ); 738const bool fp16_ok = !o .no_fp16 && fp16_shape_ok && kern::iq_supported ((int )p .gu )&& kern::iq_supported ((int )p .d ); 739const bool fused_flash = !o .no_fused && N == (int ) fused::kMoeEmbd && FF == (int ) fused::kMoeFF && FusedFlash ::supported ((int )p .gu , (int )p .d ); 740#if !defined(FB_HIP ) 741const bool fused_q36 = !o .no_fused && !fused_flash && N == fq::kQ36Embd && FF == fq::kQ36FF && FusedQ36 ::supported ((int )p .gu , (int )p .d ); 742#else 743const bool fused_q36 = false; 744#endif 745const bool grp_ok = !o .no_grp && (o .grouped || s .name == "q36" )&& kern::native_expert_supported ((int )p .gu , (int )p .d ,N ,FF ); 746const bool fr_ok = fp16_ok && kern::native_expert_supported ((int )p .gu , (int )p .d ,N ,FF ); 747const bool i8_ok = o .i8 && kern::native_expert_supported ((int )p .gu , (int )p .d ,N ,FF )&& kern::native_expert_i8_supported (kern::native_expert_layout ((int )p .gu , (int )p .d ,N ,FF )); 748 749 std::unique_ptr < MmqPath > mp ; 750 std::unique_ptr < Fp16Path > fp ; 751 std::unique_ptr < GrpPath > gp ; 752 std::unique_ptr < I8Path > ip ; 753 std::unique_ptr < FusedBase > fu ; 754if (mmq_ok )mp = std::make_unique < MmqPath > (p ,s ,geo ,rows ,r ,blob ,gu ,hmq ,dm ); 755if (fp16_ok )fp = std::make_unique < Fp16Path > (p ,s ,geo ,gemm ,T ,rows ,r ,blob ,gu ,dm ,fr_ok ); 756if (grp_ok )gp = std::make_unique < GrpPath > (p ,s ,T ,rows ,r ,blob ,dm ); 757if (i8_ok )ip = std::make_unique < I8Path > (p ,s ,T ,rows ,r ,blob ,dm ); 758if (fused_flash )fu = std::make_unique < FusedPath < FusedFlash >> (p ,geo ,s ,T ,rows ,ids ,blob ,dm ); 759#if !defined(FB_HIP ) 760if (fused_q36 )fu = std::make_unique < FusedPath < FusedQ36 >> (p ,geo ,s ,T ,rows ,ids ,blob ,dm ); 761#endif 762ck (cudaDeviceSynchronize (),"uploads" );// (the uploads above are on the legacy stream, the work below on a non-blocking one) 763 764auto pair_rows = [& ] {return r .row_of ; }; 765 std::vector < PathRow > paths ; 766if (mp )paths .push_back ({"MMQ" , [& ] {mp -> run (x_dev .as < float > (),src_dev .as < int32_t > (),st ); },pair_rows , {}, {}, {},0 }); 767if (fp ) { 768paths .push_back ({"FP16" , [& ] {fp -> run (false,x_dev .as < float > (),x16_dev .as < uint16_t > (),src_dev .as < int32_t > (),st ); },pair_rows , {}, {}, {},0 }); 769if (fr_ok )paths .push_back ({"FP16+FR" , [& ] {fp -> run (true,x_dev .as < float > (),x16_dev .as < uint16_t > (),src_dev .as < int32_t > (),st ); },pair_rows , {}, {}, {},0 }); 770 } 771if (gp )paths .push_back ({"GRP" , [& ] {gp -> run (x_dev .as < float > (),st ); },pair_rows , {}, {}, {},0 }); 772if (ip )paths .push_back ({"I8" , [& ] {set_i8_tm (0 );ip -> run_i8 (x_dev .as < float > (),st ); },pair_rows , {}, {}, {},0 }); 773if (ip ) { 774static const char * const tm_names []= {"I8t1" ,"I8t2" ,"I8t3" ,"I8t4" ,"I8t5" ,"I8t6" ,"I8t7" ,"I8t8" }; 775for (size_t k = 0 ;k < o .i8_tms .size ()&& k < 8 ;++ k ) { 776const int tm = o .i8_tms [k ]; 777paths .push_back ({tm_names [std::min (std::max (tm ,1 ),8 )- 1 ], [& ,tm ] {set_i8_tm (tm );ip -> run_i8 (x_dev .as < float > (),st ); },pair_rows , {}, {}, {},0 }); 778 } 779 } 780if (fu )paths .push_back ({"FUSED" , [& ] {fu -> run (x_dev .as < float > (),st ); }, 781 [& ] { 782 std::vector < int32_t > slot ((size_t )rows ); 783ck (cudaMemcpy (slot .data (),fu -> slot ().p ,slot .size ()* 4 ,cudaMemcpyDeviceToHost ),"slot" ); 784return slot ; 785 }, {}, {}, {},0 }); 786 787size_t free1 = 0 ; 788cudaMemGetInfo (& free1 ,& tot ); 789const double vram_mib = (double ) (free0 - std::min (free0 ,free1 )) / (1024.0 * 1024.0 ); 790 791if (real ) std::printf ("== REAL layer %d (the engine's own rows and routing, the layer's own experts)\n" ,real -> layer ); 792 std::printf ("== %s shape %s (%dx%d, %d experts, top %d) T=%d rows %lld (per expert avg %.1f max %d; experts with <= %d rows: %d) weights %.1f MiB/expert\n" , 793p .name ,s .name .c_str (),N ,FF ,E ,K ,T , (long long )rows , (double )rows /E ,max_rows , pf::kFewRows ,few , (double )geo .bytes / (1024.0 * 1024.0 )); 794if (paths .empty ()) { 795 std::printf (" no path covers this pair here\n" ); 796return ; 797 } 798 799// the CPU FP32 reference on a sample of pairs 800 std::vector < size_t > pick ; 801 std::vector < float > ref ; 802if (!o .no_ref ) { 803for (size_t i = 0 ;pick .size ()< (size_t )o .sample && i < (size_t )o .sample * 4 ;++ i ) { 804const size_t c = (i * 2654435761u + 12345u ) % (size_t )rows ; 805if (std::find (pick .begin (),pick .end (),c )== pick .end ())pick .push_back (c ); 806 } 807ref .assign (pick .size ()* (size_t )N ,0.0f ); 808 std::vector < std::thread > th ; 809const int nth = std::max (1 , std::min (16 , (int ) std::thread::hardware_concurrency ())); 810for (int w = 0 ;w < nth ;++ w ) 811th .emplace_back ([& ,w ] { 812 std::vector < float > g ,dn ,h ((size_t )FF ); 813for (size_t j = (size_t )w ;j < pick .size ();j += (size_t )nth ) { 814const size_t i = pick [j ]; 815dequant (p ,geo ,s ,blob_bytes (ids [i ]),g ,dn ); 816const float * xr = x .data ()+ (i / (size_t )K )* (size_t )N ; 817for (int f = 0 ;f < FF ;++ f ) { 818double gt = 0 ,up = 0 ; 819const float * wg = g .data ()+ (size_t )f * N ,* wu = g .data ()+ (size_t ) (FF + f )* N ; 820for (int k = 0 ;k < N ;++ k ) {gt += (double )wg [k ]* xr [k ];up += (double )wu [k ]* xr [k ]; } 821h [(size_t )f ]= (float ) (gt / (1.0 + std::exp (- gt ))* up ); 822 } 823for (int oo = 0 ;oo < N ;++ oo ) { 824double a = 0 ; 825const float * wd = dn .data ()+ (size_t )oo * FF ; 826for (int f = 0 ;f < FF ;++ f )a += (double )wd [f ]* h [(size_t )f ]; 827ref [j * (size_t )N + (size_t )oo ]= (float )a ; 828 } 829 } 830 }); 831for (auto & t :th )t .join (); 832 } 833 834cudaEvent_t ea ,eb ; 835ck (cudaEventCreate (& ea ),"event" ); 836ck (cudaEventCreate (& eb ),"event" ); 837auto once = [& ](PathRow & pr ) { 838ck (cudaEventRecord (ea ,st ),"record" ); 839pr .run (); 840ck (cudaEventRecord (eb ,st ),"record" ); 841ck (cudaEventSynchronize (eb ),"sync" ); 842float t = 0 ; 843ck (cudaEventElapsedTime (& t ,ea ,eb ),"elapsed" ); 844return t ; 845 }; 846 847// 1. each path once: its output (hashed, a sample against the reference), first-run time (includes one-time setup: not reported) 848float slowest = 0 ; 849for (PathRow & pr :paths ) { 850ck (cudaMemset (dm .p ,0xff ,dm .n ),"sentinel" );// an unwritten row is NaN 851ck (cudaDeviceSynchronize (),"sentinel" ); 852pr .first_ms = once (pr ); 853slowest = std::max (slowest ,pr .first_ms ); 854const std::vector < int32_t > rop = pr .rows_of_pair (); 855pr .out = read_back (dm ,rows ,N ,rop ,pick ); 856if (!o .no_ref )pr .err = compare (pr .out .sample ,ref ,pick .size (),N ); 857 } 858// 2. warm-up (~warm-ms of all paths, the clocks ramp up), then alternating rounds, the first path rotating; a very slow cell keeps fewer rounds 859const bool slow = slowest > 1500.0f ; 860int repeats = slow ? std::min (o .repeats ,3 ) :o .repeats ; 861for (float spent = 0 ;spent < (slow ?0.0f :o .warm_ms );) { 862float round = 0 ; 863for (PathRow & pr :paths )round += once (pr ); 864spent += round ; 865if (round <=0 )break ; 866 } 867for (int rep = 0 ;rep < repeats ;++ rep ) 868for (size_t i = 0 ;i < paths .size ();++ i ) { 869PathRow & pr = paths [(i + (size_t )rep ) %paths .size ()]; 870pr .t .push_back (once (pr )); 871 } 872cudaEventDestroy (ea ); 873cudaEventDestroy (eb ); 874ck (cudaGetLastError (),"after timing" ); 875 876const auto find = [& ](const char * n )-> PathRow * {for (PathRow & pr :paths )if (std::strcmp (pr .name ,n )== 0 )return & pr ;return nullptr ; }; 877PathRow * pm = find ("MMQ" ); 878// the sampled pairs of every path against MMQ's (not against the FP32 reference): two paths with the same int8 activations and exact integer sums differ by float rounding only 879if (pm != nullptr && !pm -> out .sample .empty ()) { 880 std::printf (" rms difference to MMQ's output on the sampled pairs (relative to MMQ's own RMS; worst row max|diff| / max|MMQ|):" ); 881for (PathRow & pr :paths ) { 882if (& pr == pm || pr .out .sample .size ()!= pm -> out .sample .size ())continue ; 883const Err d = compare (pr .out .sample ,pm -> out .sample ,pick .size (),N ); 884 std::printf (" %s %.2e / %.2e" ,pr .name ,d .rms ,d .worst ); 885 } 886 std::printf ("\n" ); 887// how the difference spreads over the sampled pairs: a few pairs far above the float-rounding level (one int8 code of an activation or of H landing on the other side of a 888// rounding boundary) against every pair slightly different 889for (PathRow & pr :paths ) { 890if (& pr == pm || pr .out .sample .size ()!= pm -> out .sample .size ())continue ; 891 std::vector < double > rel ; 892for (size_t i = 0 ;i < pick .size ();++ i ) { 893double me = 0 ,mr = 0 ; 894for (int o = 0 ;o < N ;++ o ) { 895const double ya = pr .out .sample [i * (size_t )N + (size_t )o ],yb = pm -> out .sample [i * (size_t )N + (size_t )o ]; 896me = std::max (me , std::isfinite (ya ) ? std::fabs (ya - yb ) :1e30 ); 897mr = std::max (mr , std::fabs (yb )); 898 } 899rel .push_back (mr > 0 ?me /mr : (me > 0 ?1e30 :0.0 )); 900 } 901 std::sort (rel .begin (),rel .end ()); 902size_t over = 0 ; 903for (double r :rel )over += r > 1e-5 ; 904const size_t n = rel .size (); 905 std::printf (" %s per sampled pair, max|diff| / max|MMQ|: %zu of %zu pairs above 1e-5; largest %.2e, second %.2e, median %.2e\n" ,pr .name ,over ,n , 906n ?rel [n - 1 ] :0.0 ,n > 1 ?rel [n - 2 ] :0.0 ,n ?rel [n /2 ] :0.0 ); 907 } 908 } 909 std::printf (" %-8s %10s %10s %10s %9s %9s %9s %-16s %s\n" ,"path" ,"ms median" ,"min" ,"max" ,pm ?"x MMQ" :"" ,"err rms" ,"worst row" ,"output hash" ,"non-finite rows" ); 910for (PathRow & pr :paths ) { 911const float md = median (pr .t ),mn = * std::min_element (pr .t .begin (),pr .t .end ()),mx = * std::max_element (pr .t .begin (),pr .t .end ()); 912char rel [32 ]= "" ; 913if (pm ) std::snprintf (rel ,sizeof rel ,"%.3f" ,median (pm -> t ) /md ); 914 std::printf (" %-8s %10.3f %10.3f %10.3f %9s " ,pr .name ,md ,mn ,mx ,rel ); 915if (pr .err .rms >=0 ) std::printf ("%9.2e %9.2e " ,pr .err .rms ,pr .err .worst );else std::printf ("%9s %9s " ,"-" ,"-" ); 916 std::printf ("%016llx %lld\n" , (unsigned long long )pr .out .hash , (long long )pr .out .nonfinite_rows ); 917 } 918if (real ) {// REALROW: one line per layer for the tables (error against FP32 of MMQ / I8 / FP16, and the sampled I8-to-MMQ difference) 919PathRow * rm = find ("MMQ" ),* ri = find ("I8" ),* rf = find ("FP16" ); 920double dif = -1 ,dwr = -1 ; 921if (rm && ri && !rm -> out .sample .empty ()&& ri -> out .sample .size ()== rm -> out .sample .size ()) {const Err d = compare (ri -> out .sample ,rm -> out .sample ,pick .size (),N );dif = d .rms ;dwr = d .worst ; } 922 std::printf ("REALROW layer=%d pair=\"%s\" T=%d mmq_err=%.3e mmq_worst=%.3e i8_err=%.3e i8_worst=%.3e fp16_err=%.3e i8_vs_mmq=%.3e i8_vs_mmq_worst=%.3e\n" ,real -> layer ,p .name ,T , 923rm ?rm -> err .rms :-1.0 ,rm ?rm -> err .worst :-1.0 ,ri ?ri -> err .rms :-1.0 ,ri ?ri -> err .worst :-1.0 ,rf ?rf -> err .rms :-1.0 ,dif ,dwr ); 924 } 925// the machine-readable line: key=value, n/a where a path is absent; ratios are speed ratios (the first path's ms over this path's ms, > 1: faster) 926auto ms = [& ](const char * n ,char * buf ,size_t cap ) {PathRow * q = find (n );if (q ) std::snprintf (buf ,cap ,"%.3f" ,median (q -> t ));else std::snprintf (buf ,cap ,"n/a" ); }; 927auto ratio = [& ](const char * a ,const char * b ,char * buf ,size_t cap ) { 928PathRow * x1 = find (a ),* x2 = find (b ); 929if (x1 && x2 ) std::snprintf (buf ,cap ,"%.3f" ,median (x1 -> t ) /median (x2 -> t ));else std::snprintf (buf ,cap ,"n/a" ); 930 }; 931auto errs = [& ](const char * n ,char * buf ,size_t cap ) {PathRow * q = find (n );if (q && q -> err .rms >=0 ) std::snprintf (buf ,cap ,"%.3e/%.3e" ,q -> err .rms ,q -> err .worst );else std::snprintf (buf ,cap ,"n/a" ); }; 932auto hs = [& ](const char * n ,char * buf ,size_t cap ) {PathRow * q = find (n );if (q ) std::snprintf (buf ,cap ,"%016llx" , (unsigned long long )q -> out .hash );else std::snprintf (buf ,cap ,"n/a" ); }; 933auto spread = [& ](const char * n ,char * buf ,size_t cap ) { 934PathRow * q = find (n ); 935if (q ) std::snprintf (buf ,cap ,"%.3f" , (* std::max_element (q -> t .begin (),q -> t .end ())- * std::min_element (q -> t .begin (),q -> t .end ())) /median (q -> t )); 936else std::snprintf (buf ,cap ,"n/a" ); 937 }; 938char m_mmq [24 ],m_fp [24 ],m_fr [24 ],m_grp [24 ],m_fu [24 ],r_fp [24 ],r_fr [24 ],r_grp [24 ],r_fu [24 ],r_fu_fp [24 ],e_mmq [40 ],e_fp [40 ],e_fr [40 ],e_grp [40 ],e_fu [40 ]; 939char m_i8 [24 ],r_i8 [24 ],e_i8 [40 ],h_i8 [24 ],sp_i8 [24 ]; 940char h_mmq [24 ],h_fp [24 ],h_fr [24 ],h_grp [24 ],h_fu [24 ],sp_mmq [24 ],sp_fp [24 ],sp_fu [24 ]; 941ms ("MMQ" ,m_mmq ,sizeof m_mmq );ms ("FP16" ,m_fp ,sizeof m_fp );ms ("FP16+FR" ,m_fr ,sizeof m_fr );ms ("GRP" ,m_grp ,sizeof m_grp );ms ("FUSED" ,m_fu ,sizeof m_fu );ms ("I8" ,m_i8 ,sizeof m_i8 );ratio ("MMQ" ,"I8" ,r_i8 ,sizeof r_i8 );errs ("I8" ,e_i8 ,sizeof e_i8 );hs ("I8" ,h_i8 ,sizeof h_i8 );spread ("I8" ,sp_i8 ,sizeof sp_i8 ); 942ratio ("MMQ" ,"FP16" ,r_fp ,sizeof r_fp );ratio ("MMQ" ,"FP16+FR" ,r_fr ,sizeof r_fr );ratio ("MMQ" ,"GRP" ,r_grp ,sizeof r_grp );ratio ("MMQ" ,"FUSED" ,r_fu ,sizeof r_fu ); 943ratio ("FP16" ,"FUSED" ,r_fu_fp ,sizeof r_fu_fp ); 944errs ("MMQ" ,e_mmq ,sizeof e_mmq );errs ("FP16" ,e_fp ,sizeof e_fp );errs ("FP16+FR" ,e_fr ,sizeof e_fr );errs ("GRP" ,e_grp ,sizeof e_grp );errs ("FUSED" ,e_fu ,sizeof e_fu ); 945hs ("MMQ" ,h_mmq ,sizeof h_mmq );hs ("FP16" ,h_fp ,sizeof h_fp );hs ("FP16+FR" ,h_fr ,sizeof h_fr );hs ("GRP" ,h_grp ,sizeof h_grp );hs ("FUSED" ,h_fu ,sizeof h_fu ); 946spread ("MMQ" ,sp_mmq ,sizeof sp_mmq );spread ("FP16" ,sp_fp ,sizeof sp_fp );spread ("FUSED" ,sp_fu ,sizeof sp_fu ); 947long long bad = 0 ; 948for (const PathRow & pr :paths )bad += pr .out .nonfinite_rows ; 949 std::string pn = p .name ; 950for (char & c :pn )if (c == ' ' )c = '_' ; 951 std::printf ("RESULT shape=%s pair=%s tokens=%d experts=%d top=%d few_row_experts=%d fewrows_default_here=%d mmq_ms=%s fp16_ms=%s fp16fr_ms=%s grp_ms=%s fused_ms=%s " 952"mmq_over_fp16=%s mmq_over_fp16fr=%s mmq_over_grp=%s mmq_over_fused=%s fp16_over_fused=%s spread_mmq=%s spread_fp16=%s spread_fused=%s repeats=%d " 953"err_mmq=%s err_fp16=%s err_fp16fr=%s err_grp=%s err_fused=%s hash_mmq=%s hash_fp16=%s hash_fp16fr=%s hash_grp=%s hash_fused=%s nonfinite_rows=%lld " 954"i8_ms=%s mmq_over_i8=%s err_i8=%s hash_i8=%s spread_i8=%s vram_mib=%.0f card=%s arch=%s skew=%.2f\n" , 955s .name .c_str (),pn .c_str (),T ,E ,K ,few ,fewrows_dflt ?1 :0 ,m_mmq ,m_fp ,m_fr ,m_grp ,m_fu ,r_fp ,r_fr ,r_grp ,r_fu ,r_fu_fp ,sp_mmq ,sp_fp ,sp_fu , 956repeats ,e_mmq ,e_fp ,e_fr ,e_grp ,e_fu ,h_mmq ,h_fp ,h_fr ,h_grp ,h_fu ,bad ,m_i8 ,r_i8 ,e_i8 ,h_i8 ,sp_i8 ,vram_mib , [& ] { 957static std::string cn ;cn = card .name ;for (char & c :cn )if (c == ' ' )c = '_' ;return cn .c_str (); }(),card .arch .c_str (),o .skew ); 958 std::fflush (stdout ); 959} 960#if defined(FB_HIP ) 961constexpr bool FB_HIP_ON = true; 962#else 963constexpr bool FB_HIP_ON = false; 964#endif 965// --------------------------------------------------------------------------------------------------------------------------------------------- 966// --dense: the engine's dense prompt GEMMs (projections) through strata::prefill::Gemm with FP16 io off and on. "On" is Gemm::set_f16_io(true), what 967// STRATA_HIP_PROMPT_F16=1 (prompt_f16(), src/prefill/gemm.cu) sets on a HIP card: bf16() then takes the FP16 image of the activations and native() / bf16() 968// run the GEMM with FP16 out (widened in place). On CUDA set_f16_io has no effect (the engine never turns it on there): both columns are the same code, which 969// makes the ratio the run-to-run noise floor. The shapes are Flash-Next's (the compiled geometry's), (T, N, K) as the engine's call sites pass them: 970// prefill.cpp (a269d4c82) gdn_qkv native :4393 gdn_gate native :4401 gdn_out native :4424 alpha/beta bf16 :4402-4403 qsa_k/v native :4445-4446 971// qsa_q native :4448 indexer k/q bf16 :4450-4451 qsa_out native :4785 router bf16 :4797 shared expert native :4861-4864 972// hyper-connection down bf16 :4336, up :4345/4366, inj :4368 (bf16_proj / native_proj at :3219-3251) 973// `uses` is how often a prompt chunk runs the shape (per layer kind); the totals line weights by it. 974struct DenseShape { 975const char * name ; 976bool bf16 ;// the weights are BF16 tensors (bf16_proj); else GGUF blocks (native_proj) 977int64_t N ,K ; 978int uses ; 979const char * site ; 980}; 981std::vector < DenseShape > dense_shapes () { 982const auto & g = strata::core::kCompiledGeometry ; 983const int64_t Nn = g .n_embd ,D = g .hc * g .n_embd ,LR = g .hc_lr ,C = g .ssm_conv_channels ,ZV = g .ssm_value_dim ,QW = g .n_head * g .head_dim , 984KV = g .n_head_kv * g .head_dim ,IQW = g .idx_q_heads * g .idx_key_dim ; 985const int nl = (int )g .n_layers ,nq = (int )g .n_qsa_layers (),ng = (int )g .n_gdn_layers (); 986return {{"gdn_qkv" , false,C ,Nn ,ng ,"4393" }, {"gdn_gate" , false,ZV ,Nn ,ng ,"4401" }, {"gdn_out" , false,Nn ,ZV ,ng ,"4424" }, 987 {"ssm_alpha_beta" , true,g .ssm_v_heads ,Nn ,2 * ng ,"4402-4403" }, 988 {"qsa_q" , false,2 * QW ,Nn ,nq ,"4448" }, {"qsa_k_v" , false,KV ,Nn ,2 * nq ,"4445-4446" }, {"qsa_out" , false,Nn ,QW ,nq ,"4785" }, 989 {"idx_k" , true,g .idx_key_dim ,Nn ,nq ,"4450" }, {"idx_q" , true,IQW ,Nn ,nq ,"4451" }, 990 {"hc_down" , true,LR ,D ,2 * nl ,"4336" }, {"hc_up" , true,D ,LR ,2 * nl ,"4345/4366" }, {"hc_inj" , true,g .hc ,D ,2 * nl ,"4368" }, 991 {"router" , true,g .n_expert ,Nn ,nl ,"4797" }, 992 {"shexp_gate_up" , false,g .n_ff_shexp ,Nn ,2 * nl ,"4861-4862" }, {"shexp_down" , false,Nn ,g .n_ff_shexp ,nl ,"4864" }}; 993} 994uint16_t f2bf (float f ) { 995uint32_t b ; 996 std::memcpy (& b ,& f ,4 ); 997b += 0x7fffu + ((b >>16 )& 1u ); 998return (uint16_t ) (b >>16 ); 999} 1000float bf2f (uint16_t h ) { 1001const uint32_t b = (uint32_t )h <<16 ; 1002float f ; 1003 std::memcpy (& f ,& b ,4 ); 1004return f ; 1005} 1006 1007void run_dense_cell (const DenseShape & d ,int T ,ggml_type ntype ,const Opts & o ,const Card & card , pf::Gemm & gemm ,cudaStream_t st ,bool dflt_on , 1008double * sum_off ,double * sum_on ) { 1009const int64_t N = d .N ,K = d .K ; 1010if (!d .bf16 && !fits_blocks (ntype ,K )) { std::printf (" %-15s skipped: K=%lld is not a whole number of %s blocks\n" ,d .name , (long long )K ,ggml_type_name (ntype ));return ; } 1011 std::mt19937 rng (o .seed + (unsigned ) (N * 31 + K )); 1012// weights (BF16 tensor or GGUF blocks), kept on the host as FP32 for the reference 1013 std::vector < float > wf ((size_t ) (N * K )); 1014Dev w ; 1015if (d .bf16 ) { 1016 std::vector < uint16_t > wb ((size_t ) (N * K )); 1017 std::uniform_real_distribution < float > u (-0.05f ,0.05f ); 1018for (size_t i = 0 ;i < wb .size ();++ i ) {wb [i ]= f2bf (u (rng ));wf [i ]= bf2f (wb [i ]); } 1019w = Dev (wb .size ()* 2 ); 1020ck (cudaMemcpy (w .p ,wb .data (),wb .size ()* 2 ,cudaMemcpyHostToDevice ),"w" ); 1021 }else { 1022const size_t rb = row_size (ntype ,K ); 1023 std::vector < uint8_t > blk ((size_t )N * rb ); 1024fill_matrix (blk .data (),ntype ,N ,K ,rng ); 1025const auto * tr = ggml_get_type_traits (ntype ); 1026for (int64_t r = 0 ;r < N ;++ r )tr -> to_float (blk .data ()+ (size_t )r * rb ,wf .data ()+ (size_t ) (r * K ),K ); 1027w = Dev (blk .size ()); 1028ck (cudaMemcpy (w .p ,blk .data (),blk .size (),cudaMemcpyHostToDevice ),"w" ); 1029 } 1030// activations: N(0,1)-like values with a few large ones, written as BF16 and FP16 images in chunks (no T x K host array); the sample rows are kept in FP32 1031Dev xbf ((size_t )T * K * 2 ),xh ((size_t )T * K * 2 ); 1032const int nsamp = std::min (8 ,T ); 1033 std::vector < int > srow ; 1034for (int i = 0 ;i < nsamp ;++ i )srow .push_back ((int ) ((int64_t )i * (T - 1 ) / std::max (1 ,nsamp - 1 ))); 1035 std::vector < float > xs ((size_t )nsamp * (size_t )K ); 1036 { 1037const int64_t chunk = 256 ; 1038 std::vector < uint16_t > cb ((size_t ) (chunk * K )),ch ((size_t ) (chunk * K )); 1039 std::uniform_real_distribution < float > u (-1.7320508f ,1.7320508f ); 1040 std::uniform_int_distribution < int > pick (0 ,199 ); 1041for (int64_t r0 = 0 ;r0 < T ;r0 += chunk ) { 1042const int64_t n = std::min < int64_t > (chunk ,T - r0 ); 1043for (int64_t i = 0 ;i < n ;++ i ) 1044for (int64_t k = 0 ;k < K ;++ k ) { 1045float v = u (rng )* (pick (rng )== 0 ?12.0f :1.0f ); 1046cb [(size_t ) (i * K + k )]= f2bf (v ); 1047ch [(size_t ) (i * K + k )]= ggml_fp32_to_fp16 (v ); 1048for (int s = 0 ;s < nsamp ;++ s )if (srow [(size_t )s ]== r0 + i )xs [(size_t )s * (size_t )K + (size_t )k ]= v ; 1049 } 1050ck (cudaMemcpy (xbf .as < uint8_t > ()+ (size_t )r0 * K * 2 ,cb .data (), (size_t ) (n * K )* 2 ,cudaMemcpyHostToDevice ),"x" ); 1051ck (cudaMemcpy (xh .as < uint8_t > ()+ (size_t )r0 * K * 2 ,ch .data (), (size_t ) (n * K )* 2 ,cudaMemcpyHostToDevice ),"x" ); 1052 } 1053 } 1054Dev y ((size_t )T * N * 4 ); 1055ck (cudaDeviceSynchronize (),"uploads" ); 1056 1057// the CPU FP32 reference on the sample rows 1058 std::vector < float > ref ((size_t )nsamp * (size_t )N ); 1059 { 1060 std::vector < std::thread > th ; 1061const int nth = std::max (1 , std::min (16 , (int ) std::thread::hardware_concurrency ())); 1062for (int t = 0 ;t < nth ;++ t ) 1063th .emplace_back ([& ,t ] { 1064for (int64_t n = t ;n < N ;n += nth ) 1065for (int s = 0 ;s < nsamp ;++ s ) { 1066double a = 0 ; 1067const float * wr = wf .data ()+ (size_t ) (n * K ); 1068const float * xr = xs .data ()+ (size_t )s * (size_t )K ; 1069for (int64_t k = 0 ;k < K ;++ k )a += (double )wr [k ]* xr [k ]; 1070ref [(size_t )s * (size_t )N + (size_t )n ]= (float )a ; 1071 } 1072 }); 1073for (auto & t :th )t .join (); 1074 } 1075auto run = [& ](bool on ) { 1076gemm .set_f16_io (on ); 1077if (d .bf16 )gemm .bf16 ((on && FB_HIP_ON ) ?xh .as < uint16_t > () :xbf .as < uint16_t > (),w .as < uint16_t > (),y .as < float > (),T ,N ,K ); 1078else gemm .native (xh .as < uint16_t > (), (int )ntype ,w .p ,y .as < float > (),T ,N ,K ); 1079 }; 1080cudaEvent_t ea ,eb ; 1081ck (cudaEventCreate (& ea ),"event" ); 1082ck (cudaEventCreate (& eb ),"event" ); 1083auto once = [& ](bool on ) { 1084ck (cudaEventRecord (ea ,st ),"record" ); 1085run (on ); 1086ck (cudaEventRecord (eb ,st ),"record" ); 1087ck (cudaEventSynchronize (eb ),"sync" ); 1088float t = 0 ; 1089ck (cudaEventElapsedTime (& t ,ea ,eb ),"elapsed" ); 1090return t ; 1091 }; 1092Err err [2 ]; 1093uint64_t hsh [2 ]= {0 ,0 }; 1094long long nonfin [2 ]= {0 ,0 }; 1095for (int on = 0 ;on < 2 ;++ on ) { 1096ck (cudaMemset (y .p ,0xff ,y .n ),"sentinel" ); 1097ck (cudaDeviceSynchronize (),"sentinel" ); 1098once (on != 0 ); 1099 std::vector < float > got ((size_t )nsamp * (size_t )N ); 1100uint64_t h = 1469598103934665603ull ; 1101for (int s = 0 ;s < nsamp ;++ s ) { 1102ck (cudaMemcpy (got .data ()+ (size_t )s * (size_t )N ,y .as < uint8_t > ()+ (size_t )srow [(size_t )s ]* (size_t )N * 4 , (size_t )N * 4 ,cudaMemcpyDeviceToHost ),"download" ); 1103const uint32_t * u = (const uint32_t * ) (got .data ()+ (size_t )s * (size_t )N ); 1104for (int64_t c = 0 ;c < N ;++ c ) {h = (h ^u [c ])* 1099511628211ull ;nonfin [on ]+= !std::isfinite (got [(size_t )s * (size_t )N + (size_t )c ]); } 1105 } 1106hsh [on ]= h ; 1107err [on ]= compare (got ,ref , (size_t )nsamp , (int )N ); 1108 } 1109 std::vector < float > t_off ,t_on ; 1110for (int rep = 0 ;rep < o .repeats + 2 ;++ rep ) {// two warm-up rounds, then the timed ones, off and on alternating (the first rotating) 1111const bool first_on = rep & 1 ; 1112const float a = once (first_on ),b = once (!first_on ); 1113if (rep < 2 )continue ; 1114 (first_on ?t_on :t_off ).push_back (a ); 1115 (first_on ?t_off :t_on ).push_back (b ); 1116 } 1117cudaEventDestroy (ea ); 1118cudaEventDestroy (eb ); 1119ck (cudaGetLastError (),"after timing" ); 1120const float m_off = median (t_off ),m_on = median (t_on ); 1121auto spread = [](const std::vector < float >& v ) {return (* std::max_element (v .begin (),v .end ())- * std::min_element (v .begin (),v .end ())) /median (v ); }; 1122 std::printf (" %-15s %-6s T=%-6d N=%-6lld K=%-6lld uses %-3d off %9.3f ms on %9.3f ms off/on %6.3f err off %.2e/%.2e on %.2e/%.2e\n" ,d .name ,d .bf16 ?"bf16" :ggml_type_name (ntype ),T , 1123 (long long )N , (long long )K ,d .uses ,m_off ,m_on ,m_off /m_on ,err [0 ].rms ,err [0 ].worst ,err [1 ].rms ,err [1 ].worst ); 1124 std::string cn = card .name ; 1125for (char & c :cn )if (c == ' ' )c = '_' ; 1126 std::printf ("RESULT dense=1 gemm=%s kind=%s site=prefill.cpp:%s tokens=%d N=%lld K=%lld uses=%d ms_off=%.3f ms_on=%.3f off_over_on=%.3f spread_off=%.3f spread_on=%.3f repeats=%d " 1127"err_off=%.3e/%.3e err_on=%.3e/%.3e hash_off=%016llx hash_on=%016llx nonfinite=%lld f16io_effective=%d f16io_default_here=%d card=%s arch=%s\n" , 1128d .name ,d .bf16 ?"bf16" :ggml_type_name (ntype ),d .site ,T , (long long )N , (long long )K ,d .uses ,m_off ,m_on ,m_off /m_on ,spread (t_off ),spread (t_on ),o .repeats , 1129err [0 ].rms ,err [0 ].worst ,err [1 ].rms ,err [1 ].worst , (unsigned long long )hsh [0 ], (unsigned long long )hsh [1 ],nonfin [0 ]+ nonfin [1 ],FB_HIP_ON ?1 :0 , 1130dflt_on ?1 :0 ,cn .c_str (),card .arch .c_str ()); 1131 std::fflush (stdout ); 1132* sum_off += (double )m_off * d .uses ; 1133* sum_on += (double )m_on * d .uses ; 1134} 1135}// namespace 1136 1137// --real: one line of the pack's native_experts.txt ("layer gu_type d_type offset blob_bytes gate_off up_off down_off": absolute offsets of the three stacked expert tensors in the GGUF shard) 1138struct PackRow { 1139int layer = 0 ,gu = 0 ,d = 0 ; 1140unsigned long long blob = 0 ,gate_off = 0 ,up_off = 0 ,down_off = 0 ; 1141}; 1142std::vector < PackRow > read_pack (const std::string & path ) { 1143 std::vector < PackRow > v ; 1144 std::ifstream in (path ); 1145if (!in )throw std::runtime_error ("--real-pack: cannot open " + path ); 1146 std::string line ; 1147while (std::getline (in ,line )) { 1148if (line .empty ()|| line [0 ]== '#' )continue ; 1149PackRow r ; 1150unsigned long long off = 0 ; 1151if (std::sscanf (line .c_str (),"%d %d %d %llu %llu %llu %llu %llu" ,& r .layer ,& r .gu ,& r .d ,& off ,& r .blob ,& r .gate_off ,& r .up_off ,& r .down_off )== 8 )v .push_back (r ); 1152 } 1153return v ; 1154} 1155 1156// the dump of STRATA_DUMP_MOE_INPUT (one file per layer: {T, N, K} int64, T x N floats, T x K expert ids) and the layer's experts (the ones some row routes to) from the GGUF 1157RealLayer load_real (const Opts & o ,const PackRow & pr ,const Pair & p ,const Shape & s ) { 1158RealLayer rl ; 1159rl .layer = pr .layer ; 1160const std::string dump = o .real_dir + "/moe.L" + std::to_string (pr .layer ); 1161 std::ifstream f (dump , std::ios::binary ); 1162if (!f )throw std::runtime_error ("no dump " + dump ); 1163int64_t hdr [3 ]= {}; 1164f .read ((char * )hdr ,sizeof hdr ); 1165if (!f || hdr [1 ]!= s .N || hdr [2 ]!= s .K || hdr [0 ] <=0 )throw std::runtime_error ("dump " + dump + ": header T " + std::to_string (hdr [0 ])+ " N " + std::to_string (hdr [1 ])+ " K " + std::to_string (hdr [2 ])); 1166rl .T = (int )hdr [0 ]; 1167rl .x .resize ((size_t )rl .T * s .N ); 1168rl .ids .resize ((size_t )rl .T * s .K ); 1169f .read ((char * )rl .x .data (), (std::streamsize ) (rl .x .size ()* 4 )); 1170f .read ((char * )rl .ids .data (), (std::streamsize ) (rl .ids .size ()* 4 )); 1171if (!f )throw std::runtime_error ("dump " + dump + ": short" ); 1172const Geo geo (p ,s ); 1173const size_t gate_per_e = geo .up_off ,down_per_e = geo .bytes - geo .down_off ; 1174 std::vector < char > need ((size_t )s .E ,0 ); 1175for (int32_t e :rl .ids ) { 1176if (e < 0 || e >=s .E )throw std::runtime_error ("dump " + dump + ": expert id " + std::to_string (e )); 1177need [(size_t )e ]= 1 ; 1178 } 1179 std::ifstream g (o .real_gguf , std::ios::binary ); 1180if (!g )throw std::runtime_error ("--real-gguf: cannot open " + o .real_gguf ); 1181rl .blob .assign ((size_t )s .E , std::vector < uint8_t > ()); 1182for (int e = 0 ;e < s .E ;++ e ) { 1183if (!need [(size_t )e ])continue ; 1184 std::vector < uint8_t >& b = rl .blob [(size_t )e ]; 1185b .resize (geo .bytes ); 1186const unsigned long long at [3 ]= {pr .gate_off + (unsigned long long )e * gate_per_e ,pr .up_off + (unsigned long long )e * gate_per_e ,pr .down_off + (unsigned long long )e * down_per_e }; 1187const size_t dst [3 ]= {0 ,geo .up_off ,geo .down_off },len [3 ]= {gate_per_e ,gate_per_e ,down_per_e }; 1188for (int k = 0 ;k < 3 ;++ k ) { 1189g .seekg ((std::streamoff )at [k ]); 1190g .read ((char * )b .data ()+ dst [k ], (std::streamsize )len [k ]); 1191if (!g )throw std::runtime_error ("--real-gguf: short read of layer " + std::to_string (pr .layer )+ " expert " + std::to_string (e )); 1192 } 1193 } 1194return rl ; 1195} 1196 1197int main (int argc ,char ** argv ) { 1198try { 1199Opts o ; 1200for (int i = 1 ;i < argc ;++ i ) { 1201const char * a = argv [i ]; 1202if (std::string v = arg_after (a ,"--shape=" ); !v .empty ()) { 1203if (v == "flash" )o .shape = {2560 ,640 ,512 ,10 ,"flash" }; 1204else if (v == "q36" )o .shape = {2048 ,512 ,256 ,8 ,"q36" }; 1205else { 1206const std::vector < int > d = parse_ints (v ); 1207if (d .size ()!= 4 || d [0 ] <=0 || d [1 ] <=0 || d [2 ] <=0 || d [3 ] <=0 || d [3 ]> d [2 ])throw std::runtime_error ("--shape=flash|q36|N,FF,E,K" ); 1208o .shape = {d [0 ],d [1 ],d [2 ],d [3 ],"custom" }; 1209 } 1210 } 1211else if (std::string v2 = arg_after (a ,"--tokens=" ); !v2 .empty ()) {o .tokens = parse_ints (v2 );o .tokens_set = true; } 1212else if (std::string va = arg_after (a ,"--dense-type=" ); !va .empty ())o .dense_type = va ; 1213else if (std::string v3 = arg_after (a ,"--only=" ); !v3 .empty ())o .only .push_back (v3 ); 1214else if (std::string v4 = arg_after (a ,"--repeats=" ); !v4 .empty ())o .repeats = std::max (1 , std::atoi (v4 .c_str ())); 1215else if (std::string v5 = arg_after (a ,"--warm-ms=" ); !v5 .empty ())o .warm_ms = (float ) std::atof (v5 .c_str ()); 1216else if (std::string v6 = arg_after (a ,"--skew=" ); !v6 .empty ())o .skew = std::atof (v6 .c_str ()); 1217else if (std::string v7 = arg_after (a ,"--experts=" ); !v7 .empty ())o .experts = std::atoi (v7 .c_str ()); 1218else if (std::string v8 = arg_after (a ,"--sample=" ); !v8 .empty ())o .sample = std::max (1 , std::atoi (v8 .c_str ())); 1219else if (std::string v9 = arg_after (a ,"--seed=" ); !v9 .empty ())o .seed = (unsigned ) std::atoll (v9 .c_str ()); 1220else if (!std::strcmp (a ,"--all" ))o .all = true; 1221else if (!std::strcmp (a ,"--list" ))o .list = true; 1222else if (!std::strcmp (a ,"--grouped" ))o .grouped = true; 1223else if (std::string v10 = arg_after (a ,"--i8-tm=" ); !v10 .empty ()) { 1224o .i8 = true; 1225for (size_t q = 0 ;q < v10 .size ();) {o .i8_tms .push_back (std::atoi (v10 .c_str ()+ q ));q = v10 .find (',' ,q )== std::string::npos ?v10 .size () :v10 .find (',' ,q )+ 1 ; } 1226 } 1227else if (!std::strcmp (a ,"--i8" ))o .i8 = true; 1228else if (!std::strcmp (a ,"--no-grp" ))o .no_grp = true; 1229else if (!std::strcmp (a ,"--no-mmq" ))o .no_mmq = true; 1230else if (!std::strcmp (a ,"--no-fused" ))o .no_fused = true; 1231else if (!std::strcmp (a ,"--no-fp16" ))o .no_fp16 = true; 1232else if (!std::strcmp (a ,"--no-ref" ))o .no_ref = true; 1233else if (!std::strcmp (a ,"--quick" ))o .quick = true; 1234else if (!std::strcmp (a ,"--dense" ))o .dense = true; 1235else if (std::string vr = arg_after (a ,"--real=" ); !vr .empty ())o .real_dir = vr ; 1236else if (std::string vp = arg_after (a ,"--real-pack=" ); !vp .empty ())o .real_pack = vp ; 1237else if (std::string vg = arg_after (a ,"--real-gguf=" ); !vg .empty ())o .real_gguf = vg ; 1238else if (std::string vl = arg_after (a ,"--real-layers=" ); !vl .empty ())o .real_layers = parse_ints (vl ); 1239else { std::fprintf (stderr ,"unknown argument %s (see the head of tests/cuda/prefill_expert_paths_bench.cpp)\n" ,a );return 1 ; } 1240 } 1241if (o .experts > 0 )o .shape .E = std::max (o .experts ,o .shape .K ); 1242if (o .quick ) {o .tokens = {512 };o .repeats = 3 ;o .warm_ms = 100.0f ;o .sample = 8 ;if (o .only .empty ())o .only .push_back ("IQ3_XXS / IQ4_NL" ); } 1243const std::vector < Pair >& pairs = all_pairs (); 1244if (o .list ) { 1245for (const Pair & p :pairs ) std::printf ("%s\n" ,p .name ); 1246return 0 ; 1247 } 1248// the opt-in switches that select the fused kernels and MMQ's K-quant library (the engine reads them; unset ones are set here, set ones are kept) 1249defenv ("STRATA_PF_FUSED" ,"1" ); 1250defenv ("STRATA_PF_FUSED_KQ" ,"1" ); 1251defenv ("STRATA_PF_FUSED_Q50" ,"1" ); 1252defenv ("STRATA_PF_FUSED_Q8D" ,"1" ); 1253defenv ("STRATA_PF_FUSED_Q8GU" ,"1" ); 1254defenv ("STRATA_PF_FUSED_Q6K" ,"1" ); 1255defenv ("STRATA_MMQ_KQ" ,"1" ); 1256 1257int n = 0 ; 1258if (cudaGetDeviceCount (& n )!= cudaSuccess || n == 0 ) { std::printf ("no GPU device: skipped\n" );return 77 ; } 1259cudaDeviceProp prop {}; 1260ck (cudaGetDeviceProperties (& prop ,0 ),"device properties" ); 1261Card card ; 1262card .name = prop .name ; 1263card .major = prop .major ; 1264card .minor = prop .minor ; 1265card .total = prop .totalGlobalMem ; 1266#if defined(FB_HIP ) 1267card .hip = true; 1268card .arch = prop .gcnArchName ; 1269#else 1270card .arch = "sm_" + std::to_string (prop .major )+ std::to_string (prop .minor ); 1271#endif 1272size_t fr_free = 0 ,fr_tot = 0 ; 1273cudaMemGetInfo (& fr_free ,& fr_tot ); 1274const Shape s0 = o .shape ; 1275// the FP16 path's swiglu_interleaved and the few-row record are written for the compiled geometry (prefill.cpp is, too): any other shape has no FP16 column 1276const bool fp16_shape_ok = s0 .N == (int ) fused::kMoeEmbd && s0 .FF == (int ) fused::kMoeFF ; 1277// fewrows.hpp's default: off unless STRATA_PF_FEWROWS, except on the Tesla P100 (cc 6.0) where gp100_prompt_default.hpp turns it on with the FP16 path 1278const char * few_env = std::getenv ("STRATA_PF_FEWROWS" ); 1279const bool fewrows_dflt = pf::fewrows_switch (few_env ,card .major == 6 && card .minor == 0 ); 1280 std::printf ("prefill_expert_paths_bench: %s (%s), %.1f GiB (%.1f free), device 0 of %d\n" ,card .name .c_str (),card .arch .c_str (), (double )card .total /1073741824.0 , 1281 (double )fr_free /1073741824.0 ,n ); 1282 std::printf (" shape %s: n_embd %d, n_ff %d, %d experts, top %d; compiled geometry %d x %d (FP16 column %s); MMQ in this build: %s; fused kernels for an IQ3_XXS / IQ4_NL layer here: %s\n" , 1283s0 .name .c_str (),s0 .N ,s0 .FF ,s0 .E ,s0 .K , (int ) fused::kMoeEmbd , (int ) fused::kMoeFF ,fp16_shape_ok ?"on" :"off: this shape is not the compiled one" , 1284 mmq::built () ?"yes" :"no" , (fused::native_supported (GGML_TYPE_IQ3_XXS ,GGML_TYPE_IQ4_NL ) ?"yes" :"no" )); 1285 std::printf (" few-row experts (<= %d rows) on the quantized kernels by default here: %s (STRATA_PF_FEWROWS=%s); routing %s; repeats %d after %.0f ms warm-up\n" , pf::kFewRows , 1286fewrows_dflt ?"yes" :"no" ,few_env ?few_env :"unset" ,o .skew > 0 ?"Zipf" :"uniform" ,o .repeats , (double )o .warm_ms ); 1287 1288cudaStream_t st = nullptr ; 1289ck (cudaStreamCreateWithFlags (& st ,cudaStreamNonBlocking ),"stream" ); 1290// the engine's Gemm, set up as Prefill::init sets it (prefill.cpp: init_external with the 32 MiB scratch and workspace, f16 I/O where the card wants it) 1291 pf::Gemm gemm ; 1292Dev gscratch ((size_t )GEMM_SCRATCH * 2 ),gws (GEMM_WS ); 1293 { 1294 std::string err ; 1295if (!gemm .init_external (st ,gscratch .as < uint16_t > (),GEMM_SCRATCH ,gws .p ,GEMM_WS ,err ))throw std::runtime_error ("Gemm::init_external: " + err ); 1296const bool f16io = pf::prompt_f16 (); 1297gemm .set_f16_io (f16io ); 1298 pf::set_act_f16 (f16io ); 1299 std::printf (" Gemm: prompt_f16() %s\n" ,f16io ?"on (FP16 in / FP16 out)" :"off" ); 1300 } 1301 1302if (o .dense ) {// the dense prompt GEMMs, FP16 io off and on (no experts, no pairs) 1303ggml_type nt = GGML_TYPE_COUNT ; 1304for (int t = 0 ;t < (int )GGML_TYPE_COUNT ;++ t ) { 1305const char * nm = ggml_type_name ((ggml_type )t ); 1306if (nm != nullptr && nospace (nm )== nospace (o .dense_type .c_str ()))nt = (ggml_type )t ; 1307 } 1308if (nt == GGML_TYPE_COUNT || ggml_get_type_traits (nt )-> to_float == nullptr )throw std::runtime_error ("--dense-type=NAME: a ggml type with a to_float, e.g. Q8_0" ); 1309if (!o .tokens_set )o .tokens = {2048 ,8192 ,20000 }; 1310if (o .quick ) {o .tokens = {512 };if (o .only .size ()== 1 && o .only [0 ]== "IQ3_XXS / IQ4_NL" )o .only .clear (); }// (--quick put its expert pair in --only) 1311const bool dflt_on = pf::prompt_f16 (); 1312 std::printf (" dense mode: Flash-Next (compiled geometry) projection GEMMs, native weights %s; FP16 io off = Gemm as the engine runs it by default, on = Gemm::set_f16_io(true) (STRATA_HIP_PROMPT_F16=1);\n" 1313" prompt_f16() here: %s (the engine turns it on only when STRATA_HIP_PROMPT_F16=1 on a HIP card); effect of set_f16_io on this build: %s\n" , 1314ggml_type_name (nt ),dflt_on ?"on" :"off" ,FB_HIP_ON ?"yes (HIP)" :"none (CUDA: both columns are the same code, the ratio is the noise floor)" ); 1315const std::vector < DenseShape > ds = dense_shapes (); 1316for (int T :o .tokens ) { 1317double so = 0 ,sn = 0 ; 1318int ran = 0 ; 1319 std::printf ("== dense GEMMs at T=%d tokens\n" ,T ); 1320for (const DenseShape & d :ds ) { 1321if (!o .only .empty ()) { 1322bool take = false; 1323for (const std::string & k :o .only )take |=nospace (d .name ).find (nospace (k .c_str ()))!= std::string::npos ; 1324if (!take )continue ; 1325 } 1326try { 1327run_dense_cell (d ,T ,nt ,o ,card ,gemm ,st ,dflt_on ,& so ,& sn ); 1328++ ran ; 1329 }catch (const std::exception & e ) { 1330cudaGetLastError (); 1331 std::printf (" %-15s T=%d: SKIPPED (%s)\n" ,d .name ,T ,e .what ()); 1332if (std::strstr (e .what (),"cudaMalloc" )== nullptr )throw ; 1333 } 1334 } 1335if (ran > 0 ) std::printf ("RESULT dense_total=1 tokens=%d gemms=%d ms_off_per_chunk=%.2f ms_on_per_chunk=%.2f off_over_on=%.3f (sum over the shapes x uses per chunk) arch=%s\n" ,T ,ran ,so ,sn ,sn > 0 ?so /sn :0.0 ,card .arch .c_str ()); 1336 } 1337ck (cudaStreamDestroy (st ),"destroy" ); 1338return 0 ; 1339 } 1340if (!o .real_dir .empty ()) {// --real: one cell per layer of the dump, the layer's own pair, rows, routing and experts 1341if (o .real_pack .empty ()|| o .real_gguf .empty ())throw std::runtime_error ("--real needs --real-pack=native_experts.txt and --real-gguf=SHARD.gguf" ); 1342const std::vector < PackRow > pack = read_pack (o .real_pack ); 1343int cells = 0 ,skipped = 0 ; 1344for (const PackRow & pr :pack ) { 1345if (!o .real_layers .empty ()&& std::find (o .real_layers .begin (),o .real_layers .end (),pr .layer )== o .real_layers .end ())continue ; 1346const Pair * pp = nullptr ; 1347for (const Pair & q :pairs )if ((int )q .gu == pr .gu && (int )q .d == pr .d )pp = & q ; 1348if (pp == nullptr ) { std::printf ("== REAL layer %d: gate/up type %d, down type %d is not a pair of this bench: skipped\n" ,pr .layer ,pr .gu ,pr .d );++ skipped ;continue ; } 1349try { 1350const RealLayer rl = load_real (o ,pr ,* pp ,s0 ); 1351run_cell (* pp ,s0 ,rl .T ,o ,card ,gemm ,st ,fp16_shape_ok ,fewrows_dflt ,& rl ); 1352++ cells ; 1353 }catch (const std::exception & e ) { 1354cudaGetLastError (); 1355 std::printf ("== REAL layer %d: SKIPPED (%s)\n" ,pr .layer ,e .what ()); 1356++ skipped ; 1357if (std::strstr (e .what (),"cudaMalloc" )== nullptr && std::strstr (e .what (),"dump" )== nullptr )throw ; 1358 } 1359 std::fflush (stdout ); 1360 } 1361ck (cudaStreamDestroy (st ),"destroy" ); 1362 std::printf ("prefill_expert_paths_bench --real: %d layers run, %d skipped\n" ,cells ,skipped ); 1363return 0 ; 1364 } 1365 std::vector < Pair > sel ; 1366for (size_t i = 0 ;i < pairs .size ();++ i ) { 1367bool take = false; 1368if (!o .only .empty ())for (const std::string & k :o .only )take |=nospace (pairs [i ].name ).find (nospace (k .c_str ()))!= std::string::npos ;// (spaces ignored: --only=IQ3_XXS/IQ4_NL) 1369else take = o .all || i < (size_t )kDefaultPairs ; 1370if (take )sel .push_back (pairs [i ]); 1371 } 1372if (sel .empty ())throw std::runtime_error ("no pair matches --only (see --list)" ); 1373int cells = 0 ,skipped = 0 ; 1374for (const Pair & p :sel ) { 1375if (!fits_blocks (p .gu ,s0 .N )|| !fits_blocks (p .d ,s0 .FF )|| !fits_blocks (p .gu ,s0 .N )) { 1376 std::printf ("== %s: skipped, the rows (%d / %d values) are not whole blocks of the format\n" ,p .name ,s0 .N ,s0 .FF ); 1377++ skipped ; 1378continue ; 1379 } 1380for (int T :o .tokens ) { 1381try { 1382run_cell (p ,s0 ,T ,o ,card ,gemm ,st ,fp16_shape_ok ,fewrows_dflt ); 1383++ cells ; 1384 }catch (const std::exception & e ) { 1385cudaGetLastError (); 1386 std::printf ("== %s T=%d: SKIPPED (%s)\n" ,p .name ,T ,e .what ()); 1387 std::fflush (stdout ); 1388++ skipped ; 1389if (std::strstr (e .what (),"cudaMalloc" )== nullptr )throw ;// only a failed allocation is a skip; anything else ends the run 1390 } 1391 } 1392 } 1393ck (cudaStreamDestroy (st ),"destroy" ); 1394 std::printf ("prefill_expert_paths_bench: %d cells run, %d skipped\n" ,cells ,skipped ); 1395return 0 ; 1396 }catch (const std::exception & e ) { 1397 std::fprintf (stderr ,"prefill_expert_paths_bench failed: %s\n" ,e .what ()); 1398return 1 ; 1399 } 1400}