okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
74d12d663
main
1// src/prefill/prefill.cpp - see include/strata/prefill/prefill.hpp. 2#include "strata/kernels/fused_gr.hpp" 3#include "strata/prefill/prefill.hpp" 4#include "strata/prefill/copy_events.hpp" 5#include "strata/prefill/timer_marks.hpp" 6#include "strata/prefill/mmq_ids_margin.hpp" 7#include "strata/core/run_manifest.hpp" 8#include "strata/artifact/gguf_reader.hpp" 9#include "strata/prefill/pf_fused_override.hpp" 10#include "strata/prefill/staged_group_rule.hpp" 11#include "strata/prefill/staged_fo_rule.hpp" 12#include "strata/prefill/plain_floor_rule.hpp" 13#include "strata/prefill/share_own_rule.hpp" 14#include "strata/prefill/fp16_rows_rule.hpp" 15#include "strata/prefill/own_only_line.hpp" 16#include "strata/prefill/own_only_switches.hpp" 17#include "strata/prefill/stream_floor_rule.hpp" 18#include "strata/prefill/switch_point_rule.hpp" 19#include "strata/kernels/gfx_arch.hpp" 20#include "strata/quant/types.hpp" 21#include "strata/prefill/fewrows.hpp" 22#include "strata/prefill/gp100_prompt_default.hpp" 23#if defined(STRATA_HAVE_DFLASH2 ) 24#include "strata/kernels/dflash2.hpp" 25#endif 26#include "strata/prefill/warm_policy.hpp" 27#include "strata/prefill/share_rules.hpp" 28#include "strata/core/arch_defaults.hpp" 29#include "strata/core/kfd_quiet.hpp" // LOAD: the first prompt's buffers at init (integrated gfx11, Linux HIP) 30#include <atomic> 31#if defined(__cpp_lib_atomic_wait ) 32#define STRATA_ATOMIC_WAIT 1 // #1488: std::atomic::wait / notify_all are a GCC 11 library feature; GCC 10 spins instead 33#endif 34#include "mmq_resident_sort.hpp" 35#include "wmma_gemm.h" 36#include "strata/core/kv_host_dma.hpp" 37#include "strata/core/mtp.hpp" 38#include "strata/core/pinned_ring.hpp" 39#include "strata/core/progress.hpp" 40#include "strata/core/on_device.hpp" 41#include "strata/core/stream_watch.hpp" 42#include "strata/platform/aux_cpus.hpp" 43 44#include "strata/core/layout.hpp" 45#include "strata/kernels/cpu/expert.hpp" 46#include "strata/kernels/native_qsa.hpp" 47#include "strata/kernels/native_mmvq.hpp" 48#include "strata/kernels/cpu/native_expert.hpp" 49#include "strata/kernels/cpu/pool.hpp" 50#include "strata/kernels/native_qsa_indexer.hpp" 51#include "strata/kernels/ngram.hpp" 52#include "strata/kernels/ple.hpp" 53#include "strata/kernels/native_ple_postops.hpp" 54#include "strata/kernels/iq_kernels.hpp" 55#include "strata/kernels/cpu/expert_layout.hpp" 56#include "strata/core/latent_dense.hpp" // latent MoE: the per-layer D/U Q8_0 tables, host-side 57#include "strata/core/latent_share.hpp" // latent MoE: the session-level device D/U pair, pulled in init 58#include "strata/kernels/latent.hpp" // latent_plan_rows / latent_u_grouped (the verify soul) 59#include "strata/kernels/cpu/hadamard.hpp" 60#include "strata/kernels/qsa.hpp" 61#include "strata/kernels/kv_stream.hpp" 62#include "strata/kernels/cvec.hpp" 63#include "strata/kernels/kv_q4.hpp" 64#include "strata/core/layer.hpp" 65#include "strata/core/native_dense.hpp" 66#include "strata/core/native_head.hpp" 67#include "strata/kernels/verify_kernels.hpp" 68#include "strata/kernels/qsa_decode_attn.hpp" 69#include "strata/kernels/qsa_pattn.hpp" 70#include "strata/kernels/qsa_prompt_attn.hpp" 71#include "strata/kernels/qsa_select.hpp" 72#include "strata/kernels/qsa_two_pass.hpp" 73#include "strata/kernels/qsa_two_pass_status.hpp" 74#include "strata/prefill/gemm.hpp" 75#include "strata/prefill/moe_fused.hpp" 76#include "strata/prefill/moe_ws.hpp" 77#include "strata/prefill/moe_fused_iq.hpp" 78#include "strata/prefill/moe_mmq.hpp" 79#include "strata/kernels/i8_expert_rule.hpp" 80#include "strata/prefill/i8_group.hpp" 81#include "strata/prefill/routed_stream.hpp" 82#include "strata/prefill/lat_group_tables.hpp" 83#include "strata/prefill/lat_q3k_fused.hpp" // M4: STRATA_LAT_FUSED_Q3K 84#include "strata/prefill/moe_fused_q3k.hpp" // the q3k pack's variant of v5's latent kernel 85#include "strata/prefill/staged_batch.hpp" 86#include "strata/core/peer_experts.hpp" 87#include "strata/core/expert_nibble.hpp" 88#include "strata/core/sm120_series.hpp" 89 90namespace strata::kernels {// the P100 class rule's entry point (iq_kernels.cu; Metal: stubs_i8.cpp); declared here so that no kernel object's header changes 91bool native_expert_i8_floor_gated ()noexcept ;// true: the unset int8 default gives way to the FP16 path from stream_all_min() tokens up (Tesla P100, build without MMQ) 92}// namespace strata::kernels 93 94namespace { 95// STRATA_PLE_BATCH for the prompt path: the user's variable wins; unset, it is on except for an engine built with CUDA 12.8 on a compute capability 12.0 card 96// (sm120_series.hpp ple_batch_default), which says so once. 97bool ple_batch_enabled () { 98#if defined(CUDART_VERSION )&& !defined(STRATA_USE_HIP )&& !defined(__HIPCC__ ) 99constexpr int kRt = CUDART_VERSION ; 100constexpr bool kHip = false; 101#else 102constexpr int kRt = 0 ; 103constexpr bool kHip = true; 104#endif 105static const char * env = std::getenv ("STRATA_PLE_BATCH" ); 106int dev = 0 ,major = 0 ,minor = 0 ; 107if (env == nullptr && !kHip ) { 108if (cudaGetDevice (& dev )== cudaSuccess ) { 109cudaDeviceGetAttribute (& major ,cudaDevAttrComputeCapabilityMajor ,dev ); 110cudaDeviceGetAttribute (& minor ,cudaDevAttrComputeCapabilityMinor ,dev ); 111 } 112 (void )cudaGetLastError (); 113 } 114const bool on = strata::ple_batch_resolve (env ,kRt ,kHip ,major ,minor ); 115static std::atomic < bool > said {false}; 116if (!on && env == nullptr && !said .exchange (true)) 117 std::fprintf (stderr ,"strata prefill: the batched PLE post-ops are off by default here: this engine was built with CUDA 12.8, whose build faults in the prompt path on a " 118"compute capability 12.0 card (issues #220, #224). Use an engine built with CUDA 13.0 or newer; STRATA_PLE_BATCH=1 turns it on anyway.\n" ); 119return on ; 120} 121}// namespace 122#include "strata/core/defaults_026.hpp" 123#include "strata/prefill/kernels.hpp" 124#include "strata/prefill/kva.hpp" // STRATA_KVA: the optional approximate-prefill plan (research, off by default) 125 126#include <cuda_runtime.h> 127 128#include <algorithm> 129#include <cassert> 130#include <chrono> 131#include <cmath> 132#include <cstdio> 133#include <deque> 134#include <map> 135#include <string> 136#include <atomic> 137#include <condition_variable> 138#include <cstring> 139#include <future> 140#include <memory> 141#include <optional> 142#include <mutex> 143#include <thread> 144#include <utility> 145#include <vector> 146 147#if !defined(STRATA_PREFILL_MMQ )&& !defined(STRATA_PREFILL_FUSED ) 148// A build without the llama.cpp sources (no STRATA_NATIVE_EXPERTS): no MMQ, the FP16 expert path everywhere. (P4-SPLIT: a build with 149// Strata's own prompt kernels but no MMQ, -DSTRATA_MMQ=OFF, has the real helpers and src/prefill/mmq_absent.cpp instead.) 150#include "strata/core/geometry.hpp" 151 152namespace strata::prefill::mmq { 153bool built () {return false; } 154bool supported (int ) {return false; } 155bool fits (int ,int64_t ) {return false; } 156size_t matrix_bytes (int ,int64_t ,int64_t ) {return 0 ; } 157size_t q8_bytes (int64_t ,int64_t ) {return 0 ; } 158void quantize (const float * ,const int32_t * ,void * ,int ,int64_t ,int64_t ,int64_t ,void * ,float * ) {} 159bool fp4_activations (int ) {return false; } 160void quantize_scatter (const float * ,const int32_t * ,const int32_t * ,void * ,int ,int64_t ,int64_t ,int64_t ,int ,void * ) {} 161Context ::Context () {} 162Context ::~Context () {} 163void Context ::run (const Product & ,void * ) {} 164void gather_native (const void * ,const void * ,size_t ,const void * ,size_t ,void * ,void * ,void * ,const void * ,void * ,size_t ) {} 165bool gather_native_group (const GatherGroup & ,size_t ,size_t ,size_t ,size_t ,void * ,size_t ,void * ,size_t ,void * ,size_t , 166void * ,size_t ) {return false; } 167void gather_strata_q2 (const uint8_t * ,void * ,void * ,void * ) {} 168void swiglu (const float * ,float * ,int64_t ,int64_t ,bool ,void * ) {} 169bool swiglu_quant_ok (int ) {return false; } 170void swiglu_quant (const float * ,void * ,int64_t ,bool ,void * ) {} 171void swiglu_scaled (const float * ,float * ,int64_t ,int64_t ,const int32_t * ,int ,const float * ,int64_t ,void * ) {} 172void down_row_scales (float * ,const int32_t * ,int ,const float * ,int64_t ,void * ) {} 173void iota (int32_t * ,int64_t ,void * ) {} 174bool tab_built () {return false; } 175bool tab_fits (int ,int64_t ) {return false; } 176size_t overread_bytes (int ,int64_t ) {return 0 ; } 177bool whole_tiles (int ,int64_t ,int ) {return false; } 178int direct_mode () {return 0 ; } 179size_t direct_slot_guard () {return 0 ; } 180void prep_group (const GuardTab & ,size_t ,void * ,void * ,size_t ,void * ) {} 181}// namespace strata::prefill::mmq 182#endif 183#ifndef STRATA_PREFILL_FUSED 184// #136: the fused int8 experts are CUDA-only (HIP and builds without MMQ keep the MMQ / FP16 paths) 185namespace strata::prefill::fused { 186bool built () {return false; } 187bool gfx12_iq2s_default () {return false; }// AMD-Q: a HIP build without the fused kernels (STRATA_PREFILL_MMQ off) still links prefill.cpp's share-limit call 188bool available () {return false; } 189bool enabled () {return false; } 190bool requested () {return false; } 191size_t act_bytes (int64_t ,int64_t ) {return 0 ; } 192size_t group_bytes (int64_t ,int ) {return 0 ; } 193void quantize_act (const float * ,int64_t ,int64_t ,void * ,void * ) {} 194void group (const int32_t * ,int64_t ,int ,int ,void * ,int32_t * ,int32_t * ,void * ) {} 195void group_bounds (const int32_t * ,int ,void * ,void * ) {} 196void experts (const Batch & ,int ,int64_t ,const void * ,const void * ,const int32_t * ,void * ,float * ,void * ) {} 197bool native_supported (int ,int ) {return false; } 198void quantize_act_native (const float * ,int64_t ,int64_t ,void * ,void * ) {} 199void experts_native (const Batch & ,const NativeGeom & ,int ,int64_t ,const void * ,const void * ,const int32_t * ,void * , 200float * ,void * ) {} 201bool native_wide () {return false; } 202void experts_native (const WideBatch & ,const NativeGeom & ,int ,int64_t ,const void * ,const void * ,const int32_t * ,void * , 203float * ,void * ) {} 204void set_down_rotation (bool ,const float * ) {} 205bool p1a_wanted () {return false; } 206void p1a_input (const void * ,size_t ) {} 207bool p1a_used () {return false; } 208bool p1a_takes_pair (int ,int ) {return false; } 209void hadamard128_rows (float * ,int64_t ,int64_t ,const float * ,void * ) {} 210}// namespace strata::prefill::fused 211#endif 212#if defined(STRATA_PREFILL_FUSED )&& !defined(STRATA_PREFILL_MMQ ) 213// P4-SPLIT: built with Strata's own prompt kernels and without llama.cpp's MMQ (-DSTRATA_MMQ=OFF, or HIP without STRATA_PREFILL_MMQ) 214#define STRATA_PF_OWN_ONLY 1 215namespace { 216// Such an engine takes Strata's fused kernels wherever they exist for the card and the layer's formats, so the opt-in switches of those 217// kernels are on by default here (a switch the user set, either value, is kept); every other layer takes the FP16 path. Set before main(), 218// so the first reader of each (the engine's start-up rules, the kernels' own static reads) sees it. Listed once in the prompt path's line. 219// (the list lives in own_only_switches.hpp: the start-up rules of generate.cpp ask it which names the build set and which the user did) 220std::vector < std::string >& own_only_switches () {return strata::prefill::own_only_recorded (); } 221const bool g_own_only_defaults = [] { 222 strata::prefill::own_only_build_flag ()= true;// (the engine's start-up rules ask own_only_build(): a build without MMQ has no MMQ kernels to go back to) 223 strata::kernels::native_expert_i8_set_mmq_free ();// the int8 expert kernels are the default prompt-expert kernels here (i8_expert_rule.hpp, i8_switch_effective) 224#if defined(STRATA_USE_HIP )|| defined(__HIPCC__ ) 225// (gfx12 only: every one of these is read behind the device's own gfx12 check, moe_fused_iq.cu q8d_hip_requested .. q6k_hip_requested, so a gfx11 226// card keeps the rules it has: its layers of those formats take the FP16 path here as before) 227constexpr bool kHipList = true;// (include/strata/prefill/own_only_switches.hpp) 228#else 229// (STRATA_PF_FUSED_Q2N, the native Q2_0 pack's Q2_0 / Q2_0 layers, is in the list: the kernel reads it behind its own sm_80 check, so a card below sm_80 is unchanged, 230// and =0 takes it back; the reasons and the numbers are in own_only_switches.hpp) 231constexpr bool kHipList = false; 232#endif 233// a name that is already in the environment is the user's and is not recorded (the engine's rules read the record: own_only_user_named) 234 strata::prefill::own_only_apply_defaults ( 235kHipList , [](const char * k ) {return std::getenv (k ); }, 236 [](const char * k ) { 237#if defined(_WIN32 ) 238_putenv_s (k ,"1" ); 239#else 240setenv (k ,"1" ,0 ); 241#endif 242 }, 243own_only_switches ()); 244return true; 245}(); 246}// namespace 247#endif 248namespace { 249// own_only_line.hpp peer_keeps_mmq: this engine has no MMQ, so --peer-device's prompt share is always declined (set_peer) and the walk keeps its own kernels. 250// Here and not in the header: STRATA_PF_OWN_ONLY is defined above, after the header was included. 251#if defined(STRATA_PF_OWN_ONLY ) 252constexpr bool kPfOwnOnlyBuild = true; 253#else 254constexpr bool kPfOwnOnlyBuild = false; 255#endif 256}// namespace 257#ifndef STRATA_PREFILL_WS 258// the weight-stationary experts (moe_ws.hpp) are in the CUDA STRATA_EXPERIMENTAL_SM60 build only 259namespace strata::prefill::ws { 260int mode () {return 0 ; } 261bool supported (int ,int ) {return false; } 262bool faster (int ,double ) {return false; } 263size_t chunks (const int32_t * ,size_t ,const int32_t * ,const int32_t * ,Chunk * ) {return 0 ; } 264bool gate_up (const Layer & ,void * ) {return false; } 265void down (const Layer & ,void * ) {} 266}// namespace strata::prefill::ws 267#endif 268 269#if defined(STRATA_GPU_METAL ) 270// The Metal backend reads a prompt through its decode window (metal/src/engine/window.cpp): init keeps the chunk, run 271// hands over, draft_kv declines (the MTP hook reads the window's rows itself). 272namespace strata::metal_engine { 273bool window_ensure (const strata::core::ModelGeometry & g , strata::core::SessionState & ss ,int64_t max_cells , std::string & err ); 274bool prompt_taps (const std::vector < int >& layers ,int64_t first_pos ,const std::function < bool (const float * ,int64_t ,int64_t , std::string & )>& cb , std::string & err );// dflash2.inc 275bool prompt_run (const int64_t * tokens ,int64_t n ,int64_t pos0 ,const float * const * embd_rows , 276const std::function < bool (const float * ,int64_t ,int64_t , std::string & )>& on_chunk , std::string & err ); 277}// namespace strata::metal_engine 278#endif 279 280namespace { 281// STRATA_PLE_COMPACT=1 (opt-in): the prompt chunk's PLE rows go up raw and are dequantized on the device (IQ4_NL tables 282// held in memory); the same floats as the host dequant, 7x fewer bytes over PCIe 283bool ple_compact_on () { 284static const bool on = [] {const char * v = std::getenv ("STRATA_PLE_COMPACT" );return v != nullptr && v [0 ]== '1' ; }(); 285return on ; 286} 287// STRATA_PLE_COPY_STREAM=1 (opt-in, with PLE_COMPACT): the raw rows go up on a stream of their own instead of the compute 288// stream, which otherwise idles for the DMA (4.7 MB a 3K chunk = 2.9 ms on a Gen2 x4 link); the same bytes and kernels 289bool ple_copy_stream_on () { 290static const bool on = [] {const char * v = std::getenv ("STRATA_PLE_COPY_STREAM" );return v != nullptr && v [0 ]== '1' ; }(); 291return on ; 292} 293}// namespace 294namespace strata::prefill { 295namespace { 296 297using Clock = std::chrono::steady_clock ; 298constexpr float EPS = 1e-6f ; 299// the shape the engine is compiled for (include/strata/core/geometry.hpp; -DSTRATA_GEOMETRY picks it) 300constexpr int64_t N = strata::core::kCompiledGeometry .n_embd ,HC = strata::core::kCompiledGeometry .hc ,D = N * HC ,LR = strata::core::kCompiledGeometry .hc_lr ,K = strata::core::kCompiledGeometry .n_expert_used ,NE = strata::core::kCompiledGeometry .n_expert ; 301constexpr int64_t C = strata::core::kCompiledGeometry .ssm_conv_channels ,ZV = strata::core::kCompiledGeometry .ssm_value_dim ,HV = strata::core::kCompiledGeometry .ssm_v_heads ; 302// widths the buffers and kernel arguments below are written in (int, as the literals they replace were) 303constexpr int kEmbd = (int ) strata::core::kCompiledGeometry .n_embd ,kFF = (int ) strata::core::kCompiledGeometry .n_ff ,kFF2 = 2 * kFF ; 304constexpr int kNHead = (int ) strata::core::kCompiledGeometry .n_head ,kNKv = (int ) strata::core::kCompiledGeometry .n_head_kv ,kHeadDim = (int ) strata::core::kCompiledGeometry .head_dim ; 305constexpr int kQW = kNHead * kHeadDim ,kQFull = 2 * kQW ,kKvW = kNKv * kHeadDim ; 306static_assert(kQW == strata::core::kCompiledGeometry .ssm_value_dim ,"prefill: the attention width (heads x head_dim) and the GDN value width share the m.q / m.attn / m.attn_h buffers, so they must be equal" ); 307constexpr int kIdxQHeads = (int ) strata::core::kCompiledGeometry .idx_q_heads ,kIdxK = (int ) strata::core::kCompiledGeometry .idx_key_dim ,kIdxQW = kIdxQHeads * kIdxK ; 308// plan v0.3 P6: staging holds the largest blob of the pack (a native pack's blobs differ per layer) 309inline int64_t MAXBLOB () {return (int64_t ) strata::kernels::cpu::expert_layout ().max_blob ; } 310constexpr int STAGE = 8 ;// host->device expert staging ring (chunks below stream_all_min()) 311// The staged walk's ring when its MMQ groups take the staged experts too: two groups, so a slot is refilled only after 312// the group that read it was gathered (the walk stages at most STAGE_GRP - MMQ_GROUP - 1 entries ahead) 313constexpr int STAGE_GRP = 32 ; 314constexpr int kSplitHelpRing = 48 ;// layer split help: the helper stage's ring slots it streams through (at most) 315// The staged walk's batched group entry (fz_staged below): on by default in a CUDA build, opt-in (STRATA_PF_FUSED=1) in a HIP build (owner 2026-11-12, "8 yes for 316// nvidia"; staged_group_rule.hpp). The card's own fused rule (fused::native_supported) still has to take the layer's formats. 317inline bool staged_group_entry_on () { 318static const bool on = [] { 319#if defined(STRATA_USE_HIP )|| defined(__HIPCC__ )|| defined(STRATA_HIP_GFX906 ) 320constexpr bool hip = true; 321#else 322constexpr bool hip = false; 323#endif 324return strata::prefill::staged_group_entry_default (hip , std::getenv ("STRATA_PF_FUSED" )); 325 }(); 326return on ; 327} 328// STRATA_PREFILL_GROUP_GATHER (unset or not 0): the staged walk's resident groups (read again here for P4-SMALL's fused groups, which 329// need that staging: the same variable, the same answer) 330inline bool staged_group_gather () { 331static const bool on = [] { 332const char * v = std::getenv ("STRATA_PREFILL_GROUP_GATHER" ); 333return v == nullptr || std::atoi (v )!= 0 ; 334 }(); 335return on ; 336} 337// STRATA_PREFILL_STREAM_AHEAD=0 keeps the previous routed-only upload schedule (A/B). 338inline bool stream_ahead_enabled () { 339static const bool on = [] { 340const char * v = std::getenv ("STRATA_PREFILL_STREAM_AHEAD" ); 341return v == nullptr || std::atoi (v )!= 0 ; 342 }(); 343return on ; 344} 345// Step 3: from this chunk size on, every non-resident expert of every layer streams in a fixed order through a 346// ring_slots()-slot ring (nearly all 512 are routed at such a chunk), so the copy engine keeps working through the 347// attention halves instead of waiting for each layer's routing. 348// #828: STRATA_TEST_PAGEABLE=1 makes every pinned host allocation with a pageable fallback in Prefill::init fail, so the 349// fallbacks (what an LXC container's memlock limit forces) run on a PC that can pin - for ASan / MALLOC_CHECK_=3 runs. 350inline bool force_pageable () { 351static const bool v = [] {const char * e = std::getenv ("STRATA_TEST_PAGEABLE" );return e != nullptr && e [0 ]== '1' ; }(); 352return v ; 353} 354// #1057: the Stager threads wait by sleeping (atomic wait, blocking-sync events) instead of a yield spin. On Linux the 355// spinners starved a pinned host thread (DGX Spark IQ3_S 8K prompt 91 -> 1,222 tok/s with sleeping waits); on Windows 356// the 5070 read an 8K Q2_0 prompt 1.2% slower with them (1,469.5 -> 1,452 tok/s, 10 pairs), so they stay spinning 357// there. Same output either way. STRATA_STAGER_SLEEP=1/0 forces either. 358inline bool stager_sleep () { 359static const bool v = [] { 360const char * e = std::getenv ("STRATA_STAGER_SLEEP" ); 361if (e != nullptr && e [0 ]!= '\0' )return e [0 ]!= '0' ; 362#if defined(_WIN32 ) 363return false; 364#else 365return true; 366#endif 367 }(); 368return v ; 369} 370constexpr int RING_MAX = 1024 ;// the arrays; the ring itself is ring_slots(), at most ring_cap() 371// The chunk size from which every expert streams: 1024 since 0.1.30 (was 2048). Measured on the 5070, Q2_0 / IQ2_XS, 372// fixed cache: 1,500-token prompts 621 -> 785 / 612 -> 735 tok/s, 2,000 727 -> 934 / 712 -> 892, 4,000 (its last 373// chunk) 779 -> 912 / 766 -> 844, the same output. Below ~1,000 tokens the output changed on Q2_0 (a smaller chunk 374// takes other kernels), so 1024 is the floor. STRATA_PREFILL_STREAM_MIN overrides (A/B). With the CPU share armed 375// (Prefill::arm_cpu_share) it is the share's own limit instead: the share applies to staged chunks only. 376constexpr int64_t kStreamAllMinDefault = 1024 ;// the default above (and the CPU share's default limit) 377int64_t g_stream_min_share = 0 ; 378// A layer set in which EVERY layer has no MMQ tile for its formats and the fused kernels take it (UD-Q4_K_XL's Q4_K / Q5_K gate/up with a Q5_1 / Q8_0 down: STRATA_MMQ_KQ is 379// opt-in, so mmq::fits is false; the same test mmq_plan() makes, p.fo). Its chunks below the floor take the staged walk, which has no fused entry for such a layer 380// (fz_staged needs use_mmq, or the staged entry for fused-only layers: STRATA_PF_STAGED_FO, on by default on the class below) and without it runs every routed expert on the dequantize-to-FP16 path: about 1.6 s a prompt whatever its length (stream_floor_rule.hpp). 381inline bool layers_all_fused_only () { 382const auto & lay = strata::kernels::cpu::expert_layout (); 383if (!lay .native || lay .fmt .empty ())return false; 384if (const char * e = std::getenv ("STRATA_PREFILL_MMQ" );e != nullptr && std::atoi (e )== 0 )return false;// mmq_plan(): no plan, no fused-only layers 385#if defined(STRATA_PF_OWN_ONLY ) 386if (!fused::built ())return false; 387#else 388if (!mmq::built ())return false; 389#endif 390for (const auto & f :lay .fmt ) { 391if (mmq::fits (f .gu_type ,kFF2 )&& mmq::fits (f .d_type ,N ))return false;// a layer on MMQ 392if (!fused::native_supported (f .gu_type ,f .d_type ))return false;// a layer on the FP16 path at every size 393 } 394return true; 395} 396// The device class the lower floor was measured on: Windows, one visible card, gfx1151 (Strix Halo). Not cached before a card answers. 397inline bool stream_floor_class_measured () { 398#if defined(STRATA_USE_HIP )&& defined(_WIN32 ) 399static std::atomic < int > state {-1 }; 400int s = state .load (std::memory_order_acquire ); 401if (s < 0 ) { 402int dev = 0 ,n = 0 ; 403cudaDeviceProp prop ; 404if (cudaGetDeviceCount (& n )!= cudaSuccess || cudaGetDevice (& dev )!= cudaSuccess || cudaGetDeviceProperties (& prop ,dev )!= cudaSuccess ) { 405 (void )cudaGetLastError (); 406return false; 407 } 408s = n == 1 && strata::kernels::gfx_arch_is_gfx1151 (prop .gcnArchName ) ?1 :0 ; 409state .store (s , std::memory_order_release ); 410 } 411return s == 1 ; 412#else 413return false; 414#endif 415} 416// The staged walk's group entry (fz_staged) also takes a layer with no MMQ tile that the fused kernels cover (mmq_plan().fo), routed experts only, so a prompt chunk below the long-prompt 417// floor does not run each routed expert on the dequantize + FP16 GEMM path (staged_fo_rule.hpp). STRATA_PF_STAGED_FO=1 asks for it on any card (research), 0 turns it off; unset: in a build without MMQ on every class for the layers the fused kernels cover; in a build with MMQ on where it was 418// measured (Windows gfx1151 with a layer set that is fused-only on every layer, and the entry's own prerequisites: the staged walk's resident-group gather and its group entry). Decided once when 419// the expert layout is known (a call before that answers from the variable alone and is not cached). 420inline bool staged_fo_on () { 421static std::atomic < int > cached {-1 }; 422const int c = cached .load (std::memory_order_acquire ); 423if (c >=0 )return c == 1 ; 424const char * env = std::getenv ("STRATA_PF_STAGED_FO" ); 425const auto & lay = strata::kernels::cpu::expert_layout (); 426if (!lay .native || lay .fmt .empty ())return strata::prefill::staged_fo_switch (env ); 427const bool cls = stream_floor_class_measured (); 428#if defined(STRATA_PF_OWN_ONLY ) 429constexpr bool own_only = true;// a build without MMQ: the fused staged entry on every class, for every layer the fused kernels cover (staged_fo_rule.hpp) 430#else 431constexpr bool own_only = false; 432#endif 433const bool v = strata::prefill::staged_fo_decide (env , strata::prefill::staged_fo_class_default (own_only ,cls && layers_all_fused_only (),staged_group_gather ()&& staged_group_entry_on ())); 434cached .store (v ?1 :0 , std::memory_order_release ); 435return v ; 436} 437// A layer on which the CPU share took experts (rows_cpu > 0) in a build without MMQ keeps the staged fused entry and the int8 kernels for the GPU's own experts: their rows, bounds and scratch come 438// from `order` / `off`, the CPU's rows are the last block of Dm and the GPU never writes them (share_own_rule.hpp). A build with MMQ keeps the old rule (MMQ's groups take the layer). 439// STRATA_PF_SHARE_OWN=0 is the old rule everywhere, =1 the new one in a build with MMQ too (research). 440inline bool share_keeps_own_kernels (int64_t rows_cpu ) { 441static const char * const env = std::getenv ("STRATA_PF_SHARE_OWN" ); 442#if defined(STRATA_PF_OWN_ONLY ) 443constexpr bool own_only = true; 444#else 445constexpr bool own_only = false; 446#endif 447return strata::prefill::share_layer_keeps_own_kernels (own_only ,env ,rows_cpu ); 448} 449// STRATA_SWITCH_POINT (CUDA builds only): the floor of a card that streams part of the experts comes from switch_point_rule.hpp's cost estimate. ON BY DEFAULT for the class 450// in_default_class() names (NVIDIA discrete card on PCIe, one GPU, link probe ran, compute capability 8.6); STRATA_SWITCH_POINT=0 is the way back, =1 asks for it on any other CUDA card. 451// The card's counts arrive from Prefill::set_card_expert_share (the cache's slots and layers x experts, known before the first lend); until then the default answers. 452std::atomic < int64_t > g_sp_resident {-1 },g_sp_total {0 }; 453double g_sp_blob_mb = 0.0 ,g_sp_link_gbps = 0.0 ;// the cache's mean blob (MB) and the start-up probe (GB/s), from Prefill::set_card_expert_share 454int g_sp_sm = 0 ;// the card's multiprocessor count 455int g_sp_cc_major = 0 ,g_sp_cc_minor = 0 ;// the card's compute capability 456bool g_sp_integrated = true;// not known as discrete until the card answered 457// STRATA_SWITCH_POINT as set: -1 unset, 1 for "1", 0 for any other value (the way back) 458inline int switch_point_env () { 459static const int e = [] { 460const char * v = std::getenv ("STRATA_SWITCH_POINT" ); 461return v != nullptr && v [0 ]!= '\0' ? strata::prefill::switch_point::env_state (v ) :-1 ; 462 }(); 463return e ; 464} 465// the card's counts have arrived (set_card_expert_share ran: a single card, no batch slots) 466inline bool switch_point_known () {return g_sp_resident .load (std::memory_order_acquire ) >=0 ; } 467inline bool switch_point_on () { 468#if defined(STRATA_USE_HIP )|| defined(__HIPCC__ )|| defined(STRATA_HIP_GFX906 ) 469return false;// measured on CUDA only 470#else 471if (!switch_point_known ())return false; 472 strata::prefill::switch_point::DeviceClass d ; 473d .cuda = true; 474d .discrete = !g_sp_integrated ; 475d .single_gpu = true;// set_card_expert_share is called from the single-card, no-batch paths only 476d .link_probed = g_sp_link_gbps > 0.0 ; 477d .cc_major = g_sp_cc_major ;d .cc_minor = g_sp_cc_minor ; 478return strata::prefill::switch_point::enabled (d ,switch_point_env ()); 479#endif 480} 481// the card as the rule scales it; a field not set gives card_known() == false and the default floor 482inline strata::prefill::switch_point::Card sp_card () { 483 strata::prefill::switch_point::Card c ; 484c .blob_mb = g_sp_blob_mb ;c .link_gbps = g_sp_link_gbps ;c .sm = g_sp_sm ; 485return c ; 486} 487// A build without MMQ (STRATA_PF_OWN_ONLY) loading a pack that is not a native one (the AVX-512 Q2_0 pack) whose layers the plan marks fused (mmq_plan(): `!lay.native && fused::enabled()`). 488// The staged fused entry (fz_staged) and the int8 kernels (i8_l) read the native layout only, so below the floor each routed expert of such a layer runs on the dequantize + FP16 path. 489// False without a loaded layout (the caller does not cache then) and in a build with MMQ. 490inline bool plain_pack_all_fused () { 491#if defined(STRATA_PF_OWN_ONLY ) 492const auto & lay = strata::kernels::cpu::expert_layout (); 493if (lay .native || lay .n_layers <=0 )return false; 494if (const char * e = std::getenv ("STRATA_PREFILL_MMQ" );e != nullptr && std::atoi (e )== 0 )return false;// mmq_plan(): no plan, no fused layers 495return fused::built ()&& fused::enabled (); 496#else 497return false; 498#endif 499} 500// A build without MMQ (STRATA_PF_OWN_ONLY) on a gfx12 card (R9700, RX 9070 / 9060) loading a native pack whose every layer is a trellis pair (Gyro-S TQK6 / TQK7 and the other trellis types) that the fused kernels 501// take (layers_all_fused_only(): no layer on MMQ or on the FP16 path). Below the floor the staged fused entry reads these layers about twice as slowly as MMQ did (R9700, Gyro-S, 128 to 1,000 tokens: 542 to 1,241 ms 502// against 252 to 659 ms), the streamed walk is faster than MMQ at every size (167 to 415 ms). False in a build with MMQ, on every other card, and without a loaded layout. 503inline bool trellis_gfx12_all_fused () { 504#if defined(STRATA_PF_OWN_ONLY )&& defined(STRATA_USE_HIP ) 505const auto & lay = strata::kernels::cpu::expert_layout (); 506if (!lay .native || lay .fmt .empty ())return false; 507for (const auto & f :lay .fmt ) 508if (f .gu_type < (int ) strata::quant::Type ::TQ2_T || f .gu_type > (int ) strata::quant::Type ::TQP7 )return false;// not a trellis gate/up 509int dev = 0 ; 510cudaDeviceProp prop ; 511if (cudaGetDevice (& dev )!= cudaSuccess || cudaGetDeviceProperties (& prop ,dev )!= cudaSuccess ) { 512 (void )cudaGetLastError (); 513return false; 514 } 515return strata::kernels::gfx_arch_is_gfx12_wmma (prop .gcnArchName )&& layers_all_fused_only (); 516#else 517return false; 518#endif 519} 520// The same layer set on a CUDA card (a build without MMQ, STRATA_PF_OWN_ONLY, not HIP): a native pack whose every layer is a trellis pair (Gyro-S TQK6 / TQK7) that the fused kernels take (layers_all_fused_only()). 521// No card query here: on CUDA fused::native_supported takes the trellis pair only where the kernels are set up (the sm_86 class, compute capability 8.0 / 8.6 / 8.9, with 80 or more SMs by default; any 522// sm_80+ card with STRATA_PF_FUSED_TQ=1; none with STRATA_PF_FUSED=0 or _TQ=0), so the floor is lowered exactly where those kernels run. False in a build with MMQ, on HIP, and without a loaded layout. 523inline bool trellis_cuda_all_fused () { 524#if defined(STRATA_PF_OWN_ONLY )&& !defined(STRATA_USE_HIP ) 525const auto & lay = strata::kernels::cpu::expert_layout (); 526if (!lay .native || lay .fmt .empty ())return false; 527for (const auto & f :lay .fmt ) 528if (f .gu_type < (int ) strata::quant::Type ::TQ2_T || f .gu_type > (int ) strata::quant::Type ::TQP7 )return false;// not a trellis gate/up 529return layers_all_fused_only (); 530#else 531return false; 532#endif 533} 534// The gfx12 set on Windows gfx1151 (one card, stream_floor_class_measured()): a build without MMQ (STRATA_PF_OWN_ONLY) loading a native pack whose every layer is a trellis pair that the fused kernels 535// take (layers_all_fused_only()). On gfx1151 the fused kernels take the trellis pair only where fused_tq_hip.hpp device_on says so (STRATA_PF_TQ_G1151), so with the switch off this is false. Below the 536// 1,024 floor the staged fused entry does not take Gyro-S's Hadamard-folded layers and every chunk ran on the FP16 path (256 tokens 1,914 ms against 726 ms in 0.2.13): the floor goes to 64 537// (stream_floor_rule.hpp) and --short-read keeps 64 (staged_fo_rule.hpp). False in a build with MMQ, on Linux, on every other card, and without a loaded layout. 538inline bool trellis_g1151_all_fused () { 539#if defined(STRATA_PF_OWN_ONLY )&& defined(STRATA_USE_HIP )&& defined(_WIN32 ) 540const auto & lay = strata::kernels::cpu::expert_layout (); 541if (!lay .native || lay .fmt .empty ())return false; 542for (const auto & f :lay .fmt ) 543if (f .gu_type < (int ) strata::quant::Type ::TQ2_T || f .gu_type > (int ) strata::quant::Type ::TQP7 )return false;// not a trellis gate/up 544return stream_floor_class_measured ()&& layers_all_fused_only (); 545#else 546return false; 547#endif 548} 549// a layer of the loaded native pack is Hadamard-folded (its gate/up or its down): the staged fused entry (fz_staged) does not take such a layer 550inline bool layers_any_folded () { 551const auto & lay = strata::kernels::cpu::expert_layout (); 552if (!lay .native )return false; 553for (const auto & f :lay .fmt ) 554if (f .had_gu || f .had_d )return true; 555return false; 556} 557#if defined(STRATA_PF_OWN_ONLY ) 558// The two start-up lines of a build without MMQ that name the long-prompt floor ("prompt pieces of N tokens or more read on the fused kernels ..." when the pack's own floor is 559// cached, and "prompt kernels: chunks of N tokens or more ..." when the plan is made) are printed once arm_cpu_share has run (own_only_line.hpp OwnOnlyLineDeferred), with 560// the floor stream_all_min() returns then: both moments come before the CPU share is armed and before the card has answered, and printed there they named 64 while the engine 561// ran at the share's 3,072 or the plain pack's 1,536. own_only_line_flush() is defined after stream_all_min(). 562std::mutex g_own_line_mu ; 563strata::prefill::OwnOnlyLineDeferred g_own_line ; 564inline void own_only_line_flush (); 565#endif 566// The floor without STRATA_PREFILL_STREAM_MIN and the CPU share: stream_floor_rule.hpp's answer, decided once when the expert layout is known (a call before that gets the default and is not cached). 567inline int64_t default_stream_floor () { 568static std::atomic < int64_t > cached {-1 }; 569const int64_t c = cached .load (std::memory_order_acquire ); 570if (c >=0 )return c ; 571const auto & lay = strata::kernels::cpu::expert_layout (); 572const bool plain = plain_pack_all_fused ();// a build without MMQ and a non-native pack on the fused kernels: no staged entry or int8 path exists for its layout (stream_floor_rule.hpp) 573if ((!lay .native || lay .fmt .empty ())&& !plain )return strata::prefill::kStreamFloorDefault ; 574const bool cls = !plain && stream_floor_class_measured (); 575int64_t v = strata::prefill::stream_floor_default (cls ,cls && layers_all_fused_only (),staged_fo_on (),plain ,trellis_gfx12_all_fused (),trellis_cuda_all_fused (), !plain && trellis_g1151_all_fused ()); 576#if !defined(STRATA_USE_HIP )&& !defined(__HIPCC__ )&& !defined(STRATA_HIP_GFX906 ) 577// the card's counts are not known yet (set_card_expert_share has not run) and the rule is not switched off: the default, not cached 578if (v == strata::prefill::kStreamFloorDefault && switch_point_env ()!= 0 && !switch_point_known ())return v ; 579#endif 580if (v == strata::prefill::kStreamFloorDefault && switch_point_on ()) { 581const int64_t res = g_sp_resident .load (std::memory_order_acquire ),tot = g_sp_total .load (std::memory_order_acquire ); 582const auto card = sp_card (); 583if (!strata::prefill::switch_point::card_known (card ))return v ;// the link or the card is not known: the default, not cached 584v = strata::prefill::switch_point::floor_for_card (res ,tot ,card ); 585if (v != strata::prefill::kStreamFloorDefault ) 586 std::fprintf (stderr ,"prefill: prompt chunks of %lld tokens or more stream every expert the card does not hold (%lld of %lld experts resident; %.2f MB experts, %.1f GB/s link, %d SMs); a shorter chunk stages only the routed ones. STRATA_SWITCH_POINT=0 keeps the fixed 1,024.\n" , 587 (long long )v , (long long )res , (long long )tot ,card .blob_mb ,card .link_gbps ,card .sm ); 588cached .store (v , std::memory_order_release ); 589return v ; 590 } 591cached .store (v , std::memory_order_release ); 592#if defined(STRATA_PF_OWN_ONLY ) 593if (v != strata::prefill::kStreamFloorDefault ) {// printed with the floor in force once the share is armed (own_only_line_flush) 594 { 595 std::lock_guard < std::mutex > lk (g_own_line_mu ); 596g_own_line .want_pieces (plain ); 597 } 598own_only_line_flush (); 599 } 600#else 601if (v != strata::prefill::kStreamFloorDefault ) 602 std::fprintf (stderr ,"prefill: prompt pieces of %lld tokens or more read on the fused kernels, as long prompts do. STRATA_PREFILL_STREAM_MIN=1024 keeps the old rule.\n" , (long long )v ); 603#endif 604return v ; 605} 606// The plain pack in a build without MMQ on a DISCRETE CUDA card takes strata::prefill::kPlainDiscreteFloor, with or without the CPU share (plain_floor_rule.hpp: the share's limit would replace the 607// floor although it takes nothing of that pack, and the plain pack's own 64 was measured on an integrated GPU). The card must have answered (set_card_expert_share ran: one card, no batch slots) and 608// the expert layout be loaded; before that the old rule answers and nothing is cached. Integrated cards, HIP builds and a build with MMQ never take it. STRATA_PF_PLAIN_FLOOR=0 is the way back. 609inline bool plain_discrete_floor_now () { 610#if defined(STRATA_PF_OWN_ONLY )&& !defined(STRATA_USE_HIP )&& !defined(__HIPCC__ )&& !defined(STRATA_HIP_GFX906 ) 611static std::atomic < int > cached {-1 }; 612const int c = cached .load (std::memory_order_acquire ); 613if (c >=0 )return c == 1 ; 614if (strata::kernels::cpu::expert_layout ().n_layers <=0 || !switch_point_known ())return false; 615const bool v = strata::prefill::plain_takes_discrete_floor (plain_pack_all_fused (), !g_sp_integrated , std::getenv ("STRATA_PF_PLAIN_FLOOR" )); 616cached .store (v ?1 :0 , std::memory_order_release ); 617return v ; 618#else 619return false; 620#endif 621} 622inline int64_t stream_all_min () { 623static const int64_t env = [] {const char * e = std::getenv ("STRATA_PREFILL_STREAM_MIN" );return e ? (int64_t ) std::atoll (e ) : (int64_t )-1 ; }(); 624if (env >=0 )return env ; 625#if defined(STRATA_PF_OWN_ONLY ) 626const bool discrete = plain_discrete_floor_now (); 627// (default_stream_floor() prints its line once and caches: only asked when its answer can be the result, as before) 628return strata::prefill::floor_with_share (discrete ,g_stream_min_share ,discrete || g_stream_min_share <=0 ?default_stream_floor () :0 ); 629#else 630// a build with MMQ keeps the old text of this function (its compiled code stays the same) 631return g_stream_min_share > 0 ?g_stream_min_share :default_stream_floor (); 632#endif 633} 634#if defined(STRATA_PF_OWN_ONLY ) 635inline void own_only_line_flush () { 636 { 637 std::lock_guard < std::mutex > lk (g_own_line_mu ); 638if (!g_own_line .due ()&& !g_own_line .pieces_due ())return ; 639 } 640const int64_t floor_tokens = stream_all_min ();// outside the lock: a first call caches default_stream_floor(), which flushes itself (nothing is printed twice) 641 std::lock_guard < std::mutex > lk (g_own_line_mu ); 642if (g_own_line .pieces_due ()) std::fprintf (stderr ,"%s\n" ,g_own_line .take_pieces (floor_tokens ).c_str ()); 643if (g_own_line .due ()) std::fprintf (stderr ,"%s\n" ,g_own_line .take (floor_tokens ).c_str ()); 644} 645#endif 646// STRATA_PREFILL_CPU_SHARE (opt-in; set_cpu_pool): a chunk below stream_all_min() hands the decode CPU pool - idle 647// while a prompt is read - the non-resident experts few of its tokens route to, instead of streaming them over PCIe. 648// `auto`: the share measured, each layer's CPU time per expert and the GPU's per streamed expert (CUDA events around 649// its expert work, read after the next layer's routing sync - the host reaches the combine long before the GPU does) 650// as running means, and the next layers hand the CPU g / (c + g) of them, where both sides end together - so a small 651// CPU takes a small share - and only while the layers that share are measured cheaper than the ones that do not (the 652// gate at cpu_maybe). x: a fixed x. Unset or 0: every expert on the GPU (the default). RTX 5090 + 9950X3D, 653// 600-token prompts: UD-Q4_K_XL 1,528-1,548 -> 1,296-1,369 ms (share 0.65), Q2_0 472-491 -> 445-448, IQ2_XS 507 -> 490 654// (250 tokens 402 -> 368); IQ2_XS on 2 AVX2 workers 512 -> 487 (share 0.49). 655// 0.1.41: ON BY DEFAULT where it was measured (CUDA builds, one GPU, no batch slots): STRATA_PREFILL_CPU_SHARE unset 656// behaves as `auto` with STRATA_PREFILL_CPU_SHARE_MAX=1024 (chunks below 1024 tokens: -20..-35% at 512 and 1000 tokens 657// on an RTX 3060, a Tesla P100 and an RTX 5070, 8/8 pairs each; mean KL against the share off about 0.004). 658// STRATA_PREFILL_CPU_SHARE=0 turns it off: the output is then the 0.1.40.3 bytes. g_share_default is set by 659// Prefill::arm_cpu_share(.., true) from the paths that qualify; the layer split and batch slots stay off, and HIP except a single gfx12 card (AMD-Q, arm_cpu_share). 660bool g_share_default = false; 661// Prefill::fix_cpu_share (--draft-costs, repeatable output): a share learned once on this machine, used like a fixed 662// STRATA_PREFILL_CPU_SHARE while the variable is unset and the default share is armed: no measured time then changes 663// which experts the CPU takes (the balance's EMA and the per-layer gate are both skipped, as with the variable). 664double g_share_fixed = -1.0 ; 665inline double cpu_share_explicit () {// -2: the variable is not set; -1: measured 666static const double v = [] { 667const char * e = std::getenv ("STRATA_PREFILL_CPU_SHARE" ); 668if (e == nullptr )return -2.0 ; 669if (std::strcmp (e ,"auto" )== 0 )return -1.0 ; 670return std::clamp (std::atof (e ),0.0 ,1.0 ); 671 }(); 672return v ; 673} 674inline double cpu_share_env () {// -1: measured 675const double v = cpu_share_explicit (); 676return v == -2.0 ? (g_share_default ? (g_share_fixed >=0.0 ?g_share_fixed :-1.0 ) :0.0 ) :v ; 677} 678inline bool cpu_share_on () {return cpu_share_env ()!= 0.0 ; } 679// STRATA_PF_PEER_CPU=1 (opt-in): the share also runs beside a peer GPU (--peer-device), which it otherwise leaves off. It 680// takes only experts that neither card computes, and its rows go before the peer's block, so the peer's stays the tail 681// its combine reads from (back_at); the staged chunks then go up to cpu_share_max()'s 3072 tokens, not the default 682// share's 1024. Measured on an RTX 5060 Ti (PCIe 3.0 x8) + RTX 3060, IQ3_XXS, a 161-173K-token conversation, tool results 683// read one after another: 117-132 tokens 1.80-1.92 -> 1.16 s, 325-335 2.12-2.89 -> 1.36-1.63 s, 524 3.33 -> 1.99 s, 684// 1067 3.74 -> 2.64 s, 2012 4.33 -> 4.22 s, 3.2-3.5K unchanged (the whole chain 36.0 -> 29.7 s). 685inline bool pf_peer_cpu () { 686static const bool on = [] {const char * e = std::getenv ("STRATA_PF_PEER_CPU" );return e != nullptr && std::atoi (e )!= 0 ; }(); 687return on ; 688} 689// STRATA_PREFILL_CPU_SHARE_MAX (default 3072, at least 1024): with the share on, chunks below it are staged after their 690// routing - so they can hand the CPU its share - instead of streaming every expert the cards do not hold. The share pays 691// on chunks up to ~3K tokens, where few tokens route to many of the streamed experts; 1024 keeps the old limit. 692int64_t g_share_limit_arch = 0 ;// AMD-Q: the default limit of a gfx12 card (share_rules::gfx12_share_limit), set by arm_cpu_share 693inline int64_t cpu_share_max () { 694static const int64_t v = [] { 695const char * e = std::getenv ("STRATA_PREFILL_CPU_SHARE_MAX" ); 696return e ? std::max < int64_t > (kStreamAllMinDefault , (int64_t ) std::atoll (e )) : (int64_t )3072 ; 697 }(); 698static const bool explicit_max = std::getenv ("STRATA_PREFILL_CPU_SHARE_MAX" )!= nullptr ; 699// its measured range; STRATA_PF_PEER_CPU's is 3072 (see pf_peer_cpu) 700if (g_share_default && cpu_share_explicit ()== -2.0 && !explicit_max && !pf_peer_cpu ())// the default-armed share: share_rules::default_share_limit (STRATA_PREFILL_CPU_SHARE_MAX=1024 restores the old 1,024) 701return g_share_limit_arch > 0 ?g_share_limit_arch : strata::prefill::share_rules::default_share_limit (); 702return v ; 703} 704// On a layer split every stage may have the pool (set_cpu_pool), and the stages read different chunks at the same time: 705// one stage at a time takes it for a chunk, the other reads its chunk with the GPU alone. 706std::atomic < bool > g_cpu_pool_busy {false}; 707// STRATA_PREFILL_CPU_SHARE_BATCH: a slot is decoding beside this read (Prefill::set_share_blocked): the pool is its windows' 708std::atomic < bool > g_share_blocked {false}; 709double g_pinned_share = 1.0 ; 710// The streamed ring: 384 slots when (nearly) every streamed expert is DMA'd from pinned RAM - measured on Q2_0, 711// 8192-token chunks: 96 slots 1153 tok/s, 384 1294 (the next layer's experts arrive during its attention half) - 712// and 96 when a large share goes through host copies (IQ3_S on 64 GB, a third unpinned: 96 slots 1216, 256 1070 - 713// the host copies are the limit and the bigger ring only takes cache slots). STRATA_PREFILL_RING overrides. 714// 715// Those are slots on the pack they were measured on, and a slot is one WHOLE expert blob - a Q2_0 blob is 716// 1,382,400 B, so 384 slots is 506 MiB. On a pack with bigger blobs the same slot count is a different amount of 717// memory: 1,912 MiB on Q8_0 (5,222,400 B), which is more than half of an 8 GB card's expert cache and what held 718// that card at a 1,024-token chunk when its own buffers would have fitted 6,144. Measured on the 4-way rig, one 719// env var and nothing else: chunk 1,024 -> 6,144, prefill 87 -> 402 tok/s. So the budget is kept in BYTES and the 720// slot count is derived from the pack (`ring_budget_slots`); Q2_0 still resolves to exactly 1024 (fused) and 384, 721// so the pack all of this was tuned on does not move. 722int g_ring_override = 0 ;// #340: set by a layer split (Prefill::set_ring_override); 0 = the rule below 723// #583 (0.1.39b): the auto chunk scan's byte-budget ring (Prefill::set_ring_budget), for requests whose chunk is above 724// g_ring_small_max - the chunk 0.1.39's rule would have picked. A prompt that fits that chunk keeps 0.1.39's ring: 725// on one chunk the smaller ring only slowed it (RTX 5070, 4K prompts: Coder -15%, IQ3_S -5%, IQ3_XXS -2%). 726int g_ring_budget = 0 ; 727int64_t g_ring_small_max = 0 ; 728// #136: the fused experts (STRATA_PF_FUSED=1) launch on a batch of a layer's streamed experts at once, so the ring 729// should hold a whole layer's (~460 of 512 on Q2_0): with 384 slots a layer's last batch waits for slots its own 730// first batch frees. Measured on the 5070, Q2_0, the 4K / 32K code-agent prompts (one run each): fused at 384 slots 731// +5% / +3% over MMQ, at 512 +19-22% / +11-12% (MMQ itself at 512: -2% / -1%). P3: with the fused path's smaller 732// buffers (moe_bufs) 1024 slots - two layers' experts - fit too; 2 pairs each, prompt tok/s at 512 / 1024 slots: 4K 733// 1,512 / 1,605, 32K 2,485 / 2,660 (both chunk 8192), 128K with KV streaming 2,346 / 2,392 (the chunk falls from 734// 8192 to 6144, but more experts stay resident). A native pack likewise when the native kernels (moe_fused_iq.hpp) 735// take any of its layers: IQ2_XS, 4K / 32K, their first version at 384 slots -3% / -6% against MMQ, at 512 +8% / 0%. 736inline bool fused_ring () { 737if (const int ov = strata::prefill::pf_fused_override ().load (std::memory_order_relaxed );ov == 0 || ov == strata::prefill::kPfFusedKernelsOnly ) 738return false;// the small-card prompt path decided on MMQ's layout 739if (core::peer_portable ())return false;// multi-GPU: --peer-device keeps the MMQ path and its buffer sizes 740const strata::kernels::cpu::ExpertLayout & lay = strata::kernels::cpu::expert_layout (); 741// the Q2_0 pack: fused::enabled(). A native pack: native_supported() alone - it implies enabled() wherever the Q2_0 742// kernels exist, and on gfx12 (the native kernels only) enabled() is false while the native layers do run fused. 743if (!lay .native )return fused::enabled (); 744// EVERY layer: fused_layout() shrinks the MoE buffers to the fused path's needs, so a layer the native kernels do 745// not cover (Unsloth UD-IQ4_XS's Q8_0 down projections) would run MMQ in them at the full chunk and overflow them 746// (garbage, an illegal memory access or a hung prompt on gfx1151). A pack with such a layer keeps MMQ's buffers; 747// its covered layers still take the fused kernels. 748// PER DEVICE: native_supported() asks the CURRENT device (the SM count and compute capability of moe_fused_iq.cu's 749// dev_info()), so on a layer split over unlike cards the answer differs by stage: an 84-SM 5080 takes the fused 750// kernels at 12.0, a 70-SM 5070 Ti beside it does not. Cached as one global bool, the answer came from whichever 751// card happened to be current at the first call: on a split whose first stage was the 5080 the MoE buffers were 752// shrunk for every stage, and each 5070 Ti stage then failed every chunk >= stream_all_min() with "Prefill: the 753// fused layout's MoE buffers are too small for layer 25's expert path at a chunk of 8192 tokens" (measured 754// 2026-10-26, 2x 5080 + 2x 5070 Ti, --layer-split 12,25,37 - layer 25 opens the first 5070 Ti stage). Atomic 755// because the batch-slot threads read this too; a lost race recomputes the same per-device answer. 756static std::atomic < int8_t > per_dev [32 ];// 0 unknown, 1 every layer covered on this device, 2 not 757int dev = 0 ; 758if (cudaGetDevice (& dev )!= cudaSuccess || dev < 0 || dev >=32 ) { (void )cudaGetLastError ();dev = 0 ; } 759const int8_t known = per_dev [dev ].load (std::memory_order_relaxed ); 760if (known != 0 )return known == 1 ; 761bool all = !lay .fmt .empty (); 762for (const auto & f :lay .fmt ) 763if (!fused::native_supported (f .gu_type ,f .d_type )) {all = false;break ; } 764per_dev [dev ].store (all ?1 :2 , std::memory_order_relaxed ); 765return all ; 766} 767// the largest ring: 512 slots; 1024 with the Q2_0 pack's fused experts (P3's smaller buffers, measured there) - the 768// native packs' fused layers were measured at 512 769inline int ring_cap () {return fused_ring ()&& !strata::kernels::cpu::expert_layout ().native ?RING_MAX :512 ; } 770// The ring's budget in bytes: the measured slot counts above, at the blob size they were measured with. It is 771// bytes and not slots because a slot is one whole blob and the blob is the pack's - see the note above. 772inline constexpr uint64_t Q2_0_BLOB = 1382400ull ;// the blob of the pack the ring was tuned on 773inline uint64_t ring_bytes () { 774const uint64_t slots = fused_ring () ?1024ull :384ull ;// #136: a fused ring holds two layers' experts 775return (g_pinned_share >=0.9 ?slots :slots /4 )* Q2_0_BLOB ; 776} 777// ...and what that buys on THIS pack, never past ring_cap(): the slot count `init` lays out, and what the auto 778// chunk scan treats as a full ring. A pack whose blobs are larger than Q2_0's gets fewer slots for the same 779// bytes, which is the point - the ring competes with the expert cache for the same VRAM. 780// 0.1.39b: on by default (#583); STRATA_RING_BYTES=0 restores 0.1.39's ring, loan and auto chunk list. It moves the 781// prompt path's loan on a native pack (fewer ring slots, the rest kept as cache slots, a larger auto chunk), so a long 782// prompt's experts are read through a different mix of resident and streamed groups and its bits differ from 0.1.39's 783// (RTX 5070, IQ3_XXS, 32K prompt: +14% to +26%; teacher-forced against the FP16 prompt path in the same band). 784// #1454: `bo` shares `emb`'s storage (carve), which frees T * N floats per chunk. The planner keeps counting them by 785// default, so the auto chunk and the borrowed cache slots (and with them the prompt path's bits) are exactly 0.1.40.3's; 786// STRATA_EMB_REUSE_ACCOUNT=1 lets it use the saved bytes: a larger chunk or more borrowed slots where VRAM is the limit 787// (RTX 3060, IQ3_XXS: chunk 6400 -> 6656, prompt +3.9%), with other rounding in the prompt path. 788inline bool emb_reuse_account () { 789static const bool on = [] {const char * v = std::getenv ("STRATA_EMB_REUSE_ACCOUNT" );return v != nullptr && v [0 ]== '1' ; }(); 790return on ; 791} 792inline bool ring_bytes_on () { 793static const bool on = [] {const char * v = std::getenv ("STRATA_RING_BYTES" );return v == nullptr || v [0 ]!= '0' ; }(); 794return on ; 795} 796inline int ring_budget_slots () { 797const int64_t per = MAXBLOB (); 798const int64_t n = per > 0 ? (int64_t ) (ring_bytes () / (uint64_t )per ) :0 ; 799const int cap = ring_cap (); 800return (int ) (n <=0 ?0 : (n > cap ?cap :n )); 801} 802inline int ring_slots (size_t T ) { 803const char * v = std::getenv ("STRATA_PREFILL_RING" ); 804#if defined(STRATA_USE_HIP ) 805// S6: with the matrix-core attention (the gfx12 default since 148-amd; STRATA_HIP_WMMA=1 or auto elsewhere / forced, on a card that 806// has it) a 96-slot ring: measured with it, 9070 XT 4K prompts 718 -> 1,211 tok/s (16K 1,949 -> 2,032), R9700 4K 2,426 -> 2,483 (16K the same) 807static const bool wmma = strata::kernels::qsa_prompt_attn_matrix_cores_requested (); 808if (!v && g_ring_override <=0 && wmma ) { 809if ((int64_t )T < stream_all_min ())return STAGE ; 810// R9700 (gfx1201) 11-03, IQ3_S fused kernels and UD-Q4_K_XL MMQ: a layer's streamed experts want a deeper ring than 96 at chunks 811// up to 8K tokens (ring 256 / 192 / 96, 3 rounds x 2 reps interleaved, prompt tok/s: 4K +12.5% / +11.8% / base, 8K +2.4% / +4.4% / 812// base; UD-Q4 ring 192: 4K +6.9%, 8K +9.5%, 20K +4.0%), while at 16K chunks the extra loan only costs (32K prompt: 256 -0.4%, 813// 192 -1.3%). The ring is staging depth only; capped at ~800 MiB of blobs (UD-Q4's 3.99 MB blobs: 200 slots). 814// STRATA_PREFILL_RING=96 restores the old value; so does STRATA_GFX12_RING=0. 815// gfx12 only: the ring was measured on an R9700. The Strix Halo (gfx1151) also runs the matrix-core attention by default on Windows and keeps 96, as in 0.2.10 816// (STRATA_HIP_WMMA=1 on it made the branch above true, and this depth with it). 817static const bool deeper = [] { 818const char * e = std::getenv ("STRATA_GFX12_RING" ); 819return !(e != nullptr && e [0 ]== '0' )&& strata::kernels::qsa_prompt_attn_matrix_cores_gfx12 (); 820 }(); 821if (!deeper || (int64_t )T >=12288 )return 96 ; 822const int64_t per = MAXBLOB (); 823const int cap = per > 0 ? (int ) std::max < int64_t > (96 , (int64_t ) (800u <<20 ) /per ) :96 ; 824return std::min (cap , (int64_t )T <=6144 ?256 :192 ); 825 } 826#endif 827// the byte budget as this pack's slots: 1024 fused / 384 not on Q2_0, fewer on a pack with bigger blobs. The 828// unpinned arm stays a slot count (96): it was measured where the host copies are the limit, and there the ring 829// is not what is competing for VRAM. 830// 0.1.39's ring (1024 fused / 384 pinned, 96 when a large share goes through host copies), and the #583 byte 831// budget the auto scan chose for chunks past the size 0.1.39's rule would have picked (set_ring_budget) 832const int pinned_ring = g_pinned_share >=0.9 ? (fused_ring () ?1024 :384 ) :96 ; 833const bool budget = ring_bytes_on ()&& g_ring_budget > 0 && (int64_t )T > g_ring_small_max ; 834const int r = v ? std::atoi (v ) :g_ring_override > 0 ?g_ring_override :budget ?g_ring_budget :pinned_ring ; 835if (v && r == STAGE )return STAGE ;// Explicit opt-in to routed-only staging, including large chunks. 836const int big = r < 16 ?16 :r > ring_cap () ?ring_cap () :r ; 837return (int64_t )T >=stream_all_min () ?big :STAGE ; 838} 839// The staging buffers a layout holds: the ring, and at least STAGE_GRP for the staged walk's grouped gather. Counted 840// and taken through this one place, so the bytes the prompt path borrows cover every buffer it writes. 841inline int stage_slots (size_t T ) {return std::max (ring_slots (T ),STAGE_GRP ); } 842constexpr int DQ = 2 ;// dequantized-expert ring (FP16 gate/up + down) 843// The BF16-weight projections (hyper-connection, SSM alpha/beta, indexer, router, shared gate, PLE key/value) take 844// BF16 activations here and FP32 ones in decode. STRATA_PREFILL_BF16X2=1 adds each activation's BF16 remainder as a 845// second GEMM (Y = W.hi + W.lo, ~16 mantissa bits): a router that picks its top 10 from the same x decode would. 846// 2 = all but the hyper-connection's; 1 = the hyper-connection's too (its activations are 10240 wide and its up 847// projection writes as much: slower); 0 (the default: opt-in, it changes the prompt path's numbers) = off. 848// `f16_io`: the stage's FP16 prompt path (Prefill::init decides it once per stage, on the stage's own device): FP16 849// activations carry 11 mantissa bits, so the BF16 low part does not apply there. 850inline int bf16x2_mode (bool f16_io ) { 851static const int v = [] { 852const char * e = std::getenv ("STRATA_PREFILL_BF16X2" ); 853return e != nullptr ? std::atoi (e ) :0 ; 854 }(); 855return f16_io ?0 :v ; 856} 857inline bool bf16x2 (bool f16_io ) {return bf16x2_mode (f16_io )!= 0 ; } 858// STRATA_HANDOFF_PIPE=P (opt-in, 2..16; unset/0/1 = the one copy): a layer split hands a chunk's rows on in P row pieces. 859// The stage records an event when its chunk's work is done and one after each piece's copy into the pinned hand-off 860// buffer, waits on the host only for the first (what on_stage_chunk's checkpoint parts and the error check need), and 861// starts the next stage at once: that stage's upload of piece i waits on piece i's event on the GPU, so its uploads 862// overlap the remaining downloads (separate PCIe links; the 3090s here have no P2P) and the thread start is hidden 863// behind them. The same bytes land in the same rows before the next stage's first kernel: exact. No device memory; 864// the events and the existing two pinned buffers per stage only. 865static constexpr int kHandPiecesMax = 16 ; 866static int handoff_pipe_pieces () { 867static const int v = [] { 868const char * e = std::getenv ("STRATA_HANDOFF_PIPE" ); 869const int p = e ? std::atoi (e ) :0 ; 870return p >=2 ? std::min (p ,kHandPiecesMax ) :0 ; 871 }(); 872return v ; 873} 874// rows [r0, r0 + nr) of piece i of a T-row chunk in P pieces (the same split on both sides of a hand-off) 875static void handoff_piece (int64_t T ,int P ,int i ,int64_t & r0 ,int64_t & nr ) { 876const int64_t per = (T + P - 1 ) /P ; 877r0 = std::min < int64_t > (T , (int64_t )i * per ); 878nr = std::min < int64_t > (T ,r0 + per )- r0 ; 879} 880// STRATA_HANDOFF_PIPE: the next stage's chunks run on one thread of the stage's own, started once and pinned once 881// (std::async started a thread per chunk: ~1 ms from the hand-off to the next stage's first call, measured with nsys). 882// The futures are the same (run_impl's result, or what it threw), so the chain's waits do not change. 883// (STRATA_HANDOFF_PIPE_WORKER=0: a thread per chunk again, for an A/B of the two halves.) 884static bool handoff_pipe_worker () { 885static const bool v = [] {const char * e = std::getenv ("STRATA_HANDOFF_PIPE_WORKER" );return !e || std::atoi (e )!= 0 ; }(); 886return handoff_pipe_pieces ()> 0 && v ; 887} 888struct HandWorker { 889 std::mutex mu ; 890 std::condition_variable cv ; 891 std::deque < std::packaged_task < bool ()>> jobs ; 892bool stop = false; 893 std::thread th ; 894HandWorker () { 895th = std::thread ([this ] { 896 strata::platform::name_this_thread ("strata-hand" ); 897 strata::aux_cpus::pin_current_thread (); 898for (;;) { 899 std::packaged_task < bool ()> job ; 900 { 901 std::unique_lock < std::mutex > lk (mu ); 902cv .wait (lk , [this ] {return stop || !jobs .empty (); }); 903if (jobs .empty ())return ;// stopped, and every job taken has run (no broken promise) 904job = std::move (jobs .front ()); 905jobs .pop_front (); 906 } 907job (); 908 } 909 }); 910 } 911 std::future < bool > submit (std::packaged_task < bool ()> job ) { 912 std::future < bool > f = job .get_future (); 913 { 914 std::lock_guard < std::mutex > lk (mu ); 915jobs .push_back (std::move (job )); 916 } 917cv .notify_one (); 918return f ; 919 } 920 ~HandWorker () { 921 { 922 std::lock_guard < std::mutex > lk (mu ); 923stop = true; 924 } 925cv .notify_one (); 926if (th .joinable ())th .join (); 927 } 928}; 929 930// S23 (opt-in STRATA_HC_UPMIX=1): the hyper-connection read's up projection and gr_mix_r as one kernel (gr_upmix: gfx11, 931// and CUDA sm_80+ on chunks of 33+ tokens - there, with CUDA 13.3 on an RTX 5090, cuBLAS's up GEMM sums K in the fused 932// kernel's order and the read is the default pair's bits: gr_upmix_parity, STRATA_HC_UPMIX_CHECK); 933// STRATA_HC_UPMIX_CHECK=N also runs the default pair on the first N reads and reports the difference of `mixed` 934static int64_t pf_switch_min_t () {// S23: STRATA_PF_SWITCH_MIN_T=N - the rounding-level prompt switches only on chunks of 935// N or more tokens (shorter prompts keep the default numerics, and their outputs; the switches pay on long ones) 936static const int64_t v = [] {const char * e = std::getenv ("STRATA_PF_SWITCH_MIN_T" );return e ? (int64_t ) std::atoll (e ) : (int64_t )0 ; }(); 937return v ; 938} 939// STRATA_PF_DM16 (gfx11, the F16 fused expert kernels): the down rows go to the combine as FP16 instead of FP32 (half the bytes written and read) 940inline bool pf_dm16 () { 941static const bool on = [] {const char * e = std::getenv ("STRATA_PF_DM16" );return e != nullptr && e [0 ]== '1' ; }(); 942return on ; 943} 944inline bool hc_upmix () { 945static const bool v = [] {const char * e = std::getenv ("STRATA_HC_UPMIX" );return e != nullptr && e [0 ]== '1' ; }(); 946return v ; 947} 948// CUDA: the fused read only on chunks of 33+ tokens - below that cuBLAS's up GEMM takes another kernel, rounding-level 949// apart, so short chunks keep the default pair 950inline int64_t hc_upmix_min_t () { 951#if defined(__HIPCC__ ) 952return 0 ; 953#else 954return 33 ; 955#endif 956} 957inline bool bf16x2_hc (bool f16_io ) {return bf16x2_mode (f16_io )== 1 ; } 958// S23 (opt-in STRATA_CVEC_FUSE=1): a steered layer's FFN write + control vector + the next half's norm in one pass 959// over R (gr_write_cvec_norm_rs; bitwise the gr_write + cvec_apply + gr_norm_rs it replaces) 960// S23 (opt-in STRATA_PF_HCDOWN=1, on chunks of STRATA_PF_SWITCH_MIN_T+ tokens): the hyper-connection read's down and 961// inject projections as one WMMA GEMM over xn16 (strata_pf_hcdown_bf16), xn16 written with token stride 962// 10240 + 64. Rounding-level (another k order than hipBLASLt): quality-gated. 963inline bool pf_hcdown () { 964static const bool v = [] {const char * e = std::getenv ("STRATA_PF_HCDOWN" );return e && e [0 ]== '1' ; }(); 965return v ; 966} 967constexpr int64_t XN_PAD = 64 ; 968// S (opt-in STRATA_HCD_EXACT=1, on chunks of STRATA_PF_SWITCH_MIN_T+ tokens): the HC down projection by a WMMA kernel with 969// hipBLASLt's own k order (bitwise: strata_pf_hcdown_exact_bf16), xn16 written with token stride 10240 + 64 (the inject 970// projection stays on hipBLASLt, reading that stride) 971inline bool hcd_exact () { 972static const bool v = [] {const char * e = std::getenv ("STRATA_HCD_EXACT" );return e && e [0 ]== '1' ; }(); 973return v ; 974} 975inline bool hc_pad () {return pf_hcdown ()|| hcd_exact (); } 976// STRATA_QSA_FUSE_NR (default on, =0 runs rms_rows + rope [+ split_q] as separate kernels): the QSA layer's K, query and 977// indexer-query norm + rotary in one pass each (strata::prefill::rms_rope_rows; the same bits as the chain it replaces). 978// STRATA_QSA_FUSE_GATE (default on, =0 keeps the separate gate_attn pass): the attention output gate sigmoid(gate) * O in the 979// epilogue of the matrix-core prompt attention (qsa_prompt_attn_batch_gated; the same bits as gate_attn). Only where that 980// kernel runs and the output is not rotated back (kv_rot / hybrid K8V4 rotate it before the gate). 981inline bool qsa_fuse_gate () { 982static const bool v = [] {const char * e = std::getenv ("STRATA_QSA_FUSE_GATE" );return !(e != nullptr && e [0 ]== '0' ); }(); 983return v ; 984} 985inline bool qsa_fuse_nr () { 986static const bool v = [] {const char * e = std::getenv ("STRATA_QSA_FUSE_NR" );return !(e != nullptr && e [0 ]== '0' ); }(); 987return v ; 988} 989inline bool cvec_fuse () { 990static const bool v = [] {const char * e = std::getenv ("STRATA_CVEC_FUSE" );return e && e [0 ]== '1' ; }(); 991return v ; 992} 993// S23 (opt-in STRATA_PF_PAD=1 with STRATA_PF_GEMM=1): the FP16 activations of the two K 6144 projections (ssm_out's 994// y_h, attn_output's attn_h) with row stride 6144 + 64, so the GEMM's rows do not camp on the memory channels (the 995// 4 KB-multiple stride; Gemm::native pads the weight the same way). Same bits. 996inline bool pf_pad () { 997static const bool v = [] { 998const char * p = std::getenv ("STRATA_PF_PAD" );const char * g = std::getenv ("STRATA_PF_GEMM" ); 999if (!(p && p [0 ]== '1' && g && g [0 ]== '1' ))return false; 1000// The padded stride pays only for strata_pf_gemm_f16_ld, which is built for the gfx11 matrix cores. On another 1001// card nothing takes a padded X (it used to end the engine: "a padded X ... needs STRATA_PF_PAD's path", #1237): 1002// do not pad, and say so once. 1003if (!strata_pf_padded_gemm_available ()) { 1004 std::fprintf (stderr ,"prefill gemm: STRATA_PF_PAD needs the padded gfx11 product, which this card does not run; " 1005"not padding\n" ); 1006return false; 1007 } 1008return true; 1009 }(); 1010return v ; 1011} 1012constexpr int64_t ZV_PAD = 64 ; 1013 1014// F-1: STRATA_GR_UNFUSED=1 keeps the FP32 copy of the normalized rows (gr_norm + gr_mix), the A/B arm 1015inline bool gr_unfused () { 1016static const bool v = [] {const char * e = std::getenv ("STRATA_GR_UNFUSED" );return e && e [0 ]== '1' ; }(); 1017return v ; 1018} 1019 1020double ms_since (Clock ::time_point t ) {return std::chrono::duration < double , std::milli > (Clock ::now ()- t ).count (); } 1021 1022// STRATA_PF_ALLOC_TRACE=1 (diagnostic, no behaviour change; round 0216): the free-memory figure (cudaMemGetInfo) around the prompt path's 1023// allocations, against what the code asked for, to see what `bytes_needed` does not count (RESULTS-STRIX2.md). 1024inline bool pf_alloc_trace () { 1025static const bool on = [] {const char * e = std::getenv ("STRATA_PF_ALLOC_TRACE" );return e != nullptr && e [0 ]== '1' ; }(); 1026return on ; 1027} 1028inline int64_t pf_free_mib () { 1029size_t f = 0 ,t = 0 ; 1030cudaMemGetInfo (& f ,& t ); 1031return (int64_t ) (f >>20 ); 1032} 1033// one line: the free figure now, its drop since the last mark, and what the code itself asked for in between (MiB) 1034inline void pf_mark (const char * what ,int64_t & last ,uint64_t asked_bytes = 0 ) { 1035if (!pf_alloc_trace ())return ; 1036const int64_t now = pf_free_mib (); 1037 std::fprintf (stderr ,"prefill alloc trace: %-44s free %7lld MiB, dropped %7lld MiB, asked %7lld MiB\n" ,what , (long long )now , 1038 (long long ) (last - now ), (long long ) (asked_bytes >>20 )); 1039last = now ; 1040} 1041 1042// Either cudaMalloc (owned, freed with the object) or a bump allocation from a borrowed region; with no base and 1043// no region it only counts, which is how `bytes_needed` sizes the region. 1044struct Alloc { 1045uint64_t tr_asked = 0 ,tr_n = 0 ;///< STRATA_PF_ALLOC_TRACE: the cudaMalloc takes' sizes, and how far the free figure fell over them 1046int64_t tr_drop = 0 ; 1047uint8_t * base = nullptr ; 1048uint64_t cap = 0 ,used = 0 ; 1049uint64_t failed_bytes = 0 ;///< the take that could not be allocated; the failure message names it 1050uint64_t granule = 0 ;///< count_only: each take rounds up to this (cudaMalloc's 2 MiB pages: owned buffers) 1051bool count_only = false; 1052bool spill = false,spilled = false; 1053 std::vector < void *>* owned = nullptr ; 1054template < typename T > T * take (size_t n ,bool & ok ) { 1055uint64_t bytes = ((uint64_t )n * sizeof (T )+ 256 + 255 )& ~255ull ; 1056if (count_only ) { 1057if (granule > 0 )bytes = (bytes + granule - 1 ) /granule * granule ; 1058used += bytes ; 1059return nullptr ; 1060 } 1061if (base != nullptr && !spilled && used + bytes <=cap ) { 1062T * p = (T * ) (base + used ); 1063used += bytes ; 1064return p ; 1065 } 1066if (base != nullptr && !spill ) {ok = false;failed_bytes = bytes ;return nullptr ; } 1067void * p = nullptr ; 1068const int64_t tr0 = pf_alloc_trace () ?pf_free_mib () :0 ; 1069if (cudaMalloc (& p ,bytes )!= cudaSuccess ) {ok = false;failed_bytes = bytes ;return nullptr ; } 1070if (pf_alloc_trace ()) {tr_drop += tr0 - pf_free_mib ();tr_asked += bytes ;++ tr_n ; } 1071spilled = true; 1072owned -> push_back (p ); 1073used += bytes ; 1074return (T * )p ; 1075 } 1076}; 1077 1078}// namespace 1079 1080// Step 4 of the prompt-speed plan: the experts the arena could not pin (a third of the streamed ones on IQ3_S) are 1081// copied into pinned buffers by these threads, ahead of the launches. Copied in line by the launching thread they 1082// left the GPU without queued work while each ~2 MB memcpy ran (~15 s of a 32K prompt on IQ3_S). Job j - a layer's 1083// j-th unpinned expert, in launch order - lands in host buffer j % kRing, which is free again once the DMA of job 1084// j - kRing (recorded by the launching thread, `issued`) is done. 1085struct Stager { 1086// D-5: the pinned ring's depth (STRATA_STAGER_RING, default 16) - how far the host copies can run ahead of the 1087// DMAs of the unpinned experts' blobs 1088int kRing = 16 ; 1089bool sleep = stager_sleep ();// blocking waits (the layer-major pair always: they share the CPU with the host thread) 1090// pp-opt: the jobs a thread claims at once (STRATA_STAGER_BATCH; set by init's caller, at most kMaxBatch and kRing) 1091static constexpr int kMaxBatch = 32 ; 1092int batch = 1 ; 1093// `from` set: the blob is copied by the source itself (CS-T: a GGUF read in place assembles it from its three 1094// role slices; a pointer to it would not live as long as the queue) 1095struct Job {const uint8_t * src ;size_t bytes ; core::ExpertSource * from = nullptr ;int32_t l = 0 ,e = 0 ; }; 1096 std::vector < uint8_t *> buf ; 1097 std::vector < char > pinned ; 1098 std::vector < std::vector < uint8_t >> pageable ;// the fallback when no more RAM can be pinned 1099 std::vector < cudaEvent_t > dma_done ; 1100 std::vector < Job > jobs ; 1101 std::unique_ptr < std::atomic < int > []> ready ; 1102// layer-major prefill: a job the routing turned out not to need (`skip`) is not read once nobody has claimed it 1103 std::unique_ptr < std::atomic < char > []> skipped ; 1104size_t ready_cap = 0 ; 1105// gen << 32 | n << 16 | next index: a claim is a CAS on the generation it woke for (a thread late from the 1106// previous layer can never take a job of this one - the expert pool's issue #29 lesson) 1107 std::atomic < uint64_t > head {0 }; 1108 std::atomic < int > issued {0 },active {0 }; 1109uint32_t gen = 0 ; 1110bool quit = false; 1111 std::mutex mu ; 1112 std::condition_variable cv ; 1113 std::vector < std::thread > threads ; 1114int device = 0 ; 1115 1116bool init (size_t blob_bytes ,int nthreads ) { 1117if (const char * v = std::getenv ("STRATA_STAGER_RING" ))kRing = std::clamp (std::atoi (v ),2 ,256 ); 1118buf .assign ((size_t )kRing ,nullptr ); 1119pinned .assign ((size_t )kRing ,0 ); 1120dma_done .assign ((size_t )kRing ,nullptr ); 1121pageable .resize (kRing ); 1122for (int i = 0 ;i < kRing ;++ i ) { 1123pinned [i ]= !force_pageable ()&& cudaHostAlloc ((void ** )& buf [i ],blob_bytes ,cudaHostAllocDefault )== cudaSuccess ; 1124if (!pinned [i ]) { 1125cudaGetLastError (); 1126pageable [(size_t )i ].resize (blob_bytes ); 1127buf [i ]= pageable [(size_t )i ].data (); 1128 } 1129if (cudaEventCreateWithFlags (& dma_done [i ],sleep ? (cudaEventDisableTiming |cudaEventBlockingSync ) 1130 :cudaEventDisableTiming )!= cudaSuccess )return false; 1131 } 1132cudaGetDevice (& device ); 1133for (int t = 0 ;t < nthreads ;++ t ) 1134threads .emplace_back ([this ] { 1135// --aux-cpus: the copy threads go to the spare CPUs with the other helpers; STRATA_AUX_STAGER=0 leaves them where 1136// they were created (a small spare set would then hold all of them: it limits the copy rate of a long read) 1137 strata::platform::name_this_thread ("strata-stage" ); 1138static const bool keep = [] {const char * v = std::getenv ("STRATA_AUX_STAGER" );return v != nullptr && std::atoi (v )== 0 ; }(); 1139if (keep ) strata::aux_cpus::note_owned_thread (); 1140else strata::aux_cpus::pin_current_thread (); 1141work (); 1142 }); 1143return true; 1144 } 1145 ~Stager () { 1146finish (); 1147 { std::lock_guard < std::mutex > lk (mu );quit = true; } 1148cv .notify_all (); 1149for (auto & t :threads )t .join (); 1150for (int i = 0 ;i < kRing ;++ i ) { 1151if (dma_done [i ])cudaEventDestroy (dma_done [i ]); 1152if (buf [i ]&& pinned [i ])cudaFreeHost (buf [i ]); 1153 } 1154 } 1155void work () { 1156cudaSetDevice (device ); 1157uint32_t seen = 0 ; 1158for (;;) { 1159 { 1160 std::unique_lock < std::mutex > lk (mu ); 1161cv .wait (lk , [& ] {return quit || gen != seen ; }); 1162if (quit )return ; 1163seen = gen ; 1164 } 1165for (;;) { 1166active .fetch_add (1 , std::memory_order_acq_rel ); 1167// pp-opt: a run of up to `batch` consecutive jobs (batch <= kRing, so the earliest unfinished run 1168// never waits for a buffer of its own) 1169int k = 1 ; 1170const int j = claim (seen ,batch ,k ); 1171if (j < 0 ) {active .fetch_sub (1 , std::memory_order_acq_rel );break ; } 1172for (int i = j ;i < j + k ;++ i ) { 1173// The copies run ahead of the DMAs, so most of these threads spend most of a prompt waiting here: sleep 1174// (atomic wait, and a blocking-sync event below), not a yield spin - 32 spinners took every core 1175// (Linux; see stager_sleep for Windows). 1176if (i >=kRing ) {// job i - kRing's DMA from this buffer is queued 1177#if defined(STRATA_ATOMIC_WAIT ) 1178if (sleep ) 1179for (int x ; (x = issued .load (std::memory_order_acquire )) <=i - kRing ;)issued .wait (x ); 1180else 1181#endif 1182while (issued .load (std::memory_order_acquire ) <=i - kRing ) std::this_thread::yield (); 1183// ...and its own copy into the buffer is done: `issued` is a watermark, so a job nobody waits for 1184// (the layer-major prefetch reads experts the routing may skip) can be passed while its thread still 1185// writes the buffer this job is about to fill 1186while (!ready [(size_t ) (i - kRing )].load (std::memory_order_acquire )) std::this_thread::yield (); 1187 } 1188// and done - for a generation's first kRing jobs that is the previous generation's last DMA from 1189// the buffer, which nothing else waits for when a chunk ends without a sync (no MTP) or the DMA 1190// was a ring entry the routing skipped (an event never recorded returns at once) 1191cudaEventSynchronize (dma_done [i %kRing ]); 1192 } 1193int32_t rl [kMaxBatch ],re [kMaxBatch ]; 1194uint8_t * rd [kMaxBatch ]; 1195size_t nr = 0 ; 1196 core::ExpertSource * from = nullptr ; 1197for (int i = j ;i < j + k ;++ i ) { 1198if (skipped [(size_t )i ].load (std::memory_order_acquire ))continue ;// nothing will read it: no copy 1199const Job & jb = jobs [(size_t )i ]; 1200if (jb .from == nullptr ) { std::memcpy (buf [i %kRing ],jb .src ,jb .bytes );continue ; } 1201from = jb .from ; 1202rl [nr ]= jb .l ;re [nr ]= jb .e ;rd [nr ]= buf [i %kRing ];++ nr ; 1203 } 1204if (nr > 0 && !from -> copy_blobs (rl ,re ,rd ,nr )) { 1205 std::fprintf (stderr ,"prefill: the expert source could not copy experts %d.. of layer %d\n" ,re [0 ],rl [0 ]); 1206 std::abort (); 1207 } 1208for (int i = j ;i < j + k ;++ i )ready [(size_t )i ].store (1 , std::memory_order_release ); 1209active .fetch_sub (1 , std::memory_order_acq_rel ); 1210 } 1211 } 1212 } 1213int claim (uint32_t g ,int want ,int & k ) { 1214uint64_t cur = head .load (std::memory_order_acquire ); 1215for (;;) { 1216if ((uint32_t ) (cur >>32 )!= g )return -1 ; 1217const int n = (int ) ((cur >>16 )& 0xffff ),j = (int ) (cur & 0xffff ); 1218if (j >=n )return -1 ; 1219k = std::min (want ,n - j ); 1220if (head .compare_exchange_weak (cur ,cur + (uint64_t )k , std::memory_order_acq_rel , std::memory_order_acquire )) 1221return j ; 1222 } 1223 } 1224/// A layer's jobs; the previous layer's are finished (finish()). 1225void start (std::vector < Job >&& js ) { 1226if (js .empty ())return ; 1227 std::lock_guard < std::mutex > lk (mu ); 1228jobs = std::move (js ); 1229if (ready_cap < jobs .size ()) { 1230ready_cap = jobs .size ()* 2 ; 1231ready .reset (new std::atomic < int > [ready_cap ]); 1232skipped .reset (new std::atomic < char > [ready_cap ]); 1233 } 1234for (size_t i = 0 ;i < jobs .size ();++ i ) { 1235ready [i ].store (0 , std::memory_order_relaxed ); 1236skipped [i ].store (0 , std::memory_order_relaxed ); 1237 } 1238issued .store (0 ); 1239++ gen ; 1240head .store ((uint64_t )gen <<32 | (uint64_t )jobs .size () <<16 , std::memory_order_release ); 1241cv .notify_all (); 1242 } 1243/// Layer-major prefill: job j's bytes are not needed after all (the routing skipped the expert) - a thread that has not 1244/// started it yet marks it ready without reading. Never waited for, so its buffer's content does not matter. 1245void skip (int j ) {skipped [(size_t )j ].store (1 , std::memory_order_release ); } 1246/// Layer-major prefill, before wait(j): the launching thread stages its jobs in increasing order, so a job below j 1247/// it has not issued was skipped and never gets a DMA - the watermark moves to j. A skipped job is never issued, 1248/// so without this a routed job after about a ring's depth of skipped ones waits for `issued` forever. 1249void pass (int j ) { 1250if (issued .load (std::memory_order_relaxed )< j ) { 1251issued .store (j , std::memory_order_release ); 1252#if defined(STRATA_ATOMIC_WAIT ) 1253issued .notify_all (); 1254#endif 1255 } 1256 } 1257/// Job j's bytes, in a pinned buffer (waits for the copy). 1258const uint8_t * wait (int j ) { 1259while (!ready [(size_t )j ].load (std::memory_order_acquire )) std::this_thread::yield (); 1260return buf [j %kRing ]; 1261 } 1262/// The launching thread queued job j's DMA on `copy`: its buffer is free once that is done. 1263void issued_one (int j ,cudaStream_t copy ) { 1264cudaEventRecord (dma_done [j %kRing ],copy ); 1265issued .store (j + 1 , std::memory_order_release ); 1266#if defined(STRATA_ATOMIC_WAIT ) 1267issued .notify_all (); 1268#endif 1269 } 1270/// No job is running after this (the end of a layer, or an early return in the middle of one). 1271void finish () { 1272head .store ((uint64_t )gen <<32 , std::memory_order_release );// n = 0: nothing more to claim 1273issued .store (1 <<30 , std::memory_order_release ); 1274#if defined(STRATA_ATOMIC_WAIT ) 1275issued .notify_all (); 1276#endif 1277while (active .load (std::memory_order_acquire )!= 0 ) std::this_thread::yield (); 1278 } 1279}; 1280 1281// multi-GPU: the peer GPU's share of a prompt chunk's experts. Per MoE layer the primary copies its normed 1282// activations over P2P, the peer quantizes the rows routed to the experts it holds, runs the same MMQ products the 1283// primary would (gathered from its own slots), and copies the result rows back into the primary's Dm rows - the rows 1284// are laid out local-first, so the peer's are one contiguous block at the end. 1285struct PeerPrefill { 1286 core::PeerExperts * peer = nullptr ; 1287int dev = -1 ; 1288int64_t cap_rows = 0 ,T_max = 0 ; 1289cudaStream_t s = nullptr ; 1290cudaEvent_t ev_in = nullptr ;// on the primary: the activations and the row tables are ready 1291cudaEvent_t ev_done = nullptr ;// on the peer: its rows have landed in the primary's Dm 1292// multi-GPU: the result rows go back group by group on a second stream while the next group computes 1293cudaStream_t s_out = nullptr ; 1294static constexpr int kGrpEv = NE /16 + 2 ; 1295cudaEvent_t ev_grp [kGrpEv ]= {}; 1296bool out_pending = false;// s_out may still read Dm (the next layer's products wait for it) 1297bool out_pipe = true; 1298// multi-GPU COMPACT: the peer's per-row buffers hold one GROUP's rows instead of the layer's (a group 1299// = up to 16 experts and at most G rows), the result rows double-buffered: ~0.9 GB -> ~0.26 GB on the helper 1300// card at 8192-token chunks, and no row cap (every peer-held expert's rows go to the peer). 1301// STRATA_PF_PEER_COMPACT=0: the layer-sized buffers (the A/B). 1302bool compact = true; 1303int64_t G = 0 ; 1304void * Xq_g = nullptr ,* Hq_g = nullptr ; 1305float * GU_g = nullptr ,* H_g = nullptr ,* Dm_b [2 ]= {}; 1306cudaEvent_t ev_dm [2 ]= {}; 1307bool dm_live [2 ]= {}; 1308 std::vector < std::pair < size_t ,size_t >> groups ; 1309// multi-GPU PEER STREAMING: a share of the experts the primary would stream over ITS PCIe link in a 1310// big chunk is streamed by the peer over its own link instead (into its own ring) and computed there - it halves 1311// the primary's copy load and moves expert work to the card that idles through most of the MoE half. 1312// STRATA_PF_PEER_STREAM = the share (0 = off), STRATA_PF_PEER_RING = its ring slots. 1313double ps_frac = 0.0 ; 1314int RP = 0 ; 1315 std::vector < uint8_t *> pstage ; 1316 std::vector < cudaEvent_t > pcopied ,pused ; 1317 std::vector < char > plive ; 1318cudaStream_t s_cp = nullptr ; 1319struct PsEntry {int32_t l ,e ;const uint8_t * blob ; }; 1320 std::vector < PsEntry > pseq ;// this chunk's peer-streamed experts, layer by layer in id order 1321 std::vector < size_t > pseq_start ; 1322 std::vector < char > ps_flag ;// [layer * NE + e]: streamed by the peer in this chunk 1323size_t p_issued = 0 ,pk = 0 ; 1324int64_t ps_experts = 0 ; 1325float * mixed = nullptr ,* GU = nullptr ,* H = nullptr ,* Dm = nullptr ; 1326void * Xq = nullptr ,* Hq = nullptr ; 1327int32_t * src = nullptr ,* bounds = nullptr ,* ident = nullptr ; 1328uint8_t * grp_gu = nullptr ,* grp_d = nullptr ; 1329 std::unique_ptr < mmq::Context > ctx ; 1330 mmq::Context * run_ctx = nullptr ;// the context its products run in: ctx, or a layer split helper stage's 1331// Without P2P (a layer split's helper) the activations and the result rows go through MAPPED pinned host buffers: the device that needs them reads them with a copy kernel. A copy-engine 1332// upload would queue behind the expert blobs that device's streams already hold (up to a ring of them, ~70 us 1333// each - the grouping tables' reason for mapped memory too), and cudaMemcpyPeerAsync would be staged by the 1334// driver. `back_at` / `back_rows`: the rows this layer sends back. 1335bool p2p = true; 1336// The row table and the group bounds go the same way: the primary's are pinned for its own device only (or 1337// pageable), and a copy from them on the peer's stream would hold up the host until that stream is idle. 1338float * host_x = nullptr ;// T x N activations (mapped, portable) 1339float * host_rows = nullptr ;// the peer's result rows (mapped, portable) 1340int32_t * host_src = nullptr ;// the peer's rows' tokens (mapped, portable) 1341int32_t * host_bounds = nullptr ;// its group bounds (mapped, portable) 1342size_t host_x_cap = 0 ,host_rows_cap = 0 ,host_src_cap = 0 ;// elements 1343static constexpr size_t kHostBounds = 2 * (NE + NE /16 + 2 )+ 64 ; 1344int64_t back_at = 0 ,back_rows = 0 ; 1345// SUMS (the host route's default, STRATA_PF_PEER_SUMS=0: rows): the peer adds its rows into one weighted sum per 1346// token (`sum`, from the routing weights `wk` and each row's routed pair `pair`) and sends that back (`host_sum`, 1347// T x N) instead of its rows (rows_peer x N, up to K times more over the primary's link); the primary's combine 1348// adds it to its own experts' rows (eddoursul/Strata's second-GPU prompt path, f8de703). 1349bool sums = false; 1350cudaStream_t x_stream = nullptr ;// primary: the host route's copies beside its compute stream 1351cudaEvent_t ev_x = nullptr ; 1352bool f16 = false;// the sums mode's transfers in FP16 (STRATA_PF_PEER_F16=0: FP32) 1353// the sums in one launch per group (STRATA_PF_PEER_GATHER=0: per expert): per group [tokens | starts | rows] at 1354// adds_at[g], built on the host from the rows' pairs, uploaded once per layer 1355bool gather = false; 1356int32_t * adds = nullptr ,* host_adds = nullptr ; 1357size_t adds_cap = 0 ; 1358 std::vector < size_t > adds_at ; 1359 std::vector < int32_t > ntok ,tcur ,touched ; 1360uint16_t * sum16 = nullptr ,* host_x16 = nullptr ,* host_sum16 = nullptr ; 1361float * sum = nullptr ,* wk = nullptr ; 1362int32_t * pair = nullptr ; 1363float * host_w = nullptr ,* host_sum = nullptr ; 1364int32_t * host_pair = nullptr ; 1365 std::vector < int32_t > bounds_host ; 1366 core::PinnedRing up_ring ;// #1996: this device's pageable uploads (bounds, routed rows) go up from pinned slots 1367// APR (prism.hadamard): per layer, this device's copy of the down projection's sign vector (nullptr: identity or 1368// not folded). The gate/up input arrives already rotated (the primary sends its rotated copy, m.Xr). 1369 std::vector < const float *> had_sh ; 1370 std::vector < void *> owned ; 1371int64_t layers = 0 ,experts = 0 ,rows = 0 ,over_cap = 0 ;// stats 1372 ~PeerPrefill () { 1373if (dev < 0 )return ; 1374int prev = 0 ; 1375cudaGetDevice (& prev ); 1376cudaSetDevice (dev ); 1377if (s )cudaStreamSynchronize (s ); 1378ctx .reset (); 1379up_ring .release (); 1380for (void * p :owned )cudaFree (p ); 1381if (ev_done )cudaEventDestroy (ev_done ); 1382if (s_out )cudaStreamSynchronize (s_out ); 1383for (cudaEvent_t e :ev_grp )if (e )cudaEventDestroy (e ); 1384for (cudaEvent_t e :ev_dm )if (e )cudaEventDestroy (e ); 1385if (s_cp )cudaStreamSynchronize (s_cp ); 1386for (cudaEvent_t e :pcopied )if (e )cudaEventDestroy (e ); 1387for (cudaEvent_t e :pused )if (e )cudaEventDestroy (e ); 1388if (s_cp )cudaStreamDestroy (s_cp ); 1389if (s_out )cudaStreamDestroy (s_out ); 1390if (s )cudaStreamDestroy (s ); 1391cudaSetDevice (prev ); 1392if (ev_in )cudaEventDestroy (ev_in ); 1393if (x_stream ) {cudaStreamSynchronize (x_stream );cudaStreamDestroy (x_stream ); } 1394if (ev_x )cudaEventDestroy (ev_x ); 1395if (host_x )cudaFreeHost (host_x ); 1396if (host_rows )cudaFreeHost (host_rows ); 1397if (host_src )cudaFreeHost (host_src ); 1398if (host_bounds )cudaFreeHost (host_bounds ); 1399if (host_w )cudaFreeHost (host_w ); 1400if (host_sum )cudaFreeHost (host_sum ); 1401if (host_pair )cudaFreeHost (host_pair ); 1402if (host_x16 )cudaFreeHost (host_x16 ); 1403if (host_sum16 )cudaFreeHost (host_sum16 ); 1404if (host_adds )cudaFreeHost (host_adds ); 1405 } 1406}; 1407 1408// #1712: a chunk's small int32 tables (the QSA step records, the token ids) go up from a pinned buffer. A cudaMemcpyAsync 1409// from pageable memory is staged by the runtime; on gfx1100 the first text prompt after a picture one was seen to read stale 1410// step records that way. The event holds the next upload back until the last one has left the buffer. No pinned RAM: 1411// the copy is made from the caller's memory, as before. 1412struct PinnedUpload { 1413int32_t * p = nullptr ; 1414size_t n = 0 ; 1415cudaEvent_t ev = nullptr ; 1416void init (size_t count ) { 1417if (p || force_pageable ())return ; 1418if (cudaHostAlloc ((void ** )& p ,count * sizeof (int32_t ),cudaHostAllocDefault )!= cudaSuccess ) { 1419cudaGetLastError (); 1420p = nullptr ; 1421return ; 1422 } 1423n = count ; 1424if (cudaEventCreateWithFlags (& ev ,cudaEventDisableTiming )!= cudaSuccess ) { 1425cudaGetLastError (); 1426cudaFreeHost (p ); 1427p = nullptr ; 1428n = 0 ; 1429ev = nullptr ; 1430 } 1431 } 1432bool upload (void * dst ,const int32_t * src ,size_t count ,cudaStream_t s ) { 1433const size_t bytes = count * sizeof (int32_t ); 1434if (!p || count > n )return cudaMemcpyAsync (dst ,src ,bytes ,cudaMemcpyHostToDevice ,s )== cudaSuccess ; 1435if (cudaEventSynchronize (ev )!= cudaSuccess )return false;// the previous upload is out of the buffer 1436 std::memcpy (p ,src ,bytes ); 1437return cudaMemcpyAsync (dst ,p ,bytes ,cudaMemcpyHostToDevice ,s )== cudaSuccess && cudaEventRecord (ev ,s )== cudaSuccess ; 1438 } 1439void release () { 1440if (ev )cudaEventDestroy (ev ); 1441if (p )cudaFreeHost (p ); 1442p = nullptr ; 1443ev = nullptr ; 1444n = 0 ; 1445 } 1446}; 1447 1448// STRATA_PREFILL_WARM=1: chunks below stream_all_min() take the per-layer walk, where each layer's file-tier 1449// experts are page faults of the stager's few threads (128 KiB of read-ahead each). This thread hands the source a 1450// layer's whole list at once (madvise(WILLNEED) - the drive sees one deep queue), and the next layer's list from 1451// the previous chunk while this layer computes. Only warms pages: what the stager copies is unchanged. 1452struct PrefillWarmer { 1453 core::ExpertSource * src = nullptr ; 1454struct Job {int64_t layer ; std::vector < int64_t > experts ; }; 1455 std::vector < Job > queue ; 1456bool quit = false; 1457 std::mutex mu ; 1458 std::condition_variable cv ; 1459 std::thread thread ; 1460 std::atomic < int64_t > warmed {0 },dropped {0 }; 1461 1462explicit PrefillWarmer (core::ExpertSource * s ) :src (s ) { 1463thread = std::thread ([this ] { 1464 strata::aux_cpus::pin_current_thread (); 1465for (;;) { 1466Job j ; 1467 { 1468 std::unique_lock < std::mutex > lk (mu ); 1469cv .wait (lk , [& ] {return quit || !queue .empty (); }); 1470if (quit )return ; 1471j = std::move (queue .front ()); 1472queue .erase (queue .begin ()); 1473 } 1474src -> warm (j .layer ,j .experts .data (), (int64_t )j .experts .size ()); 1475warmed .fetch_add ((int64_t )j .experts .size (), std::memory_order_relaxed ); 1476 } 1477 }); 1478 } 1479 ~PrefillWarmer () { 1480 { 1481 std::lock_guard < std::mutex > lk (mu ); 1482quit = true; 1483 } 1484cv .notify_all (); 1485if (thread .joinable ())thread .join (); 1486 } 1487void submit (int64_t layer , std::vector < int64_t > experts ) { 1488if (experts .empty ())return ; 1489 { 1490 std::lock_guard < std::mutex > lk (mu ); 1491while (queue .size () >=4 ) {// behind: the oldest layer is done or nearly so 1492dropped .fetch_add ((int64_t )queue .front ().experts .size (), std::memory_order_relaxed ); 1493queue .erase (queue .begin ()); 1494 } 1495queue .push_back ({layer , std::move (experts )}); 1496 } 1497cv .notify_one (); 1498 } 1499}; 1500 1501struct Prefill ::Impl { 1502const core::WeightTable * wt = nullptr ; 1503const core::ModelGeometry * g = nullptr ; 1504 core::SessionState * ss = nullptr ; 1505 core::ExpertSource * src = nullptr ; 1506const core::ExpertCache * cache = nullptr ; 1507const int32_t * host_res = nullptr ; 1508int64_t T = 0 ,T_max = 0 ; 1509bool borrowed = false,borrow_spill = false; 1510cudaStream_t cs = nullptr ,copy = nullptr ; 1511Gemm gemm ; 1512 std::vector < void *> owned ; 1513// chunk buffers 1514float * emb = nullptr ,* R = nullptr ,* xn = nullptr ,* lo = nullptr ,* gated = nullptr ,* inj = nullptr ; 1515float * grs = nullptr ;// F-1: the hyper-connection read's row scales (T x 4) 1516uint16_t * xn16 = nullptr ,* lo16 = nullptr ; 1517float * mixed = nullptr ; 1518uint16_t * mixed_bf = nullptr ,* mixed_h = nullptr ; 1519bool f16_io = false;// HIP, STRATA_HIP_PROMPT_F16=1: this stage's 16-bit GEMMs run FP16 in and out (set in init) 1520bool xn_f16 = false;// Turing, BF16 on FP16 tensor cores: xn16 written as the FP16 values the GEMM would convert 1521uint16_t * xn16_lo = nullptr ,* lo16_lo = nullptr ,* mixed_bf_lo = nullptr ;// bf16x2(): the BF16 GEMMs' low parts 1522float * bo = nullptr ; 1523// GDN 1524float * qkv = nullptr ,* z = nullptr ,* ab = nullptr ,* gate = nullptr ,* beta = nullptr ,* hbuf = nullptr ,* y = nullptr ; 1525uint16_t * y_h = nullptr ; 1526// QSA 1527float * Kc = nullptr ,* Vc = nullptr ,* Qf = nullptr ,* q = nullptr ,* idx_raw = nullptr ,* q_idx = nullptr ,* attn = nullptr ; 1528uint16_t * attn_h = nullptr ; 1529int32_t * steps_dev = nullptr ; 1530 std::vector < int32_t > steps_host ; 1531PinnedUpload steps_up ; 1532int32_t * sel_ids = nullptr ; 1533float * sel_scores = nullptr ;// [sel_batch, max_blocks] 1534int64_t sel_batch = 256 ,max_blocks = 0 ; 1535float * attn_scratch = nullptr ; 1536int64_t attn_batch = 32 ,cap = 0 ; 1537// MoE 1538float * logits = nullptr ,* w = nullptr ,* GU = nullptr ,* Dm = nullptr ,* sgate = nullptr ,* sup = nullptr , 1539* shared = nullptr ,* sg = nullptr ; 1540int32_t * ids = nullptr ,* slot_dev = nullptr ,* src_dev = nullptr ; 1541uint16_t * Xs = nullptr ,* Hh = nullptr ,* sh_h = nullptr ; 1542float * Xr = nullptr ;// APR: Hadamard-rotated copy of `mixed` for the MMQ path 1543// latent MoE: D/U stay pinned host-side, brought up once per session (m.owned); xl/xlq are the per-token 1544// group-wise D products (xl row = src*G + labels[ids[slot]]), yl/ylq the down latents, tok the routing table 1545bool latent = false; 1546int64_t lat_first_layer = 0 ; 1547int64_t lat_H = 0 ,lat_ELL = 0 ,lat_I = 0 ,lat_G = 8 ,lat_E = 0 ; 1548 strata::core::LatentDense lat_d ; 1549int lat_fmt = 8 ;// Q4DU: the dense pack's format (8 Q8_0 / 4 Q4_0) 1550 std::vector < int32_t > lat_labels ;// [layers * E] group labels, host 1551int32_t * lat_labels_dev = nullptr ;// their device copy 1552uint8_t * lat_d_dev = nullptr ,* lat_u_dev = nullptr ;// per-layer D then U, layer-major on the device 1553float * xl = nullptr ;// T * G * ELL floats, the D products 1554uint8_t * xlq = nullptr ;// q8_1 rows of xl (T*G rows, ELL/32*36 bytes each) 1555float * yl = nullptr ;// T * K * ELL floats, the down latents (A_dn products) 1556uint8_t * ylq = nullptr ;// q8_1 rows of yl 1557int32_t * tok = nullptr ;// T * K: the xl row of each routed entry 1558int32_t * tok_ix = nullptr ;// token-major (s*K+k) -> expert (the plan kernel's ids table) 1559int32_t * ids_p = nullptr ;// position p -> expert (U's ids) 1560int32_t * lat_n = nullptr ;// device: [0] grouped kernels' group count, [1] latent_plan_rows' entries 1561unsigned long long * lat_gp = nullptr ;// the grouped kernel's per-group blob pointers (device) 1562int32_t * lat_gs = nullptr ;// its per-group entry starts (device) 1563int32_t * lat_gcd = nullptr ;// STRATA_LAT_FUSED_Q3K: the per-group row COUNTS (device) 1564uint8_t * lat_hbuf = nullptr ;// ... and the fused A stage's staged H rows, 800 B an entry 1565int32_t * lat_gxl = nullptr ;// STRATA_LATENT_MMQ: the xl row of each row of a pending group's buffers 1566int32_t * lat_gdst = nullptr ;// ... and the absolute entry each of those rows belongs to (down's dst) 1567uint8_t * lat_xq = nullptr ;// T q8_1 rows of `mixed` (D's input activations) 1568uint8_t * lat_scratch = nullptr ;// the grouped kernel's scratch (T*K entries) 1569 std::vector < int32_t > lat_tokx_host ,lat_idsx_host ,lat_idsp_host ;// the plan tables, T*K each, host 1570// step 2b (MMQ): the activations quantized per layer, H in FP32 and its group's quantized rows, the identity 1571// row map, the group bounds, the group buffers of gathered experts 1572void * Xq = nullptr ,* Hq = nullptr ; 1573float * H = nullptr ; 1574size_t H_bytes = 0 ;// H's size (STRATA_PF_P1A: FP16 H rows must fit) 1575int32_t * ids_identity = nullptr ,* bounds_dev = nullptr ; 1576uint8_t * grp_gu = nullptr ,* grp_d = nullptr ; 1577float * Xscale = nullptr ,* Hscale = nullptr ,* grp_tail = nullptr ;// NVFP4: activation scales, expert tails 1578float * row_sd = nullptr ;// NVFP4 in MMQ: each Dm row's s_down, applied by the combine as it reads the row 1579 std::vector < int32_t > bounds_host ; 1580// STRATA_MMQ_WS=1 (moe_ws.hpp): a layer whose experts are all resident - their byte offsets from the expert cache's 1581// base in MMQ order and the CTAs' chunks, built on the host per layer and uploaded with the bounds (the device 1582// buffers exist only where ws::mode() != 0; the host copies are the unmapped path's) 1583int64_t * xoff_dev = nullptr ; 1584 std::vector < int64_t > xoff_host ; 1585 ws::Chunk * ws_chunks = nullptr ; 1586 std::vector < ws::Chunk > ws_chunks_host ; 1587// STRATA_PF_GROUP_SCRATCH: per group, its first entry in sub (-1: the group fits the scratch); a sub-range is 1588// experts [a, b) of `order` and the offset of its relative bounds in bounds_host / bounds_dev 1589struct SubRange {int32_t a ,b ,rel ; }; 1590 std::vector < int32_t > sub_first ; 1591 std::vector < SubRange > sub ; 1592int64_t group_cap = 0 ; 1593 std::unique_ptr < mmq::Context > mmq_ctx ; 1594 std::vector < int32_t > ids_host ,slot_host ,src_host ,cnt ,off ; 1595// set_cpu_pool: a small chunk's CPU experts. The layer's MoE input (T x N, from `mixed`), the rows the pool writes 1596// (Dm's tail, in Dm's row order), ones for row_sd (the CPU's rows carry s_down already), all pinned; and the 1597// pool's per-token activations and jobs. 1598float * cpu_x = nullptr ,* cpu_rows = nullptr ,* cpu_ones = nullptr ; 1599size_t cpu_x_n = 0 ,cpu_rows_n = 0 ,cpu_ones_n = 0 ; 1600bool cpu_dead = false;// a pinned buffer of the share could not be had (host memory is short): the GPU does it all 1601 std::vector < uint8_t > cpu_nact ; 1602 std::vector < kernels::cpu::ActQ > cpu_actq ;// a Q2_0 layer's activations (the pool's Q2_0 kernels read ActQ) 1603 std::vector < kernels::cpu::ExpertJobMulti > cpu_jobs ; 1604// the measured share: running means of the CPU's ms per expert and the GPU's per streamed expert, and the share 1605// they balance at (cpu_share_env) 1606double cpu_c_ms = 0 ,cpu_g_ms = 0 ,cpu_share_now = 0.5 ; 1607cudaEvent_t cpu_ev [2 ]= {};// the GPU's expert work of the last CPU-sharing layer, read once the stream is done 1608bool cpu_pend = false; 1609double pend_cpu_ms = 0 ; 1610int64_t pend_n_cpu = 0 ,pend_n_gpu = 0 ; 1611// ... and whether sharing pays at all (auto): an eligible layer's wall time per non-resident expert, from before 1612// its routing sync to its combine (CUDA events, two sets: a layer's start is recorded before the last one's is 1613// read); two adjacent layers of the two arms give a ratio (with / without), and the median of the last 1614// CPU_RATIOS decides. Layers differ up to 8x in that cost, the same in every run, which is why adjacent layers 1615// are compared rather than a running mean per arm. 1616static constexpr int CPU_RATIOS = 5 ; 1617int64_t cpu_layers = 0 ;// the eligible layers so far (the arms' schedule) 1618int64_t cpu_first_l = -1 ;// the model's first eligible layer: 2x the others' cost in both arms, never read 1619cudaEvent_t cpu_wall [4 ]= {}; 1620int pend_wall = 0 ,pend_set = 0 ,pend_l = 0 ;// pend_wall 1: the last eligible layer ran without the share, 2: with 1621int64_t pend_wall_n = 0 ; 1622int last_arm = 0 ,last_l = 0 ; 1623double last_w = 0 ; 1624double cpu_ratio [CPU_RATIOS ]= {}; 1625int cpu_nratio = 0 ; 1626bool cpu_gate = false;// the median ratio is below 1: the layers that share are the cheaper ones 1627// The grouping tables in mapped pinned memory, [ids | slot | src] of T_max * K each, then the MMQ bounds: kernels 1628// read and write them in place. A cudaMemcpyAsync of them queues behind the expert blobs the copy stream already 1629// holds (up to `ring` of them, ~70 us each), and the GPU idles meanwhile - measured 4.2 s of a 128K prompt's 1630// 70 s at the default ring, 0.7 s with a 16-slot one. STRATA_GROUP_COPY=1: the copies (the A/B arm). 1631int32_t * grp_host = nullptr ; 1632int32_t * grp_dev = nullptr ;// its device alias 1633size_t grp_n = 0 ,grp_tk = 0 ;// int32s allocated; T_max * K (the offset of slot, and of src past it) 1634uint16_t * dq_gu [DQ ]= {}; 1635uint16_t * dq_d [DQ ]= {}; 1636// Few-row experts on the FP16 path (fewrows.hpp, STRATA_PF_FEWROWS): fr_xq: the layer's T rows as q8_1 (the grouped 1637// kernels' activations); fr_rec: one plan record per expert position of the layer; fr_scr: the grouped kernels' scratch. 1638void * fr_xq = nullptr ; 1639uint8_t * fr_rec = nullptr ; 1640void * fr_scr = nullptr ; 1641int64_t fr_xq_rows = 0 ; 1642// OWN-I8 (STRATA_EXPERT_I8=1, native_expert_i8): kI8RecBytes of device memory - the group tables of one launch (blob pointers, row bounds, the 1643// group count); the layer's tokens as q8_1 rows live in fr_xq (the same rows the few-row path quantizes), its scratch is the group's GU rows 1644uint8_t * i8_rec = nullptr ; 1645uint8_t * stage_dev [RING_MAX ]= {}; 1646int ring = STAGE ;// the slots of this layout's ring (ring_slots) 1647// THE PROMPT ROOM's resolved counts for this layout (carve): the rule's ring, the room's first slot (past the 1648// staging buffers this layout holds), and the lender's slots on top of them. `ring` is `room_at` + `room` while 1649// a roomed prompt runs and `rule` alone otherwise (set_ring_room_active). 1650int ring_rule = 0 ,ring_room = 0 ,ring_room_at = 0 ; 1651// this layout's GU, H and Xq are the fused path's (moe_bufs' `fused`), so a layer that runs MMQ or the FP16 path may 1652// only write stream_all_min() - 1 of its rows into them; fused_layout() keeps the two in step (#583, #954) 1653bool fused_bufs = false; 1654int64_t tail_req = -1 ;// the MMQ tail (tokens) the fused layout was carved for: -1 = stream_all_min() - 1 (start-up, the way back); relayout's `tail` 1655 std::unique_ptr < Stager > stager ;// the unpinned experts' host copies (step 4) 1656 std::unique_ptr < Stager > lm_stager [2 ];// STRATA_PREFILL_LM_NEXTFILES: layer-major's two stagers, used in turn 1657 std::unique_ptr < PrefillWarmer > warmer ;// STRATA_PREFILL_WARM=1: the per-layer walk's page warming 1658 std::vector < std::vector < int64_t >> warm_prev ;// per layer: the file-tier experts of the previous chunk 1659cudaEvent_t copied [RING_MAX ]= {},used [RING_MAX ]= {}; 1660bool stage_live [RING_MAX ]= {}; 1661// the event that releases each ring slot: its own `used`, or - when an MMQ group is gathered in one launch - the 1662// `used` of the last slot gathered with it, recorded once for all of them (a later record only waits longer) 1663int used_of [RING_MAX ]= {}; 1664// PLE 1665float * ple_emb = nullptr ; 1666 std::vector < float > ple_pageable [2 ];// the fallback when no more RAM can be pinned 1667float * ple_emb_host [2 ]= {};// pinned, double-buffered: the next chunk's rows are read while this 1668cudaEvent_t ple_copied [2 ]= {};// one runs; the event marks that buffer's upload done 1669 std::vector < uint32_t > ple_rows [2 ]; 1670bool ple_compact [2 ]= {false, false};// STRATA_PLE_COMPACT: the pinned buffer holds raw IQ4_NL rows 1671uint8_t * ple_raw_dev = nullptr ;// their device copy (cudaMalloc'd, the chunk's 16 rows a token) 1672cudaStream_t ple_copy = nullptr ;// STRATA_PLE_COPY_STREAM: the raw rows' upload stream (null: on cs) 1673cudaEvent_t ple_raw_free = nullptr ;// cs has dequantized ple_raw_dev: the next chunk's upload may overwrite it 1674float * ple_norm = nullptr ; 1675uint8_t * region = nullptr ;// the attention/MoE scratch region (idle while the PLE block runs) 1676uint64_t region_bytes = 0 ; 1677PrefillStats * stats = nullptr ; 1678// KV streaming: one layer's whole K/V, staged from the host copy per layer and chunk (identity layout) 1679 strata::kernels::KvHostPools stage ; 1680int32_t * ident_table = nullptr ; 1681cudaStream_t kv_copy = nullptr ; 1682cudaEvent_t kv_released = nullptr ,kv_ready = nullptr ; 1683// layer split: the device, and the hand-off to the next stage (two pinned chunk buffers, used in turn) 1684int device = -1 ; 1685float * hand [2 ]= {}; 1686// STRATA_HANDOFF_PIPE: per hand-off buffer, "the chunk's work is done" and one "landed" event per piece 1687int hand_pieces = 0 ; 1688cudaEvent_t hand_done [2 ]= {}; 1689cudaEvent_t hand_ev [2 ][kHandPiecesMax ]= {}; 1690 std::unique_ptr < HandWorker > hand_worker ;// STRATA_HANDOFF_PIPE: the next stage's chunks' thread (lazily) 1691// C-4: the chunk's token ids on the device, for one batched embedding gather 1692int32_t * tok_dev = nullptr ; 1693 std::vector < int32_t > tok_host ; 1694PinnedUpload tok_up ; 1695 core::PinnedRing up_ring ;// #1996: every other upload of the prompt path whose host side is pageable 1696// APR (prism.hadamard): per layer, this device's copies of the gate/up (n_embd) and down (n_ff) sign vectors 1697// (nullptr: identity signs or not folded), resolved once in init so a prompt chunk reads a pointer 1698 std::vector < const float *> had_sx ,had_sh ; 1699 std::unique_ptr < PeerPrefill > pp ;// multi-GPU: the peer GPU's expert share (set_peer) 1700// layer split: the next stage's GPU as a stream-only peer (set_stage_helper); its buffers are that stage's own 1701// prompt buffers, bound per prompt, and it takes the place of `pp` for a run it helps 1702 std::unique_ptr < PeerPrefill > help_pp ; 1703// layer-major prefill (STRATA_PREFILL_LAYER_MAJOR=1): a super-chunk's state between a layer's attention halves 1704// and its experts - device buffers per prompt (lm_prepare / lm_release), pinned host buffers kept 1705struct LmBufs { 1706int64_t S = 0 ;// tokens of a super-chunk (0: not allocated) 1707bool r_dev = false;// its residual rows in VRAM (else R_host, copied per sub-chunk) 1708void * dev = nullptr ;// the one device allocation the pointers below are carved from 1709float * mixed = nullptr ,* acc = nullptr ,* inj = nullptr ,* R = nullptr ,* w = nullptr ; 1710uint16_t * mixed_h = nullptr ;// the FFN half's FP16 rows (the FP16 path's inputs, port 2026-10-24) 1711uint8_t * xa = nullptr ;// the FFN half's int8 rows per token (fused::quantize_act_native), when a layer's groups run fused 1712int32_t * ids = nullptr ,* tab = nullptr ; 1713uint8_t * lat_xlq = nullptr ,* lat_ylq = nullptr ; 1714void * lat_host = nullptr ;// mapped compressed rows in host-residual mode 1715int32_t * lat_tok = nullptr ,* lat_slot = nullptr ; 1716float * lat_sg = nullptr ; 1717uint8_t * lat_tabs = nullptr ;// every A batch's grouping tables of one layer (one upload a layer) 1718size_t lat_tabs_n = 0 ; 1719// STRATA_PREFILL_LM_NEXT: the next layer's RAM-tier experts, copied while this layer finishes 1720uint8_t * pre = nullptr ; 1721int64_t pre_n = 0 ,pre_layer = -1 ; 1722 std::vector < int32_t > pre_of ;// expert -> its slot in `pre` for pre_layer (-1: not prefetched) 1723cudaEvent_t pre_done = nullptr ,pre_free = nullptr ; 1724size_t tab_n = 0 ; 1725float * R_host = nullptr ; 1726size_t R_host_n = 0 ; 1727int32_t * tab_host = nullptr ; 1728size_t tab_host_n = 0 ; 1729int32_t * idsw_host = nullptr ; 1730size_t idsw_host_n = 0 ; 1731int64_t free_mib = 0 ;// VRAM free when the buffers were sized (the log line) 1732// host mode: the residual rows of two sub-chunks on the device in turn (the chunk's R and R2), so the copy 1733// stream uploads the next one and downloads the last one while the compute stream works on this one 1734float * R2 = nullptr ; 1735cudaEvent_t ev_in [2 ]= {},ev_done [2 ]= {},ev_out [2 ]= {}; 1736 }lm ; 1737}; 1738 1739namespace { 1740// the staging pool of a streamed session: every page of one layer (same sequence in init and bytes_needed) 1741// STRATA_KV_STAGE_OWN (A/B only): the staging pool gets its own allocation instead of borrowed expert slots, so a 1742// streamed run lends the prompt path exactly the slots a resident one does (a lent expert runs on the CPU, which 1743// rounds differently: without this an A/B compares two expert placements as well as two KV placements) 1744bool stage_own () {static const bool v = std::getenv ("STRATA_KV_STAGE_OWN" )!= nullptr ;return v ; } 1745void take_stage (Alloc & o_borrowed ,const core::SessionState & ss ,const strata::kernels::QsaShapes & s , 1746 strata::kernels::KvHostPools & st ,bool & ok ) { 1747const core::QsaState & q0 = ss .qsa_states [ss .qsa_primary ()]; 1748if (q0 .kv_mode != 1 )return ; 1749if (stage_own ()&& o_borrowed .count_only )return ; 1750Alloc own ; 1751own .owned = o_borrowed .owned ; 1752Alloc & o = stage_own () ?own :o_borrowed ; 1753const size_t rows = (size_t )q0 .n_pages * s .n_head_kv * s .page_size ; 1754if (q0 .kv_hybrid ) {// K8V4: the three runs of kKvHybrid; pools_of() then reads as the hybrid pools (mode 3) 1755st .k_q = o .take < int8_t > (rows * s .head_dim ,ok ); 1756st .k_scale = o .take < uint16_t > (rows * (s .head_dim /64 ),ok ); 1757st .v_q4 = o .take < uint8_t > (rows * strata::kernels::kv_q4_bytes_per_head ((int )s .head_dim ),ok ); 1758 }else if (q0 .kv_q4 ) { 1759st .k_q4 = o .take < uint8_t > (rows * strata::kernels::kv_q4_bytes_per_head ((int )s .head_dim ),ok ); 1760st .v_q4 = o .take < uint8_t > (rows * strata::kernels::kv_q4_bytes_per_head ((int )s .head_dim ),ok ); 1761 }else if (q0 .kv_int8 ) { 1762st .k_q = o .take < int8_t > (rows * s .head_dim ,ok ); 1763st .v_q = o .take < int8_t > (rows * s .head_dim ,ok ); 1764st .k_scale = o .take < uint16_t > (rows * (s .head_dim /64 ),ok ); 1765st .v_scale = o .take < uint16_t > (rows * (s .head_dim /64 ),ok ); 1766 }else { 1767st .k_pool = o .take < uint16_t > (rows * s .head_dim ,ok ); 1768st .v_pool = o .take < uint16_t > (rows * s .head_dim ,ok ); 1769 } 1770} 1771strata::kernels::QsaAttnPools pools_of (const strata::kernels::KvHostPools & h ,const int32_t * table ) { 1772 strata::kernels::QsaAttnPools p ; 1773p .k_pool = h .k_pool ;p .v_pool = h .v_pool ;p .k_q = h .k_q ;p .v_q = h .v_q ;p .k_scale = h .k_scale ;p .v_scale = h .v_scale ; 1774p .k_q4 = h .k_q4 ;p .v_q4 = h .v_q4 ; 1775p .page_table = table ; 1776return p ; 1777} 1778}// namespace 1779 1780Prefill ::Prefill () :impl_ (new Impl ) {} 1781Prefill ::~Prefill () { 1782clear_taps (); 1783release (); 1784} 1785 1786bool Prefill ::reserve_taps (const std::vector < int >& layers ,int64_t cap_rows ,int64_t n_embd , std::string & err ) { 1787#if defined(STRATA_HAVE_DFLASH2 ) 1788tap_layers_ = layers ; 1789tap_cap_ = cap_rows ; 1790if (tap_dev_ != nullptr )return true; 1791size_t mine = 0 ;// a layer split's stage keeps the taps of the layers it runs (the others arrive from the other stages) 1792for (int l :layers )if (l >=stage_lb_ && (stage_le_ < 0 || l < stage_le_ ))++ mine ; 1793if (mine == 0 )return true; 1794if (cudaMalloc ((void ** )& tap_dev_ , (size_t )cap_rows * mine * (size_t )n_embd * 4 )!= cudaSuccess ) { 1795 (void )cudaGetLastError (); 1796tap_dev_ = nullptr ; 1797err = "the prompt staging of the DFlash2 taps does not fit in VRAM" ; 1798return false; 1799 } 1800return true; 1801#else 1802 (void )layers ; (void )cap_rows ; (void )n_embd ; 1803err = "no DFlash2 in this build" ; 1804return false; 1805#endif 1806} 1807 1808void Prefill ::clear_taps () { 1809if (tap_dev_ != nullptr ) { 1810cudaFree (tap_dev_ ); 1811tap_dev_ = nullptr ; 1812 } 1813tap_layers_ .clear (); 1814on_taps = nullptr ; 1815} 1816 1817void Prefill ::reset () { 1818release (); 1819impl_ .reset (new Impl ); 1820stats_ = PrefillStats {}; 1821} 1822 1823void Prefill ::release () { 1824if (!impl_ )return ; 1825impl_ -> hand_worker .reset ();// idle here (run drains the chain before it returns); joins its thread 1826if (impl_ -> cs )cudaStreamSynchronize (impl_ -> cs ); 1827if (impl_ -> copy )cudaStreamSynchronize (impl_ -> copy ); 1828if (impl_ -> kv_copy )cudaStreamSynchronize (impl_ -> kv_copy ); 1829if (impl_ -> ple_copy ) (void )cudaStreamSynchronize (impl_ -> ple_copy ); 1830for (int i = 0 ;i < RING_MAX ;++ i ) { 1831if (impl_ -> copied [i ])cudaEventDestroy (impl_ -> copied [i ]); 1832if (impl_ -> used [i ])cudaEventDestroy (impl_ -> used [i ]); 1833 } 1834for (int b = 0 ;b < 2 ;++ b ) { 1835if (impl_ -> hand [b ])cudaFreeHost (impl_ -> hand [b ]); 1836if (impl_ -> hand_done [b ])cudaEventDestroy (impl_ -> hand_done [b ]); 1837for (cudaEvent_t & e :impl_ -> hand_ev [b ]) 1838if (e )cudaEventDestroy (e ); 1839if (impl_ -> ple_copied [b ])cudaEventDestroy (impl_ -> ple_copied [b ]); 1840if (impl_ -> ple_emb_host [b ]&& impl_ -> ple_pageable [b ].empty ())cudaFreeHost (impl_ -> ple_emb_host [b ]); 1841if (b == 0 && impl_ -> ple_raw_dev ) { (void )cudaFree (impl_ -> ple_raw_dev );impl_ -> ple_raw_dev = nullptr ; } 1842 } 1843if (impl_ -> copy )cudaStreamDestroy (impl_ -> copy ); 1844if (impl_ -> fr_xq )cudaFree (impl_ -> fr_xq ); 1845if (impl_ -> fr_rec )cudaFree (impl_ -> fr_rec ); 1846if (impl_ -> fr_scr )cudaFree (impl_ -> fr_scr ); 1847if (impl_ -> i8_rec )cudaFree (impl_ -> i8_rec ); 1848if (impl_ -> kv_copy )cudaStreamDestroy (impl_ -> kv_copy ); 1849if (impl_ -> ple_copy ) (void )cudaStreamDestroy (impl_ -> ple_copy ); 1850if (impl_ -> ple_raw_free ) (void )cudaEventDestroy (impl_ -> ple_raw_free ); 1851if (impl_ -> kv_released )cudaEventDestroy (impl_ -> kv_released ); 1852if (impl_ -> kv_ready )cudaEventDestroy (impl_ -> kv_ready ); 1853if (impl_ -> grp_host )cudaFreeHost (impl_ -> grp_host ); 1854if (impl_ -> lm .dev )cudaFree (impl_ -> lm .dev ); 1855if (impl_ -> lm .lat_host )cudaFreeHost (impl_ -> lm .lat_host ); 1856if (impl_ -> lm .R_host )cudaFreeHost (impl_ -> lm .R_host ); 1857if (impl_ -> lm .tab_host )cudaFreeHost (impl_ -> lm .tab_host ); 1858if (impl_ -> lm .idsw_host )cudaFreeHost (impl_ -> lm .idsw_host ); 1859for (int b = 0 ;b < 2 ;++ b ) 1860for (cudaEvent_t e : {impl_ -> lm .ev_in [b ],impl_ -> lm .ev_done [b ],impl_ -> lm .ev_out [b ]}) 1861if (e )cudaEventDestroy (e ); 1862impl_ -> steps_up .release (); 1863impl_ -> tok_up .release (); 1864impl_ -> up_ring .release (); 1865for (float * p : {impl_ -> cpu_x ,impl_ -> cpu_rows ,impl_ -> cpu_ones }) 1866if (p )cudaFreeHost (p ); 1867for (cudaEvent_t e :impl_ -> cpu_ev ) 1868if (e )cudaEventDestroy (e ); 1869for (cudaEvent_t e :impl_ -> cpu_wall ) 1870if (e )cudaEventDestroy (e ); 1871for (void * p :impl_ -> owned )cudaFree (p ); 1872} 1873 1874namespace { 1875constexpr int64_t GEMM_SCRATCH = 32ll <<20 ;// FP16 elements for the largest dequantized dense weight 1876constexpr size_t GEMM_WS = 32u <<20 ;// cuBLAS workspace 1877 1878// THE ATTENTION HALF AND THE MoE HALF SHARE THEIR BUFFERS. A layer runs its attention (GDN or QSA), writes it back 1879// into the residual, and only then its MoE, so the three sets of scratch are never live at once: one region the size 1880// of the largest holds them all. That is ~260 KB of the ~680 KB a prompt token cost - which is what lets a chunk 1881// grow (every expert is streamed once per chunk, so a bigger chunk streams fewer bytes per token). The sizes are 1882// counted with the same `take` sequence `init` uses; a mismatch makes `init` fail with "do not fit", never overlap. 1883uint64_t gdn_set_bytes (size_t T ) { 1884Alloc a ;a .count_only = true;bool ok = true; 1885a .take < float > (T * C ,ok );a .take < float > (T * ZV ,ok );a .take < float > (T * 2 * HV ,ok );a .take < float > (T * HV ,ok ); 1886a .take < float > (T * HV ,ok );a .take < float > (T * C ,ok );a .take < float > (T * ZV ,ok ); 1887a .take < uint16_t > (T * (ZV + (pf_pad () ?ZV_PAD :0 )),ok ); 1888return a .used ; 1889} 1890uint64_t qsa_set_bytes (size_t T ,int64_t cap ,int64_t max_blocks ,int64_t sel_batch ,int64_t attn_batch , 1891const strata::kernels::QsaShapes & s ) { 1892Alloc a ;a .count_only = true;bool ok = true; 1893a .take < float > (T * kKvW ,ok );a .take < float > (T * kKvW ,ok );a .take < float > (T * kQFull ,ok );a .take < float > (T * kQW ,ok ); 1894a .take < float > (T * kIdxK ,ok );a .take < float > (T * kIdxQW ,ok );a .take < float > (T * kQW ,ok ); 1895a .take < uint16_t > (T * (ZV + (pf_pad () ?ZV_PAD :0 )),ok ); 1896a .take < int32_t > (T * (size_t )cap ,ok ); 1897a .take < float > ((size_t )sel_batch * (size_t )max_blocks ,ok ); 1898a .take < float > ((size_t )attn_batch * strata::kernels::qsa_decode_attn_scratch_floats (cap ,s ),ok ); 1899return a .used ; 1900} 1901// Step 2b: which layers' experts go through MMQ (both weight types covered; the Strata Q2_0 pack always - its blob 1902// is converted to GGUF Q2_0 blocks on the gather), whether any layer keeps the FP16 path (IQ1_M), and the largest 1903// gate/up and down matrices a group buffer slot holds. STRATA_PREFILL_MMQ=0: the FP16 path everywhere (the A/B). 1904constexpr int MMQ_GROUP = 16 ;// experts per MMQ launch (the gather is per expert, as blobs arrive) 1905// Latent A batches (Edge0): up to this many experts a launch; the latent tables (lat_gp/lat_gs/lat_gcd) and, for a latent pack, 1906// the group buffers are sized for it. 1907constexpr int LAT_GROUP = 64 ; 1908// MMQ reads up to one 256-value tile past a matrix's last row when the row length is not a multiple of it (the down 1909// product: 640 values). Those bytes meet zero activations, which is harmless only if they decode to finite numbers - 1910// llama.cpp zero-pads after every tensor, and so does a group buffer: this many zeroed bytes follow its last expert. 1911constexpr size_t MMQ_TAIL = 4096 ; 1912// OWN-I8: the int8 kernels' groups are collected by i8_group.hpp (its own group size, no MMQ); both sizes are the same number here 1913static_assert(MMQ_GROUP == strata::prefill::i8grp::kGroupMax ,"the int8 expert group and the MMQ group have the same size" ); 1914#if defined(STRATA_PREFILL_MMQ ) 1915static_assert(strata::prefill::i8grp::kGroupMax == strata::prefill::mmq::kGatherGroupMax ,"the int8 expert group and MMQ's gather group have the same size" ); 1916#endif 1917// STRATA_I8_COUNT=1 (diagnostic, off by default, no effect on any result): one stderr line per prompt chunk saying how many of the routed (token, expert) 1918// entries of the layers that reached the MMQ group walk ran on native_expert_i8 and how many stayed on the walk's own kernels (MMQ, or the FP16 path). 1919bool i8_count_on () { 1920static const bool on = [] {const char * v = std::getenv ("STRATA_I8_COUNT" );return v != nullptr && std::atoi (v )!= 0 ; }(); 1921return on ; 1922} 1923struct I8Count { 1924int64_t layers = 0 ,layers_i8 = 0 ,ent = 0 ,ent_i8 = 0 ,groups_i8 = 0 ,min_avg = INT64_MAX ,layers_few = 0 ,ent_few = 0 ; 1925}; 1926I8Count & i8_count () { 1927static I8Count c ; 1928return c ; 1929} 1930// The MMQ row table (`ids_identity`, T*K rows) is read past its end by llama.cpp's stream-k fixup, which loads a whole 1931// J-column tile of ids before it compares the tile with the expert's rows (see mmq_ids_margin.hpp: the margin follows the 1932// backend's tile bound). An expert takes at most one row per token, so max_rows <= T. Without the slack the table is an 1933// exact-sized cudaMalloc that can end a 2 MiB page, and the over-read faults at the next one (Xid 31 FAULT_PDE, "prefill 1934// copy_i32: an illegal memory access" on a long prompt). The one size used by carve, bytes_needed_impl and the three 1935// places that write the identity (bind_stage_helper, run_impl, lm_run). 0: the size overflows (carve fails). 1936size_t mmq_ids_rows (size_t T ) { 1937if (T > (size_t )INT64_MAX / (size_t )K )return 0 ; 1938return (size_t ) mmq::mmq_ids_table_rows ((uint64_t ) (T * (size_t )K ), (uint64_t )T ); 1939} 1940struct MmqPlan { 1941bool any = false,fallback = true; 1942 std::vector < char > layer ;// per layer: MMQ 1943 std::vector < char > wmma_only ;// per layer: in the MMQ grouping for the WMMA tiles only (pf_wmma: IQ1_M) 1944 std::vector < char > fo ;// per layer: no MMQ here but the native fused kernels cover its formats 1945// (gfx11: UD-Q4_K_XL's Q4_K / Q5_K and Q5_1 / Q8_0 experts, STRATA_PF_FUSED=1) 1946size_t gu_max = 0 ,d_max = 0 ; 1947// STRATA_MMQ_DIRECT=1: per layer, whether resident experts are read in their cache slots (pointer-table MMQ), 1948// and the bytes the down product reads past its matrix there (zeroed in the slot's guard before each group) 1949 std::vector < char > direct ; 1950 std::vector < uint32_t > d_over ; 1951// STRATA_MMQ_GROUP_SORT=1 (without STRATA_MMQ_RESIDENT_SORT_NE): per MMQ layer, whether both products' 16-expert 1952// launches run whole tiles on every visible GPU (mmq::whole_tiles), so its full groups may be taken in row-count order 1953 std::vector < char > group_sort ; 1954}; 1955// Volta (sm_70): MMQ runs on dp4a there (no int8 tensor cores). pf_wmma(): the layers MMQ would take, and the IQ1_M 1956// ones the FP16 path would, run as one launch per expert group on FP16 tensor-core tiles instead 1957// (strata::kernels::gemm_iq_f16_grouped: each weight superblock dequantized once into shared memory by the FP16 path's 1958// own formulas, FP16 activations, FP32 sums). OPT-IN: STRATA_PF_WMMA=1 (the activations are FP16 rather than MMQ's 1959// q8_1, so the answers differ from the default). Only when EVERY visible CUDA card is compute capability 7.0 or 1960// newer: the tiles need tensor cores, and a Volta + Pascal rig (one process, one decision) keeps MMQ. 1961bool pf_wmma () { 1962#if defined(__HIPCC__ )|| defined(STRATA_PF_OWN_ONLY )// (P4-SPLIT: its layers ride MMQ's grouping) 1963return false; 1964#else 1965static const bool on = [] { 1966const char * e = std::getenv ("STRATA_PF_WMMA" ); 1967if (e == nullptr || e [0 ]!= '1' )return false; 1968int n = 0 ; 1969if (cudaGetDeviceCount (& n )!= cudaSuccess || n <=0 )return false; 1970for (int d = 0 ;d < n ;++ d ) { 1971int major = 0 ; 1972if (cudaDeviceGetAttribute (& major ,cudaDevAttrComputeCapabilityMajor ,d )!= cudaSuccess || major < 7 )return false; 1973 } 1974return true; 1975 }(); 1976return on ; 1977#endif 1978} 1979// Tesla P100 (GP100, compute capability 6.0; the STRATA_EXPERIMENTAL_SM60 build): the prompt experts take the FP16 path 1980// by default instead of MMQ, with the few-row experts (fewrows.hpp) on the quantized grouped kernels. GP100 has no 1981// __dp4a (MMQ runs on the bit-exact emulation in dp4a.hpp), and with the few-row route the FP16 path is at 0.95 / 0.91 / 1982// 0.93 / 1.00 of MMQ's prompt speed at 300 / 1,000 / 2K / 4K and above it from 8K (lane P4-FALLBACK, 11-11: 1983// phaseA-tests/par/RESULTS-P4-FALLBACK.md). Only when EVERY visible CUDA card is cc 6.0 (one process, one decision), 1984// and not with what needs MMQ: STRATA_MMQ_WS=1 (its weight-stationary kernels are MMQ's products), STRATA_EXPERT_NIBBLE=1 1985// (the FP16 path reads GGUF blocks) and --peer-device (the prompt peer computes on MMQ only). An explicit 1986// STRATA_PREFILL_MMQ keeps its old meaning. The rule: gp100_prompt_default.hpp (gp100_prompt_default_test); 1987// kGp100Default there is the one line that turns it on. 1988bool gp100_fp16_default (const char * env ) { 1989#if defined(__HIPCC__ )|| !defined(STRATA_EXPERIMENTAL_SM60 ) 1990 (void )env ; 1991return false; 1992#else 1993if (!kGp100Default || env != nullptr )return false; 1994static const bool on = [] { 1995Gp100PromptInputs in ; 1996in .mmq_ws = ws::mode ()!= 0 ; 1997in .nibble = strata::core::nibble::config ().on ; 1998in .peer_device = peer_device_requested ().load (); 1999in .all_cc60 = true; 2000int n = 0 ; 2001if (cudaGetDeviceCount (& n )!= cudaSuccess || n <=0 ) {cudaGetLastError ();in .all_cc60 = false; } 2002for (int d = 0 ;in .all_cc60 && d < n ;++ d ) { 2003int major = 0 ,minor = 0 ; 2004if (cudaDeviceGetAttribute (& major ,cudaDevAttrComputeCapabilityMajor ,d )!= cudaSuccess || 2005cudaDeviceGetAttribute (& minor ,cudaDevAttrComputeCapabilityMinor ,d )!= cudaSuccess ) { 2006cudaGetLastError (); 2007in .all_cc60 = false; 2008 }else if (major != 6 || minor != 0 ) { 2009in .all_cc60 = false; 2010 } 2011 } 2012return gp100_fp16_rule (in ); 2013 }(); 2014return on ; 2015#endif 2016} 2017const MmqPlan & mmq_plan () { 2018static const MmqPlan plan = [] { 2019MmqPlan p ; 2020const auto & lay = strata::kernels::cpu::expert_layout (); 2021const char * env = std::getenv ("STRATA_PREFILL_MMQ" ); 2022#if defined(STRATA_PF_OWN_ONLY ) 2023const bool gp100 = false;// no MMQ in this build: the FP16 path is not a default of the P100 rule here 2024const bool on = fused::built ()&& (env == nullptr || std::atoi (env )!= 0 );// P4-SPLIT: no MMQ tile anywhere, the fused-only layers below 2025#else 2026const bool gp100 = mmq::built ()&& gp100_fp16_default (env ); 2027const bool on = mmq::built ()&& !gp100 && (env == nullptr || std::atoi (env )!= 0 ); 2028#endif 2029const int64_t layers = lay .native ? (int64_t )lay .fmt .size () :lay .n_layers ; 2030p .layer .assign ((size_t ) std::max < int64_t > (layers ,0 ),0 ); 2031p .fo .assign (p .layer .size (),0 ); 2032p .wmma_only .assign (p .layer .size (),0 ); 2033p .fallback = !on || layers <=0 ; 2034 std::map < std::string ,int64_t > mf_layers ;// STRATA_MANIFEST: "path|reason|formats" -> layers (filled only when it is on) 2035const bool mf = strata::core::manifest::enabled (); 2036auto mf_note = [& ](const char * path ,const std::string & why ,int gt ,int dt ) { 2037if (mf )++ mf_layers [std::string (path )+ "|" + why + "|gate_up " + strata::ggml_type_name ((uint32_t )gt )+ ", down " + strata::ggml_type_name ((uint32_t )dt )]; 2038 }; 2039for (int64_t l = 0 ;on && l < layers ;++ l ) { 2040const int gt = lay .native ?lay .fmt [(size_t )l ].gu_type :42 ,dt = lay .native ?lay .fmt [(size_t )l ].d_type :42 ; 2041// #420: a tile on every GPU for these shapes (gate+up: 1280 rows, down: N rows), else the FP16 path 2042if (!mmq::fits (gt ,kFF2 )|| !mmq::fits (dt ,N )) { 2043// pf_wmma: a format dq_dispatch takes (IQ1_M, an IQ4_NL down) rides the MMQ grouping, computed by the WMMA tiles only 2044if (pf_wmma ()&& lay .native && (dt == 42 || dt == 20 )&& strata::kernels::iq_row_bytes (gt ,N )> 0 ) { 2045p .layer [(size_t )l ]= 1 ; 2046p .wmma_only [(size_t )l ]= 1 ; 2047p .any = true; 2048p .gu_max = std::max (p .gu_max , mmq::matrix_bytes (gt ,kFF2 ,N )); 2049p .d_max = std::max (p .d_max , mmq::matrix_bytes (dt ,N ,kFF )); 2050mf_note ("mmq-grouping, FP16 WMMA tiles" ,"MMQ has no tile for these formats; STRATA_PF_WMMA=1 computes them on FP16 tensor cores" ,gt ,dt ); 2051continue ; 2052 } 2053p .fallback = true; 2054// the fused path's buffers (Xq, H) exist for it; a chunk it does not take (a small one) keeps the FP16 path 2055if (on && lay .native && fused::native_supported (gt ,dt )) {p .fo [(size_t )l ]= 1 ;p .any = true; } 2056#if defined(STRATA_PF_OWN_ONLY ) 2057if (on && !lay .native && fused::enabled ()) {p .fo [(size_t )l ]= 1 ;p .any = true; }// the Strata Q2_0 pack (moe_fused.cu) 2058#endif 2059if (mf ) { 2060const bool fo = p .fo [(size_t )l ]!= 0 ; 2061const std::string why = std::string (!mmq::fits (gt ,kFF2 ) ?"no MMQ tile for the gate/up format on every visible GPU" :"no MMQ tile for the down format on every visible GPU" )+ 2062 (fo ?"; the native fused kernels take it" :"; the dequantize + FP16 GEMM path takes it" ); 2063mf_note (fo ?"fused-native" :"fp16-gemm" ,why ,gt ,dt ); 2064 } 2065continue ; 2066 } 2067p .layer [(size_t )l ]= 1 ; 2068p .any = true; 2069p .gu_max = std::max (p .gu_max , mmq::matrix_bytes (gt ,kFF2 ,N )); 2070p .d_max = std::max (p .d_max , mmq::matrix_bytes (dt ,N ,kFF )); 2071mf_note ("mmq" ,"an MMQ tile exists for both products on every visible GPU" ,gt ,dt ); 2072 } 2073if (mf ) { 2074if (!on ) { 2075 strata::core::manifest::instance ().path ("prefill" ,"experts" , false, 2076 !mmq::built () ?"this build has no MMQ (ggml sources were not available)" 2077 :gp100 ?"Tesla P100 (compute capability 6.0): the FP16 path is the default there" 2078 :"STRATA_PREFILL_MMQ=0" , 2079"the expert products take the FP16 path" ); 2080 }else if (layers <=0 ) { 2081 strata::core::manifest::instance ().path ("prefill" ,"experts" , false,"no expert layout loaded" ,"" ); 2082 } 2083for (const auto & [k ,n ] :mf_layers ) { 2084const size_t a = k .find ('|' ),b = k .find ('|' ,a + 1 ); 2085const std::string kind = k .substr (0 ,a ); 2086 strata::core::manifest::instance ().path ("prefill" ,"experts: " + k .substr (b + 1 ),kind == "mmq" || kind [0 ]== 'm' , 2087k .substr (a + 1 ,b - a - 1 ),kind + ", " + std::to_string (n )+ " layers" ); 2088 } 2089 } 2090#if defined(STRATA_PF_OWN_ONLY ) 2091if (layers > 0 ) {// The owner approved this wording (11-13). One line per process (the plan is made once): the layer counts per path, from the rule functions that pick the path. 2092const bool peer_off = strata::prefill::peer_keeps_mmq (strata::core::peer_portable (),kPfOwnOnlyBuild );// the walk's own condition (no_peer): false in this build 2093const bool entry_on = staged_fo_on ();// the staged group entry for a fused-only layer below the floor (staged_fo_rule.hpp) 2094 strata::prefill::OwnOnlySplit big ,small ;// at or above the long-prompt floor, below it 2095const bool i8_gated = strata::kernels::native_expert_i8_floor_gated ();// P100 class: the int8 default is for chunks under stream_all_min() only, the FP16 path from it up 2096for (int64_t l = 0 ;l < layers ;++ l ) { 2097const bool fo = p .fo [(size_t )l ]!= 0 && !peer_off ; 2098bool i8 = false;// the int8 expert kernels take this layer's formats (the class rule or STRATA_EXPERT_I8, i8_wants_identity's test) 2099bool unfolded = true;// no Hadamard fold and no tail: the int8 kernels read neither (i8_l: !had_gu && !had_d && !tail_off) 2100bool staged_ok = true;// the staged entry: no fold; a tail only where the fused kernels take the pair (fz_staged: they apply the tail's scales inside) 2101if (lay .native ) { 2102const auto & f = lay .fmt [(size_t )l ]; 2103unfolded = !f .tail_off && !f .had_gu && !f .had_d ; 2104staged_ok = !f .had_gu && !f .had_d && (!f .tail_off || fo ); 2105if (unfolded ) 2106i8 = strata::kernels::native_expert_i8_prompt (strata::kernels::native_expert_layout (f .gu_type ,f .d_type ,f .n_embd ,f .n_ff ), (int64_t )1 <<20 ); 2107 } 2108 strata::prefill::own_only_count_layer (big ,small ,fo ,i8 ,i8_gated ,entry_on ,staged_ok ); 2109 } 2110 {// printed once the share is armed, with the floor in force then (own_only_line_flush) 2111 std::lock_guard < std::mutex > lk (g_own_line_mu ); 2112g_own_line .plan (layers ,big ,small ,peer_off ); 2113 } 2114own_only_line_flush (); 2115 std::string sw ; 2116for (const std::string & k :own_only_switches ())sw += (sw .empty () ?"" :" " )+ k ; 2117if (mf ) strata::core::manifest::instance ().path ("prefill" ,"own-only-build" , true, 2118"this engine was built without llama.cpp's MMQ prompt kernels" , 2119"switches on by default here (a switch you set is kept): " + (sw .empty () ? std::string ("none" ) :sw )); 2120 } 2121#endif 2122// STRATA_MMQ_DIRECT=1: a native layer's resident experts are read in place when the pointer-table MMQ covers 2123// both products, gate/up reads nothing past its matrix, the down over-read fits the slot guard, and the blob 2124// is exactly [gate | up | down] in MMQ's matrix sizes (the bytes a gather would copy) 2125p .direct .assign (p .layer .size (),0 ); 2126p .d_over .assign (p .layer .size (),0 ); 2127if (on && lay .native && mmq::direct_mode ()== 1 ) { 2128int64_t nd = 0 ; 2129for (int64_t l = 0 ;l < layers ;++ l ) { 2130if (!p .layer [(size_t )l ])continue ; 2131const auto & f = lay .fmt [(size_t )l ]; 2132const int gt = f .gu_type ,dt = f .d_type ; 2133if (!mmq::tab_fits (gt ,kFF2 )|| !mmq::tab_fits (dt ,N ))continue ; 2134if (mmq::overread_bytes (gt ,N )!= 0 || mmq::overread_bytes (dt ,kFF )> mmq::kSlotGuard )continue ; 2135if (f .up_off != mmq::matrix_bytes (gt ,kFF2 ,N ) /2 || f .down_off != 2 * f .up_off )continue ; 2136if (mmq::matrix_bytes (dt ,N ,kFF )!= f .bytes - f .down_off )continue ; 2137p .direct [(size_t )l ]= 1 ; 2138p .d_over [(size_t )l ]= (uint32_t ) mmq::overread_bytes (dt ,kFF ); 2139++ nd ; 2140 } 2141 std::fprintf (stderr ,"strata: prompt MMQ reads resident experts in place (STRATA_MMQ_DIRECT=1): %lld of %lld " 2142"layers\n" , (long long )nd , (long long )layers ); 2143 strata::core::manifest::instance ().path ("prefill" ,"mmq-direct" ,nd > 0 ,nd > 0 ?"STRATA_MMQ_DIRECT=1" :"STRATA_MMQ_DIRECT=1, but no layer is eligible" , 2144 std::to_string (nd )+ " of " + std::to_string (layers )+ " layers read resident experts in place" ); 2145 } 2146// the verdict depends only on the layer's formats and the visible GPUs: taken once here, not per chunk 2147p .group_sort .assign (p .layer .size (),0 ); 2148if (on && detail::mmq_group_sort_requested ()&& !detail::mmq_resident_sort_requested ()) { 2149int64_t ns = 0 ; 2150for (int64_t l = 0 ;l < layers ;++ l ) { 2151if (!p .layer [(size_t )l ])continue ; 2152const int gt = lay .native ?lay .fmt [(size_t )l ].gu_type :42 ,dt = lay .native ?lay .fmt [(size_t )l ].d_type :42 ; 2153p .group_sort [(size_t )l ]= mmq::whole_tiles (gt ,kFF2 ,MMQ_GROUP )&& mmq::whole_tiles (dt ,N ,MMQ_GROUP ); 2154ns += p .group_sort [(size_t )l ]; 2155 } 2156 std::fprintf (stderr ,"strata: prompt MMQ sorts the full expert groups (STRATA_MMQ_GROUP_SORT=1): %lld of %lld " 2157"layers\n" , (long long )ns , (long long )layers ); 2158 strata::core::manifest::instance ().path ("prefill" ,"mmq-group-sort" ,ns > 0 ,ns > 0 ?"STRATA_MMQ_GROUP_SORT=1" :"STRATA_MMQ_GROUP_SORT=1, but whole tiles are not guaranteed on every GPU" , 2159 std::to_string (ns )+ " of " + std::to_string (layers )+ " layers" ); 2160 } 2161return p ; 2162 }(); 2163return plan ; 2164} 2165// the FP16 buffers (Xs, Hh): the FP16 path's, or pf_wmma's activations and down input 2166bool fp16_bufs (const MmqPlan & mp ) {return mp .fallback || pf_wmma (); } 2167// OWN-I8: does a layer of this layout take the int8 expert groups on this device (the class rule or STRATA_EXPERT_I8=1, and the formats)? A build without MMQ 2168// has no MMQ buffers when no layer takes the fused kernels (mmq_plan().any is false); the int8 groups need one row table of theirs (the identity ids_identity), 2169// which carve and bytes_needed then take on their own. 2170bool i8_wants_identity () { 2171static const bool on = [] { 2172const auto & lay = strata::kernels::cpu::expert_layout (); 2173if (!lay .native )return false; 2174for (const auto & f :lay .fmt ) { 2175if (f .tail_off || f .had_gu || f .had_d )continue ; 2176const strata::kernels::NativeExpertLayout L = strata::kernels::native_expert_layout (f .gu_type ,f .d_type ,f .n_embd ,f .n_ff ); 2177if (strata::kernels::native_expert_i8_prompt (L , (int64_t )1 <<20 ))return true; 2178 } 2179return false; 2180 }(); 2181return on ; 2182} 2183// STRATA_PF_GROUP_SCRATCH=1 (opt-in): on a layout whose every layer takes MMQ (no fused experts, no FP16 fallback or pf_wmma), the 2184// gate/up output, its SwiGLU and its q8_1 copy (GU, H, Hq) hold one expert group's rows instead of the whole chunk's: 2185// a group's products read them and are done with them before the next group starts, so the products and the bits are 2186// the ones of the chunk-sized buffers. ~84 KB a token less, which lets a bigger chunk fit in the slots the prompt 2187// path borrows (fewer chunks: every streamed expert crosses PCIe fewer times per token). A group whose rows pass the 2188// cap runs as sub-ranges of its experts (one expert holds at most T rows: a token routes to an expert once). 2189bool pf_group_scratch () { 2190static const bool on = [] {const char * v = std::getenv ("STRATA_PF_GROUP_SCRATCH" );return v != nullptr && std::atoi (v )!= 0 ; }(); 2191if (!on )return false; 2192// decided once, with a line saying why when it stays off (recommend, never force: the switch is ignored, the prompt path is as before) 2193static const bool ok = [] { 2194const MmqPlan & mp = mmq_plan (); 2195const char * why = nullptr ; 2196if (!mp .any || fp16_bufs (mp ))why = "the prompt path runs the FP16 path or pf_wmma here, not MMQ" ;// the FP16 path's or pf_wmma's buffers 2197else for (char c :mp .layer )if (!c ) {why = "a layer does not take MMQ" ;break ; } 2198if (why == nullptr )for (char c :mp .direct )if (c ) {why = "STRATA_MMQ_DIRECT is on for a layer (its guard tables are per whole group)" ;break ; }// per whole group 2199if (why != nullptr ) 2200 std::fprintf (stderr ,"strata prefill: STRATA_PF_GROUP_SCRATCH=1 is ignored: %s%s" ,why ,"\n" ); 2201return why == nullptr ; 2202 }(); 2203return ok ; 2204} 2205// one MMQ product range: experts [a, b) of the layer's order, and its relative bounds' offset in the bounds table 2206struct MoeRange {int32_t a ,b ,rel ; }; 2207// the rows one group's scratch holds: T (a single expert's most) plus three times a group's average 2208int64_t group_cap_rows (size_t T ,int64_t n_expert ) { 2209// STRATA_PF_GROUP_CAP=<rows> (a test knob, at least T): a smaller cap, so that most groups run as sub-ranges 2210static const int64_t forced = [] {const char * v = std::getenv ("STRATA_PF_GROUP_CAP" );return v ? (int64_t ) std::atoll (v ) :0 ; }(); 2211if (forced > 0 )return std::max < int64_t > (forced , (int64_t )T ); 2212const int64_t avg = (int64_t )T * K * MMQ_GROUP / std::max < int64_t > (n_expert ,1 ); 2213return ((int64_t )T + 3 * avg + 63 ) /64 * 64 ; 2214} 2215// the bounds table's int32s: the absolute bounds, one relative table per group and, with STRATA_PF_GROUP_SCRATCH, the 2216// relative tables of the sub-ranges of the groups that pass the cap (at most one per expert, each with an end entry) 2217size_t bounds_ints (int64_t n_expert ) { 2218return (size_t ) (2 * (n_expert + n_expert /MMQ_GROUP + 2 ))+ (pf_group_scratch () ? (size_t ) (3 * n_expert + 64 ) :0 ); 2219} 2220// STRATA_PF_HC_REGION=1 (opt-in): the hyper-connection read's scratch (xn16, lo, lo16, gated and the BF16x2 low halves) in the 2221// region the attention half and the MoE half share, as a fourth set: a half's read is done with it before that half's 2222// set is written, and the fused write at a half's end (gr_write_norm_rs: the next half's xn16) runs after the half's last 2223// region reader on the same stream. The same kernels on the same values: the same bits. ~63 KB a token outside the 2224// region less (the region already holds more than this set). 2225bool pf_hc_region () { 2226static const bool on = [] {const char * v = std::getenv ("STRATA_PF_HC_REGION" );return v != nullptr && std::atoi (v )!= 0 ; }(); 2227return on && !gr_unfused (); 2228} 2229uint64_t hc_set_bytes (size_t T ,bool f16_io ) { 2230Alloc a ;a .count_only = true;bool ok = true; 2231a .take < uint16_t > (T * (D + (hc_pad () ?XN_PAD :0 )),ok );a .take < float > (T * LR ,ok );a .take < uint16_t > (T * LR ,ok ); 2232a .take < float > (T * D ,ok ); 2233if (bf16x2_hc (f16_io )) {a .take < uint16_t > (T * D ,ok );a .take < uint16_t > (T * LR ,ok ); } 2234return a .used ; 2235} 2236// #136 P3: a layout whose chunks run the fused experts (STRATA_PF_FUSED=1, the Q2_0 pack, a streamed chunk of 2237// stream_all_min() tokens or more). Its GU, H and Xq hold only the fused path's grouping tables, int8 H and per-token 2238// int8 activations, and Hq nothing: ~100 KB a token less than MMQ's FP32 GU / H and per-slot q8_1 rows, which is what 2239// lets a bigger chunk or ring fit in the slots the prompt path borrows. A last chunk below stream_all_min() still runs 2240// MMQ in the same buffers, so each keeps MMQ's size for stream_all_min() - 1 tokens. `src`: the layout streams experts 2241// (Prefill::init got an ExpertSource; without one no chunk takes the streamed walk, so no chunk is fused). 2242bool fused_layout (size_t T ,bool src ) { 2243// STRATA_LATENT_MMQ: the latent A stage's MMQ reads every entry row of the full chunk, so the fused path's 2244// small-chunk buffers (stream_all_min()-1 tokens) must not be chosen - the backstop at the layer loop would 2245// otherwise be the only thing standing between this and an out-of-bounds Xq/Hq write. 2246static const bool lat_mmq = [] { 2247const char * v = std::getenv ("STRATA_LATENT_MMQ" ); 2248return v != nullptr && v [0 ]== '1' ; 2249 }(); 2250if (lat_mmq )return false; 2251return src && fused_ring ()&& mmq_plan ().any && ring_slots (T )> STAGE && (int64_t )T >=stream_all_min (); 2252} 2253// M4: STRATA_LAT_FUSED_Q3K=1 - the latent A stage on the q3k pack's own fused kernels (lat_q3k_fused: gate/up + 2254// SwiGLU + the q8_1 of H + down in two launches, each expert read where it already is, so no gather_native and no 2255// per-expert launch). Read once: moe_set_bytes, the carve and the layer loop must agree on it. Off by default. 2256bool lat_fused_q3k_on () { 2257static const bool on = [] { 2258const char * v = std::getenv ("STRATA_LAT_FUSED_Q3K" ); 2259return v != nullptr && v [0 ]== '1' ; 2260 }(); 2261return on ; 2262} 2263 2264// The MoE buffers MMQ and the fused path share: GU and H in floats, Xq and Hq in bytes. Without `fused` (the 2265// default): MMQ's, for T tokens. 2266// STRATA_PF_P1A=1: once, at the last layer of the first fused prompt chunk, which layers' experts took the P1A kernels (by type pair) 2267template < class F > 2268void p1a_report (const std::vector < F >& fmt ,size_t l ,bool took ) { 2269static std::vector < int > seen ;// per layer: -1 not on the fused path yet, 0 today's kernels, 1 P1A 2270static bool said = false; 2271if (said || fmt .empty ())return ; 2272if (seen .empty ())seen .assign (fmt .size (),-1 ); 2273if (l < seen .size ()&& seen [l ]< 0 )seen [l ]= took ?1 :0 ; 2274if (l + 1 != fmt .size ())return ; 2275said = true; 2276const auto name = [](int t )-> std::string { 2277switch (t ) { 2278case 7 :return "Q5_1" ; 2279case 8 :return "Q8_0" ; 2280case 12 :return "Q4_K" ; 2281case 13 :return "Q5_K" ; 2282default :return "type " + std::to_string (t ); 2283 } 2284 }; 2285 std::map < std::string ,int > on ,off ; 2286int n_on = 0 ,n_off = 0 ,n_unseen = 0 ; 2287for (size_t i = 0 ;i < fmt .size ();++ i ) { 2288const std::string pair = name (fmt [i ].gu_type )+ "/" + name (fmt [i ].d_type ); 2289if (seen [i ]== 1 ) {++ on [pair ];++ n_on ; } 2290else if (seen [i ]== 0 ) {++ off [pair ];++ n_off ; } 2291else ++ n_unseen ; 2292 } 2293const auto list = [](const std::map < std::string ,int >& m ) { 2294 std::string s ; 2295for (const auto & kv :m )s += (s .empty () ?"" :", " )+ kv .first + " " + std::to_string (kv .second ); 2296return s .empty () ? std::string ("none" ) :s ; 2297 }; 2298if (n_on == 0 )return ;// a pack or chunk with no P1A layer: no line 2299 std::fprintf (stderr ,"strata: prompt experts P1A (STRATA_PF_P1A=1): gate/up + down on the P1A kernels in %d of %zu layers (%s); " 2300"today's kernels in %d (%s); %d not on the fused path in this chunk\n" , 2301n_on ,fmt .size (),list (on ).c_str (),n_off ,list (off ).c_str (),n_unseen ); 2302} 2303// STRATA_PF_P1A (gfx1151): some layer of the loaded native pack takes the P1A kernels; only then does H grow to FP16 rows, so a 2304// pack with no such layer sizes exactly what it did before. The expert layout is loaded before the first plan (generate.cpp's 2305// main: expert_layout_load ahead of every bytes_needed and Prefill::init); debug builds check that every sizing sees one answer. 2306// A smaller H than the P1A kernels need is never written past: experts_native takes them only when the FP16 rows fit in the 2307// H that Prefill::init carved (H_bytes), and runs today's kernels for that call otherwise. 2308bool p1a_pack () { 2309bool any = false; 2310if (fused::p1a_wanted ()) { 2311const strata::kernels::cpu::ExpertLayout & lay = strata::kernels::cpu::expert_layout (); 2312for (size_t l = 0 ;lay .native && l < lay .fmt .size ()&& !any ;++ l ) 2313any = fused::p1a_takes_pair (lay .fmt [l ].gu_type ,lay .fmt [l ].d_type ); 2314 } 2315#ifndef NDEBUG 2316static std::atomic < int > first {-1 };// the first sizing's answer; a later different one = a plan made before the layout was loaded 2317int want = -1 ; 2318if (!first .compare_exchange_strong (want , (int )any ))assert (want == (int )any ); 2319#endif 2320return any ; 2321} 2322struct MoeBufs {size_t gu ,h ,xq ,hq ; }; 2323// `tail` (>= 0, fused only): the MMQ rows a chunk below the floor may bring, in tokens (a lent layout sized for its 2324// segment's own last chunk, loan_rules.hpp); -1: stream_all_min() - 1, as the start-up layout. 2325MoeBufs moe_bufs (size_t T ,int64_t n_expert ,bool fused ,int64_t tail = -1 ) { 2326if (!fused && pf_group_scratch ()) {// GU, H, Hq: one group's rows (Xq keeps every row: gate/up reads the layer's) 2327const size_t gc = (size_t )group_cap_rows (T ,n_expert ); 2328return {gc * kFF2 ,gc * kFF , mmq::q8_bytes ((int64_t ) (T * K ),N ), mmq::q8_bytes ((int64_t )gc ,kFF )}; 2329 } 2330if (!fused )return {T * K * kFF2 ,T * K * kFF , mmq::q8_bytes ((int64_t ) (T * K ),N ), mmq::q8_bytes ((int64_t ) (T * K ),kFF )}; 2331const int64_t tail_tokens = tail >=0 ? std::min < int64_t > (tail , std::max < int64_t > (stream_all_min ()- 1 ,0 )) :stream_all_min ()- 1 ; 2332const size_t ts = (size_t ) std::min < int64_t > ((int64_t )T ,tail_tokens );// MMQ's last small chunk 2333// STRATA_PF_P1A=1 (gfx1151 only; on by default on Windows gfx1151) and a pack with P1A layers: H holds FP16 rows (n_ff halves a routed row) 2334const size_t h_p1a = p1a_pack () ? (T * K * kFF * 2 + 3 ) /4 :0 ; 2335return {std::max < size_t > (ts * K * kFF2 , (fused::group_bytes ((int64_t ) (T * K ), (int )n_expert )+ 3 ) /4 ), 2336 std::max < size_t > (std::max < size_t > (ts * K * kFF , (fused::act_bytes ((int64_t ) (T * K ),kFF )+ 3 ) /4 ),h_p1a ), 2337 std::max (mmq::q8_bytes ((int64_t ) (ts * K ),N ), fused::act_bytes ((int64_t )T ,N )), 2338 mmq::q8_bytes ((int64_t ) (ts * K ),kFF )}; 2339} 2340uint64_t moe_set_bytes (size_t T ,int64_t n_expert ,bool fused ,int64_t tail = -1 ) { 2341const MmqPlan & mp = mmq_plan (); 2342const MoeBufs mb = moe_bufs (T ,n_expert ,fused ,tail ); 2343Alloc a ;a .count_only = true;bool ok = true; 2344a .take < float > (T * n_expert ,ok );a .take < float > (T * K ,ok );a .take < int32_t > (T * K ,ok );a .take < int32_t > (T * K ,ok ); 2345a .take < int32_t > (T * K ,ok ); 2346// the FP16 path's Xs / Hh: in a fused layout the tail below the stream floor only (fp16_rows_rule.hpp), like GU / H / Hq above 2347const size_t Tf = (size_t ) strata::prefill::fp16_buf_tokens ((int64_t )T ,fused ,stream_all_min ()); 2348if (fp16_bufs (mp ))a .take < uint16_t > (Tf * K * N ,ok ); 2349a .take < float > (mb .gu ,ok ); 2350if (fp16_bufs (mp ))a .take < uint16_t > (Tf * K * kFF ,ok ); 2351a .take < float > (T * K * N ,ok );a .take < float > (T * kFF ,ok ); 2352a .take < float > (T * kFF ,ok );a .take < uint16_t > (T * kFF ,ok );a .take < float > (T * N ,ok );a .take < float > (T ,ok ); 2353if (mp .any ) { 2354a .take < uint8_t > (mb .xq ,ok ); 2355a .take < float > (mb .h ,ok ); 2356a .take < uint8_t > (mb .hq ,ok ); 2357a .take < float > (T * K ,ok );a .take < float > (T * K ,ok );a .take < float > (MMQ_GROUP * 4 ,ok ); 2358a .take < float > (T * K ,ok ); 2359// APR: the rotated copy of `mixed` for the MMQ path (carve's m.Xr) - it must be counted here too, or the MoE 2360// set outgrows the region `carve` sizes from this, and `init` fails with "do not fit" at any chunk 2361if (strata::kernels::cpu::hadamard_spec ().any ())a .take < float > (T * N ,ok ); 2362 } 2363 {// latent MoE: xl/xlq/yl/ylq/tok (carve's takes, same order; region-sized for both arm layouts) 2364const auto & lay0 = strata::kernels::cpu::expert_layout (); 2365if (lay0 .native && !lay0 .fmt .empty ()&& lay0 .fmt [0 ].n_embd != (int64_t )N ) { 2366const int64_t ELL = lay0 .fmt [0 ].n_embd ; 2367const int64_t G = 8 ; 2368a .take < float > (T * G * ELL ,ok ); 2369a .take < uint8_t > (T * G * (ELL /32 * 36 ),ok ); 2370a .take < float > (T * K * ELL ,ok ); 2371a .take < uint8_t > (T * K * (ELL /32 * 36 ),ok ); 2372a .take < int32_t > (T * K ,ok ); 2373a .take < int32_t > (T * K ,ok ); 2374a .take < int32_t > (T * K ,ok ); 2375a .take < uint8_t > (T * (N /32 )* 36 ,ok ); 2376a .take < int32_t > (2 ,ok ); 2377a .take < uint8_t > (strata::kernels::native_expert_scratch_bytes ((int64_t ) (T * K ),lay0 .fmt [0 ].n_ff ),ok ); 2378a .take < unsigned long long > (LAT_GROUP ,ok ); 2379a .take < int32_t > (LAT_GROUP + 1 ,ok ); 2380a .take < int32_t > (LAT_GROUP ,ok );// M4: lat_gcd 2381// M4: the fused A stage's staged H rows (n_ff / 32 = 20 q8_1 blocks = 800 B an entry), only when on 2382if (lat_fused_q3k_on ())a .take < uint8_t > (T * K * 800 ,ok ); 2383a .take < int32_t > (T * K ,ok );// STRATA_LATENT_MMQ: lat_gxl / lat_gdst (always taken: the region must 2384a .take < int32_t > (T * K ,ok );// not depend on an env var the carve might see differently) 2385 } 2386 } 2387return a .used ; 2388} 2389} 2390 2391// The first BF16 and the first FP16 GEMM of a process each pay a one-time library / code-object load in hipBLAS (1.2 s and 2392// 1.0 s on an R9700, hipBLASLt 1.2.0: STRATA_COLD_TRACE), which the first prompt then carries (a 700-token prompt: 5.9 s, 2393// 3.5 s of it these). One tiny product of each type, on a handle and stream of its own, moves that cost out of the first 2394// request; generate.cpp starts it on a thread before the expert arena loads, so it costs no start-up time, and 2395// Prefill::init waits for it. The outputs go to scratch buffers of their own, so no later result changes. 2396// STRATA_PREFILL_WARM=0 turns it off. 2397void warm_gemm_libraries (int device ) { 2398static const bool off = [] {const char * e = std::getenv ("STRATA_PREFILL_WARM" );return e != nullptr && e [0 ]== '0' ; }(); 2399if (off )return ; 2400#if defined(STRATA_USE_HIP ) 2401// #3204: not when the process sees cards of more than one architecture (gfx1151 + gfx1201: prompts -25%); see 2402// warm_policy.hpp. STRATA_PREFILL_WARM=1 asks for it anyway. 2403static const bool arch_ok = [] { 2404 std::vector < std::string > archs ; 2405int n = 0 ; 2406if (cudaGetDeviceCount (& n )!= cudaSuccess ) { (void )cudaGetLastError ();return true; } 2407for (int i = 0 ;i < n && i < 32 ;++ i ) { 2408cudaDeviceProp p {}; 2409if (cudaGetDeviceProperties (& p ,i )== cudaSuccess )archs .emplace_back (p .gcnArchName ); 2410else (void )cudaGetLastError (); 2411 } 2412const bool wanted = warm_gemm_wanted (archs , std::getenv ("STRATA_PREFILL_WARM" )); 2413if (!wanted ) 2414 std::fprintf (stderr ,"strata prefill: no hipBLAS warm-up: the cards are of more than one architecture " 2415"(it slows prompts there, #3204); the first prompt loads the libraries (STRATA_PREFILL_WARM=1 asks for it)\n" ); 2416return wanted ; 2417 }(); 2418if (!arch_ok )return ; 2419static std::mutex mu ; 2420static unsigned done_mask = 0 ;// per device: each card loads its own code objects 2421if (device < 0 || device >=32 )return ; 2422 std::lock_guard < std::mutex > lk (mu ); 2423if (done_mask & (1u <<device ))return ; 2424done_mask |=1u <<device ; 2425int prev = 0 ; 2426if (cudaGetDevice (& prev )!= cudaSuccess ) { (void )cudaGetLastError ();return ; } 2427if (prev != device && cudaSetDevice (device )!= cudaSuccess ) { (void )cudaGetLastError ();return ; } 2428const auto t0 = std::chrono::steady_clock::now (); 2429constexpr int64_t T = 64 ,Nn = 64 ,K = 320 ; 2430uint16_t * x = nullptr ,* w = nullptr ; 2431float * y = nullptr ; 2432cudaStream_t st = nullptr ; 2433bool ok = cudaStreamCreate (& st )== cudaSuccess && cudaMalloc ((void ** )& x , (size_t )T * K * 2 )== cudaSuccess && 2434cudaMalloc ((void ** )& w , (size_t )Nn * K * 2 )== cudaSuccess && cudaMalloc ((void ** )& y , (size_t )T * Nn * 4 )== cudaSuccess ; 2435if (ok ) { 2436Gemm gm ; 2437 std::string err ; 2438ok = gm .init ((void * )st ,T * K ,err ); 2439if (ok ) { 2440cudaMemsetAsync (x ,0 , (size_t )T * K * 2 ,st ); 2441cudaMemsetAsync (w ,0 , (size_t )Nn * K * 2 ,st ); 2442gm .bf16 (x ,w ,y ,T ,Nn ,K ); 2443gm .f16 (x ,w ,y ,T ,Nn ,K ); 2444cudaStreamSynchronize (st ); 2445 } 2446 } 2447 (void )cudaGetLastError (); 2448if (x )cudaFree (x ); 2449if (w )cudaFree (w ); 2450if (y )cudaFree (y ); 2451if (st )cudaStreamDestroy (st ); 2452if (prev != device )cudaSetDevice (prev ); 2453if (ok ) 2454 std::fprintf (stderr ,"strata prefill: warmed the BF16 and FP16 GEMM libraries on GPU %d in %.0f ms (STRATA_PREFILL_WARM=0 skips)\n" , 2455device , std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t0 ).count ()); 2456#else 2457 (void )device ; 2458#endif 2459} 2460 2461bool Prefill ::init (const core::WeightTable & wt ,const core::ModelGeometry & g , core::SessionState & ss , 2462 core::ExpertSource * src ,const core::ExpertCache * cache ,const int32_t * host_res ,int64_t chunk , 2463void * stream , std::string & err ,void * borrow ,uint64_t borrow_bytes ,bool borrow_spill ) { 2464Impl & m = * impl_ ; 2465int64_t tr_last = pf_alloc_trace () ?pf_free_mib () :0 ; 2466pf_mark ("init: start (chunk, then the sign tables)" ,tr_last ); 2467#if defined(STRATA_GPU_METAL ) 2468 (void )wt ; (void )src ; (void )cache ; (void )host_res ; (void )stream ; (void )borrow ; 2469 (void )borrow_bytes ; 2470m .T = chunk > 0 ?chunk :1 ; 2471return strata::metal_engine::window_ensure (g ,ss ,ss .qsa_states [ss .qsa_primary ()].max_cells ,err ); 2472#endif 2473m .wt = & wt ;m .g = & g ;m .ss = & ss ;m .src = src ;m .cache = cache ;m .host_res = host_res ; 2474m .T = chunk ;m .cs = (cudaStream_t )stream ;m .stats = & stats_ ; 2475if (g .n_embd != N || g .hc != HC || g .hc_lr != LR || g .n_expert < 1 || ss .k != K ) { 2476err = "prefill: geometry differs from the artifact's" ;return false; 2477 } 2478 {// a native pack's experts: this path's expert buffers and products (and so their Hadamard rotations) are 2479// N wide in and 640 wide in the middle; the sign vectors are looked up at the layout's own widths 2480const strata::kernels::cpu::ExpertLayout & lay = strata::kernels::cpu::expert_layout (); 2481m .latent = lay .native && !lay .fmt .empty ()&& lay .fmt [0 ].n_embd != (int64_t )N ; 2482if (m .latent ) {// latent MoE: stride-N attention, ELL-wide expert rows (the A part of W1 = A @ D.T) 2483m .lat_H = (int64_t )N ; 2484m .lat_ELL = lay .fmt [0 ].n_embd ; 2485m .lat_I = lay .fmt [0 ].n_ff ; 2486m .lat_G = 8 ; 2487m .lat_E = lay .n_expert ; 2488for (size_t l = 1 ;l < lay .fmt .size ();++ l ) 2489if (lay .fmt [l ].n_embd != m .lat_ELL || lay .fmt [l ].n_ff != m .lat_I ) { 2490err = "prefill latent: layer " + std::to_string (l )+ "'s experts differ from layer 0's" ; 2491return false; 2492 } 2493const char * dense = std::getenv ("STRATA_LATENT_DENSE" ); 2494if (dense == nullptr || dense [0 ]== 0 ) { 2495err = "prefill latent: the latent layout needs STRATA_LATENT_DENSE=<latent_dense_q8.bin>" ; 2496return false; 2497 } 2498if (!m .lat_d .open (dense ,g .n_layers ,m .lat_G ,m .lat_H ,m .lat_ELL ,err )) { 2499err = "prefill latent dense: " + err ; 2500return false; 2501 } 2502m .lat_fmt = m .lat_d .fmt ();// Q4DU: every D/U kernel call below derives from it 2503const char * apack = std::getenv ("STRATA_LATENT_A" ); 2504if (apack == nullptr || apack [0 ]== 0 ) { 2505err = "prefill latent: the latent layout needs STRATA_LATENT_A=<latent_fp4_pack/experts.bin>" ; 2506return false; 2507 } 2508 {// labels.bin beside the A pack: one int32 group label per (layer, expert), rows of E 2509 std::string lp = apack ; 2510const size_t slash = lp .find_last_of ('/' ); 2511lp = slash == std::string::npos ? std::string ("labels.bin" ) :lp .substr (0 ,slash + 1 )+ "labels.bin" ; 2512 std::FILE * lf = std::fopen (lp .c_str (),"rb" ); 2513if (lf == nullptr ) {err = "prefill latent: " + lp + " missing" ;return false; } 2514m .lat_labels .resize ((size_t )g .n_layers * (size_t )m .lat_E ); 2515const size_t got = std::fread (m .lat_labels .data (),sizeof (int32_t ),m .lat_labels .size (),lf ); 2516 std::fclose (lf ); 2517if (got != m .lat_labels .size ()) {err = "prefill latent: " + lp + " is too small" ;return false; } 2518for (const int32_t v :m .lat_labels ) 2519if (v < 0 || v >=m .lat_G ) {err = "prefill latent: bad group label " + std::to_string (v );return false; } 2520 } 2521 } 2522for (size_t l = 0 ;lay .native && !m .latent && l < lay .fmt .size ();++ l ) 2523if (lay .fmt [l ].n_embd != N || lay .fmt [l ].n_ff != kFF ) { 2524err = "prefill: layer " + std::to_string (l )+ "'s experts are " + std::to_string (lay .fmt [l ].n_embd )+ 2525" x " + std::to_string (lay .fmt [l ].n_ff )+ ", not the artifact's 2560 x 640" ; 2526return false; 2527 } 2528// APR: the sign vectors on this device, once (hadamard_device_signs takes a mutex and, the first time per 2529// device, cudaMallocs its copy): run_impl reads m.had_sx / m.had_sh 2530m .had_sx .assign (lay .native ?lay .fmt .size () :0 ,nullptr ); 2531m .had_sh .assign (m .had_sx .size (),nullptr ); 2532for (size_t l = 0 ;l < m .had_sx .size ();++ l ) { 2533if (lay .fmt [l ].had_gu ) 2534m .had_sx [l ]= strata::kernels::hadamard_device_signs (lay .fmt [l ].gu_signs , (int )lay .fmt [l ].n_embd ); 2535if (lay .fmt [l ].had_d ) 2536m .had_sh [l ]= strata::kernels::hadamard_device_signs (lay .fmt [l ].d_signs , (int )lay .fmt [l ].n_ff ); 2537 } 2538 } 2539cudaGetDevice (& m .device ); 2540if (stage_le_ < 0 )stage_le_ = g .n_layers ; 2541if (stage_lb_ < 0 || stage_lb_ >=stage_le_ || stage_le_ > g .n_layers || (stage_le_ < g .n_layers )!= (next_ != nullptr )) { 2542err = "prefill: the stage's layer range is wrong" ; 2543return false; 2544 } 2545// the CPU share's staged-chunk limit, before the ring is sized below (a caller that sizes loans first armed it) 2546arm_cpu_share (cpu_pool_ != nullptr ); 2547for (int b = 0 ;next_ != nullptr && b < 2 ;++ b ) 2548if (!m .hand [b ]&& cudaHostAlloc ((void ** )& m .hand [b ], (size_t )chunk * D * 4 ,cudaHostAllocPortable )!= cudaSuccess ) { 2549err = "prefill: the layer split's hand-off buffers" ; 2550return false; 2551 } 2552if (next_ != nullptr && handoff_pipe_pieces ()> 0 && m .hand_pieces == 0 ) {// events only: no device memory 2553bool ok = true; 2554auto make = [](cudaEvent_t & e ) {return e != nullptr || cudaEventCreateWithFlags (& e ,cudaEventDisableTiming )== cudaSuccess ; }; 2555for (int b = 0 ;b < 2 ;++ b ) {// (a retry after a failed init keeps the events it made) 2556ok = ok && make (m .hand_done [b ]); 2557for (int i = 0 ;ok && i < handoff_pipe_pieces ();++ i )ok = make (m .hand_ev [b ][i ]); 2558 } 2559if (!ok ) {err = "prefill: the layer split's hand-off events (STRATA_HANDOFF_PIPE)" ;return false; } 2560m .hand_pieces = handoff_pipe_pieces (); 2561 } 2562if (m .tok_dev == nullptr ) { 2563if (const cudaError_t e = cudaMalloc ((void ** )& m .tok_dev , (size_t )chunk * sizeof (int32_t ));e != cudaSuccess ) { 2564err = std::string ("prefill: the token id buffer (" )+ cudaGetErrorString (e )+ ")" ; 2565return false; 2566 } 2567m .owned .push_back (m .tok_dev ); 2568m .tok_host .resize ((size_t )chunk ); 2569m .tok_up .init ((size_t )chunk ); 2570 } 2571if (m .latent && m .lat_labels_dev == nullptr ) {// the group labels, once per session 2572const size_t lb = m .lat_labels .size ()* sizeof (int32_t ); 2573if (cudaMalloc ((void ** )& m .lat_labels_dev ,lb )!= cudaSuccess || 2574cudaMemcpy (m .lat_labels_dev ,m .lat_labels .data (),lb ,cudaMemcpyHostToDevice )!= cudaSuccess ) { 2575 (void )cudaGetLastError (); 2576err = "prefill latent: the labels device buffer could not be had" ; 2577return false; 2578 } 2579m .owned .push_back (m .lat_labels_dev ); 2580 } 2581if (m .latent && m .lat_d_dev == nullptr ) {// a session-shared pair when present (latent_share.hpp), else owned below 2582m .lat_d_dev = strata::core::latent_shared_d (); 2583m .lat_u_dev = strata::core::latent_shared_u (); 2584if (m .lat_d_dev != nullptr ) { 2585const auto & shared = strata::core::latent_shared (); 2586m .lat_first_layer = shared .first_layer ; 2587const int64_t end_layer = shared .end_layer < 0 ?g .n_layers :shared .end_layer ; 2588if (m .lat_first_layer > stage_lb_ || end_layer < stage_le_ ) { 2589err = "prefill latent: shared D/U range does not cover this stage" ; 2590return false; 2591 } 2592 } 2593 } 2594if (m .latent && m .lat_d_dev == nullptr ) {// no shared pair: one owned copy, uploaded once per session 2595const uint64_t db = (uint64_t )g .n_layers * m .lat_d .d_bytes (); 2596const uint64_t ub = (uint64_t )g .n_layers * m .lat_d .u_bytes (); 2597if (cudaMalloc ((void ** )& m .lat_d_dev ,db )!= cudaSuccess || 2598cudaMalloc ((void ** )& m .lat_u_dev ,ub )!= cudaSuccess ) { 2599const cudaError_t ce = cudaGetLastError (); 2600if (m .lat_d_dev ) {cudaFree (m .lat_d_dev );m .lat_d_dev = nullptr ; } 2601if (m .lat_u_dev ) {cudaFree (m .lat_u_dev );m .lat_u_dev = nullptr ; } 2602err = "prefill latent: the D/U device buffers could not be had (" + 2603 std::string (ce != cudaSuccess ?cudaGetErrorString (ce ) :"ok" )+ ", bytes=" + std::to_string (db + ub )+ ")" ; 2604return false; 2605 } 2606bool up = true; 2607for (int64_t l = 0 ;up && l < g .n_layers ;++ l ) { 2608if (cudaMemcpy (m .lat_d_dev + (size_t )l * m .lat_d .d_bytes (),m .lat_d .d (l ),m .lat_d .d_bytes (), 2609cudaMemcpyHostToDevice )!= cudaSuccess || 2610cudaMemcpy (m .lat_u_dev + (size_t )l * m .lat_d .u_bytes (),m .lat_d .u (l ),m .lat_d .u_bytes (), 2611cudaMemcpyHostToDevice )!= cudaSuccess ) 2612up = false; 2613 } 2614m .owned .push_back (m .lat_d_dev );// pushed only after both mallocs held; the failure path freed them above 2615m .owned .push_back (m .lat_u_dev ); 2616if (!up ) {err = "prefill latent: the D/U upload failed" ;return false; } 2617 } 2618if (cudaStreamCreateWithFlags (& m .copy ,cudaStreamNonBlocking )!= cudaSuccess ) {err = "prefill: copy stream" ;return false; } 2619const size_t T = (size_t )chunk ; 2620m .T_max = chunk ; 2621m .borrowed = borrow != nullptr ; 2622m .borrow_spill = m .borrowed && borrow_spill ; 2623bool ok = true; 2624// one-time: events, the stager, the host buffers (for the largest chunk), the identity page table 2625for (int i = 0 ;i < ring_cap ();++ i ) { 2626if (cudaEventCreateWithFlags (& m .copied [i ],cudaEventDisableTiming )!= cudaSuccess )ok = false; 2627if (cudaEventCreateWithFlags (& m .used [i ],cudaEventDisableTiming )!= cudaSuccess )ok = false; 2628 } 2629if (!m .stager ) { 2630m .stager = std::make_unique < Stager > (); 2631const int hw = (int ) std::thread::hardware_concurrency (); 2632const char * stv = std::getenv ("STRATA_STAGER_THREADS" );// D-5: the host copy threads of unpinned blobs 2633// A GGUF read in place (UD-Q4_K_XL beyond its RAM budget): most of a chunk's blobs are page faults on the 2634// SSD, so the copies need many reads in flight - 32 threads and a 128-deep ring read a 4K chunk in 29 s 2635// instead of 71 s on an RTX 5070 / NVMe PC (4 threads, 16 deep: the defaults, kept for every other source) 2636bool files = false; 2637for (int64_t l = 0 ;src != nullptr && !files && l < g .n_layers ;++ l ) 2638for (int64_t e = 0 ; !files && e < g .n_expert ;++ e )files = src -> transient (l ,e ); 2639// #1353: ... but a source answers transient() for every blob it copies out of the GGUF, including the ones whose 2640// pages are already in the page cache (a Q8 pack on a big-RAM box with a warm cache). Those copies are memcpy 2641// from RAM, where 32 threads and a 128-deep ring ran 4-7x slower than the defaults. So ask the OS: the SSD 2642// profile only when fewer than 90% of a sample of the blobs' pages are resident (-1: it cannot tell, keep it). 2643if (files && !stv ) { 2644const char * ev = std::getenv ("STRATA_STAGER_SSD" );// 1 / 0: force the profile (A/B, support) 2645if (ev != nullptr && ev [0 ]!= '\0' )files = ev [0 ]!= '0' ; 2646else if (const double warm = src -> cached_share (256 );warm >=0.9 ) { 2647files = false; 2648 std::fprintf (stderr ,"prefill: the GGUF experts are %.0f%% in the page cache; the stager takes the RAM profile\n" ,warm * 100.0 ); 2649 } 2650 } 2651const int threads = stv ? std::clamp (std::atoi (stv ),1 ,32 ) :files ?32 : std::max (2 , std::min (4 ,hw /4 )); 2652if (files && std::getenv ("STRATA_STAGER_RING" )== nullptr )m .stager -> kRing = 4 * threads ; 2653// pp-opt: with files, each thread claims runs of neighbouring blobs and reads them as one request (copy_blobs); 2654// STRATA_STAGER_BATCH=1 is the A/B arm (one blob per request, as before) 2655 { 2656const char * bv = std::getenv ("STRATA_STAGER_BATCH" ); 2657const int want = bv ? std::atoi (bv ) :files ?8 :1 ; 2658m .stager -> batch = std::clamp (want ,1 ,Stager ::kMaxBatch ); 2659 } 2660if (!m .stager -> init ((size_t )MAXBLOB (),threads ))ok = false; 2661m .stager -> batch = std::min (m .stager -> batch ,m .stager -> kRing ); 2662 } 2663pf_mark ("init: stager ring (pinned host buffers)" ,tr_last , (uint64_t )m .stager -> kRing * (uint64_t )MAXBLOB ()); 2664// STRATA_PREFILL_LM_NEXTFILES=<ring>: layer-major's two stagers on the last stage (the one that reads a short prompt 2665// whole), created here so no prompt pays for their pinned rings; 2666// STRATA_PREFILL_LM_NEXTFILES_THREADS (default 8) each, sleeping waits 2667if (const char * nf = std::getenv ("STRATA_PREFILL_LM_NEXTFILES" );m .latent && next_ == nullptr && nf != nullptr && std::atoll (nf )> 0 ) { 2668const char * tv = std::getenv ("STRATA_PREFILL_LM_NEXTFILES_THREADS" ); 2669const int nthreads = tv ? std::clamp (std::atoi (tv ),1 ,32 ) :8 ; 2670for (int k = 0 ;k < 2 ;++ k ) { 2671if (m .lm_stager [k ])continue ; 2672m .lm_stager [k ]= std::make_unique < Stager > (); 2673m .lm_stager [k ]-> kRing = (int ) std::clamp < long long > (std::atoll (nf ),2 ,1024 ); 2674m .lm_stager [k ]-> batch = m .stager -> batch ; 2675m .lm_stager [k ]-> sleep = true; 2676if (!m .lm_stager [k ]-> init ((size_t )MAXBLOB (),nthreads )) {m .lm_stager [k ].reset ();continue ; } 2677m .lm_stager [k ]-> batch = std::min (m .lm_stager [k ]-> batch ,m .lm_stager [k ]-> kRing ); 2678 } 2679 } 2680if (!m .warmer && src != nullptr && src -> warms ()) { 2681const char * wv = std::getenv ("STRATA_PREFILL_WARM" ); 2682if (wv != nullptr && std::atoi (wv )!= 0 ) { 2683m .warmer = std::make_unique < PrefillWarmer > (src ); 2684m .warm_prev .assign ((size_t )g .n_layers , {}); 2685 std::fprintf (stderr ,"prefill: STRATA_PREFILL_WARM=1: the per-layer walk warms this layer's and the next " 2686"layer's file-tier experts\n" ); 2687 } 2688 } 2689m .steps_host .resize (T * strata::kernels::kStepCount ); 2690m .steps_up .init (T * strata::kernels::kStepCount ); 2691m .ids_host .resize (T * K );m .slot_host .resize (T * K );m .src_host .resize (T * K );m .cnt .resize (m .g -> n_expert );m .off .resize (m .g -> n_expert + 1 ); 2692if (m .latent ) {m .lat_tokx_host .resize (T * K );m .lat_idsx_host .resize (T * K );m .lat_idsp_host .resize (T * K ); } 2693 { 2694// the routing tables, the MMQ group bounds (bounds_ints: with STRATA_PF_GROUP_SCRATCH, the sub-ranges' tables too); 2695// STRATA_MMQ_WS: the in-place offsets (n_expert int64) and the weight-stationary layers' chunks (4 int32 each, 2696// 16-byte aligned) 2697const size_t need = 3 * T * K + bounds_ints (m .g -> n_expert )+ 2698 (ws::mode ()!= 0 ?2 * (size_t )m .g -> n_expert + 4 * ws::max_chunks ((int64_t )T * K ,m .g -> n_expert )+ 3 :0 ); 2699const char * gc = std::getenv ("STRATA_GROUP_COPY" ); 2700if (m .grp_n < need && !(gc && gc [0 ]== '1' )) { 2701if (m .grp_host )cudaFreeHost (m .grp_host ); 2702m .grp_host = m .grp_dev = nullptr ; 2703m .grp_n = m .grp_tk = 0 ; 2704void * h = nullptr ,* d = nullptr ; 2705if (!force_pageable ()&& 2706cudaHostAlloc (& h ,need * 4 ,cudaHostAllocMapped | (core::peer_portable () ?cudaHostAllocPortable :0 ))== cudaSuccess && 2707cudaHostGetDevicePointer (& d ,h ,0 )== cudaSuccess ) { 2708m .grp_host = (int32_t * )h ; 2709m .grp_dev = (int32_t * )d ; 2710m .grp_n = need ; 2711m .grp_tk = T * K ; 2712 }else {// the copies, as before 2713if (h )cudaFreeHost (h ); 2714cudaGetLastError (); 2715 } 2716 } 2717 } 2718pf_mark ("init: routing tables (pinned, mapped)" ,tr_last ); 2719for (int b = 0 ;b < 2 ;++ b ) { 2720if (!m .ple_emb_host [b ]&& 2721 (force_pageable ()|| cudaHostAlloc ((void ** )& m .ple_emb_host [b ], (size_t )T * N * 4 ,cudaHostAllocDefault )!= cudaSuccess )) { 2722cudaGetLastError (); 2723m .ple_pageable [b ].resize (T * N );// pageable: the upload is staged before it returns 2724m .ple_emb_host [b ]= m .ple_pageable [b ].data (); 2725 } 2726if (!m .ple_copied [b ]&& cudaEventCreateWithFlags (& m .ple_copied [b ],cudaEventDisableTiming )!= cudaSuccess ) 2727ok = false; 2728m .ple_rows [b ].resize (T * strata::kernels::PLE_N_HEADS ); 2729if (ple_compact_on ()&& m .ple_raw_dev == nullptr && 2730cudaMalloc ((void ** )& m .ple_raw_dev , (size_t )T * strata::kernels::PLE_N_HEADS * strata::kernels::PLE_ROW_BYTES )!= cudaSuccess ) { 2731m .ple_raw_dev = nullptr ; 2732 (void )cudaGetLastError (); 2733 } 2734 } 2735// STRATA_PLE_COPY_STREAM: a stream of its own, not the expert copy stream - that one may hold a ring of blobs and 2736// waits on their slots' release, so a wait on it could idle the compute stream for longer than the DMA itself 2737if (ple_copy_stream_on ()&& m .ple_raw_dev != nullptr && 2738 ((!m .ple_copy && cudaStreamCreateWithFlags (& m .ple_copy ,cudaStreamNonBlocking )!= cudaSuccess )|| 2739 (!m .ple_raw_free && cudaEventCreateWithFlags (& m .ple_raw_free ,cudaEventDisableTiming )!= cudaSuccess ))) { 2740// an optional optimization: the raw rows go up on the compute stream as with STRATA_PLE_COMPACT alone 2741if (m .ple_copy ) { (void )cudaStreamDestroy (m .ple_copy );m .ple_copy = nullptr ; } 2742 (void )cudaGetLastError (); 2743 std::fprintf (stderr ,"prefill: STRATA_PLE_COPY_STREAM=1: the upload stream could not be created, the PLE rows go up on the compute stream\n" ); 2744 } 2745if (ss .qsa_states [ss .qsa_primary ()].kv_mode == 1 ) {// KV streaming: the staging pool's identity page table 2746const int64_t pages = ss .qsa_states [ss .qsa_primary ()].n_pages ; 2747 std::vector < int32_t > ident ((size_t )pages ); 2748for (int64_t i = 0 ;i < pages ;++ i )ident [(size_t )i ]= (int32_t )i ; 2749if (cudaMalloc ((void ** )& m .ident_table ,ident .size ()* 4 )!= cudaSuccess || 2750cudaMemcpy (m .ident_table ,ident .data (),ident .size ()* 4 ,cudaMemcpyHostToDevice )!= cudaSuccess ) 2751ok = false; 2752else 2753m .owned .push_back (m .ident_table ); 2754 } 2755if (!ok ) {err = "prefill: host buffers or events for a chunk of " + std::to_string (chunk )+ " tokens" ;return false; } 2756#if defined(STRATA_USE_HIP )&& defined(__linux__ ) 2757// integrated gfx11 (kfd_quiet.hpp, LOAD): the device buffers the first prompt made at its first layer (the int8 experts' q8_1 2758// activations for a whole chunk, their group record; the K/V copy stream with STRATA_KV_PREFETCH=1) are made here, during 2759// the load, so the first request allocates nothing while its kernels run. The same buffers and sizes the prompt path makes 2760// (it keeps them while a chunk fits: fr_xq_rows >= T); a failure here is not an error, the prompt path then tries as before. 2761if (strata::core::kfd_quiet::load_moves ().first_prompt_buffers && T > 0 ) { 2762if (m .fr_xq == nullptr && cudaMalloc (& m .fr_xq ,T * (size_t ) (N /32 )* 36 )== cudaSuccess )m .fr_xq_rows = (int64_t )T ; 2763else if (m .fr_xq == nullptr ) {m .fr_xq = nullptr ; (void )cudaGetLastError (); } 2764if (m .i8_rec == nullptr && cudaMalloc ((void ** )& m .i8_rec , strata::prefill::i8grp::kRecBytes )!= cudaSuccess ) { 2765m .i8_rec = nullptr ; 2766 (void )cudaGetLastError (); 2767 } 2768if (const char * kp = std::getenv ("STRATA_KV_PREFETCH" );kp != nullptr && std::atoi (kp )!= 0 ) { 2769if ((!m .kv_copy && cudaStreamCreateWithFlags (& m .kv_copy ,cudaStreamNonBlocking )!= cudaSuccess )|| 2770 (!m .kv_released && cudaEventCreateWithFlags (& m .kv_released ,cudaEventDisableTiming )!= cudaSuccess )|| 2771 (!m .kv_ready && cudaEventCreateWithFlags (& m .kv_ready ,cudaEventDisableTiming )!= cudaSuccess )) 2772 (void )cudaGetLastError ();// the request makes what is missing, and says so if it cannot 2773 } 2774 } 2775// and (11-15) the CPU prompt share's pinned buffers, only where the share is armed (STRATA_PREFILL_CPU_SHARE: off by default on 2776// this class): the activations, the rows and their scales at the sizes the first CPU-sharing layer asks for, for the largest chunk 2777// that shares (below cpu_share_max(), the floor of the full stream on an integrated GPU). The prompt path keeps a buffer that is 2778// large enough and regrows one that is not, as before; a failure here leaves it to the prompt path. 2779if (strata::core::kfd_quiet::load_moves ().cpu_share_buffers && T > 0 && cpu_pool_ != nullptr && cpu_share_on ()) { 2780const size_t ts = std::min < size_t > (T , (size_t ) std::max < int64_t > (cpu_share_max (),1 )); 2781const size_t rows = (size_t ) std::min < int64_t > ((int64_t )ts * K , (int64_t ) strata::kernels::cpu::MAXT * g .n_expert ); 2782auto pin = [](float *& p ,size_t & n ,size_t want ) { 2783if (p != nullptr )return ; 2784if (cudaHostAlloc ((void ** )& p ,want * sizeof (float ),cudaHostAllocDefault )== cudaSuccess ) { 2785n = want ; 2786 }else { 2787p = nullptr ; 2788n = 0 ; 2789 (void )cudaGetLastError (); 2790 } 2791 }; 2792pin (m .cpu_x ,m .cpu_x_n ,ts * N ); 2793pin (m .cpu_rows ,m .cpu_rows_n ,rows * N ); 2794const bool ones_new = m .cpu_ones == nullptr ; 2795pin (m .cpu_ones ,m .cpu_ones_n ,rows ); 2796if (ones_new && m .cpu_ones != nullptr ) std::fill (m .cpu_ones ,m .cpu_ones + rows ,1.0f ); 2797 } 2798#endif 2799pf_mark ("init: host buffers, PLE rows, identity table" ,tr_last ); 2800Alloc o ; 2801o .base = (uint8_t * )borrow ; 2802o .cap = borrow_bytes ; 2803o .spill = m .borrow_spill ; 2804o .owned = & m .owned ; 2805 { 2806uint16_t * gs = o .take < uint16_t > ((size_t )GEMM_SCRATCH ,ok ); 2807void * ws = o .take < uint8_t > (GEMM_WS ,ok ); 2808// STRATA_DEQUANT_SIDE: the second dequant scratch (counted by bytes_needed_impl, retaken by relayout) 2809uint16_t * gs2 = gemm_dequant_side () ?o .take < uint16_t > ((size_t )GEMM_SCRATCH ,ok ) :nullptr ; 2810if (!ok ) {err = "prefill: GEMM scratch does not fit" ;return false; } 2811if (!m .gemm .init_external (stream ,gs ,GEMM_SCRATCH ,ws ,GEMM_WS ,err ))return false; 2812 { std::string side_err ;if (!m .gemm .set_dequant_side (gs2 ,side_err )) std::fprintf (stderr ,"prefill: STRATA_DEQUANT_SIDE=1 not taken (%s): the dense weights are dequantized in front of their GEMMs\n" ,side_err .c_str ()); } 2813// this stage's device decides, once, here (init runs on the stage's own device): its gr_* kernels write the 2814// image its GEMMs read, and set_act_f16 writes that device's symbol 2815const core::OnDevice on_stage (m .device ); 2816m .f16_io = prompt_f16 (); 2817m .gemm .set_f16_io (m .f16_io ); 2818set_act_f16 (m .f16_io ); 2819static const bool f16_range = std::getenv ("STRATA_F16_RANGE" )!= nullptr ;// what reaches FP16's range 2820if (f16_range ) {set_f16_range (true);gemm_set_f16_range (true); } 2821// the hyper-connection's xn16 straight as the FP16 the tensor-core GEMM reads (its two readers then skip the 2822// conversion pass; the same values): STRATA_XN_F16=0 keeps the BF16 image 2823static const bool xn_env = [] {const char * e = std::getenv ("STRATA_XN_F16" );return e == nullptr || e [0 ]!= '0' ; }(); 2824m .xn_f16 = xn_env && !m .f16_io && m .gemm .bf16_converts_x (); 2825 } 2826pf_mark ("init: GEMM scratch + workspace (Alloc takes so far)" ,tr_last ,o .tr_asked ); 2827if (!carve (T ,& o )) { 2828size_t fb = 0 ,tb = 0 ; 2829cudaMemGetInfo (& fb ,& tb ); 2830 (void )cudaGetLastError (); 2831err = "prefill: device buffers for a chunk of " + std::to_string (chunk )+ " tokens do not fit (" + 2832 std::to_string (fb >>20 )+ " of " + std::to_string (tb >>20 )+ " MiB free at the failure; " + 2833 std::to_string (o .used >>20 )+ " MiB taken, the failing buffer wanted " + 2834 std::to_string (o .failed_bytes >>20 )+ " MiB)" ; 2835return false; 2836 } 2837pf_mark ("init: carve (all buffers of the chunk)" ,tr_last ,o .tr_asked ); 2838if (pf_alloc_trace ()) 2839 std::fprintf (stderr ,"prefill alloc trace: Alloc takes: %llu cudaMallocs, asked %lld MiB, free fell %lld MiB over them (bytes_needed counts %lld MiB for this chunk's own buffers; o.used %lld MiB)\n" , 2840 (unsigned long long )o .tr_n , (long long ) (o .tr_asked >>20 ), (long long )o .tr_drop , 2841 (long long ) (Prefill ::bytes_needed (g ,ss ,chunk ,src != nullptr ) >>20 ), (long long ) (o .used >>20 )); 2842 {int wd = 0 ;if (cudaGetDevice (& wd )== cudaSuccess )warm_gemm_libraries (wd );else (void )cudaGetLastError (); } 2843pf_mark ("init: warm_gemm_libraries (BLAS handles, workspaces)" ,tr_last ); 2844return true; 2845} 2846 2847// Every device buffer of a chunk of T tokens, from the Alloc `alloc` (after the GEMM scratch and workspace): `init` 2848// once, and `relayout` for a request's own chunk. The order is `bytes_needed`'s. 2849bool Prefill ::carve (size_t T ,void * alloc ) { 2850Impl & m = * impl_ ; 2851Alloc & o = * static_cast < Alloc *> (alloc ); 2852const core::ModelGeometry & g = * m .g ; 2853 core::SessionState & ss = * m .ss ; 2854bool ok = true; 2855m .emb = o .take < float > (T * N ,ok );m .R = o .take < float > (T * D ,ok ); 2856m .xn = gr_unfused () ?o .take < float > (T * D ,ok ) :nullptr ;// F-1: not needed (gr_mix_r reads R) 2857m .grs = o .take < float > (T * HC ,ok ); 2858const bool hcr = pf_hc_region ();// STRATA_PF_HC_REGION: xn16 / lo / lo16 / gated (and their _lo) are taken in the region 2859if (!hcr ) { 2860m .xn16 = o .take < uint16_t > (T * (D + (hc_pad () ?XN_PAD :0 )),ok );m .lo = o .take < float > (T * LR ,ok );m .lo16 = o .take < uint16_t > (T * LR ,ok ); 2861m .gated = o .take < float > (T * D ,ok ); 2862 } 2863m .inj = o .take < float > (T * HC ,ok ); 2864m .mixed = o .take < float > (T * N ,ok );m .mixed_bf = o .take < uint16_t > (T * N ,ok ); 2865m .mixed_h = o .take < uint16_t > (T * N ,ok ); 2866// Embedding rows are dead after gr_broadcast on m.cs; subsequent half outputs use the same stream. 2867m .bo = m .emb ; 2868if (!hcr && bf16x2_hc (m .f16_io )) {m .xn16_lo = o .take < uint16_t > (T * D ,ok );m .lo16_lo = o .take < uint16_t > (T * LR ,ok ); } 2869if (bf16x2 (m .f16_io ))m .mixed_bf_lo = o .take < uint16_t > (T * N ,ok ); 2870m .steps_dev = o .take < int32_t > (T * strata::kernels::kStepCount ,ok ); 2871 strata::kernels::QsaShapes s = core::qsa_shapes (g ); 2872m .cap = strata::kernels::qsa_selection_width (strata::kernels::kTopkMaxCells ,s ); 2873m .max_blocks = ss .qsa_states [ss .qsa_primary ()].max_cells /s .idx_block + 2 ; 2874 { 2875// one region for the attention half's and the MoE half's scratch (see gdn_set_bytes) 2876const bool fz = fused_layout (T ,m .src != nullptr ); 2877m .fused_bufs = fz ; 2878const MoeBufs mb = moe_bufs (T ,m .g -> n_expert ,fz ,m .tail_req ); 2879const uint64_t region = std::max ({gdn_set_bytes (T ),qsa_set_bytes (T ,m .cap ,m .max_blocks ,m .sel_batch , 2880m .attn_batch ,s ),moe_set_bytes (T ,m .g -> n_expert ,fz ,m .tail_req ), 2881hcr ?hc_set_bytes (T ,m .f16_io ) : (uint64_t )0 }); 2882uint8_t * base = o .take < uint8_t > ((size_t )region ,ok ); 2883// No region: the sub-allocators below would each cudaMalloc their share (hundreds of MiB) on a card that has just 2884// shown it has no room, and leave those buffers in `owned`. The failure is reported by the caller. 2885if (base == nullptr )return false; 2886m .region = base ; 2887m .region_bytes = region ; 2888Alloc a ; 2889a .base = base ;a .cap = region ;a .owned = & m .owned ; 2890m .qkv = a .take < float > (T * C ,ok );m .z = a .take < float > (T * ZV ,ok );m .ab = a .take < float > (T * 2 * HV ,ok ); 2891m .gate = a .take < float > (T * HV ,ok );m .beta = a .take < float > (T * HV ,ok );m .hbuf = a .take < float > (T * C ,ok ); 2892m .y = a .take < float > (T * ZV ,ok );m .y_h = a .take < uint16_t > (T * (ZV + (pf_pad () ?ZV_PAD :0 )),ok ); 2893Alloc b ; 2894b .base = base ;b .cap = region ;b .owned = & m .owned ; 2895m .Kc = b .take < float > (T * kKvW ,ok );m .Vc = b .take < float > (T * kKvW ,ok );m .Qf = b .take < float > (T * kQFull ,ok ); 2896m .q = b .take < float > (T * kQW ,ok );m .idx_raw = b .take < float > (T * kIdxK ,ok );m .q_idx = b .take < float > (T * kIdxQW ,ok ); 2897m .attn = b .take < float > (T * ZV ,ok );m .attn_h = b .take < uint16_t > (T * (ZV + (pf_pad () ?ZV_PAD :0 )),ok ); 2898m .sel_ids = b .take < int32_t > (T * (size_t )m .cap ,ok ); 2899m .sel_scores = b .take < float > ((size_t )m .sel_batch * (size_t )m .max_blocks ,ok ); 2900m .attn_scratch = b .take < float > ((size_t )m .attn_batch * strata::kernels::qsa_decode_attn_scratch_floats (m .cap ,s ),ok ); 2901Alloc c ; 2902c .base = base ;c .cap = region ;c .owned = & m .owned ; 2903m .logits = c .take < float > (T * m .g -> n_expert ,ok );m .w = c .take < float > (T * K ,ok );m .ids = c .take < int32_t > (T * K ,ok ); 2904m .slot_dev = c .take < int32_t > (T * K ,ok );m .src_dev = c .take < int32_t > (T * K ,ok ); 2905const MmqPlan & mp = mmq_plan (); 2906const size_t Tf = (size_t ) strata::prefill::fp16_buf_tokens ((int64_t )T ,fz ,stream_all_min ());// (the tail below the floor in a fused layout: fp16_rows_rule.hpp) 2907m .Xs = fp16_bufs (mp ) ?c .take < uint16_t > (Tf * K * N ,ok ) :nullptr ; 2908m .GU = c .take < float > (mb .gu ,ok ); 2909m .Hh = fp16_bufs (mp ) ?c .take < uint16_t > (Tf * K * kFF ,ok ) :nullptr ; 2910m .Dm = c .take < float > (T * K * N ,ok ); 2911m .sgate = c .take < float > (T * kFF ,ok );m .sup = c .take < float > (T * kFF ,ok );m .sh_h = c .take < uint16_t > (T * kFF ,ok ); 2912m .shared = c .take < float > (T * N ,ok );m .sg = c .take < float > (T ,ok ); 2913if (mp .any ) { 2914m .Xq = c .take < uint8_t > (mb .xq ,ok ); 2915m .H = c .take < float > (mb .h ,ok ); 2916m .H_bytes = mb .h * sizeof (float ); 2917m .Hq = c .take < uint8_t > (mb .hq ,ok ); 2918m .Xscale = c .take < float > (T * K ,ok );m .Hscale = c .take < float > (T * K ,ok ); 2919m .grp_tail = c .take < float > (MMQ_GROUP * 4 ,ok ); 2920m .row_sd = c .take < float > (T * K ,ok ); 2921// APR: the rotated expert input (only for Hadamard-folded packs) 2922m .Xr = strata::kernels::cpu::hadamard_spec ().any () ?c .take < float > (T * N ,ok ) :nullptr ; 2923 } 2924if (m .latent ) {// latent MoE buffers (counted in moe_set_bytes and so in the region) 2925m .xl = c .take < float > (T * (size_t )m .lat_G * (size_t )m .lat_ELL ,ok ); 2926m .xlq = c .take < uint8_t > (T * (size_t )m .lat_G * ((size_t )m .lat_ELL /32 * 36 ),ok ); 2927m .yl = c .take < float > (T * K * (size_t )m .lat_ELL ,ok ); 2928m .ylq = c .take < uint8_t > (T * K * ((size_t )m .lat_ELL /32 * 36 ),ok ); 2929m .tok = c .take < int32_t > (T * K ,ok ); 2930m .tok_ix = c .take < int32_t > (T * K ,ok ); 2931m .ids_p = c .take < int32_t > (T * K ,ok ); 2932m .lat_xq = c .take < uint8_t > (T * (N /32 )* 36 ,ok ); 2933m .lat_n = c .take < int32_t > (2 ,ok );// [0] the grouped kernels' group count, [1] latent_plan_rows' all entries 2934m .lat_scratch = c .take < uint8_t > ( 2935 strata::kernels::native_expert_scratch_bytes ((int64_t ) (T * K ),m .lat_I ),ok ); 2936m .lat_gp = c .take < unsigned long long > (LAT_GROUP ,ok ); 2937m .lat_gs = c .take < int32_t > (LAT_GROUP + 1 ,ok ); 2938m .lat_gcd = c .take < int32_t > (LAT_GROUP ,ok ); 2939m .lat_hbuf = lat_fused_q3k_on () ?c .take < uint8_t > ((size_t )T * K * 800 ,ok ) :nullptr ; 2940m .lat_gxl = c .take < int32_t > (T * K ,ok ); 2941m .lat_gdst = c .take < int32_t > (T * K ,ok ); 2942 } 2943if (hcr ) {// STRATA_PF_HC_REGION: the hyper-connection read's set, from the region's start like the others 2944Alloc h ; 2945h .base = base ;h .cap = region ;h .owned = & m .owned ; 2946m .xn16 = h .take < uint16_t > (T * (D + (hc_pad () ?XN_PAD :0 )),ok );m .lo = h .take < float > (T * LR ,ok ); 2947m .lo16 = h .take < uint16_t > (T * LR ,ok );m .gated = h .take < float > (T * D ,ok ); 2948if (bf16x2_hc (m .f16_io )) {m .xn16_lo = h .take < uint16_t > (T * D ,ok );m .lo16_lo = h .take < uint16_t > (T * LR ,ok ); } 2949 } 2950if (base == nullptr )ok = false; 2951 } 2952for (int i = 0 ;i < DQ ;++ i ) {m .dq_gu [i ]= o .take < uint16_t > (kFF2 * kEmbd ,ok );m .dq_d [i ]= o .take < uint16_t > (kEmbd * kFF ,ok ); } 2953if (mmq_plan ().any ) { 2954const MmqPlan & mp = mmq_plan (); 2955const size_t ids_rows = mmq_ids_rows (T ); 2956if (ids_rows == 0 )ok = false; 2957m .ids_identity = o .take < int32_t > (ids_rows ,ok );// (its over-read slack: mmq_ids_rows) 2958m .bounds_dev = o .take < int32_t > (bounds_ints (m .g -> n_expert ),ok ); 2959const size_t grp_n = m .latent ?LAT_GROUP :MMQ_GROUP ;// a latent pack batches LAT_GROUP experts here (STRATA_LATENT_MMQ) 2960m .grp_gu = o .take < uint8_t > (grp_n * mp .gu_max + MMQ_TAIL ,ok ); 2961m .grp_d = o .take < uint8_t > (grp_n * mp .d_max + MMQ_TAIL ,ok ); 2962if (ws::mode ()!= 0 ) {// STRATA_MMQ_WS: the offsets and chunks (bytes_needed_impl takes the same) 2963m .xoff_dev = o .take < int64_t > ((size_t )m .g -> n_expert ,ok ); 2964m .ws_chunks = (ws::Chunk * )o .take < int32_t > (4 * ws::max_chunks ((int64_t )T * K ,m .g -> n_expert ),ok ); 2965 } 2966// (written at every run's start, not here: when serving, these are live expert-cache slots until a request 2967// lends them - a write now would corrupt a resident expert) 2968if (!m .mmq_ctx )m .mmq_ctx = std::make_unique < mmq::Context > (); 2969 }else if (i8_wants_identity ()) { 2970const size_t ids_rows = mmq_ids_rows (T ); 2971if (ids_rows == 0 )ok = false; 2972m .ids_identity = o .take < int32_t > (ids_rows ,ok );// OWN-I8: the identity row table of the int8 groups (no MMQ buffers in this layout) 2973 } 2974if (m .latent && !mmq_plan ().any )// the latent walk's ent_dst needs the identity map even without MMQ 2975m .ids_identity = o .take < int32_t > (T * K ,ok ); 2976m .ring = ring_slots (T ); 2977const int nstage = stage_slots (T );// the staged walk may use STAGE_GRP of them 2978m .ring_rule = m .ring ;// the rule's ring: inside the region, because the loan was sized for it 2979m .ring_room = 0 ;// THE PROMPT ROOM's slots on top of it (set_ring_room), the lender's own bytes 2980m .ring_room_at = nstage ;// the room starts past the layout's staging buffers (stage_slots(T) of them) 2981// THE PROMPT ROOM (set_ring_room + set_ring_room_base): another device user's bytes - the MTP drafter's 512 2982// routed experts, which only the decode reads - pointed at as so many more ring slots for one prompt. The slots 2983// ARE those bytes: nothing is allocated, nothing is owned, nothing spills, and the last layout of this path 2984// keeps them, so a prompt takes them by moving `m.ring` alone (set_ring_room_active) and the lender's own bytes 2985// are never left out of VRAM. Never past ring_cap() (`copied`/`used` exist for i < ring_cap(), and the arrays 2986// are RING_MAX) and never past what the lender said it has (one slot is one max_blob). 2987if (ring_room_ > 0 && m .ring > STAGE && ring_room_base_ != nullptr ) { 2988const int64_t cap = std::min < int64_t > ((int64_t )ring_cap ()- m .ring_room_at , 2989 (int64_t ) (ring_room_bytes_ / (uint64_t )MAXBLOB ())); 2990const int64_t room = std::min < int64_t > ((int64_t )ring_room_ ,cap ); 2991if (room > 0 ) { 2992m .ring_room = (int )room ; 2993if (ring_room_active_ )m .ring = m .ring_room_at + (int )room ;// the room is this prompt's: the ring counts it 2994 } 2995 } 2996if (o .base == nullptr && nstage > 0 ) { 2997// OWNED buffers: the ring in ONE allocation. 384 separate 2.7 MiB cudaMallocs each round up to a 2 MiB page 2998// (~1.3 MiB a slot, ~0.5 GiB in all) that no count ever saw. A borrowed region keeps its per-slot layout (and 2999// so its price, `bytes_needed`: the loans' slot counts do not move). 3000uint8_t * ring_base = o .take < uint8_t > ((size_t )nstage * (size_t )MAXBLOB (),ok ); 3001for (int i = 0 ;ok && i < nstage ;++ i ) { 3002m .stage_dev [i ]= ring_base + (size_t )i * (size_t )MAXBLOB (); 3003m .stage_live [i ]= false; 3004m .used_of [i ]= i ; 3005 } 3006 }else { 3007for (int i = 0 ;i < nstage ;++ i ) { 3008m .stage_dev [i ]= o .take < uint8_t > ((size_t )MAXBLOB (),ok ); 3009m .stage_live [i ]= false;// a new buffer: nothing of an earlier layout to wait for 3010m .used_of [i ]= i ; 3011 } 3012 } 3013if (m .ring_room > 0 ) {// THE PROMPT ROOM's slots: the lender's bytes, at the lender's address, taken from nobody 3014for (int i = m .ring_room_at ;i < m .ring_room_at + m .ring_room ;++ i ) { 3015m .stage_dev [i ]= (uint8_t * )ring_room_base_ + (size_t ) (i - m .ring_room_at )* (size_t )MAXBLOB (); 3016m .stage_live [i ]= false;// the lender's bytes are live experts, not a staged blob 3017m .used_of [i ]= i ; 3018 } 3019 } 3020m .ple_emb = o .take < float > (T * N ,ok ); 3021m .ple_norm = o .take < float > ((size_t ) strata::kernels::NG_HC_DIM ,ok ); 3022take_stage (o ,ss ,s ,m .stage ,ok ); 3023m .T = (int64_t )T ; 3024m .group_cap = pf_group_scratch ()&& !m .fused_bufs ?group_cap_rows (T ,m .g -> n_expert ) :0 ; 3025if (m .group_cap > 0 || hcr ) {// activation evidence: once per layout (a chunk size), what the switches took 3026 std::fprintf (stderr ,"strata prefill: chunk %zu tokens:%s%s\n" ,T , 3027m .group_cap > 0 ? (" STRATA_PF_GROUP_SCRATCH on (GU/H/Hq hold " + std::to_string (m .group_cap )+ " rows, not " + 3028 std::to_string ((long long ) (T * K ))+ ");" ).c_str () :"" , 3029hcr ?" STRATA_PF_HC_REGION on (the hyper-connection read's scratch is in the shared region);" :"" ); 3030 } 3031return ok ; 3032} 3033 3034bool Prefill ::relayout (int64_t chunk ,void * borrow ,uint64_t borrow_bytes , std::string & err ,int64_t tail ) { 3035Impl & m = * impl_ ; 3036m .tail_req = tail ;// read by carve (a failure leaves the layout unusable as before; the caller ends the request) 3037if (m .borrow_spill ) { 3038err = "prefill: a hybrid borrowed/owned layout cannot be changed between requests" ; 3039return false; 3040 } 3041if (!m .borrowed || borrow == nullptr || chunk <=0 || chunk > m .T_max ) { 3042err = "prefill: relayout needs borrowed buffers and a chunk of at most " + std::to_string (m .T_max ); 3043return false; 3044 } 3045if (cudaStreamSynchronize (m .cs )!= cudaSuccess || cudaStreamSynchronize (m .copy )!= cudaSuccess || 3046 (m .kv_copy && cudaStreamSynchronize (m .kv_copy )!= cudaSuccess )) { 3047err = "prefill: relayout: the stream failed" ; 3048return false; 3049 } 3050bool ok = true; 3051Alloc o ; 3052o .base = (uint8_t * )borrow ; 3053o .cap = borrow_bytes ; 3054o .owned = & m .owned ; 3055uint16_t * gs = o .take < uint16_t > ((size_t )GEMM_SCRATCH ,ok ); 3056void * ws = o .take < uint8_t > (GEMM_WS ,ok ); 3057uint16_t * gs2 = gemm_dequant_side () ?o .take < uint16_t > ((size_t )GEMM_SCRATCH ,ok ) :nullptr ;// STRATA_DEQUANT_SIDE 3058if (ok )m .gemm .rebind (gs ,GEMM_SCRATCH ,ws ,GEMM_WS ); 3059if (ok ) { std::string side_err ;if (!m .gemm .set_dequant_side (gs2 ,side_err )) std::fprintf (stderr ,"prefill: STRATA_DEQUANT_SIDE=1 not taken (%s): the dense weights are dequantized in front of their GEMMs\n" ,side_err .c_str ()); } 3060if (!ok || !carve ((size_t )chunk ,& o )) { 3061size_t fb = 0 ,tb = 0 ; 3062cudaMemGetInfo (& fb ,& tb ); 3063 (void )cudaGetLastError (); 3064err = "prefill: device buffers for a chunk of " + std::to_string (chunk )+ " tokens do not fit (" + 3065 std::to_string (fb >>20 )+ " of " + std::to_string (tb >>20 )+ " MiB free at the failure; " + 3066 std::to_string (o .used >>20 )+ " MiB taken, the failing buffer wanted " + 3067 std::to_string (o .failed_bytes >>20 )+ " MiB)" ; 3068return false; 3069 } 3070return true; 3071} 3072 3073int64_t Prefill ::chunk ()const {return impl_ -> T ; } 3074int64_t Prefill ::layout_tail ()const {return impl_ -> tail_req ; } 3075int64_t Prefill ::tail_room ()const { 3076const Impl & m = * impl_ ; 3077if (!m .fused_bufs )return std::numeric_limits < int64_t > ::max ();// MMQ-sized buffers: any chunk the layout has 3078const int64_t d = std::max < int64_t > (stream_all_min ()- 1 ,0 ); 3079return m .tail_req >=0 ? std::min (m .tail_req ,d ) :d ; 3080} 3081bool Prefill ::tail_matters (int64_t chunk ,bool src ) {return chunk > 0 && fused_layout ((size_t )chunk ,src ); } 3082 3083void Prefill ::set_ring_room_active (bool on ) { 3084ring_room_active_ = on ; 3085Impl & m = * impl_ ; 3086// the slots' own pointers do not move: the room is taken and given back by the ring's count alone 3087if (m .ring_room > 0 )m .ring = on ?m .ring_room_at + m .ring_room :m .ring_rule ; 3088} 3089 3090bool Prefill ::idle (std::string & err ) { 3091Impl & m = * impl_ ; 3092if ((m .cs && cudaStreamSynchronize (m .cs )!= cudaSuccess )|| 3093 (m .copy && cudaStreamSynchronize (m .copy )!= cudaSuccess )|| 3094 (m .kv_copy && cudaStreamSynchronize (m .kv_copy )!= cudaSuccess )) { 3095 (void )cudaGetLastError (); 3096err = "prefill: the prompt path's streams failed" ; 3097return false; 3098 } 3099return true; 3100} 3101 3102bool Prefill ::draft_kv (core::MtpDrafter & mtp ,const float * R_rows ,const int32_t * next_tokens ,int64_t n ,int64_t cell0 , 3103 std::string & err ,const char ** why ) { 3104Impl & m = * impl_ ; 3105#if defined(STRATA_GPU_METAL ) 3106 (void )m ; (void )mtp ; (void )R_rows ; (void )next_tokens ; (void )n ; (void )cell0 ; (void )err ; 3107if (why )* why = "the Metal window feeds the draft layer itself" ; 3108return false; 3109#endif 3110const core::OnDevice on_device (m .device );// the stage's own GPU current (a layer split's drafter: the last stage) 3111auto decline = [& ](const char * reason ) {if (why != nullptr )* why = reason ;return false; }; 3112static const bool off = [] {const char * v = std::getenv ("STRATA_MTP_BATCH" );return v != nullptr && v [0 ]== '0' ; }(); 3113// A ring (KV streaming: the drafter's window, page p in slot p % n_slots over a host copy) takes the same appends 3114// with its own page table and host copy, as a streamed main layer does; the cells written are those the window can 3115// still reach (r0 below), which the ring holds, so no two of them share a slot. STRATA_MTP_BATCH_RING=0: the 3116// drafter's own pass for a ring (the A/B). 3117static const bool ring_ok = [] {const char * v = std::getenv ("STRATA_MTP_BATCH_RING" );return v == nullptr || v [0 ]!= '0' ; }(); 3118 core::QsaState & st = mtp .kv_state_rw (); 3119if (off )return decline ("STRATA_MTP_BATCH=0" ); 3120if (n <=0 || m .g == nullptr || m .region == nullptr )return decline ("no prompt scratch region on this path" ); 3121if (st .kv_mode != 0 && !(st .kv_mode == 2 && ring_ok )) 3122return decline (st .kv_mode == 2 ?"the drafter's K/V is a ring and STRATA_MTP_BATCH_RING=0" :"the drafter's K/V mode is not paged/ring" ); 3123if (st .kv_hybrid )return decline ("the drafter's K/V is hybrid (kv_hybrid)" ); 3124if (mtp .device ()!= m .device )return decline ("the drafter is on another device than this prefill path" ); 3125const auto t0 = Clock ::now (); 3126const core::ModelGeometry & g = * m .g ; 3127const int64_t Nn = g .n_embd ,HCN = g .hc * g .n_embd ,KV = g .n_head_kv * g .head_dim ; 3128constexpr int kQ8_0 = 8 ;// GGML_TYPE_Q8_0 3129const float * w_ne = mtp .tensor_f32 ("pre_fc_norm_embedding.weight" ); 3130const void * w_fe = mtp .tensor_q8 ("fc_embedding.weight" ); 3131const float * w_nh = mtp .tensor_f32 ("pre_fc_norm_hidden.weight" ); 3132const void * w_fh = mtp .tensor_q8 ("fc_hidden.weight" ); 3133const float * w_hn = mtp .tensor_f32 ("attn_hyper_connection.hc_norm.weight" ); 3134const uint16_t * w_dn = mtp .tensor_bf16 ("attn_hyper_connection.input_mix_weight_down.weight" ); 3135const uint16_t * w_up = mtp .tensor_bf16 ("attn_hyper_connection.input_mix_weight_up.weight" ); 3136const void * w_k = mtp .tensor_q8 ("self_attn.k_proj.weight" ); 3137const void * w_v = mtp .tensor_q8 ("self_attn.v_proj.weight" ); 3138const float * w_kn = mtp .tensor_f32 ("self_attn.k_norm.weight" ); 3139if (!w_ne || !w_fe || !w_nh || !w_fh || !w_hn || !w_dn || !w_up || !w_k || !w_v || !w_kn ) 3140return decline ("a drafter tensor is missing (Q8_0 projections / norms)" ); 3141const core::NativeEmbed * nemb = core::native_embed (); 3142const core::WeightRef * wemb = nemb ?nullptr :m .wt -> find ("token_embd.weight" ); 3143if (!nemb && (wemb == nullptr || wemb -> codebook_iq4nl || wemb -> ne0 != g .n_embd || wemb -> group_elems <=0 || 3144 (wemb -> code_bits != 2 && wemb -> code_bits != 4 && wemb -> code_bits != 8 ))) 3145return decline ("the token embedding is not gatherable on this path" ); 3146// the cells the drafter's window can still reach 3147const int64_t r0 = std::max < int64_t > (0 ,mtp .first_needed ()- cell0 ); 3148if (r0 >=n )return true; 3149// per row: emb/e2 (N), en16 (N half), hn/h2/Rm/gated (HCN), hn16/xn16 (HCN half), lo (LR) + lo16, grs, mixed (N) + 3150// mixed_h, K and V (KV each), the token id 3151// E-9: the drafter's Q8_0 matrices through FP16 GEMMs (Gemm::native: dequantize + cuBLAS / hipBLAS), our own code 3152// instead of llama.cpp's MMQ. Measured on an RTX PRO 5000 (IQ3_S, 5 rounds, 20 decode prompts of five classes, lane 3153// P4-FALLBACK 11-11): the same tokens in 100 of 100 requests, prompt time 1.001 of MMQ's form, decode 0.993-1.000 by 3154// class, acceptance 0.7447 against 0.7470. STRATA_MTP_BATCH_F16=0: the Q8_1 x Q8_0 MMQ form (as the drafter's own 3155// integer dot products, mmvq), kept until MMQ leaves the build. 3156static const bool f16_only = [] {const char * v = std::getenv ("STRATA_MTP_BATCH_F16" );return v == nullptr || v [0 ]!= '0' ; }(); 3157const bool q8 = !f16_only && mmq::built ()&& mmq::fits (kQ8_0 ,Nn )&& mmq::fits (kQ8_0 ,KV );// #420 3158const uint64_t per_row = 4 * (2 * Nn + 4 * HCN + LR + HC + Nn + 2 * KV + 1 )+ 2 * (Nn + 2 * HCN + LR + Nn )+ 64 + 3159 (q8 ? (uint64_t ) mmq::q8_bytes (g .hc ,Nn )+ 8 * g .hc :0 );// (8 * hc: the row table twice, see its margin below) 3160int64_t B = std::min < int64_t > (n - r0 , (int64_t ) (m .region_bytes /per_row )& ~(int64_t )63 ); 3161if (st .kv_mode == 2 )// a ring: one batch's cells must not share a slot (a batch can straddle one page more) 3162B = std::min < int64_t > (B , ((st .n_slots - 1 )* strata::kernels::qsa_real_shapes ().page_size )& ~(int64_t )63 ); 3163if (B < 64 )return decline ("too little scratch for a 64-row batch" ); 3164uint8_t * q = m .region ; 3165auto carve = [& ](size_t bytes ) {void * p = q ;q += (bytes + 255 )& ~(size_t )255 ;return p ; }; 3166float * emb = (float * )carve ((size_t )B * Nn * 4 ); 3167float * e2 = (float * )carve ((size_t )B * Nn * 4 ); 3168uint16_t * en16 = (uint16_t * )carve ((size_t )B * Nn * 2 ); 3169float * hn = (float * )carve ((size_t )B * HCN * 4 ); 3170float * h2 = (float * )carve ((size_t )B * HCN * 4 ); 3171float * Rm = (float * )carve ((size_t )B * HCN * 4 ); 3172float * gated = (float * )carve ((size_t )B * HCN * 4 ); 3173uint16_t * hn16 = (uint16_t * )carve ((size_t )B * HCN * 2 ); 3174uint16_t * xn16 = (uint16_t * )carve ((size_t )B * HCN * 2 ); 3175float * lo = (float * )carve ((size_t )B * LR * 4 ); 3176uint16_t * lo16 = (uint16_t * )carve ((size_t )B * LR * 2 ); 3177float * grs = (float * )carve ((size_t )B * HC * 4 ); 3178float * mixed = (float * )carve ((size_t )B * Nn * 4 ); 3179uint16_t * mixed_h = (uint16_t * )carve ((size_t )B * Nn * 2 ); 3180float * Kc = (float * )carve ((size_t )B * KV * 4 ); 3181float * Vc = (float * )carve ((size_t )B * KV * 4 ); 3182int32_t * tok = (int32_t * )carve ((size_t )B * 4 ); 3183void * xq = q8 ?carve (mmq::q8_bytes (B * g .hc ,Nn )) :nullptr ; 3184// The row table is read past its end by llama.cpp's MMQ (a whole J-column tile from the start of each tile; the stream-k fixup up to roundup(max_rows, J) 3185// from the expert's first row; J up to 128): rows + the margin of mmq_ids_margin.hpp, max_rows <= B * hc (one expert, p.n = 1), the identity over all of it. 3186const uint64_t ids_rows = q8 ? mmq::mmq_ids_table_rows ((uint64_t ) (B * g .hc ), (uint64_t ) (B * g .hc )) :0 ; 3187int32_t * ident = q8 ? (int32_t * )carve ((size_t )ids_rows * 4 ) :nullptr ; 3188int32_t * bnd = q8 ? (int32_t * )carve (16 ) :nullptr ; 3189if ((uint64_t ) (q - m .region )> m .region_bytes )return decline ("the batch buffers do not fit the scratch region" ); 3190static const bool timing = std::getenv ("STRATA_DRAFT_TIMING" )!= nullptr ;// debug: where this pass's time goes 3191if (timing )cudaStreamSynchronize (m .cs ); 3192const auto ti0 = Clock ::now (); 3193if (!mtp .idle (err ))return false;// the drafter's own stream (its graph uploads) before this writes its K/V 3194const double ms_idle = ms_since (ti0 ); 3195const auto tl0 = Clock ::now (); 3196 strata::kernels::QsaShapes s = core::qsa_shapes (g ); 3197 std::vector < int32_t > tk ((size_t )B ); 3198if (q8 ) { 3199if (!m .mmq_ctx )m .mmq_ctx = std::make_unique < mmq::Context > (); 3200 mmq::iota (ident , (int64_t )ids_rows ,m .cs ); 3201 } 3202// y[rows, n_out] = x[rows, k] . w^T for a Q8_0 matrix: MMQ from the FP32 rows (bounds slot 0: rows, 1: rows*hc) 3203auto proj = [& ](const float * x ,const uint16_t * x16 ,const void * w ,float * y ,int64_t rows ,int64_t n_out , 3204int64_t k ,int slot ) { 3205if (!q8 ) {m .gemm .native (x16 ,kQ8_0 ,w ,y ,rows ,n_out ,k );return ; } 3206 mmq::quantize (x ,nullptr ,xq ,kQ8_0 ,k ,k ,rows ,m .cs ); 3207 mmq::Product p ; 3208p .w = w ;p .type = kQ8_0 ;p .w_rows = n_out ;p .w_cols = k ;p .expert_bytes = mmq::matrix_bytes (kQ8_0 ,n_out ,k ); 3209p .n = 1 ;p .xq = xq ;p .bounds = bnd + 2 * slot ;p .ids = ident ;p .total_rows = rows ;p .max_rows = rows ; 3210p .dst = y ;p .ld_dst = n_out ; 3211m .mmq_ctx -> run (p ,m .cs ); 3212 }; 3213for (int64_t b0 = r0 ;b0 < n ;b0 += B ) { 3214const int64_t nb = std::min (B ,n - b0 ),c0 = cell0 + b0 ; 3215for (int64_t i = 0 ;i < nb ;++ i )tk [(size_t )i ]= next_tokens [b0 + i ]; 3216const int32_t bh [4 ]= {0 , (int32_t )nb ,0 , (int32_t ) (nb * g .hc )}; 3217// #1996: bh is on this stack and tk is refilled every pass: both go up through pinned slots 3218if (q8 && m .up_ring .h2d (bnd ,bh ,sizeof bh ,m .cs )!= cudaSuccess ) { 3219err = "prefill: the draft bounds' upload failed" ; 3220return false; 3221 } 3222if (m .up_ring .h2d (tok ,tk .data (), (size_t )nb * 4 ,m .cs )!= cudaSuccess ) { 3223err = "prefill: the draft tokens' upload failed" ; 3224return false; 3225 } 3226// the input branches: the next token's embedding, and this cell's final residual rows 3227if (nemb ) { 3228nemb -> gather_dev (tok ,nb ,emb ,m .cs ); 3229 }else { 3230const auto * codes = (const uint8_t * )wemb -> data ; 3231const auto * scales = (const float * ) (codes + wemb -> codes_bytes ); 3232const auto * offsets = wemb -> has_offset ? (const float * ) (codes + wemb -> codes_bytes + wemb -> scales_bytes ) 3233 :nullptr ; 3234 strata::kernels::embedding_gather_dev (codes ,scales ,offsets ,tok , (int )nb ,wemb -> ne0 ,wemb -> code_bits , 3235wemb -> code_bias ,wemb -> group_elems , 3236 (uint64_t ) (wemb -> ne0 / (8 /wemb -> code_bits )), 3237 (uint64_t ) (wemb -> ne0 /wemb -> group_elems ),emb ,m .cs ); 3238 } 3239rms_rows (emb ,w_ne ,nb ,Nn ,Nn ,EPS ,m .cs ); 3240if (!q8 )to_f16 (emb ,en16 ,nb * Nn ,m .cs ); 3241proj (emb ,en16 ,w_fe ,e2 ,nb ,Nn ,Nn ,0 ); 3242cudaMemcpyAsync (hn ,R_rows + (size_t )b0 * HCN , (size_t )nb * HCN * 4 ,cudaMemcpyDeviceToDevice ,m .cs ); 3243if (mtp .hnorm_per_stream ())// --mtp-hnorm stream: as the drafter's own pass (mtp.cpp) 3244 strata::kernels::native_qsa_rms_norm_grouped (hn ,w_nh ,hn , (int )Nn , (int )g .hc , (int ) (nb * g .hc ),EPS ,m .cs ); 3245else 3246rms_rows (hn ,w_nh ,nb ,HCN ,HCN ,EPS ,m .cs ); 3247if (!q8 )to_f16 (hn ,hn16 ,nb * HCN ,m .cs ); 3248proj (hn ,hn16 ,w_fh ,h2 ,nb * g .hc ,Nn ,Nn ,1 );// every stream through fc_hidden 3249 strata::kernels::add_streams_broadcast (h2 ,e2 ,Rm ,Nn , (int )g .hc , (int )nb ,m .cs ); 3250// the attention hyper-connection's read (its mixed input only: this pass writes nothing back) 3251gr_norm_rs (Rm ,w_hn ,EPS ,grs ,xn16 ,nb ,m .cs ); 3252m .gemm .bf16 (xn16 ,w_dn ,lo ,nb ,LR ,HCN ); 3253gr_silu (lo ,lo16 ,nb ,m .cs ); 3254m .gemm .bf16 (lo16 ,w_up ,gated ,nb ,HCN ,LR ); 3255gr_mix_r (Rm ,grs ,w_hn ,gated ,mixed ,nullptr ,nb ,m .cs ,mixed_h ); 3256// K and V into the drafter's cache, as the prompt path's QSA layers append theirs 3257proj (mixed ,mixed_h ,w_k ,Kc ,nb ,KV ,Nn ,0 ); 3258proj (mixed ,mixed_h ,w_v ,Vc ,nb ,KV ,Nn ,0 ); 3259rms_rows (Kc ,w_kn ,nb * g .n_head_kv ,g .head_dim ,g .head_dim ,EPS ,m .cs ); 3260rope (Kc ,nb ,g .n_head_kv ,g .head_dim ,KV ,c0 , strata::kernels::rope_scaling (),m .cs ); 3261if (st .kv_rot ) {// rotated as the drafter's own decode stores them (mtp.cpp) 3262 strata::kernels::fwht256_inplace_cuda (Kc ,nb * g .n_head_kv ,m .cs ); 3263 strata::kernels::fwht256_inplace_cuda (Vc ,nb * g .n_head_kv ,m .cs ); 3264 } 3265if (st .kv_q4 ) { 3266 strata::kernels::kv_append_q4 (st .k_q4 ,st .v_q4 ,st .page_table ,c0 ,nb ,Kc ,Vc ,s ,m .cs ,& st .host ); 3267 }else { 3268kv_append (Kc ,Vc ,nb ,c0 ,st .page_table ,s .page_size ,st .kv_int8 ?nullptr :st .k_pool , 3269st .kv_int8 ?nullptr :st .v_pool ,st .k_q ,st .v_q ,st .k_scale ,st .v_scale ,m .cs ,& st .host ); 3270 } 3271 } 3272if (cudaStreamSynchronize (m .cs )!= cudaSuccess ) { 3273err = std::string ("prefill: the draft layer's K/V: " )+ cudaGetErrorString (cudaGetLastError ()); 3274return false; 3275 } 3276mtp .ms_prefill += ms_since (t0 ); 3277if (timing ) 3278 std::fprintf (stderr ,"strata draft kv: %lld cells from %lld (first needed %lld), batch %lld: drafter idle %.1f ms, " 3279"the batches %.1f ms, all %.1f ms\n" , (long long )n , (long long )cell0 , (long long ) (cell0 + r0 ), 3280 (long long )B ,ms_idle ,ms_since (tl0 ),ms_since (t0 )); 3281return true; 3282} 3283namespace { 3284// Layer split: STRATA_PREFILL_HELP=1 lends the idle stage's GPU (opt-in: the helped rows are computed in another MMQ 3285// grouping and round differently from the default, like STRATA_SPLIT_OWN). Unset or 0: every stage's prompt experts on 3286// its own GPU, as before. 3287bool split_help_env () { 3288static const bool v = [] {const char * e = std::getenv ("STRATA_PREFILL_HELP" );return e != nullptr && std::atoi (e )!= 0 ; }(); 3289return v ; 3290} 3291// The share of a stage's streamed experts the idle stage's GPU takes for a one-chunk prompt of T tokens (0: none). 3292// The streamed bytes are the same at any T; the hand-over (the activations there, the rows back) grows with T and is 3293// paid per layer whatever the share. Measured on 2x RTX 3090 (UD-Q4_K_XL, PCIe 4.0 x16 each, no P2P), fixed shares 3294// 0.2 / 0.3 / 0.4 against none: 1.5K tokens 749 / 820 / 908 (none 675), 3K 1335 / 1437 / 1328 (1262), 4K 1622 / 1620 / 3295// 1440 (1609), 6K 1811 / 1660 / 1471 (2038), 8K 1895 / 1804 / 1663 (2230) - the best share falls with T and from ~4K 3296// none pays, which this rule follows (0.41 at 1.5K, 0.32 at 3K, off from ~3.3K). 3297// STRATA_PREFILL_HELP_FRAC sets the share for every T. 3298double split_help_frac (int64_t T ) { 3299static const double fixed = [] { 3300const char * e = std::getenv ("STRATA_PREFILL_HELP_FRAC" ); 3301return e ? std::clamp (std::atof (e ),0.0 ,1.0 ) :-1.0 ; 3302 }(); 3303if (fixed >=0.0 )return fixed ; 3304const double f = std::min (0.45 ,0.5 - (double )T /16384.0 ); 3305return f >=0.3 ?f :0.0 ; 3306} 3307}// namespace 3308 3309namespace { 3310// APR: the down projections' sign vectors on the current device (the peer's or the helper's), one per layer, 3311// resolved once at setup (hadamard_device_signs: a mutex and, the first time on that device, a cudaMalloc) into 3312// P.had_sh, which a prompt chunk reads directly. The gate/up signs are not needed there: the primary sends its 3313// already rotated input (m.Xr). 3314void peer_had_signs (PeerPrefill & P ) { 3315const auto & lay = strata::kernels::cpu::expert_layout (); 3316P .had_sh .assign (lay .native ?lay .fmt .size () :0 ,nullptr ); 3317for (size_t l = 0 ;l < P .had_sh .size ();++ l ) 3318if (lay .fmt [l ].had_d ) 3319P .had_sh [l ]= strata::kernels::hadamard_device_signs (lay .fmt [l ].d_signs , (int )lay .fmt [l ].n_ff ); 3320} 3321}// namespace 3322 3323bool Prefill ::set_stage_helper (Prefill * helper , std::string & err ) { 3324Impl & m = * impl_ ; 3325m .help_pp .reset (); 3326if (helper == nullptr || helper == this || !split_help_env ())return true; 3327const Impl & h = * helper -> impl_ ; 3328if (m .device < 0 || h .device < 0 || h .device == m .device || !mmq_plan ().any )return true; 3329#if defined(STRATA_PF_OWN_ONLY ) 3330return true;// (P4-SPLIT: the helper stage computes on MMQ only) 3331#endif 3332auto pp = std::make_unique < PeerPrefill > (); 3333pp -> peer = nullptr ;// stream-only: it holds no experts, it streams a share of this stage's 3334pp -> compact = true; 3335pp -> p2p = false;// the mapped host route, whether or not the cards could reach each other (measured there) 3336pp -> out_pipe = true; 3337bool ok ; 3338 { 3339const core::OnDevice on (m .device ); 3340ok = cudaEventCreateWithFlags (& pp -> ev_in ,cudaEventDisableTiming )== cudaSuccess ; 3341 } 3342int prev = 0 ; 3343cudaGetDevice (& prev ); 3344pp -> dev = h .device ; 3345cudaSetDevice (pp -> dev ); 3346ok = ok && cudaStreamCreateWithFlags (& pp -> s ,cudaStreamNonBlocking )== cudaSuccess && 3347cudaStreamCreateWithFlags (& pp -> s_out ,cudaStreamNonBlocking )== cudaSuccess && 3348cudaStreamCreateWithFlags (& pp -> s_cp ,cudaStreamNonBlocking )== cudaSuccess && 3349cudaEventCreateWithFlags (& pp -> ev_done ,cudaEventDisableTiming )== cudaSuccess ; 3350for (int i = 0 ;ok && i < PeerPrefill ::kGrpEv ;++ i ) 3351ok = cudaEventCreateWithFlags (& pp -> ev_grp [i ],cudaEventDisableTiming )== cudaSuccess ; 3352for (int b = 0 ;ok && b < 2 ;++ b )ok = cudaEventCreateWithFlags (& pp -> ev_dm [b ],cudaEventDisableTiming )== cudaSuccess ; 3353// the ring's events; its slots are the helper stage's own ring, bound per prompt (bind_stage_helper) 3354pp -> pcopied .assign ((size_t )kSplitHelpRing ,nullptr ); 3355pp -> pused .assign ((size_t )kSplitHelpRing ,nullptr ); 3356for (int i = 0 ;ok && i < kSplitHelpRing ;++ i ) 3357ok = cudaEventCreateWithFlags (& pp -> pcopied [(size_t )i ],cudaEventDisableTiming )== cudaSuccess && 3358cudaEventCreateWithFlags (& pp -> pused [(size_t )i ],cudaEventDisableTiming )== cudaSuccess ; 3359if (ok )peer_had_signs (* pp );// APR: on the helper's device 3360cudaSetDevice (prev ); 3361if (!ok ) {err = "prefill: the layer split's prompt help (streams and events)" ;return false; } 3362helper_ = helper ; 3363m .help_pp = std::move (pp ); 3364return true; 3365} 3366 3367// A one-chunk prompt of T tokens on a layer split: binds the stream-only peer to the helper stage's prompt buffers 3368// (that stage idles until this one hands its rows over). False when it cannot help this prompt. 3369bool Prefill ::bind_stage_helper (int64_t T ) { 3370Impl & m = * impl_ ; 3371if (!m .help_pp || helper_ == nullptr || m .pp )return false; 3372const double frac = split_help_frac (T ); 3373if (frac <=0.0 || T < stream_all_min ()|| m .src == nullptr || m .ring <=STAGE || fused_ring ())return false; 3374const strata::kernels::cpu::ExpertLayout & lay = strata::kernels::cpu::expert_layout (); 3375for (int64_t l = stage_lb_ ;l < stage_le_ ;++ l ) { 3376if (!(mmq_plan ().any && mmq_plan ().layer [(size_t )l ]))return false;// the peer computes on MMQ only 3377if (lay .native && fused::native_supported (lay .fmt [(size_t )l ].gu_type ,lay .fmt [(size_t )l ].d_type ))return false; 3378 } 3379Impl & h = * helper_ -> impl_ ; 3380// the helper's buffers must be laid out for this chunk (the serve path lends every stage's at once) 3381if (h .T < T || h .mixed == nullptr || h .Xq == nullptr || h .Hq == nullptr || h .GU == nullptr || h .H == nullptr || 3382h .Dm == nullptr || h .src_dev == nullptr || h .ids_identity == nullptr || h .bounds_dev == nullptr || 3383h .grp_gu == nullptr || h .grp_d == nullptr || !h .mmq_ctx || h .ring <=STAGE ) 3384return false; 3385PeerPrefill & P = * m .help_pp ; 3386P .T_max = T ; 3387P .cap_rows = T * K ; 3388P .G = T ;// one expert never has more rows than the chunk has tokens 3389P .mixed = h .mixed ; 3390P .Xq_g = h .Xq ;// the helper's per-layer buffers hold T * K rows: a group's T fit 3391P .Hq_g = h .Hq ; 3392P .GU_g = h .GU ; 3393P .H_g = h .H ; 3394P .Dm_b [0 ]= h .Dm ; 3395P .Dm_b [1 ]= h .Dm + (size_t )T * N ; 3396P .src = h .src_dev ; 3397P .ident = h .ids_identity ; 3398P .bounds = h .bounds_dev ; 3399P .grp_gu = h .grp_gu ; 3400P .grp_d = h .grp_d ; 3401P .run_ctx = h .mmq_ctx .get (); 3402P .RP = std::min (h .ring ,kSplitHelpRing ); 3403P .pstage .assign (h .stage_dev ,h .stage_dev + P .RP ); 3404P .plive .assign ((size_t )P .RP ,0 ); 3405P .dm_live [0 ]= P .dm_live [1 ]= false; 3406P .out_pending = false; 3407P .ps_frac = frac ; 3408if (!P .p2p ) {// grown once to the largest chunk it helped 3409auto grow = [](auto *& p ,size_t & cap ,size_t n ) { 3410if (cap >=n )return true; 3411if (p )cudaFreeHost (p ); 3412p = nullptr ; 3413cap = 0 ; 3414if (cudaHostAlloc ((void ** )& p ,n * sizeof (* p ),cudaHostAllocPortable |cudaHostAllocMapped )!= cudaSuccess ) { 3415cudaGetLastError (); 3416p = nullptr ; 3417return false; 3418 } 3419cap = n ; 3420return true; 3421 }; 3422size_t bounds_cap = P .host_bounds ?PeerPrefill ::kHostBounds :0 ; 3423if (!grow (P .host_x ,P .host_x_cap , (size_t )T * N )|| !grow (P .host_rows ,P .host_rows_cap , (size_t )T * K * N )|| 3424 !grow (P .host_src ,P .host_src_cap , (size_t )T * K )|| !grow (P .host_bounds ,bounds_cap ,PeerPrefill ::kHostBounds )) 3425return false; 3426 } 3427const core::OnDevice on (P .dev ); 3428 mmq::iota (P .ident , (int64_t )mmq_ids_rows ((size_t )T ),P .s );// the helper's row table (h.T >= T): a refill may have overwritten its slots 3429return true; 3430} 3431 3432bool Prefill ::set_peer (core::PeerExperts * peer ,int64_t cap_rows , std::string & err ) { 3433Impl & m = * impl_ ; 3434if (peer == nullptr || !peer -> valid ()) {m .pp .reset ();return true; } 3435// Without P2P the activations and the result rows take the mapped host route of the layer split's helper 3436// (STRATA_PF_PEER_HOST=0: refuse as before, the prompt path then stays on the primary) 3437const bool host_route_ok = [] {const char * v = std::getenv ("STRATA_PF_PEER_HOST" );return v == nullptr || std::atoi (v )!= 0 ; }(); 3438if (!peer -> p2p ()&& !host_route_ok ) {err = "prefill peer: the two GPUs cannot access each other (no P2P)" ;return false; } 3439#if defined(STRATA_PF_OWN_ONLY ) 3440err = "prefill peer: needs the MMQ prompt path (this engine was built without it)" ; 3441return false; 3442#endif 3443if (!mmq_plan ().any ) {err = "prefill peer: needs the MMQ prompt path" ;return false; } 3444 {// NVFP4: the peer's MMQ products have no per-expert scales (grp_tail, row_sd); its decode rows do 3445const auto & lay = strata::kernels::cpu::expert_layout (); 3446for (const auto & f :lay .fmt ) 3447if (lay .native && f .tail_off ) {err = "prefill peer: not for NVFP4 experts yet" ;return false; } 3448 } 3449if (strata::kernels::cpu::hadamard_spec ().any ()) {// APR: the peer's MMQ share does not rotate; declined 3450 std::fprintf (stderr ,"strata: prefill peer: not used for a Hadamard-folded (APR) pack\n" ); 3451m .pp .reset (); 3452return true; 3453 } 3454auto pp = std::make_unique < PeerPrefill > (); 3455pp -> peer = peer ; 3456pp -> p2p = peer -> p2p (); 3457pp -> T_max = m .T_max ; 3458pp -> cap_rows = std::max < int64_t > (1 , std::min < int64_t > (cap_rows ,m .T_max * K )); 3459const int64_t R = pp -> cap_rows ; 3460const MmqPlan & mp = mmq_plan (); 3461if (cudaEventCreateWithFlags (& pp -> ev_in ,cudaEventDisableTiming )!= cudaSuccess ) {err = "prefill peer: event" ;return false; } 3462if (!pp -> p2p ) {// the host route's copies on a stream of their own (STRATA_PF_PEER_XSTREAM=0: the compute stream) 3463const char * xv = std::getenv ("STRATA_PF_PEER_XSTREAM" ); 3464if ((xv == nullptr || std::atoi (xv )!= 0 )&& 3465 (cudaStreamCreateWithFlags (& pp -> x_stream ,cudaStreamNonBlocking )!= cudaSuccess || 3466cudaEventCreateWithFlags (& pp -> ev_x ,cudaEventDisableTiming )!= cudaSuccess )) { 3467err = "prefill peer: copy stream" ; 3468return false; 3469 } 3470 } 3471int prev = 0 ; 3472cudaGetDevice (& prev ); 3473pp -> dev = peer -> device (); 3474cudaSetDevice (pp -> dev ); 3475bool ok = cudaStreamCreateWithFlags (& pp -> s ,cudaStreamNonBlocking )== cudaSuccess && 3476cudaEventCreateWithFlags (& pp -> ev_done ,cudaEventDisableTiming )== cudaSuccess ; 3477 { 3478const char * v = std::getenv ("STRATA_PF_PEER_OUT_PIPE" );// =0: one copy after the last group (the A/B) 3479pp -> out_pipe = (v == nullptr || std::atoi (v )!= 0 )|| pp -> compact ;// compact always pipes 3480 } 3481if (ok && pp -> out_pipe ) { 3482ok = cudaStreamCreateWithFlags (& pp -> s_out ,cudaStreamNonBlocking )== cudaSuccess ; 3483for (int i = 0 ;ok && i < PeerPrefill ::kGrpEv ;++ i ) 3484ok = cudaEventCreateWithFlags (& pp -> ev_grp [i ],cudaEventDisableTiming )== cudaSuccess ; 3485 } 3486auto take = [& ](size_t bytes )-> void * { 3487void * p = nullptr ; 3488if (!ok || cudaMalloc (& p ,bytes )!= cudaSuccess ) {ok = false;return nullptr ; } 3489pp -> owned .push_back (p ); 3490return p ; 3491 }; 3492pp -> mixed = (float * )take ((size_t )m .T_max * N * 4 ); 3493 { 3494const char * v = std::getenv ("STRATA_PF_PEER_COMPACT" ); 3495pp -> compact = (v == nullptr || std::atoi (v )!= 0 )|| !pp -> p2p ;// the layer-sized path copies over P2P only 3496 } 3497if (pp -> compact ) { 3498pp -> cap_rows = m .T_max * K ;// no row cap: only the row tables grow with it 3499pp -> G = m .T_max ;// one expert never has more rows than the chunk has tokens 3500const int64_t Gr = pp -> G ; 3501pp -> Xq_g = take (mmq::q8_bytes (Gr ,N )); 3502pp -> Hq_g = take (mmq::q8_bytes (Gr ,kFF )); 3503pp -> GU_g = (float * )take ((size_t )Gr * kFF2 * 4 ); 3504pp -> H_g = (float * )take ((size_t )Gr * kFF * 4 ); 3505pp -> Dm_b [0 ]= (float * )take ((size_t )Gr * N * 4 ); 3506pp -> Dm_b [1 ]= (float * )take ((size_t )Gr * N * 4 ); 3507for (int b = 0 ;b < 2 && ok ;++ b )ok = cudaEventCreateWithFlags (& pp -> ev_dm [b ],cudaEventDisableTiming )== cudaSuccess ; 3508const char * fs = std::getenv ("STRATA_PF_PEER_STREAM" ); 3509pp -> ps_frac = fs ? std::atof (fs ) :0.35 ;// measured: 0.25-0.5 all ~1950-1970 at 32K, 0.35 best 3510if (pp -> ps_frac > 0.0 && !mp .fallback && m .T_max >=stream_all_min ()) { 3511pp -> RP = 48 ; 3512if (const char * pr = std::getenv ("STRATA_PF_PEER_RING" );pr != nullptr )pp -> RP = std::atoi (pr ); 3513pp -> pstage .assign ((size_t )pp -> RP ,nullptr ); 3514pp -> pcopied .assign ((size_t )pp -> RP ,nullptr ); 3515pp -> pused .assign ((size_t )pp -> RP ,nullptr ); 3516pp -> plive .assign ((size_t )pp -> RP ,0 ); 3517ok = ok && cudaStreamCreateWithFlags (& pp -> s_cp ,cudaStreamNonBlocking )== cudaSuccess ; 3518for (int i = 0 ;ok && i < pp -> RP ;++ i ) { 3519pp -> pstage [(size_t )i ]= (uint8_t * )take ((size_t )MAXBLOB ()); 3520ok = ok && cudaEventCreateWithFlags (& pp -> pcopied [(size_t )i ],cudaEventDisableTiming )== cudaSuccess && 3521cudaEventCreateWithFlags (& pp -> pused [(size_t )i ],cudaEventDisableTiming )== cudaSuccess ; 3522 } 3523 }else { 3524pp -> ps_frac = 0.0 ; 3525 } 3526 }else { 3527pp -> Xq = take (mmq::q8_bytes (R ,N )); 3528pp -> Hq = take (mmq::q8_bytes (R ,kFF )); 3529pp -> GU = (float * )take ((size_t )R * kFF2 * 4 ); 3530pp -> H = (float * )take ((size_t )R * kFF * 4 ); 3531pp -> Dm = (float * )take ((size_t )R * N * 4 ); 3532 } 3533const int64_t Rt = pp -> cap_rows ; 3534if (!pp -> p2p && pp -> compact ) { 3535const char * v = std::getenv ("STRATA_PF_PEER_SUMS" ); 3536pp -> sums = v == nullptr || std::atoi (v )!= 0 ; 3537 } 3538if (pp -> sums ) { 3539const char * v = std::getenv ("STRATA_PF_PEER_F16" ); 3540pp -> f16 = (v == nullptr || std::atoi (v )!= 0 )&& N %8 == 0 ; 3541if (pp -> f16 )pp -> sum16 = (uint16_t * )take ((size_t )m .T_max * N * 2 ); 3542const char * gv = std::getenv ("STRATA_PF_PEER_GATHER" ); 3543pp -> gather = gv == nullptr || std::atoi (gv )!= 0 ; 3544if (pp -> gather ) {// tokens and starts (<= 2 rows + 1 per group) and rows: <= 3 x the rows + 2 per expert 3545pp -> adds_cap = 3 * (size_t )Rt + 2 * NE + 64 ; 3546pp -> adds = (int32_t * )take (pp -> adds_cap * 4 ); 3547pp -> tcur .assign ((size_t )m .T_max ,0 ); 3548 } 3549pp -> sum = (float * )take ((size_t )m .T_max * N * 4 ); 3550pp -> wk = (float * )take ((size_t )m .T_max * K * 4 ); 3551pp -> pair = (int32_t * )take ((size_t )Rt * 4 ); 3552 } 3553pp -> src = (int32_t * )take ((size_t )Rt * 4 ); 3554const uint64_t ident_rows = mmq::mmq_ids_table_rows ((uint64_t )Rt , (uint64_t )m .T_max );// + the stream-k fixup's over-read 3555if (ident_rows == 0 )ok = false; 3556pp -> ident = (int32_t * )take ((size_t )ident_rows * 4 ); 3557pp -> bounds = (int32_t * )take ((size_t ) (2 * (NE + NE /MMQ_GROUP + 2 ))* 4 ); 3558pp -> grp_gu = (uint8_t * )take (MMQ_GROUP * mp .gu_max + MMQ_TAIL ); 3559pp -> grp_d = (uint8_t * )take (MMQ_GROUP * mp .d_max + MMQ_TAIL ); 3560if (ok ) { 3561pp -> ctx = std::make_unique < mmq::Context > (); 3562pp -> run_ctx = pp -> ctx .get (); 3563 mmq::iota (pp -> ident , (int64_t )ident_rows ,pp -> s ); 3564peer_had_signs (* pp );// APR: on the peer's device 3565ok = cudaStreamSynchronize (pp -> s )== cudaSuccess ; 3566 } 3567if (ok && !pp -> p2p ) {// the host route's mapped buffers, sized for the largest chunk 3568auto host = [& ](auto *& ptr ,size_t & cap ,size_t n ) { 3569if (cudaHostAlloc ((void ** )& ptr ,n * sizeof (* ptr ),cudaHostAllocPortable |cudaHostAllocMapped )!= cudaSuccess ) { 3570cudaGetLastError (); 3571ptr = nullptr ; 3572ok = false; 3573return ; 3574 } 3575cap = n ; 3576 }; 3577size_t bounds_cap = 0 ,w_cap = 0 ,sum_cap = 0 ,pair_cap = 0 ; 3578size_t x16_cap = 0 ,sum16_cap = 0 ; 3579if (pp -> f16 )host (pp -> host_x16 ,x16_cap , (size_t )m .T_max * N ); 3580else host (pp -> host_x ,pp -> host_x_cap , (size_t )m .T_max * N ); 3581if (ok && pp -> sums ) { 3582host (pp -> host_w ,w_cap , (size_t )m .T_max * K ); 3583if (ok && pp -> f16 )host (pp -> host_sum16 ,sum16_cap , (size_t )m .T_max * N ); 3584else if (ok )host (pp -> host_sum ,sum_cap , (size_t )m .T_max * N ); 3585if (ok )host (pp -> host_pair ,pair_cap , (size_t )pp -> cap_rows ); 3586size_t adds_cap = 0 ; 3587if (ok && pp -> gather )host (pp -> host_adds ,adds_cap ,pp -> adds_cap ); 3588 }else if (ok ) { 3589host (pp -> host_rows ,pp -> host_rows_cap , (size_t )pp -> cap_rows * N ); 3590 } 3591if (ok )host (pp -> host_src ,pp -> host_src_cap , (size_t )pp -> cap_rows ); 3592if (ok )host (pp -> host_bounds ,bounds_cap ,PeerPrefill ::kHostBounds ); 3593if (!ok ) { 3594cudaSetDevice (prev ); 3595err = "prefill peer: the host route's pinned buffers (" + 3596 std::to_string (((size_t )pp -> cap_rows * N * 4 + (size_t )m .T_max * N * 4 ) >>20 )+ " MiB) do not fit in RAM" ; 3597return false; 3598 } 3599 } 3600size_t fb = 0 ,tb = 0 ; 3601cudaMemGetInfo (& fb ,& tb ); 3602cudaSetDevice (prev ); 3603if (!ok ) {err = "prefill peer: the peer's buffers do not fit (raise --peer-reserve-mib or lower --peer-prefill-rows)" ;return false; } 3604 std::fprintf (stderr ,"strata prefill: peer GPU %d computes its experts' rows of each prompt chunk (up to %lld rows per " 3605"layer%s%s); %zu MiB left free on it\n" ,pp -> dev , (long long )pp -> cap_rows , 3606pp -> p2p ?"" : (pp -> sums ? (pp -> f16 ?", no P2P: through mapped host memory in FP16, one weighted sum per token back" 3607 :", no P2P: through mapped host memory, one weighted sum per token back" ) 3608 :", no P2P: through mapped host memory" ), 3609pp -> compact ? (pp -> ps_frac > 0.0 ? (", compact group buffers, streams " + std::to_string ((int ) (pp -> ps_frac * 100 + 0.5 ))+ 3610"% of the primary's streamed experts through a " + std::to_string (pp -> RP )+ "-slot ring" ).c_str () 3611 :", compact group buffers" ) :"" ,fb >>20 ); 3612// APR: this path rotates on the peer too (peer_had_signs), but no P2P pair has run it end to end with a 3613// Hadamard-folded pack yet (the validated two-GPU runs had no P2P, so their prompts stayed on the first GPU) 3614if (strata::kernels::cpu::hadamard_spec ().any ()) 3615 std::fprintf (stderr ,"strata prefill: warning: prompt processing on a P2P peer GPU is not validated end to end " 3616"with Hadamard-folded experts yet\n" ); 3617m .pp = std::move (pp ); 3618return true; 3619} 3620 3621void Prefill ::set_pinned_share (double share ) {g_pinned_share = share ; } 3622void Prefill ::set_ring_override (int slots ) {g_ring_override = slots > 0 ?slots :0 ; } 3623void Prefill ::set_ring_budget (int slots ,int64_t small_max ) { 3624g_ring_budget = slots > 0 ?slots :0 ; 3625g_ring_small_max = small_max > 0 ?small_max :0 ; 3626} 3627double Prefill ::pinned_share () {return g_pinned_share ; } 3628int64_t Prefill ::stream_all_min_tokens () {return stream_all_min (); } 3629int64_t Prefill ::short_read_default (int64_t base ) { 3630const auto & lay = strata::kernels::cpu::expert_layout (); 3631if (!lay .native || lay .fmt .empty ())return base ; 3632const bool cls = stream_floor_class_measured (); 3633return strata::prefill::short_read_default (base ,cls ,cls && layers_all_fused_only (),staged_fo_on (),trellis_g1151_all_fused ()&& layers_any_folded ()); 3634} 3635void Prefill ::set_card_expert_share (int64_t resident_slots ,int64_t total_pairs ,double blob_mb ,double link_gbps ) { 3636#if !defined(STRATA_USE_HIP )&& !defined(STRATA_HIP_GFX906 ) 3637int dev = 0 ; 3638cudaDeviceProp prop ; 3639const bool got = cudaGetDevice (& dev )== cudaSuccess && cudaGetDeviceProperties (& prop ,dev )== cudaSuccess ; 3640g_sp_sm = got ?prop .multiProcessorCount :0 ; 3641g_sp_cc_major = got ?prop .major :0 ; 3642g_sp_cc_minor = got ?prop .minor :0 ; 3643g_sp_integrated = got ?prop .integrated != 0 : true; 3644#endif 3645g_sp_blob_mb = blob_mb ; 3646g_sp_link_gbps = link_gbps ; 3647g_sp_total .store (total_pairs , std::memory_order_release ); 3648g_sp_resident .store (resident_slots , std::memory_order_release ); 3649} 3650 3651// --prefill-pipe (opt-in; STRATA_PREFILL_PIPE): a layer split reads a prompt as a pipeline - stage s reads chunk c while 3652// stage s+1 reads chunk c-1. A stage-chunk costs its layers x (b + a C): a fixed part per chunk (b: the pass over the 3653// layer's experts - dequantized, or streamed over PCIe where they are not in VRAM) and a part per token (a). The prompt 3654// then takes about sum_i (b + a C_i) + (S - 1) max_i (b + a C_i) for chunks C_i over S stages: few large or uneven 3655// chunks keep the later stages waiting (a 10.7K prompt in a 7680 and a 3011 chunk over four GP100 dies: the first 3656// stage carried 24 of 36 s), many small ones pay b again and again. In units of a that is k r + n + (S - 1)(r + C) for 3657// k chunks of C tokens (the last one the rest) and r = b/a, so the rule tries every chunk count from the fewest the 3658// buffers allow, each chunk evened out on the 256-token grid and at least 512, and keeps the cheapest - when it beats 3659// today's split (chunks of `cap`, the last the rest) by 3%. r differs by an order of magnitude between rigs: ~700 tokens 3660// on four GP100 dies (every expert in VRAM, slow arithmetic), ~5000 on two RTX 3090 Ti (fast arithmetic, part of the 3661// experts streamed per chunk), and a wrong r costs (1024 on two RTX 4090: 22-36% slower). The engine neither guesses r 3662// nor learns it from the prompts it serves - that made a prompt's chunks, and so its output bits, depend on how busy 3663// the PC happened to be: setup's --calibrate measures it once (tools/calibrate.py) and writes `--prefill-pipe <r>`. 3664// `--prefill-pipe 1` needs no r: STRATA_PREFILL_EQUAL's rule - today's chunk count evened out, only when today's last 3665// chunk has stream_all_min() tokens or more. A chunk that size streams every expert its stage does not hold, a shorter 3666// one only the experts it routes to: a tail of a few tokens is nearly free, and evening it out would add a full pass 3667// (two RTX 4090, a prompt 25 tokens past 8192: 25% slower). --calibrate tries it like the other values. 3668namespace { 3669double g_pipe = -1.0 ;// --prefill-pipe; < 0: not given (STRATA_PREFILL_PIPE, else 0) 3670double g_pipe_req = -1.0 ;// the `pipe=` request key; < 0: none 3671double pipe_value () { 3672if (g_pipe_req >=0.0 )return g_pipe_req ; 3673if (g_pipe >=0.0 )return g_pipe ; 3674static const double env = [] { 3675const char * v = std::getenv ("STRATA_PREFILL_PIPE" ); 3676return v != nullptr && v [0 ]!= '\0' ? std::max (0.0 , std::atof (v )) :0.0 ; 3677 }(); 3678return env ; 3679} 3680}// namespace 3681void Prefill ::set_pipe (double value ) {g_pipe = value ; } 3682void Prefill ::set_pipe_request (double value ) {g_pipe_req = value ; } 3683double Prefill ::pipe_setting () {return pipe_value (); } 3684namespace { 3685// b/a in whole tokens: 0 for none (or NaN), at most 2^20 (llround of an infinity is undefined - `pipe=inf` parses) 3686int64_t ratio_tokens (double ratio ) {return ratio > 0.0 ? (int64_t ) std::llround (std::min (ratio ,1048576.0 )) :0 ; } 3687}// namespace 3688int64_t Prefill ::pipe_key (double value ) {return !(value > 0.0 ) ?-1 :value <=1.0 ?0 :ratio_tokens (value ); } 3689// In whole tokens (r rounded): integer sums and a 97/100 test, so a near-tie cannot fall one way in one build and the 3690// other way in another (the same chunks as the double version for every whole r: an exact 97% is not better). 3691int64_t Prefill ::pipeline_chunk (int64_t n ,int64_t cap ,int stages ,double ratio ) { 3692if (stages < 2 || n <=0 || cap <=0 )return cap ; 3693const int64_t r = ratio_tokens (ratio ),S1 = stages - 1 ; 3694if (r == 0 ) { 3695// `--prefill-pipe 1`: STRATA_PREFILL_EQUAL's rule (#693, generate.cpp equal_chunk) - today's chunk count, evened 3696// out on the 256-token grid, only when today's last chunk streams every expert anyway (stream_all_min tokens or 3697// more): evening a short tail out would add a full pass over the experts (two RTX 4090: 25% slower) 3698const int64_t k = (n + cap - 1 ) /cap ; 3699const int64_t last = n - (k - 1 )* cap ; 3700if (k <=1 || last < stream_all_min ())return cap ; 3701const int64_t per = (n + k - 1 ) /k ; 3702return std::min (cap , ((per + 255 ) /256 )* 256 ); 3703 } 3704auto cost = [& ](int64_t c ) {// chunks of c tokens, the last the rest 3705const int64_t k = (n + c - 1 ) /c ; 3706return k * r + n + S1 * (r + std::min (c ,n )); 3707 }; 3708const int64_t today = std::min (n ,cap ); 3709const int64_t today_cost = cost (today ); 3710const int64_t k_min = (n + cap - 1 ) /cap ; 3711const int64_t k_max = ratio > 0.0 ? std::max < int64_t > (k_min , std::min < int64_t > (64 , (n + 511 ) /512 )) :k_min ; 3712int64_t best = today ; 3713int64_t best_cost = today_cost ; 3714for (int64_t k = k_min ;k <=k_max ;++ k ) { 3715const int64_t c = std::min (cap , std::max < int64_t > (512 , (((n + k - 1 ) /k + 255 ) /256 )* 256 )); 3716const int64_t v = cost (c ); 3717if (v < best_cost ) {best_cost = v ;best = c ; } 3718 } 3719return (best < today && 100 * best_cost < 97 * today_cost ) ?best :cap ; 3720} 3721int Prefill ::stage_count ()const { 3722int stages = 1 ; 3723for (const Prefill * p = next_ ;p != nullptr ;p = p -> next_ )++ stages ; 3724return stages ; 3725} 3726int64_t Prefill ::plan_chunk (int64_t n )const { 3727const double pipe = pipe_value (); 3728const int stages = stage_count (); 3729if (pipe <=0.0 || hand_in_ != nullptr || stages < 2 )return 0 ; 3730return pipeline_chunk (n ,impl_ -> T ,stages ,pipe > 1.0 ?pipe :0.0 ); 3731} 3732void Prefill ::force_chunk (int64_t chunk ,bool single ,bool planned ) { 3733force_chunk_ = chunk ; 3734force_single_ = single ; 3735force_planned_ = planned ; 3736} 3737void Prefill ::log_plan (int64_t n ,int64_t chunk ,int stages ) { 3738const double pipe = pipe_value (); 3739 std::fprintf (stderr ,"strata prefill: %lld tokens in %lld-token chunks over %d stages (--prefill-pipe %s)\n" , 3740 (long long )n , (long long )chunk ,stages , 3741pipe > 1.0 ? (std::to_string ((long long )ratio_tokens (pipe ))+ ": b/a" ).c_str () 3742 :"1: today's chunk count, evened out" ); 3743} 3744int64_t Prefill ::chain_experts_streamed ()const { 3745int64_t sum = 0 ; 3746for (const Prefill * p = this ;p != nullptr ;p = p -> next_ )sum += p -> stats_ .experts_streamed ; 3747return sum ; 3748} 3749 3750uint64_t Prefill ::bytes_needed (const core::ModelGeometry & g ,const core::SessionState & ss ,int64_t chunk ,bool src ,int64_t tail ) { 3751return bytes_needed_impl (g ,ss ,chunk , false,src ,tail ); 3752} 3753 3754// What `init` really allocates when the prompt path owns its buffers (no loan): every cudaMalloc rounds up to a 2 MiB 3755// page, and the ring is one allocation (carve). `bytes_needed` stays the borrowed region's sum. 3756uint64_t Prefill ::bytes_needed_owned (const core::ModelGeometry & g ,const core::SessionState & ss ,int64_t chunk , 3757bool src ) { 3758return bytes_needed_impl (g ,ss ,chunk , true,src ); 3759} 3760 3761uint64_t Prefill ::bytes_needed_impl (const core::ModelGeometry & g ,const core::SessionState & ss ,int64_t chunk , 3762bool owned_pages ,bool src ,int64_t tail ) { 3763// the same allocation sequence as `init` (`carve`), counted - with the MoE layout `carve` picks for the same source 3764const size_t T = (size_t )chunk ; 3765bool ok = true; 3766Alloc o ; 3767o .count_only = true; 3768if (owned_pages )o .granule = 2ull <<20 ; 3769o .take < uint16_t > ((size_t )GEMM_SCRATCH ,ok ); 3770o .take < uint8_t > (GEMM_WS ,ok ); 3771if (gemm_dequant_side ())o .take < uint16_t > ((size_t )GEMM_SCRATCH ,ok );// STRATA_DEQUANT_SIDE: the second scratch 3772auto f = [& ](size_t n ) {o .take < float > (n ,ok ); }; 3773// `carve`'s order, buffer for buffer: emb, R, xn, grs, xn16, lo, lo16, gated, inj, mixed, mixed_bf, mixed_h, 3774// bo aliases emb. This counted `xn` unconditionally (carve takes it only under STRATA_GR_UNFUSED) and never counted 3775// `grs`. Net over-count T*(D-HC)*4 bytes: 42 MB at a 1024-token chunk, 252 MB (48 Q8_0 slots) at 6144 - the 3776// prompt path was told it had less room than it did. Safe - the direction is over-estimating, and `take` 3777// still bounds-checks - but it under-sizes every loan, so every chunk the scan picks is one step smaller. 3778if (ring_bytes_on ()) { 3779f (T * N );f (T * D ); 3780if (gr_unfused ())f (T * D ); 3781f (T * HC ); 3782 }else {// STRATA_RING_BYTES=0: 0.1.39's count 3783f (T * N );f (T * D );f (T * D ); 3784 } 3785const bool hcr = pf_hc_region (); 3786if (!hcr ) {o .take < uint16_t > (T * (D + (hc_pad () ?XN_PAD :0 )),ok );f (T * LR );o .take < uint16_t > (T * LR ,ok );f (T * D ); } 3787f (T * HC );f (T * N );o .take < uint16_t > (T * N ,ok );o .take < uint16_t > (T * N ,ok ); 3788if (!emb_reuse_account ())f (T * N );// bo: aliases emb in carve; still counted unless STRATA_EMB_REUSE_ACCOUNT=1 3789const bool f16_io = prompt_f16 ();// the current device's mode (the stage's), as Prefill::init will decide it 3790if (!hcr && bf16x2_hc (f16_io )) {o .take < uint16_t > (T * D ,ok );o .take < uint16_t > (T * LR ,ok ); } 3791if (bf16x2 (f16_io ))o .take < uint16_t > (T * N ,ok ); 3792o .take < int32_t > (T * strata::kernels::kStepCount ,ok ); 3793 strata::kernels::QsaShapes s = core::qsa_shapes (g ); 3794const int64_t cap = strata::kernels::qsa_selection_width (strata::kernels::kTopkMaxCells ,s ); 3795const int64_t max_blocks = ss .qsa_states [ss .qsa_primary ()].max_cells /s .idx_block + 2 ; 3796o .take < uint8_t > ((size_t ) std::max ({gdn_set_bytes (T ),qsa_set_bytes (T ,cap ,max_blocks ,256 ,32 ,s ), 3797moe_set_bytes (T ,g .n_expert ,fused_layout (T ,src ),tail ), 3798hcr ?hc_set_bytes (T ,f16_io ) : (uint64_t )0 }),ok ); 3799for (int i = 0 ;i < DQ ;++ i ) {o .take < uint16_t > (kFF2 * kEmbd ,ok );o .take < uint16_t > (kEmbd * kFF ,ok ); } 3800if (mmq_plan ().any ) { 3801const MmqPlan & mp = mmq_plan (); 3802const size_t ids_rows = mmq_ids_rows (T ); 3803if (ids_rows == 0 )ok = false; 3804o .take < int32_t > (ids_rows ,ok );// ids_identity 3805o .take < int32_t > (bounds_ints (g .n_expert ),ok ); 3806const auto & lay_g = strata::kernels::cpu::expert_layout (); 3807const size_t grp_n = lay_g .native && !lay_g .fmt .empty ()&& lay_g .fmt [0 ].n_embd != (int64_t )N ?LAT_GROUP :MMQ_GROUP ;// as carve: latent packs batch LAT_GROUP 3808o .take < uint8_t > (grp_n * mp .gu_max + MMQ_TAIL ,ok ); 3809o .take < uint8_t > (grp_n * mp .d_max + MMQ_TAIL ,ok ); 3810if (ws::mode ()!= 0 ) {// carve's STRATA_MMQ_WS offsets and chunks 3811o .take < int64_t > ((size_t )g .n_expert ,ok ); 3812o .take < int32_t > (4 * ws::max_chunks ((int64_t )T * K ,g .n_expert ),ok ); 3813 } 3814 }else if (i8_wants_identity ()) { 3815const size_t ids_rows = mmq_ids_rows (T ); 3816if (ids_rows == 0 )ok = false; 3817o .take < int32_t > (ids_rows ,ok );// ids_identity (OWN-I8, a build without MMQ buffers) 3818 }else { 3819const auto & lay0 = strata::kernels::cpu::expert_layout (); 3820if (lay0 .native && !lay0 .fmt .empty ()&& lay0 .fmt [0 ].n_embd != (int64_t )N )o .take < int32_t > (T * K ,ok ); 3821 } 3822if (owned_pages ) { 3823if (stage_slots (T )> 0 )o .take < uint8_t > ((size_t )stage_slots (T )* (size_t )MAXBLOB (),ok );// one allocation 3824 }else { 3825for (int i = 0 ;i < stage_slots (T );++ i )o .take < uint8_t > ((size_t )MAXBLOB (),ok ); 3826 } 3827f (T * N ); 3828f ((size_t ) strata::kernels::NG_HC_DIM ); 3829 strata::kernels::KvHostPools stage ; 3830take_stage (o ,ss ,s ,stage ,ok ); 3831return o .used + (8u <<20 );// alignment slack 3832} 3833 3834uint64_t Prefill ::bytes_needed_no_ring (const core::ModelGeometry & g ,const core::SessionState & ss ,int64_t chunk , 3835bool src ) { 3836return bytes_needed (g ,ss ,chunk ,src )- (uint64_t )stage_slots ((size_t )chunk )* (uint64_t )MAXBLOB (); 3837} 3838 3839int64_t Prefill ::ring_default_slots () { 3840const int r = g_pinned_share >=0.9 ? (fused_ring () ?1024 :384 ) :96 ; 3841return (int64_t ) std::min (r ,ring_cap ()); 3842} 3843 3844int64_t Prefill ::ring_cap_for (int64_t old_chunk ) { 3845// 0.1.39b (#583, measured on the RTX 5070): giving up ring slots for a bigger chunk paid where 0.1.39's ring held 3846// the chunk at 4096 or less (IQ3_XXS 32K prompts +14% to +26%: 4096/384 -> 6656/56) and lost where 0.1.39 already 3847// read 6144-token chunks (the Coder: 6144/384 -> 7936/199, 32K -12%). From kKeepRingChunk on the ring keeps its 3848// 0.1.39 size and the scan only looks for a bigger chunk next to it (IQ3_XXS unpinned 6144/96 -> 6912/96: +9%). 3849constexpr int64_t kKeepRingChunk = 6144 ; 3850return old_chunk >=kKeepRingChunk ?ring_default_slots () :ring_max_slots (); 3851} 3852 3853// the unpinned arm keeps its measured 96 (the PR's rule; the byte budget would have been ~49 slots on IQ3_S) 3854int64_t Prefill ::ring_max_slots () { 3855return g_pinned_share >=0.9 ? (int64_t )ring_budget_slots () : (int64_t ) std::min (96 ,ring_cap ()); 3856} 3857 3858int64_t Prefill ::ring_slots_for (int64_t chunk ) {return ring_slots ((size_t )chunk ); } 3859void Prefill ::set_cpu_pool (kernels::cpu::ExpertPool * pool ) {cpu_pool_ = pool ; } 3860void Prefill ::arm_cpu_share (bool applies ,bool by_default ) { 3861#if !defined(STRATA_USE_HIP )&& !defined(STRATA_HIP_GFX906 ) 3862if (applies && by_default && cpu_share_explicit ()== -2.0 && !g_share_default ) { 3863g_share_default = true; 3864if (switch_point_on ()&& g_sp_resident .load (std::memory_order_acquire ) >=0 && strata::prefill::switch_point::card_known (sp_card ())) { 3865// STRATA_SWITCH_POINT (on by default for its class, 0 = off): the share's limit scales with the card's own floor (floor x kShareRatio), not the fixed 3,072 3866const int64_t lim = strata::prefill::switch_point::share_limit_for (strata::prefill::switch_point::floor_for_card ( 3867g_sp_resident .load (std::memory_order_acquire ),g_sp_total .load (std::memory_order_acquire ),sp_card ())); 3868if (lim > 0 )g_share_limit_arch = lim ; 3869 } 3870 std::fprintf (stderr ,"prefill: the CPU share is ON by default for prompt chunks up to %lld tokens (the idle CPU " 3871"takes some of the experts the GPU would stream; answers can differ slightly from 0.1.40.3, " 3872"mean KL ~0.004 below 1024 tokens, ~0.011 at 1-3K). STRATA_PREFILL_CPU_SHARE=0 turns it off, " 3873"STRATA_PREFILL_CPU_SHARE_MAX=1024 keeps the old limit.\n" , (long long )cpu_share_max ()); 3874 } 3875#elif defined(STRATA_USE_HIP )&& !defined(STRATA_HIP_GFX906 ) 3876// AMD-Q (owner decision 10-31): the same default on a single gfx12 card (arch_defaults.hpp: gfx12_prefill_share_default); every other AMD family stays off 3877if (applies && by_default && cpu_share_explicit ()== -2.0 && !g_share_default ) { 3878int dev = 0 ; 3879cudaDeviceProp prop ; 3880if (cudaGetDevice (& dev )== cudaSuccess && cudaGetDeviceProperties (& prop ,dev )== cudaSuccess && 3881 strata::core::gfx12_prefill_share_default (prop .gcnArchName )) { 3882g_share_default = true; 3883g_share_limit_arch = strata::prefill::share_rules::gfx12_share_limit (fused::gfx12_iq2s_default ()); 3884 std::fprintf (stderr ,"prefill: the CPU share is ON by default for prompt chunks up to %lld tokens on this gfx12 card (the idle CPU " 3885"takes some of the experts the GPU would stream; answers can differ slightly: first-token KL ~0.02 at 1K tokens, " 3886"prompts of 500-1,000 tokens +18..+31%%, 2K and up unchanged). STRATA_PREFILL_CPU_SHARE=0 or STRATA_GFX12_DEFAULTS=0 turns it off, " 3887"STRATA_PREFILL_CPU_SHARE_MAX=1024 keeps a 1,024 limit.\n" , (long long )cpu_share_max ()); 3888 } 3889 } 3890#else 3891 (void )by_default ; 3892#endif 3893if (applies && cpu_share_on ())g_stream_min_share = cpu_share_max (); 3894#if defined(STRATA_PF_OWN_ONLY ) 3895 {// the floor is final now (the card answered before this call): the start-up line of a build without MMQ 3896 std::lock_guard < std::mutex > lk (g_own_line_mu ); 3897g_own_line .mark_ready (); 3898 } 3899own_only_line_flush (); 3900#endif 3901} 3902 3903void Prefill ::set_share_blocked (bool blocked ) {g_share_blocked .store (blocked , std::memory_order_release ); } 3904 3905void Prefill ::fix_cpu_share (double share ) {g_share_fixed = share >=0.0 ? std::clamp (share ,0.0 ,1.0 ) :-1.0 ; } 3906 3907bool Prefill ::cpu_share_balancing () {return cpu_share_env ()< 0.0 ; } 3908bool Prefill ::ring_bytes_enabled () {return ring_bytes_on (); } 3909size_t Prefill ::slot_guard_bytes () {return mmq::direct_slot_guard (); } 3910 3911bool Prefill ::nibble_prompt_check (std::string & why ) { 3912const auto & lay = strata::kernels::cpu::expert_layout (); 3913if (mmq::direct_mode ()!= 0 ) { 3914why = "STRATA_MMQ_DIRECT (the prompt MMQ would read the 4-bit slots in place)" ; 3915return false; 3916 } 3917for (int64_t l = 0 ;lay .native && l < (int64_t )lay .fmt .size ();++ l ) { 3918if (!core::nibble::layer (l ).on )continue ; 3919const auto & f = lay .fmt [(size_t )l ]; 3920const char * w = !mmq_plan ().any || (size_t )l >=mmq_plan ().layer .size ()|| !mmq_plan ().layer [(size_t )l ] 3921 ?"no prompt MMQ for it (the FP16 path dequantizes GGUF blocks)" 3922 :mmq_plan ().wmma_only [(size_t )l ] ?"the WMMA tiles read GGUF blocks" 3923 : fused::native_supported (f .gu_type ,f .d_type ) ?"the fused prompt kernels read GGUF blocks" 3924 : mmq::matrix_bytes (f .gu_type ,kFF2 ,N )!= (size_t ) core::nibble::kRows * f .gu_row || 3925 mmq::matrix_bytes (f .d_type ,N ,kFF )!= f .bytes - f .down_off 3926 ?"MMQ's matrices are not the blob's [gate | up] and down" 3927 :nullptr ; 3928if (w != nullptr ) { 3929why = "layer " + std::to_string (l )+ ": " + w ; 3930return false; 3931 } 3932 } 3933return true; 3934} 3935 3936namespace { 3937 3938const core::WeightRef * need (const core::LayerView & v ,const char * suffix , std::string & err ) { 3939const core::WeightRef * r = v .get (suffix ); 3940if (!r )err = v .name (suffix )+ " is missing" ; 3941return r ; 3942} 3943// STRATA_COLD_TRACE=1 (diagnostic): the wall time of the first 80 dense projections of the process, each synchronized, to show 3944// which first calls pay a one-time cost (library / code object loads). 3945struct ColdTrace { 3946bool on ;int n = 0 ; std::chrono::steady_clock::time_point t0 ; 3947ColdTrace () {const char * e = std::getenv ("STRATA_COLD_TRACE" );on = e != nullptr && e [0 ]== '1' ; } 3948bool begin () { 3949if (!on || n >=80 )return false; 3950cudaDeviceSynchronize (); 3951t0 = std::chrono::steady_clock::now (); 3952return true; 3953 } 3954void end (const char * what ,const std::string & name ,int64_t T ,int64_t N ,int64_t K ) { 3955cudaDeviceSynchronize (); 3956const double ms = std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t0 ).count (); 3957++ n ; 3958 std::fprintf (stderr ,"strata cold-trace: #%d %s %s T=%lld N=%lld K=%lld %.2f ms\n" ,n ,what ,name .c_str (), (long long )T , 3959 (long long )N , (long long )K ,ms ); 3960 } 3961}; 3962ColdTrace g_cold ; 3963bool native_proj (Gemm & gm ,const core::WeightRef * w ,const uint16_t * X ,float * Y ,int64_t T ,const std::string & name , 3964 std::string & err ,int64_t ldy = 0 ,int64_t ldx = 0 ) { 3965if (!w -> native_data ) {err = "prefill: " + name + " has no native GGUF blocks (run with --native)" ;return false; } 3966const bool ct = g_cold .begin (); 3967gm .native (X ,w -> native_type ,w -> native_data ,Y ,T ,w -> ne1 ,w -> ne0 ,ldy ,0.0f ,ldx ); 3968if (ct )g_cold .end ("native" ,name ,T ,w -> ne1 ,w -> ne0 ); 3969return true; 3970} 3971bool bf16_proj (Gemm & gm ,const core::WeightRef * w ,const uint16_t * X ,float * Y ,int64_t T ,const std::string & name , 3972 std::string & err ,int64_t ldy = 0 ,const uint16_t * X_lo = nullptr ,int64_t ldx = 0 , 3973void * stream = nullptr ,bool x_f16 = false) { 3974if (w -> kind != core::WeightKind ::Bf16InF32 || !w -> data ) {err = "prefill: " + name + " is not a resident BF16 tensor" ;return false; } 3975const uint16_t * wb = (const uint16_t * )w -> data ; 3976if (w -> q8_scale != nullptr ) { 3977// STRATA_HC_REQ8: the GEMM takes bf16, so the int8 codes are expanded into one reused scratch on this stream 3978static uint16_t * scratch = nullptr ; 3979static int64_t cap = 0 ; 3980if (w -> elements > cap ) { 3981if (scratch )cudaFree (scratch ); 3982if (cudaMalloc ((void ** )& scratch , (size_t )w -> elements * 2 )!= cudaSuccess ) { 3983scratch = nullptr ;cap = 0 ;err = "prefill: the STRATA_HC_REQ8 scratch" ;return false; 3984 } 3985cap = w -> elements ; 3986 } 3987 strata::kernels::hc_q8_to_bf16 (w -> data ,w -> q8_scale ,scratch , (long long )w -> elements ,stream ); 3988wb = scratch ; 3989 } 3990const bool ct = g_cold .begin (); 3991gm .bf16 (X ,wb ,Y ,T ,w -> ne1 > 0 ?w -> ne1 :1 ,w -> ne0 ,ldy ,0.0f ,ldx ,x_f16 ); 3992if (ct )g_cold .end ("bf16" ,name ,T ,w -> ne1 ,w -> ne0 ); 3993if (X_lo )gm .bf16 (X_lo ,wb ,Y ,T ,w -> ne1 > 0 ?w -> ne1 :1 ,w -> ne0 ,ldy ,1.0f ); 3994return true; 3995} 3996 3997}// namespace 3998 3999namespace { 4000// STRATA_PREFILL_TIMING=1: the prompt path's GPU time by phase. Events are recorded on the compute stream in order; 4001// the time between two consecutive marks is charged to the phase of the first, so a gap where the GPU waits (for the 4002// host's expert grouping, or for an expert's copy) lands on the phase that was waiting. Events are reused: the marks 4003// are folded at every MoE layer's host sync, after which all of them have completed. 4004enum PfPhase {kPfStart ,kPfHc ,kPfGdn ,kPfQsa ,kPfQsaIdx ,kPfQsaSel ,kPfQsaAttn ,kPfRouter ,kPfHostGroup ,kPfGather , 4005kPfWaitCopy ,kPfDequant ,kPfGemmGU ,kPfGemmD ,kPfCombine ,kPfPle ,kPfKvStage ,kPfGdnConv ,kPfGdnRec ,kPfGdnOut ,kPfHcWrite , 4006kPfHcDown ,kPfHcUp ,kPfHcInj ,kPfHcMix ,kPfQsaIdxG ,kPfQsaPrep , 4007kPfCount }; 4008const char * const kPfNames [kPfCount ]= {"embed+steps" ,"hc read" ,"gdn" ,"qsa proj" ,"qsa indexer" ,"qsa select" , 4009"qsa attn" ,"router+shared" ,"host grouping" ,"gather" ,"wait copy" ,"dequant" , 4010"gemm gate/up" ,"gemm down" ,"combine" ,"ple" ,"kv stage" ,"gdn conv+gates" , 4011"gdn recurrence" ,"gdn out proj" ,"hc write" ,"hc read: down+silu" ,"hc read: up" ,"hc read: inject" ,"hc read: mix" ,"qsa: indexer gemms" ,"qsa: norm/rope/kv append/q prep" }; 4012struct PfTimer { 4013bool on = std::getenv ("STRATA_PREFILL_TIMING" )!= nullptr ; 4014 std::vector < cudaEvent_t > ev ; 4015 std::vector < int > ph ; 4016size_t used = 0 ; 4017double ms [kPfCount ]= {}; 4018void mark (int phase ,cudaStream_t s ) { 4019if (!on )return ; 4020// a mark in the phase already running adds nothing to the totals (the gaps are charged to the earlier mark's 4021// phase either way), but every event record is a submission of its own under WDDM (~80 us on a 6900 XT, 4022// Windows 11): compute() marks "dequant" once per expert, which put ~16 records per MMQ group on the stream 4023// and charged the launch gaps they made to "dequant". The same totals, a fraction of the records. 4024if (strata::prefill::timer_mark_repeats (ph .data (),used ,phase ))return ; 4025if (used == ev .size ()) { 4026cudaEvent_t e = nullptr ; 4027cudaEventCreate (& e ); 4028ev .push_back (e ); 4029ph .push_back (0 ); 4030 } 4031ph [used ]= phase ; 4032cudaEventRecord (ev [used ],s ); 4033++ used ; 4034 } 4035// every recorded mark has completed (the stream was synchronized): charge the gaps, keep the last mark 4036void fold () { 4037if (!on || used < 2 )return ; 4038for (size_t i = 0 ;i + 1 < used ;++ i ) { 4039float t = 0.0f ; 4040if (cudaEventElapsedTime (& t ,ev [i ],ev [i + 1 ])== cudaSuccess )ms [ph [i ]]+= t ; 4041 } 4042 std::swap (ev [0 ],ev [used - 1 ]); 4043 std::swap (ph [0 ],ph [used - 1 ]); 4044used = 1 ; 4045 } 4046 ~PfTimer () { 4047for (cudaEvent_t e :ev )cudaEventDestroy (e ); 4048 } 4049}; 4050// multi-GPU: the peer's own timeline (STRATA_PREFILL_TIMING): marks on the peer stream, folded with the primary's 4051enum PePhase {kPeIdle ,kPeMoeIn ,kPeMoeGemm ,kPeMoeOut ,kPeCount }; 4052const char * const kPeNames [kPeCount ]= {"idle" ,"moe in" ,"moe gemm" ,"moe out" }; 4053struct PeTimer { 4054bool on = std::getenv ("STRATA_PREFILL_TIMING" )!= nullptr ; 4055int dev = -1 ; 4056 std::vector < cudaEvent_t > ev ; 4057 std::vector < int > ph ; 4058size_t used = 0 ; 4059double ms [kPeCount ]= {}; 4060void mark (int phase ,cudaStream_t s ) {// the peer device is current 4061if (!on )return ; 4062if (used == ev .size ()) { 4063cudaEvent_t e = nullptr ; 4064cudaEventCreate (& e ); 4065ev .push_back (e ); 4066ph .push_back (0 ); 4067 } 4068ph [used ]= phase ; 4069cudaEventRecord (ev [used ],s ); 4070++ used ; 4071 } 4072void fold () {// every mark has completed 4073if (!on || used < 2 )return ; 4074for (size_t i = 0 ;i + 1 < used ;++ i ) { 4075float t = 0.0f ; 4076if (cudaEventElapsedTime (& t ,ev [i ],ev [i + 1 ])== cudaSuccess )ms [ph [i ]]+= t ; 4077 } 4078 std::swap (ev [0 ],ev [used - 1 ]); 4079 std::swap (ph [0 ],ph [used - 1 ]); 4080used = 1 ; 4081 } 4082 ~PeTimer () { 4083if (dev < 0 )return ; 4084int prev = 0 ; 4085cudaGetDevice (& prev ); 4086cudaSetDevice (dev ); 4087for (cudaEvent_t e :ev )cudaEventDestroy (e ); 4088cudaSetDevice (prev ); 4089 } 4090}; 4091 4092// ---- KVA (STRATA_KVA, research): the capture and oracle taps of the late layers' block inputs --------------- 4093// 4094// A capture run writes, for every layer at or after the split and every chunk, the chunk's multi-stream residual 4095// R [T, hc*n_embd] as it ENTERS the layer - exactly the vector a projector would have to produce. One file per 4096// layer (`L<layer>.bin`), rows in position order, bf16 (fp32 with STRATA_KVA_CAPTURE_FP32, for parity runs): a 4097// reader seeks straight to a position. The oracle mode replays such a file in place of a projector, which is how 4098// the state-only path is checked against the full one before any weights are fitted. 4099struct KvaTap { 4100 std::string dir ; 4101bool fp32 = false; 4102 std::vector < std::FILE *> f ;// one per layer, opened on first use 4103 std::vector < int64_t > next_pos ;// where the next record must start (0: nothing written yet) 4104 std::vector < float > host ;// one chunk's rows, fp32 4105 std::vector < uint16_t > bf ;// their bf16 image 4106 std::string err ; 4107 4108bool open (const std::string & d ,bool is_fp32 ) { 4109dir = d ; 4110fp32 = is_fp32 ; 4111f .assign (128 ,nullptr ); 4112next_pos .assign (128 ,0 ); 4113return true; 4114 } 4115void close () { 4116for (std::FILE *& p :f ) {if (p != nullptr ) std::fclose (p );p = nullptr ; } 4117 } 4118/// A new cold read starts: a capture file holds one prompt's rows, so every layer starts over. 4119void begin_prompt () { 4120close (); 4121if (next_pos .empty ())next_pos .assign (f .size (),0 ); 4122for (int64_t & p :next_pos )p = 0 ; 4123 } 4124 std::string path (int64_t layer )const {return dir + "/L" + std::to_string ((long long )layer )+ ".bin" ; } 4125 4126/// The chunk's rows of `layer` from the device residual `R` - a capture. 4127bool write (int64_t layer ,const float * R ,int64_t T ,int64_t p0 ,int64_t D ,cudaStream_t cs ) { 4128if (layer < 0 || layer >= (int64_t )f .size ()) {err = "kva capture: layer out of range" ;return false; } 4129if (next_pos [(size_t )layer ]!= p0 ) { 4130err = "kva capture: layer " + std::to_string ((long long )layer )+ " expects position " + 4131 std::to_string ((long long )next_pos [(size_t )layer ])+ ", got " + std::to_string ((long long )p0 )+ 4132" (a capture needs one cold, in-order read)" ; 4133return false; 4134 } 4135host .resize ((size_t )T * D ); 4136if (cudaMemcpyAsync (host .data (),R , (size_t )T * D * 4 ,cudaMemcpyDeviceToHost ,cs )!= cudaSuccess || 4137cudaStreamSynchronize (cs )!= cudaSuccess ) { 4138err = "kva capture: the residual copy failed" ; 4139return false; 4140 } 4141 std::FILE *& p = f [(size_t )layer ]; 4142if (p == nullptr ) { 4143p = std::fopen (path (layer ).c_str (),"wb" ); 4144if (p == nullptr ) {err = "kva capture: cannot write " + path (layer );return false; } 4145 } 4146if (fp32 ) { 4147 std::fwrite (host .data (),4 , (size_t )T * D ,p ); 4148 }else { 4149bf .resize ((size_t )T * D ); 4150for (size_t i = 0 ;i < bf .size ();++ i ) {// round to nearest even, as STRATA_PREFILL_DUMP_R_ALL does 4151uint32_t u ; 4152 std::memcpy (& u ,& host [i ],4 ); 4153u += 0x7fffu + ((u >>16 )& 1u ); 4154bf [i ]= (uint16_t ) (u >>16 ); 4155 } 4156 std::fwrite (bf .data (),2 ,bf .size (),p ); 4157 } 4158 std::fflush (p ); 4159next_pos [(size_t )layer ]= p0 + T ; 4160return true; 4161 } 4162 4163/// The chunk's rows of `layer` into the device residual `R` - an oracle replay. 4164bool read (int64_t layer ,float * R ,int64_t T ,int64_t p0 ,int64_t D ,cudaStream_t cs ) { 4165if (layer < 0 || layer >= (int64_t )f .size ()) {err = "kva oracle: layer out of range" ;return false; } 4166 std::FILE *& p = f [(size_t )layer ]; 4167if (p == nullptr ) { 4168p = std::fopen (path (layer ).c_str (),"rb" ); 4169if (p == nullptr ) {err = "kva oracle: cannot read " + path (layer );return false; } 4170 } 4171const int64_t n = T * D ; 4172const int64_t esz = fp32 ?4 :2 ; 4173const long long off = (long long ) ((int64_t )p0 * D * esz ); 4174#if defined(_WIN32 ) 4175const bool seek_ok = _fseeki64 (p ,off ,SEEK_SET )== 0 ; 4176#else 4177const bool seek_ok = fseeko (p , (off_t )off ,SEEK_SET )== 0 ; 4178#endif 4179if (!seek_ok ) {err = "kva oracle: cannot seek " + path (layer );return false; } 4180host .resize ((size_t )n ); 4181if (fp32 ) { 4182const size_t got = std::fread (host .data (),4 , (size_t )n ,p ); 4183if (got != (size_t )n ) { 4184err = "kva oracle: short read of " + path (layer )+ " at position " + std::to_string ((long long )p0 )+ 4185": wanted " + std::to_string ((long long )n )+ " values, got " + std::to_string ((long long )got ); 4186return false; 4187 } 4188 }else { 4189bf .resize ((size_t )n ); 4190const size_t got = std::fread (bf .data (),2 , (size_t )n ,p ); 4191if (got != (size_t )n ) { 4192err = "kva oracle: short read of " + path (layer )+ " at position " + std::to_string ((long long )p0 )+ 4193": wanted " + std::to_string ((long long )n )+ " values, got " + std::to_string ((long long )got ); 4194return false; 4195 } 4196for (size_t i = 0 ;i < bf .size ();++ i ) {// bf16 -> fp32: the top half, exactly 4197const uint32_t u = (uint32_t )bf [i ] <<16 ; 4198 std::memcpy (& host [i ],& u ,4 ); 4199 } 4200 } 4201if (cudaMemcpyAsync (R ,host .data (), (size_t )n * 4 ,cudaMemcpyHostToDevice ,cs )!= cudaSuccess ) { 4202err = "kva oracle: the upload failed" ; 4203return false; 4204 } 4205return true; 4206 } 4207}; 4208}// namespace 4209 4210bool Prefill ::run_impl (const int64_t * tokens ,int64_t n ,int64_t pos0 , std::string & err ) { 4211err .clear (); 4212// force_chunk is for this run only: taken before any early return can leave it to the next one 4213const int64_t forced = hand_in_ == nullptr ? std::exchange (force_chunk_ ,0 ) :0 ; 4214const bool forced_single = force_single_ ,forced_planned = force_planned_ ; 4215Impl & m = * impl_ ; 4216const core::OnDevice on_device (m .device ); 4217// the stall report asks this stream (the one the waits below block on) whether its work is done (#5718 follow-up) 4218const core::WatchedStream watched ("the prompt's GPU work" , (void * )m .cs ,m .device ); 4219const core::ModelGeometry & g = * m .g ; 4220 core::SessionState & ss = * m .ss ; 4221const auto t_start = Clock ::now (); 4222const int64_t LB = stage_lb_ ,LE = stage_le_ ; 4223// STRATA_KVA: the approximate-prefix plan of this run, if it qualifies (a cold read of one long prompt, one 4224// stage, no capture). Positions [0, kva_frontier) are approximated in the layers at and after the split. 4225const KvaConfig & kva = kva_config (); 4226const KvaEngine & kva_eng = kva_engine (); 4227const int64_t kva_suffix = kva .effective_suffix (); 4228bool kva_routine = false; 4229const char * kva_why_not = kva .decline (kva_eng ,pos0 ,n ,LB ,LE < 0 ?-1 :LE , (int64_t )g .n_layers , 4230embd_rows != nullptr , !tap_layers_ .empty (),& kva_routine , 4231g .n_layers != 48 || g .n_expert != 512 ); 4232if (kva_why_not == nullptr && (g .n_layers != 48 || g .n_expert != 512 )) { 4233// STRATA_KVA_ANY_MODEL=1 (research): allowed on a shape KVA was not measured on, with a warning once 4234static std::atomic < bool > warned {false}; 4235if (!warned .exchange (true)) 4236 std::fprintf (stderr ,"strata prefill: WARNING: STRATA_KVA_ANY_MODEL=1: KVA was only measured on Qwen3.8-Flash-Next " 4237"(48 layers, 512 experts); this model has %lld layers and %lld experts\n" , 4238 (long long )g .n_layers , (long long )g .n_expert ); 4239 } 4240const bool kva_run = kva_why_not == nullptr ; 4241const int64_t kva_split = std::min < int64_t > (std::max < int64_t > (kva .split ,1 ),g .n_layers ); 4242const int64_t kva_frontier = std::max < int64_t > (0 ,n - kva_suffix ); 4243static KvaTap kva_capture ;// process-wide: one cold read at a time, so the per-layer position is enough 4244static KvaTap kva_oracle ; 4245int64_t kva_positions = 0 ,kva_chunks = 0 ;// what actually took the approximate path (diagnostics) 4246kva_floor_ = 0 ;// this run's: raised below as chunks are approximated 4247if (kva .capture && kva_capture .f .empty ())kva_capture .open (kva .capture_dir ,kva .capture_fp32 ); 4248if (kva .capture && pos0 == 0 && hand_in_ == nullptr )kva_capture .begin_prompt ();// one prompt per capture 4249if (kva_run && kva .mode == KvaConfig ::Mode ::Oracle && kva_oracle .f .empty ()) 4250kva_oracle .open (kva .oracle_dir ,kva .oracle_fp32 ); 4251// The direct successor's future lives on the Prefill object. Intermediate 4252// stages therefore do not drain the complete remaining GPU chain here. 4253double host_sync_ms = 0 ,host_chunk_ms = 0 ,host_setup_ms = 0 ;// STRATA_PREFILL_TIMING: the host's share 4254 strata::kernels::QsaShapes s = core::qsa_shapes (g ); 4255// read once (STRATA_KV_PREFETCH=1/0: the next streamed layer's KV prefix is staged on its own stream) 4256static const bool kv_prefetch_on = [] { 4257const char * e = std::getenv ("STRATA_KV_PREFETCH" ); 4258return e ? std::atoi (e )!= 0 : false; 4259 }(); 4260const bool kv_prefetch = kv_prefetch_on ; 4261if (kv_prefetch ) { 4262if ((!m .kv_copy && cudaStreamCreateWithFlags (& m .kv_copy ,cudaStreamNonBlocking )!= cudaSuccess )|| 4263 (!m .kv_released && cudaEventCreateWithFlags (& m .kv_released ,cudaEventDisableTiming )!= cudaSuccess )|| 4264 (!m .kv_ready && cudaEventCreateWithFlags (& m .kv_ready ,cudaEventDisableTiming )!= cudaSuccess )) { 4265err = "prefill: KV prefetch stream/events" ; 4266return false; 4267 } 4268 } 4269// An early return must drain DMA before the caller refills the borrowed expert slots. 4270struct KvDrain { 4271cudaStream_t stream ; 4272 ~KvDrain () {if (stream )cudaStreamSynchronize (stream ); } 4273 }kv_drain {kv_prefetch ?m .kv_copy :nullptr }; 4274KvDrain ple_drain {m .ple_copy };// STRATA_PLE_COPY_STREAM: no upload left in flight from a buffer the next run refills 4275int64_t kv_prefetches = 0 ; 4276const uint64_t gdn_floats = (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size + 4277 (uint64_t )g .ssm_conv_channels * (g .ssm_d_conv - 1 ); 4278int32_t prev [2 ]= {ss .ple_prev [0 ],ss .ple_prev [1 ]}; 4279// layer split: a prompt of one chunk runs the stages one after the other, so the next stage's GPU idles while 4280// this one reads; it streams and computes a share of this stage's experts then (set_stage_helper), in the 4281// place of a --peer-device peer, and gives the stage back its own buffers when the run ends 4282// the chunk this prompt is read in: the buffers' size, or with --prefill-pipe on a layer split the one that keeps 4283// every stage busy (pipeline_chunk: 1 evens today's chunk count out, a number > 1 is the rig's b/a). Only the first 4284// stage chooses: a later one is handed one chunk at a time. A run the engine forced (force_chunk: one part of a 4285// segment it planned on its whole length) reads in that chunk and keeps the segment's single/planned flags. 4286if (forced > m .T ) { 4287err = "prefill: a forced chunk of " + std::to_string ((long long )forced )+ " tokens is larger than the buffers' " + 4288 std::to_string ((long long )m .T ); 4289return false; 4290 } 4291const int64_t planned_C = forced > 0 ?0 :plan_chunk (n ); 4292const int64_t C = forced > 0 ?forced :planned_C > 0 ?planned_C :m .T ; 4293if (planned_C > 0 && C < std::min (n ,m .T ))log_plan (n ,C ,stage_count ()); 4294const bool single_chunk = hand_in_ == nullptr ? (forced > 0 ?forced_single :n <=C ) :single_chunk_ ; 4295// a read the pipe chunked takes no CPU share: its chunks overlap on the stages by design, and which stage won the 4296// pool would decide which experts the CPU computed (other bits) - timing, where the chunks are a function of n 4297const bool pipe_chunked = hand_in_ == nullptr ? (forced > 0 ?forced_planned :planned_C > 0 && C < std::min (n ,m .T )) 4298 :pipe_chunked_ ; 4299const bool helped = single_chunk && bind_stage_helper (n ); 4300if (helped ) std::swap (m .pp ,m .help_pp ); 4301struct HelpScope { 4302Impl & m ; 4303bool on ; 4304 ~HelpScope () { 4305if (!on )return ; 4306const core::OnDevice d (m .pp -> dev );// its work is done before the stage hands over; settle its streams 4307cudaStreamSynchronize (m .pp -> s_cp ); 4308cudaStreamSynchronize (m .pp -> s_out ); 4309cudaStreamSynchronize (m .pp -> s ); 4310 std::swap (m .pp ,m .help_pp ); 4311 } 4312 }help_scope {m ,helped }; 4313PfTimer pt ; 4314PeTimer pe ; 4315if (m .pp )pe .dev = m .pp -> dev ;else pe .on = false; 4316const cudaStream_t cs = (cudaStream_t )m .cs ; 4317// the MMQ row table lives in the borrowed cache slots, which the refill after a prompt overwrites with experts: 4318// write it again for every prompt (a layout is reused as long as the chunk and the slots are the same) 4319if (m .ids_identity != nullptr ) mmq::iota (m .ids_identity , (int64_t )mmq_ids_rows ((size_t )m .T ),m .cs ); 4320// The PLE rows of a chunk are read from the model file on the host (an SSD read per missed row): the chunk 4321// after this one is read on a thread while the GPU runs this one, into the other of two buffers. The rows 4322// depend only on the tokens (the two before a position name its n-grams), so this is the same data. 4323const bool ple_on = ss .ple .ready ()&& LB <=1 && 1 < LE ; 4324// the PLE block batched over the chunk: the pinned postops and a BF16 or GGUF-native key (else token by token); 4325// STRATA_PLE_BATCH=0 keeps the per-token block (the A/B) 4326const bool ple_batch_env = ple_batch_enabled (); 4327const bool ple_batch = ple_on && ple_batch_env && strata::kernels::ple_native_postops_enabled ()&& 4328 (ss .ple .w .key_bf16 != nullptr || ss .ple .w .key_native_data != nullptr )&& 4329m .region_bytes / ((uint64_t ) (3 * strata::kernels::NG_HC_DIM + N + 4 )* 4 + (uint64_t )N * 2 + 4096 ) >=64 ; 4330const int32_t prev0 [2 ]= {prev [0 ],prev [1 ]}; 4331auto ple_gather = [& m ,& ss ,tokens ,n ,prev0 ,C ](int64_t c0 ,int buf , std::string & e )-> bool { 4332const int64_t T = std::min (C ,n - c0 ); 4333auto at = [& ](int64_t i ) {return i < 2 ?prev0 [i ] : (int32_t )tokens [i - 2 ]; };// prev0, then the tokens 4334int32_t pv [2 ]= {at (c0 ),at (c0 + 1 )}; 4335for (int64_t t = 0 ;t < T ;++ t ) { 4336const int32_t tok = (int32_t )tokens [c0 + t ]; 4337 strata::kernels::ngram_rows (& tok ,pv ,1 ,ss .ple .consts , 4338m .ple_rows [buf ].data ()+ t * strata::kernels::PLE_N_HEADS ); 4339pv [0 ]= pv [1 ]; 4340pv [1 ]= tok ; 4341 } 4342// STRATA_PLE_COMPACT=1: the raw rows (1,440 bytes a token instead of 10,240 floats' bytes) into the same pinned 4343// buffer; ple_land uploads them and dequantizes on the device 4344if (ple_compact_on ()&& m .ple_pageable [buf ].empty ()&& m .ple_raw_dev != nullptr && 4345ss .ple .table -> gather_raw_iq4nl (m .ple_rows [buf ].data (), (size_t )T , (uint8_t * )m .ple_emb_host [buf ])) { 4346m .ple_compact [buf ]= true; 4347return true; 4348 } 4349m .ple_compact [buf ]= false; 4350return ss .ple .table -> gather_batch (m .ple_rows [buf ].data (), (size_t )T ,m .ple_emb_host [buf ],e ); 4351 }; 4352 std::string ple_next_err ; 4353 std::future < bool > ple_next ;// declared after everything it reads: an early return waits for it 4354int ple_buf = 0 ; 4355 4356if (hand_in_ == nullptr )stopped_at_ = -1 ; 4357#if defined(STRATA_HAVE_DFLASH2 ) 4358 std::vector < int > tap_slot ; 4359// the taps of the layers THIS stage runs (the whole model without a split), at [row][its taps][n_embd]; on a split the callback of each stage 4360// gets its own share and the engine lands them on the drafter's card 4361tap_local_ .clear (); 4362for (int l :tap_layers_ )if (l >=stage_lb_ && (stage_le_ < 0 || l < stage_le_ )&& l < g .n_layers - 1 )tap_local_ .push_back (l ); 4363if (!tap_local_ .empty ()) { 4364if (tap_dev_ == nullptr && 4365cudaMalloc ((void ** )& tap_dev_ , (size_t )tap_cap_ * tap_local_ .size ()* (size_t )g .n_embd * 4 )!= cudaSuccess ) { 4366 (void )cudaGetLastError (); 4367tap_dev_ = nullptr ; 4368err = "prefill: the DFlash2 tap staging does not fit in VRAM" ; 4369return false; 4370 } 4371tap_slot .assign ((size_t )g .n_layers ,-1 ); 4372for (size_t i = 0 ;i < tap_local_ .size ();++ i )tap_slot [(size_t )tap_local_ [i ]]= (int )i ; 4373 } 4374#endif 4375for (int64_t c0 = 0 ;c0 < n ;c0 += C ) { 4376if (should_stop && should_stop ()) {err = "cancelled" ;return false; } 4377// the first stage: end the run before this chunk (every chunk before it is handed on; the caller's drain 4378// waits for the later stages to read them) 4379if (c0 > 0 && hand_in_ == nullptr && stop_at_chunk && stop_at_chunk ()) { 4380stopped_at_ = c0 ; 4381break ; 4382 } 4383if (std::getenv ("STRATA_TRACE" )) { 4384static Clock ::time_point t0 ;// process-wide: the stages run on different threads 4385static bool set = false; 4386if (!set ) {t0 = Clock ::now ();set = true; } 4387const double ms = std::chrono::duration < double , std::milli > (Clock ::now ()- t0 ).count (); 4388 std::fprintf (stderr ,"strata trace: prompt chunk %lld of %lld stage [%lld,%lld) %.1f ms\n" , (long long )c0 , 4389 (long long )n , (long long )stage_lb_ , (long long )stage_le_ ,ms ); 4390 std::fflush (stderr ); 4391 } 4392const int64_t T = std::min (C ,n - c0 ),p0 = pos0 + c0 ; 4393// A fused layout carved with a tail (relayout's `tail`, loan_rules.hpp) holds MMQ's rows for that many tokens of a 4394// chunk below the stream floor: a longer one would overrun GU / H / Xq / Hq (an illegal access, or a hang). The 4395// lend sizes the tail from the segment, so this is the clean error for anything that drifts from it. 4396if (m .fused_bufs && T < stream_all_min ()&& T > tail_room ()) { 4397err = "prefill: a chunk of " + std::to_string ((long long )T )+ " tokens below the stream floor does not fit the fused layout's tail of " + 4398 std::to_string ((long long )tail_room ())+ " tokens" ; 4399return false; 4400 } 4401// STRATA_KVA: this chunk is approximated in the layers at and after the split when its last position is 4402// before the request's full-computation suffix; a chunk in the suffix runs the ordinary path everywhere. 4403const bool kva_approx = kva_run && (p0 + T <=kva_frontier ); 4404if (kva_approx ) { 4405kva_positions += T ; 4406++ kva_chunks ; 4407kva_floor_ = p0 + T ;// the chunks are a prefix of the run: this is the first position with real rows 4408 } 4409 core::progress_at ("reading the prompt (batched): preparing the chunk from token" ,p0 );// #251 4410#if defined(STRATA_HAVE_DFLASH2 ) 4411// DFlash2 prompt taps: the rows of this chunk at positions >= tap_first_ (the drafter looks back one window) 4412const int64_t tap_t0 = tap_dev_ != nullptr && !tap_local_ .empty () ? std::min < int64_t > (T , std::max < int64_t > (0 ,tap_first_ - p0 )) :T ; 4413const int64_t tap_rows = T - tap_t0 ; 4414if (tap_rows > tap_cap_ ) {err = "prefill: the DFlash2 tap staging is smaller than the chunk's tapped rows" ;return false; } 4415#else 4416const int64_t tap_t0 = 0 ,tap_rows = 0 ; 4417#endif 4418++ stats_ .chunks ; 4419pt .mark (kPfStart ,cs ); 4420const auto tsetup = Clock ::now (); 4421// ---- embeddings, broadcast to the four streams - or, in a later stage of a layer split, the rows the 4422// previous stage handed on 4423if (hand_in_ != nullptr && hand_ev_ != nullptr ) { 4424// STRATA_HANDOFF_PIPE: each piece's upload waits on the GPU for its download on the stage before. The 4425// stage before split the chunk it handed on (n rows); one chunk here is all of it, otherwise (a smaller 4426// chunk here) every piece is waited for before the one copy. 4427const auto * ev = static_cast < const cudaEvent_t *> (hand_ev_ ); 4428const bool whole = c0 == 0 && T == n ; 4429bool ok = true; 4430for (int i = 0 ;ok && i < hand_pieces_ ;++ i ) { 4431int64_t r0 = 0 ,nr = 0 ; 4432handoff_piece (n ,hand_pieces_ ,i ,r0 ,nr ); 4433ok = cudaStreamWaitEvent (m .cs ,ev [i ],0 )== cudaSuccess ; 4434if (ok && whole && nr > 0 ) 4435ok = cudaMemcpyAsync (m .R + (size_t )r0 * D ,hand_in_ + (size_t )r0 * D , (size_t )nr * D * 4 , 4436cudaMemcpyHostToDevice ,m .cs )== cudaSuccess ; 4437 } 4438if (ok && !whole ) 4439ok = cudaMemcpyAsync (m .R ,hand_in_ + (size_t )c0 * D , (size_t )T * D * 4 ,cudaMemcpyHostToDevice , 4440m .cs )== cudaSuccess ; 4441if (!ok ) { 4442err = std::string ("prefill: the layer split's hand-off upload failed (STRATA_HANDOFF_PIPE): " )+ 4443cudaGetErrorString (cudaGetLastError ()); 4444return false; 4445 } 4446 }else if (hand_in_ != nullptr ) { 4447if (cudaMemcpyAsync (m .R ,hand_in_ + (size_t )c0 * D , (size_t )T * D * 4 ,cudaMemcpyHostToDevice ,m .cs )!= 4448cudaSuccess ) { 4449err = "prefill: the layer split's hand-off upload failed" ; 4450return false; 4451 } 4452 } 4453// C-4: the whole chunk's rows in one gather (the same per-element arithmetic as the per-token path, so the 4454// same bits); a chunk with picture rows, or a token outside the table, takes the per-token path 4455bool batched = hand_in_ == nullptr && m .tok_dev != nullptr ; 4456const core::NativeEmbed * nemb = core::native_embed (); 4457const core::WeightRef * wemb = nemb ?nullptr :m .wt -> find ("token_embd.weight" ); 4458if (batched && nemb == nullptr && 4459 (wemb == nullptr || wemb -> codebook_iq4nl || wemb -> ne0 != g .n_embd || wemb -> group_elems <=0 || 4460 (wemb -> code_bits != 2 && wemb -> code_bits != 4 && wemb -> code_bits != 8 ))) 4461batched = false; 4462for (int64_t t = 0 ;batched && t < T ;++ t ) { 4463const int64_t tok = tokens [c0 + t ]; 4464if ((embd_rows && embd_rows [p0 + t ])|| tok < 0 || (wemb && tok >=wemb -> ne1 ))batched = false; 4465else m .tok_host [(size_t )t ]= (int32_t )tok ; 4466 } 4467if (batched ) { 4468if (!m .tok_up .upload (m .tok_dev ,m .tok_host .data (), (size_t )T ,m .cs )) { 4469err = "prefill: the token id upload failed" ; 4470return false; 4471 } 4472if (nemb ) { 4473nemb -> gather_dev (m .tok_dev ,T ,m .emb ,m .cs ); 4474 }else { 4475const auto * codes = (const uint8_t * )wemb -> data ; 4476const auto * scales = (const float * ) (codes + wemb -> codes_bytes ); 4477const auto * offsets = wemb -> has_offset ? (const float * ) (codes + wemb -> codes_bytes + wemb -> scales_bytes ) 4478 :nullptr ; 4479 strata::kernels::embedding_gather_dev (codes ,scales ,offsets ,m .tok_dev , (int )T ,wemb -> ne0 , 4480wemb -> code_bits ,wemb -> code_bias ,wemb -> group_elems , 4481 (uint64_t ) (wemb -> ne0 / (8 /wemb -> code_bits )), 4482 (uint64_t ) (wemb -> ne0 /wemb -> group_elems ),m .emb ,m .cs ); 4483 } 4484 } 4485for (int64_t t = 0 ;hand_in_ == nullptr && !batched && t < T ;) { 4486const float * row = embd_rows ?embd_rows [p0 + t ] :nullptr ; 4487if (row ) { 4488// #1996: the picture's rows live in the caller's (pageable) memory. A run of consecutive rows is 4489// gathered into one pinned slot and goes up as one copy; the slot is guarded by its event. 4490const int64_t row_bytes = N * 4 ,run_max = std::max < int64_t > (1 , (4 <<20 ) /row_bytes ); 4491int64_t t1 = t + 1 ; 4492while (t1 < T && t1 - t < run_max && embd_rows [p0 + t1 ])++ t1 ; 4493void * stage = m .up_ring .acquire ((size_t ) ((t1 - t )* row_bytes )); 4494cudaError_t e = cudaSuccess ; 4495if (stage != nullptr ) { 4496for (int64_t r = t ;r < t1 ;++ r ) 4497 std::memcpy ((char * )stage + (size_t ) ((r - t )* row_bytes ),embd_rows [p0 + r ], (size_t )row_bytes ); 4498e = m .up_ring .submit (m .emb + t * N ,stage , (size_t ) ((t1 - t )* row_bytes ),m .cs ); 4499 }else {// no pinned RAM: row by row from the caller's memory, each waited for 4500for (int64_t r = t ;r < t1 && e == cudaSuccess ;++ r ) 4501e = core::PinnedRing ::direct (m .emb + r * N ,embd_rows [p0 + r ], (size_t )row_bytes ,m .cs ); 4502 } 4503if (e != cudaSuccess ) { 4504err = "prefill: the image embedding upload failed" ; 4505return false; 4506 } 4507t = t1 ; 4508 }else { 4509if (!core::embed_row (* m .wt ,g ,tokens [c0 + t ],m .emb + t * N ,m .cs ,err ))return false; 4510++ t ; 4511 } 4512 } 4513if (hand_in_ == nullptr )gr_broadcast (m .emb ,m .R ,T ,m .cs ); 4514// ---- the PLE rows of the whole chunk, one batched SSD request on a thread (see ple_gather). A later chunk's 4515// were read ahead during the previous chunk; the first chunk's are read beside layer 0 - they are needed from 4516// layer 1 on, and gathering them here first left the GPU idle for the whole read (~0.4 s of a 32K prompt) 4517if (ple_on && !ple_next .valid ()) 4518ple_next = std::async (std::launch::async , [& ple_gather ,& ple_next_err ,c0 ,b = ple_buf ] { 4519 strata::aux_cpus::pin_current_thread (); 4520return ple_gather (c0 ,b ,ple_next_err ); 4521 }); 4522bool ple_pending = ple_on ; 4523// the chunk's rows onto the device just before layer 1 reads them, and the next chunk's gather started 4524auto ple_land = [& ]()-> bool { 4525if (!ple_pending )return true; 4526ple_pending = false; 4527const auto tp = Clock ::now (); 4528if (!ple_next .get ()) { 4529err = ple_next_err ; 4530return false; 4531 } 4532// #1996: the pageable fallback (no RAM to pin) goes up through a pinned slot; the pinned buffers as before 4533const size_t raw_bytes = (size_t )T * strata::kernels::PLE_N_HEADS * strata::kernels::PLE_ROW_BYTES ; 4534// STRATA_PLE_COPY_STREAM: the raw rows go up on their own stream once the previous chunk's dequant has read 4535// the buffer (ple_raw_free), and the compute stream waits for them (ple_copied) only at the dequant - the 4536// DMA overlaps layer 0 instead of idling the compute queue. ple_copied still marks that buffer's upload 4537// done, on whichever stream ran it, for the host-side reuse guard below. 4538const bool ple_side = m .ple_compact [ple_buf ]&& m .ple_copy != nullptr ; 4539const cudaStream_t ple_up = ple_side ?m .ple_copy :m .cs ; 4540if ((ple_side && cudaStreamWaitEvent (m .ple_copy ,m .ple_raw_free ,0 )!= cudaSuccess )|| 4541 (m .ple_compact [ple_buf ] 4542 ?cudaMemcpyAsync (m .ple_raw_dev ,m .ple_emb_host [ple_buf ],raw_bytes ,cudaMemcpyHostToDevice ,ple_up ) 4543 :m .ple_pageable [ple_buf ].empty () 4544 ?cudaMemcpyAsync (m .ple_emb ,m .ple_emb_host [ple_buf ], (size_t )T * N * 4 ,cudaMemcpyHostToDevice ,m .cs ) 4545 :m .up_ring .h2d (m .ple_emb ,m .ple_emb_host [ple_buf ], (size_t )T * N * 4 ,m .cs ))!= 4546cudaSuccess || 4547cudaEventRecord (m .ple_copied [ple_buf ],ple_up )!= cudaSuccess || 4548 (ple_side && cudaStreamWaitEvent (m .cs ,m .ple_copied [ple_buf ],0 )!= cudaSuccess )) { 4549err = std::string ("prefill: the PLE rows' upload failed: " )+ cudaGetErrorString (cudaGetLastError ()); 4550return false; 4551 } 4552if (m .ple_compact [ple_buf ]) { 4553 strata::kernels::ple_iq4nl_dequant (m .ple_raw_dev ,T * strata::kernels::PLE_N_HEADS ,m .ple_emb ,m .cs ); 4554if (ple_side && cudaEventRecord (m .ple_raw_free ,m .cs )!= cudaSuccess ) { 4555err = std::string ("prefill: the PLE rows' upload failed: " )+ cudaGetErrorString (cudaGetLastError ()); 4556return false; 4557 } 4558 } 4559if (c0 + C < n ) { 4560// the other buffer's upload (a chunk ago) is done before the SSD thread refills it 4561if (cudaEventSynchronize (m .ple_copied [ple_buf ^1 ])!= cudaSuccess ) { 4562err = std::string ("prefill: the PLE rows' upload failed: " )+ cudaGetErrorString (cudaGetLastError ()); 4563return false; 4564 } 4565ple_next = std::async (std::launch::async , [& ple_gather ,& ple_next_err ,c1 = c0 + C ,b = ple_buf ^1 ] { 4566 strata::aux_cpus::pin_current_thread (); 4567return ple_gather (c1 ,b ,ple_next_err ); 4568 }); 4569 } 4570ple_buf ^=1 ; 4571stats_ .ms_ple += ms_since (tp ); 4572return true; 4573 }; 4574for (int64_t t = 0 ;t < T ;++ t ) {prev [0 ]= prev [1 ];prev [1 ]= (int32_t )tokens [c0 + t ]; } 4575// ---- the QSA step records of every position in the chunk 4576for (int64_t t = 0 ;t < T ;++ t ) strata::kernels::qsa_step_fill (m .steps_host .data ()+ t * strata::kernels::kStepCount ,p0 + t ,s ); 4577if (!m .steps_up .upload (m .steps_dev ,m .steps_host .data (), (size_t )T * strata::kernels::kStepCount ,m .cs )) { 4578err = "prefill: the QSA step records' upload failed" ; 4579return false; 4580 } 4581 4582int64_t qsa_index = 0 ,gdn_index = 0 ; 4583for (int64_t l = 0 ;l < LB ;++ l ) (core::is_qsa_layer (g ,l ) ?qsa_index :gdn_index )+= 1 ; 4584int64_t kv_pending = -1 ; 4585auto kv_prefetch_after = [& ](int64_t layer ,int64_t ordinal )-> bool { 4586if (!kv_prefetch || p0 <=0 )return true; 4587if (kv_pending >=0 )return true;// one staging pool: the pending prefetch has not been consumed yet 4588for (int64_t l = layer ;l < LE ;++ l ) { 4589if (!core::is_qsa_layer (g ,l ))continue ; 4590const core::QsaState & state = ss .qsa_states [ordinal ]; 4591if (state .kv_mode != 1 ) {++ ordinal ;continue ; } 4592// Reuse one KV pool only after its last attention reader completes. The next layer's 4593// [0, p0) host prefix is immutable throughout this chunk; its new rows are appended later. 4594if (cudaEventRecord (m .kv_released ,cs )!= cudaSuccess || 4595cudaStreamWaitEvent (m .kv_copy ,m .kv_released ,0 )!= cudaSuccess ) { 4596err = "prefill: releasing KV staging pool" ; 4597return false; 4598 } 4599 strata::kernels::kv_stage_from_host (pools_of (m .stage ,m .ident_table ),state .host , 4600 core::qsa_kv_format (state ), (p0 + s .page_size - 1 ) /s .page_size ,s ,m .kv_copy ); 4601if (cudaPeekAtLastError ()!= cudaSuccess || 4602cudaEventRecord (m .kv_ready ,m .kv_copy )!= cudaSuccess ) { 4603err = "prefill: enqueueing KV prefetch" ; 4604return false; 4605 } 4606kv_pending = ordinal ; 4607++ kv_prefetches ; 4608break ; 4609 } 4610return true; 4611 }; 4612if (!kv_prefetch_after (LB ,qsa_index ))return false; 4613// step 3: this chunk's stream - every non-resident expert of every layer, layer by layer in id order (entry 4614// k lands in ring slot k % ring); a copy is issued once the entry `ring` before it is consumed (its slot's 4615// `used` event recorded), so the copy stream never waits on an event that is not queued yet 4616const strata::kernels::cpu::ExpertLayout & lay0 = strata::kernels::cpu::expert_layout (); 4617const bool stream_all = m .ring > STAGE && T >=stream_all_min ()&& m .src != nullptr ; 4618// the CPU share: this chunk takes the pool if no other stage of a layer split has it now (released at the end 4619// of the chunk, after the last layer's CPU thread is joined) 4620struct PoolHold { 4621bool held = false; 4622 ~PoolHold () {if (held )g_cpu_pool_busy .store (false, std::memory_order_release ); } 4623 }pool_hold ; 4624if (cpu_pool_ != nullptr && cpu_share_on ()&& !stream_all && !pipe_chunked && 4625 !g_share_blocked .load (std::memory_order_acquire )) { 4626bool expect = false; 4627pool_hold .held = g_cpu_pool_busy .compare_exchange_strong (expect , true, std::memory_order_acq_rel ); 4628 } 4629const bool ps_on = stream_all && m .pp && m .pp -> ps_frac > 0.0 ; 4630if (m .pp && !ps_on )m .pp -> ps_flag .clear (); 4631// multi-GPU: the peer's ring - issue its copies up to `limit` / give entries back (the peer device is current) 4632auto p_issue_until = [& ](size_t limit ) { 4633PeerPrefill & P = * m .pp ; 4634limit = std::min (limit ,P .pseq .size ()); 4635while (P .p_issued < limit ) { 4636const PeerPrefill ::PsEntry & en = P .pseq [P .p_issued ]; 4637const size_t sl = P .p_issued % (size_t )P .RP ; 4638if (P .plive [sl ])cudaStreamWaitEvent (P .s_cp ,P .pused [sl ],0 ); 4639cudaMemcpyAsync (P .pstage [sl ],en .blob , (size_t ) strata::kernels::cpu::expert_layout ().blob_bytes (en .l ), 4640cudaMemcpyHostToDevice ,P .s_cp ); 4641cudaEventRecord (P .pcopied [sl ],P .s_cp ); 4642P .plive [sl ]= 1 ; 4643++ P .p_issued ; 4644 } 4645 }; 4646auto p_release_to = [& ](int64_t l ,int32_t e_stop ,cudaStream_t ps ) { 4647PeerPrefill & P = * m .pp ; 4648while (P .pk < P .pseq_start [(size_t )l + 1 ]&& P .pseq [P .pk ].e < e_stop ) { 4649cudaEventRecord (P .pused [P .pk % (size_t )P .RP ],ps ); 4650++ P .pk ; 4651p_issue_until (P .pk + (size_t )P .RP ); 4652 } 4653 }; 4654struct StreamEntry {int32_t l ,e ;const uint8_t * blob ;int job ; }; 4655 std::vector < StreamEntry > seq ; 4656 std::vector < size_t > seq_start ; 4657size_t issued = 0 ,consumed = 0 ; 4658if (stream_all ) { 4659seq_start .assign ((size_t )g .n_layers + 1 ,0 ); 4660 std::vector < Stager ::Job > js ; 4661if (ps_on ) { 4662m .pp -> pseq .clear (); 4663m .pp -> pseq_start .assign ((size_t )g .n_layers + 1 ,0 ); 4664m .pp -> ps_flag .assign ((size_t )g .n_layers * m .g -> n_expert ,0 ); 4665m .pp -> p_issued = m .pp -> pk = 0 ; 4666 } 4667double ps_acc = 0.0 ; 4668// STRATA_KVA: a layer that will not run its MoE half must not queue expert transfers either - the 4669// transfer plan is where the avoidable cost lives (the research handoff's "expert transfers must be 4670// skipped too"). `kva_skips_layer` is the one place the two conditions meet. 4671auto kva_skips_layer = [& ](int64_t l ) { 4672return kva_approx && l >=kva_split && 4673 (kva .only == KvaConfig ::Only ::All || 4674 (kva .only == KvaConfig ::Only ::Gdn )== !core::is_qsa_layer (g ,l )); 4675 }; 4676for (int64_t l = LB ;l < LE ;++ l ) { 4677seq_start [(size_t )l ]= seq .size (); 4678if (ps_on )m .pp -> pseq_start [(size_t )l ]= m .pp -> pseq .size (); 4679if (kva_skips_layer (l ))continue ;// no transfer for a layer whose MoE half is skipped 4680for (int32_t e = 0 ;e < m .g -> n_expert ;++ e ) { 4681if (m .host_res && m .cache && m .host_res [(size_t )l * m .g -> n_expert + e ] >=0 )continue ; 4682if (m .pp && m .pp -> peer && m .pp -> peer -> has (l ,e ))continue ;// multi-GPU: computed on (or read from) the peer 4683int job = -1 ; 4684const uint8_t * b = nullptr ; 4685if (m .src -> transient (l ,e )) {// CS-T: copied by the source into the stager's buffer 4686job = (int )js .size (); 4687js .push_back ({nullptr , (size_t )lay0 .blob_bytes (l ),m .src , (int32_t )l ,e }); 4688 }else { 4689b = m .src -> blob_stable (l ,e ); 4690if (!b ) {err = "prefill: expert source has no blob" ;return false; } 4691if (ps_on && m .src -> pinned (l ,e )) {// multi-GPU: every ps_frac-th one goes to the peer's ring 4692ps_acc += m .pp -> ps_frac ; 4693if (ps_acc >=1.0 ) { 4694ps_acc -= 1.0 ; 4695m .pp -> pseq .push_back ({(int32_t )l ,e ,b }); 4696m .pp -> ps_flag [(size_t )l * m .g -> n_expert + e ]= 1 ; 4697continue ; 4698 } 4699 } 4700if (!m .src -> pinned (l ,e )) { 4701job = (int )js .size (); 4702js .push_back ({b , (size_t )lay0 .blob_bytes (l )}); 4703 } 4704 } 4705seq .push_back ({(int32_t )l ,e ,b ,job }); 4706 } 4707 } 4708for (int64_t l = LE ;l <=g .n_layers ;++ l ) { 4709seq_start [(size_t )l ]= seq .size (); 4710if (ps_on )m .pp -> pseq_start [(size_t )l ]= m .pp -> pseq .size (); 4711 } 4712m .stager -> start (std::move (js )); 4713 } 4714struct StagerDone { 4715Stager * st ; 4716 ~StagerDone () {if (st )st -> finish (); } 4717 }chunk_stager_done {stream_all ?m .stager .get () :nullptr }; 4718auto issue_until = [& ](size_t limit ) { 4719limit = std::min (limit ,seq .size ()); 4720while (issued < limit ) { 4721const StreamEntry & en = seq [issued ]; 4722const int sl = (int ) (issued % (size_t )m .ring ); 4723const auto th = Clock ::now (); 4724const size_t bytes = (size_t )lay0 .blob_bytes (en .l ); 4725if (m .stage_live [sl ])cudaStreamWaitEvent (m .copy ,m .used [m .used_of [sl ]],0 ); 4726if (en .job < 0 ) { 4727cudaMemcpyAsync (m .stage_dev [sl ],en .blob ,bytes ,cudaMemcpyHostToDevice ,m .copy ); 4728++ stats_ .experts_dma ; 4729 }else { 4730const uint8_t * hb = m .stager -> wait (en .job ); 4731cudaMemcpyAsync (m .stage_dev [sl ],hb ,bytes ,cudaMemcpyHostToDevice ,m .copy ); 4732m .stager -> issued_one (en .job ,m .copy ); 4733 } 4734cudaEventRecord (m .copied [sl ],m .copy ); 4735m .stage_live [sl ]= true; 4736stats_ .ms_experts_host += ms_since (th ); 4737++ stats_ .experts_streamed ; 4738++ issued ; 4739 } 4740 }; 4741// D-5: the stream is issued by its own host thread, so the thread launching the layers' kernels never waits 4742// behind a host copy of an unpinned blob (that wait left the GPU idle: the 'wait copy' / 'dequant' time of the 4743// i-quant prompts). The same copies in the same order into the same slots, and a slot is refilled only once 4744// the compute stream has recorded that it is done with it: the same results. STRATA_PREFILL_ISSUER=0: inline. 4745static const bool issuer_on = [] { 4746const char * v = std::getenv ("STRATA_PREFILL_ISSUER" ); 4747return v == nullptr || std::atoi (v )!= 0 ; 4748 }(); 4749static const int copy_event_every = [] { 4750const char * v = std::getenv ("STRATA_PREFILL_COPY_EVENT_EVERY" ); 4751return strata::prefill::copy_event_every_from (v ? std::atoi (v ) :1 ); 4752 }(); 4753static const bool copy_wait_dedupe = [] { 4754const char * v = std::getenv ("STRATA_PREFILL_COPY_WAIT_DEDUPE" ); 4755return v != nullptr && std::atoi (v )!= 0 ; 4756 }(); 4757// STRATA_PREFILL_ROUTED_STREAM=1 (opt-in, routed_stream.hpp): the issuer keeps at most a few copies queued 4758// ahead of the link (STRATA_PREFILL_ROUTED_STREAM_DEPTH, default 16), each layer's routing is published once 4759// its router has run (host grouping below), and an entry not yet issued that no token of the chunk routes to 4760// is dropped. Routed entries are copied as below, into the same slots: the same bits. The threaded issuer 4761// on one GPU only (no peer prompt ring), and not with STRATA_PREFILL_COPY_EVENT_EVERY > 1 or 4762// STRATA_PREFILL_COPY_WAIT_DEDUPE=1, whose copy records the routed walk does not write (routed_stream::eligible); 4763// unset, nothing here runs and the loop below is the walk. Declared 4764// before the issuer thread, so they outlive it on every return (IssuerJoin joins it first). 4765static const bool rs_env = routed_stream::enabled_from (std::getenv ("STRATA_PREFILL_ROUTED_STREAM" )); 4766static const int rs_depth = routed_stream::depth_from (std::getenv ("STRATA_PREFILL_ROUTED_STREAM_DEPTH" )); 4767const bool rs_on = rs_env && routed_stream::eligible ( 4768stream_all ,issuer_on ,m .pp != nullptr ,copy_event_every ,copy_wait_dedupe ); 4769 routed_stream::RouteGate rs_gate ; 4770size_t rs_dropped = 0 ; 4771if (rs_on ) { 4772rs_gate .reset (g .n_layers , (int32_t )m .g -> n_expert ); 4773if (static bool said = false; !said ) { 4774said = true; 4775 std::fprintf (stderr ,"strata: STRATA_PREFILL_ROUTED_STREAM=1: a streamed prompt chunk drops the experts no token " 4776"routes to before they are copied (at most %d copies queued ahead of the link)\n" ,rs_depth ); 4777 } 4778 }else if (rs_env && stream_all ) { 4779if (static bool said_off = false; !said_off ) { 4780said_off = true; 4781 std::fprintf (stderr ,"strata: STRATA_PREFILL_ROUTED_STREAM=1 is not used: %s\n" , 4782 routed_stream::held_off (issuer_on ,m .pp != nullptr ,copy_event_every ,copy_wait_dedupe )); 4783 } 4784 } 4785 std::atomic < size_t > a_issued {0 },a_consumed {0 }; 4786 std::atomic < bool > a_stop {false}; 4787double iss_ms = 0 ; 4788int64_t iss_streamed = 0 ,iss_dma = 0 ; 4789 std::thread issuer ; 4790struct IssuerJoin { 4791 std::atomic < bool >* stop ; 4792 std::thread * t ; 4793 ~IssuerJoin () {if (t -> joinable ()) {stop -> store (true);t -> join (); } } 4794 }issuer_join {& a_stop ,& issuer }; 4795const bool threaded_issue = stream_all && issuer_on ; 4796// Opt-in, the threaded issuer only: under WDDM every cudaEventRecord and cross-stream wait is a 4797// submission of its own (~80 / ~45 us each on a 6900 XT under Windows 11, ~3 / ~0 us on Linux), and the 4798// streamed walk paid one record and one wait per expert although a group gathers after ONE wait on its last 4799// copy and is released by ONE event. STRATA_PREFILL_COPY_EVENT_EVERY=N records the copied event every N-th 4800// entry (and before the issuer waits, and on the last), and the consumer waits on the first recorded entry at or 4801// after the one it needs (the copy stream is in order). STRATA_PREFILL_COPY_WAIT_DEDUPE=1 skips the copy 4802// stream's wait on a slot's release event when the previous slot was released by the same event (one flush). 4803// The same copies into the same slots: the same bytes. 4804const bool sparse_copied = threaded_issue && copy_event_every > 1 ; 4805if (threaded_issue && (sparse_copied || copy_wait_dedupe )) { 4806static bool said = false; 4807if (!said ) { 4808said = true; 4809 std::fprintf (stderr ,"strata: prompt copies: a copied event every %d streamed experts " 4810"(STRATA_PREFILL_COPY_EVENT_EVERY), %s (STRATA_PREFILL_COPY_WAIT_DEDUPE)\n" , 4811copy_event_every ,copy_wait_dedupe ?"one wait per release event" :"a wait per slot" ); 4812 } 4813 } 4814 std::vector < std::atomic < int64_t >> rec_of (sparse_copied ? (size_t )m .ring :0 );// the entry a slot's event marks 4815for (auto & r :rec_of )r .store (-1 , std::memory_order_relaxed ); 4816 std::atomic < size_t > a_rec {0 };// 1 + the last entry whose copied event is recorded 4817int64_t iss_waits = 0 ,iss_dedup = 0 ; 4818if (threaded_issue ) { 4819issuer = std::thread ([& ] { 4820 strata::platform::name_this_thread ("strata-issue" ); 4821 strata::aux_cpus::pin_current_thread (); 4822const core::OnDevice od (m .device ); 4823if (rs_on ) { 4824auto ops = routed_stream::make_ops ( 4825 [& ] {return a_consumed .load (std::memory_order_acquire ); }, 4826 [& ] {return a_stop .load (std::memory_order_acquire ); }, 4827 [& ](int sl ) {return cudaEventQuery (m .copied [sl ])!= cudaErrorNotReady ; }, 4828 [](const StreamEntry & en ) {return en .job < 0 ; }, 4829 [& ](size_t idx ,int sl ) {// the copy of the loop below, unchanged 4830const StreamEntry & en = seq [idx ]; 4831const auto th = Clock ::now (); 4832const size_t bytes = (size_t )lay0 .blob_bytes (en .l ); 4833if (m .stage_live [sl ])cudaStreamWaitEvent (m .copy ,m .used [m .used_of [sl ]],0 ); 4834if (en .job < 0 ) { 4835cudaMemcpyAsync (m .stage_dev [sl ],en .blob ,bytes ,cudaMemcpyHostToDevice ,m .copy ); 4836++ iss_dma ; 4837 }else { 4838const uint8_t * hb = m .stager -> wait (en .job ); 4839cudaMemcpyAsync (m .stage_dev [sl ],hb ,bytes ,cudaMemcpyHostToDevice ,m .copy ); 4840m .stager -> issued_one (en .job ,m .copy ); 4841 } 4842cudaEventRecord (m .copied [sl ],m .copy ); 4843m .stage_live [sl ]= true; 4844iss_ms += ms_since (th ); 4845++ iss_streamed ; 4846 }, 4847 [] { std::this_thread::yield (); }); 4848rs_dropped = routed_stream::issue_walk (seq , (size_t )m .ring ,rs_depth ,rs_gate ,a_issued ,ops ).dropped ; 4849return ; 4850 } 4851int64_t last_rec = -1 ;// sparse_copied: the last entry whose copied event is recorded 4852int prev_rel = -1 ;// dedupe: the release event the copy stream waited on for the previous entry 4853auto record = [& ](size_t i ) { 4854cudaEventRecord (m .copied [i % (size_t )m .ring ],m .copy ); 4855rec_of [i % (size_t )m .ring ].store ((int64_t )i , std::memory_order_release ); 4856a_rec .store (i + 1 , std::memory_order_release ); 4857last_rec = (int64_t )i ; 4858 }; 4859// before the issuer waits: what it issued is covered, so no consumer waits on an entry with no event 4860auto cover = [& ](size_t idx ) {if (sparse_copied && idx > 0 && last_rec < (int64_t )idx - 1 )record (idx - 1 ); }; 4861for (size_t idx = 0 ;idx < seq .size ();++ idx ) { 4862while (idx >=a_consumed .load (std::memory_order_acquire )+ (size_t )m .ring ) { 4863cover (idx ); 4864if (a_stop .load (std::memory_order_acquire ))return ; 4865 std::this_thread::yield (); 4866 } 4867const StreamEntry & en = seq [idx ]; 4868const int sl = (int ) (idx % (size_t )m .ring ); 4869const auto th = Clock ::now (); 4870const size_t bytes = (size_t )lay0 .blob_bytes (en .l ); 4871if (m .stage_live [sl ]) { 4872// Both this slot and the previous one must have been released in THIS walk (idx - 1 >= ring: the 4873// previous slot's event of an earlier walk could be re-recorded by this walk's first flush), and 4874// the ring must be longer than one MMQ group (a flush of a whole ring would re-record the event 4875// after the previous slot's wait). Then the same event means the same flush, and the wait for 4876// the previous slot already covers this one. 4877const int rel = m .used_of [sl ]; 4878if (copy_wait_dedupe && strata::prefill::copy_wait_dedupe_ok (idx ,m .ring ,MMQ_GROUP ,rel ,prev_rel )) { 4879++ iss_dedup ; 4880 }else { 4881cudaStreamWaitEvent (m .copy ,m .used [rel ],0 ); 4882++ iss_waits ; 4883 } 4884prev_rel = rel ; 4885 }else { 4886prev_rel = -1 ; 4887 } 4888if (en .job < 0 ) { 4889cudaMemcpyAsync (m .stage_dev [sl ],en .blob ,bytes ,cudaMemcpyHostToDevice ,m .copy ); 4890++ iss_dma ; 4891 }else { 4892cover (idx );// the stager may make the issuer wait 4893const uint8_t * hb = m .stager -> wait (en .job ); 4894cudaMemcpyAsync (m .stage_dev [sl ],hb ,bytes ,cudaMemcpyHostToDevice ,m .copy ); 4895m .stager -> issued_one (en .job ,m .copy ); 4896 } 4897if (!sparse_copied )cudaEventRecord (m .copied [sl ],m .copy ); 4898else if (strata::prefill::copy_event_due (idx ,seq .size (),copy_event_every ))record (idx ); 4899m .stage_live [sl ]= true; 4900iss_ms += ms_since (th ); 4901++ iss_streamed ; 4902a_issued .store (idx + 1 , std::memory_order_release ); 4903 } 4904 }); 4905 }else if (stream_all ) { 4906issue_until ((size_t )m .ring );// layer 0's first experts, behind the embedding and the PLE 4907 } 4908// the consumer's side: entry k's copy is on the copy stream (the thread issued it), then k is given back 4909auto wait_issued = [& ](size_t k ) { 4910if (!threaded_issue )return ; 4911while (a_issued .load (std::memory_order_acquire ) <=k ) std::this_thread::yield (); 4912 }; 4913// the compute stream waits for entry k's copy: on its slot's event (`slot`, as before this switch existed), or 4914// (sparse_copied) on the first recorded entry at or after it. That event's slot cannot be re-recorded before k 4915// is given back (the issuer stays a ring ahead). 4916auto wait_copied = [& ](size_t k ,size_t slot ) { 4917if (!sparse_copied ) { 4918cudaStreamWaitEvent (m .cs ,m .copied [slot ],0 ); 4919return ; 4920 } 4921while (a_rec .load (std::memory_order_acquire ) <=k ) std::this_thread::yield (); 4922const size_t hi = a_rec .load (std::memory_order_acquire ); 4923// (hi - 1 is always recorded, so the last entry is only the fallback that covers k all the same) 4924const size_t r = strata::prefill::copy_event_entry (k ,hi , [& ](size_t e ) { 4925return rec_of [e % (size_t )m .ring ].load (std::memory_order_acquire )== (int64_t )e ; 4926 }); 4927cudaStreamWaitEvent (m .cs ,m .copied [r % (size_t )m .ring ],0 ); 4928 }; 4929auto give_back = [& ](size_t upto ) { 4930if (threaded_issue )a_consumed .store (upto , std::memory_order_release ); 4931else issue_until (upto + (size_t )m .ring ); 4932 }; 4933if (ps_on ) { 4934int pd = 0 ; 4935cudaGetDevice (& pd ); 4936cudaSetDevice (m .pp -> dev ); 4937p_issue_until ((size_t )m .pp -> RP ); 4938cudaSetDevice (pd ); 4939 } 4940host_setup_ms += ms_since (tsetup ); 4941bool normed = false;// F-2: the previous half's write already normed R for this half (grs, xn16) 4942// #579 #613 (opt-in diagnosis, STRATA_PF_STEP_SYNC=1): the compute and copy streams are waited for after each 4943// step named below, a step that took over 250 ms is logged, and a stall's report names the step it is in. 4944// Slower (a sync per step); the bytes are the same. 4945static const bool step_sync = [] {const char * e = std::getenv ("STRATA_PF_STEP_SYNC" );return e && e [0 ]== '1' ; }(); 4946auto pf_step = [& ](const char * what ,int64_t layer ) { 4947if (!step_sync )return ; 4948 core::progress_at (what ,layer ,p0 ); 4949const auto ts = Clock ::now (); 4950const cudaError_t a = cudaStreamSynchronize (m .cs ),b = cudaStreamSynchronize (m .copy ); 4951const double ms = ms_since (ts ); 4952if (ms > 250.0 || a != cudaSuccess || b != cudaSuccess ) 4953 std::fprintf (stderr ,"strata pf-step: chunk from token %lld, layer %lld: %s took %.0f ms (%s / %s)\n" , 4954 (long long )p0 , (long long )layer ,what ,ms ,cudaGetErrorString (a ),cudaGetErrorString (b )); 4955 }; 4956for (int64_t l = LB ;l < LE ;++ l ) { 4957 core::progress_beat ();// the serve watchdog: a prompt chunk of 8192 tokens is still moving 4958if (l > LB )pf_step ("reading the prompt (batched, step sync): the experts and the rest of layer" ,l - 1 ); 4959 core::progress_at ("reading the prompt (batched): layer" ,l ,p0 );// #251: a stall names layer and chunk 4960const core::LayerView v (* m .wt ,l ); 4961// STRATA_KVA: `kva_layer` means this layer's output has no consumer left for this chunk, so only its 4962// state advances; `kva_subst` means the block input itself is replayed from a capture (oracle mode). 4963const bool kva_layer = kva_approx && l >=kva_split && 4964 (kva .only == KvaConfig ::Only ::All || 4965 (kva .only == KvaConfig ::Only ::Gdn )== !core::is_qsa_layer (g ,l )); 4966// STRATA_KVA_SKIP=moe: the layer's attention half (GDN or QSA, outputs included) runs in full and only the MoE 4967// half is skipped; `kva_state_only` is the default form, where only the state advances 4968const bool kva_moe_only = kva_layer && kva .skip == KvaConfig ::Skip ::Moe ; 4969const bool kva_state_only = kva_layer && !kva_moe_only ; 4970const bool kva_subst = kva_layer && kva .mode == KvaConfig ::Mode ::Oracle ; 4971const bool kva_cap_layer = kva .capture && LB == 0 && (LE < 0 || LE == g .n_layers )&& l >=kva_split ; 4972if (l == std::max < int64_t > (LB ,1 )) {// the PLE rows, read from layer 1 on (a wait for the SSD read of the first chunk lands on "ple") 4973pt .mark (kPfPle ,cs ); 4974if (!ple_land ())return false; 4975 } 4976// ---- the PLE block at layer 1, token by token (its conv reads the previous tokens' rows) 4977if (l == 1 && ple_on && ple_batch ) { 4978// the whole chunk at once, in sub-batches carved from the idle scratch region: the key and value 4979// projections as GEMMs (a token at a time they re-read ~52 MB of BF16 key per token on the IQ 4980// files), the rest with the per-token kernels' arithmetic (native_ple_postops_batch) 4981pt .mark (kPfPle ,cs ); 4982const auto tp = Clock ::now (); 4983const strata::kernels::PleWeights & pw = ss .ple .w ; 4984constexpr int64_t HD = strata::kernels::NG_HC_DIM ; 4985const uint64_t per_token = (uint64_t ) (3 * HD + N + 4 )* 4 + (uint64_t )N * (bf16x2 (m .f16_io ) ?4 :2 )+ 4096 ; 4986const int64_t SB = std::min < int64_t > (T , (int64_t ) (m .region_bytes /per_token )); 4987for (int64_t s0 = 0 ;s0 < T ;s0 += SB ) { 4988const int64_t nb = std::min (SB ,T - s0 ); 4989uint8_t * q = m .region ; 4990auto carve_f = [& ](size_t n ) {float * p = (float * )q ;q += (n * 4 + 255 )& ~(size_t )255 ;return p ; }; 4991float * key = carve_f ((size_t )nb * HD ); 4992float * qn = carve_f ((size_t )nb * HD ); 4993float * gated = carve_f ((size_t )nb * HD ); 4994float * val = carve_f ((size_t )nb * N ); 4995float * gate = carve_f ((size_t )nb * 4 ); 4996uint16_t * e16 = (uint16_t * )carve_f ((size_t )nb * N /2 ); 4997uint16_t * e16_lo = bf16x2 (m .f16_io ) ? (uint16_t * )carve_f ((size_t )nb * N /2 ) :nullptr ; 4998const float * emb = m .ple_emb + s0 * N ; 4999if (pw .key_bf16 != nullptr ) { 5000to_bf16 (emb ,e16 ,nb * N ,m .cs ,e16_lo ); 5001m .gemm .bf16 (e16 ,pw .key_bf16 ,key ,nb ,HD ,N ); 5002if (e16_lo )m .gemm .bf16 (e16_lo ,pw .key_bf16 ,key ,nb ,HD ,N ,0 ,1.0f ); 5003 }else { 5004to_f16 (emb ,e16 ,nb * N ,m .cs ); 5005m .gemm .native (e16 ,pw .key_native_type ,pw .key_native_data ,key ,nb ,HD ,N ); 5006to_bf16 (emb ,e16 ,nb * N ,m .cs ,e16_lo ); 5007 } 5008m .gemm .bf16 (e16 ,pw .value_bf16 ,val ,nb ,N ,N ); 5009if (e16_lo )m .gemm .bf16 (e16_lo ,pw .value_bf16 ,val ,nb ,N ,N ,0 ,1.0f ); 5010try { 5011 strata::kernels::native_ple_postops_batch (key ,m .R + s0 * D ,val ,ss .ple .hist ,pw ,qn ,gated , 5012gate , (int )nb ,m .cs ); 5013 }catch (const std::exception & e ) {err = std::string ("prefill PLE: " )+ e .what ();return false; } 5014 } 5015stats_ .ms_ple += ms_since (tp ); 5016 }else if (l == 1 && ple_on ) { 5017pt .mark (kPfPle ,cs ); 5018const auto tp = Clock ::now (); 5019for (int64_t t = 0 ;t < T ;++ t ) { 5020 strata::kernels::PleOut po ; 5021po .normalized = m .ple_norm ; 5022po .result = m .R + t * D ; 5023try { 5024 strata::kernels::ple_block (m .ple_emb + t * N ,m .R + t * D ,ss .ple .hist ,ss .ple .w ,po , 5025ss .ple .scratch ,m .cs ); 5026 }catch (const std::exception & e ) {err = std::string ("prefill PLE: " )+ e .what ();return false; } 5027 strata::kernels::ple_history_advance (ss .ple .hist ,m .ple_norm ,m .cs ); 5028 } 5029stats_ .ms_ple += ms_since (tp ); 5030 } 5031// STRATA_KVA: the capture and the oracle hook the residual ENTERING the layer - the vector a projector 5032// has to produce for it. A capture run is an ordinary full read; the oracle replaces the input. 5033if (kva_cap_layer && !kva_capture .write (l ,m .R ,T ,p0 ,D ,cs )) {err = kva_capture .err ;return false; } 5034// STRATA_LAT_R_DUMP=<dir> (latent debug): the residual entering the layer, fp32, rows in 5035// position order, appended to <dir>/L<layer>.bin per chunk - offline layer-by-layer diff. 5036static const char * lat_r_dump = std::getenv ("STRATA_LAT_R_DUMP" ); 5037if (lat_r_dump ) { 5038static std::vector < float > lat_r_host ; 5039lat_r_host .resize ((size_t )T * D ); 5040if (cudaMemcpyAsync (lat_r_host .data (),m .R , (size_t )T * D * 4 ,cudaMemcpyDeviceToHost ,m .cs )!= cudaSuccess || 5041cudaStreamSynchronize (m .cs )!= cudaSuccess ) { 5042err = "lat R dump: the residual copy failed" ;return false; 5043 } 5044char lat_r_path [512 ]; 5045 std::snprintf (lat_r_path ,sizeof lat_r_path ,"%s/L%lld.bin" ,lat_r_dump , (long long )l ); 5046 std::FILE * lat_r_f = std::fopen (lat_r_path ,"wb" ); 5047if (lat_r_f == nullptr ) {err = std::string ("lat R dump: cannot write " )+ lat_r_path ;return false; } 5048 std::fwrite (lat_r_host .data (),4 , (size_t )T * D ,lat_r_f ); 5049 std::fclose (lat_r_f ); 5050 } 5051if (kva_subst ) { 5052if (!kva_oracle .read (l ,m .R ,T ,p0 ,D ,cs )) {err = kva_oracle .err ;return false; } 5053normed = false;// the previous half's norm of R is stale once the input is replaced 5054 } 5055for (int half = 0 ;half < 2 ;++ half ) { 5056if (kva_moe_only && half == 1 ) { 5057// KVA moe-skip: the attention half wrote its output into R; this layer's MoE half has no consumer 5058// left for an approximated chunk, so it (and its expert transfers) is skipped. R is not normed for 5059// it (the write after the attention half normed it with this layer's FFN weights). 5060normed = false; 5061consumed = std::max (consumed ,seq_start [(size_t )l + 1 ]); 5062give_back (consumed ); 5063break ; 5064 } 5065// ---- the hyper-connection read of this half 5066const char * pre = half == 0 ?"hc_attn_" :"hc_ffn_" ; 5067const std::string sn = std::string (pre )+ "norm.weight" ,sd = std::string (pre )+ "down.weight" , 5068su = std::string (pre )+ "up.weight" ,si = std::string (pre )+ "inject.weight" ; 5069const core::WeightRef * wn = need (v ,sn .c_str (),err ),* wd = need (v ,sd .c_str (),err ), 5070* wu = need (v ,su .c_str (),err ),* wi = need (v ,si .c_str (),err ); 5071if (!wn || !wd || !wu || !wi )return false; 5072// STRATA_HC_Q8 without a bf16 copy: this path's GEMMs read bf16, so the matrices are dequantized per half 5073 core::WeightRef wd_q8 ,wu_q8 ; 5074if (!wd -> data && wd -> hc_q8 && !wu -> data && wu -> hc_q8 ) { 5075wd_q8 = * wd ;wu_q8 = * wu ; 5076wd_q8 .data = core::NativeDense ::hc_bf16_view (* wd ,m .cs ,0 ,0 ); 5077wu_q8 .data = core::NativeDense ::hc_bf16_view (* wu ,m .cs ,1 ,0 ); 5078if (!wd_q8 .data || !wu_q8 .data ) {err = "prefill: the Q8_0 hyper-connection projections could not be dequantized" ;return false; } 5079wd = & wd_q8 ;wu = & wu_q8 ; 5080 } 5081pt .mark (kPfHc ,cs ); 5082// the xn16 token stride of this chunk (the writers of both halves and of the fused write-backs use it) 5083const int64_t ldx = hc_pad ()&& T >= std::max < int64_t > (pf_switch_min_t (),64 )&& !gr_unfused ()&& 5084 !m .xn16_lo ?D + XN_PAD :D ; 5085const bool xf16 = m .xn_f16 && !m .xn16_lo && ldx == D ;// xn16 holds FP16 (its writers and readers below) 5086if (gr_unfused ())gr_norm (m .R , (const float * )wn -> data ,EPS ,m .xn ,m .xn16 ,T ,m .cs ,m .xn16_lo ,xf16 ); 5087else if (!normed )gr_norm_rs (m .R , (const float * )wn -> data ,EPS ,m .grs ,m .xn16 ,T ,m .cs ,m .xn16_lo ,ldx ,xf16 ); 5088normed = false; 5089pt .mark (kPfHcDown ,cs );// STRATA_PREFILL_TIMING: the hyper-connection read's parts on their own lines (norm stays on "hc read") 5090bool hcd = false; 5091bool hdown = false; 5092if (wd -> q8_scale == nullptr && ldx != D && !pf_hcdown ()) {// not with STRATA_HC_REQ8's int8 rows // STRATA_HCD_EXACT: the exact-order down kernel when hipBLASLt would take 1176 / 1177 5093hdown = wd -> kind == core::WeightKind ::Bf16InF32 && wd -> data && wd -> ne0 == D && wd -> ne1 == LR && 5094m .gemm .bf16_hcd_exact (m .xn16 ,ldx , (const uint16_t * )wd -> data ,m .lo ,T ,LR ,D ); 5095 }else if (wd -> q8_scale == nullptr && ldx != D ) { 5096if (wd -> kind != core::WeightKind ::Bf16InF32 || !wd -> data || wd -> ne0 != D || wd -> ne1 != LR || 5097wi -> kind != core::WeightKind ::Bf16InF32 || !wi -> data || wi -> ne0 != D || wi -> ne1 != HC || 5098 !strata_pf_hcdown_bf16 (m .xn16 ,ldx , (const uint16_t * )wd -> data , (const uint16_t * )wi -> data ,LR , 5099HC ,m .lo ,m .inj ,T ,D ,m .cs )) { 5100err = "prefill: STRATA_PF_HCDOWN could not run the hyper-connection projections" ; 5101return false; 5102 } 5103hcd = true; 5104 } 5105if (!hcd && !hdown && !bf16_proj (m .gemm ,wd ,m .xn16 ,m .lo ,T ,sd ,err ,0 ,m .xn16_lo ,ldx != D ?ldx :0 ,m .cs ,xf16 ))return false; 5106gr_silu (m .lo ,m .lo16 ,T ,m .cs ,m .lo16_lo ); 5107pt .mark (kPfHcUp ,cs ); 5108bool upmixed = false; 5109// on the FP16 prompt path (m.f16_io) lo16 holds FP16 bits (act16) and gr_upmix reads it on the FP16 matrix-core builtin (g_act_f16) 5110if (wu -> q8_scale == nullptr && hc_upmix ()&& T >= std::max (pf_switch_min_t (),hc_upmix_min_t ())&& !gr_unfused ()&& !m .lo16_lo && !m .mixed_bf_lo && 5111wu -> kind == core::WeightKind ::Bf16InF32 && wu -> data && wu -> ne0 == LR && wu -> ne1 == D ) { 5112static int checks = [] {const char * e = std::getenv ("STRATA_HC_UPMIX_CHECK" );return e ? std::atoi (e ) :0 ; }(); 5113if (checks > 0 ) {// the default pair first, kept for the comparison 5114-- checks ; 5115if (!bf16_proj (m .gemm ,wu ,m .lo16 ,m .gated ,T ,su ,err ))return false; 5116gr_mix_r (m .R ,m .grs , (const float * )wn -> data ,m .gated ,m .mixed ,m .mixed_bf ,T ,m .cs ,m .mixed_h ); 5117 std::vector < float > ref ((size_t )T * N ),got ((size_t )T * N ); 5118cudaMemcpyAsync (ref .data (),m .mixed ,ref .size ()* 4 ,cudaMemcpyDeviceToHost ,m .cs ); 5119upmixed = gr_upmix (m .lo16 , (const uint16_t * )wu -> data ,m .R ,m .grs , (const float * )wn -> data , 5120m .mixed ,m .mixed_bf ,m .mixed_h ,T ,m .cs ); 5121cudaMemcpyAsync (got .data (),m .mixed ,got .size ()* 4 ,cudaMemcpyDeviceToHost ,m .cs ); 5122cudaStreamSynchronize (m .cs ); 5123double e2 = 0 ,r2 = 0 ,emax = 0 ; 5124for (size_t i = 0 ;i < ref .size ();++ i ) { 5125const double dd = (double )got [i ]- ref [i ]; 5126e2 += dd * dd ;r2 += (double )ref [i ]* ref [i ];emax = std::max (emax , std::fabs (dd )); 5127 } 5128 std::fprintf (stderr ,"strata: STRATA_HC_UPMIX_CHECK layer %lld half %d T %lld: mixed rel RMS %.3e, " 5129"max |diff| %.3e (%s)\n" , (long long )l ,half , (long long )T , 5130 std::sqrt (e2 / std::max (r2 ,1e-30 )),emax ,upmixed ?"upmix" :"upmix refused" ); 5131 }else { 5132upmixed = gr_upmix (m .lo16 , (const uint16_t * )wu -> data ,m .R ,m .grs , (const float * )wn -> data , 5133m .mixed ,m .mixed_bf ,m .mixed_h ,T ,m .cs ); 5134 } 5135 } 5136if (!upmixed && !bf16_proj (m .gemm ,wu ,m .lo16 ,m .gated ,T ,su ,err ,0 ,m .lo16_lo ,0 ,m .cs ))return false; 5137pt .mark (kPfHcInj ,cs ); 5138if (!hcd && !bf16_proj (m .gemm ,wi ,m .xn16 ,m .inj ,T ,si ,err ,0 ,m .xn16_lo ,ldx != D ?ldx :0 ,m .cs ,xf16 ))return false; 5139pt .mark (kPfHcMix ,cs ); 5140if (upmixed ) { 5141 }else if (gr_unfused ()) { 5142gr_mix (m .xn ,m .gated ,m .mixed ,m .mixed_bf ,T ,m .cs ,m .mixed_h ,m .mixed_bf_lo ); 5143 }else { 5144gr_mix_r (m .R ,m .grs , (const float * )wn -> data ,m .gated ,m .mixed ,m .mixed_bf ,T ,m .cs ,m .mixed_h , 5145m .mixed_bf_lo ); 5146 } 5147 5148if (wd_q8 .data ) {// the HC GEMMs that read the scratch are enqueued: the next user waits for them 5149 core::NativeDense ::hc_bf16_release (m .cs ,0 ,0 ); 5150 core::NativeDense ::hc_bf16_release (m .cs ,1 ,0 ); 5151 } 5152if (half == 0 && !core::is_qsa_layer (g ,l )) { 5153// ======================= GDN ======================= 5154const core::WeightRef * wqkv = need (v ,"attn_qkv.weight" ,err ),* wg = need (v ,"attn_gate.weight" ,err ), 5155* wo = need (v ,"ssm_out.weight" ,err ),* wa = need (v ,"ssm_alpha.weight" ,err ), 5156* wb = need (v ,"ssm_beta.weight" ,err ),* wc = need (v ,"ssm_conv1d.weight" ,err ), 5157* wnm = need (v ,"ssm_norm.weight" ,err ),* wdt = need (v ,"ssm_dt.bias" ,err ), 5158* wsa = need (v ,"ssm_a" ,err ); 5159if (!wqkv || !wg || !wo || !wa || !wb || !wc || !wnm || !wdt || !wsa )return false; 5160pt .mark (kPfGdn ,cs ); 5161float * state = ss .gdn_state + (size_t ) (gdn_index - ss .gdn_ord0 )* gdn_floats ; 5162float * conv = state + (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size ; 5163if (!native_proj (m .gemm ,wqkv ,m .mixed_h ,m .qkv ,T ,v .name ("attn_qkv.weight" ),err ))return false; 5164// KVA: the gate projection feeds only the output normalization, which a state-only layer skips 5165// (STRATA_KVA_GDN_NORM=1 keeps the full recurrence as the A/B control for the state-only one) 5166static const bool kva_gdn_norm = [] { 5167const char * v = std::getenv ("STRATA_KVA_GDN_NORM" ); 5168return v != nullptr && std::atoi (v )!= 0 ; 5169 }(); 5170if ((!kva_state_only || kva_gdn_norm )&& 5171 !native_proj (m .gemm ,wg ,m .mixed_h ,m .z ,T ,v .name ("attn_gate.weight" ),err ))return false; 5172if (!bf16_proj (m .gemm ,wa ,m .mixed_bf ,m .ab ,T ,v .name ("ssm_alpha.weight" ),err ,2 * HV ,m .mixed_bf_lo ))return false; 5173if (!bf16_proj (m .gemm ,wb ,m .mixed_bf ,m .ab + HV ,T ,v .name ("ssm_beta.weight" ),err ,2 * HV ,m .mixed_bf_lo ))return false; 5174pt .mark (kPfGdnConv ,cs );// "gdn" is the projections in; the rest on their own lines 5175gdn_gates (m .ab , (const float * )wdt -> data , (const float * )wsa -> data ,m .gate ,m .beta ,T ,m .cs ); 5176const int64_t ld_y = pf_pad ()&& T >= std::max < int64_t > (pf_switch_min_t (),64 ) ?ZV + ZV_PAD :0 ; 5177bool fused_gdn = false; 5178#if defined(STRATA_USE_HIP ) 5179// gfx12, STRATA_GDN_CHUNKED=1: conv and recurrence together, the conv output as FP16 (their time then shows in "gdn conv+gates") 5180if (!kva_state_only ) 5181fused_gdn = gdn_conv_recurrence_fused (conv ,m .qkv , (const float * )wc -> data ,m .hbuf ,state ,m .gate ,m .beta ,m .z , 5182 (const float * )wnm -> data ,EPS ,EPS ,m .y ,m .y_h ,T ,m .cs ,ld_y ); 5183#endif 5184if (!fused_gdn )gdn_conv (conv ,m .qkv , (const float * )wc -> data ,m .hbuf ,T ,EPS ,m .cs ); 5185pt .mark (kPfGdnRec ,cs ); 5186if (fused_gdn ) { 5187 }else if (kva_state_only && !kva_gdn_norm )// KVA: the recurrence without the output normalization 5188gdn_recurrence_state_only (state ,m .hbuf ,m .gate ,m .beta ,m .y ,T ,m .cs ); 5189else 5190gdn_recurrence (state ,m .hbuf ,m .gate ,m .beta ,m .z , (const float * )wnm -> data ,EPS ,m .y ,m .y_h ,T ,m .cs , 5191ld_y ); 5192pt .mark (kPfGdnOut ,cs ); 5193if (!kva_state_only )// KVA: the out projection feeds only the residual write and the MoE half 5194if (!native_proj (m .gemm ,wo ,m .y_h ,m .bo ,T ,v .name ("ssm_out.weight" ),err ,0 ,ld_y ))return false; 5195++ gdn_index ; 5196if (kva_state_only ) { 5197// the layer consumed no expert: its stream entries must still be released, or the issuer 5198// thread fills the ring and the next fully computed layer waits for a copy that never comes 5199consumed = std::max (consumed ,seq_start [(size_t )l + 1 ]); 5200give_back (consumed ); 5201break ;// state advanced: no gated residual write, no MoE half of this layer 5202 } 5203 }else if (half == 0 ) { 5204// ======================= QSA ======================= 5205const core::QsaState & st = ss .qsa_states [qsa_index ]; 5206const core::WeightRef * wq = need (v ,"attn_q.weight" ,err ),* wk = need (v ,"attn_k.weight" ,err ), 5207* wv = need (v ,"attn_v.weight" ,err ),* wo = need (v ,"attn_output.weight" ,err ), 5208* wik = need (v ,"indexer.k_proj.weight" ,err ), 5209* wiq = need (v ,"indexer.q_proj.weight" ,err ), 5210* wqn = need (v ,"attn_q_norm.weight" ,err ),* wkn = need (v ,"attn_k_norm.weight" ,err ), 5211* wiqn = need (v ,"indexer.q_norm.weight" ,err ), 5212* wikn = need (v ,"indexer.k_norm.weight" ,err ); 5213if (!wq || !wk || !wv || !wo || !wik || !wiq || !wqn || !wkn || !wiqn || !wikn )return false; 5214pt .mark (kPfQsa ,cs ); 5215if (!native_proj (m .gemm ,wk ,m .mixed_h ,m .Kc ,T ,v .name ("attn_k.weight" ),err ))return false; 5216if (!native_proj (m .gemm ,wv ,m .mixed_h ,m .Vc ,T ,v .name ("attn_v.weight" ),err ))return false; 5217// KVA: the query projections have no consumer when only the KV/indexer state advances 5218if (!kva_state_only && !native_proj (m .gemm ,wq ,m .mixed_h ,m .Qf ,T ,v .name ("attn_q.weight" ),err ))return false; 5219pt .mark (kPfQsaIdxG ,cs );// STRATA_PREFILL_TIMING: "qsa proj" is the k, v and q projections 5220if (!bf16_proj (m .gemm ,wik ,m .mixed_bf ,m .idx_raw ,T ,v .name ("indexer.k_proj.weight" ),err ,0 ,m .mixed_bf_lo ))return false; 5221if (!kva_state_only && !bf16_proj (m .gemm ,wiq ,m .mixed_bf ,m .q_idx ,T ,v .name ("indexer.q_proj.weight" ),err ,0 ,m .mixed_bf_lo ))return false; 5222pt .mark (kPfQsaPrep ,cs ); 5223if (qsa_fuse_nr ()) { 5224rms_rope_rows (m .Kc ,kKvW ,kHeadDim ,m .Kc ,kKvW , (const float * )wkn -> data ,T ,kNKv ,kHeadDim ,EPS ,p0 , strata::kernels::rope_scaling (),m .cs ); 5225 }else { 5226rms_rows (m .Kc , (const float * )wkn -> data ,T * 2 ,256 ,256 ,EPS ,m .cs ); 5227rope (m .Kc ,T ,kNKv ,kHeadDim ,kKvW ,p0 , strata::kernels::rope_scaling (),m .cs ); 5228 } 5229// KV streaming: this layer's cells [0, p0) come in from the host copy to the staging pool, and the 5230// chunk's cells go to the host copy, the staging pool, and the VRAM slots of resident blocks 5231const bool staged = st .kv_mode == 1 ; 5232if (staged ) { 5233pt .mark (kPfKvStage ,cs ); 5234if (kv_pending == qsa_index ) { 5235if (cudaStreamWaitEvent (cs ,m .kv_ready ,0 )!= cudaSuccess ) { 5236err = "prefill: waiting for KV prefetch" ; 5237return false; 5238 } 5239kv_pending = -1 ; 5240 }else strata::kernels::kv_stage_from_host (pools_of (m .stage ,m .ident_table ),st .host , 5241 core::qsa_kv_format (st ), 5242 (p0 + s .page_size - 1 ) /s .page_size ,s ,m .cs ); 5243pt .mark (kPfQsa ,cs ); 5244pf_step ("reading the prompt (batched, step sync): the K/V staged from RAM at layer" ,l ); 5245 } 5246// #579 #613 (HIP, opt-in A/B, STRATA_KV_HOST_DMA=1): the append writes the staging pool and the 5247// resident slots only, and one DMA copies the chunk's blocks from the staging pool to the host copy 5248// - no kernel writes host memory over PCIe. The bytes every reader sees are the same (the staged 5249// first block is complete; past the chunk's last cell nothing is read until a later append writes 5250// it). CUDA: the default (core/kv_host_dma.hpp: the kernel's own stores to the host copy ran at 5251// about 0.24 GB/s, 50 us a prompt token); STRATA_KV_HOST_DMA=0 gives the kernel's stores back. 5252#if defined(STRATA_USE_HIP ) 5253static const bool kv_host_dma = [] {const char * e = std::getenv ("STRATA_KV_HOST_DMA" );return e && e [0 ]== '1' ; }(); 5254#else 5255static const bool kv_host_dma = core::kv_host_dma_on (std::getenv ("STRATA_KV_HOST_DMA" ), true); 5256#endif 5257const bool host_by_dma = core::kv_host_dma_use (kv_host_dma ,staged ,m .stage .present ()); 5258const strata::kernels::KvHostPools * host_w = host_by_dma ?nullptr :& st .host ; 5259if (st .kv_hybrid ) {// K8V4: K INT8 unrotated, V rotated Q4_0 (only V and the output rotate) 5260// streamed: each half writes its part of the host copy and of the staging pool 5261 strata::kernels::fwht256_inplace_cuda (m .Vc ,T * 2 ,m .cs ); 5262const strata::kernels::KvHostPools hk = strata::kernels::kv_hybrid_k_half (st .host ), 5263hv = strata::kernels::kv_hybrid_v_half (st .host ), 5264sk = strata::kernels::kv_hybrid_k_half (m .stage ), 5265sv = strata::kernels::kv_hybrid_v_half (m .stage ); 5266const bool mirror = st .host .present (); 5267kv_append (m .Kc ,m .Kc ,T ,p0 ,st .page_table ,s .page_size ,nullptr ,nullptr , 5268st .k_q ,st .k_q ,st .k_scale ,st .k_scale ,m .cs ,mirror ?& hk :nullptr , 5269staged ?& sk :nullptr ); 5270 strata::kernels::kv_append_q4 (st .v_q4 ,st .v_q4 ,st .page_table ,p0 ,T ,m .Vc ,m .Vc ,s ,m .cs , 5271mirror ?& hv :nullptr ,staged ?& sv :nullptr ); 5272 }else { 5273if (st .kv_rot ) {// rotated K and V (kv_q4.hpp), the queries below too, the output back 5274 strata::kernels::fwht256_inplace_cuda (m .Kc ,T * 2 ,m .cs ); 5275 strata::kernels::fwht256_inplace_cuda (m .Vc ,T * 2 ,m .cs ); 5276 } 5277if (st .kv_q4 ) 5278 strata::kernels::kv_append_q4 (st .k_q4 ,st .v_q4 ,st .page_table ,p0 ,T ,m .Kc ,m .Vc ,s ,m .cs , 5279host_w ,staged ?& m .stage :nullptr ); 5280else 5281kv_append (m .Kc ,m .Vc ,T ,p0 ,st .page_table ,s .page_size ,st .kv_int8 ?nullptr :st .k_pool , 5282st .kv_int8 ?nullptr :st .v_pool ,st .k_q ,st .v_q ,st .k_scale ,st .v_scale ,m .cs , 5283host_w ,staged ?& m .stage :nullptr ); 5284if (host_by_dma ) 5285 strata::kernels::kv_unstage_to_host (pools_of (m .stage ,m .ident_table ),st .host , 5286 core::qsa_kv_format (st ),p0 /s .page_size , 5287 (p0 + T + s .page_size - 1 ) /s .page_size ,s ,m .cs ); 5288 } 5289if (staged )pf_step ("reading the prompt (batched, step sync): the K/V append at layer" ,l ); 5290if (qsa_fuse_nr ()) { 5291rms_rope_rows (m .Qf ,kNHead * 2 * kHeadDim ,2 * kHeadDim ,m .q ,kQW , (const float * )wqn -> data ,T ,kNHead ,kHeadDim ,EPS ,p0 , strata::kernels::rope_scaling (),m .cs ); 5292 }else { 5293split_q (m .Qf ,m .q ,T ,m .cs ); 5294rms_rows (m .q , (const float * )wqn -> data ,T * kNHead ,kHeadDim ,kHeadDim ,EPS ,m .cs ); 5295rope (m .q ,T ,kNHead ,kHeadDim ,kQW ,p0 , strata::kernels::rope_scaling (),m .cs ); 5296 } 5297if (st .kv_rot ) strata::kernels::fwht256_inplace_cuda (m .q ,T * kNHead ,m .cs ); 5298if (qsa_fuse_nr ()) { 5299rms_rope_rows (m .q_idx ,kIdxQW ,kIdxK ,m .q_idx ,kIdxQW , (const float * )wiqn -> data ,T ,kIdxQHeads ,kIdxK ,EPS ,p0 , strata::kernels::rope_scaling (),m .cs ); 5300 }else { 5301rms_rows (m .q_idx , (const float * )wiqn -> data ,T * 4 ,128 ,128 ,EPS ,m .cs ); 5302rope (m .q_idx ,T ,kIdxQHeads ,kIdxK ,kIdxQW ,p0 , strata::kernels::rope_scaling (),m .cs ); 5303 } 5304// the indexer appends, token by token; then scores + selection for many queries at once: 5305// a query reads completed blocks (final once completed) and `dead` for its own tail block 5306const strata::kernels::QsaIndexerBuffers ib {st .idx_tail ,st .idx_dead ,st .idx_pooled ,st .idx_block_pos }; 5307pt .mark (kPfQsaIdx ,cs ); 5308// C-2: the chunk's appends in three launches instead of one per token (the same end state: 5309// the queries below read it only after the whole chunk is appended). STRATA_INDEXER_PER_TOKEN=1: the old 5310try { 5311static const bool per_token = std::getenv ("STRATA_INDEXER_PER_TOKEN" )!= nullptr ; 5312if (!per_token ) { 5313 strata::kernels::native_qsa_indexer_append_batch (m .idx_raw ,T ,p0 ,0 , (const float * )wikn -> data , 5314EPS ,ib ,s ,st .max_cells , 5315 strata::kernels::rope_scaling (),m .cs ); 5316 } 5317for (int64_t t = 0 ;per_token && t < T ;++ t ) { 5318const int32_t * step_t = m .steps_dev + t * strata::kernels::kStepCount ; 5319 strata::kernels::native_qsa_indexer_append (m .idx_raw + t * 128 ,step_t + strata::kernels::kStepPos ,0 , 5320 (const float * )wikn -> data ,EPS ,ib ,s ,st .max_cells , 5321 strata::kernels::rope_scaling (),m .cs ); 5322 } 5323 }catch (const std::exception & e ) {err = std::string ("prefill indexer: " )+ e .what ();return false; } 5324// KVA: the KV pages and the indexer's keys/pool are complete for this chunk. Nothing that 5325// reads them (query side, selection, attention, output projection, the MoE half) has a 5326// consumer left, so the layer ends here. 5327if (kva_state_only ) { 5328++ qsa_index ; 5329if (!kv_prefetch_after (l + 1 ,qsa_index ))return false; 5330// no expert is consumed here: release the stream entries so the issuer cannot stall 5331consumed = std::max (consumed ,seq_start [(size_t )l + 1 ]); 5332give_back (consumed ); 5333break ; 5334 } 5335pt .mark (kPfQsaSel ,cs ); 5336#if !defined(STRATA_GPU_METAL ) 5337// STRATA_SELECT_TWO_PASS=1 (qsa_two_pass.hpp): the tensor-core scorer's calls whose last query has 5338// STRATA_SELECT_TWO_PASS_MIN blocks or more score every block in single-pass TF32 and again in 3xTF32 5339// only where the error bound reaches the cut-off; qsa_block_topk below returns the same cells. Its 5340// scratch is m.attn, which the attention below writes and nothing reads before; the key norms are 5341// this layer's and chunk's (the indexer appends above are complete) 5342static const bool tp_on = strata::kernels::qsa_two_pass_on (); 5343static const bool tp_check = tp_on && strata::kernels::qsa_two_pass_check_on (); 5344static const int64_t tp_min = strata::kernels::qsa_two_pass_min_blocks (); 5345const uint64_t tp_bytes = (uint64_t )m .T * ZV * sizeof (float ); 5346const int64_t tp_nbid = T > 0 ? (int64_t )m .steps_host [(size_t ) ((T - 1 )* strata::kernels::kStepCount + 5347 strata::kernels::kStepNBid )] :0 ; 5348const bool tp_ok = tp_on && tp_nbid + 1 >=tp_min && 5349 strata::kernels::qsa_two_pass_keys (st .idx_pooled ,tp_nbid ,m .sel_batch ,m .max_blocks , 5350m .attn ,tp_bytes ,m .cs ); 5351#endif 5352for (int64_t t0 = 0 ;t0 < T ;t0 += m .sel_batch ) { 5353const int64_t nb = std::min (m .sel_batch ,T - t0 ); 5354const int32_t * steps0 = m .steps_dev + t0 * strata::kernels::kStepCount ; 5355// C-1: the grid reaches the batch's last query's n_bid (they rise with the position) 5356const int64_t active = (int64_t )m .steps_host [(size_t ) ((t0 + nb - 1 )* strata::kernels::kStepCount + 5357 strata::kernels::kStepNBid )]+ 1 ; 5358// the scores on tensor cores (3xTF32: FP32-level, not bitwise), below sm_80 the FP32 tiled kernel with STRATA_SELECT_SIMT=1; 5359// STRATA_SELECT_OLD=1: the warp kernel 5360static const bool old_sel = std::getenv ("STRATA_SELECT_OLD" )!= nullptr ; 5361bool tp_call = false; 5362#if !defined(STRATA_GPU_METAL ) 5363tp_call = tp_ok && !old_sel && active >=tp_min && 5364 strata::kernels::qsa_block_scores_two_pass (st .idx_pooled ,st .idx_dead ,m .q_idx + t0 * kIdxQW , 5365steps0 ,nb ,m .sel_batch ,m .max_blocks ,s , 5366m .sel_scores ,m .attn ,tp_bytes ,m .cs ,active ); 5367#endif 5368if (!tp_call && (old_sel || !strata::kernels::qsa_block_scores_tc (st .idx_pooled ,st .idx_dead ,m .q_idx + t0 * kIdxQW , 5369steps0 ,nb ,m .max_blocks ,s ,m .sel_scores , 5370m .cs ,active ))) 5371 strata::kernels::qsa_block_scores (st .idx_pooled ,st .idx_dead ,m .q_idx + t0 * kIdxQW ,steps0 ,nb , 5372m .max_blocks ,s ,m .sel_scores ,m .cs ,active ); 5373 strata::kernels::qsa_block_topk (m .sel_scores ,steps0 ,nb ,m .max_blocks ,m .cap ,s , 5374m .sel_ids + t0 * m .cap ,m .cs ,active ); 5375#if !defined(STRATA_GPU_METAL ) 5376// STRATA_SELECT_TWO_PASS_CHECK=1 (diagnostic, one GPU): today's scores and ids for the same 5377// queries, compared with the two-pass ones (counts at the prompt's end). Their buffers are the 5378// rest of m.attn past the two-pass scratch when it is large enough (the attention below writes 5379// m.attn after the comparison), else buffers of their own 5380if (tp_call && tp_check ) { 5381static float * own_sc = nullptr ; 5382static int32_t * own_ids = nullptr ; 5383static size_t own_sc_n = 0 ,own_ids_n = 0 ; 5384const size_t want_sc = (size_t )m .sel_batch * (size_t )m .max_blocks ,want_ids = (size_t )m .sel_batch * (size_t )m .cap ; 5385const uint64_t at = (strata::kernels::qsa_two_pass_scratch_bytes (m .sel_batch ,m .max_blocks )+ 255u )& ~uint64_t (255u ); 5386const uint64_t at_ids = at + (((uint64_t )want_sc * 4u + 255u )& ~uint64_t (255u )); 5387float * ref_sc = nullptr ; 5388int32_t * ref_ids = nullptr ; 5389if (at_ids + (uint64_t )want_ids * 4u <=tp_bytes ) { 5390ref_sc = reinterpret_cast < float *> (reinterpret_cast < uint8_t *> (m .attn )+ at ); 5391ref_ids = reinterpret_cast < int32_t *> (reinterpret_cast < uint8_t *> (m .attn )+ at_ids ); 5392 }else { 5393if (want_sc > own_sc_n || want_ids > own_ids_n ) { 5394cudaStreamSynchronize (m .cs ); 5395cudaFree (own_sc ); 5396cudaFree (own_ids ); 5397own_sc = nullptr ; 5398own_ids = nullptr ; 5399own_sc_n = own_ids_n = 0 ; 5400if (cudaMalloc ((void ** )& own_sc ,want_sc * 4 )!= cudaSuccess || 5401cudaMalloc ((void ** )& own_ids ,want_ids * 4 )!= cudaSuccess ) { 5402err = "STRATA_SELECT_TWO_PASS_CHECK: no room for its buffers" ; 5403return false; 5404 } 5405own_sc_n = want_sc ; 5406own_ids_n = want_ids ; 5407 } 5408ref_sc = own_sc ; 5409ref_ids = own_ids ; 5410 } 5411if (!strata::kernels::qsa_block_scores_tc (st .idx_pooled ,st .idx_dead ,m .q_idx + t0 * kIdxQW ,steps0 ,nb , 5412m .max_blocks ,s ,ref_sc ,m .cs ,active )) { 5413err = "STRATA_SELECT_TWO_PASS_CHECK: the tensor-core scorer did not run" ; 5414return false; 5415 } 5416 strata::kernels::qsa_block_topk (ref_sc ,steps0 ,nb ,m .max_blocks ,m .cap ,s ,ref_ids ,m .cs ,active ); 5417 strata::kernels::qsa_two_pass_check (m .sel_scores ,m .sel_ids + t0 * m .cap ,ref_sc ,ref_ids ,steps0 ,nb , 5418m .sel_batch ,m .max_blocks ,m .cap ,m .attn ,m .cs ); 5419 } 5420#endif 5421 } 5422// STRATA_SEL_OVERLAP (debug, D-1's question): how much do neighbouring queries' selections share? 5423// Per tile of 16 queries: the union of their selected cells against the sum of their widths. 5424if (static const bool ovl = std::getenv ("STRATA_SEL_OVERLAP" )!= nullptr ;ovl && qsa_index == 0 ) { 5425 std::vector < int32_t > ids ((size_t ) (T * m .cap )); 5426cudaMemcpyAsync (ids .data (),m .sel_ids ,ids .size ()* 4 ,cudaMemcpyDeviceToHost ,m .cs ); 5427cudaStreamSynchronize (m .cs ); 5428double sum_w = 0 ,sum_u = 0 ; 5429for (int64_t t0 = 0 ;t0 + 16 <=T ;t0 += 16 ) { 5430 std::vector < int32_t > u ; 5431for (int64_t t = t0 ;t < t0 + 16 ;++ t ) { 5432const int64_t w = m .steps_host [(size_t ) (t * strata::kernels::kStepCount + strata::kernels::kStepWidth )]; 5433sum_w += (double )w ; 5434u .insert (u .end (),ids .begin ()+ t * m .cap ,ids .begin ()+ t * m .cap + w ); 5435 } 5436 std::sort (u .begin (),u .end ()); 5437sum_u += (double ) (std::unique (u .begin (),u .end ())- u .begin ()); 5438 } 5439 std::fprintf (stderr ,"strata prefill: selection overlap at %lld: 16-query tiles read %.1f%% of the " 5440"cells one query at a time does\n" , (long long )p0 ,sum_w > 0 ?100.0 * sum_u /sum_w :0.0 ); 5441 } 5442// STRATA_IDX_FP16_CHECK: would FP16 pooled indexer keys select the same cells? (the KV-streaming 5443// design's last question). Every query is selected again from the pooled keys and `dead` rounded 5444// to fp16 (exactly what an fp16 store reads back); the agreement with the fp32 selection is 5445// printed cumulatively after each chunk's last QSA layer. Debug: syncs per layer. 5446if (static const bool f16chk = std::getenv ("STRATA_IDX_FP16_CHECK" )!= nullptr ;f16chk ) { 5447static float * pooled16 = nullptr ,* dead16 = nullptr ; 5448static int32_t * ids16 = nullptr ; 5449static double shared = 0 ,cells = 0 ; 5450static long long queries = 0 ,same = 0 ,sel_queries = 0 ; 5451const int64_t rows = st .idx_pooled_rows ; 5452if (pooled16 == nullptr && 5453 (cudaMalloc ((void ** )& pooled16 , (size_t )rows * s .idx_dim * 4 )!= cudaSuccess || 5454cudaMalloc ((void ** )& dead16 , (size_t )s .idx_dim * 4 )!= cudaSuccess || 5455cudaMalloc ((void ** )& ids16 , (size_t ) (m .T * m .cap )* 4 )!= cudaSuccess )) { 5456err = "STRATA_IDX_FP16_CHECK: no room for its buffers" ; 5457return false; 5458 } 5459round_f16 (st .idx_pooled ,pooled16 ,rows * s .idx_dim ,m .cs ); 5460round_f16 (st .idx_dead ,dead16 ,s .idx_dim ,m .cs ); 5461for (int64_t t0 = 0 ;t0 < T ;t0 += m .sel_batch ) { 5462const int64_t nb = std::min (m .sel_batch ,T - t0 ); 5463const int32_t * steps0 = m .steps_dev + t0 * strata::kernels::kStepCount ; 5464 strata::kernels::qsa_block_scores (pooled16 ,dead16 ,m .q_idx + t0 * kIdxQW ,steps0 ,nb , 5465m .max_blocks ,s ,m .sel_scores ,m .cs ); 5466 strata::kernels::qsa_block_topk (m .sel_scores ,steps0 ,nb ,m .max_blocks ,m .cap ,s , 5467ids16 + t0 * m .cap ,m .cs ); 5468 } 5469 std::vector < int32_t > a ((size_t ) (T * m .cap )),b ((size_t ) (T * m .cap )); 5470cudaMemcpyAsync (a .data (),m .sel_ids ,a .size ()* 4 ,cudaMemcpyDeviceToHost ,m .cs ); 5471cudaMemcpyAsync (b .data (),ids16 ,b .size ()* 4 ,cudaMemcpyDeviceToHost ,m .cs ); 5472cudaStreamSynchronize (m .cs ); 5473for (int64_t t = 0 ;t < T ;++ t ) { 5474const int64_t w = m .steps_host [(size_t ) (t * strata::kernels::kStepCount + strata::kernels::kStepWidth )]; 5475const int32_t * x = a .data ()+ t * m .cap ,* y = b .data ()+ t * m .cap ; 5476int64_t i = 0 ,j = 0 ,c = 0 ; 5477while (i < w && j < w ) { 5478if (x [i ]== y [j ]) {++ c ;++ i ;++ j ; }else if (x [i ]< y [j ])++ i ;else ++ j ; 5479 } 5480++ queries ; 5481same += c == w ; 5482if (p0 + t + 1 > m .cap ) {++ sel_queries ;shared += (double )c ;cells += (double )w ; } 5483 } 5484if (qsa_index + 1 == g .n_qsa_layers ()) 5485 std::fprintf (stderr ,"strata prefill: FP16 indexer keys: %lld of %lld selections identical; " 5486"where the selection is sparse, %.4f%% of cells shared (%lld queries)\n" , 5487same ,queries ,cells > 0 ?100.0 * shared /cells :100.0 ,sel_queries ); 5488 } 5489// STRATA_QSA_DUMP=<file>: append every QSA layer's selected cells for the prompt's last 5490// STRATA_QSA_DUMP_LAST (4096) positions - records of int32 {qsa layer, pos0, T, cap} + T*cap cells, 5491// for tools/qsa_locality.py (how local the sparse attention's reads are: the KV-streaming question). 5492// STRATA_QSA_DUMP_LAYER=i: QSA layer i only; STRATA_QSA_DUMP_STEPS=1: each record then ends with the 5493// T * kStepCount steps too (tests/cuda/pa_bench.cpp replays such a record) 5494if (static const char * dump = std::getenv ("STRATA_QSA_DUMP" );dump != nullptr ) { 5495static const long long last = std::getenv ("STRATA_QSA_DUMP_LAST" ) 5496 ? std::atoll (std::getenv ("STRATA_QSA_DUMP_LAST" )) :4096 ; 5497static const int only = std::getenv ("STRATA_QSA_DUMP_LAYER" ) ? std::atoi (std::getenv ("STRATA_QSA_DUMP_LAYER" )) :-1 ; 5498if (p0 + T > pos0 + n - last && (only < 0 || only == (int )qsa_index )) { 5499 std::vector < int32_t > h ((size_t ) (T * m .cap )); 5500cudaMemcpyAsync (h .data (),m .sel_ids ,h .size ()* 4 ,cudaMemcpyDeviceToHost ,m .cs ); 5501cudaStreamSynchronize (m .cs ); 5502if (std::FILE * f = std::fopen (dump ,"ab" )) { 5503const int32_t hdr [4 ]= {(int32_t )qsa_index , (int32_t )p0 , (int32_t )T , (int32_t )m .cap }; 5504 std::fwrite (hdr ,4 ,4 ,f ); 5505 std::fwrite (h .data (),4 ,h .size (),f ); 5506if (std::getenv ("STRATA_QSA_DUMP_STEPS" )) { 5507 std::vector < int32_t > sv ((size_t ) (T * strata::kernels::kStepCount )); 5508cudaMemcpy (sv .data (),m .steps_dev ,sv .size ()* 4 ,cudaMemcpyDeviceToHost ); 5509 std::fwrite (sv .data (),4 ,sv .size (),f ); 5510 } 5511 std::fclose (f ); 5512 } 5513 } 5514 } 5515const strata::kernels::QsaAttnPools pools = staged ?pools_of (m .stage ,m .ident_table ) 5516 : core::qsa_attn_pools (st ); 5517pt .mark (kPfQsaAttn ,cs ); 5518// perf-review D-1: the whole chunk on tensor cores, one block per (query, KV head), FP32-level 5519// accuracy but not bitwise (qsa_prompt_attn.hpp). Q4_0 KV, or STRATA_PROMPT_ATTN_OLD=1: the 5520// decode kernel, 32 queries at a time (K8V4 runs the tensor kernel's mode 3: INT8 K, 5521// V dequantized from its q4_0 blocks to fp16 at gather) 5522static const bool old_attn = std::getenv ("STRATA_PROMPT_ATTN_OLD" )!= nullptr ; 5523const int64_t ld_a = pf_pad ()&& T >= std::max < int64_t > (pf_switch_min_t (),64 ) ?ZV + ZV_PAD :0 ; 5524const bool gated = !old_attn && !st .kv_rot && !st .kv_hybrid && qsa_fuse_gate ()&& 5525 strata::kernels::qsa_prompt_attn_batch_gated (m .q ,pools ,m .sel_ids ,m .steps_dev ,m .cap ,s ,m .Qf , 5526m .attn_h ,ld_a > 0 ?ld_a :ZV ,T ,m .cs ); 5527 { 5528static bool told = false;// once: which of the two fusions this run took 5529if (!told ) { 5530told = true; 5531 std::fprintf (stderr ,"strata prefill: QSA layers: norm + rope in one pass %s, attention gate in the attention epilogue %s\n" , 5532qsa_fuse_nr () ?"on" :"off" ,gated ?"on" :"off" ); 5533 } 5534 } 5535// STRATA_PATTN_SM60=1 (qsa_pattn.hpp, sm_6x, int8 K/V): the decode kernels' output bit for bit from a 5536// score kernel and a value kernel that merges as it folds (no partials, no merge kernel), ~100 5537// queries a batch in the same scratch; any refusal or launch failure runs the loop below 5538if (!gated && (old_attn || !strata::kernels::qsa_prompt_attn_batch (m .q ,pools ,m .sel_ids ,m .steps_dev ,m .cap ,s , 5539m .attn ,T ,m .cs ))) 5540#if !defined(STRATA_GPU_METAL )// qsa_pattn.cu is in the CUDA / HIP kernel library only 5541if (!(strata::kernels::pattn_mode ()!= 0 && 5542 strata::kernels::qsa_pattn_batch (m .q ,pools ,m .sel_ids ,m .steps_dev ,m .cap ,s ,m .attn_scratch , 5543 (uint64_t )m .attn_batch * 5544 strata::kernels::qsa_decode_attn_scratch_floats (m .cap ,s ), 5545m .attn ,T ,m .cs ))) 5546#endif 5547for (int64_t t0 = 0 ;t0 < T ;t0 += m .attn_batch ) { 5548const int64_t nb = std::min (m .attn_batch ,T - t0 ); 5549 strata::kernels::qsa_decode_attn_batch (m .q + t0 * kQW ,pools ,m .sel_ids + t0 * m .cap , 5550m .steps_dev + t0 * strata::kernels::kStepCount ,m .cap , 5551s ,m .attn_scratch ,m .attn + t0 * kQW ,nb ,m .cs ); 5552 } 5553if (st .kv_rot || st .kv_hybrid ) strata::kernels::fwht256_inplace_cuda (m .attn ,T * kNHead ,m .cs ); 5554pt .mark (kPfQsa ,cs ); 5555if (!gated )gate_attn (m .attn ,m .Qf ,m .attn_h ,T ,m .cs ,ld_a ); 5556if (!native_proj (m .gemm ,wo ,m .attn_h ,m .bo ,T ,v .name ("attn_output.weight" ),err ,0 ,ld_a ))return false; 5557++ qsa_index ; 5558if (!kv_prefetch_after (l + 1 ,qsa_index ))return false; 5559 }else { 5560// ======================= MoE ======================= 5561const core::WeightRef * wr = need (v ,"ffn_gate_inp.weight" ,err ), 5562* wgi = need (v ,"ffn_gate_inp_shexp.weight" ,err ), 5563* wsg = need (v ,"ffn_gate_shexp.weight" ,err ), 5564* wsu = need (v ,"ffn_up_shexp.weight" ,err ), 5565* wsd = need (v ,"ffn_down_shexp.weight" ,err ); 5566if (!wr || !wgi || !wsg || !wsu || !wsd )return false; 5567pt .mark (kPfRouter ,cs ); 5568if (!bf16_proj (m .gemm ,wr ,m .mixed_bf ,m .logits ,T ,v .name ("ffn_gate_inp.weight" ),err ,0 ,m .mixed_bf_lo ))return false; 5569route (m .logits ,m .ids ,m .w ,T ,m .g -> n_expert ,m .cs ); 5570// RESEARCH HOOK (141-research, opt-in, never on by default): STRATA_DBG_FEAT=<file> dumps, per MoE layer and chunk, 5571// the routed ids + weights (and for the layers in STRATA_DBG_FEAT_LAYERS the router-input hidden state, bf16); 5572// STRATA_DBG_ROUTE_OVERRIDE=<file> replaces the routing of the layers listed in that file with the file's ids + weights. 5573 { 5574static const char * feat_path = std::getenv ("STRATA_DBG_FEAT" ); 5575static const char * ovr_path = std::getenv ("STRATA_DBG_ROUTE_OVERRIDE" ); 5576if (feat_path != nullptr || ovr_path != nullptr ) { 5577static std::FILE * ff = feat_path ? std::fopen (feat_path ,"wb" ) :nullptr ; 5578static std::vector < bool > featl = [] { 5579 std::vector < bool > r (64 , false); 5580const char * e = std::getenv ("STRATA_DBG_FEAT_LAYERS" ); 5581 std::string s = e ?e :"3,4,15,16,27,28,39,40" ; 5582size_t i = 0 ; 5583while (i < s .size ()) {size_t j = s .find (',' ,i );if (j == std::string::npos )j = s .size ();int v = std::atoi (s .substr (i ,j - i ).c_str ());if (v >=0 && v < 64 )r [(size_t )v ]= true;i = j + 1 ; } 5584return r ; 5585 }(); 5586static int64_t posl [64 ]= {}; 5587struct Ovr { std::vector < int32_t > ids ; std::vector < float > w ; }; 5588static std::map < std::pair < int32_t ,int32_t > ,Ovr > ovr = [] { 5589 std::map < std::pair < int32_t ,int32_t > ,Ovr > mp ; 5590const char * p = std::getenv ("STRATA_DBG_ROUTE_OVERRIDE" ); 5591 std::FILE * f = p ? std::fopen (p ,"rb" ) :nullptr ; 5592if (f == nullptr )return mp ; 5593int32_t h [3 ]; 5594while (std::fread (h ,4 ,3 ,f )== 3 ) { 5595Ovr o ;o .ids .resize ((size_t )h [2 ]* K );o .w .resize ((size_t )h [2 ]* K ); 5596if (std::fread (o .ids .data (),4 ,o .ids .size (),f )!= o .ids .size ())break ; 5597if (std::fread (o .w .data (),4 ,o .w .size (),f )!= o .w .size ())break ; 5598mp [{h [0 ],h [1 ]}]= std::move (o ); 5599 } 5600 std::fclose (f ); 5601 std::fprintf (stderr ,"route override: %zu records\n" ,mp .size ()); 5602return mp ; 5603 }(); 5604const int32_t pos = (int32_t )posl [l & 63 ]; 5605posl [l & 63 ]+= T ; 5606cudaStreamSynchronize ((cudaStream_t )m .cs ); 5607if (ff != nullptr ) { 5608 std::vector < int32_t > hid ((size_t )T * K ); std::vector < float > hw ((size_t )T * K ); 5609cudaMemcpy (hid .data (),m .ids ,hid .size ()* 4 ,cudaMemcpyDeviceToHost ); 5610cudaMemcpy (hw .data (),m .w ,hw .size ()* 4 ,cudaMemcpyDeviceToHost ); 5611 std::vector < uint16_t > ids16 (hid .size ()),w16 (hw .size ()); 5612for (size_t i = 0 ;i < hid .size ();++ i ) {ids16 [i ]= (uint16_t )hid [i ];w16 [i ]= (uint16_t ) (((* (const uint32_t * )& hw [i ])+ 0x8000u ) >>16 ); } 5613const int32_t hd [4 ]= {(int32_t )l ,pos , (int32_t )T ,featl [(size_t ) (l & 63 )] ?1 :0 }; 5614 std::fwrite (hd ,4 ,4 ,ff ); 5615 std::fwrite (ids16 .data (),2 ,ids16 .size (),ff ); 5616 std::fwrite (w16 .data (),2 ,w16 .size (),ff );// bf16 weights 5617if (hd [3 ]) { 5618 std::vector < uint16_t > hx ((size_t )T * N ); 5619cudaMemcpy (hx .data (),m .mixed_bf ,hx .size ()* 2 ,cudaMemcpyDeviceToHost ); 5620 std::fwrite (hx .data (),2 ,hx .size (),ff ); 5621 } 5622 } 5623auto it = ovr .find ({(int32_t )l ,pos }); 5624if (it != ovr .end ()&& (int64_t )it -> second .ids .size ()== T * K ) { 5625cudaMemcpy (m .ids ,it -> second .ids .data (), (size_t )T * K * 4 ,cudaMemcpyHostToDevice ); 5626cudaMemcpy (m .w ,it -> second .w .data (), (size_t )T * K * 4 ,cudaMemcpyHostToDevice ); 5627 } 5628 } 5629 } 5630// the shared expert and its scalar gate 5631auto shared_expert = [& ]()-> bool { 5632if (!native_proj (m .gemm ,wsg ,m .mixed_h ,m .sgate ,T ,v .name ("ffn_gate_shexp.weight" ),err ))return false; 5633if (!native_proj (m .gemm ,wsu ,m .mixed_h ,m .sup ,T ,v .name ("ffn_up_shexp.weight" ),err ))return false; 5634swiglu_pair (m .sgate ,m .sup ,m .sh_h ,T ,m .cs ); 5635if (!native_proj (m .gemm ,wsd ,m .sh_h ,m .shared ,T ,v .name ("ffn_down_shexp.weight" ),err ))return false; 5636if (wgi -> kind != core::WeightKind ::Bf16InF32 ) {err = "prefill: shared gate is not BF16" ;return false; } 5637m .gemm .bf16 (m .mixed_bf , (const uint16_t * )wgi -> data ,m .sg ,T ,1 ,N ); 5638if (m .mixed_bf_lo )m .gemm .bf16 (m .mixed_bf_lo , (const uint16_t * )wgi -> data ,m .sg ,T ,1 ,N ,0 ,1.0f ); 5639return true; 5640 }; 5641// Only the router needs to finish before readback. Queue the shared expert afterwards 5642// so it can overlap CPU grouping and the routed-only path's initial expert uploads. 5643const bool defer_shared = !stream_all && stream_ahead_enabled (); 5644if (!defer_shared && !shared_expert ())return false; 5645// #136: STRATA_PF_FUSED=1 - the Q2_0 pack's experts on the fused int8 kernels (moe_fused.hpp), 5646// grouped on the GPU: no host sync. Only where every expert's place is known before the routing - 5647// the streamed walk, in which every non-resident expert of the layer comes through the ring in id 5648// order - and where the MMQ buffers exist: they hold the fused path's own (the per-token int8 5649// activations in Xq, the int8 H in H, the grouping tables in GU). Chunks below stream_all_min() 5650// keep MMQ; without the variable nothing here runs. A native pack's layer takes the native kernels 5651// (moe_fused_iq.hpp) where they cover its two formats, else MMQ (or the FP16 path: IQ1_M). 5652const strata::kernels::cpu::ExpertLayout & lay = strata::kernels::cpu::expert_layout (); 5653// APR (prism.hadamard): folded gate/up take H (s * x), folded down H (s * h), on the FP16 and MMQ 5654// paths and on the multi-GPU prompt paths (the peer, the layer split's helper: MMQ); the fused 5655// kernels do not rotate (and have no trellis types), so a folded layer takes MMQ instead 5656const bool had_gu = lay .native && lay .fmt [(size_t )l ].had_gu ; 5657const bool had_d = lay .native && lay .fmt [(size_t )l ].had_d ; 5658const bool use_mmq = mmq_plan ().any && mmq_plan ().layer [(size_t )l ]; 5659// STRATA_EXPERT_NIBBLE=1: a layer whose gate/up experts are 4-bit codes in their slots is gathered 5660// for MMQ as the GGUF blocks rebuilt from them (core::nibble::gather_gguf); every other expert path 5661// reads GGUF blocks in the slot, so it stops there instead (never a wrong answer) 5662#if STRATA_EXPERT_NIBBLE_BUILT // every guard of this switch is compiled out of the other builds 5663const core::nibble::LayerVram & nib_l = core::nibble::layer (l ); 5664#endif 5665const int had_block = lay .native ?lay .fmt [(size_t )l ].had_block :0 ; 5666const float * had_sx = had_gu ?m .had_sx [(size_t )l ] :nullptr ;// resolved in init 5667const float * had_sh = had_d ?m .had_sh [(size_t )l ] :nullptr ; 5668const int mmq_gt = lay .native ?lay .fmt [(size_t )l ].gu_type :42 ; 5669const int mmq_dt = lay .native ?lay .fmt [(size_t )l ].d_type :42 ; 5670// --peer-device with MMQ: MMQ only, whether or not the peer took the prompt path (set_peer can decline), as 5671// fused_ring() sized the ring and the buffers for it. Without MMQ the share is always declined: the 5672// kernels the walk picks without the flag, in MMQ's buffer layout (own_only_line.hpp peer_keeps_mmq) 5673const bool no_peer = !strata::prefill::peer_keeps_mmq (core::peer_portable (),kPfOwnOnlyBuild ); 5674const bool fused_only = mmq_plan ().any && mmq_plan ().fo [(size_t )l ]; 5675// a Hadamard-folded layer (APR / Gyro) on the fused kernels: only the trellis pairs (CUDA, STRATA_PF_FUSED_TQ=1: native_supported 5676// answers for them only with it), block 128: the gate/up input rotated into m.Xr as the MMQ path does, the down input 5677// rotated inside experts_native (fused::set_down_rotation); every other folded layer keeps MMQ 5678const bool fold_ok = had_block == 128 && ((mmq_gt == 145 && mmq_dt == 146 )|| (mmq_gt == 144 && mmq_dt == 144 ))&& 5679 (!had_gu || m .Xr != nullptr ); 5680const bool fused_nat = (use_mmq || fused_only )&& stream_all && no_peer && lay .native && ((!had_gu && !had_d )|| fold_ok )&& 5681 fused::native_supported (mmq_gt ,mmq_dt ); 5682#if defined(STRATA_PF_OWN_ONLY ) 5683const bool fused_l = ((use_mmq || fused_only )&& stream_all && no_peer && !lay .native && fused::enabled ())|| fused_nat ; 5684#else 5685const bool fused_l = (use_mmq && stream_all && no_peer && !lay .native && fused::enabled ())|| fused_nat ; 5686#endif 5687bool dm16_used = false;// STRATA_PF_DM16: this layer's down rows are FP16 (fused::dm_f16_used() after the experts) 5688bool fz_staged_l = false;// P4-SMALL: this staged chunk's groups ran on the fused kernels (GU / H hold their tables and int8 rows) 5689if (m .group_cap > 0 && (fused_l || !use_mmq )) {// GU / H / Hq are one group's size 5690err = "prefill: STRATA_PF_GROUP_SCRATCH needs MMQ on every layer (a layer took the fused or FP16 path)" ; 5691return false; 5692 } 5693// #583 / #954: the fused layout's GU/H/Xq hold the grouping tables and the int8 rows, sized for 5694// stream_all_min() - 1 tokens of MMQ's rows, so a layer that takes MMQ or the FP16 path at the FULL 5695// chunk would write T*K rows into a (stream_all_min() - 1)*K-row buffer: an illegal access, or a kernel 5696// that never returns (the first ck() to see it is `prefill mmq: iota`, one prompt later). fused_layout() 5697// and fused_ring() keep the shrink and this decision in step; this is the backstop for anything that 5698// drifts: a clear error, never a hang. 5699// STRATA_DBG_FORCE_SLOW_LAYER=1 (a test of the backstop): layer 0 counts as one the fused path does not take 5700static const bool force_slow = [] {const char * e = std::getenv ("STRATA_DBG_FORCE_SLOW_LAYER" );return e && e [0 ]== '1' ; }(); 5701if ((!fused_l || (force_slow && l == 0 ))&& m .fused_bufs && T >=stream_all_min ()) { 5702err = "prefill: the fused layout's MoE buffers are too small for layer " + std::to_string (l )+ 5703"'s expert path at a chunk of " + std::to_string (T )+ " tokens" ; 5704return false; 5705 } 5706size_t n_order = 0 ;// the routed experts (the debug report; unknown when fused) 5707bool peer_now = false;// multi-GPU: the peer computed rows of this layer (MMQ path only) 5708// set_cpu_pool: this layer's CPU experts (rows [T * K - rows_cpu, T * K) of Dm), computed on a thread 5709// that reads on_cpu: declared first, so the future (which waits for the thread) goes first 5710 std::vector < char > on_cpu ; 5711 std::vector < const uint8_t *> cpu_blob ;// the CPU experts' blobs, taken on this thread (the source is not thread-safe) 5712double cpu_ms = 0 ;// the thread's time (the measured share) 5713 std::future < bool > cpu_fut ; 5714int64_t rows_cpu = 0 ,n_cpu = 0 ,n_stream = 0 ,cpu_at = 0 ;// cpu_at: the CPU's first row of Dm 5715bool cpu_arm = true;// auto: this layer may share (false: the arm without) 5716int cpu_set = -1 ;// auto: the wall events' set, -1 when not measured 5717bool cpu_cold = false;// auto: one-time costs in the window (no reading) 5718#if STRATA_EXPERT_NIBBLE_BUILT 5719if (fused_l && nib_l .on ) core::nibble::fatal (l ,"the prompt path's fused experts" ,"they read GGUF blocks" ); 5720#endif 5721if (m .latent && fused_l ) {// the int8 fused path (STRATA_PF_FUSED) reads GGUF blocks 5722err = "prefill latent: the fused expert path (STRATA_PF_FUSED) is not supported" ; 5723return false; 5724 } 5725if (fused_l ) { 5726if (static bool said = false; !said ) { 5727said = true; 5728 std::fprintf (stderr ,"strata: prompt experts on the fused int8 kernels (STRATA_PF_FUSED=1, " 5729"#136)\n" ); 5730 } 5731pt .mark (kPfGather ,cs ); 5732// the layer's input to int8 once per token; the rows of each expert from the router's ids 5733if (fused_nat && had_gu ) {// (a folded trellis gate/up: its input rotated, as the MMQ path's xsrc = m.Xr) 5734 strata::kernels::hadamard_rows (m .mixed ,m .Xr ,T ,N ,had_block ,had_sx ,m .cs ); 5735 fused::quantize_act_native (m .Xr ,T ,N ,m .Xq ,m .cs ); 5736 }else if (fused_nat ) fused::quantize_act_native (m .mixed ,T ,N ,m .Xq ,m .cs ); 5737else fused::quantize_act (m .mixed ,T ,N ,m .Xq ,m .cs ); 5738// (a folded trellis down: H rotated inside experts_native; off again after the layer's launches) 5739if (fused_nat && had_d ) fused::set_down_rotation (true,had_sh ); 5740// STRATA_PF_P1A=1 (gfx1151): the layer input's FP16 rows for the P1A kernels (p1a_input keeps nullptr otherwise) 5741if (fused_nat ) fused::p1a_input (had_gu ?nullptr :m .mixed_h ,m .H_bytes ); 5742bool p1a_layer = false; 5743 fused::group (m .ids ,T * K , (int )K , (int )m .g -> n_expert ,m .GU ,m .slot_dev ,m .src_dev ,m .cs ); 5744// launches over the experts in id order, each at most kMaxBatch experts (STRATA_PF_BATCH: below) 5745// of which at most a third of the ring streamed: the next batch's blobs arrive while one computes. 5746// An expert the routing did not pick has no tiles; its ring slot is given back with its batch. 5747const size_t per = (size_t ) std::max (1 ,m .ring /3 ); 5748size_t k = seq_start [(size_t )l ]; 5749const size_t kend = seq_start [(size_t )l + 1 ]; 5750// STRATA_PF_BATCH=N (opt-in): experts per launch (the same rows, so the same bits; a launch is one 5751// persistent grid, so fewer launches leave fewer grid tails) - at most kMaxBatch, or up to 5752// kBatchRoom in a WideBatch on the native NT = 256 kernels (STRATA_PF_FUSED_NT=256 or _F16=1) or 5753// the warp-specialized kernel (STRATA_PF_FUSED_WS=1) 5754static const int pf_batch = [] { 5755const char * v = std::getenv ("STRATA_PF_BATCH" ); 5756const int n = v ? std::atoi (v ) :0 ; 5757return n > 0 ? std::min (n , fused::kBatchRoom ) : fused::kMaxBatch ; 5758 }(); 5759const bool wide = fused_nat && pf_batch > fused::kMaxBatch && fused::native_wide (); 5760const int per_launch = wide ?pf_batch : std::min (pf_batch , fused::kMaxBatch ); 5761for (int32_t e = 0 ;e < m .g -> n_expert ;) { 5762 fused::Batch b ; 5763 std::optional < fused::WideBatch > wb ;// wide: the launch's pointers (b keeps e0 / e1) 5764if (wide )wb .emplace (); 5765const uint8_t ** blob = wb ?wb -> blob :b .blob ; 5766b .e0 = e ; 5767const size_t k0 = k ; 5768for (;e < m .g -> n_expert && e - b .e0 < per_launch ;++ e ) { 5769if (k < kend && seq [k ].e == e ) { 5770if (k - k0 == per )break ; 5771blob [e - b .e0 ]= m .stage_dev [k % (size_t )m .ring ]; 5772++ k ; 5773 }else {// not streamed: resident (the walk streams all others) 5774blob [e - b .e0 ]= m .cache -> device_slot (m .host_res [(size_t )l * m .g -> n_expert + e ]); 5775// counted whether routed or not (the routing stays on the GPU): at a streamed 5776// chunk's size (>= 1024 tokens x 10 of 512) nearly every expert is routed 5777++ stats_ .experts_resident ; 5778 } 5779 } 5780b .e1 = e ; 5781if (k > k0 ) { 5782// one copy stream, in order: the batch's last blob covers the others 5783pt .mark (kPfWaitCopy ,cs ); 5784wait_issued (k - 1 ); 5785wait_copied (k - 1 , (k - 1 ) % (size_t )m .ring ); 5786 } 5787pt .mark (kPfGemmGU ,cs ); 5788if (fused_nat ) { 5789 fused::want_dm_f16 (pf_dm16 ()&& rows_cpu == 0 && !peer_now && ((reinterpret_cast < uintptr_t > (m .shared ) |reinterpret_cast < uintptr_t > (m .bo ))& 15 )== 0 ); 5790const auto & f = lay .fmt [(size_t )l ]; 5791const fused::NativeGeom ng {f .gu_type ,f .d_type ,f .gu_row ,f .d_row ,f .up_off ,f .down_off }; 5792if (wb ) { 5793wb -> e0 = b .e0 ; 5794wb -> e1 = b .e1 ; 5795 fused::experts_native (* wb ,ng , (int )m .g -> n_expert ,T * K ,m .GU ,m .Xq ,m .src_dev , 5796m .H ,m .Dm ,m .cs ); 5797 }else { 5798 fused::experts_native (b ,ng , (int )m .g -> n_expert ,T * K ,m .GU ,m .Xq ,m .src_dev ,m .H , 5799m .Dm ,m .cs ); 5800 } 5801dm16_used = fused::dm_f16_used (); 5802p1a_layer = p1a_layer || fused::p1a_used (); 5803 }else { 5804 fused::experts (b , (int )m .g -> n_expert ,T * K ,m .GU ,m .Xq ,m .src_dev ,m .H ,m .Dm ,m .cs ); 5805 } 5806for (size_t kk = k0 ;kk < k ;++ kk ) { 5807cudaEventRecord (m .used [kk % (size_t )m .ring ],m .cs ); 5808m .used_of [kk % (size_t )m .ring ]= (int ) (kk % (size_t )m .ring ); 5809 } 5810if (k > k0 ) { 5811consumed = k ; 5812give_back (consumed ); 5813 } 5814 } 5815if (fused_nat && had_d ) fused::set_down_rotation (false,nullptr ); 5816if (fused_nat && fused::p1a_wanted ()) { 5817 fused::p1a_input (nullptr ,0 ); 5818p1a_report (lay .fmt , (size_t )l ,p1a_layer ); 5819 } 5820 }else { 5821// group the (token, k) pairs by expert on the host 5822pt .mark (kPfHostGroup ,cs ); 5823// (the sync below also orders this layer's writes of slot/src/bounds after the previous 5824// layer's kernels that read them) 5825const bool grp_mapped = m .grp_host != nullptr ; 5826int32_t * ids_h = grp_mapped ?m .grp_host :m .ids_host .data (); 5827int32_t * slot_h = grp_mapped ?m .grp_host + m .grp_tk :m .slot_host .data (); 5828int32_t * src_h = grp_mapped ?m .grp_host + 2 * m .grp_tk :m .src_host .data (); 5829if (grp_mapped )copy_i32 (m .grp_dev ,m .ids ,T * K ,m .cs ); 5830else if (m .up_ring .d2h_sync (m .ids_host .data (),m .ids , (size_t )T * K * 4 ,m .cs )!= cudaSuccess ) { 5831err = "prefill: the routed ids' download failed" ;// #1996 5832return false; 5833 } 5834bool cpu_maybe = pool_hold .held && !stream_all && m .src != nullptr && !m .cpu_dead && 5835lay .native && !m .latent && (!m .pp || pf_peer_cpu ())&& !lay .fmt .empty (); 5836// The share's two pinned buffers are small (~50 MB) but are had mid-request, when the host may have 5837// nothing left (0.1.41 report: tight RAM, chats failing). A buffer that cannot be had ends the share 5838// for this engine - the GPU takes every expert, as with STRATA_PREFILL_CPU_SHARE=0 - instead of 5839// failing the request. 5840auto cpu_share_off = [& ](const char * what ) { 5841m .cpu_dead = true; 5842cpu_maybe = false; 5843 std::fprintf (stderr ,"prefill: the CPU share is off for this run: the host could not give %s " 5844"(RAM is short); the GPU streams every expert\n" ,what ); 5845 }; 5846// auto shares only while the layers that share cost less per non-resident expert than their 5847// neighbours that do not. #1282 (RX 7900 GRE + 5700X3D): every share lost, auto's 0.47 by 5848// 4.5%, the host's issue time per streamed expert rising 107 -> 200 us with the CPU busy - 5849// a cost g / (c + g) cannot see, as both sides are measured with the share on. The first 5850// eligible layers alternate, without first, until CPU_MIN_RATIOS ratios are in; then the 5851// cheaper arm, and every CPU_PROBE-th layer the other one (a prime: the probes move across 5852// the layers from one chunk to the next), so both stay measured. 5853if (cpu_maybe && cpu_share_env ()< 0.0 ) { 5854constexpr int64_t CPU_PROBE = 29 ; 5855constexpr int CPU_MIN_RATIOS = 3 ; 5856const int64_t i = m .cpu_layers ++ ; 5857cpu_arm = m .cpu_nratio < CPU_MIN_RATIOS ? (i & 1 )!= 0 : (i %CPU_PROBE == 0 )!= m .cpu_gate ; 5858if (m .cpu_first_l < 0 )m .cpu_first_l = l ; 5859cpu_cold = l == m .cpu_first_l ; 5860if (m .cpu_wall [0 ]== nullptr ) 5861for (cudaEvent_t & e :m .cpu_wall )cudaEventCreate (& e ); 5862cpu_set = (int ) (i & 1 ); 5863cudaEventRecord (m .cpu_wall [2 * cpu_set ],m .cs ); 5864 } 5865if (cpu_maybe && cpu_arm ) { 5866const size_t want = (size_t )T * N ; 5867if (m .cpu_x_n < want ) { 5868cpu_cold = true; 5869if (m .cpu_x )cudaFreeHost (m .cpu_x ); 5870m .cpu_x = nullptr ; 5871m .cpu_x_n = 0 ; 5872if (cudaHostAlloc ((void ** )& m .cpu_x ,want * sizeof (float ),cudaHostAllocDefault )!= cudaSuccess ) { 5873 (void )cudaGetLastError (); 5874m .cpu_x = nullptr ; 5875cpu_share_off ("the activation buffer" ); 5876 }else { 5877m .cpu_x_n = want ; 5878 } 5879 } 5880if (cpu_maybe )cudaMemcpyAsync (m .cpu_x ,m .mixed ,want * sizeof (float ),cudaMemcpyDeviceToHost ,m .cs ); 5881 } 5882// #579: a stall here is the GPU (this layer's attention and router, or the previous layer's 5883// work), not the host: the watchdog's report says so (only its text changes) 5884 core::progress_at ("reading the prompt (batched): waiting for the GPU (attention, router) at layer" , 5885l ,p0 ); 5886cudaStreamSynchronize (m .cs ); 5887 core::progress_at ("reading the prompt (batched): layer" ,l ,p0 ); 5888if (on_routes )on_routes (l ,ids_h ,T * K );// 149-prefetch: the RAM policy's prompt seed 5889if (cpu_maybe ) {// the rows buffer, once, at its largest (an expert takes at most MAXT tokens' rows) 5890const size_t cap = (size_t ) std::min < int64_t > (T * K , (int64_t ) strata::kernels::cpu::MAXT * m .g -> n_expert )* N ; 5891if (m .cpu_rows_n < cap ) { 5892if (m .cpu_rows )cudaFreeHost (m .cpu_rows ); 5893m .cpu_rows = nullptr ; 5894m .cpu_rows_n = 0 ; 5895if (cudaHostAlloc ((void ** )& m .cpu_rows ,cap * sizeof (float ),cudaHostAllocDefault )!= cudaSuccess ) { 5896 (void )cudaGetLastError (); 5897m .cpu_rows = nullptr ; 5898cpu_share_off ("the rows buffer" ); 5899 }else { 5900m .cpu_rows_n = cap ; 5901 } 5902 } 5903 } 5904if (m .cpu_pend ) {// the measured share: the last CPU-sharing layer's GPU time is final now 5905m .cpu_pend = false; 5906float g_ms = 0 ; 5907if (cudaEventElapsedTime (& g_ms ,m .cpu_ev [0 ],m .cpu_ev [1 ])== cudaSuccess ) { 5908constexpr double a = 0.25 ; 5909const double c = m .pend_cpu_ms / (double )m .pend_n_cpu ,g = g_ms / (double )m .pend_n_gpu ; 5910m .cpu_c_ms = m .cpu_c_ms > 0 ?m .cpu_c_ms + a * (c - m .cpu_c_ms ) :c ; 5911m .cpu_g_ms = m .cpu_g_ms > 0 ?m .cpu_g_ms + a * (g - m .cpu_g_ms ) :g ; 5912m .cpu_share_now = std::clamp (m .cpu_g_ms / (m .cpu_c_ms + m .cpu_g_ms ),0.05 ,0.9 ); 5913stats_ .cpu_share_balanced = m .cpu_share_now ; 5914++ stats_ .cpu_share_readings ; 5915 } 5916 } 5917if (m .pend_wall ) {// the last eligible layer's wall, and its ratio to the one before it 5918float w_ms = 0 ; 5919if (cudaEventElapsedTime (& w_ms ,m .cpu_wall [2 * m .pend_set ],m .cpu_wall [2 * m .pend_set + 1 ])== cudaSuccess ) { 5920const double w = w_ms / (double )m .pend_wall_n ; 5921if (m .last_arm != 0 && m .last_arm != m .pend_wall && m .pend_l > m .last_l ) {// same chunk 5922 std::rotate (m .cpu_ratio ,m .cpu_ratio + 1 ,m .cpu_ratio + Impl ::CPU_RATIOS ); 5923m .cpu_ratio [Impl ::CPU_RATIOS - 1 ]= m .pend_wall == 2 ?w /m .last_w :m .last_w /w ; 5924m .cpu_nratio = std::min (m .cpu_nratio + 1 ,Impl ::CPU_RATIOS ); 5925double v [Impl ::CPU_RATIOS ]; 5926 std::copy (m .cpu_ratio + Impl ::CPU_RATIOS - m .cpu_nratio ,m .cpu_ratio + Impl ::CPU_RATIOS ,v ); 5927 std::nth_element (v ,v + m .cpu_nratio /2 ,v + m .cpu_nratio );// even: the upper one 5928m .cpu_gate = v [m .cpu_nratio /2 ]< 1.0 ; 5929 } 5930// debug: STRATA_DBG_CPU_GATE=1 prints each reading and what the next layers do 5931if (static const bool dbg = std::getenv ("STRATA_DBG_CPU_GATE" )!= nullptr ;dbg ) 5932 std::fprintf (stderr ,"cpu gate: layer %d %s, %lld non-resident, %.2f ms (%.4f a expert) -> %s\n" , 5933m .pend_l ,m .pend_wall == 2 ?"shared" :"not shared" , (long long )m .pend_wall_n , 5934w_ms ,w ,m .cpu_gate ?"share" :"do not share" ); 5935m .last_arm = m .pend_wall ; 5936m .last_l = m .pend_l ; 5937m .last_w = w ; 5938 } 5939m .pend_wall = 0 ; 5940 } 5941pt .fold (); 5942if (pe .on ) {// the peer's marks so far are done: the primary waited for its last rows 5943int pd = 0 ;cudaGetDevice (& pd );cudaSetDevice (pe .dev );cudaStreamSynchronize (m .pp -> s );pe .fold ();cudaSetDevice (pd ); 5944 } 5945if (defer_shared ) { 5946pt .mark (kPfRouter ,cs );// keep the existing router+shared timing attribution 5947if (!shared_expert ())return false; 5948pt .mark (kPfHostGroup ,cs ); 5949 } 5950 std::fill (m .cnt .begin (),m .cnt .end (),0 ); 5951for (int64_t i = 0 ;i < T * K ;++ i ) { 5952const int32_t e = ids_h [(size_t )i ]; 5953if (e < 0 || e >=m .g -> n_expert ) {err = "prefill: routed id out of range" ;return false; } 5954++ m .cnt [(size_t )e ]; 5955 } 5956// STRATA_PREFILL_ROUTED_STREAM: this layer's routing to the issuer (it drops the unrouted entries 5957// it has not issued yet; the walk below gives every unrouted entry back without reading it) 5958if (rs_on )rs_gate .publish (l ,m .cnt .data ()); 5959const bool pre_mmq = mmq_plan ().any && mmq_plan ().layer [(size_t )l ]; 5960// STRATA_PF_PEER_CPU: an expert the peer computes below (streamed to it, or held by it) is not 5961// the CPU's to take, nor one the primary would stream 5962auto peer_takes = [& ](int32_t e )-> bool { 5963if (!m .pp || !pre_mmq )return false; 5964const size_t i = (size_t )l * m .g -> n_expert + e ; 5965if (!m .pp -> ps_flag .empty ()&& m .pp -> ps_flag [i ])return true; 5966return m .pp -> peer != nullptr && m .pp -> peer -> has (l ,e ); 5967 }; 5968if (cpu_maybe ) { 5969 std::vector < std::pair < int32_t ,int32_t >> cand ;// (tokens, expert) 5970int64_t nstream = 0 ; 5971for (int32_t e = 0 ;e < m .g -> n_expert ;++ e ) { 5972const int32_t c = m .cnt [(size_t )e ]; 5973if (c == 0 || (m .host_res && m .cache && m .host_res [(size_t )l * m .g -> n_expert + e ] >=0 )) 5974continue ; 5975if (peer_takes (e ))continue ; 5976++ nstream ; 5977// a blob the CPU reads from RAM: page-locked, or any other that is not assembled into a 5978// short-lived buffer (the arena's unpinned part, the mapped experts.bin's pages) 5979if (c <= strata::kernels::cpu::MAXT && (m .src -> pinned (l ,e )|| !m .src -> transient (l ,e ))) 5980cand .emplace_back (c ,e ); 5981 } 5982 std::sort (cand .begin (),cand .end ()); 5983const double share = cpu_share_env () >=0.0 ?cpu_share_env () :cpu_arm ?m .cpu_share_now :0.0 ; 5984const size_t take = std::min (cand .size (), (size_t ) std::llround (share * (double )nstream )); 5985n_stream = nstream ; 5986// The CPU thread touches no ExpertSource (its blob() counts reads without a lock, and its 5987// calls race with this thread's own blob_stable()/pinned() ones): the pointers are taken 5988// here, and an expert without a stable blob stays on the GPU. 5989for (size_t i = 0 ;i < cand .size ()&& n_cpu < (int64_t )take ;++ i ) { 5990const int32_t e = cand [i ].second ; 5991const uint8_t * b = m .src -> blob_stable (l ,e ); 5992if (b == nullptr )continue ; 5993if (on_cpu .empty ()) { 5994on_cpu .assign ((size_t )m .g -> n_expert ,0 ); 5995cpu_blob .assign ((size_t )m .g -> n_expert ,nullptr ); 5996 } 5997on_cpu [(size_t )e ]= 1 ; 5998cpu_blob [(size_t )e ]= b ; 5999rows_cpu += cand [i ].first ; 6000++ n_cpu ; 6001 } 6002 } 6003// multi-GPU: the rows of the experts the peer computes go last, as one block [peer_at, T*K) 6004 std::vector < char > on_peer ; 6005int64_t rows_local = T * K ,rows_peer = 0 ; 6006if (m .pp && pre_mmq ) { 6007on_peer .assign ((size_t )m .g -> n_expert ,0 ); 6008for (int32_t e = 0 ;e < m .g -> n_expert ;++ e ) { 6009const int32_t c = m .cnt [(size_t )e ]; 6010if (c > 0 && !m .pp -> ps_flag .empty ()&& m .pp -> ps_flag [(size_t )l * m .g -> n_expert + e ]) {// peer-streamed 6011on_peer [(size_t )e ]= 2 ; 6012rows_peer += c ; 6013continue ; 6014 } 6015if (c == 0 || (m .host_res && m .cache && m .host_res [(size_t )l * m .g -> n_expert + e ] >=0 )|| 6016 !m .pp -> peer || !m .pp -> peer -> has (l ,e )) 6017continue ; 6018if (rows_peer + c > m .pp -> cap_rows ) {++ m .pp -> over_cap ;continue ; } 6019on_peer [(size_t )e ]= 1 ; 6020rows_peer += c ; 6021 } 6022rows_local = T * K - rows_peer ; 6023 } 6024// STRATA_PF_PEER_CPU: beside the peer the CPU's block goes before the peer's, which stays the tail 6025// (its combine takes every row from back_at on); alone, last as before 6026const bool cpu_mid = !on_peer .empty ()&& !on_cpu .empty (); 6027 { 6028int32_t r = 0 ; 6029// latent MoE: the resident experts' entries come first, so the A stage takes 6030// them as one contiguous run of grouped launches (the staged blobs' per-expert 6031// launches follow). Every table below is built from off[], so the permutation 6032// flows through coherently (tok/ids/yl/U/Dm and the combine all stay entry-major). 6033for (int pass = m .latent ?0 :1 ;pass < 2 ;++ pass ) 6034for (int32_t e = 0 ;e < m .g -> n_expert ;++ e ) { 6035if (!(on_peer .empty ()|| !on_peer [(size_t )e ])|| 6036 !(on_cpu .empty ()|| !on_cpu [(size_t )e ])) 6037continue ; 6038const bool res = m .host_res && m .cache && 6039m .host_res [(size_t )l * m .g -> n_expert + e ] >=0 ; 6040if (m .latent && pass == 0 && !res )continue ; 6041if (m .latent && pass == 1 && res )continue ; 6042m .off [(size_t )e ]= r ; 6043r += m .cnt [(size_t )e ]; 6044 } 6045for (int32_t e = 0 ;e < m .g -> n_expert && cpu_mid ;++ e )// the CPU's block, before the peer's 6046if (on_cpu [(size_t )e ]) {m .off [(size_t )e ]= r ;r += m .cnt [(size_t )e ]; } 6047// the peer's rows in order_peer's order (peer-held, then peer-streamed): its groups need them contiguous 6048for (int kind = 1 ;kind <=2 && !on_peer .empty ();++ kind ) 6049for (int32_t e = 0 ;e < m .g -> n_expert ;++ e ) 6050if (on_peer [(size_t )e ]== kind ) {m .off [(size_t )e ]= r ;r += m .cnt [(size_t )e ]; } 6051for (int32_t e = 0 ;e < m .g -> n_expert && !on_cpu .empty ()&& !cpu_mid ;++ e )// the CPU's block, last 6052if (on_cpu [(size_t )e ]) {m .off [(size_t )e ]= r ;r += m .cnt [(size_t )e ]; } 6053m .off [(size_t )m .g -> n_expert ]= r ; 6054rows_local -= rows_cpu ; 6055 } 6056cpu_at = cpu_mid ?rows_local :T * K - rows_cpu ;// the CPU's first row 6057const int64_t peer_at = cpu_mid ?rows_local + rows_cpu :rows_local ;// the peer's first row 6058 std::vector < int32_t > fill (m .off .begin (),m .off .end ()- 1 ); 6059for (int64_t i = 0 ;i < T * K ;++ i ) { 6060const int32_t e = ids_h [(size_t )i ]; 6061const int32_t p = fill [(size_t )e ]++ ; 6062slot_h [(size_t )i ]= p ; 6063src_h [(size_t )p ]= (int32_t ) (i /K ); 6064if (m .latent ) {// latent plan tables in position order (tokx: token-major index; idsx at that cell) 6065const int32_t s = (int32_t ) (i /K ),kk = (int32_t ) (i %K ); 6066m .lat_tokx_host [(size_t )p ]= s * (int32_t )K + kk ; 6067m .lat_idsx_host [(size_t ) (s * (int32_t )K + kk )]= e ; 6068m .lat_idsp_host [(size_t )p ]= e ; 6069 } 6070 } 6071// the experts, in id order: resident ones from VRAM, the others through the staging ring 6072 std::vector < int32_t > order ,order_peer ; 6073for (int32_t e = 0 ;e < m .g -> n_expert ;++ e ) 6074if (m .cnt [(size_t )e ]> 0 && (on_peer .empty ()|| on_peer [(size_t )e ]!= 2 )&& 6075 (on_cpu .empty ()|| !on_cpu [(size_t )e ])) 6076 (!on_peer .empty ()&& on_peer [(size_t )e ] ?order_peer :order ).push_back (e ); 6077for (int32_t e = 0 ;e < m .g -> n_expert && !on_peer .empty ();++ e )// the peer-streamed ones last: 6078if (on_peer [(size_t )e ]== 2 )order_peer .push_back (e );// their copies get the most time 6079// Aurora (STRATA_MMQ_RESIDENT_SORT_NE=1, opt-in): a layer whose experts are ALL resident and 6080// run through MMQ groups takes them in row-count order, so each 16-expert group's max_rows 6081// (its padded tile rows) is close to its experts' own; slot/src/off are rebuilt coherently 6082// before the upload, the routed ids, weights and the within-expert row order stay as they are. 6083// STRATA_MMQ_GROUP_SORT=1 (opt-in, exact): the same order for the full groups only, where each 6084// tile is one block's whole K (MmqPlan::group_sort); the partial group keeps its ID order and bits. 6085// STRATA_MMQ_RESIDENT_SORT_NE=1 takes precedence (it sorts the partial group too). 6086const bool sort_all = m .latent ? false : detail::mmq_resident_sort_requested (); 6087const bool sort_full = !sort_all && !m .latent && use_mmq && mmq_plan ().group_sort [(size_t )l ]&& 6088order .size () >= (size_t )MMQ_GROUP ; 6089if (detail::mmq_resident_sort_eligible ((sort_all || sort_full )&& on_peer .empty (),use_mmq ,lay .native , 6090m .cache != nullptr ,m .host_res ?m .host_res + (size_t )l * m .g -> n_expert :nullptr , 6091m .g -> n_expert ,stream_all , !stream_all || seq_start [(size_t )l ]== seq_start [(size_t )l + 1 ])) 6092 detail::mmq_resident_sort_rows (ids_h ,T * K , (int32_t )K ,m .cnt ,m .off ,order ,slot_h ,src_h , 6093 detail::mmq_resident_sort_span (order .size (),MMQ_GROUP ,sort_full )); 6094if (grp_mapped ) { 6095copy_i32 (m .slot_dev ,m .grp_dev + m .grp_tk ,T * K ,m .cs ); 6096copy_i32 (m .src_dev ,m .grp_dev + 2 * m .grp_tk ,T * K ,m .cs ); 6097 }else { 6098if (m .up_ring .h2d (m .slot_dev ,m .slot_host .data (), (size_t )T * K * 4 ,m .cs )!= cudaSuccess || // #1996 6099m .up_ring .h2d (m .src_dev ,m .src_host .data (), (size_t )T * K * 4 ,m .cs )!= cudaSuccess ) { 6100err = "prefill: the routing tables' upload failed" ; 6101return false; 6102 } 6103 } 6104// Diagnostics: STRATA_DUMP_MOE_INPUT=path, STRATA_DUMP_MOE_LAYER=l - the first chunk's MoE input 6105// of layer l ({T, N, K} int64, T x N floats, T x K expert ids) for testing products on real rows 6106static const char * dump_moe = std::getenv ("STRATA_DUMP_MOE_INPUT" ); 6107static bool dumped_moe = false; 6108// STRATA_DUMP_MOE_LAYER=all (research): every layer of the process's first chunk, layer l into <path>.L<l> (the layers come in order; the second chunk and later 6109// requests are not dumped) 6110static const bool dump_all = [] {const char * e = std::getenv ("STRATA_DUMP_MOE_LAYER" );return e != nullptr && std::strcmp (e ,"all" )== 0 ; }(); 6111static int dump_next = 0 ; 6112const bool dump_this = dump_moe != nullptr && (dump_all ?l == dump_next 6113 : (!dumped_moe && l == std::atoi (std::getenv ("STRATA_DUMP_MOE_LAYER" ) ? std::getenv ("STRATA_DUMP_MOE_LAYER" ) :"0" ))); 6114if (dump_this ) { 6115dumped_moe = true; 6116if (dump_all )++ dump_next ; 6117 std::vector < float > x ((size_t ) (T * N )); 6118cudaMemcpyAsync (x .data (),m .mixed ,x .size ()* sizeof (float ),cudaMemcpyDeviceToHost ,m .cs ); 6119cudaStreamSynchronize (m .cs ); 6120const std::string dump_path = dump_all ? std::string (dump_moe )+ ".L" + std::to_string (l ) : std::string (dump_moe ); 6121if (std::FILE * f = std::fopen (dump_path .c_str (),"wb" )) { 6122const int64_t hdr [3 ]= {(int64_t )T , (int64_t )N , (int64_t )K }; 6123 std::fwrite (hdr ,sizeof hdr ,1 ,f ); 6124 std::fwrite (x .data (),sizeof (float ),x .size (),f ); 6125 std::fwrite (ids_h ,sizeof (int32_t ), (size_t ) (T * K ),f ); 6126 std::fclose (f ); 6127 } 6128 } 6129n_order = order .size (); 6130// set_cpu_pool: the CPU's experts on a thread while this one streams and runs the GPU's; their 6131// unweighted rows land in Dm's row order, so the combine weights them as any other row 6132if (rows_cpu > 0 ) { 6133const size_t want = (size_t )rows_cpu * N ; 6134if (m .cpu_rows_n < want ) { 6135cpu_cold = true; 6136if (m .cpu_rows )cudaFreeHost (m .cpu_rows ); 6137m .cpu_rows = nullptr ; 6138m .cpu_rows_n = 0 ; 6139const size_t cap_rows = (size_t )rows_cpu * 2 ;// headroom: few reallocations 6140if (cudaHostAlloc ((void ** )& m .cpu_rows ,cap_rows * N * sizeof (float ),cudaHostAllocDefault )!= cudaSuccess ) { 6141err = "prefill: cannot allocate the CPU experts' rows" ; 6142return false; 6143 } 6144m .cpu_rows_n = cap_rows * N ; 6145 } 6146// this fork (NVFP4): row_sd 1 for the CPU's rows, which carry s_down already - sized on its 6147// own, as the rows buffer is now taken once at its largest above (0.1.42) 6148if (m .cpu_ones_n < (size_t )rows_cpu ) { 6149if (m .cpu_ones )cudaFreeHost (m .cpu_ones ); 6150m .cpu_ones = nullptr ; 6151m .cpu_ones_n = 0 ; 6152const size_t n1 = std::max < size_t > ((size_t )rows_cpu * 2 ,m .cpu_rows_n /N ); 6153if (cudaHostAlloc ((void ** )& m .cpu_ones ,n1 * sizeof (float ),cudaHostAllocDefault )!= cudaSuccess ) { 6154err = "prefill: cannot allocate the CPU experts' row scales" ; 6155return false; 6156 } 6157 std::fill (m .cpu_ones ,m .cpu_ones + n1 ,1.0f ); 6158m .cpu_ones_n = n1 ; 6159 } 6160const int64_t r0c = cpu_at ; 6161const strata::kernels::cpu::NativeFmt & cf = lay .fmt [(size_t )l ]; 6162if (cpu_share_env ()< 0.0 ) { 6163if (m .cpu_ev [0 ]== nullptr ) {cudaEventCreate (& m .cpu_ev [0 ]);cudaEventCreate (& m .cpu_ev [1 ]); } 6164cudaEventRecord (m .cpu_ev [0 ],m .cs ); 6165 } 6166cpu_fut = std::async (std::launch::async , [& m ,& on_cpu ,& cpu_blob ,& cf ,& cpu_ms ,src_h ,l ,T ,r0c ,this ]()-> bool { 6167const auto t0 = std::chrono::steady_clock::now (); 6168constexpr size_t AB = strata::kernels::cpu::kNativeActBytes ; 6169// a Q2_0 layer (gate/up on the pool's Q2_0 kernels): ActQ activations, as decode's 6170const bool q2 = strata::kernels::cpu::q2_native_kernels (cf .gu_type ); 6171if (q2 && m .cpu_actq .size ()< (size_t )T )m .cpu_actq .resize ((size_t )T ); 6172if (!q2 && m .cpu_nact .size ()< (size_t )T * AB )m .cpu_nact .resize ((size_t )T * AB ); 6173 std::vector < char > need ((size_t )T ,0 ); 6174for (int32_t e = 0 ;e < m .g -> n_expert ;++ e )// the tokens the CPU's experts read 6175if (on_cpu [(size_t )e ]) 6176for (int32_t r = 0 ;r < m .cnt [(size_t )e ];++ r ) 6177need [(size_t )src_h [(size_t )m .off [(size_t )e ]+ (size_t )r ]]= 1 ; 6178for (int64_t t = 0 ;t < T ;++ t ) 6179if (need [(size_t )t ]&& q2 ) 6180 strata::kernels::cpu::act_quant_any (m .cpu_x + (size_t )t * N , (int )N ,m .cpu_actq [(size_t )t ]); 6181else if (need [(size_t )t ]) 6182 strata::kernels::cpu::native_quant_act (cf ,m .cpu_x + (size_t )t * N , 6183m .cpu_nact .data ()+ (size_t )t * AB ); 6184m .cpu_jobs .clear (); 6185for (int32_t e = 0 ;e < m .g -> n_expert ;++ e ) { 6186if (!on_cpu [(size_t )e ])continue ; 6187 strata::kernels::cpu::ExpertJobMulti j ; 6188j .blob = cpu_blob [(size_t )e ]; 6189j .nt = m .cnt [(size_t )e ]; 6190for (int r = 0 ;r < j .nt ;++ r ) { 6191const int64_t p = (int64_t )m .off [(size_t )e ]+ r ; 6192if (q2 )j .act [r ]= & m .cpu_actq [(size_t )src_h [(size_t )p ]]; 6193else j .nact [r ]= m .cpu_nact .data ()+ (size_t )src_h [(size_t )p ]* AB ; 6194j .out [r ]= m .cpu_rows + (size_t ) (p - r0c )* N ; 6195 } 6196m .cpu_jobs .push_back (j ); 6197 } 6198cpu_pool_ -> run_split_multi_native (cf ,m .cpu_jobs .data (), (int )m .cpu_jobs .size ()); 6199cpu_ms = std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t0 ).count (); 6200return true; 6201 }); 6202 } 6203if (m .latent ) {// latent MoE: D once per layer, A/U in expert-major batches (position-ordered Dm) 6204// STRATA_PREFILL_GROUP_GATHER=0: one gather, one wait and one record per expert. 6205static const bool group_env = [] { 6206const char * v = std::getenv ("STRATA_PREFILL_GROUP_GATHER" ); 6207return v == nullptr || std::atoi (v )!= 0 ; 6208 }(); 6209// (LAT_GROUP > kGatherGroupMax: the latent walk gathers per expert, as on the fork) 6210const bool group_gather = group_env && stream_all && lay .native && (use_mmq && LAT_GROUP <= mmq::kGatherGroupMax ); 6211// The staged walk (a short prompt) groups too, resident and staged experts alike: its ring is 6212// then STAGE_GRP slots, two groups, and it stages no further ahead than the open group allows, 6213// so a group's staged slots stay unread-over until its flush (one wait on the last copy, one 6214// event releasing them all, as in the streamed walk). 6215const bool group_resident = group_env && !stream_all && lay .native && (use_mmq && LAT_GROUP <= mmq::kGatherGroupMax ); 6216const bool gg_now = group_gather || group_resident ; 6217const int stage_n = group_resident ?STAGE_GRP :STAGE ; 6218// Stage ahead: the copy stream moves blobs host -> device while the compute stream works. 6219int stage_next = 0 ; 6220 std::vector < int > stage_of (order .size (),-1 ); 6221// the unpinned ones are copied to pinned buffers by the stager's threads, in this order 6222 std::vector < int > job_of (order .size (),-1 ); 6223if (!stream_all ) { 6224 std::vector < Stager ::Job > js ; 6225for (size_t j = 0 ;j < order .size ();++ j ) { 6226const int32_t e = order [j ]; 6227if (m .host_res && m .cache && m .host_res [(size_t )l * m .g -> n_expert + e ] >=0 )continue ; 6228if (m .src -> pinned (l ,e ))continue ; 6229job_of [j ]= (int )js .size (); 6230if (m .src -> transient (l ,e )) {// CS-T: copied by the source 6231js .push_back ({nullptr , (size_t )lay .blob_bytes (l ),m .src , (int32_t )l ,e }); 6232continue ; 6233 } 6234const uint8_t * b = m .src -> blob_stable (l ,e ); 6235if (!b ) {err = "prefill: expert source has no blob" ;return false; } 6236js .push_back ({b , (size_t )lay .blob_bytes (l )}); 6237 } 6238if (m .warmer ) { 6239 std::vector < int64_t > cur ; 6240for (size_t j = 0 ;j < order .size ();++ j ) 6241if (job_of [j ] >=0 )cur .push_back (order [j ]); 6242m .warm_prev [(size_t )l ]= cur ; 6243m .warmer -> submit (l , std::move (cur )); 6244if (l + 1 < m .g -> n_layers ) { 6245 std::vector < int64_t > nxt ; 6246for (int64_t e :m .warm_prev [(size_t ) (l + 1 )]) { 6247if (m .host_res && m .cache && m .host_res [(size_t ) (l + 1 )* m .g -> n_expert + e ] >=0 ) 6248continue ; 6249if (m .src -> pinned (l + 1 , (int32_t )e ))continue ; 6250nxt .push_back (e ); 6251 } 6252m .warmer -> submit (l + 1 , std::move (nxt )); 6253 } 6254 } 6255m .stager -> start (std::move (js )); 6256 } 6257StagerDone stager_done {stream_all ?nullptr :m .stager .get ()}; 6258auto stage_one = [& ](size_t j )-> bool { 6259const int32_t e = order [j ]; 6260const bool resident = m .host_res && m .cache && m .host_res [(size_t )l * m .g -> n_expert + e ] >=0 ; 6261if (resident )return true; 6262const int sl = stage_next ; 6263stage_next = (stage_next + 1 ) %stage_n ; 6264const auto th = Clock ::now (); 6265const bool pinned = m .src -> pinned (l ,e );// pinned: never transient 6266const uint8_t * b = pinned ?m .src -> blob_stable (l ,e ) :nullptr ; 6267if (pinned && !b ) {err = "prefill: expert source has no blob" ;return false; } 6268if (pinned ) { 6269// DMA straight from the page-locked arena: the copy stream only waits for the slot 6270if (m .stage_live [sl ])cudaStreamWaitEvent (m .copy ,m .used [m .used_of [sl ]],0 ); 6271cudaMemcpyAsync (m .stage_dev [sl ],b , (size_t )lay .blob_bytes (l ),cudaMemcpyHostToDevice ,m .copy ); 6272++ stats_ .experts_dma ; 6273 }else { 6274// copied to a pinned buffer by the stager (waits only if it is behind), then DMA 6275const uint8_t * hb = m .stager -> wait (job_of [j ]); 6276if (m .stage_live [sl ])cudaStreamWaitEvent (m .copy ,m .used [m .used_of [sl ]],0 ); 6277cudaMemcpyAsync (m .stage_dev [sl ],hb , (size_t )lay .blob_bytes (l ),cudaMemcpyHostToDevice ,m .copy ); 6278m .stager -> issued_one (job_of [j ],m .copy ); 6279 } 6280cudaEventRecord (m .copied [sl ],m .copy ); 6281m .stage_live [sl ]= true; 6282stage_of [j ]= sl ; 6283stats_ .ms_experts_host += ms_since (th ); 6284++ stats_ .experts_streamed ; 6285return true; 6286 }; 6287const auto & f = lay .fmt [(size_t )l ]; 6288const int64_t ELL = m .lat_ELL ,G = m .lat_G ; 6289if (!m .cache || !m .host_res ) { 6290err = "prefill latent: the expert cache is required (--expert-cache)" ; 6291return false; 6292 } 6293if (m .up_ring .h2d (m .tok ,m .lat_tokx_host .data (), (size_t )T * K * 4 ,m .cs )!= cudaSuccess || 6294m .up_ring .h2d (m .tok_ix ,m .lat_idsx_host .data (), (size_t )T * K * 4 ,m .cs )!= cudaSuccess || 6295m .up_ring .h2d (m .ids_p ,m .lat_idsp_host .data (), (size_t )T * K * 4 ,m .cs )!= cudaSuccess ) { 6296err = "prefill latent: the plan tables' upload failed" ; 6297return false; 6298 } 6299 {int32_t duo [2 ]= {0 , (int32_t ) (T * K )};m .up_ring .h2d (m .lat_n ,duo ,8 ,m .cs ); } 6300// STRATA_LATENT_FUSED_DU (on by default, =0 the iq_mmvq/latent_u_grouped path): the D 6301// and U dense projections on moe_fused.cu's fused dense kernels - the Q8_0 weights on 6302// the int8 tensor cores, the D stage's products quantized straight to the xl rows' 6303// own q8_1 blocks (the FP32 xl round trip never runs). 6304static const bool lat_du_env = [] { 6305const char * v = std::getenv ("STRATA_LATENT_FUSED_DU" ); 6306return v == nullptr || v [0 ]!= '0' ; 6307 }(); 6308const bool lat_du = lat_du_env && fused::latent_fused_available (); 6309// D: each token's 8 group products [T, G*ELL] -> q8_1 rows (xlq) 6310pt .mark (kPfGather ,m .cs ); 6311 strata::kernels::quantize_q8_1_rows (m .mixed ,T , (int )N ,m .lat_xq ,m .cs ); 6312if (lat_du ) { 6313// a colscaled pack (the Q3_K one: scales/l{l}.f32 beside its manifest) needs the 6314// DU kernel that folds 1/s into the xl columns; v5's pack has no scales and keeps 6315// the original kernel (its signature and its bits are untouched) 6316const float * lat_inv = strata::kernels::lat_gu_colscale_dev ((int )l , (int )ELL ); 6317if (lat_inv ) 6318 fused_q3k::latent_dense_d (m .lat_d_dev + (size_t ) (l - m .lat_first_layer )* m .lat_d .d_bytes (),m .lat_xq ,T , 6319 (int )N , (int )G ,ELL ,m .xlq ,m .cs ,m .lat_fmt ,lat_inv ); 6320else 6321 fused::latent_dense_d (m .lat_d_dev + (size_t ) (l - m .lat_first_layer )* m .lat_d .d_bytes (),m .lat_xq ,T , 6322 (int )N , (int )G ,ELL ,m .xlq ,m .cs ,m .lat_fmt ); 6323 }else { 6324 strata::kernels::iq_mmvq (strata::kernels::lat_dense_fmt_to_type (m .lat_fmt ), 6325m .lat_d_dev + (size_t ) (l - m .lat_first_layer )* m .lat_d .d_bytes (),m .lat_xq ,m .xl , (int )N , 6326 (int ) (G * ELL ),T ,m .cs );// Q4DU: fmt->ggml type (8 Q8_0 / 2 Q4_0) 6327// Q3_K shared column scales: as in verify.cpp, scale the D stage's x by 1/s once, 6328// before the quantize below (the prefill's only consumer of the f32 m.xl rows). 6329if (const float * inv = strata::kernels::lat_gu_colscale_dev ((int )l , (int )ELL )) 6330 strata::kernels::lat_colscale_rows (m .xl , (int64_t )T * G , (int )ELL ,inv ,m .cs ); 6331 strata::kernels::quantize_q8_1_rows (m .xl , (int64_t )T * G , (int )ELL ,m .xlq ,m .cs ); 6332 } 6333 {// STRATA_LAT_MOE_DUMP (debug): the latent arm's intermediates, layer 0 6334static const char * lat_moe_dump = std::getenv ("STRATA_LAT_MOE_DUMP" ); 6335if (lat_moe_dump && l == 0 ) { 6336 std::vector < uint8_t > hb ; 6337auto lat_wr = [& ](const char * name ,const void * dev ,size_t bytes ) { 6338hb .resize (bytes ); 6339if (cudaMemcpyAsync (hb .data (),dev ,bytes ,cudaMemcpyDeviceToHost ,m .cs )!= cudaSuccess || 6340cudaStreamSynchronize (m .cs )!= cudaSuccess ) { 6341err = std::string ("lat moe dump: the copy of " )+ name + " failed" ;return false; 6342 } 6343char p [512 ]; std::snprintf (p ,sizeof p ,"%s/%s" ,lat_moe_dump ,name ); 6344 std::FILE * fp = std::fopen (p ,"wb" ); 6345if (fp == nullptr ) {err = std::string ("lat moe dump: cannot write " )+ p ;return false; } 6346 std::fwrite (hb .data (),1 ,bytes ,fp ); std::fclose (fp );return true; 6347 }; 6348const size_t xrowb = (size_t ) (ELL /32 )* 36 ; 6349if (!lat_wr ("d-xlq.bin" ,m .xlq , (size_t )T * G * xrowb ))return false; 6350 } 6351 } 6352 {// STRATA_LAT_MOE_DUMP (debug): the fused kernels' exact inputs, layer 0 6353static const char * lat_moe_dump4 = std::getenv ("STRATA_LAT_MOE_DUMP" ); 6354if (lat_moe_dump4 && l == 0 ) { 6355const int32_t E = (int32_t )m .g -> n_expert ; 6356 {// m.cnt / m.off (host) 6357char p [512 ]; std::snprintf (p ,sizeof p ,"%s/g-cnt.bin" ,lat_moe_dump4 ); 6358 std::FILE * fp = std::fopen (p ,"wb" ); 6359if (fp ) { std::fwrite (m .cnt .data (),4 , (size_t )E ,fp ); std::fclose (fp ); } 6360 std::snprintf (p ,sizeof p ,"%s/g-off.bin" ,lat_moe_dump4 ); 6361fp = std::fopen (p ,"wb" ); 6362if (fp ) { std::fwrite (m .off .data (),4 , (size_t )E + 1 ,fp ); std::fclose (fp ); } 6363 } 6364auto lat_dwr = [& ](const char * name ,const void * dev ,size_t bytes ) { 6365 std::vector < uint8_t > hb (bytes ); 6366if (cudaMemcpyAsync (hb .data (),dev ,bytes ,cudaMemcpyDeviceToHost ,m .cs )!= cudaSuccess || 6367cudaStreamSynchronize (m .cs )!= cudaSuccess )return false; 6368char p [512 ]; std::snprintf (p ,sizeof p ,"%s/%s" ,lat_moe_dump4 ,name ); 6369 std::FILE * fp = std::fopen (p ,"wb" ); 6370if (fp == nullptr )return false; 6371 std::fwrite (hb .data (),1 ,bytes ,fp ); std::fclose (fp );return true; 6372 }; 6373const size_t npitch = (size_t ) (N /32 )* 36 ; 6374if (!lat_dwr ("i-xq.bin" ,m .lat_xq , (size_t )T * npitch ))return false; 6375 } 6376 } 6377 strata::kernels::latent_plan_rows (m .tok ,m .tok ,m .lat_n ,m .tok_ix , 6378m .lat_labels_dev + (size_t )l * m .lat_E ,m .lat_E ,0 , (int )G , (int )K ,m .cs ); 6379 {// STRATA_LAT_MOE_DUMP (debug): the plan tables after rewrite, layer 0 6380static const char * lat_moe_dump5 = std::getenv ("STRATA_LAT_MOE_DUMP" ); 6381if (lat_moe_dump5 && l == 0 ) { 6382auto lat_dwr = [& ](const char * name ,const void * dev ,size_t bytes ) { 6383 std::vector < uint8_t > hb (bytes ); 6384if (cudaMemcpyAsync (hb .data (),dev ,bytes ,cudaMemcpyDeviceToHost ,m .cs )!= cudaSuccess || 6385cudaStreamSynchronize (m .cs )!= cudaSuccess )return false; 6386char p [512 ]; std::snprintf (p ,sizeof p ,"%s/%s" ,lat_moe_dump5 ,name ); 6387 std::FILE * fp = std::fopen (p ,"wb" ); 6388if (fp == nullptr )return false; 6389 std::fwrite (hb .data (),1 ,bytes ,fp ); std::fclose (fp );return true; 6390 }; 6391if (!lat_dwr ("g-tok.bin" ,m .tok , (size_t )T * K * 4 ))return false; 6392if (!lat_dwr ("g-ids.bin" ,m .ids_p , (size_t )T * K * 4 ))return false; 6393 } 6394 } 6395// A: batches of busy experts in id order; a streamed blob waits on its ring slot 6396// STRATA_EXPERT_NIBBLE: a nibble layer's cache slots hold 4-bit gate/up codes, which only 6397// the nib layout reads (verify: L = nibble::layer(l).on ? layout_nib : layout, for the VRAM 6398// share); a staged / PCIe blob is always the plain GGUF bytes. 6399const bool nib_l = 6400#if STRATA_EXPERT_NIBBLE_BUILT 6401 strata::core::nibble::layer (l ).on ; 6402#else 6403 false; 6404#endif 6405auto la_for = [& ](bool nib ) { 6406#if STRATA_EXPERT_NIBBLE_BUILT 6407return nib ? strata::kernels::native_expert_layout_nib (f .gu_type ,f .d_type , (int )ELL , 6408 (int )m .lat_I ) 6409 : strata::kernels::native_expert_layout (f .gu_type ,f .d_type , (int )ELL , 6410 (int )m .lat_I ); 6411#else 6412 (void )nib ; 6413return strata::kernels::native_expert_layout (f .gu_type ,f .d_type , (int )ELL , (int )m .lat_I ); 6414#endif 6415 }; 6416// STRATA_LATENT_FUSED (on by default, =0 the native grouped kernel): the A stage on 6417// moe_fused.cu's fused batch kernels - the plain-GGUF NVFP4 blobs where they are 6418// (resident slot or staged ring slot), the layer's whole grouping as its tables 6419// (fused::LatentGeom / group_latent / experts_latent in moe_fused.hpp) 6420static const bool lat_fused_env = [] { 6421const char * v = std::getenv ("STRATA_LATENT_FUSED" ); 6422return v == nullptr || v [0 ]!= '0' ; 6423 }(); 6424static const bool lat_log = [] { 6425const char * v = std::getenv ("STRATA_LATENT_FUSED_LOG" ); 6426return v != nullptr && v [0 ]== '1' ; 6427 }(); 6428const bool lat_fused = 6429lat_fused_env && !nib_l && fused::latent_fused_available ()&& 6430 ((f .gu_type == 40 && f .d_type == 40 )|| 6431 (lat_fused_q3k_on ()&& f .gu_type == 11 && f .d_type == 20 && m .lat_I == 640 )); 6432 fused::LatentGeom lat_lg {}; 6433size_t lat_h = 0 ; 6434if (lat_fused ) { 6435const strata::kernels::NativeExpertLayout & lp = la_for (false); 6436const int64_t nent = (int64_t ) (T * K ); 6437const int lne = (int )m .g -> n_expert ; 6438lat_lg .ell = (int64_t )ELL ; 6439lat_lg .iff = (int64_t )m .lat_I ; 6440lat_lg .gu_row = lp .gu_row ; 6441lat_lg .d_row = lp .d_row ; 6442lat_lg .up_off = lp .up_off ; 6443lat_lg .down_off = lp .down_off ; 6444lat_lg .tail_off = lp .tail_off ; 6445lat_h = fused::latent_h_off (nent ,lne ); 6446if (strata::kernels::native_expert_scratch_bytes (nent , (int64_t )m .lat_I )< 6447 fused::latent_scratch_bytes (nent ,lne , (int64_t )m .lat_I )) { 6448err = "prefill latent: the fused A stage does not fit the grouped kernel's scratch" ; 6449return false; 6450 } 6451 std::vector < char > lt (fused::latent_group_bytes (nent ,lne )); 6452 fused::group_latent (m .cnt .data (),m .off .data (),lne ,lt .data (),lt .size ()); 6453if (m .up_ring .h2d (m .lat_scratch ,lt .data (),lt .size (),m .cs )!= cudaSuccess ) { 6454err = "prefill latent: the fused tables' upload failed" ; 6455return false; 6456 } 6457 } 6458// STRATA_LATENT_MMQ=1: the A stage on llama.cpp's int8 MMQ. xlq is (token,group)- 6459// ordered and MMQ reads entry-ordered rows, so this layer builds the entry -> xl row 6460// table once (m.tok, T*K entries); each launch then quantizes just its own rows from 6461// it. Off by default: the native_expert_grouped path below stays the default. 6462static const bool lat_mmq_env = [] { 6463const char * v = std::getenv ("STRATA_LATENT_MMQ" ); 6464return v != nullptr && v [0 ]== '1' ; 6465 }(); 6466const bool lat_mmq = lat_mmq_env && m .mmq_ctx != nullptr && m .Xq != nullptr && 6467m .H != nullptr && m .Hq != nullptr && m .grp_gu != nullptr && 6468m .grp_d != nullptr && m .bounds_dev != nullptr && !nib_l ; 6469// M4: STRATA_LAT_FUSED_Q3K=1 - the q3k pack only (Q3_K gate/up, IQ4_NL down, the 1280 / 6470// 640 latent geometry), and it takes the launches in place of both other paths. 6471const bool lat_fused_q3k = lat_fused_q3k_on ()&& f .gu_type == 11 /* GGML_TYPE_Q3_K */ && 6472f .d_type == 20 /* GGML_TYPE_IQ4_NL */ && ELL == 1280 && m .lat_I == 640 && 6473m .lat_hbuf != nullptr && m .lat_gcd != nullptr && !nib_l ; 6474if (lat_fused_q3k && !nib_l ) { 6475static bool noted = false; 6476if (!noted ) { 6477noted = true; 6478 std::fprintf (stderr , 6479"latfusedq3k: the A stage runs lat_q3k_fused (experts read in " 6480"place, gather_native skipped), hbuf %lld B, T*K %lld entries\n" , 6481 (long long ) ((size_t )T * K * 800 ), (long long ) (T * K )); 6482 } 6483 } 6484 std::vector < int32_t > lat_rows ;// STRATA_LATENT_MMQ: entry -> xl row, this layer 6485 strata::prefill::lat::Tables lat_tab ;// its per-layer row tables (built below) 6486// One WAIT covers a whole copy batch, which can be many MMQ groups deep: the fused walk waits 6487// once per ring/3 experts, and 16 is far too shallow to keep the copy engine fed. The MMQ 6488// products still take 16 experts a launch (kGatherGroupMax), sliced out of the batch. 6489constexpr size_t kLatBatch = 8 * LAT_GROUP ; 6490// Measured: a copy batch deeper than one product group (ring/3 = 128) was 6 % SLOWER at 4K 6491// (712.3 vs 757.5) and 1.4 % at 16K - the flushes are host-cheap (0.43 ms each, profiled), 6492// so there was nothing for a deeper batch to hide. One group per batch: the fused walk's 6493// depth is for its one-launch-per-128 kernels, which the MMQ products cannot use. 6494const size_t lat_batch = (size_t )LAT_GROUP ; 6495if (lat_mmq ) { 6496if (l == 0 && std::getenv ("STRATA_LATENT_MMQ_DEBUG" )!= nullptr ) { 6497int32_t mx = 0 ,mn = (int32_t )2147483647 ; 6498for (int32_t v :m .lat_tokx_host ) {mx = std::max (mx ,v );mn = std::min (mn ,v ); } 6499 std::fprintf (stderr ,"latmmq-dbg: T=%lld K=%d G=%lld ELL=%lld TG=%lld TK=%lld " 6500"tok[min,max]=[%d,%d] nb_experts=%lld\n" , (long long )T , (int )K , 6501 (long long )G , (long long )ELL , (long long ) (T * G ), (long long ) (T * K ), 6502 (int )mn , (int )mx , (long long )m .g -> n_expert ); 6503 } 6504// xlq's rows are (token, group): xl row = src*G + labels[l*E + expert], NOT the 6505// default path's m.tok (src*K + kk, which reads past T*G rows whenever K > G). 6506// m.tok is rebuilt for this branch only; the default path below is not taken. 6507lat_rows .assign ((size_t ) (T * K ),0 ); 6508for (size_t p2 = 0 ;p2 < lat_rows .size ();++ p2 ) { 6509const int32_t s2 = m .lat_tokx_host [p2 ] / (int32_t )K ; 6510const int32_t e2 = m .lat_idsp_host [p2 ]; 6511const size_t li = (size_t )l * (size_t )m .lat_E + (size_t )e2 ; 6512lat_rows [p2 ]= s2 * (int32_t )G + 6513 (li < m .lat_labels .size () ?m .lat_labels [li ] :0 ); 6514 } 6515// The layer's two row tables, in the walk's order: a group is one contiguous run of them, 6516// so a flush uploads only its bounds and shifts the two pointers by its base - instead of 6517// rebuilding both tables on the host and uploading them at every group. 6518lat_tab = strata::prefill::lat::build (order ,m .off .data (),m .cnt .data (),lat_rows ); 6519if (lat_tab .rows > 0 && 6520 (m .up_ring .h2d (m .lat_gxl ,lat_tab .xl .data (), (size_t )lat_tab .rows * 4 ,m .cs )!= 6521cudaSuccess || 6522m .up_ring .h2d (m .lat_gdst ,lat_tab .entry .data (), (size_t )lat_tab .rows * 4 , 6523m .cs )!= cudaSuccess )) { 6524err = "prefill latent: the layer's row tables' upload failed" ; 6525return false; 6526 } 6527 } 6528// STRATA_LATENT_MMQ: the A stage's gathers are collected up to LAT_GROUP experts and run as 6529// one gate/up + SwiGLU + down set. A 4K prompt's experts average ~80 rows, so a per-expert 6530// Product was ~100 us of launch for ~0.1 GFLOP: 24.6k launches, `gemm down` alone 40 % of 6531// the chunk's GPU time. The rows also have to be one contiguous entry range (the row table 6532// slice and the relative bounds both assume it), so a group flushes early when it is not. 6533const size_t lat_gub = mmq::matrix_bytes (f .gu_type ,1280 , (int64_t )ELL ); 6534const size_t lat_db = mmq::matrix_bytes (f .d_type , (int64_t )ELL ,640 ); 6535size_t lat_q = 0 ,lat_nflush = 0 ,lat_nexp = 0 ,lat_maxq = 0 ; 6536static const size_t lat_gmax = std::getenv ("STRATA_LATENT_MMQ_G1" )!= nullptr 6537 ?1 6538 : (std::getenv ("STRATA_LATENT_MMQ_G" )!= nullptr 6539 ? (size_t ) std::atoi (std::getenv ("STRATA_LATENT_MMQ_G" )) 6540 : (size_t )LAT_GROUP );// A/B: the group's expert count 6541// The MMQ buffers hold stream_all_min() - 1 tokens' rows (moe_bufs), so a pending group is capped 6542// by ROWS, not by expert count: sixteen experts can carry more rows than that (a 4K chunk's top 6543// sixteen held far more than the 10.2k-row cap), and a group over the cap ran the gate/up product 6544// past m.GU into the next buffer - the illegal memory access the trace named at the gu launch. 6545const int64_t lat_rowcap = std::min < int64_t > (T ,stream_all_min ()- 1 )* (int64_t )K ; 6546int64_t lat_nr = 0 ; 6547int64_t lat_base = 0 ;// the layer tables' first row of the group being filled 6548int32_t lat_gq [LAT_GROUP ],lat_ge [LAT_GROUP ]; 6549int32_t lat_gc [kLatBatch ];// per batch entry: its row COUNT (-1: take gs's difference) 6550int32_t lat_cnt [LAT_GROUP ];// the GROUP's counts, in z - the walk's batch position is a 6551// different index once a cap flush resets z mid-batch 6552for (int32_t & v :lat_gc )v = -1 ; 6553auto arm_flush = [& ]()-> bool { 6554if (!lat_mmq || lat_q == 0 )return true; 6555const size_t nb2 = lat_q ; 6556lat_q = 0 ; 6557// lat flush breakdown: host time per step of one flush, summed over the chunk 6558auto now2 = [] {return std::chrono::steady_clock::now (); }; 6559auto ms2 = [](auto x ,auto y ) { 6560return std::chrono::duration < double , std::milli > (y - x ).count (); 6561 }; 6562static double P [6 ]= {0 ,0 ,0 ,0 ,0 ,0 }; 6563const auto T0 = now2 (); 6564auto tr = [& ](const char * tag )-> bool { 6565static const bool on = std::getenv ("STRATA_LATENT_MMQ_TRACE" )!= nullptr ; 6566if (!on )return true; 6567const cudaError_t e = cudaStreamSynchronize (m .cs ); 6568if (e != cudaSuccess || cudaGetLastError ()!= cudaSuccess ) { 6569 std::fprintf (stderr ,"latmmq-trace FAIL %s l=%d nb2=%zu: %s\n" ,tag , (int )l , 6570nb2 ,cudaGetErrorString (cudaGetLastError ())); 6571return false; 6572 } 6573 std::fprintf (stderr ,"latmmq-trace ok %s l=%d nb2=%zu\n" ,tag , (int )l ,nb2 ); 6574return true; 6575 }; 6576++ lat_nflush ;lat_nexp += nb2 ;lat_maxq = std::max (lat_maxq ,nb2 ); 6577// The buffers hold this group's rows as an expert-major concatenation, 0..nr-1, so a 6578// group never needs a contiguous entry range: off[] is NOT monotonic in expert id (the 6579// resident block is laid out first), and requiring it let a group average 2.6 experts 6580// instead of LAT_GROUP - which kept the products in stream-k + fixup mode. 6581// This group's rows are the layer tables' run [lat_base, lat_base + nr), so only its 6582// bounds are per group here. lat_gc carries the count where the walk knows it; the 6583// per-expert and resident walks leave it -1, and there gs's difference is the count. 6584 std::vector < int32_t > bh ((size_t ) (nb2 + 1 )); 6585int32_t at = 0 ; 6586bh [0 ]= 0 ; 6587for (size_t q = 0 ;q < nb2 ;++ q ) { 6588at += lat_cnt [q ]; 6589bh [q + 1 ]= at ; 6590 } 6591const int64_t nr = (int64_t )at ; 6592if (lat_base + nr > lat_tab .rows ) { 6593 std::fprintf (stderr , 6594"prefill latent: the group's rows [%lld, %lld) pass the layer's %lld " 6595"(lat_q=%zu nb2=%zu)\n" , (long long )lat_base , 6596 (long long ) (lat_base + nr ), (long long )lat_tab .rows ,lat_q ,nb2 ); 6597for (size_t q = 0 ;q < nb2 ;++ q ) 6598 std::fprintf (stderr ," g[%zu] base=%d end=%d cnt=%d\n" ,q ,lat_gq [q ], 6599lat_ge [q ],lat_gc [q ]); 6600err = "prefill latent: the group's rows pass the layer tables" ; 6601return false; 6602 } 6603lat_nr = 0 ; 6604// lat_gc is NOT cleared here: a flush can fall in the middle of a batch (the row cap), and 6605// the experts after it still need their own counts. Each layer initialises it to -1. 6606if (nr <=0 )return true; 6607// the gate/up and down rows of this launch only: rows 0..nr-1 of Xq/GU/H/Hq. Under 6608// stream_all those buffers hold stream_all_min() - 1 tokens' rows, not the chunk's 6609// T*K, so an absolute row index writes past them (T >= 1024 went non-finite). 6610cudaMemsetAsync (m .grp_gu + nb2 * lat_gub ,0 ,MMQ_TAIL ,m .cs ); 6611cudaMemsetAsync (m .grp_d + nb2 * lat_db ,0 ,MMQ_TAIL ,m .cs ); 6612if (!tr ("memset" ))return false; 6613if (!tr ("pre-upload" ))return false; 6614if (m .up_ring .h2d (m .bounds_dev ,bh .data (),bh .size ()* 4 ,m .cs )!= cudaSuccess ) { 6615if (!tr ("upload" ))return false; 6616err = "prefill latent: the MMQ group's bounds' upload failed" ; 6617return false; 6618 } 6619int64_t maxr = 0 ; 6620for (size_t q = 0 ;q < nb2 ;++ q ) 6621maxr = std::max < int64_t > (maxr , (int64_t ) (bh [q + 1 ]- bh [q ])); 6622const auto T1 = now2 (); 6623P [0 ]+= ms2 (T0 ,T1 ); 6624// Xq is MMQ's q8_1 (block_q8_1_mmq: 128-value blocks, transposed, row stride 6625// pad512(ELL) values), filled from the f32 latent rows by MMQ's own quantizer, which 6626// gathers row i from ids[i]. xlq holds the engine's kv q8_1 rows (36-byte blocks, 6627// no padding) - a different layout, only the native/decode kernels can read it. 6628pt .mark (kPfGemmGU ,m .cs ); 6629 mmq::quantize (m .xl ,m .lat_gxl + lat_base ,m .Xq ,f .gu_type , (int64_t )ELL , (int64_t )ELL ,nr ,m .cs ); 6630const auto T2 = now2 (); 6631P [1 ]+= ms2 (T1 ,T2 ); 6632if (!tr ("quant_xq" ))return false; 6633if (std::getenv ("STRATA_LATENT_MMQ_TRACE" )!= nullptr ) { 6634 std::vector < int32_t > hi ((size_t )nr ),hb2 (nb2 + 1 ); 6635cudaMemcpy (hi .data (),m .ids_identity , (size_t )nr * 4 ,cudaMemcpyDeviceToHost ); 6636cudaMemcpy (hb2 .data (),m .bounds_dev , (nb2 + 1 )* 4 ,cudaMemcpyDeviceToHost ); 6637int32_t imn = hi [0 ],imx = hi [0 ]; 6638for (int32_t v :hi ) {imn = std::min (imn ,v );imx = std::max (imx ,v ); } 6639 std::fprintf (stderr ,"latmmq-ids: nr=%lld id[min,max]=[%d,%d] bounds[0]=%d bounds[nb2]=%d nb2=%zu\n" , 6640 (long long )nr ,imn ,imx ,hb2 [0 ],hb2 [nb2 ],nb2 ); 6641 } 6642static const bool lat_tr = std::getenv ("STRATA_LATENT_MMQ_TRACE" )!= nullptr ; 6643static bool lat_said = false; 6644if (lat_tr && !lat_said ) { 6645lat_said = true; 6646const MmqPlan & mpp = mmq_plan (); 6647const MoeBufs mbx = moe_bufs ((size_t )T ,m .g -> n_expert , false); 6648 std::fprintf (stderr ,"latmmq-cap: any=%d gu_max=%zu d_max=%zu gub=%zu db=%zu mb_gu=%zu mb_h=%zu " 6649"mb_hq=%zu mb_xq=%zu " 6650"ids=%p bounds=%p grp_gu=%p grp_d=%p xl=%p Xq=%p GU=%p H=%p Hq=%p yl=%p nr=%lld maxr=%lld\n" , 6651 (int )mpp .any ,mpp .gu_max ,mpp .d_max ,lat_gub ,lat_db ,mbx .gu ,mbx .h ,mbx .hq ,mbx .xq , 6652 (void * )m .ids_identity , (void * )m .bounds_dev , (void * )m .grp_gu , (void * )m .grp_d , 6653 (void * )m .xl , (void * )m .Xq , (void * )m .GU , (void * )m .H , (void * )m .Hq , (void * )m .yl , 6654 (long long )nr , (long long )maxr ); 6655for (size_t q = 0 ;q <=nb2 && q < 17 ;++ q ) 6656 std::fprintf (stderr ,"latmmq-bh[%zu]=%d\n" ,q ,bh [q ]); 6657 } 6658 {// latmmq-dev: which device each buffer lives on, and the current one 6659static bool devsaid = false; 6660if (!devsaid && std::getenv ("STRATA_LATENT_MMQ_TRACE" )!= nullptr ) { 6661devsaid = true; 6662int cur = -1 ;cudaGetDevice (& cur ); 6663auto devof = [](const void * p2 )-> int { 6664cudaPointerAttributes a {}; 6665if (cudaPointerGetAttributes (& a ,p2 )!= cudaSuccess ) {cudaGetLastError ();return -1 ; } 6666return (int )a .device ; 6667 }; 6668auto typeof = [](const void * p2 )-> int { 6669cudaPointerAttributes a2 {}; 6670if (cudaPointerGetAttributes (& a2 ,p2 )!= cudaSuccess ) {cudaGetLastError ();return -1 ; } 6671return (int )a2 .type ;// 1 host, 2 device, 3 managed 6672 }; 6673 std::fprintf (stderr ,"latmmq-mem: xl=%d yl=%d H=%d Hq=%d GU=%d Xq=%d Dm=%d grp_gu=%d grp_d=%d " 6674"ids=%d (1=host,2=device,3=managed)\n" , 6675typeof (m .xl ),typeof (m .yl ),typeof (m .H ),typeof (m .Hq ),typeof (m .GU ), 6676typeof (m .Xq ),typeof (m .Dm ),typeof (m .grp_gu ),typeof (m .grp_d ), 6677typeof (m .ids_identity )); 6678 std::fprintf (stderr ,"latmmq-dev: cur=%d ids=%d bounds=%d grp_gu=%d grp_d=%d Xq=%d " 6679"GU=%d H=%d Hq=%d yl=%d xl=%d gxl=%d gdst=%d\n" ,cur , 6680devof (m .ids_identity ),devof (m .bounds_dev ),devof (m .grp_gu ), 6681devof (m .grp_d ),devof (m .Xq ),devof (m .GU ),devof (m .H ), 6682devof (m .Hq ),devof (m .yl ),devof (m .xl ),devof (m .lat_gxl ), 6683devof (m .lat_gdst )); 6684 } 6685 } 6686auto run_p = [& ](const mmq::Product & pr ) { 6687static const bool alt = std::getenv ("STRATA_LATENT_MMQ_ALTCTX" )!= nullptr ; 6688static std::unique_ptr < mmq::Context > altctx ; 6689if (alt ) { 6690if (!altctx )altctx = std::make_unique < mmq::Context > (); 6691altctx -> run (pr ,m .cs ); 6692return ; 6693 } 6694m .mmq_ctx -> run (pr ,m .cs ); 6695 }; 6696 mmq::Product gu ; 6697gu .w = m .grp_gu ;gu .type = f .gu_type ;gu .w_rows = 1280 ;gu .w_cols = (int64_t )ELL ; 6698gu .expert_bytes = lat_gub ;gu .n = (int )nb2 ;gu .xq = m .Xq ; 6699gu .bounds = m .bounds_dev ;gu .ids = m .ids_identity ; 6700gu .total_rows = nr ;gu .max_rows = maxr ; 6701gu .dst = m .GU ;gu .ld_dst = 1280 ; 6702run_p (gu ); 6703const auto T3 = now2 (); 6704P [2 ]+= ms2 (T2 ,T3 ); 6705if (!tr ("gu" ))return false; 6706pt .mark (kPfDequant ,m .cs );// gate/up = quantize(xl) + the gu kernel 6707 mmq::swiglu (m .GU ,m .H ,nr ,640 , false,m .cs ); 6708if (!tr ("swiglu" ))return false; 6709pt .mark (kPfGemmD ,m .cs ); 6710 mmq::quantize (m .H ,nullptr ,m .Hq ,f .d_type ,640 ,640 ,nr ,m .cs ); 6711const auto T4 = now2 (); 6712P [3 ]+= ms2 (T3 ,T4 ); 6713if (!tr ("quant_h" ))return false; 6714 mmq::Product dn ; 6715dn .w = m .grp_d ;dn .type = f .d_type ;dn .w_rows = (int64_t )ELL ;dn .w_cols = 640 ; 6716dn .expert_bytes = lat_db ;dn .n = (int )nb2 ;dn .xq = m .Hq ; 6717// A/B only (wrong answers): is the scattered dst row - yl[entry], with entry not 6718// monotonic in buffer row - what makes the down product slow? 6719static const bool lat_dn_ident = std::getenv ("STRATA_LATENT_MMQ_IDENT" )!= nullptr ; 6720dn .bounds = m .bounds_dev ; 6721dn .ids = lat_dn_ident ?m .ids_identity : (m .lat_gdst + lat_base ); 6722dn .total_rows = nr ;dn .max_rows = maxr ; 6723dn .dst = m .yl ;dn .ld_dst = (int64_t )ELL ; 6724pt .mark (kPfGemmD ,m .cs );// dequant phase = swiglu + quantize(H) 6725run_p (dn ); 6726const auto T5 = now2 (); 6727P [4 ]+= ms2 (T4 ,T5 ); 6728if (!tr ("dn" ))return false; 6729pt .mark (kPfCombine ,m .cs );// gemm down = the dn kernel alone 6730lat_base += nr ; 6731P [5 ]+= ms2 (T0 ,now2 ()); 6732if (l %8 == 7 && std::getenv ("STRATA_LATENT_MMQ_PROF" )!= nullptr ) 6733 std::fprintf (stderr , 6734"latmmq-prof: l=%d pre=%.0f quant=%.0f gu=%.0f h=%.0f dn=%.0f " 6735"all=%.0f ms flushes=%zu\n" , (int )l ,P [0 ],P [1 ],P [2 ],P [3 ],P [4 ], 6736P [5 ],lat_nflush ); 6737return true; 6738 }; 6739const size_t n_order = order .size (); 6740unsigned long long gp [kLatBatch ];// host tables, uploaded per launch: the grouped 6741int32_t gs [kLatBatch + 1 ];// kernel reads grp_ptr/grp_start on the device 6742auto arm_launch = [& ](const strata::kernels::NativeExpertLayout & La ,size_t nb , 6743size_t q0 = 0 ) { 6744if (m .up_ring .h2d (m .lat_gp ,gp ,nb * 8 ,m .cs )!= cudaSuccess || 6745m .up_ring .h2d (m .lat_gs ,gs , (nb + 1 )* 4 ,m .cs )!= cudaSuccess ) { 6746err = "prefill latent: the group tables' upload failed" ; 6747return false; 6748 } 6749 {int32_t ngi = (int32_t )nb ;m .up_ring .h2d (m .lat_n ,& ngi ,4 ,m .cs ); } 6750pt .mark (kPfGemmGU ,m .cs ); 6751// STRATA_LATENT_MMQ=1: the A stage on llama.cpp's int8 MMQ, the path the non-latent 6752// native packs already take (gather_native + Product). xlq is (token,group)-ordered 6753// and MMQ reads entry-ordered rows, so its rows are gathered by m.tok first; the 6754// experts' blobs are gathered into MMQ's group matrices; gate/up, SwiGLU and down 6755// are then three launches over the whole batch instead of one grouped kernel that 6756// re-reads each expert per entry. Off by default (native_expert_grouped below). 6757if (lat_fused_q3k ) { 6758// M4: the group's row count - lat_gc where the walk knows it, else the gs 6759// difference (the same resolution the MMQ path does), so starts[] may be in any 6760// order and need not tile the entry space 6761int32_t lc [LAT_GROUP ]; 6762for (size_t q = 0 ;q < nb ;++ q ) { 6763const int32_t c = lat_gc [q0 + q ]; 6764lc [q ]= c >=0 ?c : (int32_t ) (gs [q0 + q + 1 ]- gs [q0 + q ]); 6765 } 6766if (m .up_ring .h2d (m .lat_gcd ,lc ,nb * 4 ,m .cs )!= cudaSuccess ) { 6767err = "prefill latent: the per-group row counts' upload failed" ; 6768return false; 6769 } 6770static const bool fq_nprof = std::getenv ("STRATA_LATENT_NPROF" )!= nullptr ; 6771cudaEvent_t ev0 = nullptr ,ev1 = nullptr ; 6772if (fq_nprof ) {cudaEventCreate (& ev0 );cudaEventCreate (& ev1 );cudaEventRecord (ev0 ,m .cs ); } 6773 strata::prefill::lat_q3k_fused ((const uint8_t * const * )m .lat_gp ,m .lat_gs , (int )nb , 6774m .xlq ,m .lat_hbuf ,m .yl ,ELL ,m .cs ,m .lat_gcd ,m .tok , 6775m .ids_identity ); 6776if (fq_nprof ) { 6777cudaEventRecord (ev1 ,m .cs ); 6778cudaEventSynchronize (ev1 ); 6779float cms = 0.f ; 6780cudaEventElapsedTime (& cms ,ev0 ,ev1 ); 6781const long long ent = (long long )gs [q0 + nb ]- (long long )gs [q0 ]; 6782static double acc = 0 ; 6783static long long ncall = 0 ,nent = 0 ; 6784acc += cms ;++ ncall ;nent += ent ; 6785if (ncall %24 == 0 ) 6786 std::fprintf (stderr , 6787"latfq3kprof: calls=%lld ms=%.0f entries=%lld us/entry=%.2f " 6788"last: nb=%zu ent=%lld cap=%lld T=%lld K=%lld\n" , 6789ncall ,acc ,nent , 6790nent > 0 ?acc * 1000.0 / (double )nent :0.0 ,nb ,ent , 6791 (long long ) (T * K ), (long long )T , (long long )K ); 6792cudaEventDestroy (ev0 );cudaEventDestroy (ev1 ); 6793 } 6794return true; 6795 } 6796if (lat_mmq ) { 6797if (m .xl == nullptr ) { 6798err = "prefill latent: the MMQ A stage needs the f32 latent rows" ; 6799return false; 6800 } 6801pt .mark (kPfGather ,m .cs ); 6802for (size_t q = 0 ;q < nb ;++ q ) { 6803const int64_t c = lat_gc [q0 + q ] >=0 6804 ? (int64_t )lat_gc [q0 + q ] 6805 : (int64_t )gs [q0 + q + 1 ]- (int64_t )gs [q0 + q ]; 6806// a group is one contiguous run of rows in the buffers: close it before it would pass the cap 6807if (lat_q > 0 && lat_nr + c > lat_rowcap && !arm_flush ())return false; 6808const size_t z = lat_q ; 6809const uint8_t * bd = (const uint8_t * )gp [q0 + q ]; 6810static const bool lat_nogather = std::getenv ("STRATA_LATENT_MMQ_NOGATHER" )!= nullptr ; 6811if (!lat_nogather )// A/B only: the answers are wrong with this on 6812 mmq::gather_native (bd ,bd + f .up_off ,lat_gub /2 ,bd + f .down_off ,lat_db , 6813m .grp_gu + z * lat_gub ,m .grp_d + z * lat_db ,m .cs ); 6814lat_gq [z ]= gs [q0 + q ]; 6815lat_ge [z ]= (int32_t ) ((int64_t )gs [q0 + q ]+ c ); 6816lat_cnt [z ]= (int32_t )c ; 6817lat_nr += c ; 6818++ lat_q ; 6819if (lat_q == lat_gmax && !arm_flush ())return false; 6820 } 6821pt .mark (kPfDequant ,m .cs );// the gather kernels' own time 6822return true; 6823 } 6824 { 6825static const bool nprof = std::getenv ("STRATA_LATENT_NPROF" )!= nullptr ; 6826cudaEvent_t ev0 = nullptr ,ev1 = nullptr ; 6827if (nprof ) {cudaEventCreate (& ev0 );cudaEventCreate (& ev1 );cudaEventRecord (ev0 ,m .cs ); } 6828 strata::kernels::native_expert_grouped (La ,m .lat_gp ,m .lat_gs ,m .lat_n ,m .ids_identity , 6829m .tok , (int64_t )nb , (int64_t ) (T * K ),m .xlq , 6830m .lat_scratch ,m .yl ,m .cs ,0 ); 6831if (nprof ) { 6832cudaEventRecord (ev1 ,m .cs ); 6833cudaEventSynchronize (ev1 ); 6834float cms = 0.f ; 6835cudaEventElapsedTime (& cms ,ev0 ,ev1 ); 6836const long long ent = (long long )gs [q0 + nb ]- (long long )gs [q0 ]; 6837static double acc = 0 ;static long long ncall = 0 ,nent = 0 ; 6838acc += cms ;++ ncall ;nent += ent ; 6839if (ncall %24 == 0 ) 6840 std::fprintf (stderr , 6841"latnprof: calls=%lld ms=%.0f entries=%lld us/entry=%.2f " 6842"last: nb=%zu ent=%lld cap=%lld T=%lld K=%lld\n" , 6843ncall ,acc ,nent ,nent > 0 ?acc * 1000.0 / (double )nent :0.0 , 6844nb ,ent , (long long ) (T * K ), (long long )T , (long long )K ); 6845cudaEventDestroy (ev0 );cudaEventDestroy (ev1 ); 6846 } 6847 } 6848return true; 6849 }; 6850// A: per-expert grouped launches (the kernel's grp_start ranges tile contiguous entries, so a 6851// layout-mixed batch cannot share a launch): resident slots take the nib layout on nib 6852// layers, staged blobs (plain GGUF bytes) the plain one. 6853size_t staged = 0 ; 6854const size_t lookahead = (size_t )stage_n - 1 ; 6855if (lat_fused ) { 6856// A on the fused batch kernels, #136's walk: the experts in id order, one WideBatch 6857// launch per kMaxBatch of them - at most a third of the ring streamed, so the next 6858// batch's blobs arrive while one computes. An expert the routing did not pick has no 6859// tiles (its blob pointer is read only if it has); its ring slot is given back with 6860// its batch. The blobs are wherever they are (a resident cache slot, a staged ring 6861// slot, the peer's VRAM), all the same plain native NVFP4 layout. 6862auto lat_fire = [& ](const fused::WideBatch & fb ) { 6863if (lat_log ) { 6864int nrouted = 0 ,nnull = 0 ; 6865for (int ee = fb .e0 ;ee < fb .e1 ;++ ee ) { 6866if (m .cnt [(size_t )ee ]> 0 )++ nrouted ; 6867if (fb .blob [ee - fb .e0 ]== nullptr )++ nnull ; 6868 } 6869 std::fprintf (stderr , 6870"latfused: l=%d e0=%d e1=%d span=%d routed=%d nullblob=%d n=%lld " 6871"xlq=%p tok=%p scratch=%p lat_h=%zu ring=%d\n" , 6872 (int )l ,fb .e0 ,fb .e1 ,fb .e1 - fb .e0 ,nrouted ,nnull , 6873 (long long ) (T * K ), 6874 (void * )m .xlq , (void * )m .tok , (void * )m .lat_scratch ,lat_h , 6875 (int )m .ring ); 6876 } 6877// off[] is a permutation for the latent grouping (the residents' block first), 6878// so the grid bound is the whole chunk, not off[e1] - off[e0] 6879// the q3k pack takes the same walk with Q3_K gate/up and IQ4_NL down in place of 6880// the NVFP4 blocks; every other pack takes the original. `fb` already carries the 6881// batch's blobs by expert id and `m.tok` the entry -> xl row map, so the two calls 6882// differ only in the decode. 6883// the geometry is the pack's own: lat_lg carries gu_row / d_row / up_off / down_off / 6884// tail_off read from its native_experts.txt, so ell 1280 and 1792 both work 6885if (f .gu_type == 11 /* GGML_TYPE_Q3_K */ && f .d_type == 20 /* GGML_TYPE_IQ4_NL */ && 6886m .lat_I == 640 ) { 6887 fused_q3k::experts_latent_q3k (fb ,lat_lg , (int )m .g -> n_expert , (int64_t ) (T * K ), 6888m .lat_scratch ,m .xlq ,m .tok ,m .lat_scratch + lat_h , 6889m .yl ,m .cs ); 6890 }else { 6891 fused::experts_latent (fb ,lat_lg , (int )m .g -> n_expert , (int64_t ) (T * K ), 6892m .lat_scratch ,m .xlq ,m .tok ,m .lat_scratch + lat_h , 6893m .yl ,m .cs ); 6894 } 6895 }; 6896auto lat_blob = [& ](int32_t e )-> const uint8_t * { 6897const bool r0 = m .host_res && m .cache && 6898m .host_res [(size_t )l * m .g -> n_expert + e ] >=0 ; 6899const uint8_t * bp = 6900r0 ?m .cache -> device_slot (m .host_res [(size_t )l * m .g -> n_expert + e ]) 6901 : (m .pp && m .pp -> peer ?m .pp -> peer -> slot_ptr (l ,e ) :nullptr ); 6902if (bp == nullptr && m .cnt [(size_t )e ]> 0 ) { 6903err = "prefill latent: an expert is neither resident, streamed nor on the peer" ; 6904return nullptr ; 6905 } 6906if (r0 )++ stats_ .experts_resident ; 6907return bp ;// null: unrouted, the kernels skip it (no tiles) 6908 }; 6909if (stream_all ) { 6910const size_t per = (size_t ) std::max < int64_t > (1 , (int64_t )m .ring /3 ); 6911size_t k = seq_start [(size_t )l ]; 6912const size_t kend = seq_start [(size_t )l + 1 ]; 6913for (int32_t e = 0 ;e < m .g -> n_expert ;) { 6914 fused::WideBatch fb ; 6915fb .e0 = e ; 6916const size_t k0 = k ; 6917for (;e < m .g -> n_expert && e - fb .e0 < fused::kMaxBatch ;++ e ) { 6918if (k < kend && seq [k ].e == e ) { 6919if (k - k0 == per )break ; 6920fb .blob [e - fb .e0 ]= m .stage_dev [k % (size_t )m .ring ]; 6921++ k ; 6922 }else { 6923fb .blob [e - fb .e0 ]= lat_blob (e ); 6924if (fb .blob [e - fb .e0 ]== nullptr && !err .empty ())return false; 6925 } 6926 } 6927fb .e1 = e ; 6928if (k > k0 ) { 6929// one copy stream, in order: the batch's last blob covers the others 6930pt .mark (kPfWaitCopy ,m .cs ); 6931wait_issued (k - 1 ); 6932wait_copied (k - 1 , (k - 1 ) % (size_t )m .ring ); 6933 } 6934pt .mark (kPfGemmGU ,m .cs ); 6935lat_fire (fb ); 6936for (size_t kk = k0 ;kk < k ;++ kk ) { 6937cudaEventRecord (m .used [kk % (size_t )m .ring ],m .cs ); 6938m .used_of [kk % (size_t )m .ring ]= (int ) (kk % (size_t )m .ring ); 6939 } 6940if (k > k0 ) { 6941consumed = k ; 6942give_back (consumed ); 6943 } 6944 } 6945 }else { 6946// the staged walk: the same lookahead keeps the copies coming; a batch waits 6947// only for its last staged blob (one copy stream, in order) 6948size_t nb = 0 ,nst = 0 ; 6949// an open batch keeps its staged slots until it launches (staged_batch.hpp) 6950const strata::prefill::StagedBatchPlan plan = strata::prefill::staged_batch_plan (stage_n ,LAT_GROUP ); 6951int fb_stage [LAT_GROUP ]; 6952 fused::WideBatch fb ; 6953int32_t bfirst = 0 ,blast = 0 ; 6954auto lat_flush = [& ]()-> bool { 6955if (nb == 0 )return true; 6956fb .e0 = bfirst ; 6957fb .e1 = blast + 1 ; 6958if (nst > 0 ) { 6959pt .mark (kPfWaitCopy ,m .cs ); 6960cudaStreamWaitEvent (m .cs ,m .copied [fb_stage [nst - 1 ]],0 ); 6961 } 6962pt .mark (kPfGemmGU ,m .cs ); 6963lat_fire (fb ); 6964for (size_t i = 0 ;i < nst ;++ i ) {// the staged slots free once the launch is done 6965cudaEventRecord (m .used [fb_stage [i ]],m .cs ); 6966m .used_of [fb_stage [i ]]= fb_stage [i ]; 6967 } 6968nb = nst = 0 ; 6969return true; 6970 }; 6971for (size_t j = 0 ;j < n_order ;++ j ) { 6972const int32_t e = order [j ]; 6973while (staged < n_order && staged <=j + plan .ahead ) { 6974if (!stage_one (staged ))return false; 6975++ staged ; 6976 } 6977if (nb == 0 )bfirst = e ; 6978if (stage_of [j ]< 0 ) {// resident (or on the peer) 6979fb .blob [e - bfirst ]= lat_blob (e ); 6980if (fb .blob [e - bfirst ]== nullptr && !err .empty ())return false; 6981 }else { 6982fb .blob [e - bfirst ]= m .stage_dev [stage_of [j ]]; 6983fb_stage [nst ++ ]= stage_of [j ]; 6984 } 6985blast = e ; 6986++ nb ; 6987if (nb == plan .group_limit || (size_t ) (e + 1 - bfirst ) >= fused::kBatchRoom ) { 6988if (!lat_flush ())return false; 6989 } 6990 } 6991if (!lat_flush ())return false; 6992 } 6993 }else if (stream_all ) { 6994// STRATA_LATENT_MMQ: the same walk, but ONE wait per batch of LAT_GROUP experts, as 6995// the fused path waits once per batch: the batch's copies are ordered on m.copy, so 6996// the last one covers the others, and one gate/up + down set runs over all of them. 6997// Waiting per expert made the A stage copy -> compute -> copy with no overlap (the 6998// GPU sat at ~45 %): that, not the kernels, was the whole gap to the fused path. 6999// STRATA_LATENT_BATCH=1 (opt-in until verified end to end): the batched walk for the 7000// native path too. STRATA_LATENT_NOBATCH=1 keeps it on for the MMQ path only. 7001static const bool lat_batched = 7002lat_mmq ? std::getenv ("STRATA_LATENT_NOBATCH" )== nullptr 7003 : std::getenv ("STRATA_LATENT_BATCH" )!= nullptr ; 7004if (lat_batched ) { 7005size_t k = seq_start [(size_t )l ]; 7006const size_t kend = seq_start [(size_t )l + 1 ]; 7007auto release_to = [& ](int32_t e_stop ) { 7008while (k < kend && seq [k ].e < e_stop ) { 7009const int sl = (int ) (k % (size_t )m .ring ); 7010cudaEventRecord (m .used [sl ],m .cs ); 7011m .used_of [sl ]= sl ; 7012consumed = ++ k ; 7013give_back (consumed ); 7014 } 7015 }; 7016static double lat_wait_ms [2 ]= {0 ,0 };// [0] issued, [1] copied 7017size_t nb = 0 ,k0 = k ; 7018auto fire = [& ]()-> bool { 7019if (nb == 0 )return true; 7020if (k > k0 ) { 7021auto now = [] {return std::chrono::steady_clock::now (); }; 7022auto ms = [](auto a ,auto b ) { 7023return std::chrono::duration < double , std::milli > (b - a ).count (); 7024 }; 7025const auto t0 = now (); 7026wait_issued (k - 1 ); 7027const auto t1 = now (); 7028pt .mark (kPfWaitCopy ,m .cs ); 7029wait_copied (k - 1 , (k - 1 ) % (size_t )m .ring ); 7030const auto t2 = now (); 7031lat_wait_ms [0 ]+= ms (t0 ,t1 ); 7032lat_wait_ms [1 ]+= ms (t1 ,t2 ); 7033 } 7034 {// STRATA_LATENT_MMQ_TRACE: the batch's shape and blob pointers 7035static int dbgn = 0 ; 7036if (dbgn < 2 && std::getenv ("STRATA_LATENT_MMQ_TRACE" )!= nullptr ) { 7037++ dbgn ; 7038 std::fprintf (stderr ,"latmmq-fire l=%d nb=%zu ring=%d\n" , (int )l ,nb , 7039 (int )m .ring ); 7040for (size_t q = 0 ;q < nb ;++ q ) 7041 std::fprintf (stderr ,"latmmq-fire[%zu] gp=%llx gs=%d..%d\n" ,q , 7042gp [q ],gs [q ],gs [q + 1 ]); 7043 } 7044 } 7045for (size_t q0 = 0 ;q0 < nb ;q0 += (size_t )LAT_GROUP )// the batch's groups 7046if (!arm_launch (la_for (false), std::min < size_t > ((size_t )LAT_GROUP ,nb - q0 ), 7047q0 )) 7048return false; 7049for (size_t kk = k0 ;kk < k ;++ kk ) {// a slot is refilled only once the kernels 7050cudaEventRecord (m .used [kk % (size_t )m .ring ],m .cs );// that read it are done 7051m .used_of [kk % (size_t )m .ring ]= (int ) (kk % (size_t )m .ring ); 7052 } 7053if (k > k0 ) {consumed = k ;give_back (consumed ); } 7054nb = 0 ; 7055k0 = k ; 7056return true; 7057 }; 7058for (size_t j = 0 ;j < n_order ;++ j ) { 7059const int32_t e = order [j ]; 7060release_to (e ); 7061if (k < kend && seq [k ].e == e ) { 7062gp [nb ]= (unsigned long long )m .stage_dev [k % (size_t )m .ring ]; 7063++ k ; 7064++ stats_ .experts_streamed ; 7065 }else { 7066const bool r0 = m .host_res && m .cache && 7067m .host_res [(size_t )l * m .g -> n_expert + e ] >=0 ; 7068const uint8_t * bp = r0 7069 ?m .cache -> device_slot (m .host_res [(size_t )l * m .g -> n_expert + e ]) 7070 : (m .pp && m .pp -> peer ?m .pp -> peer -> slot_ptr (l ,e ) :nullptr ); 7071if (bp == nullptr ) { 7072err = "prefill latent: an expert is neither resident, streamed nor on the peer" ; 7073return false; 7074 } 7075++ stats_ .experts_resident ; 7076gp [nb ]= (unsigned long long )bp ; 7077 } 7078// An entry carries BOTH things: gs is the expert's absolute entry base (what the row 7079// table slice and the dst rows are keyed by), lat_gc its row count (what the group's 7080// buffer rows and the launch grid are keyed by). Using gs's consecutive differences 7081// as the counts was wrong: off[] is NOT monotonic in expert id under stream_all (the 7082// resident block is laid out first), so a group's bounds ran backwards, max_rows came 7083// out ~10x total_rows, and the gate/up launch read ids past nr and wrote dst rows past 7084// m.GU - the illegal memory access the trace named at the gu launch. Only a group whose 7085// experts happened to sit in off[] order (the layer's first) came out right. 7086// native_expert_grouped takes no counts: group g's rows are 7087// [grp_start[g], grp_start[g+1]). So a batch may only hold experts whose row 7088// ranges are contiguous - flush when this one does not start where the last 7089// ended (under stream_all the rows are slot-ordered, the walk id-ordered). 7090if (!lat_mmq && !lat_fused_q3k && nb > 0 && 7091 (int32_t )m .off [(size_t )e ]!= gs [nb ]) { 7092if (!fire ())return false; 7093 } 7094gs [nb ]= (int32_t )m .off [(size_t )e ]; 7095gs [nb + 1 ]= (int32_t ) (m .off [(size_t )e ]+ m .cnt [(size_t )e ]); 7096lat_gc [nb ]= (int32_t )m .cnt [(size_t )e ]; 7097++ nb ; 7098if (nb == lat_batch && !fire ())return false; 7099 } 7100if (!fire ())return false; 7101release_to (m .g -> n_expert ); 7102 }else { 7103// the streamed walk, with the original walk's bookkeeping below: this layer's 7104// entries [k, kend) in id order; an entry the routing did not pick only gives 7105// its slot back (the group walk never runs on the latent arm, so the MMQ 7106// group-gather sides of the original conditions are provably inert) 7107size_t k = seq_start [(size_t )l ]; 7108const size_t kend = seq_start [(size_t )l + 1 ]; 7109auto release_to = [& ](int32_t e_stop ) { 7110while (k < kend && seq [k ].e < e_stop ) { 7111const int sl = (int ) (k % (size_t )m .ring ); 7112cudaEventRecord (m .used [sl ],m .cs ); 7113m .used_of [sl ]= sl ; 7114consumed = ++ k ; 7115give_back (consumed ); 7116 } 7117 }; 7118for (size_t j = 0 ;j < n_order ;++ j ) { 7119const int32_t e = order [j ]; 7120release_to (e ); 7121if (k < kend && seq [k ].e == e ) { 7122const int sl = (int ) (k % (size_t )m .ring ); 7123wait_issued (k ); 7124pt .mark (kPfWaitCopy ,m .cs ); 7125wait_copied (k , (size_t )sl ); 7126gp [0 ]= (unsigned long long )m .stage_dev [sl ]; 7127gs [0 ]= (int32_t )m .off [(size_t )e ]; 7128gs [1 ]= (int32_t ) (m .off [(size_t )e ]+ m .cnt [(size_t )e ]); 7129// staged bytes: always the plain GGUF layout 7130if (!arm_launch (la_for (false),1 ))return false; 7131consumed = ++ k ; 7132give_back (consumed );// the slot frees once this launch is done 7133 }else { 7134const bool r0 = m .host_res && m .cache && 7135m .host_res [(size_t )l * m .g -> n_expert + e ] >=0 ; 7136const uint8_t * bp = r0 ?m .cache -> device_slot (m .host_res [(size_t )l * m .g -> n_expert + e ]) 7137 : (m .pp && m .pp -> peer ?m .pp -> peer -> slot_ptr (l ,e ) :nullptr ); 7138if (bp == nullptr ) { 7139err = "prefill latent: an expert is neither resident, streamed nor on the peer" ; 7140return false; 7141 } 7142gp [0 ]= (unsigned long long )bp ; 7143gs [0 ]= (int32_t )m .off [(size_t )e ]; 7144gs [1 ]= (int32_t ) (m .off [(size_t )e ]+ m .cnt [(size_t )e ]); 7145++ stats_ .experts_resident ; 7146// the cache slot's nib layout on nib layers 7147if (!arm_launch (la_for (nib_l ),1 ))return false; 7148 } 7149 } 7150release_to (m .g -> n_expert ); 7151 } 7152 }else { 7153// A: the resident experts share grouped launches (off[] put their entries 7154// first, so up to LAT_GROUP of them tile one launch's group table - the 7155// ranges stay contiguous because the residents were assigned offsets in id 7156// order as one block). A staged blob still launches alone behind its copy's 7157// event: the staging ring's lookahead overlap is what it is for. 7158// STRATA_EXPERT_NIBBLE: the cache slots' nib layout on nib layers; a staged 7159// blob is always the plain GGUF bytes. 7160size_t nb = 0 ; 7161for (size_t j = 0 ;j < n_order ;++ j ) { 7162const int32_t e = order [j ]; 7163while (staged < n_order && staged <=j + lookahead ) { 7164if (!stage_one (staged ))return false; 7165++ staged ; 7166 } 7167if (stage_of [j ]< 0 ) {// resident: accumulate into the shared launch 7168gp [nb ]= (unsigned long long )m .cache -> device_slot ( 7169m .host_res [(size_t )l * m .g -> n_expert + e ]); 7170gs [nb ]= (int32_t )m .off [(size_t )e ]; 7171gs [nb + 1 ]= (int32_t ) (m .off [(size_t )e ]+ m .cnt [(size_t )e ]); 7172++ nb ; 7173++ stats_ .experts_resident ; 7174if (nb == (size_t )LAT_GROUP ) { 7175if (!arm_launch (la_for (nib_l ),nb ))return false; 7176nb = 0 ; 7177 } 7178continue ; 7179 } 7180if (nb > 0 ) {// launch the residents collected so far before the staged one 7181if (!arm_launch (la_for (nib_l ),nb ))return false; 7182nb = 0 ; 7183 } 7184pt .mark (kPfWaitCopy ,m .cs ); 7185cudaStreamWaitEvent (m .cs ,m .copied [stage_of [j ]],0 ); 7186gp [0 ]= (unsigned long long )m .stage_dev [stage_of [j ]]; 7187gs [0 ]= (int32_t )m .off [(size_t )e ]; 7188gs [1 ]= (int32_t ) (m .off [(size_t )e ]+ m .cnt [(size_t )e ]); 7189if (!arm_launch (la_for (false),1 ))return false; 7190cudaEventRecord (m .used [stage_of [j ]],m .cs );// the slot frees once this launch is done 7191m .used_of [stage_of [j ]]= stage_of [j ]; 7192 } 7193if (nb > 0 ) { 7194if (!arm_launch (la_for (nib_l ),nb ))return false; 7195 } 7196 } 7197if (!arm_flush ())return false;// STRATA_LATENT_MMQ: the layer's pending group 7198// U: each down latent hits U[labels[expert]]; the H-wide rows are this layer's Dm 7199 {// STRATA_LAT_MOE_DUMP (debug): the A stage's product yl, layer 0 7200static const char * lat_moe_dump3 = std::getenv ("STRATA_LAT_MOE_DUMP" ); 7201if (lat_moe_dump3 && l == 0 ) { 7202 std::vector < float > hb ((size_t )T * K * (size_t )ELL ); 7203if (cudaMemcpyAsync (hb .data (),m .yl ,hb .size ()* 4 ,cudaMemcpyDeviceToHost ,m .cs )!= cudaSuccess || 7204cudaStreamSynchronize (m .cs )!= cudaSuccess ) { 7205err = "lat moe dump: the yl copy failed" ;return false; 7206 } 7207char p [512 ]; std::snprintf (p ,sizeof p ,"%s/a-yl.bin" ,lat_moe_dump3 ); 7208 std::FILE * fp = std::fopen (p ,"wb" ); 7209if (fp == nullptr ) {err = std::string ("lat moe dump: cannot write " )+ p ;return false; } 7210 std::fwrite (hb .data (),4 ,hb .size (),fp ); std::fclose (fp ); 7211 } 7212 } 7213pt .mark (kPfGemmD ,m .cs ); 7214 strata::kernels::quantize_q8_1_rows (m .yl , (int64_t ) (T * K ), (int )ELL ,m .ylq ,m .cs ); 7215if (lat_du ) { 7216// the entries bucketed by their expert's label: the fused U kernel's tiles are one 7217// label's rows. The A stage's tables and H inside lat_scratch are dead by now 7218// (stream-ordered), so the bucket list lives there. 7219// the tables ON THE DEVICE: a mid-layer pinned h2d waits behind the blob prefetch's 7220// DMA queue (20-30 ms a layer once stream_all's prefetch runs deep); these tiny 7221// launches cost ~50 us. goff at +0, cursors at +48 (9 ints), rows at +128 of the 7222// scratch (the A stage's tables and H are dead here, stream-ordered). 7223 fused::latent_dense_u_tables (m .ids_p ,m .lat_labels_dev + (size_t )l * m .lat_E , 7224 (int64_t ) (T * K ), (int )G , 7225 (int32_t * )m .lat_scratch , (int32_t * )m .lat_scratch + 12 , 7226 (int32_t * )m .lat_scratch + 32 ,m .cs ); 7227// the grid bound without the counts: every split fits in ceil(n / 64) + G tiles 7228const int64_t unw = (((int64_t ) (T * K )+ 63 ) /64 + G )* (N >>8 ); 7229 fused::latent_dense_u (m .lat_u_dev + (size_t ) (l - m .lat_first_layer )* m .lat_d .u_bytes (),m .ylq , 7230 (const int32_t * )m .lat_scratch + 32 , (const int32_t * )m .lat_scratch , 7231 (int )G ,unw , (int64_t ) (T * K ), (int )ELL , (int )N ,m .Dm ,m .cs , 7232m .lat_fmt ); 7233 }else { 7234 strata::kernels::latent_u_grouped (m .lat_u_dev + (size_t ) (l - m .lat_first_layer )* m .lat_d .u_bytes (),m .ylq ,m .ids_p , 7235m .lat_labels_dev + (size_t )l * m .lat_E ,m .lat_E , (int64_t ) (T * K ), 7236 (int )ELL , (int )N ,m .Dm ,m .cs ,m .lat_fmt ); 7237 } 7238 }else 7239// pf_wmma: this layer's groups on the FP16 tensor-core tiles (single GPU, native pack, Q2_0 / IQ4_NL down) 7240 { 7241const bool wmma_l = use_mmq && pf_wmma ()&& !fused_l && on_peer .empty ()&& lay .native && 7242 (mmq_dt == 42 || mmq_dt == 20 )&& !lay .fmt [(size_t )l ].tail_off && 7243 strata::kernels::iq_row_bytes (mmq_gt ,N )> 0 ; 7244if (use_mmq && mmq_plan ().wmma_only [(size_t )l ]&& !wmma_l ) { 7245err = "prefill: an IQ1_M layer in the MMQ grouping needs the WMMA tiles, which this chunk cannot take" ; 7246return false; 7247 } 7248const size_t mmq_gub = use_mmq ? mmq::matrix_bytes (mmq_gt ,kFF2 ,N ) :0 ; 7249const size_t mmq_db = use_mmq ? mmq::matrix_bytes (mmq_dt ,N ,kFF ) :0 ; 7250bool ws_layer = false;// STRATA_MMQ_WS: this layer's products weight-stationary (below) 7251 ws::Layer wl ; 7252pt .mark (kPfGather ,cs ); 7253// P4-SMALL: a staged chunk's (below stream_all_min()) MMQ groups of a native layer the fused kernels cover on this device 7254// run as the gathered-group entry (fused::group_bounds + experts_native on each expert where it is: its cache slot or its 7255// staging slot), in place of MMQ's per-row quantize, gather, gate/up, SwiGLU, quantize and down. The activations go to int8 7256// ONCE PER TOKEN (quantize_act_native into Xq, where MMQ wrote a q8_1 copy for each of a token's K rows); the rows' tokens are 7257// src_dev, the groups' relative bounds MMQ's own, H into H, the down rows into Dm at the group's rows (the combine is MMQ's). 7258// The staging is the resident groups' (STAGE_GRP slots held until the group's launch). Not (in a build with MMQ) with a layer the CPU share took experts of (share_own_rule.hpp), nor with a peer, 7259// STRATA_MMQ_DIRECT / _WS, the WMMA tiles, STRATA_PF_GROUP_SCRATCH, NVFP4 tails, Hadamard-folded or nibble layers. 7260const bool fz_staged = !stream_all && strata::prefill::staged_entry_layer (use_mmq ,fused_only ,staged_fo_on ())&& lay .native && !fused_l && !wmma_l && !had_gu && !had_d && share_keeps_own_kernels (rows_cpu )&& 7261on_peer .empty ()&& !m .pp && m .group_cap == 0 && (!lay .fmt [(size_t )l ].tail_off || fused::native_supported (mmq_gt ,mmq_dt ))&& ws::mode ()== 0 && // (an NVFP4 tail: only where the fused kernels take the pair - they apply s_gate / s_up / s_down inside, so the entry needs no row_sd) 7262 !(m .cache && mmq_plan ().direct [(size_t )l ])&& staged_group_gather ()&& staged_group_entry_on ()&& 7263MMQ_GROUP <= mmq::kGatherGroupMax && MMQ_GROUP <= fused::kMaxBatch && 7264#if STRATA_EXPERT_NIBBLE_BUILT 7265 !nib_l .on && 7266#endif 7267 fused::native_supported (mmq_gt ,mmq_dt ); 7268// OWN-I8 (STRATA_EXPERT_I8=1 on any card; unset: the default of the HIP cards gfx1030 / 1031 / 1032, i8_expert_rule.hpp; =0 off): the MMQ groups of a native layer on our own 7269// int8 dot-product kernels (native_expert_i8, src/kernels/cuda/i8_expert.cuh), where MMQ's gather, per-row quantize, 7270// gate/up, SwiGLU, quantize and down run. The group's experts are read where they are (the cache slot or the ring slot: 7271// the gather's wait and slot release are kept, the copy is not made); the layer's tokens go to q8_1 ONCE per token (fr_xq, 7272// the few-row path's rows) in place of MMQ's per-row copy; SwiGLU and the q8_1 of H are inside the gate/up launch, down 7273// writes the rows of Dm the combine reads. Not with a layer the fused kernels take (they are the faster path on the 7274// cards that have them), (in a build with MMQ) a layer the CPU share took experts of, a peer, STRATA_MMQ_DIRECT / _WS, the WMMA tiles, STRATA_PF_GROUP_SCRATCH, NVFP4 7275// tails, Hadamard-folded or nibble layers; and only for groups of 256 entries or more (native_expert_i8_prompt). 7276static const bool i8_group_env = [] {// the group walk's own switch: the I8 launches ride on it 7277const char * v = std::getenv ("STRATA_PREFILL_GROUP_GATHER" ); 7278return v == nullptr || std::atoi (v )!= 0 ; 7279 }(); 7280 strata::kernels::NativeExpertLayout i8_L {}; 7281bool i8_l = false; 7282bool i8_few = false;// the few-rows route: the layer's groups run on native_expert_grouped, the activations as quantize_q8_1_rows makes them 7283// (a build without MMQ has no use_mmq layer: the layers the fused kernels do not take come here too, as long as the buffers below exist) 7284if (lay .native && strata::kernels::i8_order_allows (fused_l ,fz_staged )&& !wmma_l && !had_gu && !had_d && share_keeps_own_kernels (rows_cpu )&& on_peer .empty ()&& !m .pp && 7285m .group_cap == 0 && (!m .fused_bufs || !stream_all )&& !lay .fmt [(size_t )l ].tail_off && ws::mode ()== 0 && 7286 !(m .cache && mmq_plan ().direct [(size_t )l ])&& i8_group_env && !order .empty ()&& 7287 (!strata::kernels::native_expert_i8_floor_gated ()|| strata::kernels::i8_chunk_default_allows (-1 , true, true, (int64_t )T ,stream_all_min ()))&& // the P100 class rule: from the stream floor up the unset default is the FP16 path (i8_expert_rule.hpp) 7288m .GU != nullptr && m .Dm != nullptr && m .src_dev != nullptr && m .ids_identity != nullptr && 7289#if STRATA_EXPERT_NIBBLE_BUILT 7290 !nib_l .on && 7291#endif 7292 true) { 7293const auto & f = lay .fmt [(size_t )l ]; 7294i8_L = strata::kernels::native_expert_layout (f .gu_type ,f .d_type ,f .n_embd ,f .n_ff ); 7295const int64_t i8_groups = ((int64_t )order .size ()+ MMQ_GROUP - 1 ) /MMQ_GROUP ; 7296const bool i8_same = i8_L .up_off == f .up_off && i8_L .down_off == f .down_off && i8_L .bytes == f .bytes && f .n_embd == N && f .n_ff == kFF ; 7297// The few-rows route (i8_expert_rule.hpp): with it, the size floor of the int8 kernel (256 entries a group) gives way to the crossing; a layer 7298// under it (average rows per expert, over the experts that have rows) runs on the grouped kernels in the same groups, from it up on the int8 7299// kernel. A pair the grouped kernels do not have, or a group whose scratch would not fit the layer's GU rows, keeps the floor. 7300const int i8_fr = i8_same ? strata::kernels::native_expert_i8_few_rows_limit () :0 ; 7301i8_l = i8_same && strata::kernels::native_expert_i8_prompt (i8_L ,i8_fr > 0 ? strata::kernels::kI8MinGroupEntries :rows_local /i8_groups ); 7302if (i8_l && i8_fr > 0 && strata::kernels::i8_fewrows_takes (i8_fr ,rows_local , (int64_t )order .size ())) { 7303int64_t max_rows = 0 ;// the most rows one group of the walk launches with 7304for (size_t j = 0 ;j < order .size ();j += (size_t )MMQ_GROUP ) { 7305const size_t je = std::min (order .size (),j + (size_t )MMQ_GROUP )- 1 ; 7306max_rows = std::max < int64_t > (max_rows , (int64_t )m .off [(size_t )order [je ]]+ m .cnt [(size_t )order [je ]]- m .off [(size_t )order [j ]]); 7307 } 7308if (strata::kernels::native_expert_supported (f .gu_type ,f .d_type ,f .n_embd ,f .n_ff )&& 7309 strata::kernels::native_expert_scratch_bytes (max_rows ,kFF ) <= (size_t )rows_local * (size_t )kFF2 * sizeof (float )) 7310i8_few = true; 7311else 7312i8_l = strata::kernels::native_expert_i8_prompt (i8_L ,rows_local /i8_groups ); 7313 } 7314if (i8_count_on ()&& i8_groups > 0 ) { 7315I8Count & c = i8_count (); 7316c .min_avg = std::min < int64_t > (c .min_avg ,rows_local /i8_groups ); 7317if (i8_l )c .groups_i8 += i8_groups ; 7318 } 7319 } 7320if (i8_count_on ()) {// every layer that reaches here: its routed entries and where they ran 7321I8Count & c = i8_count (); 7322++ c .layers ; 7323c .ent += rows_local ; 7324if (i8_l ) {++ c .layers_i8 ;c .ent_i8 += rows_local ; } 7325if (i8_few ) {++ c .layers_few ;c .ent_few += rows_local ; }// (the few-rows route's layers are counted in the int8 ones too) 7326 } 7327// the routed experts' input: `mixed`, or (APR) its rotated copy, which the peer / the layer 7328// split's helper also take (one rotation for both cards; `mixed` itself feeds the shared expert) 7329const float * xsrc = m .mixed ; 7330if (fz_staged ) { 7331fz_staged_l = true; 7332if (!use_mmq ) {// a fused-only layer (the class default, or STRATA_PF_STAGED_FO=1): said once 7333#if !defined(STRATA_PF_OWN_ONLY )// a build without MMQ says it in its start-up line (own_only_line.hpp) 7334static bool said_fo = false; 7335if (!said_fo ) { 7336said_fo = true; 7337 std::fprintf (stderr ,"strata prefill: a layer with no MMQ tile reads prompt pieces below %lld tokens on the fused kernels' staged group " 7338"entry, routed experts only. STRATA_PF_STAGED_FO=0 keeps the old rule.\n" , (long long )stream_all_min ()); 7339 } 7340#endif 7341 } 7342 fused::quantize_act_native (m .mixed ,T ,N ,m .Xq ,m .cs ); 7343 } 7344if (i8_l ) {// the layer's T tokens as q8_1 rows, once (the grouped kernels' activations) 7345if (static bool said = false; !said ) { 7346said = true; 7347if (strata::kernels::native_expert_i8_by_default ()) { 7348#if !defined(STRATA_PF_OWN_ONLY )// a build without MMQ says what runs in its start-up line (own_only_line.hpp), per chunk size: this one would be wrong above the P100's stream floor 7349 std::fprintf (stderr ,"strata: prompt experts on our own int8 kernels (the default of this build or graphics card; STRATA_EXPERT_I8=0 goes back to the old kernels)\n" ); 7350#endif 7351 }else 7352 std::fprintf (stderr ,"strata: prompt experts on our own int8 dot-product kernels (STRATA_EXPERT_I8=1)\n" ); 7353 } 7354if (m .fr_xq == nullptr || m .fr_xq_rows < T ) { 7355if (m .fr_xq )cudaFree (m .fr_xq ); 7356m .fr_xq = nullptr ; 7357m .fr_xq_rows = 0 ; 7358if (cudaMalloc (& m .fr_xq , (size_t )T * (size_t ) (N /32 )* 36 )!= cudaSuccess ) { 7359m .fr_xq = nullptr ; 7360err = "prefill: int8 experts: no memory for the activations" ; 7361return false; 7362 } 7363m .fr_xq_rows = T ; 7364 } 7365if (m .i8_rec == nullptr && cudaMalloc ((void ** )& m .i8_rec , strata::prefill::i8grp::kRecBytes )!= cudaSuccess ) { 7366m .i8_rec = nullptr ; 7367err = "prefill: int8 experts: no memory for the group record" ; 7368return false; 7369 } 7370if (i8_few )// the few-rows route: the grouped kernels read q8_1 with FP16 scales (the same 36 bytes a block) 7371 strata::kernels::quantize_q8_1_rows (m .mixed ,T ,N ,m .fr_xq ,m .cs ); 7372else 7373 strata::kernels::native_expert_i8_quantize (m .mixed ,T ,N ,m .fr_xq ,m .cs );// the kernels' own image (FP32 scales), 36 bytes per block as q8_1 7374 } 7375if (use_mmq || fz_staged ) {// (fz_staged without use_mmq: a fused-only layer with the entry on (staged_fo_on(), staged_fo_rule.hpp); the block builds the group bounds) 7376// step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed` (APR: 7377// from its rotated copy `Xr`): each token quantized once and written to its K rows 7378// (slot_dev, the inverse of src_dev). 7379// NVFP4 w4a4 activations carry a per-row scale (Xscale): that mode keeps the gather. 7380if (wmma_l ) {// FP16 rows (pf_wmma); APR: Hadamard-folded gate/up take H, rotated in fp16 storage as the FP16 path does 7381gather_rows16 (m .mixed_h ,m .src_dev ,m .Xs ,T * K ,N ,m .cs ); 7382if (had_gu ) strata::kernels::hadamard_rows_f16 (m .Xs ,T * K ,N ,had_block ,had_sx ,m .cs ); 7383 }else { 7384if (had_gu ) { 7385 strata::kernels::hadamard_rows (m .mixed ,m .Xr ,T ,N ,had_block ,had_sx ,m .cs ); 7386xsrc = m .Xr ; 7387 } 7388if (fz_staged ) { 7389// (P4-SMALL: Xq already holds the per-token int8 rows, above) 7390 }else if (i8_l ) { 7391// (OWN-I8: the tokens' q8_1 rows are in fr_xq, above; MMQ's per-row copy is not made) 7392 }else if (mmq::fp4_activations (mmq_gt )) 7393 mmq::quantize (xsrc ,m .src_dev ,m .Xq ,mmq_gt ,N ,N ,T * K ,m .cs ,m .Xscale ); 7394else 7395 mmq::quantize_scatter (xsrc ,m .slot_dev ,m .src_dev ,m .Xq ,mmq_gt ,N ,N ,T , (int )K ,m .cs ); 7396 } 7397// each group's rows: absolute bounds (gate/up reads the layer's rows), relative ones (down 7398// reads the group's own quantized H) 7399const size_t n = order .size (),ng = (n + MMQ_GROUP - 1 ) /MMQ_GROUP ; 7400m .bounds_host .resize (n + 1 + ng * (MMQ_GROUP + 1 )); 7401for (size_t j = 0 ;j < n ;++ j )m .bounds_host [j ]= m .off [(size_t )order [j ]]; 7402m .bounds_host [n ]= (int32_t )rows_local ; 7403for (size_t g = 0 ;g < ng ;++ g ) 7404for (size_t i = 0 ;i <=MMQ_GROUP ;++ i ) 7405m .bounds_host [n + 1 + g * (MMQ_GROUP + 1 )+ i ]= 7406m .bounds_host [std::min (n ,g * MMQ_GROUP + i )]- m .bounds_host [g * MMQ_GROUP ]; 7407// STRATA_PF_GROUP_SCRATCH: a group whose rows pass the scratch's cap runs as sub-ranges of 7408// its experts, each with its own relative bounds (appended); every expert fits alone 7409m .sub_first .assign (ng ,-1 ); 7410m .sub .clear (); 7411if (m .group_cap > 0 ) { 7412for (size_t g = 0 ;g < ng ;++ g ) { 7413const size_t j0 = g * MMQ_GROUP ,j1 = std::min (n ,j0 + MMQ_GROUP ); 7414if (m .bounds_host [j1 ]- m .bounds_host [j0 ] <=m .group_cap )continue ; 7415m .sub_first [g ]= (int32_t )m .sub .size (); 7416for (size_t a = j0 ;a < j1 ;) { 7417size_t b = a + 1 ; 7418while (b < j1 && m .bounds_host [b + 1 ]- m .bounds_host [a ] <=m .group_cap )++ b ; 7419const int32_t rel = (int32_t )m .bounds_host .size (); 7420for (size_t i = a ;i <=b ;++ i )m .bounds_host .push_back (m .bounds_host [i ]- m .bounds_host [a ]); 7421m .sub .push_back ({(int32_t )a , (int32_t )b ,rel }); 7422a = b ; 7423 } 7424 } 7425if (m .bounds_host .size ()> bounds_ints (m .g -> n_expert )) { 7426err = "prefill: STRATA_PF_GROUP_SCRATCH's bounds table overflowed" ; 7427return false; 7428 } 7429 } 7430if (grp_mapped ) { 7431int32_t * bh = m .grp_host + 3 * m .grp_tk ; 7432 std::memcpy (bh ,m .bounds_host .data (),m .bounds_host .size ()* 4 ); 7433copy_i32 (m .bounds_dev ,m .grp_dev + 3 * m .grp_tk , (int64_t )m .bounds_host .size (),m .cs ); 7434 }else { 7435if (m .up_ring .h2d (m .bounds_dev ,m .bounds_host .data (),m .bounds_host .size ()* 4 ,m .cs )!= cudaSuccess ) {// #1996 7436err = "prefill: the group bounds' upload failed" ; 7437return false; 7438 } 7439 } 7440// STRATA_MMQ_WS=1 (moe_ws.hpp, GP100): a layer whose routed experts are ALL resident, on this 7441// GPU alone (no peer, CPU or streamed share), runs gate/up and down as one weight-stationary 7442// launch each, with ONE swiglu_quant over all its rows in between, instead of a gate/up, 7443// swiglu and down MMQ launch per 16-expert group - the same GU, H and Dm bits. The experts 7444// are read where they lie in the expert cache (offsets from its base). Only where both 7445// products beat the per-group MMQ at this layer's rows per expert, H can be q8_1 in one pass 7446// (no Hadamard, NVFP4 or FP4 rows; not STRATA_DBG_NAN, which reads H in floats), and not the 7447// fused layout (its Hq holds stream_all_min() - 1 tokens' rows). 7448static const bool ws_dbg = std::getenv ("STRATA_DBG_NAN" )!= nullptr ; 7449const double ws_u = n > 0 ? (double )rows_local / (double )n :0.0 ; 7450if (ws::mode ()!= 0 && m .xoff_dev != nullptr && m .ws_chunks != nullptr && n > 0 && !ws_dbg && 7451lay .native && m .cache != nullptr && m .host_res != nullptr && !wmma_l && 7452 !mmq_plan ().direct [(size_t )l ]&& lay .fmt [(size_t )l ].up_off == mmq_gub /2 && 7453order_peer .empty ()&& rows_cpu == 0 && rows_local == T * K && !m .fused_bufs && m .group_cap == 0 && 7454 (!stream_all || seq_start [(size_t )l ]== seq_start [(size_t )l + 1 ])&& !had_gu && !had_d && 7455 !lay .fmt [(size_t )l ].tail_off && !mmq::fp4_activations (mmq_gt )&& 7456 !mmq::fp4_activations (mmq_dt )&& mmq::swiglu_quant_ok (mmq_dt )&& 7457 ws::supported (mmq_gt ,mmq_dt )&& ws::faster (mmq_gt ,ws_u )&& ws::faster (mmq_dt ,ws_u )) { 7458const uint8_t * ip_base = m .cache -> device_slot (0 ); 7459m .xoff_host .assign (n ,-1 ); 7460bool all = true;// every expert resident 7461uint64_t at = 0 ;// their offsets' low bits 7462for (size_t j = 0 ;j < n && all ;++ j ) { 7463const int32_t s = m .host_res [(size_t )l * m .g -> n_expert + order [j ]]; 7464if (s < 0 ) {all = false;break ; } 7465m .xoff_host [j ]= (int64_t ) (m .cache -> device_slot (s )- ip_base ); 7466at |= (uint64_t )m .xoff_host [j ]; 7467 } 7468ws_layer = all && ((uint64_t ) (uintptr_t )ip_base |at |lay .fmt [(size_t )l ].down_off ) % ws::kAlign == 0 ; 7469if (ws_layer ) { 7470if (static bool said_ws = false; !said_ws ) { 7471said_ws = true; 7472 std::fprintf (stderr ,"strata prefill: a resident layer's experts weight-stationary, one " 7473"launch per product (STRATA_MMQ_WS=1)\n" ); 7474 } 7475// the offsets after the bounds in the mapped table, the chunks after them (16-byte 7476// aligned); or the host copies through pinned slots 7477const size_t xo = 3 * m .grp_tk + bounds_ints (m .g -> n_expert ); 7478 ws::Chunk * ch = nullptr ; 7479if (grp_mapped ) { 7480int32_t * xh = m .grp_host + xo ; 7481 std::memcpy (xh ,m .xoff_host .data (),n * sizeof (int64_t )); 7482copy_i32 ((int32_t * )m .xoff_dev ,m .grp_dev + xo , (int64_t ) (2 * n ),m .cs ); 7483ch = (ws::Chunk * ) (m .grp_host + (xo + 2 * m .g -> n_expert + 3 ) /4 * 4 ); 7484 }else { 7485m .ws_chunks_host .resize (ws::max_chunks (T * K ,m .g -> n_expert )); 7486ch = m .ws_chunks_host .data (); 7487 } 7488wl .nchunks = (int64_t ) ws::chunks (order .data (),n ,m .cnt .data (),m .bounds_host .data (),ch ); 7489if (grp_mapped ) { 7490copy_i32 ((int32_t * )m .ws_chunks ,m .grp_dev + ((int32_t * )ch - m .grp_host ),4 * wl .nchunks ,m .cs ); 7491 }else if (m .up_ring .h2d (m .xoff_dev ,m .xoff_host .data (),n * sizeof (int64_t ),m .cs )!= cudaSuccess || 7492m .up_ring .h2d (m .ws_chunks ,ch , (size_t )wl .nchunks * sizeof (ws::Chunk ),m .cs )!= cudaSuccess ) { 7493err = "prefill: the weight-stationary tables' upload failed" ; 7494return false; 7495 } 7496wl .gu_type = mmq_gt ;wl .d_type = mmq_dt ;wl .w = ip_base ;wl .xoff = m .xoff_dev ; 7497wl .down_off = (int64_t )lay .fmt [(size_t )l ].down_off ;wl .chunks = m .ws_chunks ; 7498wl .rows = T * K ;wl .n = (int )n ;wl .xq = m .Xq ;wl .gu = m .GU ;wl .hq = m .Hq ;wl .dm = m .Dm ; 7499 } 7500 } 7501 }else if (i8_l ) { 7502// (the int8 kernels read the tokens' q8_1 rows through src_dev: no per-row copy at all) 7503 }else { 7504gather_rows16 (m .mixed_h ,m .src_dev ,m .Xs ,T * K ,N ,m .cs ); 7505// APR: Hadamard-folded gate/up take H (s * x); Xs is this layer's private gathered copy 7506// (rotated in fp16 storage, fp32 arithmetic: see the down projection's note below) 7507if (had_gu ) strata::kernels::hadamard_rows_f16 (m .Xs ,T * K ,N ,had_block ,had_sx ,m .cs ); 7508 } 7509// multi-GPU: the peer's share, enqueued before the primary's own experts so both cards work at once 7510peer_now = use_mmq && !order_peer .empty (); 7511if (peer_now ) { 7512PeerPrefill & P = * m .pp ; 7513// the host route's copies beside the compute stream: the primary's own experts start at once 7514// (mixed_h and w are rewritten only after this layer's combine, which waits for the peer) 7515cudaStream_t xs = m .cs ; 7516if (P .x_stream != nullptr ) { 7517cudaEventRecord (P .ev_x ,m .cs ); 7518cudaStreamWaitEvent (P .x_stream ,P .ev_x ,0 ); 7519xs = P .x_stream ; 7520 } 7521if (!P .p2p && P .f16 )cudaMemcpyAsync (P .host_x16 ,m .mixed_h , (size_t )T * N * 2 ,cudaMemcpyDeviceToHost ,xs ); 7522else if (!P .p2p )cudaMemcpyAsync (P .host_x ,m .mixed , (size_t )T * N * 4 ,cudaMemcpyDeviceToHost ,xs ); 7523if (P .sums ) {// the routing weights, and each peer row's routed pair (t * K + k) 7524cudaMemcpyAsync (P .host_w ,m .w , (size_t )T * K * 4 ,cudaMemcpyDeviceToHost ,xs ); 7525for (int64_t i = 0 ;i < T * K ;++ i ) 7526if (const int32_t r = slot_h [(size_t )i ];r >=peer_at )P .host_pair [r - peer_at ]= (int32_t )i ; 7527 } 7528cudaEventRecord (P .ev_in ,xs ); 7529int prevd = 0 ; 7530cudaGetDevice (& prevd ); 7531cudaSetDevice (P .dev ); 7532const cudaStream_t ps = P .s ; 7533cudaStreamWaitEvent (ps ,P .ev_in ,0 ); 7534if (P .out_pending ) {cudaStreamWaitEvent (ps ,P .ev_done ,0 );P .out_pending = false; } 7535pe .mark (kPeMoeIn ,ps ); 7536if (P .p2p )cudaMemcpyPeerAsync (P .mixed ,P .dev ,m .mixed ,prevd , (size_t )T * N * 4 ,ps ); 7537else if (P .f16 )f16_to_f32_wide (P .mixed ,P .host_x16 ,T * N ,ps ); 7538else copy_f32_wide (P .mixed ,P .host_x ,T * N ,ps ); 7539P .back_at = peer_at ; 7540P .back_rows = rows_peer ; 7541if (P .p2p ) { 7542// multi-GPU: the mapped table when on; src_host (a pageable vector) goes up from a pinned slot (#1996) 7543if ((grp_mapped ?cudaMemcpyAsync (P .src ,src_h + peer_at , (size_t )rows_peer * 4 , 7544cudaMemcpyHostToDevice ,ps ) 7545 :P .up_ring .h2d (P .src ,src_h + peer_at , (size_t )rows_peer * 4 ,ps ))!= 7546cudaSuccess ) { 7547cudaSetDevice (prevd ); 7548err = "prefill: the peer's routing table upload failed" ; 7549return false; 7550 } 7551 }else { 7552 std::memcpy (P .host_src ,src_h + peer_at , (size_t )rows_peer * 4 ); 7553copy_i32 (P .src ,P .host_src ,rows_peer ,ps ); 7554 } 7555const size_t n = order_peer .size (); 7556if (P .sums ) { 7557copy_f32_wide (P .wk ,P .host_w ,T * K ,ps ); 7558copy_i32 (P .pair ,P .host_pair ,rows_peer ,ps ); 7559cudaMemsetAsync (P .sum ,0 , (size_t )T * N * 4 ,ps ); 7560 } 7561if (P .compact ) { 7562// groups of up to MMQ_GROUP experts and at most G rows, each computed from its own rows 7563P .groups .clear (); 7564 { 7565size_t g0 = 0 ; 7566int64_t gr = 0 ; 7567for (size_t j = 0 ;j < n ;++ j ) { 7568const int64_t c = m .cnt [(size_t )order_peer [j ]]; 7569if (j > g0 && (j - g0 == (size_t )MMQ_GROUP || gr + c > P .G )) {P .groups .push_back ({g0 ,j });g0 = j ;gr = 0 ; } 7570gr += c ; 7571 } 7572if (n > g0 )P .groups .push_back ({g0 ,n }); 7573 } 7574const size_t ng = P .groups .size (); 7575P .bounds_host .resize (n + 1 + ng * (MMQ_GROUP + 1 )); 7576for (size_t j = 0 ;j < n ;++ j )P .bounds_host [j ]= m .off [(size_t )order_peer [j ]]- (int32_t )peer_at ; 7577P .bounds_host [n ]= (int32_t )rows_peer ; 7578for (size_t g2 = 0 ;g2 < ng ;++ g2 ) 7579for (size_t i = 0 ;i <=MMQ_GROUP ;++ i ) 7580P .bounds_host [n + 1 + g2 * (MMQ_GROUP + 1 )+ i ]= 7581P .bounds_host [std::min (P .groups [g2 ].second ,P .groups [g2 ].first + i )]- 7582P .bounds_host [P .groups [g2 ].first ]; 7583if (P .p2p || P .bounds_host .size ()> PeerPrefill ::kHostBounds ) { 7584if (P .up_ring .h2d (P .bounds ,P .bounds_host .data (),P .bounds_host .size ()* 4 ,ps )!= cudaSuccess ) {// #1996 7585cudaSetDevice (prevd ); 7586err = "prefill: the peer's group bounds upload failed" ; 7587return false; 7588 } 7589 }else { 7590 std::memcpy (P .host_bounds ,P .bounds_host .data (),P .bounds_host .size ()* 4 ); 7591copy_i32 (P .bounds ,P .host_bounds , (int64_t )P .bounds_host .size (),ps ); 7592 } 7593if (P .sums && P .gather ) {// each group's tokens, their row lists in the experts' order 7594P .adds_at .resize (ng ); 7595P .ntok .resize (ng ); 7596size_t at = 0 ; 7597for (size_t g2 = 0 ;g2 < ng ;++ g2 ) { 7598const int32_t r0 = P .bounds_host [P .groups [g2 ].first ],r1 = P .bounds_host [P .groups [g2 ].second ]; 7599P .touched .clear (); 7600for (int32_t r = r0 ;r < r1 ;++ r ) { 7601const int32_t t = P .host_pair [r ] / (int32_t )K ; 7602if (P .tcur [(size_t )t ]++ == 0 )P .touched .push_back (t ); 7603 } 7604const size_t nt = P .touched .size (); 7605int32_t * a = P .host_adds + at ;// [tokens nt | starts nt + 1 | rows] 7606a [nt ]= 0 ; 7607for (size_t i = 0 ;i < nt ;++ i ) { 7608const int32_t t = P .touched [i ]; 7609a [i ]= t ; 7610a [nt + 1 + i ]= a [nt + i ]+ P .tcur [(size_t )t ]; 7611P .tcur [(size_t )t ]= a [nt + i ];// the fill cursor 7612 } 7613int32_t * list = a + 2 * nt + 1 ; 7614for (int32_t r = r0 ;r < r1 ;++ r ) 7615list [P .tcur [(size_t ) (P .host_pair [r ] / (int32_t )K )]++ ]= r ; 7616for (int32_t t :P .touched )P .tcur [(size_t )t ]= 0 ; 7617P .adds_at [g2 ]= at ; 7618P .ntok [g2 ]= (int32_t )nt ; 7619at += 2 * nt + 1 + (size_t ) (r1 - r0 ); 7620 } 7621if (at > P .adds_cap ) { 7622err = "prefill: the peer's group tables overflow" ; 7623cudaSetDevice (prevd ); 7624return false; 7625 } 7626copy_i32 (P .adds ,P .host_adds , (int64_t )at ,ps ); 7627 } 7628pe .mark (kPeMoeGemm ,ps ); 7629const auto & f = lay .fmt [(size_t )l ]; 7630for (size_t g2 = 0 ;g2 < ng ;++ g2 ) { 7631const size_t j0 = P .groups [g2 ].first ,j1 = P .groups [g2 ].second ; 7632const int ngx = (int ) (j1 - j0 ); 7633int64_t maxr = 0 ; 7634for (size_t j = j0 ;j < j1 ;++ j ) { 7635const int32_t e = order_peer [j ]; 7636maxr = std::max < int64_t > (maxr ,m .cnt [(size_t )e ]); 7637const uint8_t * bd = nullptr ; 7638int psl = -1 ; 7639if (on_peer [(size_t )e ]== 2 ) {// from the peer's ring 7640p_release_to (l ,e ,ps ); 7641if (P .pk >=P .pseq_start [(size_t )l + 1 ]|| P .pseq [P .pk ].e != e ) { 7642err = "prefill: a peer-streamed expert is not next in the peer's ring" ; 7643cudaSetDevice (prevd ); 7644return false; 7645 } 7646psl = (int ) (P .pk % (size_t )P .RP ); 7647cudaStreamWaitEvent (ps ,P .pcopied [(size_t )psl ],0 ); 7648bd = P .pstage [(size_t )psl ]; 7649++ P .ps_experts ; 7650 }else { 7651bd = P .peer -> slot_ptr (l ,e ); 7652 } 7653const size_t q = j - j0 ; 7654if (lay .native ) 7655 mmq::gather_native (bd ,bd + f .up_off ,mmq_gub /2 ,bd + f .down_off ,mmq_db , 7656P .grp_gu + q * mmq_gub ,P .grp_d + q * mmq_db ,ps ); 7657else 7658 mmq::gather_strata_q2 (bd ,P .grp_gu + q * mmq_gub ,P .grp_d + q * mmq_db ,ps ); 7659if (psl >=0 ) {// the slot is free once gathered 7660cudaEventRecord (P .pused [(size_t )psl ],ps ); 7661++ P .pk ; 7662p_issue_until (P .pk + (size_t )P .RP ); 7663 } 7664 } 7665const int64_t r0 = P .bounds_host [j0 ],nr = P .bounds_host [j1 ]- r0 ; 7666if (nr <=0 )continue ; 7667const int32_t * rel = P .bounds + n + 1 + g2 * (MMQ_GROUP + 1 ); 7668cudaMemsetAsync (P .grp_gu + (size_t )ngx * mmq_gub ,0 ,MMQ_TAIL ,ps ); 7669cudaMemsetAsync (P .grp_d + (size_t )ngx * mmq_db ,0 ,MMQ_TAIL ,ps ); 7670 mmq::quantize (P .mixed ,P .src + r0 ,P .Xq_g ,mmq_gt ,N ,N ,nr ,ps ); 7671 mmq::Product gu ; 7672gu .w = P .grp_gu ;gu .type = mmq_gt ;gu .w_rows = kFF2 ;gu .w_cols = N ;gu .expert_bytes = mmq_gub ; 7673gu .n = ngx ;gu .xq = P .Xq_g ;gu .bounds = rel ;gu .ids = P .ident ; 7674gu .total_rows = nr ;gu .max_rows = maxr ;gu .dst = P .GU_g ;gu .ld_dst = kFF2 ; 7675P .run_ctx -> run (gu ,ps ); 7676 mmq::swiglu (P .GU_g ,P .H_g ,nr ,kFF , !lay .native ,ps ); 7677if (had_d )// APR: folded down weights take H (s * h), on this card as on the primary 7678 strata::kernels::hadamard_rows (P .H_g ,P .H_g ,nr ,kFF ,had_block ,P .had_sh [(size_t )l ],ps ); 7679 mmq::quantize (P .H_g ,nullptr ,P .Hq_g ,mmq_dt ,kFF ,kFF ,nr ,ps ); 7680const int b = (int ) (g2 & 1 ); 7681if (P .dm_live [b ])cudaStreamWaitEvent (ps ,P .ev_dm [b ],0 );// its last rows have left 7682 mmq::Product dn ; 7683dn .w = P .grp_d ;dn .type = mmq_dt ;dn .w_rows = N ;dn .w_cols = kFF ;dn .expert_bytes = mmq_db ; 7684dn .n = ngx ;dn .xq = P .Hq_g ;dn .bounds = rel ; 7685dn .ids = P .ident ;dn .total_rows = nr ;dn .max_rows = maxr ;dn .dst = P .Dm_b [b ]; 7686dn .ld_dst = N ; 7687P .run_ctx -> run (dn ,ps ); 7688if (P .sums && P .gather ) {// into the per-token sums, one launch for the group 7689const int32_t * a = P .adds + P .adds_at [g2 ]; 7690const int64_t nt = P .ntok [g2 ]; 7691peer_gather_add (P .sum ,P .Dm_b [b ],r0 ,P .wk ,P .pair ,a ,a + nt ,a + 2 * nt + 1 ,nt ,ps ); 7692continue ; 7693 } 7694if (P .sums ) {// into the per-token sums on this stream: Dm_b[b] is free after it 7695for (size_t j = j0 ;j < j1 ;++ j ) 7696peer_scatter_add (P .sum ,P .Dm_b [b ]+ (size_t ) (P .bounds_host [j ]- r0 )* N ,P .wk , 7697P .pair + P .bounds_host [j ],P .bounds_host [j + 1 ]- P .bounds_host [j ],ps ); 7698continue ; 7699 } 7700cudaEventRecord (P .ev_grp [g2 %PeerPrefill ::kGrpEv ],ps ); 7701cudaStreamWaitEvent (P .s_out ,P .ev_grp [g2 %PeerPrefill ::kGrpEv ],0 ); 7702if (P .p2p ) 7703cudaMemcpyPeerAsync (m .Dm + (size_t ) (peer_at + r0 )* N ,prevd ,P .Dm_b [b ],P .dev , 7704 (size_t )nr * N * 4 ,P .s_out ); 7705else // the primary reads them when it combines (below) 7706cudaMemcpyAsync (P .host_rows + (size_t )r0 * N ,P .Dm_b [b ], (size_t )nr * N * 4 , 7707cudaMemcpyDeviceToHost ,P .s_out ); 7708cudaEventRecord (P .ev_dm [b ],P .s_out ); 7709P .dm_live [b ]= true; 7710 } 7711 }else { 7712const size_t ng = (n + MMQ_GROUP - 1 ) /MMQ_GROUP ; 7713P .bounds_host .resize (n + 1 + ng * (MMQ_GROUP + 1 )); 7714for (size_t j = 0 ;j < n ;++ j )P .bounds_host [j ]= m .off [(size_t )order_peer [j ]]- (int32_t )peer_at ; 7715P .bounds_host [n ]= (int32_t )rows_peer ; 7716for (size_t g2 = 0 ;g2 < ng ;++ g2 ) 7717for (size_t i = 0 ;i <=MMQ_GROUP ;++ i ) 7718P .bounds_host [n + 1 + g2 * (MMQ_GROUP + 1 )+ i ]= 7719P .bounds_host [std::min (n ,g2 * MMQ_GROUP + i )]- P .bounds_host [g2 * MMQ_GROUP ]; 7720if (P .p2p || P .bounds_host .size ()> PeerPrefill ::kHostBounds ) { 7721if (P .up_ring .h2d (P .bounds ,P .bounds_host .data (),P .bounds_host .size ()* 4 ,ps )!= cudaSuccess ) {// #1996 7722cudaSetDevice (prevd ); 7723err = "prefill: the peer's group bounds upload failed" ; 7724return false; 7725 } 7726 }else { 7727 std::memcpy (P .host_bounds ,P .bounds_host .data (),P .bounds_host .size ()* 4 ); 7728copy_i32 (P .bounds ,P .host_bounds , (int64_t )P .bounds_host .size (),ps ); 7729 } 7730 mmq::quantize (P .mixed ,P .src ,P .Xq ,mmq_gt ,N ,N ,rows_peer ,ps ); 7731pe .mark (kPeMoeGemm ,ps ); 7732const auto & f = lay .fmt [(size_t )l ]; 7733for (size_t j = 0 ;j < n ;++ j ) { 7734const int32_t e = order_peer [j ]; 7735const uint8_t * bd = P .peer -> slot_ptr (l ,e ); 7736const size_t q = j %MMQ_GROUP ; 7737if (lay .native ) 7738 mmq::gather_native (bd ,bd + f .up_off ,mmq_gub /2 ,bd + f .down_off ,mmq_db , 7739P .grp_gu + q * mmq_gub ,P .grp_d + q * mmq_db ,ps ); 7740else 7741 mmq::gather_strata_q2 (bd ,P .grp_gu + q * mmq_gub ,P .grp_d + q * mmq_db ,ps ); 7742if (q + 1 < MMQ_GROUP && j + 1 < n )continue ; 7743const size_t j0 = j - q ,g2 = j0 /MMQ_GROUP ; 7744const int ngx = (int ) (q + 1 ); 7745const int64_t r0 = P .bounds_host [j0 ],nr = P .bounds_host [j + 1 ]- r0 ; 7746int64_t maxr = 0 ; 7747for (size_t i = j0 ;i <=j ;++ i )maxr = std::max < int64_t > (maxr ,m .cnt [(size_t )order_peer [i ]]); 7748cudaMemsetAsync (P .grp_gu + (size_t )ngx * mmq_gub ,0 ,MMQ_TAIL ,ps ); 7749cudaMemsetAsync (P .grp_d + (size_t )ngx * mmq_db ,0 ,MMQ_TAIL ,ps ); 7750 mmq::Product gu ; 7751gu .w = P .grp_gu ;gu .type = mmq_gt ;gu .w_rows = kFF2 ;gu .w_cols = N ;gu .expert_bytes = mmq_gub ; 7752gu .n = ngx ;gu .xq = P .Xq ;gu .bounds = P .bounds + j0 ;gu .ids = P .ident ; 7753gu .total_rows = rows_peer ;gu .max_rows = maxr ;gu .dst = P .GU ;gu .ld_dst = kFF2 ; 7754P .run_ctx -> run (gu ,ps ); 7755 mmq::swiglu (P .GU + r0 * kFF2 ,P .H + r0 * kFF ,nr ,kFF , !lay .native ,ps ); 7756if (had_d )// APR: as above 7757 strata::kernels::hadamard_rows (P .H + r0 * kFF ,P .H + r0 * kFF ,nr ,kFF ,had_block , 7758P .had_sh [(size_t )l ],ps ); 7759 mmq::quantize (P .H + r0 * kFF ,nullptr ,P .Hq ,mmq_dt ,kFF ,kFF ,nr ,ps ); 7760 mmq::Product dn ; 7761dn .w = P .grp_d ;dn .type = mmq_dt ;dn .w_rows = N ;dn .w_cols = kFF ;dn .expert_bytes = mmq_db ; 7762dn .n = ngx ;dn .xq = P .Hq ;dn .bounds = P .bounds + n + 1 + g2 * (MMQ_GROUP + 1 ); 7763dn .ids = P .ident ;dn .total_rows = nr ;dn .max_rows = maxr ;dn .dst = P .Dm + r0 * N ; 7764dn .ld_dst = N ; 7765P .run_ctx -> run (dn ,ps ); 7766if (P .out_pipe && nr > 0 ) {// this group's rows go back while the next group computes 7767cudaEventRecord (P .ev_grp [g2 ],ps ); 7768cudaStreamWaitEvent (P .s_out ,P .ev_grp [g2 ],0 ); 7769cudaMemcpyPeerAsync (m .Dm + (size_t ) (peer_at + r0 )* N ,prevd ,P .Dm + (size_t )r0 * N , 7770P .dev , (size_t )nr * N * 4 ,P .s_out ); 7771 } 7772 } 7773 } 7774pe .mark (kPeMoeOut ,ps ); 7775if (P .sums ) {// the sums go back: T x N 7776if (P .f16 ) { 7777sums_to_f16 (P .sum ,P .sum16 ,T * N ,ps ); 7778cudaMemcpyAsync (P .host_sum16 ,P .sum16 , (size_t )T * N * 2 ,cudaMemcpyDeviceToHost ,ps ); 7779 }else { 7780cudaMemcpyAsync (P .host_sum ,P .sum , (size_t )T * N * 4 ,cudaMemcpyDeviceToHost ,ps ); 7781 } 7782cudaEventRecord (P .ev_done ,ps ); 7783P .out_pending = true; 7784 }else if (P .out_pipe ) { 7785cudaEventRecord (P .ev_done ,P .s_out ); 7786P .out_pending = true; 7787 }else { 7788cudaMemcpyPeerAsync (m .Dm + (size_t )peer_at * N ,prevd ,P .Dm ,P .dev , (size_t )rows_peer * N * 4 ,ps ); 7789cudaEventRecord (P .ev_done ,ps ); 7790 } 7791pe .mark (kPeIdle ,ps ); 7792cudaSetDevice (prevd ); 7793++ P .layers ; 7794P .experts += (int64_t )n ; 7795P .rows += rows_peer ; 7796 } 7797if (ps_on ) {// multi-GPU: this layer's peer-ring entries the routing did not pick give their slots back 7798int pd = 0 ; 7799cudaGetDevice (& pd ); 7800cudaSetDevice (m .pp -> dev ); 7801p_release_to (l , (int32_t )m .g -> n_expert ,m .pp -> s ); 7802cudaSetDevice (pd ); 7803 } 7804// STRATA_PREFILL_GROUP_GATHER=0: one gather, one wait and one record per expert. 7805static const bool group_env = [] { 7806const char * v = std::getenv ("STRATA_PREFILL_GROUP_GATHER" ); 7807return v == nullptr || std::atoi (v )!= 0 ; 7808 }(); 7809const bool group_gather = group_env && stream_all && lay .native && ((use_mmq && MMQ_GROUP <= mmq::kGatherGroupMax )|| i8_l ); 7810// The staged walk (a short prompt) groups too, resident and staged experts alike: its ring is 7811// then STAGE_GRP slots, two groups, and it stages no further ahead than the open group allows, 7812// so a group's staged slots stay unread-over until its flush (one wait on the last copy, one 7813// event releasing them all, as in the streamed walk). 7814const bool group_resident = group_env && !stream_all && lay .native && (((use_mmq || fz_staged )&& MMQ_GROUP <= mmq::kGatherGroupMax )|| i8_l ); 7815const bool gg_now = group_gather || group_resident ; 7816const int stage_n = group_resident ?STAGE_GRP :STAGE ; 7817// Stage ahead: the copy stream moves blobs host -> device while the compute stream works. 7818int stage_next = 0 ; 7819 std::vector < int > stage_of (order .size (),-1 ); 7820// the unpinned ones are copied to pinned buffers by the stager's threads, in this order 7821 std::vector < int > job_of (order .size (),-1 ); 7822if (!stream_all ) { 7823 std::vector < Stager ::Job > js ; 7824for (size_t j = 0 ;j < order .size ();++ j ) { 7825const int32_t e = order [j ]; 7826if (m .host_res && m .cache && m .host_res [(size_t )l * m .g -> n_expert + e ] >=0 )continue ; 7827if (m .src -> pinned (l ,e ))continue ; 7828job_of [j ]= (int )js .size (); 7829if (m .src -> transient (l ,e )) {// CS-T: copied by the source 7830js .push_back ({nullptr , (size_t )lay .blob_bytes (l ),m .src , (int32_t )l ,e }); 7831continue ; 7832 } 7833const uint8_t * b = m .src -> blob_stable (l ,e ); 7834if (!b ) {err = "prefill: expert source has no blob" ;return false; } 7835js .push_back ({b , (size_t )lay .blob_bytes (l )}); 7836 } 7837if (m .warmer ) { 7838 std::vector < int64_t > cur ; 7839for (size_t j = 0 ;j < order .size ();++ j ) 7840if (job_of [j ] >=0 )cur .push_back (order [j ]); 7841m .warm_prev [(size_t )l ]= cur ; 7842m .warmer -> submit (l , std::move (cur )); 7843if (l + 1 < m .g -> n_layers ) { 7844 std::vector < int64_t > nxt ; 7845for (int64_t e :m .warm_prev [(size_t ) (l + 1 )]) { 7846if (m .host_res && m .cache && m .host_res [(size_t ) (l + 1 )* m .g -> n_expert + e ] >=0 ) 7847continue ; 7848if (m .src -> pinned (l + 1 , (int32_t )e ))continue ; 7849nxt .push_back (e ); 7850 } 7851m .warmer -> submit (l + 1 , std::move (nxt )); 7852 } 7853 } 7854m .stager -> start (std::move (js )); 7855 } 7856StagerDone stager_done {stream_all ?nullptr :m .stager .get ()}; 7857auto stage_one = [& ](size_t j )-> bool { 7858const int32_t e = order [j ]; 7859const bool resident = m .host_res && m .cache && m .host_res [(size_t )l * m .g -> n_expert + e ] >=0 ; 7860if (resident )return true; 7861const int sl = stage_next ; 7862stage_next = (stage_next + 1 ) %stage_n ; 7863const auto th = Clock ::now (); 7864const bool pinned = m .src -> pinned (l ,e );// pinned: never transient 7865const uint8_t * b = pinned ?m .src -> blob_stable (l ,e ) :nullptr ; 7866if (pinned && !b ) {err = "prefill: expert source has no blob" ;return false; } 7867if (pinned ) { 7868// DMA straight from the page-locked arena: the copy stream only waits for the slot 7869if (m .stage_live [sl ])cudaStreamWaitEvent (m .copy ,m .used [m .used_of [sl ]],0 ); 7870cudaMemcpyAsync (m .stage_dev [sl ],b , (size_t )lay .blob_bytes (l ),cudaMemcpyHostToDevice ,m .copy ); 7871++ stats_ .experts_dma ; 7872 }else { 7873// copied to a pinned buffer by the stager (waits only if it is behind), then DMA 7874const uint8_t * hb = m .stager -> wait (job_of [j ]); 7875if (m .stage_live [sl ])cudaStreamWaitEvent (m .copy ,m .used [m .used_of [sl ]],0 ); 7876cudaMemcpyAsync (m .stage_dev [sl ],hb , (size_t )lay .blob_bytes (l ),cudaMemcpyHostToDevice ,m .copy ); 7877m .stager -> issued_one (job_of [j ],m .copy ); 7878 } 7879cudaEventRecord (m .copied [sl ],m .copy ); 7880m .stage_live [sl ]= true; 7881stage_of [j ]= sl ; 7882stats_ .ms_experts_host += ms_since (th ); 7883++ stats_ .experts_streamed ; 7884return true; 7885 }; 7886// In the streamed walk an MMQ group is gathered in ONE launch, after ONE wait on its last 7887// streamed copy (the copy stream is in order), and its ring slots are released by ONE event. A 7888// wait and a record per expert put ~10 us of GPU bubble each on the compute stream under WDDM 7889// (226 ms of a 32K prompt on an NVFP4 pack). The same bytes into the same group slots. A ring 7890// entry the routing skipped inside an open group first gathers what the group holds so far 7891// (`flush`), so no more than a group's entries are ever held back from the issuer. 7892// STRATA_PREFILL_GROUP_GATHER=0: one gather, one wait and one record per expert. 7893 mmq::GatherGroup gg ; 7894int gg_slots [MMQ_GROUP ]; 7895size_t gg_ents [MMQ_GROUP ];// the streamed walk: their entries (wait_copied) 7896int gg_nslots = 0 ;// ring slots gathered by the next flush 7897size_t cur_entry = 0 ;// the streamed walk: the entry compute() is given 7898 strata::prefill::i8grp::Group g8 ;// OWN-I8: the open group of the int8 kernels (i8_group.hpp), for a layer with i8_l 7899// P4-SMALL (fz_staged): the open group's expert pointers and the layer's native geometry 7900// The layer's tables are built once (fused::group_bounds over every routed expert's rows, below); the experts then 7901// launch in batches: the open batch (fz_b, local experts [fz_j0, ..)) closes at kMaxBatch experts, at MMQ_GROUP experts 7902// from the staging ring (their slots stay held until the launch; the ring has STAGE_GRP), or at the layer's last expert. 7903// Resident experts take no slot, so a layer whose experts all sit in the cache launches ceil(n / kMaxBatch) pairs. 7904 fused::Batch fz_b ; 7905size_t fz_j0 = 0 ; 7906 fused::NativeGeom fz_geom {}; 7907if (fz_staged ) { 7908const auto & f = lay .fmt [(size_t )l ]; 7909fz_geom = fused::NativeGeom {f .gu_type ,f .d_type ,f .gu_row ,f .d_row ,f .up_off ,f .down_off }; 7910 } 7911// STRATA_MMQ_DIRECT=1: a resident expert with guard room in its slot is not gathered - the 7912// group's pointer tables give MMQ each expert's own address (group position q), the others are 7913// gathered at compact positions c = 0..ns-1 of the group buffers, as before (same bytes) 7914const bool direct = use_mmq && lay .native && m .cache && mmq_plan ().direct [(size_t )l ]&& !wmma_l ; 7915 mmq::WeightTab tgu ,td ; 7916 mmq::GuardTab gd ; 7917int ns = 0 ; 7918// `zero`: the MMQ tail zeroed after the gathered experts (the group's last flush); a direct 7919// group's tail is zeroed by prep_group 7920auto flush = [& ](size_t zero ) { 7921if (i8_l ? !g8 .open () :gg .n <=gg .first )return ; 7922const auto & f = lay .fmt [(size_t )l ]; 7923if (gg_nslots > 0 ) {// the copies land in order: the last one covers the others 7924pt .mark (kPfWaitCopy ,cs ); 7925wait_copied (gg_ents [gg_nslots - 1 ], (size_t )gg_slots [gg_nslots - 1 ]); 7926pt .mark (kPfDequant ,cs ); 7927 } 7928if (i8_l ) { 7929// OWN-I8 (i8_group.hpp): the open group's experts [g8.first, g8.n) run here as one launch pair on native_expert_i8, each read 7930// where it is (a flush in the middle of a group, for a skipped ring entry, runs the experts it holds so far as a group of 7931// their own). Their rows are contiguous: bounds relative to the first row go up with the blob pointers; the rows' tokens are 7932// src_dev from there, the rows' places in Dm are the identity from there; H as q8_1 lives in the group's own rows of GU 7933// (the rows of an MMQ gate/up output, unused here: 5,120 bytes a row against the 720 + a few bytes of H that this needs) 7934int64_t i8_nr = 0 ; 7935int i8_ne = 0 ; 7936pt .mark (kPfGemmGU ,cs ); 7937if (!strata::prefill::i8grp::run (i8_L ,g8 ,order .data (),m .off .data (),m .cnt .data (), 7938 [& ](const void * h ,size_t bytes ) {return m .up_ring .h2d (m .i8_rec ,h ,bytes ,m .cs )== cudaSuccess ; }, 7939m .i8_rec ,m .ids_identity ,m .src_dev ,m .fr_xq ,m .GU ,kFF2 ,m .Dm ,N ,m .cs ,& i8_nr ,& i8_ne , 7940i8_few , (size_t )rows_local * (size_t )kFF2 * sizeof (float ))) { 7941 std::fprintf (stderr ,"prefill: int8 experts: the group's record could not be made (%lld rows, %d experts)\n" , (long long )i8_nr ,i8_ne ); 7942 std::exit (1 );// (flush cannot return an error: as the gather's own failure path, the engine stops) 7943 } 7944if (gg_nslots > 0 ) {// the group's staged blobs are read: one event releases their slots 7945const int rel = gg_slots [gg_nslots - 1 ]; 7946cudaEventRecord (m .used [rel ],m .cs ); 7947for (int i = 0 ;i < gg_nslots ;++ i )m .used_of [gg_slots [i ]]= rel ; 7948 } 7949gg_nslots = 0 ; 7950g8 .launched (); 7951return ; 7952 } 7953#if STRATA_EXPERT_NIBBLE_BUILT 7954if (nib_l .on ) {// the GGUF blocks rebuilt from the 4-bit slots: the bytes the copy gives 7955if (const int rc = core::nibble::gather_gguf (nib_l ,gg .blob ,gg .first ,gg .n ,m .grp_gu ,mmq_gub , 7956m .grp_d ,mmq_db ,zero ,m .cs );rc != 0 ) 7957 core::nibble::fatal (l ,"the prompt path's group gather" ,cudaGetErrorString ((cudaError_t )rc )); 7958 }else 7959#endif 7960// NVFP4: each expert's scales go next to its group slot in the same launch 7961if (!mmq::gather_native_group (gg ,f .up_off ,mmq_gub /2 ,f .down_off ,mmq_db ,m .grp_gu ,mmq_gub , 7962m .grp_d ,mmq_db ,m .cs ,f .tail_off , 7963f .tail_off ?m .grp_tail :nullptr ,zero )) { 7964for (int i = gg .first ;i < gg .n ;++ i ) {// not 16-byte aligned: one at a time 7965const uint8_t * b = gg .blob [i ]; 7966 mmq::gather_native (b ,b + f .up_off ,mmq_gub /2 ,b + f .down_off ,mmq_db , 7967m .grp_gu + i * mmq_gub ,m .grp_d + i * mmq_db ,m .cs , 7968f .tail_off ?b + f .tail_off :nullptr , 7969f .tail_off ?m .grp_tail + i * 4 :nullptr ,i + 1 == gg .n ?zero :0 ); 7970 } 7971 } 7972if (gg_nslots > 0 ) { 7973const int rel = gg_slots [gg_nslots - 1 ]; 7974cudaEventRecord (m .used [rel ],m .cs ); 7975for (int i = 0 ;i < gg_nslots ;++ i )m .used_of [gg_slots [i ]]= rel ; 7976 } 7977gg_nslots = 0 ; 7978gg .first = gg .n ; 7979 }; 7980// one expert's products from its blob on the device; `slot` (a ring slot, or -1 for a resident 7981// expert) is released once the blob is read; `cslot`: the expert-cache slot the blob is in (-1: 7982// a ring slot or the peer's), which STRATA_MMQ_DIRECT reads in place 7983// Few-row experts (fewrows.hpp): research switch STRATA_PF_FEWROWS, off unless set 7984static const bool fr_env = fewrows_switch (std::getenv ("STRATA_PF_FEWROWS" ),gp100_fp16_default (std::getenv ("STRATA_PREFILL_MMQ" ))); 7985bool fr_q_done = false;// the layer's rows quantized to q8_1 (once per layer) 7986auto compute = [& ](size_t j ,const uint8_t * blob_dev ,int slot ,int32_t cslot )-> bool { 7987const int32_t e = order [j ]; 7988#if STRATA_EXPERT_NIBBLE_BUILT 7989if (nib_l .on && (!use_mmq || direct || wmma_l || cslot < 0 || !lay .native || 7990mmq_gub != (size_t ) core::nibble::kRows * nib_l .raw_gu_row || 7991mmq_db != nib_l .down_bytes )) 7992 core::nibble::fatal (l ,"the prompt path" , 7993 !use_mmq ?"no MMQ for the layer (the FP16 path dequantizes GGUF blocks)" 7994 :direct ?"STRATA_MMQ_DIRECT reads the slots in place" 7995 :wmma_l ?"the WMMA tiles read GGUF blocks" 7996 :cslot < 0 ?"an expert not in this GPU's slots (streamed or the peer's)" 7997 :"the MMQ group buffers are not the blob's [gate | up] and down" ); 7998#endif 7999pt .mark (kPfDequant ,cs ); 8000if (fz_staged ) {// P4-SMALL: the batch's experts where they are; its two products and SwiGLU at its last expert 8001fz_b .blob [j - fz_j0 ]= blob_dev ; 8002if (slot >=0 ) {gg_ents [gg_nslots ]= cur_entry ;gg_slots [gg_nslots ++ ]= slot ; } 8003if (j + 1 - fz_j0 < (size_t ) fused::kMaxBatch && gg_nslots < MMQ_GROUP && j + 1 < order .size ())return true; 8004if (gg_nslots > 0 ) {// the copies land in order: the last one covers the others 8005pt .mark (kPfWaitCopy ,cs ); 8006wait_copied (gg_ents [gg_nslots - 1 ], (size_t )gg_slots [gg_nslots - 1 ]); 8007 } 8008fz_b .e0 = (int )fz_j0 ; 8009fz_b .e1 = (int ) (j + 1 ); 8010pt .mark (kPfGemmGU ,cs ); 8011 fused::want_dm_f16 (false); 8012// the layer's tables (group_bounds, before the walk) and rows: the batch's experts are local indices of them 8013 fused::experts_native (fz_b ,fz_geom , (int )order .size (),T * K ,m .GU ,m .Xq ,m .src_dev ,m .H ,m .Dm ,m .cs ); 8014if (gg_nslots > 0 ) {// the batch's staged blobs are read: one event releases their slots 8015const int rel = gg_slots [gg_nslots - 1 ]; 8016cudaEventRecord (m .used [rel ],m .cs ); 8017for (int i = 0 ;i < gg_nslots ;++ i )m .used_of [gg_slots [i ]]= rel ; 8018 } 8019gg_nslots = 0 ; 8020fz_j0 = j + 1 ; 8021return true; 8022 } 8023if (i8_l ) {// OWN-I8: the expert joins the int8 kernels' open group; the group's products run in the flush 8024g8 .add (j ,blob_dev ); 8025if (slot >=0 ) {gg_ents [gg_nslots ]= cur_entry ;gg_slots [gg_nslots ++ ]= slot ; } 8026if (!strata::prefill::i8grp::Group ::last (j ,order .size ()))return true; 8027flush (0 ); 8028g8 .reset (); 8029return true; 8030 } 8031if (use_mmq ) { 8032// gather the expert into its group slot (GGUF blocks, unchanged or converted) 8033const size_t q = j %MMQ_GROUP ; 8034// the group's last expert also zeroes the MMQ tail after its slot (see MMQ_TAIL) 8035const bool last_of_group = q + 1 == MMQ_GROUP || j + 1 == order .size (); 8036if (direct ) { 8037const auto & f = lay .fmt [(size_t )l ]; 8038uint8_t * gp = cslot >=0 && ((uintptr_t )blob_dev | (uintptr_t )f .down_off ) %16 == 0 8039 ?m .cache -> slot_tail (cslot ,f .bytes ,mmq_plan ().d_over [(size_t )l ]) 8040 :nullptr ; 8041if (gp ) {// read in its slot: the guard after the blob is zeroed at the group end 8042tgu .p [q ]= blob_dev ; 8043td .p [q ]= blob_dev + f .down_off ; 8044gd .p [gd .n ++ ]= gp ; 8045++ stats_ .experts_direct ; 8046 }else { 8047const int c = ns ++ ; 8048tgu .p [q ]= m .grp_gu + (size_t )c * mmq_gub ; 8049td .p [q ]= m .grp_d + (size_t )c * mmq_db ; 8050if (gg_now ) { 8051gg .blob [c ]= blob_dev ; 8052gg .n = c + 1 ; 8053if (slot >=0 ) {gg_ents [gg_nslots ]= cur_entry ;gg_slots [gg_nslots ++ ]= slot ; } 8054 }else { 8055 mmq::gather_native (blob_dev ,blob_dev + f .up_off ,mmq_gub /2 ,blob_dev + f .down_off , 8056mmq_db ,m .grp_gu + (size_t )c * mmq_gub , 8057m .grp_d + (size_t )c * mmq_db ,m .cs ); 8058 } 8059 } 8060if (slot >=0 && !gg_now ) {cudaEventRecord (m .used [slot ],m .cs );m .used_of [slot ]= slot ; } 8061if (q + 1 < MMQ_GROUP && j + 1 < order .size ())return true; 8062if (gg_now ) {// also when the last entry was direct (a no-op without gathers) 8063flush (0 ); 8064gg = mmq::GatherGroup {}; 8065 } 8066 }else { 8067if (gg_now ) { 8068gg .blob [q ]= blob_dev ; 8069gg .n = (int )q + 1 ; 8070if (slot >=0 ) {gg_ents [gg_nslots ]= cur_entry ;gg_slots [gg_nslots ++ ]= slot ; } 8071if (!last_of_group )return true; 8072flush (MMQ_TAIL ); 8073gg = mmq::GatherGroup {}; 8074 }else if (lay .native ) { 8075const auto & f = lay .fmt [(size_t )l ]; 8076#if STRATA_EXPERT_NIBBLE_BUILT 8077if (nib_l .on ) {// as the group gather (flush), one expert at its group position q 8078const uint8_t * one [mmq::kGatherGroupMax ]= {}; 8079one [q ]= blob_dev ; 8080if (const int rc = core::nibble::gather_gguf (nib_l ,one , (int )q , (int )q + 1 ,m .grp_gu , 8081mmq_gub ,m .grp_d ,mmq_db , 8082last_of_group ?MMQ_TAIL :0 ,m .cs );rc != 0 ) 8083 core::nibble::fatal (l ,"the prompt path's gather" ,cudaGetErrorString ((cudaError_t )rc )); 8084 }else 8085#endif 8086// NVFP4: this expert's scales go next to its group slot in the same launch 8087 mmq::gather_native (blob_dev ,blob_dev + f .up_off ,mmq_gub /2 ,blob_dev + f .down_off , 8088mmq_db ,m .grp_gu + q * mmq_gub ,m .grp_d + q * mmq_db ,m .cs , 8089f .tail_off ?blob_dev + f .tail_off :nullptr , 8090f .tail_off ?m .grp_tail + q * 4 :nullptr ,last_of_group ?MMQ_TAIL :0 ); 8091 }else { 8092 mmq::gather_strata_q2 (blob_dev ,m .grp_gu + q * mmq_gub ,m .grp_d + q * mmq_db ,m .cs ); 8093if (last_of_group ) { 8094cudaMemsetAsync (m .grp_gu + (size_t ) (q + 1 )* mmq_gub ,0 ,MMQ_TAIL ,m .cs ); 8095cudaMemsetAsync (m .grp_d + (size_t ) (q + 1 )* mmq_db ,0 ,MMQ_TAIL ,m .cs ); 8096 } 8097 } 8098if (slot >=0 && !gg_now ) {cudaEventRecord (m .used [slot ],m .cs );m .used_of [slot ]= slot ; } 8099if (q + 1 < MMQ_GROUP && j + 1 < order .size ())return true; 8100 } 8101// the group's products: gate/up, swiglu, the group's H to q8_1, down 8102const size_t j0 = j - q ,g = j0 /MMQ_GROUP ,n = order .size (); 8103const int ngx = (int ) (q + 1 ); 8104if (m .group_cap > 0 ) { 8105// STRATA_PF_GROUP_SCRATCH: GU / H / Hq hold this range's rows only (the same 8106// products: gate/up writes its absolute rows at GU - ra; SwiGLU, the q8_1 copy and 8107// down read them from 0) 8108const MoeRange whole {(int32_t )j0 , (int32_t ) (j + 1 ), (int32_t ) (n + 1 + g * (MMQ_GROUP + 1 ))}; 8109const int32_t s0 = m .sub_first [g ]; 8110const size_t ns = s0 < 0 ?1 : (size_t ) [& ] {size_t c = 0 ;while (s0 + c < m .sub .size ()&& (size_t )m .sub [s0 + c ].a < j + 1 )++ c ;return c ; }(); 8111for (size_t si = 0 ;si < ns ;++ si ) { 8112const MoeRange rg = s0 < 0 ?whole :MoeRange {m .sub [s0 + si ].a ,m .sub [s0 + si ].b ,m .sub [s0 + si ].rel }; 8113const int64_t ra = m .bounds_host [rg .a ],nra = m .bounds_host [rg .b ]- ra ; 8114if (nra <=0 )continue ; 8115if (nra > m .group_cap ) { 8116err = "prefill: STRATA_PF_GROUP_SCRATCH: a range of " + std::to_string (nra )+ 8117" rows passes the scratch's " + std::to_string (m .group_cap ); 8118return false; 8119 } 8120const int nx = rg .b - rg .a ; 8121const size_t eo = (size_t ) (rg .a - (int32_t )j0 );// the range's first slot in the group 8122int64_t maxr = 0 ; 8123for (int32_t i = rg .a ;i < rg .b ;++ i )maxr = std::max < int64_t > (maxr ,m .cnt [(size_t )order [(size_t )i ]]); 8124pt .mark (kPfGemmGU ,cs ); 8125 mmq::Product gu ; 8126gu .w = m .grp_gu + eo * mmq_gub ;gu .type = mmq_gt ;gu .w_rows = kFF2 ;gu .w_cols = N ;gu .expert_bytes = mmq_gub ; 8127gu .n = nx ;gu .xq = m .Xq ;gu .bounds = m .bounds_dev + rg .a ;gu .ids = m .ids_identity ; 8128gu .total_rows = T * K ;gu .max_rows = maxr ;gu .dst = m .GU - ra * kFF2 ;gu .ld_dst = kFF2 ; 8129gu .y_scale = mmq::fp4_activations (mmq_gt ) ?m .Xscale :nullptr ; 8130m .mmq_ctx -> run (gu ,m .cs ); 8131if (lay .native && lay .fmt [(size_t )l ].tail_off ) 8132 mmq::swiglu_scaled (m .GU ,m .H ,nra ,kFF ,m .bounds_dev + rg .a ,nx ,m .grp_tail + eo * 4 ,ra ,m .cs ); 8133else 8134 mmq::swiglu (m .GU ,m .H ,nra ,kFF , !lay .native ,m .cs ); 8135if (had_d )// per row, as the whole group's path 8136 strata::kernels::hadamard_rows (m .H ,m .H ,nra ,kFF ,had_block ,had_sh ,m .cs ); 8137pt .mark (kPfGemmD ,cs ); 8138 mmq::quantize (m .H ,nullptr ,m .Hq ,mmq_dt ,kFF ,kFF ,nra ,m .cs ,m .Hscale ); 8139 mmq::Product dn ; 8140dn .w = m .grp_d + eo * mmq_db ;dn .type = mmq_dt ;dn .w_rows = N ;dn .w_cols = kFF ;dn .expert_bytes = mmq_db ; 8141dn .n = nx ;dn .xq = m .Hq ;dn .bounds = m .bounds_dev + rg .rel ; 8142dn .ids = m .ids_identity ;dn .total_rows = nra ;dn .max_rows = maxr ;dn .dst = m .Dm + ra * N ; 8143dn .ld_dst = N ; 8144dn .y_scale = mmq::fp4_activations (mmq_dt ) ?m .Hscale :nullptr ; 8145m .mmq_ctx -> run (dn ,m .cs ); 8146if (lay .native && lay .fmt [(size_t )l ].tail_off ) 8147 mmq::down_row_scales (m .row_sd + ra ,dn .bounds ,nx ,m .grp_tail + eo * 4 ,nra ,m .cs ); 8148 } 8149return true; 8150 } 8151const int64_t r0 = m .bounds_host [j0 ],nr = m .bounds_host [j + 1 ]- r0 ; 8152int64_t maxr = 0 ; 8153for (size_t i = j0 ;i <=j ;++ i )maxr = std::max < int64_t > (maxr ,m .cnt [(size_t )order [i ]]); 8154pt .mark (kPfGemmGU ,cs ); 8155if (wmma_l ) {// pf_wmma: gate/up, SwiGLU to FP16, down - the group in 2 tile launches 8156const int32_t * dnb = m .bounds_dev + n + 1 + g * (MMQ_GROUP + 1 ); 8157const bool ok1 = strata::kernels::gemm_iq_f16_grouped ( 8158mmq_gt ,m .grp_gu ,mmq_gub ,kFF2 , (int )N ,m .Xs , (int )N ,m .bounds_dev + j0 ,ngx , 8159 (int )maxr ,m .GU ,kFF2 ,m .cs ); 8160swiglu_split_f16 (m .GU + r0 * kFF2 ,m .Hh + r0 * kFF ,nr ,kFF , !lay .native ,m .cs ); 8161if (had_d )// APR: folded down weights take H (s * h), rotated in fp16 storage as the FP16 path does 8162 strata::kernels::hadamard_rows_f16 (m .Hh + r0 * kFF ,nr ,kFF ,had_block ,had_sh ,m .cs ); 8163pt .mark (kPfGemmD ,cs ); 8164const bool ok2 = strata::kernels::gemm_iq_f16_grouped ( 8165mmq_dt ,m .grp_d ,mmq_db , (int )N ,kFF ,m .Hh + r0 * kFF ,kFF ,dnb ,ngx , (int )maxr , 8166m .Dm + r0 * N , (int )N ,m .cs ); 8167if (!ok1 || !ok2 ) {err = "prefill: the WMMA expert tiles could not launch" ;return false; } 8168return true; 8169 } 8170if (direct ) { 8171// one launch: the direct experts' guards (their down over-read) and the zeroed tail 8172// after the last gathered expert (see MMQ_TAIL) 8173 mmq::prep_group (gd ,mmq_plan ().d_over [(size_t )l ], 8174ns ?m .grp_gu + (size_t )ns * mmq_gub :nullptr , 8175ns ?m .grp_d + (size_t )ns * mmq_db :nullptr ,MMQ_TAIL ,m .cs ); 8176 } 8177 mmq::Product gu ; 8178gu .w = m .grp_gu ;gu .type = mmq_gt ;gu .w_rows = kFF2 ;gu .w_cols = N ;gu .expert_bytes = mmq_gub ; 8179gu .n = ngx ;gu .xq = m .Xq ;gu .bounds = m .bounds_dev + j0 ;gu .ids = m .ids_identity ; 8180gu .total_rows = T * K ;gu .max_rows = maxr ;gu .dst = m .GU ;gu .ld_dst = kFF2 ; 8181gu .y_scale = mmq::fp4_activations (mmq_gt ) ?m .Xscale :nullptr ; 8182if (direct )gu .tab = & tgu ; 8183m .mmq_ctx -> run (gu ,m .cs ); 8184if (lay .native && lay .fmt [(size_t )l ].tail_off )// gate/up scales applied as read 8185 mmq::swiglu_scaled (m .GU + r0 * kFF2 ,m .H + r0 * kFF ,nr ,kFF ,m .bounds_dev + j0 ,ngx , 8186m .grp_tail ,r0 ,m .cs ); 8187else 8188 mmq::swiglu (m .GU + r0 * kFF2 ,m .H + r0 * kFF ,nr ,kFF , !lay .native ,m .cs ); 8189if (had_d ) 8190 strata::kernels::hadamard_rows (m .H + r0 * kFF ,m .H + r0 * kFF ,nr ,kFF ,had_block ,had_sh ,m .cs ); 8191pt .mark (kPfGemmD ,cs ); 8192 mmq::quantize (m .H + r0 * kFF ,nullptr ,m .Hq ,mmq_dt ,kFF ,kFF ,nr ,m .cs ,m .Hscale ); 8193 mmq::Product dn ; 8194dn .w = m .grp_d ;dn .type = mmq_dt ;dn .w_rows = N ;dn .w_cols = kFF ;dn .expert_bytes = mmq_db ; 8195dn .n = ngx ;dn .xq = m .Hq ;dn .bounds = m .bounds_dev + n + 1 + g * (MMQ_GROUP + 1 ); 8196dn .ids = m .ids_identity ;dn .total_rows = nr ;dn .max_rows = maxr ;dn .dst = m .Dm + r0 * N ; 8197dn .ld_dst = N ; 8198dn .y_scale = mmq::fp4_activations (mmq_dt ) ?m .Hscale :nullptr ; 8199if (direct )dn .tab = & td ; 8200m .mmq_ctx -> run (dn ,m .cs ); 8201if (lay .native && lay .fmt [(size_t )l ].tail_off )// s_down: applied by the combine 8202 mmq::down_row_scales (m .row_sd + r0 ,dn .bounds ,ngx ,m .grp_tail ,nr ,m .cs ); 8203if (direct ) { 8204tgu = mmq::WeightTab {}; 8205td = mmq::WeightTab {}; 8206gd = mmq::GuardTab {}; 8207ns = 0 ; 8208 } 8209return true; 8210 } 8211// few rows: the quantized grouped kernels on the GGUF blob, no dequantize (fewrows.hpp) 8212if (fr_env ) { 8213const int64_t fo0 = m .off [(size_t )e ],fne = m .cnt [(size_t )e ]; 8214if (fewrows_takes (fr_env , !use_mmq ,lay .native ,had_gu || had_d ,fne )) { 8215const auto & f = lay .fmt [(size_t )l ]; 8216if (m .fr_rec == nullptr || m .fr_xq_rows < T ) { 8217if (m .fr_xq )cudaFree (m .fr_xq ); 8218m .fr_xq = nullptr ; 8219const size_t xb = (size_t )T * (size_t ) (N /32 )* 36 ; 8220if (cudaMalloc (& m .fr_xq ,xb )!= cudaSuccess || 8221 (m .fr_rec == nullptr && cudaMalloc ((void ** )& m .fr_rec , (size_t )m .g -> n_expert * kFewRowsRecBytes )!= cudaSuccess )|| 8222 (m .fr_scr == nullptr && cudaMalloc (& m .fr_scr , strata::kernels::native_expert_scratch_bytes (kFewRows ,f .n_ff ))!= cudaSuccess )) { 8223err = "prefill: few-row experts: no memory" ; 8224return false; 8225 } 8226m .fr_xq_rows = T ; 8227fr_q_done = false; 8228 } 8229if (!fr_q_done ) {// the layer's T rows as q8_1, once 8230 strata::kernels::quantize_q8_1_rows (m .mixed ,T ,N ,m .fr_xq ,m .cs ); 8231fr_q_done = true; 8232 } 8233uint8_t * rec = m .fr_rec + j * kFewRowsRecBytes ; 8234fewrows_record (rec ,blob_dev , (int )fne , (int )fo0 ,m .cs ); 8235const strata::kernels::NativeExpertLayout FL = 8236 strata::kernels::native_expert_layout (f .gu_type ,f .d_type ,f .n_embd ,f .n_ff ); 8237pt .mark (kPfGemmGU ,cs ); 8238 strata::kernels::native_expert_grouped (FL , (const unsigned long long * )rec , (const int32_t * ) (rec + 8 ), 8239 (const int32_t * ) (rec + 16 ), (const int32_t * ) (rec + 24 ), 8240m .src_dev + fo0 ,1 ,fne ,m .fr_xq ,m .fr_scr ,m .Dm ,m .cs ,1 ); 8241if (slot >=0 ) {cudaEventRecord (m .used [slot ],m .cs );m .used_of [slot ]= slot ; } 8242return true; 8243 } 8244 } 8245const int q = (int ) (j %DQ ); 8246if (lay .native ) { 8247// plan v0.3 P6: a native pack's layer, dequantized by llama.cpp's own formulas 8248const auto & f = lay .fmt [(size_t )l ]; 8249 strata::kernels::iq_dequant_gu_f16 (f .gu_type ,blob_dev ,blob_dev + f .up_off ,f .n_ff ,f .n_embd , 8250m .dq_gu [q ],m .cs , 8251f .tail_off ? (const float * ) (blob_dev + f .tail_off ) :nullptr ); 8252 strata::kernels::iq_dequant_f16 (f .d_type ,blob_dev + f .down_off ,f .n_embd * f .n_ff ,m .dq_d [q ],m .cs , 8253f .tail_off ? (const float * ) (blob_dev + f .tail_off )+ 2 :nullptr ); 8254 }else { 8255blob_dequant_f16 (blob_dev ,m .dq_gu [q ],m .dq_d [q ],m .cs ); 8256 } 8257if (slot >=0 ) {cudaEventRecord (m .used [slot ],m .cs );m .used_of [slot ]= slot ; } 8258const int64_t o0 = m .off [(size_t )e ],ne = m .cnt [(size_t )e ]; 8259pt .mark (kPfGemmGU ,cs ); 8260m .gemm .f16 (m .Xs + o0 * N ,m .dq_gu [q ],m .GU + o0 * kFF2 ,ne ,kFF2 ,N ); 8261swiglu_interleaved (m .GU + o0 * kFF2 ,m .Hh + o0 * kFF ,ne ,m .cs ); 8262// APR, deliberately in place on the fp16 H: hadamard_rows_f16 reads fp16, runs the 8263// butterflies in fp32 and rounds once on the store, so against an fp32 rotation the only 8264// extra error is the one fp16 rounding of the SwiGLU output before it (~2^-11 relative per 8265// value; the GEMM reads fp16 either way). An fp32 rotation would need a T*K*640 float 8266// buffer (~200 MiB at an 8k chunk) or a fused SwiGLU + rotation kernel, for the fallback 8267// of types and builds without MMQ (the MMQ path rotates fp32 H). native_expert_parity 8268// bounds the fp16 rotation against the float one at relative L1 error < 2e-3. The 8269// gate/up input (Xs above) is handled the same way. 8270if (had_d ) strata::kernels::hadamard_rows_f16 (m .Hh + o0 * kFF ,ne ,kFF ,had_block ,had_sh ,m .cs ); 8271pt .mark (kPfGemmD ,cs ); 8272m .gemm .f16 (m .Hh + o0 * kFF ,m .dq_d [q ],m .Dm + o0 * N ,ne ,N ,kFF ); 8273return true; 8274 }; 8275if (ws_layer ) { 8276// STRATA_MMQ_WS: the layer's gate/up in one launch, H of all its rows in one pass, its down 8277// in one launch (no expert of the layer is staged or streamed: nothing to wait for or give 8278// back beyond what the walk would) 8279stats_ .experts_resident += (int64_t )order .size (); 8280pt .mark (kPfGemmGU ,cs ); 8281if (!ws::gate_up (wl ,m .cs )) {// the layer was taken because ws::faster said so 8282err = "prefill: the weight-stationary gate/up declined a layer it was picked for" ; 8283return false; 8284 } 8285 mmq::swiglu_quant (m .GU ,m .Hq ,T * K , !lay .native ,m .cs ); 8286pt .mark (kPfGemmD ,cs ); 8287 ws::down (wl ,m .cs ); 8288if (stream_all && group_gather )give_back (consumed ); 8289 }else if (!stream_all ) { 8290size_t staged = 0 ; 8291size_t pending = 0 ; 8292// P4-SMALL: the layer's tables from the routed experts' row bounds (absolute, uploaded above), once; every 8293// batch of experts below reads its own experts' tiles out of them (the streamed path's fused::group, from bounds) 8294if (fz_staged && !order .empty ()) fused::group_bounds (m .bounds_dev , (int )order .size (),m .GU ,m .cs ); 8295const bool stream_ahead = stream_ahead_enabled (); 8296const size_t lookahead = group_resident ? (size_t ) (STAGE_GRP - MMQ_GROUP - 1 ) :STAGE - 1 ; 8297for (size_t j = 0 ;j < order .size ();++ j ) { 8298// Resident experts occupy no staging slot. Keep STAGE actual transfers ahead, 8299// rather than STAGE positions in the mixed resident/streamed order. 8300while (staged < order .size ()&& (stream_ahead ?pending < STAGE :staged <=j + lookahead )) { 8301if (!stage_one (staged ))return false; 8302if (stage_of [staged ] >=0 )++ pending ; 8303++ staged ; 8304 } 8305const int32_t e = order [j ]; 8306if (stage_of [j ]< 0 ) { 8307++ stats_ .experts_resident ; 8308if (!compute (j ,m .cache -> device_slot (m .host_res [(size_t )l * m .g -> n_expert + e ]),-1 , 8309m .host_res [(size_t )l * m .g -> n_expert + e ]))return false; 8310 }else { 8311if (!group_resident ) {// grouped: the flush waits once, on the group's last copy 8312pt .mark (kPfWaitCopy ,cs ); 8313cudaStreamWaitEvent (m .cs ,m .copied [stage_of [j ]],0 ); 8314 } 8315if (!compute (j ,m .stage_dev [stage_of [j ]],stage_of [j ],-1 ))return false; 8316-- pending ;// compute recorded the slot's release event before any reuse 8317 } 8318 } 8319 }else { 8320// the streamed walk: this layer's entries [k, kend) in id order; an entry the routing did not 8321// pick only gives its slot back 8322size_t k = seq_start [(size_t )l ]; 8323const size_t kend = seq_start [(size_t )l + 1 ]; 8324auto release_to = [& ](int32_t e_stop ) { 8325while (k < kend && seq [k ].e < e_stop ) { 8326if (gg_nslots > 0 )flush (0 );// the open group's slots get their event first 8327const int sl = (int ) (k % (size_t )m .ring ); 8328cudaEventRecord (m .used [sl ],m .cs ); 8329m .used_of [sl ]= sl ; 8330consumed = ++ k ; 8331give_back (consumed ); 8332 } 8333 }; 8334for (size_t j = 0 ;j < order .size ();++ j ) { 8335const int32_t e = order [j ]; 8336release_to (e ); 8337if (k < kend && seq [k ].e == e ) { 8338const int sl = (int ) (k % (size_t )m .ring ); 8339wait_issued (k ); 8340if (!group_gather ) { 8341pt .mark (kPfWaitCopy ,cs ); 8342wait_copied (k , (size_t )sl ); 8343 } 8344cur_entry = k ; 8345if (!compute (j ,m .stage_dev [sl ],sl ,-1 ))return false; 8346consumed = ++ k ; 8347if (!group_gather || gg_nslots == 0 )give_back (consumed );// its group was gathered 8348 }else { 8349const bool r0 = m .host_res && m .cache && m .host_res [(size_t )l * m .g -> n_expert + e ] >=0 ; 8350const uint8_t * bp = r0 ?m .cache -> device_slot (m .host_res [(size_t )l * m .g -> n_expert + e ]) 8351 : (m .pp && m .pp -> peer ?m .pp -> peer -> slot_ptr (l ,e ) :nullptr );// over the cap: P2P 8352if (bp == nullptr ) {err = "prefill: an expert is neither resident, streamed nor on the peer" ;return false; } 8353++ stats_ .experts_resident ; 8354if (!compute (j ,bp ,-1 ,r0 ?m .host_res [(size_t )l * m .g -> n_expert + e ] :-1 ))return false; 8355if (group_gather && gg_nslots == 0 )give_back (consumed ); 8356 } 8357 } 8358release_to (m .g -> n_expert ); 8359 } 8360 } 8361 } 8362pt .mark (kPfCombine ,cs ); 8363if (cpu_fut .valid ()) {// set_cpu_pool: the CPU's rows into Dm's tail, row_sd 1 (s_down is in them) 8364if (cpu_share_env ()< 0.0 )cudaEventRecord (m .cpu_ev [1 ],m .cs );// after the GPU's expert work 8365if (!cpu_fut .get ()) {err = "prefill: a CPU expert has no blob" ;return false; } 8366if (cpu_share_env ()< 0.0 && n_stream > n_cpu ) { 8367m .cpu_pend = true; 8368m .pend_cpu_ms = cpu_ms ; 8369m .pend_n_cpu = n_cpu ; 8370m .pend_n_gpu = n_stream - n_cpu ; 8371 } 8372stats_ .cpu_share = cpu_share_env () >=0.0 ?cpu_share_env () :m .cpu_share_now ; 8373const int64_t r0c = cpu_at ; 8374cudaMemcpyAsync (m .Dm + (size_t )r0c * N ,m .cpu_rows , (size_t )rows_cpu * N * sizeof (float ), 8375cudaMemcpyHostToDevice ,m .cs ); 8376if (use_mmq && !fused_l && !fz_staged_l && lay .native && lay .fmt [(size_t )l ].tail_off ) 8377cudaMemcpyAsync (m .row_sd + r0c ,m .cpu_ones , (size_t )rows_cpu * sizeof (float ), 8378cudaMemcpyHostToDevice ,m .cs ); 8379stats_ .experts_cpu += n_cpu ; 8380 } 8381// no reading from a layer the share could not change (nothing taken) or with one-time costs 8382if (cpu_set >=0 && n_stream > 0 && (!cpu_arm || n_cpu > 0 )&& !cpu_cold ) { 8383cudaEventRecord (m .cpu_wall [2 * cpu_set + 1 ],m .cs ); 8384m .pend_wall = cpu_arm ?2 :1 ; 8385m .pend_set = cpu_set ; 8386m .pend_l = (int )l ; 8387m .pend_wall_n = n_stream ; 8388 } 8389if (peer_now ) {// multi-GPU: the peer's rows are in Dm (or, without P2P, in host memory) 8390cudaStreamWaitEvent (m .cs ,m .pp -> ev_done ,0 ); 8391if (!m .pp -> p2p && !m .pp -> sums ) 8392copy_f32_wide (m .Dm + (size_t )m .pp -> back_at * N ,m .pp -> host_rows ,m .pp -> back_rows * N ,m .cs ); 8393 } 8394if (peer_now && m .pp -> sums && m .pp -> f16 ) 8395moe_combine_peer16 (m .Dm ,m .slot_dev ,m .w ,m .shared ,m .sg ,m .pp -> host_sum16 ,m .pp -> back_at ,m .bo ,T ,m .cs ); 8396else if (peer_now && m .pp -> sums ) 8397moe_combine_peer (m .Dm ,m .slot_dev ,m .w ,m .shared ,m .sg ,m .pp -> host_sum ,m .pp -> back_at ,m .bo ,T ,m .cs ); 8398else if (dm16_used && rows_cpu == 0 ) 8399moe_combine16 (reinterpret_cast < const uint16_t *> (m .Dm ),m .slot_dev ,m .w ,m .shared ,m .sg ,m .bo ,T ,m .cs ); 8400else 8401 {// STRATA_LAT_MOE_DUMP (debug): Dm entering the combine, layer 0 8402static const char * lat_moe_dump2 = std::getenv ("STRATA_LAT_MOE_DUMP" ); 8403if (lat_moe_dump2 && l == 0 ) { 8404const int64_t n_dm = std::min < int64_t > (8 ,T * K ); 8405 std::vector < float > hdm ((size_t )n_dm * (size_t )m .g -> n_embd ); 8406if (cudaMemcpyAsync (hdm .data (),m .Dm ,hdm .size ()* 4 ,cudaMemcpyDeviceToHost ,m .cs )!= cudaSuccess || 8407cudaStreamSynchronize (m .cs )!= cudaSuccess ) { 8408err = "lat moe dump: the Dm copy failed" ;return false; 8409 } 8410char p [512 ]; std::snprintf (p ,sizeof p ,"%s/u-dm.bin" ,lat_moe_dump2 ); 8411 std::FILE * fp = std::fopen (p ,"wb" ); 8412if (fp == nullptr ) {err = std::string ("lat moe dump: cannot write " )+ p ;return false; } 8413 std::fwrite (hdm .data (),4 ,hdm .size (),fp ); std::fclose (fp ); 8414 } 8415 } 8416moe_combine (m .Dm ,m .slot_dev ,m .w ,m .shared ,m .sg ,m .bo ,T ,m .cs , 8417use_mmq && !fused_l && !fz_staged_l && !m .latent && lay .native && lay .fmt [(size_t )l ].tail_off ?m .row_sd :nullptr );// (fz_staged_l: the fused kernels applied s_down already) 8418// debug: STRATA_DBG_NAN=1 reports the first layer of a chunk whose MoE produced non-finite values 8419if (static const bool dbg = std::getenv ("STRATA_DBG_NAN" )!= nullptr ;dbg ) { 8420cudaStreamSynchronize (m .cs ); 8421auto bad = [& ](const float * d ,int64_t n ) { 8422 std::vector < float > h ((size_t )n ); 8423cudaMemcpy (h .data (),d , (size_t )n * 4 ,cudaMemcpyDeviceToHost ); 8424int64_t c = 0 ; 8425for (float v :h )c += !std::isfinite (v ); 8426return c ; 8427 }; 8428// (fused: GU and H hold the grouping tables and int8 rows, not floats) 8429// (the CPU's rows, the last rows_cpu of GU and H, are never written by the GPU: not checked) 8430const int64_t gpu_rows = T * K - rows_cpu ; 8431const int64_t bgu = fused_l || fz_staged_l || m .group_cap > 0 ?0 :bad (m .GU ,gpu_rows * kFF2 ),bdm = bad (m .Dm ,T * K * N ), 8432bbo = bad (m .bo ,T * N ),bsh = bad (m .shared ,T * N ),bsg = bad (m .sg ,T ),bw = bad (m .w ,T * K ); 8433const int64_t bh = m .H && !fused_l && !fz_staged_l && m .group_cap == 0 ?bad (m .H ,gpu_rows * kFF ) :-1 ;// (group scratch: the last range's rows) 8434static int64_t reported = -1 ; 8435if ((bgu || bdm || bbo || bsh || bsg || bw || bh > 0 )&& reported != stats_ .chunks ) { 8436reported = stats_ .chunks ; 8437 std::fprintf (stderr ,"strata dbg: layer %lld (mmq %d, types %d/%d, %zu experts): non-finite GU %lld " 8438"H %lld Dm %lld bo %lld of T %lld\n" , (long long )l , (int )use_mmq ,mmq_gt ,mmq_dt , 8439n_order , (long long )bgu , (long long )bh , (long long )bdm , (long long )bbo , 8440 (long long )T ); 8441 std::fprintf (stderr ,"strata dbg: layer %lld: non-finite shared %lld sg %lld w %lld\n" , (long long )l , (long long )bsh , (long long )bsg , (long long )bw ); 8442 } 8443 } 8444 } 8445pt .mark (kPfHcWrite ,cs );// the write-back (and the next half's norm) on its own line; it used to be charged to the phase before 8446// ---- the hyper-connection write of this half; F-2: fused with the next half's norm when nothing else 8447// touches R in between (not the stage's last half, not before the PLE block of layer 1, not under a 8448// control vector) 8449const int64_t nl = half == 0 ?l :l + 1 ; 8450const bool steered = half == 1 && strata::kernels::cvec ().covers (l ); 8451const float * cv_dir = nullptr ,* cv_s = nullptr ; 8452const int * cv_on = nullptr ; 8453const bool cv_fused = steered && cvec_fuse ()&& !gr_unfused ()&& nl < LE && !(nl == 1 && ple_on )&& 8454 strata::kernels::cvec ().n_embd == N && strata::kernels::cvec ().hc == HC && 8455 strata::kernels::cvec_tables (& cv_dir ,& cv_s ,& cv_on ); 8456const bool fuse = !gr_unfused ()&& nl < LE && !(half == 1 && nl == 1 && ple_on )&& (!steered || cv_fused ); 8457const core::WeightRef * wnn = nullptr ; 8458if (fuse ) { 8459const core::LayerView vn (* m .wt ,nl ); 8460wnn = need (vn ,half == 0 ?"hc_ffn_norm.weight" :"hc_attn_norm.weight" ,err ); 8461if (!wnn )return false; 8462 } 8463if (wnn && cv_fused ) { 8464// STRATA_CVEC_FUSE_CHECK=N: on the first N fused writes, also run the three-kernel path on a copy 8465// of R and report whether R, the row scales and the BF16 image are bit-identical 8466static int checks = [] {const char * e = std::getenv ("STRATA_CVEC_FUSE_CHECK" );return e ? std::atoi (e ) :0 ; }(); 8467if (checks > 0 ) { 8468-- checks ; 8469float * Rc = nullptr ,* rc = nullptr ; 8470uint16_t * xc = nullptr ; 8471cudaMalloc (& Rc , (size_t )T * D * 4 );cudaMalloc (& rc , (size_t )T * HC * 4 ); 8472cudaMalloc (& xc , (size_t )T * D * 2 ); 8473cudaMemcpyAsync (Rc ,m .R , (size_t )T * D * 4 ,cudaMemcpyDeviceToDevice ,m .cs ); 8474gr_write (Rc ,m .bo ,m .inj ,HC ,T ,m .cs ); 8475 strata::kernels::cvec_apply (Rc ,l ,T ,D ,nullptr ,0 ,nullptr ,0 , false,m .cs ); 8476gr_norm_rs (Rc , (const float * )wnn -> data ,EPS ,rc ,xc ,T ,m .cs ,nullptr ,D ,xf16 ); 8477gr_write_cvec_norm_rs (m .R ,m .bo ,m .inj ,HC ,cv_dir + l * N ,cv_s + l ,cv_on , 8478 strata::kernels::cvec ().mode , (const float * )wnn -> data ,EPS ,m .grs , 8479m .xn16 ,T ,m .cs ,m .xn16_lo ,ldx ,xf16 ); 8480 std::vector < float > a ((size_t )T * D ),b ((size_t )T * D ),ra ((size_t )T * HC ),rb ((size_t )T * HC ); 8481 std::vector < uint16_t > xa ((size_t )T * D ),xb ((size_t )T * D ); 8482cudaMemcpyAsync (a .data (),m .R ,a .size ()* 4 ,cudaMemcpyDeviceToHost ,m .cs ); 8483cudaMemcpyAsync (b .data (),Rc ,b .size ()* 4 ,cudaMemcpyDeviceToHost ,m .cs ); 8484cudaMemcpyAsync (ra .data (),m .grs ,ra .size ()* 4 ,cudaMemcpyDeviceToHost ,m .cs ); 8485cudaMemcpyAsync (rb .data (),rc ,rb .size ()* 4 ,cudaMemcpyDeviceToHost ,m .cs ); 8486cudaMemcpyAsync (xa .data (),m .xn16 ,xa .size ()* 2 ,cudaMemcpyDeviceToHost ,m .cs ); 8487cudaMemcpyAsync (xb .data (),xc ,xb .size ()* 2 ,cudaMemcpyDeviceToHost ,m .cs ); 8488cudaStreamSynchronize (m .cs ); 8489cudaFree (Rc );cudaFree (rc );cudaFree (xc ); 8490 std::fprintf (stderr ,"strata: STRATA_CVEC_FUSE_CHECK layer %lld T %lld: R %s, rs %s, xn16 %s\n" , 8491 (long long )l , (long long )T , 8492 std::memcmp (a .data (),b .data (),a .size ()* 4 ) ?"DIFFERS" :"identical" , 8493 std::memcmp (ra .data (),rb .data (),ra .size ()* 4 ) ?"DIFFERS" :"identical" , 8494 std::memcmp (xa .data (),xb .data (),xa .size ()* 2 ) ?"DIFFERS" :"identical" ); 8495 }else 8496gr_write_cvec_norm_rs (m .R ,m .bo ,m .inj ,HC ,cv_dir + l * N ,cv_s + l ,cv_on , 8497 strata::kernels::cvec ().mode , (const float * )wnn -> data ,EPS ,m .grs ,m .xn16 , 8498T ,m .cs ,m .xn16_lo ,ldx ,xf16 ); 8499normed = true; 8500 }else if (wnn ) { 8501gr_write_norm_rs (m .R ,m .bo ,m .inj ,HC , (const float * )wnn -> data ,EPS ,m .grs ,m .xn16 ,T ,m .cs , 8502m .xn16_lo ,ldx ,xf16 ); 8503normed = true; 8504 }else { 8505gr_write (m .R ,m .bo ,m .inj ,HC ,T ,m .cs ); 8506 } 8507if (steered && !cv_fused )// --control-vector-scaled 8508 strata::kernels::cvec_apply (m .R ,l ,T ,D ,nullptr ,0 ,nullptr ,0 , false,m .cs ); 8509#if defined(STRATA_HAVE_DFLASH2 ) 8510if (half == 1 && tap_rows > 0 && tap_slot [(size_t )l ] >=0 )// DFlash2: this layer's completed output, mean of the streams 8511 strata::kernels::df2_tap_rows (m .R + (size_t )tap_t0 * D ,tap_dev_ + (size_t )tap_slot [(size_t )l ]* N , (int64_t )tap_local_ .size ()* N ,N , 8512 (int )HC , (int )tap_rows ,m .cs ); 8513#endif 8514 } 8515 } 8516if (!ple_land ())return false;// a stage that ends before layer 1: the rows land anyway, the next gather starts 8517if (issuer .joinable ()) { 8518issuer .join (); 8519stats_ .ms_experts_host += iss_ms ; 8520stats_ .experts_streamed += iss_streamed ; 8521stats_ .experts_dma += iss_dma ; 8522if (rs_on && std::getenv ("STRATA_TRACE" )) { 8523 std::fprintf (stderr ,"strata trace: routed stream: chunk from token %lld (%lld tokens): %lld of %zu ring entries " 8524"copied, %zu dropped (no token routes to them), depth %d\n" , (long long )p0 , (long long )T , 8525 (long long )iss_streamed ,seq .size (),rs_dropped ,rs_depth ); 8526 std::fflush (stderr ); 8527 } 8528if (copy_wait_dedupe && pt .on ) 8529 std::fprintf (stderr ,"strata prefill copies: %lld slot waits, %lld skipped as the same release event\n" , 8530 (long long )iss_waits , (long long )iss_dedup ); 8531 } 8532stats_ .tokens += T ; 8533 core::progress_at ("reading the prompt (batched): finishing the chunk from token" ,p0 ); 8534pt .mark (kPfStart ,cs ); 8535if (next_ != nullptr ) { 8536// The current hand-off slot was used two chunks ago. 8537float * h = m .hand [hand_buf_ ]; 8538const int hp = m .hand_pieces ; 8539if (hp > 0 ) { 8540// STRATA_HANDOFF_PIPE: the pieces' downloads stay queued; the host waits for the chunk's work only (the 8541// state on_stage_chunk saves, the error check), the next stage's uploads wait on the pieces' events 8542bool ok = cudaEventRecord (m .hand_done [hand_buf_ ],m .cs )== cudaSuccess ; 8543for (int i = 0 ;ok && i < hp ;++ i ) { 8544int64_t r0 = 0 ,nr = 0 ; 8545handoff_piece (T ,hp ,i ,r0 ,nr ); 8546if (nr > 0 ) 8547ok = cudaMemcpyAsync (h + (size_t )r0 * D ,m .R + (size_t )r0 * D , (size_t )nr * D * 4 , 8548cudaMemcpyDeviceToHost ,m .cs )== cudaSuccess ; 8549ok = ok && cudaEventRecord (m .hand_ev [hand_buf_ ][i ],m .cs )== cudaSuccess ; 8550 } 8551if (!ok || cudaEventSynchronize (m .hand_done [hand_buf_ ])!= cudaSuccess ) { 8552err = std::string ("prefill: the layer split's hand-off: " )+ cudaGetErrorString (cudaGetLastError ()); 8553return false; 8554 } 8555 }else if (cudaMemcpyAsync (h ,m .R , (size_t )T * D * 4 ,cudaMemcpyDeviceToHost ,m .cs )!= cudaSuccess || 8556cudaStreamSynchronize (m .cs )!= cudaSuccess ) { 8557err = std::string ("prefill: the layer split's hand-off: " )+ cudaGetErrorString (cudaGetLastError ()); 8558return false; 8559 } 8560// Wait only for the DIRECT successor's previous chunk. That successor 8561// may already have forwarded its older chunk to later GPUs. 8562if (on_stage_chunk && !on_stage_chunk (p0 + T ,err ))return false; 8563if (next_run_ .valid ()&& !next_run_ .get ()) {err = next_err_ ;return false; } 8564next_err_ .clear (); 8565next_ -> hand_in_ = h ; 8566next_ -> hand_ev_ = hp > 0 ?static_cast < const void *> (m .hand_ev [hand_buf_ ]) :nullptr ; 8567next_ -> hand_pieces_ = hp ; 8568next_ -> single_chunk_ = single_chunk ; 8569next_ -> pipe_chunked_ = pipe_chunked ; 8570if (handoff_pipe_worker ()) { 8571if (!m .hand_worker )m .hand_worker = std::make_unique < HandWorker > (); 8572next_run_ = m .hand_worker -> submit (std::packaged_task < bool ()> ([this ,tokens ,c0 ,T ,p0 ] { 8573const bool r = next_ -> run_impl (tokens + c0 ,T ,p0 ,next_err_ ); 8574 (void )cudaGetLastError ();// clear what a thread's end cleared (std::async) 8575return r ; 8576 })); 8577 }else 8578next_run_ = std::async (std::launch::async , [this ,tokens ,c0 ,T ,p0 ] { 8579 strata::aux_cpus::pin_current_thread (); 8580return next_ -> run_impl (tokens + c0 ,T ,p0 ,next_err_ ); 8581 }); 8582hand_buf_ ^=1 ; 8583continue ;// the last stage reports the chunk (on_chunk) 8584 } 8585if (i8_count_on ()) {// STRATA_I8_COUNT=1: this chunk's entries by path (the counters restart for the next chunk) 8586I8Count & c = i8_count (); 8587 std::fprintf (stderr ,"strata i8-count: chunk of %lld tokens: %lld layers reached the group walk, %lld on native_expert_i8; routed entries %lld, on native_expert_i8 %lld (%.2f %%), " 8588"elsewhere in the walk %lld; i8 groups %lld; smallest group average seen %lld entries; few-rows route (grouped kernels, counted in the int8 ones): %lld layers, %lld entries\n" , 8589 (long long )T , (long long )c .layers , (long long )c .layers_i8 , (long long )c .ent , (long long )c .ent_i8 ,c .ent > 0 ?100.0 * (double )c .ent_i8 / (double )c .ent :0.0 , 8590 (long long ) (c .ent - c .ent_i8 ), (long long )c .groups_i8 , (long long ) (c .min_avg == INT64_MAX ?-1 :c .min_avg ), (long long )c .layers_few , 8591 (long long )c .ent_few ); 8592c = I8Count {}; 8593 } 8594if (const char * dump = std::getenv ("STRATA_PREFILL_DUMP_R" )) {// debug: the final residuals, every 64th 8595cudaStreamSynchronize (m .cs );// position (A/B quality of this path) 8596if (std::FILE * f = std::fopen (dump ,p0 == 0 ?"wb" :"ab" )) {// one prompt per file, all its chunks 8597 std::vector < float > row ((size_t )D ); 8598for (int64_t t = (64 - p0 %64 ) %64 ;t < T ;t += 64 ) { 8599cudaMemcpy (row .data (),m .R + t * D , (size_t )D * 4 ,cudaMemcpyDeviceToHost ); 8600const int64_t pos = p0 + t ; 8601 std::fwrite (& pos ,sizeof pos ,1 ,f ); 8602 std::fwrite (row .data (),4 ,row .size (),f ); 8603 } 8604 std::fclose (f ); 8605 } 8606 } 8607if (const char * dump = std::getenv ("STRATA_PREFILL_DUMP_R_ALL" )) { 8608// S25 (draft-layer distillation data, opt-in): every position's final multi-stream residual as BF16 8609// (round-to-nearest-even), rows in position order, appended across chunks and requests: [n][hc*n_embd] 8610cudaStreamSynchronize (m .cs ); 8611if (std::FILE * f = std::fopen (dump ,"ab" )) { 8612constexpr int64_t kRows = 512 ; 8613 std::vector < float > rows ((size_t ) (kRows * D )); 8614 std::vector < uint16_t > out ((size_t ) (kRows * D )); 8615for (int64_t t0 = 0 ;t0 < T ;t0 += kRows ) { 8616const int64_t nr = std::min < int64_t > (kRows ,T - t0 ); 8617cudaMemcpy (rows .data (),m .R + t0 * D , (size_t ) (nr * D )* 4 ,cudaMemcpyDeviceToHost ); 8618for (int64_t i = 0 ;i < nr * D ;++ i ) { 8619uint32_t u ; 8620 std::memcpy (& u ,& rows [(size_t )i ],4 ); 8621u += 0x7fffu + ((u >>16 )& 1u ); 8622out [(size_t )i ]= (uint16_t ) (u >>16 ); 8623 } 8624 std::fwrite (out .data (),2 , (size_t ) (nr * D ),f ); 8625 } 8626 std::fclose (f ); 8627 } 8628 } 8629#if defined(STRATA_HAVE_DFLASH2 ) 8630if (tap_rows > 0 && on_taps ) { 8631if (cudaStreamSynchronize (m .cs )!= cudaSuccess ) {err = std::string ("prefill: " )+ cudaGetErrorString (cudaGetLastError ());return false; } 8632if (!on_taps (tap_dev_ ,tap_rows ,p0 + tap_t0 ,err ))return false; 8633 } 8634#endif 8635if (on_chunk || on_stage_chunk ) { 8636const auto toc = Clock ::now (); 8637if (cudaStreamSynchronize (m .cs )!= cudaSuccess ) { 8638err = std::string ("prefill: " )+ cudaGetErrorString (cudaGetLastError ()); 8639return false; 8640 } 8641const auto toc2 = Clock ::now (); 8642if (on_stage_chunk && !on_stage_chunk (p0 + T ,err ))return false; 8643if (on_chunk && !on_chunk (m .R ,T ,p0 ,err ))return false; 8644host_sync_ms += std::chrono::duration < double , std::milli > (toc2 - toc ).count (); 8645host_chunk_ms += ms_since (toc2 ); 8646 } 8647 } 8648// Do not drain the successor here. This is the overlap: an intermediate 8649// stage can return while later GPUs are still processing the previous chunk. 8650ss .ple_prev [0 ]= prev [0 ]; 8651ss .ple_prev [1 ]= prev [1 ]; 8652if (std::getenv ("STRATA_DBG_NAN" )!= nullptr ) {// debug: the state the prompt leaves for the token path 8653cudaStreamSynchronize (m .cs ); 8654auto bad = [& ](const float * d ,int64_t n ) { 8655 std::vector < float > h ((size_t )n ); 8656cudaMemcpy (h .data (),d , (size_t )n * 4 ,cudaMemcpyDeviceToHost ); 8657int64_t c = 0 ; 8658double mx = 0 ; 8659for (float v :h ) {c += !std::isfinite (v );if (std::isfinite (v ))mx = std::max (mx , (double ) std::fabs (v )); } 8660 std::fprintf (stderr ," %lld non-finite (max |x| %.3g)" , (long long )c ,mx ); 8661 }; 8662const int64_t last = (n - 1 ) %C ; 8663 std::fprintf (stderr ,"strata dbg: prompt end: last residual row" ); 8664bad (m .R + last * D ,D ); 8665if (ss .ple .ready ()) { std::fprintf (stderr ,"; PLE history" );bad (ss .ple .hist , (int64_t ) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM ); } 8666 std::fprintf (stderr ,"; GDN state 0" ); 8667bad (ss .gdn_state ,64 * 1024 ); 8668 std::fprintf (stderr ,"\n" ); 8669 } 8670if (cudaStreamSynchronize (m .cs )!= cudaSuccess ) { 8671err = std::string ("prefill: " )+ cudaGetErrorString (cudaGetLastError ()); 8672return false; 8673 } 8674// (PR #121) an expert copy that failed on the copy stream surfaces here, not in the next request 8675if (const cudaError_t cst = cudaStreamSynchronize (m .copy );cst != cudaSuccess ) { 8676err = std::string ("prefill: expert copy stream: " )+ cudaGetErrorString (cst ); 8677return false; 8678 } 8679if (kv_prefetch ) { 8680if (const cudaError_t cst = cudaStreamSynchronize (m .kv_copy );cst != cudaSuccess ) { 8681err = std::string ("prefill: KV prefetch stream: " )+ cudaGetErrorString (cst ); 8682return false; 8683 } 8684 std::fprintf (stderr ,"strata KV prefetch: %lld layer prefixes, single existing staging pool\n" , 8685 (long long )kv_prefetches ); 8686 } 8687stats_ .ms_total += ms_since (t_start ); 8688#if !defined(STRATA_GPU_METAL ) 8689if (strata::kernels::qsa_two_pass_on ()) {// STRATA_SELECT_TWO_PASS: what the two-pass scorer did in this prompt 8690namespace tp= strata::kernels::two_pass; 8691unsigned long long c [tp::kStatCount ]= {}; 8692if (strata::kernels::qsa_two_pass_stats (c , true,m .cs )&& c [tp::kStCalls ]> 0 ) { 8693const unsigned long long sparse = c [tp::kStQueries ],kept = sparse - c [tp::kStFull ]; 8694 std::fprintf (stderr ,"strata prefill: two-pass QSA select: %llu calls, %llu queries (%llu blocks) in single-pass TF32, " 8695"%llu blocks again in 3xTF32 (%.1f per query, max %llu), %llu queries flagged (%llu " 8696"16-query tiles in full), %llu selecting every cell; candidates %.0f per query (max %llu)\n" , 8697c [tp::kStCalls ],sparse ,c [tp::kStBlocks ],c [tp::kStBand ],kept ? (double )c [tp::kStBand ] /kept :0.0 , 8698c [tp::kStBandMax ],c [tp::kStFull ],c [tp::kStFullTiles ],c [tp::kStIdentity ], 8699kept ? (double )c [tp::kStCand ] /kept :0.0 ,c [tp::kStCandMax ]); 8700if (c [tp::kChkQueries ]> 0 ) { 8701const uint32_t rb = (uint32_t )c [tp::kChkRatioMax ]; 8702float ratio = 0.0f ; 8703 std::memcpy (& ratio ,& rb ,4 ); 8704 std::fprintf (stderr ,"strata prefill: two-pass check: %llu queries, %llu with ids not the 3xTF32 scorer's (%llu ids); " 8705"scored again: %llu of %llu blocks not the 3xTF32 score bit for bit; kept: %llu of %llu " 8706"single-pass scores outside the bound, the largest |S1 - S3| / bound %.4g\n" , 8707c [tp::kChkQueries ],c [tp::kChkIdQueries ],c [tp::kChkIdEntries ],c [tp::kChkRescoredDiff ], 8708c [tp::kChkRescored ],c [tp::kChkKeptOut ],c [tp::kChkKept ], (double )ratio ); 8709 } 8710 } 8711 } 8712#endif 8713 { 8714static const bool f16_range = std::getenv ("STRATA_F16_RANGE" )!= nullptr ; 8715float xm = 0.0f ,wy [2 ]= {0.0f ,0.0f };unsigned long long xo = 0 ,wyo [2 ]= {0 ,0 }; 8716if (f16_range && f16_range_read (xm ,xo , true)&& gemm_f16_range_read (wy ,wyo , true)) 8717 std::fprintf (stderr ,"strata f16 range: %lld tokens: activation images max |x| %.1f (%llu beyond 65504 or NaN), " 8718"BF16 weights max |w| %.3f (%llu), FP16 GEMM outputs max |y| %.1f (%llu not finite)\n" , 8719 (long long )n ,xm ,xo ,wy [0 ],wyo [0 ],wy [1 ],wyo [1 ]); 8720 } 8721if (pt .on ) { 8722pt .fold (); 8723double total = 0.0 ; 8724for (double v :pt .ms )total += v ; 8725 std::string line ; 8726char b [96 ]; 8727for (int i = 0 ;i < kPfCount ;++ i ) { 8728if (pt .ms [i ] <=0.0 )continue ; 8729 std::snprintf (b ,sizeof b ," %s %.0f (%.1f%%)" ,kPfNames [i ],pt .ms [i ],total > 0 ?100.0 * pt .ms [i ] /total :0.0 ); 8730line += b ; 8731 } 8732 std::fprintf (stderr ,"strata prefill timing: %lld tokens, GPU timeline %.0f ms, wall %.0f ms, host staging %.0f ms:%s\n" , 8733 (long long )n ,total ,ms_since (t_start ),stats_ .ms_experts_host ,line .c_str ()); 8734 std::fprintf (stderr ,"strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) %.0f ms, " 8735"waiting for each chunk %.0f ms, after each chunk (the draft layer, progress) %.0f ms, " 8736"PLE %.0f ms\n" ,host_setup_ms ,host_sync_ms ,host_chunk_ms ,stats_ .ms_ple ); 8737if (pe .on ) { 8738int pd = 0 ;cudaGetDevice (& pd );cudaSetDevice (pe .dev );cudaStreamSynchronize (m .pp -> s );pe .fold ();cudaSetDevice (pd ); 8739 std::string pl ; 8740for (int i = 0 ;i < kPeCount ;++ i ) { 8741 std::snprintf (b ,sizeof b ," %s %.0f" ,kPeNames [i ],pe .ms [i ]); 8742pl += b ; 8743 } 8744 std::fprintf (stderr ,"strata prefill timing (peer GPU, ms):%s; MoE layers %lld, rows/layer %.0f of %lld cap, experts/layer %.0f, " 8745"over the cap %lld\n" ,pl .c_str (), (long long )m .pp -> layers , 8746m .pp -> layers ? (double )m .pp -> rows /m .pp -> layers :0.0 , (long long )m .pp -> cap_rows , 8747m .pp -> layers ? (double )m .pp -> experts /m .pp -> layers :0.0 , (long long )m .pp -> over_cap ); 8748if (m .pp -> ps_frac > 0.0 ) 8749 std::fprintf (stderr ,"strata prefill timing: peer-streamed experts %lld (%.0f per MoE layer)\n" , 8750 (long long )m .pp -> ps_experts ,m .pp -> layers ? (double )m .pp -> ps_experts /m .pp -> layers :0.0 ); 8751 } 8752 } 8753if (kva_run || kva .capture ) { 8754const char * mode = kva .skip == KvaConfig ::Skip ::Moe ?"moe-skip" 8755 :kva .mode == KvaConfig ::Mode ::Oracle ?"oracle" 8756 :kva .mode == KvaConfig ::Mode ::Linear ?"linear" :"identity" ; 8757const char * only = kva .only == KvaConfig ::Only ::Gdn ?", gdn layers only" 8758 :kva .only == KvaConfig ::Only ::Qsa ?", qsa layers only" :"" ; 8759 std::fprintf (stderr ,"strata prefill: KVA %s: split %lld, suffix %lld, approximated %lld of %lld positions " 8760"in %lld of %lld chunks, mode %s%s%s\n" , 8761kva_run ?"on" :"off (capture)" , (long long )kva_split , (long long )kva_suffix , 8762 (long long )kva_positions , (long long )n , (long long )kva_chunks , 8763 (long long ) (n > 0 && m .T > 0 ? (n + m .T - 1 ) /m .T :0 ),mode ,only , 8764kva .capture ?", capturing the late layers' inputs" :"" ); 8765if (kva_positions > 0 ) { 8766// What a later turn does with this state (serve): it continues from the live session or a checkpoint of 8767// it and reads only the new tokens, exactly, over the cells this read left; nothing is approximated twice. 8768// The answer quality of those turns is that of this read. STRATA_KVA=0 reads exactly. 8769static std::atomic < bool > said {false}; 8770if (!said .exchange (true)) 8771 std::fprintf (stderr ,"strata prefill: KVA: the late layers (%lld and up) hold approximated cells for " 8772"the first %lld positions of this prompt; a follow-up turn that continues from " 8773"this state reads its new tokens exactly on top of them (nothing is approximated " 8774"twice); STRATA_KVA=0 reads every prompt exactly\n" , 8775 (long long )kva_split , (long long )kva_positions ); 8776 } 8777 }else if (kva .on && (kva .explicit_on || (n >=kva .min_prompt && !kva_routine && kva_eng .blocked .empty ()))) { 8778// KVA-8 (observability): a run that was configured for KVA but fell back completely must say so and why, 8779// or an operator cannot tell it apart from a run where the feature was never asked for. (KVA only runs 8780// when STRATA_KVA=1 asked for it, so every reason is worth a line.) 8781if (kva_why_not == kKvaShapeReason ) 8782 std::fprintf (stderr ,"strata prefill: KVA configured but NOT applied: this model's shape (%lld layers, %lld experts) " 8783"is not one KVA was measured on (STRATA_KVA_ANY_MODEL=1 allows it)\n" , 8784 (long long )g .n_layers , (long long )g .n_expert ); 8785else 8786 std::fprintf (stderr ,"strata prefill: KVA configured but NOT applied: %s (prompt %lld positions, " 8787"min_prompt %lld, suffix %lld, split %lld)\n" , 8788kva_why_not != nullptr ?kva_why_not :"not applicable" , (long long )n , (long long )kva .min_prompt , 8789 (long long )kva_suffix , (long long )kva_split ); 8790 } 8791if (std::getenv ("STRATA_STATE_HASH_GDN" )!= nullptr ) {// debug: the GDN states as the prompt path leaves them 8792cudaStreamSynchronize (m .cs ); 8793 std::vector < uint8_t > b ((size_t )gdn_floats * 4 ); 8794 std::string line ; 8795char h [8 ]; 8796for (int64_t i = 0 ;i < ss .gdn_alloc ;++ i ) { 8797cudaMemcpy (b .data (),ss .gdn_state + (size_t )i * gdn_floats ,b .size (),cudaMemcpyDeviceToHost ); 8798uint64_t x = 1469598103934665603ull ; 8799for (uint8_t c :b )x = (x ^c )* 1099511628211ull ; 8800 std::snprintf (h ,sizeof (h ),"%04llx " , (unsigned long long ) (x & 0xffff )); 8801line += h ; 8802 } 8803 std::fprintf (stderr ,"strata prefill: GDN_HASH %s\n" ,line .c_str ()); 8804 } 8805return true; 8806} 8807 8808// ============================================================================================================ 8809// Layer-major prefill (STRATA_PREFILL_LAYER_MAJOR=1). 8810// 8811// The default prompt path reads a chunk (here 512 tokens) through all 48 layers, so every chunk streams every routed 8812// expert of every layer to the GPU again - ~25-34 GB of expert blobs per chunk on Q2_0, which is what bounds a prompt 8813// on a small card (PCIe / NVMe). This path reads a SUPER-CHUNK of S tokens layer by layer instead: for layer l it 8814// runs each sub-chunk's attention half, the FFN half's hyper-connection read, the router and the shared expert 8815// (in order, so the GDN / QSA / PLE state advance exactly as in the default path), parks what the experts need 8816// (the FFN input rows, the routing, the shared expert's part of the output) and then runs the layer's experts ONCE 8817// for all S tokens: each routed expert is staged once, its rows of every sub-chunk computed in one MMQ group, and 8818// the results added per token into the super-chunk's accumulator. The FFN half's hyper-connection write of layer l 8819// runs at the start of the sub-chunk's layer l + 1 (or in the final pass). Expert traffic drops by ~S / 512. 8820// 8821// The residual rows of the super-chunk live in VRAM when they fit (STRATA_PREFILL_LM_R=vram) or in pinned host 8822// memory, copied in and out per sub-chunk and layer (host). Only the experts' sum differs from the default path: 8823// it is added per expert group in id order, not in the router's k order (FP32 rounding), and the MMQ products run on 8824// other row groupings. on_chunk reports every sub-chunk in order from the final pass; while it reports one before 8825// the super-chunk's end, layer_major_mid() is true (the session state is the super-chunk's end: no checkpoint). 8826namespace { 8827const char * lm_env_text () {// STRATA_PREFILL_LAYER_MAJOR as set (nullptr: unset); the rule for unset is strata::prefill_layer_major_default 8828static const char * const e = std::getenv ("STRATA_PREFILL_LAYER_MAJOR" ); 8829return e ; 8830} 8831bool lm_env_explicit () {const char * e = lm_env_text ();return e != nullptr && e [0 ]!= '\0' ; } 8832 8833bool lm_force_env () {// STRATA_PREFILL_LM_FORCE=1 (research): the layer-major walk even for a prompt under two chunks (the identity reference of a multi-prompt read) 8834static const bool v = [] {const char * e = std::getenv ("STRATA_PREFILL_LM_FORCE" );return e != nullptr && e [0 ]== '1' ; }(); 8835return v ; 8836} 8837 8838bool lm_even_env () {// even super-chunks (STRATA_PREFILL_LM_EVEN=0: the largest that fits, then the rest) 8839static const bool v = [] {const char * e = std::getenv ("STRATA_PREFILL_LM_EVEN" );return !(e && e [0 ]== '0' ); }(); 8840return v ; 8841} 8842 8843int64_t lm_tokens_env () {// the super-chunk's target size (0: the default) 8844static const int64_t v = [] {const char * e = std::getenv ("STRATA_PREFILL_LM_TOKENS" );return e ? (int64_t ) std::atoll (e ) : (int64_t )0 ; }(); 8845return v ; 8846} 8847int64_t lm_next_env () {// STRATA_PREFILL_LM_NEXT: slots for the next layer's RAM-tier experts (0: off) 8848static const int64_t v = [] {const char * e = std::getenv ("STRATA_PREFILL_LM_NEXT" );return e ? (int64_t ) std::atoll (e ) : (int64_t )0 ; }(); 8849return v ; 8850} 8851int lm_r_env () {// 0 auto, 1 vram, 2 host 8852static const int v = [] { 8853const char * e = std::getenv ("STRATA_PREFILL_LM_R" ); 8854if (!e )return 0 ; 8855const std::string s (e ); 8856return s == "vram" ?1 :s == "host" ?2 :0 ; 8857 }(); 8858return v ; 8859} 8860// VRAM left free while a prompt runs (the verify windows, the driver): 96 MiB when STRATA_PREFILL_LAYER_MAJOR=1 asked for the walk, 512 MiB when 8861// it is on by default (a user who set nothing gets the wider margin) 8862int64_t lm_margin_bytes (bool by_default ) { 8863static const int64_t explicit_v = [] { 8864const char * e = std::getenv ("STRATA_PREFILL_LM_MARGIN_MIB" ); 8865return e ? (int64_t ) std::atoll (e ) <<20 : (int64_t )-1 ; 8866 }(); 8867return explicit_v >=0 ?explicit_v : (int64_t ) (by_default ?512 :96 ) <<20 ; 8868} 8869constexpr int64_t kLmDefaultTokens = 8192 ; 8870// the super-chunk target when the walk is on by default and STRATA_PREFILL_LM_TOKENS is not set: the size measured (2x RTX A4000, 32K prompts) 8871constexpr int64_t kLmDefaultOnTokens = 32768 ; 8872// the device tables of one layer, in int32s: row_tok (rows) | bounds (2 E) | u_tok (rows) | u_off (rows + E) | 8873// u_rows (rows) | u_w (rows), E = the most entries a layer can split into 8874int64_t lm_entries_max (int64_t rows ,int64_t G ) {return NE + rows / std::max < int64_t > (G ,1 )+ 2 ; } 8875int64_t lm_table_ints (int64_t rows ,int64_t G ) {return 5 * rows + 3 * lm_entries_max (rows ,G ); } 8876// The walk's groups of layer l on the fused int8 kernels (P4-SMALL): one launch pair per gathered group (fused::group_bounds from the group's 8877// bounds, experts_native on the experts where they are, the rows' tokens from row_tok) in place of MMQ's quantize, gate/up, SwiGLU, 8878// quantize and down. A native layer MMQ takes in the walk, whose formats the kernels cover on this device (native_supported: the card 8879// rule and the formats), not a Hadamard-folded or NVFP4 one (lm_prepare declines those anyway). The walk's MMQ buffers hold what it 8880// needs: the tables in GU, the int8 H in H, the down rows in Dm; the per-token int8 rows are the super-chunk's own (LmBufs::xa). CUDA 8881// (the HIP walk is opt-in and not measured with it); not with STRATA_PF_GROUP_SCRATCH's one-group GU / H. 8882bool lm_fused_layer (int64_t l ,bool group_scratch ) { 8883#if defined(STRATA_USE_HIP )|| defined(STRATA_HIP_GFX906 ) 8884 (void )l ; (void )group_scratch ; 8885return false; 8886#else 8887const strata::kernels::cpu::ExpertLayout & lay = strata::kernels::cpu::expert_layout (); 8888const MmqPlan & mp = mmq_plan (); 8889// (a build without MMQ has no layer on MMQ: the layers the fused kernels cover are the plan's `fo` ones, which this walk takes the same way; a build with MMQ keeps 8890// its `fo` layers on the FP16 path in the walk as before) 8891if (group_scratch || !lay .native || l < 0 || l >= (int64_t )mp .layer .size ()|| l >= (int64_t )lay .fmt .size ())return false; 8892if (!mp .layer [(size_t )l ]&& !(!mmq::built ()&& mp .any && mp .fo [(size_t )l ]))return false; 8893const auto & f = lay .fmt [(size_t )l ]; 8894if (f .had_gu || f .had_d || f .tail_off )return false; 8895return fused::native_supported (f .gu_type ,f .d_type ); 8896#endif 8897} 8898// the most A batches a latent layer cuts its rows into: one per routed expert, plus the pieces of an expert with more 8899// rows than the tile buffers 8900int64_t lm_lat_batches (int64_t rows ,int64_t G ) {return NE + rows / std::max < int64_t > (G ,1 )+ 2 ; } 8901}// namespace 8902 8903void Prefill ::lm_release () { 8904Impl & m = * impl_ ; 8905const core::OnDevice on_device (m .device ); 8906if (m .lm .dev ) { 8907cudaStreamSynchronize (m .cs ); 8908cudaFree (m .lm .dev ); 8909 } 8910if (m .lm .lat_host ) { 8911cudaStreamSynchronize (m .cs ); 8912cudaFreeHost (m .lm .lat_host ); 8913 } 8914m .lm .lat_host = nullptr ; 8915m .lm .lat_xlq = m .lm .lat_ylq = nullptr ; 8916m .lm .lat_tok = m .lm .lat_slot = nullptr ; 8917m .lm .lat_sg = nullptr ; 8918m .lm .lat_tabs = nullptr ; 8919m .lm .lat_tabs_n = 0 ; 8920m .lm .pre = nullptr ; 8921m .lm .pre_n = 0 ; 8922m .lm .pre_layer = -1 ; 8923m .lm .dev = nullptr ; 8924m .lm .mixed = m .lm .acc = m .lm .inj = m .lm .R = m .lm .w = m .lm .R2 = nullptr ; 8925m .lm .mixed_h = nullptr ; 8926m .lm .xa = nullptr ; 8927m .lm .ids = m .lm .tab = nullptr ; 8928m .lm .S = 0 ; 8929} 8930 8931int64_t Prefill ::lm_prepare (int64_t n , std::string & why ,int64_t cap ) { 8932Impl & m = * impl_ ; 8933if (m .g == nullptr ) {why = "not initialized" ;return 0 ; } 8934#if defined(STRATA_USE_HIP )|| defined(STRATA_HIP_GFX906 ) 8935// only NVIDIA CUDA has run this path by default; on an AMD build the prompt stays on the chunk-major path unless 8936// STRATA_LM_HIP=1 (opt-in, PAR-A 2026-10-30: gfx1201 is being qualified) 8937 { 8938static const bool lm_hip = [] {const char * v = std::getenv ("STRATA_LM_HIP" );return v != nullptr && v [0 ]== '1' ; }(); 8939if (!lm_hip ) { 8940why = "layer-major prefill has only been run on NVIDIA CUDA" ; 8941return 0 ; 8942 } 8943 } 8944#endif 8945const core::ModelGeometry & g = * m .g ; 8946const core::OnDevice on_device (m .device );// a layer split's later stage is sized on its own GPU 8947// layer split (2026-10-24): each stage runs its own layers layer-major over the same super-chunk and hands the 8948// super-chunk's rows to the next one (lm_prepare_chain); the peer GPU's expert share and the stage helper have 8949// no layer-major form 8950const bool split = stage_lb_ != 0 || stage_le_ != g .n_layers || next_ != nullptr ; 8951if (hand_in_ != nullptr ) {why = "a layer split's chunk hand-off is in use" ;return 0 ; } 8952if (m .pp || helper_ != nullptr || core::peer_portable ()) {why = "a peer GPU" ;return 0 ; } 8953// the PLE block (layer 1) reads the token history: on a split it runs in a first stage that holds layers 0 and 1 8954// (a later stage never reaches it) 8955if (split && m .ss -> ple .ready ()&& stage_lb_ <=1 && !(stage_lb_ == 0 && stage_le_ >=2 )) { 8956why = "a layer split whose PLE layer is not in the first stage" ; 8957return 0 ; 8958 } 8959if (embd_rows != nullptr ) {why = "an image prompt" ;return 0 ; } 8960// features of run_impl this walk does not carry: KVA's approximate late layers (a prompt that wants them takes the chunk-major path, which has it). 8961// The DFlash2 drafter's prompt taps it carries for one stage and one prompt (DF-08: lm_run taps a layer's completed output when the next layer starts) 8962if (!tap_layers_ .empty ()&& (split || !on_taps || tap_cap_ <=0 )) {why = "the DFlash2 drafter's prompt taps on a layer split" ;return 0 ; } 8963if (kva_config ().on ) {why = "STRATA_KVA is on" ;return 0 ; } 8964if (stop_at_chunk ) {why = "a batch read that yields at chunk boundaries" ;return 0 ; } 8965if (force_chunk_ > 0 ) {why = "a --prefill-pipe plan sets the chunks of this read" ;return 0 ; }// (left set for run_impl) 8966#if STRATA_EXPERT_NIBBLE_BUILT // the 4-bit expert slots (STRATA_EXPERT_NIBBLE) are gathered for MMQ only by run_impl 8967for (int64_t l = 0 ;l < g .n_layers ;++ l ) 8968if (core::nibble::layer (l ).on ) {why = "STRATA_EXPERT_NIBBLE (the experts are 4-bit slots)" ;return 0 ; } 8969#endif 8970// run_impl's debug hooks on the routing and the rows have no layer-major form 8971if (std::getenv ("STRATA_DBG_FEAT" )|| std::getenv ("STRATA_DBG_ROUTE_OVERRIDE" )|| std::getenv ("STRATA_PREFILL_DUMP_R_ALL" )) { 8972why = "a routing or row debug dump" ; 8973return 0 ; 8974 } 8975if (m .latent ) { 8976const char * mmq = std::getenv ("STRATA_LATENT_MMQ" ); 8977if (mmq && mmq [0 ]== '1' ) {why = "latent layer-major MMQ is not supported" ;return 0 ; } 8978if (m .lat_ELL != 1792 || m .lat_G != 8 || m .lat_I != 640 || m .lat_E != NE || 8979g .n_expert != NE || !m .cache || !m .host_res || 8980 !m .lat_d_dev || !m .lat_u_dev || !m .ids_identity || !m .yl || !m .ylq || !m .lat_scratch ) { 8981why = "latent layer-major buffers or geometry are unsupported" ; 8982return 0 ; 8983 } 8984 } 8985if (!m .latent ) { 8986const MmqPlan & mp = mmq_plan (); 8987if ((int64_t )mp .layer .size ()< g .n_layers ) {why = "the expert plan has fewer layers than the model" ;return 0 ; } 8988// each layer's experts on MMQ, or (port, 2026-10-24) on run_impl's FP16 path; the buffers each one needs 8989int64_t n_mmq = 0 ; 8990for (int64_t l = 0 ;l < g .n_layers ;++ l )n_mmq += mp .layer [(size_t )l ] ?1 :0 ; 8991if (n_mmq > 0 && (!m .grp_gu || !m .grp_d || !m .Xq || !m .H || !m .Hq )) {why = "the MMQ buffers are missing" ;return 0 ; } 8992if (n_mmq < g .n_layers ) { 8993bool dq_ok = true; 8994for (int i = 0 ;i < DQ ;++ i )dq_ok = dq_ok && m .dq_gu [i ]&& m .dq_d [i ]; 8995if (!m .Xs || !m .Hh || !dq_ok ) {why = "the FP16 expert path's buffers are missing" ;return 0 ; } 8996 } 8997// 0.2.2's expert formats this path's MMQ pass does not carry (port, 2026-10-24): APR's Hadamard-folded layers, 8998// NVFP4's tails and w4a4 activations, and IQ1_M layers that only the WMMA tiles run 8999 { 9000const strata::kernels::cpu::ExpertLayout & lay = strata::kernels::cpu::expert_layout (); 9001for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 9002if (l < (int64_t )mp .wmma_only .size ()&& mp .wmma_only [(size_t )l ]) {why = "a layer needs the WMMA tiles" ;return 0 ; } 9003if (!lay .native )continue ; 9004const auto & f = lay .fmt [(size_t )l ]; 9005if (f .had_gu || f .had_d ) {why = "an APR (Hadamard-folded) layer" ;return 0 ; } 9006if (f .tail_off || mmq::fp4_activations (f .gu_type )) {why = "an NVFP4 layer" ;return 0 ; } 9007 } 9008 } 9009if (m .fused_bufs ) {why = "the fused expert layout" ;return 0 ; } 9010if (!m .GU || !m .Dm || (n_mmq > 0 && !m .ids_identity )) {why = "the MoE buffers are missing" ;return 0 ; } 9011 } 9012// (an explicit STRATA_PREFILL_LM_TOKENS may be one chunk: the A/B against the default path, experts aside) 9013const int64_t min_s = (lm_force_ || lm_force_env ()) ?1 : (lm_tokens_env ()> 0 ?m .T :2 * m .T );// (lm_force_: run_multi - several prompts, however short) 9014if (n < min_s ) {why = "a short prompt" ;return 0 ; } 9015const int64_t want = lm_tokens_env ()> 0 ?lm_tokens_env () : (lm_by_default_ ?kLmDefaultOnTokens :kLmDefaultTokens ); 9016int64_t S = std::max < int64_t > (min_s ,want /m .T * m .T ); 9017S = std::min < int64_t > (S , (n + m .T - 1 ) /m .T * m .T ); 9018if (cap > 0 ) { 9019if ((!lm_force_ && cap %m .T != 0 )|| cap < min_s ) {why = "the layer split's stages read different chunks" ;return 0 ; } 9020S = std::min (S ,cap ); 9021 } 9022if (m .latent && S > INT32_MAX / std::max < int64_t > (m .lat_G ,K )) { 9023why = "latent super-chunk route indices exceed int32" ; 9024return 0 ; 9025 } 9026const int64_t G = m .T * K ; 9027bool fz = false;// a layer's groups run on the fused kernels: the super-chunk's int8 rows (LmBufs::xa) 9028for (int64_t l = 0 ;l < g .n_layers && !fz ;++ l )fz = lm_fused_layer (l ,m .group_cap > 0 ); 9029// ylq (A's output) stays in VRAM whenever that does not cost super-chunk size; mapped RAM otherwise 9030bool y_dev = true; 9031const auto dev_bytes = [& ](int64_t s ,bool r_dev ) { 9032const uint64_t per = (uint64_t ) (2 * N + HC + 2 * K )* 4 + (uint64_t )N * 2 + (r_dev ? (uint64_t )D * 4 :0 ); 9033// xlq stays in VRAM in both modes: A re-reads it once per gate/up row block, too often for mapped RAM 9034const uint64_t latent = m .latent ? (uint64_t )s * (2 * K * 4 + 4 )+ 9035 (uint64_t )s * (m .lat_G + (r_dev || y_dev ?K :0 ))* (m .lat_ELL /32 * 36 )+ 9036 (uint64_t )lm_lat_batches (s * K ,G )* fused::latent_group_bytes (G , (int )NE )+ 256 :0 ; 9037return (uint64_t )s * per + latent + (uint64_t )lm_table_ints (s * K ,G )* 4 + (m .latent ?8192 :4096 )+ 9038 (r_dev ?0 : (uint64_t )m .T * D * 4 + 256 )+ (fz ? (uint64_t ) fused::act_bytes (s ,N )+ 256 :0 ); 9039 }; 9040size_t free_b = 0 ,total_b = 0 ; 9041cudaMemGetInfo (& free_b ,& total_b ); 9042const int64_t room = (int64_t )free_b - lm_margin_bytes (lm_by_default_ ); 9043m .lm .free_mib = (int64_t ) (free_b >>20 ); 9044auto fit = [& ](bool r_dev ) {// the largest super-chunk (a multiple of the chunk) that fits `room` 9045int64_t s = S ; 9046while (s >=min_s && (int64_t )dev_bytes (s ,r_dev )> room )s -= m .T ; 9047return s >=min_s ?s : (int64_t )0 ; 9048 }; 9049// a stage after the first: its rows arrive in R_host (the previous stage writes them there); in VRAM mode it copies 9050// them up once a super-chunk instead of once a layer and sub-chunk 9051const int mode = lm_r_env (); 9052bool r_dev = false; 9053int64_t s_use = 0 ; 9054auto fit_host = [& ] {// host residual rows: ylq in VRAM unless mapped RAM allows a bigger super-chunk 9055y_dev = true; 9056const int64_t with_y = fit (false); 9057y_dev = false; 9058const int64_t without_y = fit (false); 9059// ylq crosses PCIe twice per layer when mapped: a smaller super-chunk with ylq in VRAM is faster 9060// (STRATA_PREFILL_LM_YLQ=map, A/B: the bigger super-chunk wins, as before) 9061static const bool y_map = [] {const char * e = std::getenv ("STRATA_PREFILL_LM_YLQ" );return e && std::string (e )== "map" ; }(); 9062y_dev = m .latent && (y_map ?with_y >=without_y :with_y > 0 ); 9063return y_dev ?with_y :without_y ; 9064 }; 9065if (mode == 1 ) {s_use = fit (true);r_dev = true; } 9066else if (mode == 2 ) {s_use = fit_host (); } 9067else {// auto: VRAM when the whole target fits there, else pinned host (the bigger super-chunk wins) 9068const int64_t sv = fit (true); 9069if (sv == S ) {s_use = sv ;r_dev = true; }else s_use = fit_host (); 9070 } 9071if (s_use <=0 ) { 9072why = "no VRAM for a super-chunk (" + std::to_string (free_b >>20 )+ " MiB free)" ; 9073return 0 ; 9074 } 9075Impl ::LmBufs & lb = m .lm ; 9076// pinned host: the routing's copy, the tables, and (host mode) the residual rows 9077const size_t idsw = (size_t ) (2 * s_use * K ),tab = (size_t )lm_table_ints (s_use * K ,G ); 9078auto host_grow = [](int32_t *& p ,size_t & have ,size_t want_n )-> bool { 9079if (have >=want_n )return true; 9080if (p )cudaFreeHost (p ); 9081p = nullptr ; 9082have = 0 ; 9083if (cudaHostAlloc ((void ** )& p ,want_n * 4 ,cudaHostAllocDefault )!= cudaSuccess ) {cudaGetLastError ();p = nullptr ;return false; } 9084have = want_n ; 9085return true; 9086 }; 9087if (!host_grow (lb .idsw_host ,lb .idsw_host_n ,idsw )|| !host_grow (lb .tab_host ,lb .tab_host_n ,tab )) { 9088why = "no pinned RAM for the routing tables" ;return 0 ; 9089 } 9090if (!r_dev || stage_lb_ > 0 ) { 9091int32_t * rh = (int32_t * )lb .R_host ; 9092if (!host_grow (rh ,lb .R_host_n , (size_t )s_use * D )) {why = "no pinned RAM for the residual rows" ;lb .R_host = nullptr ;return 0 ; } 9093lb .R_host = (float * )rh ; 9094 } 9095int64_t pre_n = 0 ; 9096if (m .latent && lm_next_env ()> 0 ) {// as many as fit beside the super-chunk's buffers 9097const int64_t left = room - (int64_t )dev_bytes (s_use ,r_dev ); 9098pre_n = std::clamp < int64_t > (left / std::max < int64_t > (MAXBLOB (),1 ),0 , std::min < int64_t > (lm_next_env (),NE )); 9099 } 9100const uint64_t bytes = dev_bytes (s_use ,r_dev )+ (uint64_t )pre_n * (uint64_t )MAXBLOB ()+ 256 ; 9101void * d = nullptr ; 9102if (cudaMalloc (& d ,bytes )!= cudaSuccess ) { 9103cudaGetLastError (); 9104why = "the super-chunk's buffers (" + std::to_string (bytes >>20 )+ " MiB) do not fit" ; 9105return 0 ; 9106 } 9107lb .dev = d ; 9108uint8_t * q = (uint8_t * )d ; 9109auto carve_b = [& ](size_t b ) {uint8_t * p = q ;q += (b + 255 )& ~(size_t )255 ;return p ; }; 9110lb .mixed = (float * )carve_b ((size_t )s_use * N * 4 ); 9111lb .acc = (float * )carve_b ((size_t )s_use * N * 4 ); 9112lb .mixed_h = (uint16_t * )carve_b ((size_t )s_use * N * 2 ); 9113lb .inj = (float * )carve_b ((size_t )s_use * HC * 4 ); 9114lb .ids = (int32_t * )carve_b ((size_t )s_use * K * 4 ); 9115lb .w = (float * )carve_b ((size_t )s_use * K * 4 ); 9116lb .R = r_dev ? (float * )carve_b ((size_t )s_use * D * 4 ) :nullptr ; 9117lb .tab = (int32_t * )carve_b (tab * 4 ); 9118lb .tab_n = tab ; 9119if (m .latent ) { 9120lb .lat_tok = (int32_t * )carve_b ((size_t )s_use * K * 4 ); 9121lb .lat_slot = (int32_t * )carve_b ((size_t )s_use * K * 4 ); 9122lb .lat_sg = (float * )carve_b ((size_t )s_use * 4 ); 9123lb .lat_tabs_n = (size_t )lm_lat_batches (s_use * K ,G )* fused::latent_group_bytes (G , (int )NE ); 9124lb .lat_tabs = carve_b (lb .lat_tabs_n ); 9125lb .pre_n = pre_n ; 9126lb .pre = pre_n > 0 ?carve_b ((size_t )pre_n * (size_t )MAXBLOB ()) :nullptr ; 9127lb .pre_layer = -1 ; 9128lb .pre_of .assign ((size_t )NE ,-1 ); 9129for (cudaEvent_t * e : {& lb .pre_done ,& lb .pre_free }) 9130if (pre_n > 0 && * e == nullptr && cudaEventCreateWithFlags (e ,cudaEventDisableTiming )!= cudaSuccess ) { 9131cudaGetLastError (); 9132* e = nullptr ; 9133lb .pre_n = 0 ; 9134 } 9135const size_t xb = (size_t )s_use * m .lat_G * (m .lat_ELL /32 * 36 ); 9136const size_t yb = (size_t )s_use * K * (m .lat_ELL /32 * 36 ); 9137lb .lat_xlq = carve_b (xb ); 9138if (r_dev || y_dev ) { 9139lb .lat_ylq = carve_b (yb ); 9140 }else {// ylq is written once by A and read once by U 9141void * mapped = nullptr ; 9142if (cudaHostAlloc (& lb .lat_host ,yb ,cudaHostAllocMapped )!= cudaSuccess || 9143cudaHostGetDevicePointer (& mapped ,lb .lat_host ,0 )!= cudaSuccess ) { 9144cudaGetLastError (); 9145why = "no mapped RAM for the latent super-chunk" ; 9146lm_release (); 9147return 0 ; 9148 } 9149lb .lat_ylq = (uint8_t * )mapped ; 9150 } 9151 } 9152lb .R2 = r_dev ?nullptr : (float * )carve_b ((size_t )m .T * D * 4 ); 9153lb .xa = fz ?carve_b (fused::act_bytes (s_use ,N )) :nullptr ; 9154for (int b = 0 ;b < 2 ;++ b ) 9155for (cudaEvent_t * e : {& lb .ev_in [b ],& lb .ev_done [b ],& lb .ev_out [b ]}) 9156if (* e == nullptr && cudaEventCreateWithFlags (e ,cudaEventDisableTiming )!= cudaSuccess ) { 9157cudaGetLastError (); 9158* e = nullptr ; 9159why = "the copy events" ; 9160lm_release (); 9161return 0 ; 9162 } 9163lb .r_dev = r_dev ; 9164lb .S = s_use ; 9165return s_use ; 9166} 9167 9168// A layer split: every stage gets the same super-chunk (the smallest any of them fits), re-sized until they agree. 9169int64_t Prefill ::lm_prepare_chain (int64_t n , std::string & why ) { 9170// a later stage's hand_in_ still points at the last chunk a chunk-major prompt handed it (run_impl never clears it): 9171// with no hand-off in flight that is stale, not in use (a short prompt first would otherwise turn layer-major off 9172// for every later prompt) 9173for (Prefill * p = this ;p -> next_ != nullptr ;p = p -> next_ ) 9174if (p -> next_run_ .valid ()) {why = "a layer split's chunk hand-off is in flight" ;return 0 ; } 9175for (Prefill * p = next_ ;p != nullptr ;p = p -> next_ ) { 9176p -> hand_in_ = nullptr ; 9177p -> hand_ev_ = nullptr ; 9178p -> hand_pieces_ = 0 ; 9179 } 9180int64_t cap = 0 ; 9181for (int round = 0 ;round < 4 ;++ round ) { 9182bool same = true; 9183for (Prefill * p = this ;p != nullptr ;p = p -> next_ ) { 9184Impl ::LmBufs & lb = p -> impl_ -> lm ; 9185if (lb .S > 0 && lb .S == cap )continue ; 9186if (lb .S > 0 )p -> lm_release (); 9187const int64_t s = p -> lm_prepare (n ,why ,cap ); 9188if (s <=0 ) { 9189if (p != this ) 9190why = "layers " + std::to_string (p -> stage_lb_ )+ ".." + std::to_string (p -> stage_le_ )+ ": " + why ; 9191lm_release_chain (); 9192return 0 ; 9193 } 9194if (cap > 0 && s != cap )same = false; 9195cap = s ; 9196 } 9197if (same ) { 9198// even super-chunks (STRATA_PREFILL_LM_EVEN, default on): n split into the same number of super-chunks 9199// of near-equal size (32K at a 28K fit: 2 x 16K, not 28K + 4K), so a stage's residual rows fit VRAM 9200// and a layer split's stages overlap on every super-chunk 9201const int64_t T = impl_ -> T ; 9202const int64_t k = (n + cap - 1 ) /cap ; 9203const int64_t even = ((n + k - 1 ) /k + T - 1 ) /T * T ; 9204if (k < 2 || even >=cap || !lm_even_env ())return cap ; 9205for (Prefill * p = this ;p != nullptr ;p = p -> next_ ) { 9206p -> lm_release (); 9207if (p -> lm_prepare (n ,why ,even )!= even ) { 9208if (p != this ) 9209why = "layers " + std::to_string (p -> stage_lb_ )+ ".." + std::to_string (p -> stage_le_ )+ ": " + why ; 9210lm_release_chain (); 9211return 0 ; 9212 } 9213 } 9214return even ; 9215 } 9216 } 9217why = "the layer split's stages found no common super-chunk" ; 9218lm_release_chain (); 9219return 0 ; 9220} 9221 9222void Prefill ::lm_release_chain () { 9223for (Prefill * p = this ;p != nullptr ;p = p -> next_ ) 9224if (p -> impl_ )p -> lm_release (); 9225} 9226 9227bool Prefill ::run_layer_major (const int64_t * tokens ,int64_t n ,int64_t pos0 , std::string & err ) { 9228Seg one ; 9229one .tokens = tokens ; 9230one .n = n ; 9231one .pos0 = pos0 ; 9232return lm_run (std::vector < Seg > {one },0 ,nullptr ,err ); 9233} 9234 9235// Several prompts in ONE layer-major pass (PAR-H, 2026-10-30): the super-chunk is a list of sub-chunks, each from one 9236// prompt ("segment") with its own sessions; a layer's attention halves run per sub-chunk against that segment's 9237// session (GDN / QSA / PLE state), and the layer's experts are staged ONCE for every sub-chunk of the super-chunk - 9238// the streamed experts cost is shared by the prompts. A single segment with no sessions given is exactly the usual run. 9239bool Prefill ::run_multi (const std::vector < Seg >& segs , std::string & err ) { 9240err .clear (); 9241if (segs .empty ()) {err = "prefill: no prompt" ;return false; } 9242int64_t total = 0 ; 9243for (const Seg & sg :segs )total += sg .n ; 9244 std::string why ; 9245if (hand_in_ != nullptr || !impl_ ) {err = "prefill: multi-prompt read declined (chunk hand-off in use)" ;return false; } 9246if (!tap_layers_ .empty ()) {err = "prefill: multi-prompt read declined (the DFlash2 prompt taps are for one prompt)" ;return false; } 9247for (Prefill * q = this ;q != nullptr ;q = q -> next_ )q -> lm_force_ = true; 9248struct ForceOff {Prefill * h ; ~ForceOff () {for (Prefill * q = h ;q != nullptr ;q = q -> next_ )q -> lm_force_ = false; } }force_off {this }; 9249if (lm_prepare_chain (total ,why ) <=0 ) {err = "prefill: multi-prompt read declined: " + why ;return false; } 9250bool ok = lm_run (segs ,0 ,nullptr ,err ); 9251 std::string drain_err ; 9252if (!drain_pipeline (drain_err )&& ok ) { 9253ok = false; 9254err = drain_err ; 9255 } 9256for (Prefill * q = this ;q != nullptr ;q = q -> next_ )q -> lm_mid_ = false; 9257lm_release_chain (); 9258return ok ; 9259} 9260 9261// read_short's weights of the first stage's layers: a copy of this GPU's table whose rows of those layers point into 9262// one of two layer slots, filled from the first stage's arena (and its latent D/U tables) a layer ahead 9263struct Prefill ::ShortWeights { 9264struct Item { core::WeightRef * dst ; core::WeightRef src ;uint64_t off ,bytes ,noff ,nbytes ; };// n*: native blocks 9265 core::WeightTable shadow ; 9266 std::vector < std::vector < Item >> items ;// per layer 9267uint8_t * slot [2 ]= {};// (set_short_slots's: not freed here) 9268uint64_t d_off = 0 ,u_off = 0 ,d_bytes = 0 ,u_bytes = 0 ; 9269const uint8_t * src_d = nullptr ,* src_u = nullptr ;// the first stage's D/U of layer 0 9270int src_dev = 0 ,dev = 0 ; 9271cudaStream_t st = nullptr ; 9272cudaEvent_t ready [2 ]= {},freed [2 ]= {}; 9273bool freed_set [2 ]= {}; 9274 ~ShortWeights () { 9275if (st )cudaStreamSynchronize (st ); 9276 } 9277// layer l's copies into slot l % 2, once the layer that used the slot before has finished there 9278bool issue (int64_t l ) { 9279const int s = (int ) (l & 1 ); 9280if (freed_set [s ]&& cudaStreamWaitEvent (st ,freed [s ],0 )!= cudaSuccess )return false; 9281for (const Item & it :items [(size_t )l ]) 9282if ((it .bytes && cudaMemcpyPeerAsync (slot [s ]+ it .off ,dev ,it .src .data ,src_dev , (size_t )it .bytes ,st )!= cudaSuccess )|| 9283 (it .nbytes && cudaMemcpyPeerAsync (slot [s ]+ it .noff ,dev ,it .src .native_data ,src_dev , (size_t )it .nbytes ,st )!= cudaSuccess )) 9284return false; 9285if (d_bytes && 9286 (cudaMemcpyPeerAsync (slot [s ]+ d_off ,dev ,src_d + (size_t )l * d_bytes ,src_dev , (size_t )d_bytes ,st )!= cudaSuccess || 9287cudaMemcpyPeerAsync (slot [s ]+ u_off ,dev ,src_u + (size_t )l * u_bytes ,src_dev , (size_t )u_bytes ,st )!= cudaSuccess )) 9288return false; 9289return cudaEventRecord (ready [s ],st )== cudaSuccess ; 9290 } 9291// before layer l's work on `cs`: its slot has landed, and its rows point there 9292bool begin (int64_t l ,cudaStream_t cs ) { 9293const int s = (int ) (l & 1 ); 9294for (const Item & it :items [(size_t )l ]) { 9295void * const q8_1 = it .dst -> native_q8_1 ;// (this GPU's scratch, set below) 9296* it .dst = it .src ; 9297it .dst -> data = it .bytes ?slot [s ]+ it .off :nullptr ; 9298it .dst -> native_data = it .nbytes ?slot [s ]+ it .noff :nullptr ; 9299it .dst -> native_q8_1 = it .nbytes ?q8_1 :nullptr ; 9300 } 9301return cudaStreamWaitEvent (cs ,ready [s ],0 )== cudaSuccess ; 9302 } 9303// after layer l's work on `cs`: its slot takes layer l + 2 9304bool end (int64_t l ,int64_t lo_end ,cudaStream_t cs ) { 9305const int s = (int ) (l & 1 ); 9306if (cudaEventRecord (freed [s ],cs )!= cudaSuccess )return false; 9307freed_set [s ]= true; 9308return l + 2 >=lo_end || issue (l + 2 ); 9309 } 9310const uint8_t * d (int64_t l )const {return slot [l & 1 ]+ d_off ; } 9311const uint8_t * u (int64_t l )const {return slot [l & 1 ]+ u_off ; } 9312}; 9313 9314bool Prefill ::lm_run (const std::vector < Seg >& segs ,int depth ,const std::vector < LmSub >* given_super , std::string & err ) { 9315err .clear (); 9316Impl & m = * impl_ ; 9317const core::OnDevice on_device (m .device ); 9318const core::ModelGeometry & g = * m .g ; 9319// the session of segment i on THIS stage: the segment's own (stage depth `depth`), else this stage's main session 9320auto ss_of = [& ](size_t i )-> core::SessionState * { 9321const Seg & sg = segs [i ]; 9322return (size_t )depth < sg .stage_ss .size ()&& sg .stage_ss [(size_t )depth ]!= nullptr ?sg .stage_ss [(size_t )depth ] :m .ss ; 9323 }; 9324 core::SessionState * ssp = ss_of (0 ); 9325const bool multi = segs .size ()> 1 ; 9326int64_t n = 0 ;// all the prompts' tokens 9327for (const Seg & sg :segs )n += sg .n ; 9328const int64_t pos0 = segs [0 ].pos0 ;// (only the progress line's) 9329const auto t_start = Clock ::now (); 9330const cudaStream_t cs = (cudaStream_t )m .cs ; 9331Impl ::LmBufs & lb = m .lm ; 9332const int64_t L = g .n_layers ; 9333// a layer split's stage (2026-10-24): its layers [LB, LE); a later stage's rows arrive in R_host, written by the 9334// stage before it, and a stage before the last writes its final rows into the next stage's R_host, then runs 9335// the next stage on that super-chunk on a thread while it reads its own next super-chunk (one hand-off buffer: 9336// its final pass waits until the next stage has finished the previous one) 9337const int64_t LB = stage_lb_ ,LE = stage_le_ ; 9338if (hand_in_ == nullptr )stopped_at_ = -1 ;// (stop_at_chunk is declined: this run reads every token) 9339 strata::kernels::QsaShapes s = core::qsa_shapes (g );// as 0.2.2's run_impl 9340const uint64_t gdn_floats = (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size + 9341 (uint64_t )g .ssm_conv_channels * (g .ssm_d_conv - 1 ); 9342// read_short: layers [0, short_end_) run against the scratch session `short_lo_` (it also holds the PLE run) 9343 core::SessionState * const pss = short_lo_ != nullptr ?short_lo_ :m .ss ; 9344 std::vector < std::array < int32_t ,2 >> prevs (segs .size ()); 9345for (size_t i = 0 ;i < segs .size ();++ i )prevs [i ]= {ss_of (i )-> ple_prev [0 ],ss_of (i )-> ple_prev [1 ]}; 9346if (short_lo_ != nullptr )prevs [0 ]= {short_lo_ -> ple_prev [0 ],short_lo_ -> ple_prev [1 ]}; 9347PfTimer pt ; 9348// the MMQ row table lives in the borrowed cache slots when the prompt path borrows: written for every prompt 9349// (none without an MMQ layer: the FP16 path has no such table) 9350if (m .ids_identity ) mmq::iota (m .ids_identity , (int64_t )mmq_ids_rows ((size_t )m .T ),m .cs ); 9351// ---- the PLE rows, read per chunk on a thread as run_impl does (the same state machine, in chunk order) 9352const bool ple_on = pss -> ple .ready (); 9353const bool ple_batch_env = ple_batch_enabled (); 9354const bool ple_batch = ple_on && ple_batch_env && strata::kernels::ple_native_postops_enabled ()&& 9355 (pss -> ple .w .key_bf16 != nullptr || pss -> ple .w .key_native_data != nullptr )&& 9356m .region_bytes / ((uint64_t ) (3 * strata::kernels::NG_HC_DIM + N + 4 )* 4 + (uint64_t )N * 2 + 4096 ) >=64 ; 9357// ---- the plan. A segment is cut into pieces of at most S tokens (the usual super-chunks), each piece into 9358// sub-chunks of m.T tokens from the piece's start; pieces of several segments are packed into one super-chunk while 9359// their rows fit S. One segment: exactly the usual super-chunks. 9360const int64_t S = m .lm .S ; 9361// the sub-chunk size of a multi-prompt read: what every stage of the chain can take (the stages' chunks may differ) 9362int64_t tsub = m .T ; 9363if (lm_force_ ) 9364for (const Prefill * q = this ;q != nullptr ;q = q -> next_ )tsub = std::min (tsub ,q -> impl_ -> T ); 9365 std::vector < std::vector < LmSub >> supers_own ; 9366const std::vector < std::vector < LmSub >>* supers_p = & supers_own ; 9367 std::vector < std::vector < LmSub >> one_given ; 9368if (given_super != nullptr ) { 9369one_given .push_back (* given_super ); 9370supers_p = & one_given ; 9371 }else { 9372 std::vector < LmSub > cur ; 9373int64_t cur_rows = 0 ; 9374for (size_t si = 0 ;si < segs .size ();++ si ) 9375for (int64_t p0s = 0 ;p0s < segs [si ].n ;p0s += S ) { 9376const int64_t piece = std::min (S ,segs [si ].n - p0s ); 9377if (!cur .empty ()&& cur_rows + piece > S ) { 9378supers_own .push_back (std::move (cur )); 9379cur .clear (); 9380cur_rows = 0 ; 9381 } 9382for (int64_t c0s = 0 ;c0s < piece ;c0s += tsub ) { 9383LmSub sb ; 9384sb .seg = (int )si ; 9385sb .c0 = p0s + c0s ; 9386sb .T = std::min (tsub ,piece - c0s ); 9387sb .t0 = cur_rows + c0s ; 9388cur .push_back (sb ); 9389 } 9390cur_rows += piece ; 9391 } 9392if (!cur .empty ())supers_own .push_back (std::move (cur )); 9393 } 9394const std::vector < std::vector < LmSub >>& supers = * supers_p ; 9395 std::vector < std::pair < int ,int >> flat ;// every sub-chunk in order: (super-chunk, sub-chunk) 9396for (size_t si = 0 ;si < supers .size ();++ si ) 9397for (size_t c = 0 ;c < supers [si ].size ();++ c )flat .push_back ({(int )si , (int )c }); 9398 std::vector < int64_t > flat_base (supers .size (),0 ); 9399for (size_t si = 1 ;si < supers .size ();++ si )flat_base [si ]= flat_base [si - 1 ]+ (int64_t )supers [si - 1 ].size (); 9400auto sub_at = [& ](int64_t gi )-> const LmSub & {return supers [(size_t )flat [(size_t )gi ].first ][(size_t )flat [(size_t )gi ].second ]; }; 9401const std::array < int32_t ,2 > prev_none {-1 ,-1 }; 9402 (void )prev_none ; 9403 std::vector < std::array < int32_t ,2 >> prev0s = prevs ; 9404auto ple_gather = [& m ,pss ,& segs ,& ss_of ,& prev0s ,& sub_at ](int64_t gi ,int buf , std::string & e )-> bool { 9405const LmSub & sb = sub_at (gi ); 9406const int64_t * tokens = segs [(size_t )sb .seg ].tokens ; 9407 core::SessionState * ssq = ss_of ((size_t )sb .seg ); 9408const int64_t c0 = sb .c0 ,T = sb .T ; 9409const std::array < int32_t ,2 >& prev0 = prev0s [(size_t )sb .seg ]; 9410auto at = [& ](int64_t i ) {return i < 2 ?prev0 [(size_t )i ] : (int32_t )tokens [i - 2 ]; }; 9411int32_t pv [2 ]= {at (c0 ),at (c0 + 1 )}; 9412for (int64_t t = 0 ;t < T ;++ t ) { 9413const int32_t tok = (int32_t )tokens [c0 + t ]; 9414 strata::kernels::ngram_rows (& tok ,pv ,1 ,pss -> ple .consts , 9415m .ple_rows [buf ].data ()+ t * strata::kernels::PLE_N_HEADS ); 9416pv [0 ]= pv [1 ]; 9417pv [1 ]= tok ; 9418 } 9419return pss -> ple .table -> gather_batch (m .ple_rows [buf ].data (), (size_t )T ,m .ple_emb_host [buf ],e ); 9420 }; 9421 std::string ple_next_err ; 9422 std::future < bool > ple_next ; 9423int ple_buf = 0 ; 9424auto ple_land = [& ](int64_t gi ,int64_t T )-> bool { 9425const auto tp = Clock ::now (); 9426if (!ple_next .get ()) {err = ple_next_err ;return false; } 9427// #1996: the pageable fallback (no RAM to pin) goes up through a pinned slot; the pinned buffers as before 9428if ((m .ple_pageable [ple_buf ].empty () 9429 ?cudaMemcpyAsync (m .ple_emb ,m .ple_emb_host [ple_buf ], (size_t )T * N * 4 ,cudaMemcpyHostToDevice ,cs ) 9430 :m .up_ring .h2d (m .ple_emb ,m .ple_emb_host [ple_buf ], (size_t )T * N * 4 ,cs ))!= cudaSuccess || 9431cudaEventRecord (m .ple_copied [ple_buf ],cs )!= cudaSuccess ) { 9432err = std::string ("prefill: the PLE rows' upload failed: " )+ cudaGetErrorString (cudaGetLastError ()); 9433return false; 9434 } 9435if (gi + 1 < (int64_t )flat .size ()) { 9436if (cudaEventSynchronize (m .ple_copied [ple_buf ^1 ])!= cudaSuccess ) { 9437err = std::string ("prefill: the PLE rows' upload failed: " )+ cudaGetErrorString (cudaGetLastError ()); 9438return false; 9439 } 9440ple_next = std::async (std::launch::async , [& ple_gather ,& ple_next_err ,c1 = gi + 1 ,b = ple_buf ^1 ] { 9441 strata::aux_cpus::pin_current_thread (); 9442return ple_gather (c1 ,b ,ple_next_err ); 9443 }); 9444 } 9445ple_buf ^=1 ; 9446stats_ .ms_ple += ms_since (tp ); 9447return true; 9448 }; 9449// the chunk buffers this path points into the super-chunk (restored on every return) 9450struct Restore { 9451Impl & m ; 9452float * R ,* mixed ,* inj ; 9453uint16_t * mixed_h ; 9454 ~Restore () {m .R = R ;m .mixed = mixed ;m .inj = inj ;m .mixed_h = mixed_h ; } 9455 }restore {m ,m .R ,m .mixed ,m .inj ,m .mixed_h }; 9456float * const R_chunk = m .R ; 9457const strata::kernels::cpu::ExpertLayout & lay = strata::kernels::cpu::expert_layout (); 9458double ms_attn = 0 ,ms_experts = 0 ,ms_host_tables = 0 ,ms_wait_a = 0 ,ms_wait_files = 0 ; 9459 std::vector < int > pf_job ((size_t )NE ,-1 );// the layer's prefetch: expert -> stager job (-1: not streamed) 9460// every streamed expert of layer l, in id order, to the stager - started with the layer's attention halves, so 9461// the NVMe / page-cache reads overlap them (at a super-chunk's size nearly every expert is routed) 9462static const bool pf_on = [] {const char * e = std::getenv ("STRATA_LM_PREFETCH" );return e == nullptr || e [0 ]!= '0' ; }(); 9463// STRATA_PREFILL_LM_NEXTFILES=<ring>: two stagers taking the layers in turn, so the next layer's file reads start 9464// as soon as this layer's walk has issued its own (never competing with them), into a ring that holds a layer 9465static const int64_t nextfiles = [] {const char * e = std::getenv ("STRATA_PREFILL_LM_NEXTFILES" );return e ? (int64_t ) std::atoll (e ) : (int64_t )0 ; }(); 9466const bool pf_two = m .latent && pf_on && nextfiles > 0 && m .src != nullptr && m .lm_stager [0 ]&& m .lm_stager [1 ]; 9467auto st_of = [& ](int64_t l )-> Stager * {return pf_two ?m .lm_stager [(l - LB )& 1 ].get () :m .stager .get (); }; 9468auto lm_prefetch = [& ](int64_t l )-> bool { 9469 std::fill (pf_job .begin (),pf_job .end (),-1 ); 9470if (m .src == nullptr || !pf_on )return true; 9471 std::vector < Stager ::Job > js ; 9472const bool pdirect = false;// (STRATA_PREFILL_DIRECT, #1670's other commit, is not ported) 9473for (int32_t e = 0 ;e < NE ;++ e ) { 9474if ((m .host_res && m .cache && m .host_res [(size_t )l * NE + e ] >=0 )|| m .src -> pinned (l ,e ))continue ; 9475pf_job [(size_t )e ]= (int )js .size (); 9476if (pdirect || m .src -> transient (l ,e )) { 9477js .push_back ({nullptr , (size_t )lay .blob_bytes (l ),m .src , (int32_t )l ,e }); 9478continue ; 9479 } 9480const uint8_t * b = m .src -> blob_stable (l ,e ); 9481if (!b ) {// #4695: no contiguous mapped blob (Windows, the mapping dropped for unbuffered reads): the source copies it itself 9482js .push_back ({nullptr , (size_t )lay .blob_bytes (l ),m .src , (int32_t )l ,e }); 9483continue ; 9484 } 9485js .push_back ({b , (size_t )lay .blob_bytes (l )}); 9486 } 9487st_of (l )-> start (std::move (js )); 9488return true; 9489 }; 9490struct StagerStop { 9491Stager * st [3 ]; 9492 ~StagerStop () {for (Stager * s :st )if (s )s -> finish (); }// an early return in a layer's attention halves 9493 }stager_stop {{m .stager .get (),m .lm_stager [0 ].get (),m .lm_stager [1 ].get ()}}; 9494int64_t lm_streamed = 0 ,lm_resident = 0 ,lm_groups = 0 ,lm_supers = 0 ,lm_groups_f16 = 0 ,lm_groups_fz = 0 ; 9495uint64_t lm_bytes = 0 ; 9496const int64_t G = m .T * K ;// the MoE buffers' rows (Xq, GU, H, Hq, Dm): a group's most 9497 9498// STRATA_PREFILL_LM_NEXT: the thread that enqueues the next layer's prefetch copies (see the latent walk) 9499 std::atomic < int64_t > pre_ready {-1 },pre_bytes {0 },pre_blobs {0 };// (outlive the worker below) 9500struct DmaWorker { 9501 std::thread t ; 9502 std::mutex mu ; 9503 std::condition_variable cv ; 9504 std::deque < std::function < void ()>> q ; 9505bool quit = false; 9506void start (int dev ) { 9507t = std::thread ([this ,dev ] { 9508cudaSetDevice (dev ); 9509for (;;) { 9510 std::function < void ()> f ; 9511 { 9512 std::unique_lock < std::mutex > lk (mu ); 9513cv .wait (lk , [& ] {return quit || !q .empty (); }); 9514if (q .empty ())return ; 9515f = std::move (q .front ()); 9516q .pop_front (); 9517 } 9518f (); 9519 } 9520 }); 9521 } 9522void push (std::function < void ()> f ) { 9523 { std::lock_guard < std::mutex > lk (mu );q .push_back (std::move (f )); } 9524cv .notify_one (); 9525 } 9526 ~DmaWorker () { 9527 { std::lock_guard < std::mutex > lk (mu );quit = true; } 9528cv .notify_one (); 9529if (t .joinable ())t .join (); 9530 } 9531 }dma ; 9532int64_t pre_pending = -1 ; 9533if (lb .pre_n > 0 ) { 9534int dev = 0 ; 9535cudaGetDevice (& dev ); 9536dma .start (dev ); 9537 } 9538const bool latent_du = m .latent && fused::latent_fused_available ()&& [] { 9539const char * v = std::getenv ("STRATA_LATENT_FUSED_DU" ); 9540return v == nullptr || v [0 ]!= '0' ; 9541 }(); 9542auto latent_dense_route = [& ](int64_t l ,int64_t token_base ,int64_t token_count )-> bool { 9543if ((l < m .lat_first_layer && !(short_w_ && l < short_end_ ))|| l < LB || l >=LE || token_base < 0 || 9544token_count <=0 || token_count > m .T || token_base + token_count > lb .S ) { 9545err = "prefill latent layer-major: D tile outside the stage or arena" ; 9546return false; 9547 } 9548pt .mark (kPfGather ,cs );// the timeline's "gather" is the latent D projection on this path 9549const int64_t ell = m .lat_ELL ,groups = m .lat_G ; 9550uint8_t * dst = lb .lat_xlq + (size_t )token_base * groups * (ell /32 * 36 ); 9551const uint8_t * d = short_w_ && l < short_end_ ?short_w_ -> d (l ) 9552 :m .lat_d_dev + (size_t ) (l - m .lat_first_layer )* m .lat_d .d_bytes (); 9553const float * inv = strata::kernels::lat_gu_colscale_dev ((int )l , (int )ell ); 9554 strata::kernels::quantize_q8_1_rows (m .mixed ,token_count , (int )N ,m .lat_xq ,cs ); 9555if (latent_du ) { 9556if (inv ) 9557 fused_q3k::latent_dense_d (d ,m .lat_xq ,token_count , (int )N , (int )groups , 9558ell ,dst ,cs ,m .lat_fmt ,inv ); 9559else 9560 fused::latent_dense_d (d ,m .lat_xq ,token_count , (int )N , (int )groups , 9561ell ,dst ,cs ,m .lat_fmt ); 9562 }else { 9563 strata::kernels::iq_mmvq (strata::kernels::lat_dense_fmt_to_type (m .lat_fmt ),d ,m .lat_xq , 9564m .xl , (int )N , (int ) (groups * ell ),token_count ,cs ); 9565if (inv ) strata::kernels::lat_colscale_rows (m .xl ,token_count * groups , (int )ell ,inv ,cs ); 9566 strata::kernels::quantize_q8_1_rows (m .xl ,token_count * groups , (int )ell ,dst ,cs ); 9567 } 9568return true; 9569 }; 9570auto latent_u_reduce = [& ](int64_t l ,int64_t token_base ,int64_t token_count )-> bool { 9571if ((l < m .lat_first_layer && !(short_w_ && l < short_end_ ))|| l < LB || l >=LE || token_base < 0 || 9572token_count <=0 || token_count > m .T || token_base + token_count > lb .S ) { 9573err = "prefill latent layer-major: U tile outside the stage or arena" ; 9574return false; 9575 } 9576pt .mark (kPfGemmD ,cs );// U, then the ordered combine below 9577const int64_t nent = token_count * K ,ell = m .lat_ELL ,groups = m .lat_G ; 9578const int32_t * ids = lb .ids + token_base * K ; 9579const int32_t * labels = m .lat_labels_dev + (size_t )l * m .lat_E ; 9580// This gather copies uint4s, not BF16 values: q8_1 blocks survive unchanged. 9581const int64_t row_bytes = ell /32 * 36 ; 9582gather_rows16 ((const uint16_t * )lb .lat_ylq ,lb .lat_slot + token_base * K , 9583 (uint16_t * )m .ylq ,nent ,row_bytes /2 ,cs ); 9584const uint8_t * u = short_w_ && l < short_end_ ?short_w_ -> u (l ) 9585 :m .lat_u_dev + (size_t ) (l - m .lat_first_layer )* m .lat_d .u_bytes (); 9586if (latent_du ) { 9587 fused::latent_dense_u_tables (ids ,labels ,nent , (int )groups , 9588 (int32_t * )m .lat_scratch , (int32_t * )m .lat_scratch + 12 , 9589 (int32_t * )m .lat_scratch + 32 ,cs ); 9590const int64_t work = ((nent + 63 ) /64 + groups )* (N >>8 ); 9591 fused::latent_dense_u (u ,m .ylq , (int32_t * )m .lat_scratch + 32 , 9592 (int32_t * )m .lat_scratch , (int )groups ,work ,nent , 9593 (int )ell , (int )N ,m .Dm ,cs ,m .lat_fmt ); 9594 }else { 9595 strata::kernels::latent_u_grouped (u ,m .ylq ,ids ,labels ,m .lat_E ,nent , 9596 (int )ell , (int )N ,m .Dm ,cs ,m .lat_fmt ); 9597 } 9598pt .mark (kPfCombine ,cs ); 9599// The reference starts its k-ordered FMA sum at zero, then adds shared. 9600moe_combine (m .Dm ,m .ids_identity ,lb .w + token_base * K ,lb .mixed + token_base * N , 9601lb .lat_sg + token_base ,lb .acc + token_base * N ,token_count ,cs ); 9602return true; 9603 }; 9604 9605// ---- one layer's experts over the super-chunk's Sn tokens 9606auto lm_experts = [& ](int64_t l ,int64_t Sn )-> bool { 9607Stager * const stg = st_of (l ); 9608const auto th0 = Clock ::now (); 9609const int64_t rows = Sn * K ; 9610pt .mark (kPfHostGroup ,cs );// the GPU idles from here while the host groups the routes 9611int32_t * idsw = lb .idsw_host ; 9612cudaMemcpyAsync (idsw ,lb .ids , (size_t )rows * 4 ,cudaMemcpyDeviceToHost ,cs ); 9613cudaMemcpyAsync (idsw + rows ,lb .w , (size_t )rows * 4 ,cudaMemcpyDeviceToHost ,cs ); 9614 core::progress_at ("reading the prompt (layer-major): waiting for the GPU (attention, router) at layer" ,l ,pos0 ); 9615if (cudaStreamSynchronize (cs )!= cudaSuccess ) { 9616err = std::string ("prefill (layer-major): " )+ cudaGetErrorString (cudaGetLastError ()); 9617return false; 9618 } 9619 core::progress_at ("reading the prompt (layer-major): the experts of layer" ,l ,pos0 ); 9620pt .fold (); 9621ms_wait_a += ms_since (th0 ); 9622const auto th1 = Clock ::now (); 9623const int32_t * ids_h = idsw ; 9624const float * w_h = (const float * ) (idsw + rows ); 9625 std::vector < int32_t > cnt ((size_t )NE ,0 ),off ((size_t )NE + 1 ,0 ); 9626for (int64_t i = 0 ;i < rows ;++ i ) { 9627const int32_t e = ids_h [(size_t )i ]; 9628if (e < 0 || e >=NE ) {err = "prefill (layer-major): routed id out of range" ;return false; } 9629++ cnt [(size_t )e ]; 9630 } 9631for (int32_t e = 0 ;e < NE ;++ e )off [(size_t )e + 1 ]= off [(size_t )e ]+ cnt [(size_t )e ]; 9632// ---- the routed experts in id order: resident ones from the cache, the others staged once (run_impl's walk) 9633// (started before the tables are built: the stager's threads read while the host builds them) 9634 std::vector < int32_t > uniq ; 9635for (int32_t e = 0 ;e < NE ;++ e ) 9636if (cnt [(size_t )e ]> 0 )uniq .push_back (e ); 9637auto resident = [& ](int32_t e ) {return m .host_res && m .cache && m .host_res [(size_t )l * NE + e ] >=0 ; }; 9638auto prefetched = [& ](int32_t e ) {return lb .pre_layer == l && lb .pre_of [(size_t )e ] >=0 ; }; 9639// the stager was started with every streamed expert of the layer when its attention halves began (the 9640// prefetch); an expert the routing skipped is never waited for (a later job's issue covers its buffer) 9641 std::vector < int > job_of (uniq .size (),-1 ),stage_of (uniq .size (),-1 ); 9642for (size_t u = 0 ;u < uniq .size ();++ u )job_of [u ]= pf_job [(size_t )uniq [u ]]; 9643for (int32_t e = 0 ;e < NE ;++ e )// prefetched but not routed: not read, if not started yet 9644if (cnt [(size_t )e ]== 0 && pf_job [(size_t )e ] >=0 )stg -> skip (pf_job [(size_t )e ]); 9645if (!pf_on && m .src != nullptr ) {// STRATA_LM_PREFETCH=0: the routed experts only, started now 9646 std::vector < Stager ::Job > js ; 9647const bool pdirect = false;// (STRATA_PREFILL_DIRECT, #1670's other commit, is not ported) 9648for (size_t u = 0 ;u < uniq .size ();++ u ) { 9649const int32_t e = uniq [u ]; 9650if (resident (e )|| m .src -> pinned (l ,e ))continue ; 9651job_of [u ]= (int )js .size (); 9652if (pdirect || m .src -> transient (l ,e )) { 9653js .push_back ({nullptr , (size_t )lay .blob_bytes (l ),m .src , (int32_t )l ,e }); 9654continue ; 9655 } 9656const uint8_t * b = m .src -> blob_stable (l ,e ); 9657if (!b ) {// #4695: as in lm_prefetch 9658js .push_back ({nullptr , (size_t )lay .blob_bytes (l ),m .src , (int32_t )l ,e }); 9659continue ; 9660 } 9661js .push_back ({b , (size_t )lay .blob_bytes (l )}); 9662 } 9663stg -> start (std::move (js )); 9664 } 9665struct StagerDone { 9666Stager * st ; 9667 ~StagerDone () {if (st )st -> finish (); } 9668 }stager_done {stg }; 9669// the tables: rows sorted by expert (token order within one), then per group its bounds and per-token CSR 9670int32_t * th = lb .tab_host ; 9671int32_t * row_tok = th ; 9672 std::vector < float > row_w ((size_t )rows ); 9673 { 9674 std::vector < int32_t > fill (off .begin (),off .end ()- 1 ); 9675for (int64_t i = 0 ;i < rows ;++ i ) { 9676const int32_t e = ids_h [(size_t )i ]; 9677const int32_t p = fill [(size_t )e ]++ ; 9678row_tok [p ]= (int32_t ) (i /K ); 9679row_w [(size_t )p ]= w_h [(size_t )i ]; 9680 } 9681 } 9682struct Entry {int32_t e ,r0 ,nr ; }; 9683 std::vector < Entry > ents ; 9684for (int32_t e = 0 ;e < NE ;++ e ) 9685for (int32_t r = off [(size_t )e ];r < off [(size_t )e + 1 ];r += (int32_t )G ) 9686ents .push_back ({e ,r , (int32_t ) std::min < int64_t > (G ,off [(size_t )e + 1 ]- r )}); 9687struct Grp {size_t j0 ,j1 ;int32_t r0 ,nr ,maxr ;int64_t b_at ,u_at ,uo_at ,nu ; }; 9688 std::vector < Grp > grps ; 9689for (size_t j = 0 ;j < ents .size ();) { 9690Grp gp {}; 9691gp .j0 = j ; 9692gp .r0 = ents [j ].r0 ; 9693int32_t nr = 0 ,maxr = 0 ; 9694while (j < ents .size ()&& j - gp .j0 < (size_t )MMQ_GROUP && nr + ents [j ].nr <=G ) { 9695nr += ents [j ].nr ; 9696maxr = std::max (maxr ,ents [j ].nr ); 9697++ j ; 9698 } 9699gp .j1 = j ; 9700gp .nr = nr ; 9701gp .maxr = maxr ; 9702grps .push_back (gp ); 9703 } 9704const int64_t E = (int64_t )ents .size (); 9705if (E > lm_entries_max (rows ,G )) {err = "prefill (layer-major): more expert entries than the tables hold" ;return false; } 9706int64_t at = rows ; 9707int32_t * bounds = th + at ; 9708int64_t b_used = 0 ; 9709at += 2 * lm_entries_max (rows ,G ); 9710int32_t * u_tok = th + at ; 9711at += rows ; 9712int32_t * u_off = th + at ; 9713at += rows + lm_entries_max (rows ,G ); 9714int32_t * u_rows = th + at ; 9715at += rows ; 9716float * u_w = (float * ) (th + at ); 9717at += rows ; 9718if (at > (int64_t )lb .tab_n || at > (int64_t )lb .tab_host_n ) {err = "prefill (layer-major): the tables overflow" ;return false; } 9719int64_t u_used = 0 ,uo_used = 0 ; 9720// per group, the tokens in order of first appearance and each token's rows in row order (counting, O(rows)); 9721// `slot` maps a token to its place in the group (-1: not in it), reset through the group's own token list 9722 std::vector < int32_t > slot ((size_t )Sn ,-1 ),fillp ; 9723for (Grp & gp :grps ) { 9724gp .b_at = b_used ; 9725for (size_t j = gp .j0 ;j < gp .j1 ;++ j )bounds [b_used ++ ]= ents [j ].r0 - gp .r0 ; 9726bounds [b_used ++ ]= gp .nr ; 9727gp .u_at = u_used ; 9728gp .uo_at = uo_used ; 9729int32_t * ut = u_tok + u_used ; 9730int32_t * uo = u_off + uo_used ; 9731int64_t nu = 0 ; 9732for (int32_t r = 0 ;r < gp .nr ;++ r ) { 9733const int32_t t = row_tok [gp .r0 + r ]; 9734if (slot [(size_t )t ]< 0 ) {slot [(size_t )t ]= (int32_t )nu ;ut [nu ]= t ;uo [nu ]= 0 ;++ nu ; } 9735++ uo [slot [(size_t )t ]]; 9736 } 9737fillp .assign ((size_t )nu ,0 ); 9738for (int64_t i = 0 ,acc_n = 0 ;i < nu ;++ i ) {const int32_t c = uo [i ];uo [i ]= (int32_t )acc_n ;fillp [(size_t )i ]= (int32_t )acc_n ;acc_n += c ; } 9739uo [nu ]= gp .nr ; 9740for (int32_t r = 0 ;r < gp .nr ;++ r ) { 9741const int32_t p = fillp [(size_t )slot [(size_t )row_tok [gp .r0 + r ]]]++ ; 9742u_rows [gp .r0 + p ]= r ; 9743u_w [gp .r0 + p ]= row_w [(size_t ) (gp .r0 + r )]; 9744 } 9745for (int64_t i = 0 ;i < nu ;++ i )slot [(size_t )ut [i ]]= -1 ; 9746gp .nu = nu ; 9747u_used += nu ; 9748uo_used += nu + 1 ; 9749 } 9750// (u_rows / u_w are indexed by the group's own row range [r0, r0 + nr) of the layer) 9751cudaMemcpyAsync (lb .tab ,th , (size_t )at * 4 ,cudaMemcpyHostToDevice ,cs ); 9752const int32_t * d_row_tok = lb .tab ; 9753const int32_t * d_bounds = lb .tab + rows ; 9754const int32_t * d_u_tok = lb .tab + rows + 2 * lm_entries_max (rows ,G ); 9755const int32_t * d_u_off = d_u_tok + rows ; 9756const int32_t * d_u_rows = d_u_off + rows + lm_entries_max (rows ,G ); 9757const float * d_u_w = (const float * ) (d_u_rows + rows ); 9758ms_host_tables += ms_since (th1 ); 9759// (the entries' last index per expert, for releasing a staged blob's ring slot) 9760 std::vector < size_t > last_ent ; 9761for (size_t j = 0 ;j < ents .size ();++ j ) { 9762if (j == 0 || ents [j - 1 ].e != ents [j ].e )last_ent .push_back (j ); 9763else last_ent .back ()= j ; 9764 } 9765// P4-SMALL: a fused layer's group reads its staged experts where they landed (no gather), so their slots stay held until the group's 9766// launch: STAGE_GRP slots, staged no further ahead than the open group allows (as the staged walk's resident groups, STAGE_GRP's note) 9767const bool fz_l = lb .xa != nullptr && lm_fused_layer (l ,m .group_cap > 0 ); 9768const int stage_n = fz_l ?STAGE_GRP :STAGE ; 9769const size_t ahead = fz_l ? (size_t ) (STAGE_GRP - MMQ_GROUP - 1 ) : (size_t )STAGE - 1 ; 9770int stage_next = 0 ; 9771// the latent walk keeps a batch's staged blobs until it launches, so it takes the layout's whole staging ring 9772const int lm_slots = m .latent ?stage_slots ((size_t )m .T ) :STAGE ; 9773auto stage_one = [& ](size_t u )-> bool { 9774const int32_t e = uniq [u ]; 9775if (resident (e )|| prefetched (e ))return true; 9776if (m .src == nullptr ) {err = "prefill (layer-major): an expert is neither resident nor in a source" ;return false; } 9777const int sl = stage_next ; 9778stage_next = (stage_next + 1 ) % (m .latent ?lm_slots :stage_n ); 9779const auto tq = Clock ::now (); 9780const bool pinned = m .src -> pinned (l ,e ); 9781const uint8_t * b = pinned ?m .src -> blob_stable (l ,e ) :nullptr ; 9782if (pinned && !b ) {err = "prefill (layer-major): expert source has no blob" ;return false; } 9783if (m .stage_live [sl ])cudaStreamWaitEvent (m .copy ,m .used [m .used_of [sl ]],0 ); 9784if (pinned ) { 9785cudaMemcpyAsync (m .stage_dev [sl ],b , (size_t )lay .blob_bytes (l ),cudaMemcpyHostToDevice ,m .copy ); 9786++ stats_ .experts_dma ; 9787 }else { 9788stg -> pass (job_of [u ]);// the prefetched jobs below it the routing skipped get no DMA 9789const auto tw = Clock ::now (); 9790const uint8_t * hb = stg -> wait (job_of [u ]); 9791ms_wait_files += ms_since (tw ); 9792cudaMemcpyAsync (m .stage_dev [sl ],hb , (size_t )lay .blob_bytes (l ),cudaMemcpyHostToDevice ,m .copy ); 9793stg -> issued_one (job_of [u ],m .copy ); 9794 } 9795cudaEventRecord (m .copied [sl ],m .copy ); 9796m .stage_live [sl ]= true; 9797stage_of [u ]= sl ; 9798stats_ .ms_experts_host += ms_since (tq ); 9799++ stats_ .experts_streamed ; 9800++ lm_streamed ; 9801lm_bytes += (uint64_t )lay .blob_bytes (l ); 9802return true; 9803 }; 9804if (m .latent ) { 9805const auto & f = lay .fmt [(size_t )l ]; 9806const int64_t ell = m .lat_ELL ; 9807const size_t row_bytes = (size_t ) (ell /32 * 36 ); 9808 std::vector < int32_t > xl_rows ((size_t )rows ),slots ((size_t )rows ,-1 ); 9809 std::vector < int32_t > fill (off .begin (),off .end ()- 1 ); 9810for (int64_t i = 0 ;i < rows ;++ i ) { 9811const int32_t e = ids_h [i ],p = fill [(size_t )e ]++ ; 9812const int32_t label = m .lat_labels [(size_t )l * m .lat_E + e ]; 9813if (label < 0 || label >=m .lat_G || p < 0 || p >=rows ) { 9814err = "prefill latent layer-major: invalid route mapping" ; 9815return false; 9816 } 9817xl_rows [(size_t )p ]= (int32_t ) (i /K * m .lat_G + label ); 9818slots [(size_t )i ]= p ; 9819 } 9820if (m .up_ring .h2d (lb .lat_tok ,xl_rows .data (), (size_t )rows * 4 ,cs )!= cudaSuccess || 9821m .up_ring .h2d (lb .lat_slot ,slots .data (), (size_t )rows * 4 ,cs )!= cudaSuccess ) { 9822err = "prefill latent layer-major: route upload failed" ; 9823return false; 9824 } 9825const auto layout = strata::kernels::native_expert_layout (f .gu_type ,f .d_type , 9826 (int )ell , (int )m .lat_I ); 9827const bool use_fused = fused::latent_fused_available ()&& [] { 9828const char * v = std::getenv ("STRATA_LATENT_FUSED" ); 9829return v == nullptr || v [0 ]!= '0' ; 9830 }()&& ((f .gu_type == 40 && f .d_type == 40 )|| 9831 (lat_fused_q3k_on ()&& f .gu_type == 11 && f .d_type == 20 && m .lat_I == 640 )); 9832 fused::LatentGeom geom {}; 9833geom .ell = ell ;geom .iff = m .lat_I ; 9834geom .gu_row = layout .gu_row ;geom .d_row = layout .d_row ; 9835geom .up_off = layout .up_off ;geom .down_off = layout .down_off ;geom .tail_off = layout .tail_off ; 9836// the layer's A batches, cut before the walk so all their tables go up in one copy: a small upload per 9837// batch waits behind the staging copies on the copy engine, and the kernel behind it 9838struct Cut {int32_t e0 ,e1 ;int64_t base ,count ; }; 9839 std::vector < Cut > cuts ; 9840size_t next_cut = 0 ; 9841const size_t tab_stride = fused::latent_group_bytes (G , (int )NE ); 9842// A over the entries [row_base, row_base + entry_count) of experts [e0, e1): the rows of an expert 9843// keep their 64-row tiles from the expert's first row, and every FP32 output and scratch row is 9844// relative to row_base, so a batch writes the same bytes per entry as one launch per expert. 9845auto latent_a_tile = [& ](int32_t e0 ,int32_t e1 ,int64_t row_base ,int64_t entry_count , 9846const fused::WideBatch & blobs )-> bool { 9847if (entry_count <=0 || entry_count > G || row_base < 0 || row_base + entry_count > rows || 9848e0 < 0 || e1 > NE || e1 <=e0 || e1 - e0 > fused::kBatchRoom ) { 9849err = "prefill latent layer-major: A tile outside the arena" ; 9850return false; 9851 } 9852pt .mark (kPfGemmGU ,cs );// A: gate/up, SwiGLU and down in one launch pair 9853if (use_fused ) { 9854if (fused::latent_scratch_bytes (entry_count , (int )NE ,m .lat_I )> 9855 strata::kernels::native_expert_scratch_bytes (G ,m .lat_I )) { 9856err = "prefill latent layer-major: fused A scratch does not fit" ; 9857return false; 9858 } 9859// this batch's tables, uploaded with the layer's others (latent_a_superchunk) 9860if (next_cut >=cuts .size ()|| cuts [next_cut ].e0 != e0 || cuts [next_cut ].e1 != e1 || 9861cuts [next_cut ].base != row_base || cuts [next_cut ].count != entry_count ) { 9862err = "prefill latent layer-major: the A walk left its planned batches" ; 9863return false; 9864 } 9865const uint8_t * tables = lb .lat_tabs + next_cut ++ * tab_stride ; 9866 fused::WideBatch batch = blobs ; 9867batch .e0 = e0 ;batch .e1 = e1 ; 9868void * h = m .lat_scratch ;// H rows; the tables live in lat_tabs 9869if (f .gu_type == 11 && f .d_type == 20 && m .lat_I == 640 ) 9870 fused_q3k::experts_latent_q3k (batch ,geom , (int )NE ,entry_count ,tables , 9871lb .lat_xlq ,lb .lat_tok + row_base ,h ,m .yl ,cs ); 9872else 9873 fused::experts_latent (batch ,geom , (int )NE ,entry_count ,tables , 9874lb .lat_xlq ,lb .lat_tok + row_base ,h ,m .yl ,cs ); 9875 }else { 9876if (e1 != e0 + 1 ) { 9877err = "prefill latent layer-major: the native A stage takes one expert a launch" ; 9878return false; 9879 } 9880const unsigned long long blob = (unsigned long long )blobs .blob [0 ]; 9881const int32_t starts [2 ]= {0 , (int32_t )entry_count },one = 1 ; 9882if (m .up_ring .h2d (m .lat_gp ,& blob ,sizeof blob ,cs )!= cudaSuccess || 9883m .up_ring .h2d (m .lat_gs ,starts ,sizeof starts ,cs )!= cudaSuccess || 9884m .up_ring .h2d (m .lat_n ,& one ,sizeof one ,cs )!= cudaSuccess ) { 9885err = "prefill latent layer-major: native A tables upload failed" ; 9886return false; 9887 } 9888 strata::kernels::native_expert_grouped (layout ,m .lat_gp ,m .lat_gs ,m .lat_n , 9889m .ids_identity ,lb .lat_tok + row_base ,1 ,entry_count ,lb .lat_xlq ,m .lat_scratch ,m .yl ,cs ,0 ); 9890 } 9891 strata::kernels::quantize_q8_1_rows (m .yl ,entry_count , (int )ell , 9892lb .lat_ylq + (size_t )row_base * row_bytes ,cs ); 9893pt .mark (kPfHostGroup ,cs );// the GPU idles from here until the host issues the next batch 9894++ lm_groups ; 9895return true; 9896 }; 9897// the routed experts in id order, consecutive ones batched while their rows fit the tile buffers; a 9898// batch's staged slots are released only after its launch (staged_batch.hpp sizes batch and lookahead) 9899auto latent_a_superchunk = [& ]()-> bool { 9900const StagedBatchPlan plan = staged_batch_plan (lm_slots ,LAT_GROUP ); 9901 {// the walk below flushes on exactly these conditions 9902size_t pn = 0 ; 9903for (size_t u = 0 ;u < uniq .size ();++ u ) { 9904const int32_t e = uniq [u ]; 9905const int64_t c = off [(size_t )e + 1 ]- off [(size_t )e ]; 9906if (pn > 0 && (!use_fused || cuts .back ().count + c > G || c > G || pn == plan .group_limit || 9907e + 1 - cuts .back ().e0 > fused::kBatchRoom )) 9908pn = 0 ; 9909if (c > G ) { 9910for (int64_t p = off [(size_t )e ];p < off [(size_t )e + 1 ];p += G ) 9911cuts .push_back ({e ,e + 1 ,p , std::min < int64_t > (G ,off [(size_t )e + 1 ]- p )}); 9912continue ; 9913 } 9914if (pn == 0 )cuts .push_back ({e ,e + 1 ,off [(size_t )e ],0 }); 9915cuts .back ().e1 = e + 1 ; 9916cuts .back ().count += c ; 9917++ pn ; 9918 } 9919if (use_fused ) { 9920if (cuts .size ()* tab_stride > lb .lat_tabs_n ) { 9921err = "prefill latent layer-major: more A batches than the table buffer holds" ; 9922return false; 9923 } 9924 std::vector < char > tabs (cuts .size ()* tab_stride ,0 ); 9925 std::vector < int32_t > tile_cnt ((size_t )NE ),tile_off ((size_t )NE + 1 ); 9926for (size_t k = 0 ;k < cuts .size ();++ k ) { 9927const Cut & ct = cuts [k ]; 9928auto rel = [& ](int64_t r ) { 9929return (int32_t ) (std::clamp (r ,ct .base ,ct .base + ct .count )- ct .base ); 9930 }; 9931 std::fill (tile_cnt .begin (),tile_cnt .end (),0 ); 9932for (int32_t e = 0 ;e <=NE ;++ e ) { 9933tile_off [(size_t )e ]= e < ct .e0 ?0 :e > ct .e1 ? (int32_t )ct .count :rel (off [(size_t )e ]); 9934if (e >=ct .e0 && e < ct .e1 ) 9935tile_cnt [(size_t )e ]= rel (off [(size_t )e + 1 ])- rel (off [(size_t )e ]); 9936 } 9937 fused::group_latent (tile_cnt .data (),tile_off .data (), (int )NE ,tabs .data ()+ k * tab_stride , 9938 fused::latent_group_bytes (ct .count , (int )NE )); 9939 } 9940if (m .up_ring .h2d (lb .lat_tabs ,tabs .data (),tabs .size (),cs )!= cudaSuccess ) { 9941err = "prefill latent layer-major: the A tables' upload failed" ; 9942return false; 9943 } 9944 } 9945 } 9946size_t staged = 0 ,nb = 0 ; 9947int32_t e0 = 0 ,e_last = 0 ; 9948int64_t base = 0 ,count = 0 ; 9949 fused::WideBatch blobs ; 9950 std::vector < int > open_slots ; 9951auto flush = [& ]()-> bool { 9952if (nb == 0 )return true; 9953if (!open_slots .empty ()) {// one copy stream, in order: the last copy covers the others 9954pt .mark (kPfWaitCopy ,cs ); 9955cudaStreamWaitEvent (cs ,m .copied [open_slots .back ()],0 ); 9956 } 9957if (!latent_a_tile (e0 ,e_last + 1 ,base ,count ,blobs ))return false; 9958for (int sl :open_slots ) { 9959cudaEventRecord (m .used [sl ],cs ); 9960m .used_of [sl ]= sl ; 9961 } 9962open_slots .clear (); 9963blobs = fused::WideBatch {}; 9964nb = 0 ; 9965return true; 9966 }; 9967for (size_t u = 0 ;u < uniq .size ();++ u ) { 9968const int32_t e = uniq [u ]; 9969const int64_t c = off [(size_t )e + 1 ]- off [(size_t )e ]; 9970// a full batch launches before more is staged: its slots plus the lookahead fill the ring 9971if (nb > 0 && (!use_fused || count + c > G || c > G || nb == plan .group_limit || 9972e + 1 - e0 > fused::kBatchRoom )) { 9973if (!flush ())return false; 9974 } 9975while (staged < uniq .size ()&& staged <=u + plan .ahead ) { 9976if (!stage_one (staged ++ ))return false; 9977 } 9978const uint8_t * blob = nullptr ; 9979if (stage_of [u ]< 0 && prefetched (e )) { 9980blob = lb .pre + (size_t )lb .pre_of [(size_t )e ]* (size_t )MAXBLOB (); 9981 }else if (stage_of [u ]< 0 ) { 9982blob = m .cache -> device_slot (m .host_res [(size_t )l * NE + e ]); 9983++ stats_ .experts_resident ; 9984++ lm_resident ; 9985 }else { 9986blob = m .stage_dev [stage_of [u ]]; 9987 } 9988if (c > G ) {// more rows than the tile buffers: this expert alone, in pieces 9989 fused::WideBatch one ; 9990one .blob [0 ]= blob ; 9991if (stage_of [u ] >=0 )cudaStreamWaitEvent (cs ,m .copied [stage_of [u ]],0 ); 9992for (int64_t p = off [(size_t )e ];p < off [(size_t )e + 1 ];p += G ) 9993if (!latent_a_tile (e ,e + 1 ,p , std::min < int64_t > (G ,off [(size_t )e + 1 ]- p ),one )) 9994return false; 9995if (stage_of [u ] >=0 ) { 9996cudaEventRecord (m .used [stage_of [u ]],cs ); 9997m .used_of [stage_of [u ]]= stage_of [u ]; 9998 } 9999continue ; 10000 } 10001if (nb == 0 ) {e0 = e ;base = off [(size_t )e ];count = 0 ; } 10002blobs .blob [e - e0 ]= blob ; 10003if (stage_of [u ] >=0 )open_slots .push_back (stage_of [u ]); 10004e_last = e ; 10005count += c ; 10006++ nb ; 10007 core::progress_beat (); 10008 } 10009return flush (); 10010 }; 10011if (lb .pre_n > 0 && pre_pending == l ) {// this layer's prefetched experts: enqueued, then waited on 10012while (pre_ready .load (std::memory_order_acquire )!= l ) std::this_thread::yield (); 10013lb .pre_layer = l ; 10014cudaStreamWaitEvent (cs ,lb .pre_done ,0 ); 10015 } 10016if (!latent_a_superchunk ())return false; 10017// the next layer's RAM-tier experts, routed or not (nearly all are at this length), copied while this 10018// layer's U and the next layer's attention run. a DMA thread enqueues them: a cudaMemcpyAsync blocks while 10019// the copy engine's queue is full, which held back the next launches on this thread. they wait for this 10020// layer's A to be launched, which may still read the same slots. 10021lb .pre_layer = -1 ; 10022if (lb .pre_n > 0 && l + 1 < LE && m .src != nullptr ) { 10023cudaEventRecord (lb .pre_free ,cs ); 10024pre_pending = l + 1 ; 10025const int64_t l1 = l + 1 ; 10026dma .push ([& ,l1 ] { 10027cudaStreamWaitEvent (m .copy ,lb .pre_free ,0 ); 10028 std::fill (lb .pre_of .begin (),lb .pre_of .end (),-1 ); 10029int64_t k = 0 ; 10030for (int32_t e = 0 ;e < NE && k < lb .pre_n ;++ e ) { 10031if ((m .host_res && m .cache && m .host_res [(size_t )l1 * NE + e ] >=0 )|| !m .src -> pinned (l1 ,e )) 10032continue ; 10033const uint8_t * b = m .src -> blob_stable (l1 ,e ); 10034if (b == nullptr )continue ; 10035cudaMemcpyAsync (lb .pre + (size_t )k * (size_t )MAXBLOB (),b , (size_t )lay .blob_bytes (l1 ), 10036cudaMemcpyHostToDevice ,m .copy ); 10037lb .pre_of [(size_t )e ]= (int32_t )k ++ ; 10038pre_bytes .fetch_add ((int64_t )lay .blob_bytes (l1 ), std::memory_order_relaxed ); 10039pre_blobs .fetch_add (1 , std::memory_order_relaxed ); 10040 } 10041cudaEventRecord (lb .pre_done ,m .copy ); 10042pre_ready .store (l1 , std::memory_order_release ); 10043 }); 10044 } 10045for (int64_t t = 0 ;t < Sn ;t += m .T ) 10046if (!latent_u_reduce (l ,t , std::min (m .T ,Sn - t )))return false; 10047// this layer's reads are all issued: the next layer's start now, while U and its attention run 10048if (pf_two && l + 1 < LE && !lm_prefetch (l + 1 ))return false; 10049ms_experts += ms_since (th0 ); 10050return true; 10051 } 10052const int mmq_gt = lay .native ?lay .fmt [(size_t )l ].gu_type :42 ; 10053const int mmq_dt = lay .native ?lay .fmt [(size_t )l ].d_type :42 ; 10054// a layer MMQ does not take runs run_impl's FP16 path (port, 2026-10-24): each expert dequantized to FP16 once 10055// per super-chunk, then per entry its rows' FP16 inputs (lb.mixed_h, the bits run_impl's gather reads) through 10056// two FP16 GEMMs into the group's Dm rows; the group's rows are added per token as on the MMQ path 10057const bool fp16_l = !mmq_plan ().layer [(size_t )l ]&& !fz_l ;// (fz_l without an MMQ layer: a build without MMQ, a layer of the plan's `fo` set) 10058const size_t mmq_gub = fp16_l ?0 : mmq::matrix_bytes (mmq_gt ,kFF2 ,N ),mmq_db = fp16_l ?0 : mmq::matrix_bytes (mmq_dt ,N ,kFF ); 10059size_t staged = 0 ,u = 0 ; 10060const uint8_t * blob_dev = nullptr ; 10061size_t gi = 0 ; 10062int dq = -1 ;// FP16 path: the dequant slot of the current expert 10063// fused: the open group's expert pointers and the staged slots its launch gives back; the super-chunk's rows to int8 once per layer 10064const uint8_t * fz_blob [MMQ_GROUP ]= {}; 10065int fz_rel [MMQ_GROUP ]= {}; 10066int fz_nrel = 0 ; 10067 fused::NativeGeom fz_geom {}; 10068if (fz_l ) { 10069const auto & f = lay .fmt [(size_t )l ]; 10070fz_geom = fused::NativeGeom {f .gu_type ,f .d_type ,f .gu_row ,f .d_row ,f .up_off ,f .down_off }; 10071 fused::quantize_act_native (lb .mixed ,Sn ,N ,lb .xa ,cs ); 10072 } 10073for (size_t j = 0 ;j < ents .size ();++ j ) { 10074const int32_t e = ents [j ].e ; 10075if (j == 0 || ents [j - 1 ].e != e ) {// the next expert: staged ahead, waited for, its blob located 10076if (j > 0 )++ u ; 10077while (staged < uniq .size ()&& staged <=u + ahead ) { 10078if (!stage_one (staged ))return false; 10079++ staged ; 10080 } 10081if (stage_of [u ]< 0 ) { 10082blob_dev = m .cache -> device_slot (m .host_res [(size_t )l * NE + e ]); 10083++ stats_ .experts_resident ; 10084++ lm_resident ; 10085 }else { 10086pt .mark (kPfWaitCopy ,cs ); 10087cudaStreamWaitEvent (cs ,m .copied [stage_of [u ]],0 ); 10088blob_dev = m .stage_dev [stage_of [u ]]; 10089 } 10090 } 10091const Grp & gp = grps [gi ]; 10092const size_t q = j - gp .j0 ; 10093pt .mark (kPfDequant ,cs ); 10094if (fp16_l ) { 10095if (j == 0 || ents [j - 1 ].e != e ) {// the expert's FP16 matrices, once (run_impl's dequant) 10096dq = (dq + 1 ) %DQ ; 10097if (lay .native ) { 10098const auto & f = lay .fmt [(size_t )l ]; 10099 strata::kernels::iq_dequant_gu_f16 (f .gu_type ,blob_dev ,blob_dev + f .up_off ,f .n_ff ,f .n_embd , 10100m .dq_gu [dq ],cs ,nullptr ); 10101 strata::kernels::iq_dequant_f16 (f .d_type ,blob_dev + f .down_off ,f .n_embd * f .n_ff ,m .dq_d [dq ],cs , 10102nullptr ); 10103 }else { 10104blob_dequant_f16 (blob_dev ,m .dq_gu [dq ],m .dq_d [dq ],cs ); 10105 } 10106if (stage_of [u ] >=0 ) {// the blob is read by the dequant: its ring slot is free 10107cudaEventRecord (m .used [stage_of [u ]],cs ); 10108m .used_of [stage_of [u ]]= stage_of [u ]; 10109 } 10110 } 10111// this entry's rows (group-relative offset o): FP16 inputs, gate/up, SwiGLU, down 10112const int64_t o = ents [j ].r0 - gp .r0 ,nr = ents [j ].nr ; 10113gather_rows16 (lb .mixed_h ,d_row_tok + ents [j ].r0 ,m .Xs + o * N ,nr ,N ,cs ); 10114pt .mark (kPfGemmGU ,cs ); 10115m .gemm .f16 (m .Xs + o * N ,m .dq_gu [dq ],m .GU + o * kFF2 ,nr ,kFF2 ,N ); 10116swiglu_interleaved (m .GU + o * kFF2 ,m .Hh + o * kFF ,nr ,cs ); 10117pt .mark (kPfGemmD ,cs ); 10118m .gemm .f16 (m .Hh + o * kFF ,m .dq_d [dq ],m .Dm + o * N ,nr ,N ,kFF ); 10119if (j + 1 < gp .j1 )continue ; 10120pt .mark (kPfCombine ,cs ); 10121moe_scatter_add (m .Dm ,d_u_tok + gp .u_at ,d_u_off + gp .uo_at ,d_u_rows + gp .r0 , 10122d_u_w + gp .r0 ,gp .nu ,lb .acc ,cs ); 10123++ lm_groups ; 10124++ lm_groups_f16 ; 10125++ gi ; 10126 core::progress_beat (); 10127continue ; 10128 } 10129if (fz_l ) {// P4-SMALL: the group's experts where they are; its two products and SwiGLU in one launch pair at its last entry 10130fz_blob [q ]= blob_dev ; 10131if (j == last_ent [u ]&& stage_of [u ] >=0 )fz_rel [fz_nrel ++ ]= stage_of [u ]; 10132if (j + 1 < gp .j1 )continue ; 10133const int ngx = (int ) (gp .j1 - gp .j0 ); 10134pt .mark (kPfGemmGU ,cs ); 10135 fused::group_bounds (d_bounds + gp .b_at ,ngx ,m .GU ,cs ); 10136 fused::Batch fb ; 10137fb .e0 = 0 ; 10138fb .e1 = ngx ; 10139for (int i = 0 ;i < ngx ;++ i )fb .blob [i ]= fz_blob [i ]; 10140 fused::want_dm_f16 (false); 10141 fused::experts_native (fb ,fz_geom ,ngx ,gp .nr ,m .GU ,lb .xa ,d_row_tok + gp .r0 ,m .H ,m .Dm ,cs ); 10142for (int i = 0 ;i < fz_nrel ;++ i ) {// the group's staged blobs are read: their slots are free 10143cudaEventRecord (m .used [fz_rel [i ]],cs ); 10144m .used_of [fz_rel [i ]]= fz_rel [i ]; 10145 } 10146fz_nrel = 0 ; 10147pt .mark (kPfCombine ,cs ); 10148moe_scatter_add (m .Dm ,d_u_tok + gp .u_at ,d_u_off + gp .uo_at ,d_u_rows + gp .r0 ,d_u_w + gp .r0 ,gp .nu ,lb .acc ,cs ); 10149++ lm_groups ; 10150++ lm_groups_fz ; 10151++ gi ; 10152 core::progress_beat (); 10153continue ; 10154 } 10155if (lay .native ) { 10156const auto & f = lay .fmt [(size_t )l ]; 10157 mmq::gather_native (blob_dev ,blob_dev + f .up_off ,mmq_gub /2 ,blob_dev + f .down_off ,mmq_db , 10158m .grp_gu + q * mmq_gub ,m .grp_d + q * mmq_db ,cs ); 10159 }else { 10160 mmq::gather_strata_q2 (blob_dev ,m .grp_gu + q * mmq_gub ,m .grp_d + q * mmq_db ,cs ); 10161 } 10162if (j == last_ent [u ]&& stage_of [u ] >=0 ) {// the blob is read: its ring slot is free 10163cudaEventRecord (m .used [stage_of [u ]],cs ); 10164m .used_of [stage_of [u ]]= stage_of [u ]; 10165 } 10166if (j + 1 < gp .j1 )continue ; 10167// ---- the group's products over all of its rows of the super-chunk, then the rows added per token 10168const int ngx = (int ) (gp .j1 - gp .j0 ); 10169pt .mark (kPfGemmGU ,cs ); 10170cudaMemsetAsync (m .grp_gu + (size_t )ngx * mmq_gub ,0 ,MMQ_TAIL ,cs ); 10171cudaMemsetAsync (m .grp_d + (size_t )ngx * mmq_db ,0 ,MMQ_TAIL ,cs ); 10172 mmq::quantize (lb .mixed ,d_row_tok + gp .r0 ,m .Xq ,mmq_gt ,N ,N ,gp .nr ,cs ); 10173 mmq::Product gu ; 10174gu .w = m .grp_gu ;gu .type = mmq_gt ;gu .w_rows = kFF2 ;gu .w_cols = N ;gu .expert_bytes = mmq_gub ; 10175gu .n = ngx ;gu .xq = m .Xq ;gu .bounds = d_bounds + gp .b_at ;gu .ids = m .ids_identity ; 10176gu .total_rows = gp .nr ;gu .max_rows = gp .maxr ;gu .dst = m .GU ;gu .ld_dst = kFF2 ; 10177m .mmq_ctx -> run (gu ,cs ); 10178 mmq::swiglu (m .GU ,m .H ,gp .nr ,kFF , !lay .native ,cs ); 10179pt .mark (kPfGemmD ,cs ); 10180 mmq::quantize (m .H ,nullptr ,m .Hq ,mmq_dt ,kFF ,kFF ,gp .nr ,cs ); 10181 mmq::Product dn ; 10182dn .w = m .grp_d ;dn .type = mmq_dt ;dn .w_rows = N ;dn .w_cols = kFF ;dn .expert_bytes = mmq_db ; 10183dn .n = ngx ;dn .xq = m .Hq ;dn .bounds = d_bounds + gp .b_at ;dn .ids = m .ids_identity ; 10184dn .total_rows = gp .nr ;dn .max_rows = gp .maxr ;dn .dst = m .Dm ;dn .ld_dst = N ; 10185m .mmq_ctx -> run (dn ,cs ); 10186pt .mark (kPfCombine ,cs ); 10187moe_scatter_add (m .Dm ,d_u_tok + gp .u_at ,d_u_off + gp .uo_at ,d_u_rows + gp .r0 , 10188d_u_w + gp .r0 ,gp .nu ,lb .acc ,cs ); 10189++ lm_groups ; 10190++ gi ; 10191 core::progress_beat (); 10192 } 10193ms_experts += ms_since (th0 ); 10194return true; 10195 }; 10196 10197#if defined(STRATA_HAVE_DFLASH2 ) 10198// DFlash2 prompt taps (DF-08): one prompt, one stage (lm_prepare declined the rest). A layer's completed output is the rows after the 10199// hyper-connection write of its FFN half, which this walk does when the NEXT layer starts (or in the final pass for the last one); 10200// each sub-chunk's tapped rows (positions >= tap_first_) go to their place in the staging, and the super-chunk's rows are handed to 10201// on_taps, in position order, once all its layers are done 10202 std::vector < int > tap_slot ; 10203const bool tap_on = !tap_layers_ .empty ()&& on_taps && segs .size ()== 1 && LB == 0 && LE == L && tap_cap_ > 0 ; 10204if (tap_on ) { 10205if (tap_dev_ == nullptr && 10206cudaMalloc ((void ** )& tap_dev_ , (size_t )tap_cap_ * tap_layers_ .size ()* (size_t )g .n_embd * 4 )!= cudaSuccess ) { 10207 (void )cudaGetLastError (); 10208tap_dev_ = nullptr ; 10209err = "prefill: the DFlash2 tap staging does not fit in VRAM" ; 10210return false; 10211 } 10212tap_slot .assign ((size_t )g .n_layers ,-1 ); 10213for (size_t i = 0 ;i < tap_layers_ .size ();++ i )tap_slot [(size_t )tap_layers_ [i ]]= (int )i ; 10214 }else if (!tap_layers_ .empty ()) { 10215err = "prefill (layer-major): the DFlash2 taps are not supported for this read" ; 10216return false; 10217 } 10218#endif 10219for (size_t sci = 0 ;sci < supers .size ();++ sci ) { 10220const std::vector < LmSub >& subs = supers [sci ]; 10221int64_t Sn = 0 ; 10222for (const LmSub & sb :subs )Sn = std::max (Sn ,sb .t0 + sb .T ); 10223#if defined(STRATA_HAVE_DFLASH2 ) 10224// the super-chunk's tapped rows: those at positions >= tap_first_ (the super-chunk's row r is position segs[0].pos0 + subs[0].c0 + r) 10225const int64_t super_pos = segs [0 ].pos0 + subs [0 ].c0 ; 10226const int64_t tap_s0 = tap_on ? std::min < int64_t > (Sn , std::max < int64_t > (0 ,tap_first_ - super_pos )) :Sn ;// first tapped row 10227const int64_t tap_super_rows = Sn - tap_s0 ; 10228if (tap_on && tap_super_rows > tap_cap_ ) {err = "prefill: the DFlash2 tap staging is smaller than the super-chunk's tapped rows" ;return false; } 10229#endif 10230const int64_t nc = (int64_t )subs .size (); 10231int64_t last_seg0 = -1 ; 10232for (int64_t c = 0 ;c < nc ;++ c )if (subs [(size_t )c ].seg == 0 )last_seg0 = c ; 10233++ lm_supers ; 10234lm_mid_ = true; 10235if (stage_lb_ > 0 && lb .r_dev && 10236cudaMemcpyAsync (lb .R ,lb .R_host , (size_t )Sn * D * 4 ,cudaMemcpyHostToDevice ,cs )!= cudaSuccess ) { 10237err = "prefill (layer-major): the super-chunk's rows did not go up" ; 10238return false; 10239 } 10240for (int64_t l = LB ;l <=LE ;++ l ) { 10241const auto ta = Clock ::now (); 10242if (short_w_ != nullptr ) {// read_short: the first stage's layers come through two weight slots 10243if (l > 0 && l - 1 < short_end_ && !short_w_ -> end (l - 1 ,short_end_ ,cs )) {err = "prefill: the streamed weights" ;return false; } 10244if (l == 0 && (!short_w_ -> issue (0 )|| (short_end_ > 1 && !short_w_ -> issue (1 )))) {err = "prefill: the streamed weights" ;return false; } 10245if (l < short_end_ && !short_w_ -> begin (l ,cs )) {err = "prefill: the streamed weights" ;return false; } 10246 } 10247if (l < LE && (!pf_two || l == LB )&& !lm_prefetch (l ))return false;// (two: started by l - 1's walk) 10248// host mode: sub-chunk c's rows go up on the copy stream into buffer c % 2 (issued one sub-chunk ahead) 10249auto r_buf = [& ](int64_t c ) {return (c & 1 ) ?lb .R2 :R_chunk ; }; 10250auto issue_up = [& ](int64_t c ) { 10251const int64_t TT = subs [(size_t )c ].T ; 10252cudaMemcpyAsync (r_buf (c ),lb .R_host + (size_t )subs [(size_t )c ].t0 * D , (size_t )TT * D * 4 ,cudaMemcpyHostToDevice , 10253m .copy ); 10254cudaEventRecord (lb .ev_in [c & 1 ],m .copy ); 10255 }; 10256if (!lb .r_dev && l > 0 )issue_up (0 ); 10257int64_t qsa_index = 0 ,gdn_index = 0 ; 10258for (int64_t i = 0 ;i < std::min (l ,L );++ i ) (core::is_qsa_layer (g ,i ) ?qsa_index :gdn_index )+= 1 ; 10259const int64_t qsa_index0 = qsa_index ,gdn_index0 = gdn_index ; 10260for (int64_t c = 0 ;c < nc ;++ c ) { 10261if (should_stop && should_stop ()) {err = "cancelled" ;return false; } 10262 core::progress_beat (); 10263const LmSub & sub = subs [(size_t )c ]; 10264const Seg & sgm = segs [(size_t )sub .seg ]; 10265const int64_t * const tokens = sgm .tokens ; 10266ssp = ss_of ((size_t )sub .seg ); 10267if (short_lo_ != nullptr && l < short_end_ )ssp = short_lo_ ; 10268 core::progress_at ("reading the prompt (layer-major): layer" ,l ,sgm .pos0 + sub .c0 ); 10269qsa_index = qsa_index0 ; 10270gdn_index = gdn_index0 ; 10271const int64_t c0 = sub .c0 ;// in this prompt's tokens 10272const int64_t T = sub .T ,p0 = sgm .pos0 + c0 ; 10273const int64_t t0 = sub .t0 ;// in the super-chunk 10274const int64_t gi = flat_base [sci ]+ c ;// in the whole run 10275m .R = lb .r_dev ?lb .R + t0 * D :r_buf (c ); 10276if (!lb .r_dev ) { 10277if (l > 0 ) { 10278if (c + 1 < nc )issue_up (c + 1 ); 10279cudaStreamWaitEvent (cs ,lb .ev_in [c & 1 ],0 ); 10280 }else { 10281cudaStreamWaitEvent (cs ,lb .ev_out [c & 1 ],0 );// its last download (sub-chunk c - 2) is done 10282 } 10283 } 10284m .mixed = lb .mixed + t0 * N ; 10285m .mixed_h = lb .mixed_h + t0 * N ;// the FFN half's FP16 rows stay for the layer's FP16 expert pass 10286m .inj = lb .inj + t0 * HC ; 10287float * const acc = lb .acc + t0 * N ; 10288if (l == 0 ) { 10289// ---- embeddings, broadcast to the four streams (run_impl's C-4 batched gather, else per token) 10290pt .mark (kPfStart ,cs ); 10291bool batched = m .tok_dev != nullptr ; 10292const core::NativeEmbed * nemb = core::native_embed (); 10293const core::WeightRef * wemb = nemb ?nullptr :m .wt -> find ("token_embd.weight" ); 10294if (batched && nemb == nullptr && 10295 (wemb == nullptr || wemb -> codebook_iq4nl || wemb -> ne0 != g .n_embd || wemb -> group_elems <=0 || 10296 (wemb -> code_bits != 2 && wemb -> code_bits != 4 && wemb -> code_bits != 8 ))) 10297batched = false; 10298for (int64_t t = 0 ;batched && t < T ;++ t ) { 10299const int64_t tok = tokens [c0 + t ]; 10300if (tok < 0 || (wemb && tok >=wemb -> ne1 ))batched = false; 10301else m .tok_host [(size_t )t ]= (int32_t )tok ; 10302 } 10303if (batched ) { 10304if (!m .tok_up .upload (m .tok_dev ,m .tok_host .data (), (size_t )T ,cs )) { 10305err = "prefill: the token id upload failed" ; 10306return false; 10307 } 10308if (nemb ) { 10309nemb -> gather_dev (m .tok_dev ,T ,m .emb ,cs ); 10310 }else { 10311const auto * codes = (const uint8_t * )wemb -> data ; 10312const auto * scales = (const float * ) (codes + wemb -> codes_bytes ); 10313const auto * offsets = wemb -> has_offset ? (const float * ) (codes + wemb -> codes_bytes + wemb -> scales_bytes ) 10314 :nullptr ; 10315 strata::kernels::embedding_gather_dev (codes ,scales ,offsets ,m .tok_dev , (int )T ,wemb -> ne0 , 10316wemb -> code_bits ,wemb -> code_bias ,wemb -> group_elems , 10317 (uint64_t ) (wemb -> ne0 / (8 /wemb -> code_bits )), 10318 (uint64_t ) (wemb -> ne0 /wemb -> group_elems ),m .emb ,cs ); 10319 } 10320 } 10321for (int64_t t = 0 ; !batched && t < T ;++ t ) 10322if (!core::embed_row (* m .wt ,g ,tokens [c0 + t ],m .emb + t * N ,cs ,err ))return false; 10323gr_broadcast (m .emb ,m .R ,T ,cs ); 10324if (ple_on && !ple_next .valid ()) 10325ple_next = std::async (std::launch::async , [& ple_gather ,& ple_next_err ,gi ,b = ple_buf ] { 10326 strata::aux_cpus::pin_current_thread (); 10327return ple_gather (gi ,b ,ple_next_err ); 10328 }); 10329 { 10330 std::array < int32_t ,2 >& pvv = prevs [(size_t )sub .seg ]; 10331for (int64_t t = 0 ;t < T ;++ t ) {pvv [0 ]= pvv [1 ];pvv [1 ]= (int32_t )tokens [c0 + t ]; } 10332 } 10333 }else if (l > LB ) {// (a later stage's first layer: the stage before wrote layer LB - 1) 10334// the previous layer's experts: the hyper-connection write of its FFN half 10335gr_write (m .R ,acc ,m .inj ,HC ,T ,cs ); 10336if (strata::kernels::cvec ().covers (l - 1 )) 10337 strata::kernels::cvec_apply (m .R ,l - 1 ,T ,D ,nullptr ,0 ,nullptr ,0 , false,cs ); 10338#if defined(STRATA_HAVE_DFLASH2 ) 10339if (tap_on && tap_slot [(size_t ) (l - 1 )] >=0 ) {// layer l - 1 is complete: its tapped rows of this sub-chunk, mean of the streams 10340const int64_t lo = std::min < int64_t > (T , std::max < int64_t > (0 ,tap_s0 - t0 )); 10341if (lo < T ) 10342 strata::kernels::df2_tap_rows (m .R + lo * D , 10343tap_dev_ + (size_t ) (t0 + lo - tap_s0 )* tap_layers_ .size ()* (size_t )N + (size_t )tap_slot [(size_t ) (l - 1 )]* (size_t )N , 10344 (int64_t )tap_layers_ .size ()* N ,N , (int )HC , (int ) (T - lo ),cs ); 10345 } 10346#endif 10347 } 10348if (l == LE && next_ != nullptr ) { 10349// ---- a layer split: this sub-chunk's rows into the next stage's R_host (on the copy stream, as 10350// the per-layer download) once the next stage has finished the previous super-chunk 10351stats_ .tokens += T ; 10352++ stats_ .chunks ; 10353if (c == 0 && next_run_ .valid ()&& !next_run_ .get ()) {err = next_err_ ;return false; } 10354cudaEventRecord (lb .ev_done [c & 1 ],cs ); 10355cudaStreamWaitEvent (m .copy ,lb .ev_done [c & 1 ],0 ); 10356if (cudaMemcpyAsync (next_ -> impl_ -> lm .R_host + (size_t )t0 * D ,m .R , (size_t )T * D * 4 , 10357cudaMemcpyDeviceToHost ,m .copy )!= cudaSuccess ) { 10358err = "prefill (layer-major): the layer split's hand-off failed" ; 10359return false; 10360 } 10361cudaEventRecord (lb .ev_out [c & 1 ],m .copy ); 10362continue ; 10363 } 10364if (l == LE ) { 10365// ---- the final rows of this sub-chunk: reported in order, as run_impl's chunks are 10366stats_ .tokens += T ; 10367++ stats_ .chunks ; 10368if (const char * dump = std::getenv ("STRATA_PREFILL_DUMP_R" )) {// debug: run_impl's dump format 10369cudaStreamSynchronize (cs ); 10370if (std::FILE * f = std::fopen (dump ,p0 == 0 ?"wb" :"ab" )) { 10371 std::vector < float > row ((size_t )D ); 10372for (int64_t t = (64 - p0 %64 ) %64 ;t < T ;t += 64 ) { 10373cudaMemcpy (row .data (),m .R + t * D , (size_t )D * 4 ,cudaMemcpyDeviceToHost ); 10374const int64_t pos = p0 + t ; 10375 std::fwrite (& pos ,sizeof pos ,1 ,f ); 10376 std::fwrite (row .data (),4 ,row .size (),f ); 10377 } 10378 std::fclose (f ); 10379 } 10380 } 10381if (on_chunk || on_stage_chunk ) { 10382if (cudaStreamSynchronize (cs )!= cudaSuccess ) { 10383err = std::string ("prefill: " )+ cudaGetErrorString (cudaGetLastError ()); 10384return false; 10385 } 10386lm_mid_ = c != last_seg0 && last_seg0 >=0 ; 10387if (sub .seg == 0 ) {// (the reports are the first prompt's; the others only fill their sessions) 10388if (on_stage_chunk && !lm_mid_ && !on_stage_chunk (p0 + T ,err ))return false; 10389if (on_chunk && !on_chunk (m .R ,T ,p0 ,err ))return false; 10390 } 10391 } 10392continue ; 10393 } 10394const core::LayerView v (* m .wt ,l ); 10395if (l == 1 && ple_on && !ple_land (gi ,T ))return false; 10396// ---- the PLE block at layer 1 (run_impl's, batched or token by token) 10397if (l == 1 && ple_on && ple_batch ) { 10398pt .mark (kPfPle ,cs ); 10399const auto tp = Clock ::now (); 10400const strata::kernels::PleWeights & pw = pss -> ple .w ; 10401constexpr int64_t HD = strata::kernels::NG_HC_DIM ; 10402const uint64_t per_token = (uint64_t ) (3 * HD + N + 4 )* 4 + (uint64_t )N * (bf16x2 (m .f16_io ) ?4 :2 )+ 4096 ; 10403const int64_t SB = std::min < int64_t > (T , (int64_t ) (m .region_bytes /per_token )); 10404for (int64_t s0 = 0 ;s0 < T ;s0 += SB ) { 10405const int64_t nb = std::min (SB ,T - s0 ); 10406uint8_t * q = m .region ; 10407auto carve_f = [& ](size_t nn ) {float * p = (float * )q ;q += (nn * 4 + 255 )& ~(size_t )255 ;return p ; }; 10408float * key = carve_f ((size_t )nb * HD ); 10409float * qn = carve_f ((size_t )nb * HD ); 10410float * gated = carve_f ((size_t )nb * HD ); 10411float * val = carve_f ((size_t )nb * N ); 10412float * gate = carve_f ((size_t )nb * 4 ); 10413uint16_t * e16 = (uint16_t * )carve_f ((size_t )nb * N /2 ); 10414uint16_t * e16_lo = bf16x2 (m .f16_io ) ? (uint16_t * )carve_f ((size_t )nb * N /2 ) :nullptr ; 10415const float * emb = m .ple_emb + s0 * N ; 10416if (pw .key_bf16 != nullptr ) { 10417to_bf16 (emb ,e16 ,nb * N ,cs ,e16_lo ); 10418m .gemm .bf16 (e16 ,pw .key_bf16 ,key ,nb ,HD ,N ); 10419if (e16_lo )m .gemm .bf16 (e16_lo ,pw .key_bf16 ,key ,nb ,HD ,N ,0 ,1.0f ); 10420 }else { 10421to_f16 (emb ,e16 ,nb * N ,cs ); 10422m .gemm .native (e16 ,pw .key_native_type ,pw .key_native_data ,key ,nb ,HD ,N ); 10423to_bf16 (emb ,e16 ,nb * N ,cs ,e16_lo ); 10424 } 10425m .gemm .bf16 (e16 ,pw .value_bf16 ,val ,nb ,N ,N ); 10426if (e16_lo )m .gemm .bf16 (e16_lo ,pw .value_bf16 ,val ,nb ,N ,N ,0 ,1.0f ); 10427try { 10428 strata::kernels::native_ple_postops_batch (key ,m .R + s0 * D ,val ,ssp -> ple_hist ,pw ,qn ,gated , 10429gate , (int )nb ,cs ); 10430 }catch (const std::exception & e ) {err = std::string ("prefill PLE: " )+ e .what ();return false; } 10431 } 10432stats_ .ms_ple += ms_since (tp ); 10433 }else if (l == 1 && ple_on ) { 10434pt .mark (kPfPle ,cs ); 10435const auto tp = Clock ::now (); 10436for (int64_t t = 0 ;t < T ;++ t ) { 10437 strata::kernels::PleOut po ; 10438po .normalized = m .ple_norm ; 10439po .result = m .R + t * D ; 10440try { 10441 strata::kernels::ple_block (m .ple_emb + t * N ,m .R + t * D ,ssp -> ple_hist ,pss -> ple .w ,po , 10442pss -> ple .scratch ,cs ); 10443 }catch (const std::exception & e ) {err = std::string ("prefill PLE: " )+ e .what ();return false; } 10444 strata::kernels::ple_history_advance (ssp -> ple_hist ,m .ple_norm ,cs ); 10445 } 10446stats_ .ms_ple += ms_since (tp ); 10447 } 10448if (core::is_qsa_layer (g ,l )) {// the QSA step records of this sub-chunk's positions 10449for (int64_t t = 0 ;t < T ;++ t ) 10450 strata::kernels::qsa_step_fill (m .steps_host .data ()+ t * strata::kernels::kStepCount ,p0 + t ,s ); 10451// the host table is rewritten by the next QSA sub-chunk: its upload has read it by then (#1996: from a 10452// pinned slot) 10453if (m .up_ring .h2d (m .steps_dev ,m .steps_host .data (), (size_t )T * strata::kernels::kStepCount * 4 ,cs )!= 10454cudaSuccess ) { 10455err = "prefill: the QSA step records' upload failed" ; 10456return false; 10457 } 10458 } 10459bool normed = false; 10460for (int half = 0 ;half < 2 ;++ half ) { 10461// ---- the hyper-connection read of this half (run_impl's) 10462const char * pre = half == 0 ?"hc_attn_" :"hc_ffn_" ; 10463const std::string sn = std::string (pre )+ "norm.weight" ,sd = std::string (pre )+ "down.weight" , 10464su = std::string (pre )+ "up.weight" ,si = std::string (pre )+ "inject.weight" ; 10465const core::WeightRef * wn = need (v ,sn .c_str (),err ),* wd = need (v ,sd .c_str (),err ), 10466* wu = need (v ,su .c_str (),err ),* wi = need (v ,si .c_str (),err ); 10467if (!wn || !wd || !wu || !wi )return false; 10468// STRATA_HC_Q8 without a bf16 copy (0.2.2's run_impl): this path's GEMMs read bf16, so the matrices 10469// are dequantized per half 10470 core::WeightRef wd_q8 ,wu_q8 ; 10471if (!wd -> data && wd -> hc_q8 && !wu -> data && wu -> hc_q8 ) { 10472wd_q8 = * wd ;wu_q8 = * wu ; 10473wd_q8 .data = core::NativeDense ::hc_bf16_view (* wd ,cs ,0 ,0 ); 10474wu_q8 .data = core::NativeDense ::hc_bf16_view (* wu ,cs ,1 ,0 ); 10475if (!wd_q8 .data || !wu_q8 .data ) {err = "prefill: the Q8_0 hyper-connection projections could not be dequantized" ;return false; } 10476wd = & wd_q8 ;wu = & wu_q8 ; 10477 } 10478// the stream is not optional: under STRATA_HC_REQ8 bf16_proj expands the int8 codes into one static 10479// scratch per call site, on the stream it is given. Omitted, the GEMMs below read it out of order. 10480pt .mark (kPfHc ,cs ); 10481if (gr_unfused ())gr_norm (m .R , (const float * )wn -> data ,EPS ,m .xn ,m .xn16 ,T ,cs ,m .xn16_lo ); 10482else if (!normed )gr_norm_rs (m .R , (const float * )wn -> data ,EPS ,m .grs ,m .xn16 ,T ,cs ,m .xn16_lo ); 10483normed = false; 10484if (!bf16_proj (m .gemm ,wd ,m .xn16 ,m .lo ,T ,sd ,err ,0 ,m .xn16_lo ,0 ,cs ))return false; 10485gr_silu (m .lo ,m .lo16 ,T ,cs ,m .lo16_lo ); 10486if (!bf16_proj (m .gemm ,wu ,m .lo16 ,m .gated ,T ,su ,err ,0 ,m .lo16_lo ,0 ,cs ))return false; 10487if (!bf16_proj (m .gemm ,wi ,m .xn16 ,m .inj ,T ,si ,err ,0 ,m .xn16_lo ,0 ,cs ))return false; 10488if (gr_unfused ())gr_mix (m .xn ,m .gated ,m .mixed ,m .mixed_bf ,T ,cs ,m .mixed_h ,m .mixed_bf_lo ); 10489else gr_mix_r (m .R ,m .grs , (const float * )wn -> data ,m .gated ,m .mixed ,m .mixed_bf ,T ,cs ,m .mixed_h , 10490m .mixed_bf_lo ); 10491if (wd_q8 .data ) {// the HC GEMMs that read the scratch are enqueued: the next user waits for them 10492 core::NativeDense ::hc_bf16_release (cs ,0 ,0 ); 10493 core::NativeDense ::hc_bf16_release (cs ,1 ,0 ); 10494 } 10495if (half == 0 && !core::is_qsa_layer (g ,l )) { 10496// ======================= GDN (run_impl's) ======================= 10497const core::WeightRef * wqkv = need (v ,"attn_qkv.weight" ,err ),* wg = need (v ,"attn_gate.weight" ,err ), 10498* wo = need (v ,"ssm_out.weight" ,err ),* wa = need (v ,"ssm_alpha.weight" ,err ), 10499* wb = need (v ,"ssm_beta.weight" ,err ),* wc = need (v ,"ssm_conv1d.weight" ,err ), 10500* wnm = need (v ,"ssm_norm.weight" ,err ),* wdt = need (v ,"ssm_dt.bias" ,err ), 10501* wsa = need (v ,"ssm_a" ,err ); 10502if (!wqkv || !wg || !wo || !wa || !wb || !wc || !wnm || !wdt || !wsa )return false; 10503pt .mark (kPfGdn ,cs ); 10504float * state = ssp -> gdn_state + (size_t ) (gdn_index - ssp -> gdn_ord0 )* gdn_floats ; 10505float * conv = state + (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size ; 10506if (!native_proj (m .gemm ,wqkv ,m .mixed_h ,m .qkv ,T ,v .name ("attn_qkv.weight" ),err ))return false; 10507if (!native_proj (m .gemm ,wg ,m .mixed_h ,m .z ,T ,v .name ("attn_gate.weight" ),err ))return false; 10508if (!bf16_proj (m .gemm ,wa ,m .mixed_bf ,m .ab ,T ,v .name ("ssm_alpha.weight" ),err ,2 * HV ,m .mixed_bf_lo ))return false; 10509if (!bf16_proj (m .gemm ,wb ,m .mixed_bf ,m .ab + HV ,T ,v .name ("ssm_beta.weight" ),err ,2 * HV ,m .mixed_bf_lo ))return false; 10510pt .mark (kPfGdnConv ,cs ); 10511gdn_gates (m .ab , (const float * )wdt -> data , (const float * )wsa -> data ,m .gate ,m .beta ,T ,cs ); 10512bool fused_gdn = false; 10513#if defined(STRATA_USE_HIP ) 10514fused_gdn = gdn_conv_recurrence_fused (conv ,m .qkv , (const float * )wc -> data ,m .hbuf ,state ,m .gate ,m .beta ,m .z , 10515 (const float * )wnm -> data ,EPS ,EPS ,m .y ,m .y_h ,T ,cs ,0 ); 10516#endif 10517if (!fused_gdn )gdn_conv (conv ,m .qkv , (const float * )wc -> data ,m .hbuf ,T ,EPS ,cs ); 10518pt .mark (kPfGdnRec ,cs ); 10519if (!fused_gdn ) 10520gdn_recurrence (state ,m .hbuf ,m .gate ,m .beta ,m .z , (const float * )wnm -> data ,EPS ,m .y ,m .y_h ,T ,cs ); 10521pt .mark (kPfGdnOut ,cs ); 10522if (!native_proj (m .gemm ,wo ,m .y_h ,m .bo ,T ,v .name ("ssm_out.weight" ),err ))return false; 10523++ gdn_index ; 10524 }else if (half == 0 ) { 10525// ======================= QSA (run_impl's, without its debug dumps) ======================= 10526const core::QsaState & st = ssp -> qsa_states [qsa_index ]; 10527const core::WeightRef * wq = need (v ,"attn_q.weight" ,err ),* wk = need (v ,"attn_k.weight" ,err ), 10528* wv = need (v ,"attn_v.weight" ,err ),* wo = need (v ,"attn_output.weight" ,err ), 10529* wik = need (v ,"indexer.k_proj.weight" ,err ), 10530* wiq = need (v ,"indexer.q_proj.weight" ,err ), 10531* wqn = need (v ,"attn_q_norm.weight" ,err ),* wkn = need (v ,"attn_k_norm.weight" ,err ), 10532* wiqn = need (v ,"indexer.q_norm.weight" ,err ), 10533* wikn = need (v ,"indexer.k_norm.weight" ,err ); 10534if (!wq || !wk || !wv || !wo || !wik || !wiq || !wqn || !wkn || !wiqn || !wikn )return false; 10535pt .mark (kPfQsa ,cs ); 10536if (!native_proj (m .gemm ,wk ,m .mixed_h ,m .Kc ,T ,v .name ("attn_k.weight" ),err ))return false; 10537if (!native_proj (m .gemm ,wv ,m .mixed_h ,m .Vc ,T ,v .name ("attn_v.weight" ),err ))return false; 10538if (!native_proj (m .gemm ,wq ,m .mixed_h ,m .Qf ,T ,v .name ("attn_q.weight" ),err ))return false; 10539if (!bf16_proj (m .gemm ,wik ,m .mixed_bf ,m .idx_raw ,T ,v .name ("indexer.k_proj.weight" ),err ,0 ,m .mixed_bf_lo ))return false; 10540if (!bf16_proj (m .gemm ,wiq ,m .mixed_bf ,m .q_idx ,T ,v .name ("indexer.q_proj.weight" ),err ,0 ,m .mixed_bf_lo ))return false; 10541if (qsa_fuse_nr ()) { 10542rms_rope_rows (m .Kc ,512 ,256 ,m .Kc ,512 , (const float * )wkn -> data ,T ,2 ,256 ,EPS ,p0 , strata::kernels::rope_scaling (),cs ); 10543 }else { 10544rms_rows (m .Kc , (const float * )wkn -> data ,T * 2 ,256 ,256 ,EPS ,cs ); 10545rope (m .Kc ,T ,2 ,256 ,512 ,p0 , strata::kernels::rope_scaling (),cs ); 10546 } 10547const bool staged = st .kv_mode == 1 ; 10548if (staged ) { 10549pt .mark (kPfKvStage ,cs ); 10550 strata::kernels::kv_stage_from_host (pools_of (m .stage ,m .ident_table ),st .host , 10551 core::qsa_kv_format (st ), 10552 (p0 + s .page_size - 1 ) /s .page_size ,s ,cs ); 10553pt .mark (kPfQsa ,cs ); 10554 } 10555#if defined(STRATA_USE_HIP ) 10556static const bool kv_host_dma = [] {const char * e = std::getenv ("STRATA_KV_HOST_DMA" );return e && e [0 ]== '1' ; }(); 10557#else 10558static const bool kv_host_dma = core::kv_host_dma_on (std::getenv ("STRATA_KV_HOST_DMA" ), true); 10559#endif 10560const bool host_by_dma = core::kv_host_dma_use (kv_host_dma ,staged ,m .stage .present ()); 10561const strata::kernels::KvHostPools * host_w = host_by_dma ?nullptr :& st .host ; 10562if (st .kv_hybrid ) { 10563// streamed: each half writes its part of the host copy and of the staging pool 10564 strata::kernels::fwht256_inplace_cuda (m .Vc ,T * 2 ,cs ); 10565const strata::kernels::KvHostPools hk = strata::kernels::kv_hybrid_k_half (st .host ), 10566hv = strata::kernels::kv_hybrid_v_half (st .host ), 10567sk = strata::kernels::kv_hybrid_k_half (m .stage ), 10568sv = strata::kernels::kv_hybrid_v_half (m .stage ); 10569const bool mirror = st .host .present (); 10570kv_append (m .Kc ,m .Kc ,T ,p0 ,st .page_table ,s .page_size ,nullptr ,nullptr , 10571st .k_q ,st .k_q ,st .k_scale ,st .k_scale ,cs ,mirror ?& hk :nullptr , 10572staged ?& sk :nullptr ); 10573 strata::kernels::kv_append_q4 (st .v_q4 ,st .v_q4 ,st .page_table ,p0 ,T ,m .Vc ,m .Vc ,s ,cs , 10574mirror ?& hv :nullptr ,staged ?& sv :nullptr ); 10575 }else { 10576if (st .kv_rot ) { 10577 strata::kernels::fwht256_inplace_cuda (m .Kc ,T * 2 ,cs ); 10578 strata::kernels::fwht256_inplace_cuda (m .Vc ,T * 2 ,cs ); 10579 } 10580if (st .kv_q4 ) 10581 strata::kernels::kv_append_q4 (st .k_q4 ,st .v_q4 ,st .page_table ,p0 ,T ,m .Kc ,m .Vc ,s ,cs , 10582host_w ,staged ?& m .stage :nullptr ); 10583else 10584kv_append (m .Kc ,m .Vc ,T ,p0 ,st .page_table ,s .page_size ,st .kv_int8 ?nullptr :st .k_pool , 10585st .kv_int8 ?nullptr :st .v_pool ,st .k_q ,st .v_q ,st .k_scale ,st .v_scale ,cs , 10586host_w ,staged ?& m .stage :nullptr ); 10587if (host_by_dma ) 10588 strata::kernels::kv_unstage_to_host (pools_of (m .stage ,m .ident_table ),st .host , 10589 core::qsa_kv_format (st ),p0 /s .page_size , 10590 (p0 + T + s .page_size - 1 ) /s .page_size ,s ,cs ); 10591 } 10592if (qsa_fuse_nr ()) { 10593rms_rope_rows (m .Qf ,kQFull ,2 * kHeadDim ,m .q ,kQW , (const float * )wqn -> data ,T ,kNHead ,kHeadDim ,EPS ,p0 , strata::kernels::rope_scaling (),cs ); 10594 }else { 10595split_q (m .Qf ,m .q ,T ,cs ); 10596rms_rows (m .q , (const float * )wqn -> data ,T * kNHead ,kHeadDim ,kHeadDim ,EPS ,cs ); 10597rope (m .q ,T ,kNHead ,kHeadDim ,kQW ,p0 , strata::kernels::rope_scaling (),cs ); 10598 } 10599if (st .kv_rot ) strata::kernels::fwht256_inplace_cuda (m .q ,T * kNHead ,cs ); 10600if (qsa_fuse_nr ()) { 10601rms_rope_rows (m .q_idx ,512 ,128 ,m .q_idx ,512 , (const float * )wiqn -> data ,T ,4 ,128 ,EPS ,p0 , strata::kernels::rope_scaling (),cs ); 10602 }else { 10603rms_rows (m .q_idx , (const float * )wiqn -> data ,T * 4 ,128 ,128 ,EPS ,cs ); 10604rope (m .q_idx ,T ,4 ,128 ,512 ,p0 , strata::kernels::rope_scaling (),cs ); 10605 } 10606const strata::kernels::QsaIndexerBuffers ib {st .idx_tail ,st .idx_dead ,st .idx_pooled ,st .idx_block_pos }; 10607pt .mark (kPfQsaIdx ,cs ); 10608try { 10609static const bool per_token = std::getenv ("STRATA_INDEXER_PER_TOKEN" )!= nullptr ; 10610if (!per_token ) { 10611 strata::kernels::native_qsa_indexer_append_batch (m .idx_raw ,T ,p0 ,0 , (const float * )wikn -> data , 10612EPS ,ib ,s ,st .max_cells , 10613 strata::kernels::rope_scaling (),cs ); 10614 } 10615for (int64_t t = 0 ;per_token && t < T ;++ t ) { 10616const int32_t * step_t = m .steps_dev + t * strata::kernels::kStepCount ; 10617 strata::kernels::native_qsa_indexer_append (m .idx_raw + t * 128 ,step_t + strata::kernels::kStepPos ,0 , 10618 (const float * )wikn -> data ,EPS ,ib ,s ,st .max_cells , 10619 strata::kernels::rope_scaling (),cs ); 10620 } 10621 }catch (const std::exception & e ) {err = std::string ("prefill indexer: " )+ e .what ();return false; } 10622pt .mark (kPfQsaSel ,cs ); 10623for (int64_t q0 = 0 ;q0 < T ;q0 += m .sel_batch ) { 10624const int64_t nb = std::min (m .sel_batch ,T - q0 ); 10625const int32_t * steps0 = m .steps_dev + q0 * strata::kernels::kStepCount ; 10626const int64_t active = (int64_t )m .steps_host [(size_t ) ((q0 + nb - 1 )* strata::kernels::kStepCount + 10627 strata::kernels::kStepNBid )]+ 1 ; 10628static const bool old_sel = std::getenv ("STRATA_SELECT_OLD" )!= nullptr ; 10629if (old_sel || !strata::kernels::qsa_block_scores_tc (st .idx_pooled ,st .idx_dead ,m .q_idx + q0 * 512 , 10630steps0 ,nb ,m .max_blocks ,s ,m .sel_scores , 10631cs ,active )) 10632 strata::kernels::qsa_block_scores (st .idx_pooled ,st .idx_dead ,m .q_idx + q0 * 512 ,steps0 ,nb , 10633m .max_blocks ,s ,m .sel_scores ,cs ,active ); 10634 strata::kernels::qsa_block_topk (m .sel_scores ,steps0 ,nb ,m .max_blocks ,m .cap ,s , 10635m .sel_ids + q0 * m .cap ,cs ,active ); 10636 } 10637const strata::kernels::QsaAttnPools pools = staged ?pools_of (m .stage ,m .ident_table ) 10638 : core::qsa_attn_pools (st ); 10639pt .mark (kPfQsaAttn ,cs ); 10640static const bool old_attn = std::getenv ("STRATA_PROMPT_ATTN_OLD" )!= nullptr ; 10641const bool gated = !old_attn && !st .kv_rot && !st .kv_hybrid && qsa_fuse_gate ()&& 10642 strata::kernels::qsa_prompt_attn_batch_gated (m .q ,pools ,m .sel_ids ,m .steps_dev ,m .cap ,s , 10643m .Qf ,m .attn_h ,ZV ,T ,cs ); 10644if (!gated && (old_attn || !strata::kernels::qsa_prompt_attn_batch (m .q ,pools ,m .sel_ids ,m .steps_dev ,m .cap ,s , 10645m .attn ,T ,cs ))) 10646for (int64_t q0 = 0 ;q0 < T ;q0 += m .attn_batch ) { 10647const int64_t nb = std::min (m .attn_batch ,T - q0 ); 10648 strata::kernels::qsa_decode_attn_batch (m .q + q0 * kQW ,pools ,m .sel_ids + q0 * m .cap , 10649m .steps_dev + q0 * strata::kernels::kStepCount ,m .cap , 10650s ,m .attn_scratch ,m .attn + q0 * kQW ,nb ,cs ); 10651 } 10652if (st .kv_rot || st .kv_hybrid ) strata::kernels::fwht256_inplace_cuda (m .attn ,T * kNHead ,cs ); 10653pt .mark (kPfQsa ,cs ); 10654if (!gated )gate_attn (m .attn ,m .Qf ,m .attn_h ,T ,cs ); 10655if (!native_proj (m .gemm ,wo ,m .attn_h ,m .bo ,T ,v .name ("attn_output.weight" ),err ))return false; 10656++ qsa_index ; 10657 }else { 10658// ======================= the FFN half: router + shared expert now, the experts later ========= 10659const core::WeightRef * wr = need (v ,"ffn_gate_inp.weight" ,err ), 10660* wgi = need (v ,"ffn_gate_inp_shexp.weight" ,err ), 10661* wsg = need (v ,"ffn_gate_shexp.weight" ,err ), 10662* wsu = need (v ,"ffn_up_shexp.weight" ,err ), 10663* wsd = need (v ,"ffn_down_shexp.weight" ,err ); 10664if (!wr || !wgi || !wsg || !wsu || !wsd )return false; 10665pt .mark (kPfRouter ,cs ); 10666if (!bf16_proj (m .gemm ,wr ,m .mixed_bf ,m .logits ,T ,v .name ("ffn_gate_inp.weight" ),err ,0 ,m .mixed_bf_lo ))return false; 10667route (m .logits ,lb .ids + t0 * K ,lb .w + t0 * K ,T ,m .g -> n_expert ,cs ); 10668if (!native_proj (m .gemm ,wsg ,m .mixed_h ,m .sgate ,T ,v .name ("ffn_gate_shexp.weight" ),err ))return false; 10669if (!native_proj (m .gemm ,wsu ,m .mixed_h ,m .sup ,T ,v .name ("ffn_up_shexp.weight" ),err ))return false; 10670swiglu_pair (m .sgate ,m .sup ,m .sh_h ,T ,cs ); 10671if (!native_proj (m .gemm ,wsd ,m .sh_h ,m .shared ,T ,v .name ("ffn_down_shexp.weight" ),err ))return false; 10672if (wgi -> kind != core::WeightKind ::Bf16InF32 ) {err = "prefill: shared gate is not BF16" ;return false; } 10673m .gemm .bf16 (m .mixed_bf , (const uint16_t * )wgi -> data ,m .sg ,T ,1 ,N ); 10674if (m .mixed_bf_lo )m .gemm .bf16 (m .mixed_bf_lo , (const uint16_t * )wgi -> data ,m .sg ,T ,1 ,N ,0 ,1.0f ); 10675if (m .latent ) { 10676if (!latent_dense_route (l ,t0 ,T ))return false; 10677cudaMemcpyAsync (lb .mixed + t0 * N ,m .shared , (size_t )T * N * 4 ,cudaMemcpyDeviceToDevice ,cs ); 10678cudaMemcpyAsync (lb .lat_sg + t0 ,m .sg , (size_t )T * 4 ,cudaMemcpyDeviceToDevice ,cs ); 10679 }else { 10680moe_shared_init (m .shared ,m .sg ,acc ,T ,cs ); 10681 } 10682break ;// the FFN half's write waits for the experts (the next layer, or the final pass) 10683 } 10684// ---- the attention half's write, fused with the FFN half's norm (run_impl's F-2) 10685const core::WeightRef * wnn = nullptr ; 10686if (!gr_unfused ()) { 10687wnn = need (v ,"hc_ffn_norm.weight" ,err ); 10688if (!wnn )return false; 10689 } 10690if (wnn ) { 10691gr_write_norm_rs (m .R ,m .bo ,m .inj ,HC , (const float * )wnn -> data ,EPS ,m .grs ,m .xn16 ,T ,cs , 10692m .xn16_lo ); 10693normed = true; 10694 }else { 10695gr_write (m .R ,m .bo ,m .inj ,HC ,T ,cs ); 10696 } 10697 } 10698if (!lb .r_dev ) {// down on the copy stream once this sub-chunk's work is done 10699cudaEventRecord (lb .ev_done [c & 1 ],cs ); 10700cudaStreamWaitEvent (m .copy ,lb .ev_done [c & 1 ],0 ); 10701if (cudaMemcpyAsync (lb .R_host + (size_t )t0 * D ,m .R , (size_t )T * D * 4 ,cudaMemcpyDeviceToHost , 10702m .copy )!= cudaSuccess ) { 10703err = "prefill (layer-major): the residual rows' download failed" ; 10704return false; 10705 } 10706cudaEventRecord (lb .ev_out [c & 1 ],m .copy ); 10707 } 10708 } 10709ms_attn += ms_since (ta ); 10710if (l == LE )break ; 10711if (!lm_experts (l ,Sn ))return false; 10712 } 10713#if defined(STRATA_HAVE_DFLASH2 ) 10714if (tap_on && tap_super_rows > 0 ) {// every layer of the super-chunk is done: its tapped rows, in position order (DF-08) 10715if (cudaStreamSynchronize (cs )!= cudaSuccess ) {err = std::string ("prefill: " )+ cudaGetErrorString (cudaGetLastError ());return false; } 10716if (!on_taps (tap_dev_ ,tap_super_rows ,super_pos + tap_s0 ,err ))return false; 10717 } 10718#endif 10719if (next_ != nullptr ) {// the super-chunk's rows are in the next stage's R_host: it reads them on a thread 10720if (cudaStreamSynchronize (cs )!= cudaSuccess || cudaStreamSynchronize (m .copy )!= cudaSuccess ) { 10721err = std::string ("prefill (layer-major): the layer split's hand-off: " )+ 10722cudaGetErrorString (cudaGetLastError ()); 10723return false; 10724 } 10725if (on_stage_chunk && last_seg0 >=0 && 10726 !on_stage_chunk (segs [0 ].pos0 + subs [(size_t )last_seg0 ].c0 + subs [(size_t )last_seg0 ].T ,err )) 10727return false; 10728next_err_ .clear (); 10729next_run_ = std::async (std::launch::async , [this ,segs_c = std::make_shared < std::vector < Seg >> (segs ),depth , 10730sp_super = std::make_shared < std::vector < LmSub >> (supers [sci ])] { 10731 strata::aux_cpus::pin_current_thread (); 10732return next_ -> lm_run (* segs_c ,depth + 1 ,sp_super .get (),next_err_ ); 10733 }); 10734 } 10735 } 10736lm_mid_ = false; 10737for (size_t i = 0 ;i < segs .size ();++ i ) { 10738ss_of (i )-> ple_prev [0 ]= prevs [i ][0 ]; 10739ss_of (i )-> ple_prev [1 ]= prevs [i ][1 ]; 10740 } 10741if (short_lo_ != nullptr ) { 10742short_lo_ -> ple_prev [0 ]= prevs [0 ][0 ]; 10743short_lo_ -> ple_prev [1 ]= prevs [0 ][1 ]; 10744 } 10745if (ple_next .valid ())ple_next .wait (); 10746if (cudaStreamSynchronize (cs )!= cudaSuccess ) { 10747err = std::string ("prefill: " )+ cudaGetErrorString (cudaGetLastError ()); 10748return false; 10749 } 10750if (const cudaError_t cst = cudaStreamSynchronize (m .copy );cst != cudaSuccess ) { 10751err = std::string ("prefill: expert copy stream: " )+ cudaGetErrorString (cst ); 10752return false; 10753 } 10754stats_ .ms_total += ms_since (t_start ); 10755lm_streamed += pre_blobs .load (); 10756lm_bytes += (uint64_t )pre_bytes .load (); 10757 std::fprintf (stderr ,"strata prefill: layer-major (layers %lld..%lld): %lld tokens in %lld super-chunk(s) of up to %lld (R in %s, %lld MiB VRAM free before), " 10758"%lld expert blobs streamed (%.1f MB), %lld resident, %lld expert groups (%lld on the FP16 path, %lld fused); %.0f ms (host: " 10759"enqueueing the attention halves %.0f, the experts %.0f: waiting for the attention halves " 10760"%.0f, the routing tables %.0f, the expert files %.0f)\n" , 10761 (long long )LB , (long long )LE , (long long )n , (long long )lm_supers , (long long )S , 10762lb .r_dev ?"VRAM" :"pinned RAM" , (long long )lb .free_mib , 10763 (long long )lm_streamed , (double )lm_bytes /1e6 , (long long )lm_resident , (long long )lm_groups , 10764 (long long )lm_groups_f16 , (long long )lm_groups_fz ,ms_since (t_start ),ms_attn ,ms_experts ,ms_wait_a ,ms_host_tables ,ms_wait_files ); 10765if (pt .on ) { 10766pt .fold (); 10767double total = 0.0 ; 10768for (double x :pt .ms )total += x ; 10769 std::string line ; 10770char b [96 ]; 10771for (int i = 0 ;i < kPfCount ;++ i ) { 10772if (pt .ms [i ] <=0.0 )continue ; 10773 std::snprintf (b ,sizeof b ," %s %.0f (%.1f%%)" ,kPfNames [i ],pt .ms [i ],total > 0 ?100.0 * pt .ms [i ] /total :0.0 ); 10774line += b ; 10775 } 10776 std::fprintf (stderr ,"strata prefill timing (layer-major): %lld tokens, GPU timeline %.0f ms:%s\n" , 10777 (long long )n ,total ,line .c_str ()); 10778 } 10779return true; 10780} 10781 10782 10783// The first stage's rows of layers [0, lo_end) that `mine` lacks, laid out in one slot (256-byte aligned: the canonical 10784// bytes, then the native GGUF blocks). `each` sees every row with its offsets and may refuse it. Returns one slot's row 10785// bytes; `why` is set when a row cannot be streamed. 10786template < class Each > 10787static uint64_t short_rows (const core::WeightTable & mine ,const core::WeightTable & first ,int64_t lo_end , std::string & why , 10788Each && each ) { 10789uint64_t need = 0 ; 10790for (int64_t l = 0 ;l < lo_end && why .empty ();++ l ) { 10791const std::string prefix = "blk." + std::to_string (l )+ "." ; 10792uint64_t off = 0 ; 10793for (auto it = mine .all ().lower_bound (prefix );it != mine .all ().end ()&& it -> first .rfind (prefix ,0 )== 0 ;++ it ) { 10794if (it -> second .data != nullptr || it -> second .native_data != nullptr )continue ;// (held here: the PLE tensors) 10795const core::WeightRef * s = first .find (it -> first ); 10796if (s == nullptr || (s -> data == nullptr && s -> native_data == nullptr ))continue ; 10797if (s -> hc_q8 != nullptr || s -> q8_scale != nullptr ) {why = "a first-stage weight in HC Q8 form" ;break ; } 10798uint64_t o = 0 ,b = 0 ,no = 0 ,nb = 0 ; 10799if (s -> data != nullptr ) { 10800o = off ; 10801b = s -> quantized () ?s -> codes_bytes + s -> scales_bytes + s -> offset_bytes :s -> bytes ; 10802off = (off + b + 255 )& ~(uint64_t )255 ; 10803 } 10804if (s -> native_data != nullptr ) { 10805no = off ; 10806nb = strata::kernels::native_mmvq_weight_bytes (s -> native_type , (int )s -> ne0 , (int )s -> ne1 ); 10807off = (off + nb + 255 )& ~(uint64_t )255 ; 10808 } 10809if (!each (l ,it -> first ,* s ,o ,b ,no ,nb )) {why = "no native-projection scratch on this GPU" ;break ; } 10810 } 10811const core::WeightRef * router = mine .find (prefix + "ffn_gate_inp.weight" ); 10812if (why .empty ()&& (router == nullptr || router -> data == nullptr )&& off == 0 ) 10813why = "the first stage does not hold its layers' weights" ; 10814need = std::max (need ,off ); 10815 } 10816return need ; 10817} 10818 10819uint64_t Prefill ::short_slot_bytes (const core::WeightTable & mine ,const core::WeightTable & first ,int64_t lo_end , 10820uint64_t d_bytes ,uint64_t u_bytes ) { 10821 std::string why ; 10822const uint64_t rows = short_rows (mine ,first ,lo_end ,why , [](auto && ...) {return true; }); 10823if (!why .empty ())return 0 ; 10824const uint64_t d_off = rows ,u_off = (d_off + d_bytes + 255 )& ~(uint64_t )255 ; 10825return u_off + u_bytes ; 10826} 10827 10828bool Prefill ::set_short_slots (void * slot0 ,void * slot1 ,uint64_t bytes , std::string & err ) { 10829cudaStream_t st = nullptr ; 10830cudaEvent_t ev [4 ]= {}; 10831bool ok = cudaStreamCreateWithFlags (& st ,cudaStreamNonBlocking )== cudaSuccess ; 10832for (int i = 0 ;ok && i < 4 ;++ i )ok = cudaEventCreateWithFlags (& ev [i ],cudaEventDisableTiming )== cudaSuccess ; 10833if (!ok ) { 10834 (void )cudaGetLastError (); 10835err = "prefill: the short read's weight stream" ; 10836return false; 10837 } 10838short_slot_ [0 ]= slot0 ; 10839short_slot_ [1 ]= slot1 ; 10840short_slot_n_ = bytes ; 10841short_st_ = st ; 10842for (int i = 0 ;i < 4 ;++ i )short_ev_ [i ]= ev [i ]; 10843return true; 10844} 10845 10846bool Prefill ::read_short (const int64_t * tokens ,int64_t n ,int64_t pos0 , core::SessionState * lo ,int64_t lo_end , 10847const Prefill * first , std::string & err ) { 10848err .clear (); 10849const auto decline = [& ](const char * why ) {err = std::string ("prefill: short read declined: " )+ why ;return false; }; 10850if (!impl_ || impl_ -> g == nullptr )return decline ("no prefill" ); 10851Impl & m = * impl_ ; 10852const core::ModelGeometry & g = * m .g ; 10853if (pos0 != 0 || n <=0 )return decline ("a continued prompt" ); 10854if (next_ != nullptr || stage_lb_ != lo_end || stage_le_ != g .n_layers ) 10855return decline ("not the last stage of a two-way split" ); 10856if (lo == nullptr || lo -> layer_lo != 0 || lo -> layer_hi != lo_end || n > lo -> max_cells )return decline ("the scratch session" ); 10857if (first == nullptr || !first -> impl_ || first -> next_ != this || first -> stage_lb_ != 0 || first -> stage_le_ != lo_end ) 10858return decline ("no first stage to take the weights from" ); 10859if (first -> next_run_ .valid ())return decline ("a layer split's chunk hand-off is in flight" ); 10860hand_in_ = nullptr ;// (stale: a chunk-major prompt's last hand-off, as lm_prepare_chain clears it) 10861hand_ev_ = nullptr ; 10862hand_pieces_ = 0 ; 10863const Impl & f = * first -> impl_ ; 10864if (!m .latent || !f .latent || f .lat_first_layer > 0 || !f .lat_d_dev || !f .lat_u_dev || 10865f .lat_d .d_bytes ()!= m .lat_d .d_bytes ()|| f .lat_d .u_bytes ()!= m .lat_d .u_bytes ()) 10866return decline ("the first stage's latent D/U tables" ); 10867if (g .n_qsa_layers ()> 0 && lo -> qsa_states [lo -> qsa_primary ()].kv_mode != 0 )return decline ("streamed K/V" ); 10868const core::OnDevice on_device (m .device ); 10869// the first stage's layers' rows this table lacks, laid out in one slot (256-byte aligned), then that layer's D and U 10870ShortWeights w ; 10871w .shadow = * m .wt ; 10872w .items .resize ((size_t )lo_end ); 10873void * q8_1 = nullptr ;// this GPU's native-projection activation scratch (one per table) 10874for (const auto & [name ,ref ] :m .wt -> all ()) 10875if (ref .native_q8_1 != nullptr ) {q8_1 = ref .native_q8_1 ;break ; } 10876 std::string rows_why ; 10877const uint64_t need = short_rows (* m .wt ,* f .wt ,lo_end ,rows_why , 10878 [& ](int64_t l ,const std::string & name ,const core::WeightRef & s ,uint64_t off ,uint64_t bytes ,uint64_t noff ,uint64_t nbytes ) { 10879ShortWeights ::Item item {w .shadow .find_mut (name ),s ,off ,bytes ,noff ,nbytes }; 10880item .dst -> native_q8_1 = q8_1 ; 10881w .items [(size_t )l ].push_back (item ); 10882return nbytes == 0 || q8_1 != nullptr ; 10883 }); 10884if (!rows_why .empty ())return decline (rows_why .c_str ()); 10885w .d_bytes = m .lat_d .d_bytes (); 10886w .u_bytes = m .lat_d .u_bytes (); 10887w .d_off = need ; 10888w .u_off = (w .d_off + w .d_bytes + 255 )& ~(uint64_t )255 ; 10889const uint64_t slot_bytes = w .u_off + w .u_bytes ; 10890w .src_d = f .lat_d_dev ; 10891w .src_u = f .lat_u_dev ; 10892w .src_dev = f .device ; 10893w .dev = m .device ; 10894if (short_slot_n_ < slot_bytes || short_st_ == nullptr )return decline ("no weight slots (set_short_slots)" ); 10895for (int s = 0 ;s < 2 ;++ s ) { 10896w .slot [s ]= (uint8_t * )short_slot_ [s ]; 10897w .ready [s ]= (cudaEvent_t )short_ev_ [s ]; 10898w .freed [s ]= (cudaEvent_t )short_ev_ [2 + s ]; 10899 } 10900w .st = (cudaStream_t )short_st_ ; 10901// the residency table holds the slots of whichever GPU's cache owns a layer: the first stage's layers have none here 10902 std::vector < int32_t > res ; 10903if (m .host_res != nullptr ) { 10904const size_t NE = (size_t )g .n_expert ; 10905res .assign (m .host_res ,m .host_res + (size_t )g .n_layers * NE ); 10906 std::fill (res .begin (),res .begin ()+ (size_t )lo_end * NE , (int32_t )-1 ); 10907 } 10908struct Restore { 10909Prefill * p ;int64_t lb ;const int32_t * res ;const core::WeightTable * wt ; 10910 ~Restore () { 10911p -> stage_lb_ = lb ;p -> short_lo_ = nullptr ;p -> short_end_ = 0 ;p -> short_w_ = nullptr ; 10912p -> lm_force_ = false;p -> lm_mid_ = false; 10913p -> impl_ -> host_res = res ; 10914p -> impl_ -> wt = wt ; 10915 } 10916 }restore {this ,stage_lb_ ,m .host_res ,m .wt }; 10917if (!res .empty ())m .host_res = res .data (); 10918m .wt = & w .shadow ; 10919short_w_ = & w ; 10920stage_lb_ = 0 ; 10921short_lo_ = lo ; 10922short_end_ = lo_end ; 10923lm_force_ = true; 10924 std::string why ; 10925if (lm_prepare_chain (n ,why ) <=0 )return decline (why .c_str ()); 10926Seg one ; 10927one .tokens = tokens ; 10928one .n = n ; 10929one .pos0 = 0 ; 10930const bool ok = lm_run (std::vector < Seg > {one },0 ,nullptr ,err ); 10931lm_release_chain (); 10932return ok ; 10933} 10934 10935bool Prefill ::drain_pipeline (std::string & err ) { 10936bool ok = true; 10937 10938if (next_run_ .valid ()) { 10939if (!next_run_ .get ()) { 10940err = next_err_ ; 10941ok = false; 10942 } 10943 } 10944 10945if (next_ != nullptr ) { 10946 std::string tail_err ; 10947if (!next_ -> drain_pipeline (tail_err )) { 10948if (ok )err = tail_err ; 10949ok = false; 10950 } 10951 } 10952 10953return ok ; 10954} 10955 10956bool Prefill ::reserve_uploads (int64_t T ) { 10957bool ok = true; 10958if (impl_ != nullptr && T > 0 ) { 10959Impl & m = * impl_ ; 10960const core::OnDevice on_device (m .device );// (the ring is the device's that is current at its first use) 10961// a text chunk's largest pageable uploads through the ring: the routing tables (and their ids down, T x K 10962// each); the PLE rows when they could not be pinned (T x N). A picture's rows are not covered. 10963size_t bytes = (size_t ) (T * K )* sizeof (int32_t ); 10964if (!m .ple_pageable [0 ].empty ()|| !m .ple_pageable [1 ].empty ()) 10965bytes = std::max (bytes , (size_t ) (T * N )* sizeof (float )); 10966ok = m .up_ring .reserve (bytes ); 10967 } 10968if (next_ != nullptr )ok = next_ -> reserve_uploads (T )&& ok ; 10969return ok ; 10970} 10971 10972bool Prefill ::run (const int64_t * tokens ,int64_t n ,int64_t pos0 , std::string & err ) { 10973#if defined(STRATA_USE_HIP )|| defined(STRATA_HIP_GFX906 ) 10974 (void ) strata::kernels::qsa_two_pass_on ();// HIP: a set STRATA_SELECT_TWO_PASS says once it is not used 10975#endif 10976#if defined(STRATA_GPU_METAL ) 10977static strata::kernels::two_pass::RequestStatus tp_status (std::getenv ("STRATA_SELECT_TWO_PASS" )); 10978 (void )tp_status .on ("Metal" ); 10979 { 10980const auto t0 = std::chrono::steady_clock::now (); 10981// DFlash2: the window writes the taps of the prompt rows at positions >= tap_first_ and hands them to on_taps after each chunk 10982const bool taps = !tap_layers_ .empty ()&& on_taps ; 10983if (taps && !strata::metal_engine::prompt_taps (tap_layers_ ,tap_first_ ,on_taps ,err ))return false; 10984const bool ok = strata::metal_engine::prompt_run (tokens ,n ,pos0 ,embd_rows ,on_chunk ,err ); 10985if (taps ) { 10986 std::string off_err ; 10987 strata::metal_engine::prompt_taps (tap_layers_ ,0 , {},off_err );// no callback after the prompt 10988 } 10989stats_ .tokens += n ; 10990stats_ .chunks += 1 ; 10991stats_ .ms_total += std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t0 ).count (); 10992return ok ; 10993 } 10994#endif 10995#if defined(STRATA_USE_HIP )|| defined(STRATA_HIP_GFX906 ) 10996constexpr bool lm_hip = true; 10997#else 10998constexpr bool lm_hip = false; 10999#endif 11000// layer-major prefill: STRATA_PREFILL_LAYER_MAJOR=1 / 0 win; unset, it is off everywhere (sm120_series.hpp prefill_layer_major_default: a layer split 11001// reads 32K prompts 37-55% sooner chunk-major, owner's yes 2026-11-02; the single-card small-cache rule sets the variable itself) 11002if (hand_in_ == nullptr && impl_ && 11003 strata::prefill_layer_major_resolve (lm_env_text (),lm_hip ,stage_count (), strata::qwen_defaults_026 ())) { 11004const bool by_default = !lm_env_explicit (); 11005for (Prefill * p = this ;p != nullptr ;p = p -> next_ )p -> lm_by_default_ = by_default ; 11006 std::string why ; 11007if (by_default ) { 11008static bool noted = false; 11009if (!noted ) { 11010noted = true; 11011 std::fprintf (stderr ,"strata prefill: layer-major prefill is on for this layer split (each layer's experts are read once per " 11012"super-chunk of up to %lld tokens, not once per chunk; STRATA_PREFILL_LAYER_MAJOR=0 or STRATA_DEFAULTS=026 " 11013"turns it off)\n" , (long long )kLmDefaultOnTokens ); 11014 } 11015 } 11016if (lm_prepare_chain (n ,why )> 0 ) { 11017#if !defined(STRATA_USE_HIP )&& !defined(STRATA_HIP_GFX906 ) 11018// STRATA_SELECT_TWO_PASS is in run_impl's selection only, not in this walk: say so once 11019static strata::kernels::two_pass::RequestStatus tp_status (std::getenv ("STRATA_SELECT_TWO_PASS" )); 11020 (void )tp_status .on ("the layer-major prompt path" ); 11021#endif 11022bool ok = run_layer_major (tokens ,n ,pos0 ,err ); 11023 std::string drain_err ;// a layer split: the later stages' last super-chunk 11024if (!drain_pipeline (drain_err )&& ok ) { 11025ok = false; 11026err = drain_err ; 11027 } 11028for (Prefill * p = this ;p != nullptr ;p = p -> next_ )p -> lm_mid_ = false; 11029lm_release_chain (); 11030return ok ; 11031 } 11032static std::string said ;// once per reason (a short prompt is the common one; not worth a line when nobody asked for the walk) 11033if (why != said && !(by_default && why == "a short prompt" )) { 11034said = why ; 11035 std::fprintf (stderr ,"strata prefill: layer-major off for this prompt: %s\n" ,why .c_str ()); 11036 } 11037 } 11038const bool body_ok = run_impl (tokens ,n ,pos0 ,err ); 11039 11040 std::string drain_err ; 11041const bool drain_ok = drain_pipeline (drain_err ); 11042 11043if (!body_ok )return false; 11044if (!drain_ok ) { 11045err = drain_err ; 11046return false; 11047 } 11048// STRATA_MMQ_DIRECT=1 with STRATA_MMQ_DIRECT_LOG=1 (a check, not a default): each stage's totals so far - how many 11049// resident experts its prompt MMQ read in their slots, of all its resident and streamed ones 11050if (mmq::direct_mode ()== 1 ) { 11051static const bool log = [] {const char * v = std::getenv ("STRATA_MMQ_DIRECT_LOG" );return v && std::atoi (v )!= 0 ; }(); 11052for (const Prefill * p = this ;log && p != nullptr ;p = p -> next_ ) 11053 std::fprintf (stderr ,"strata prefill: layers %lld..%lld: %lld of %lld resident experts read in place, %lld " 11054"streamed (STRATA_MMQ_DIRECT, totals)\n" , (long long )p -> stage_lb_ , 11055 (long long )p -> stage_le_ , (long long )p -> stats_ .experts_direct , 11056 (long long )p -> stats_ .experts_resident , (long long )p -> stats_ .experts_streamed ); 11057 } 11058return true; 11059} 11060 11061}// namespace strata::prefill 11062