okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
a8a51b280
main
1// src/prefill/prefill.cpp - see include/strata/prefill/prefill.hpp. 2#define DPCT_PROFILING_ENABLED 3#include <sycl/sycl.hpp> 4#include <dpct/dpct.hpp> 5#include "strata/sycl_queue.hpp" 6#include "strata/kprof.hpp" 7#include "strata/copy_queue.hpp" 8#include "strata/prefill/xmx_moe.hpp" 9#include "strata/prefill/esimd_moe.hpp" 10#include "strata/prefill_copy_queue.hpp" 11#include "strata/prefill/prefill.hpp" 12#include "strata/kernels/dflash2.hpp" 13#include "strata/workload_trace.hpp" 14#include "strata/core/gguf_expert_source.hpp" 15#include "../../../src/prefill/mmq_resident_sort.hpp" 16#include "../../../src/prefill/wmma_gemm.h" 17#include "strata/core/mtp.hpp" 18#include "strata/core/progress.hpp" 19#include "strata/core/on_device.hpp" 20 21#include "strata/core/layout.hpp" 22#include "strata/kernels/cpu/expert.hpp" 23#include "strata/kernels/native_qsa.hpp" 24#include "strata/kernels/native_qsa_indexer.hpp" 25#include "strata/core/geometry.hpp" 26#include "strata/kernels/ngram.hpp" 27#include "strata/kernels/ple.hpp" 28#include "strata/kernels/native_ple_postops.hpp" 29#include "strata/kernels/iq_kernels.hpp" 30#include "strata/kernels/iq_dequant_expert.hpp" 31#include "strata/kernels/cpu/expert_layout.hpp" 32#include "strata/kernels/cpu/hadamard.hpp" 33#include "strata/kernels/qsa.hpp" 34#include "strata/kernels/kv_stream.hpp" 35#include "strata/kernels/cvec.hpp" 36#include "strata/kernels/kv_q4.hpp" 37#include "strata/core/layer.hpp" 38#include "strata/core/native_head.hpp" 39#include "strata/kernels/verify_kernels.hpp" 40#include "strata/kernels/qsa_decode_attn.hpp" 41#include "strata/kernels/qsa_prompt_attn.hpp" 42#ifdef STRATA_SYCL_TLA_ATTN 43#include "strata/kernels/qsa_prompt_attn_tla.hpp" 44#endif 45#include "strata/kernels/qsa_select.hpp" 46#include "strata/kernels/qsa_two_pass_status.hpp" 47#include "strata/prefill/gemm.hpp" 48#include "strata/prefill/moe_fused.hpp" 49#include "strata/prefill/moe_fused_iq.hpp" 50#include "strata/prefill/moe_mmq.hpp" 51#include "strata/core/peer_experts.hpp" 52#include "strata/prefill/kernels.hpp" 53#include <oneapi/mkl.hpp> // SYCL port: the QSA block scores as GEMM tiles 54namespace strata::kernels {// SYCL port, kept out of the shared headers: qsa_select.dp.cpp, qsa_decode_attn.dp.cpp 55void qsa_block_scores_reduce (const float * S ,int64_t ld ,int64_t b0 ,int64_t nb ,const float * dead ,const float * q_idx , 56const int32_t * steps ,int64_t nq ,int64_t max_blocks ,float * scores ,void * stream ); 57void qsa_prompt_attn_percell (const float * q ,const QsaAttnPools & pools ,const int32_t * ids ,const int32_t * steps , 58int64_t cap ,const QsaShapes & s ,float * scratch ,float * attn ,int64_t n_q ,void * stream ); 59} 60 61#include <algorithm> 62#include <set> 63#include <map> 64#include <cmath> 65#include <chrono> 66#include <stdexcept> 67#include <sys/stat.h> 68#include <tuple> 69#include "strata/prefill/f16_expert_pair.hpp" 70#include <chrono> 71#include <cmath> 72#include <cstdio> 73#include <atomic> 74#include <condition_variable> 75#include <cstring> 76#include <future> 77#include <memory> 78#include <mutex> 79#include <thread> 80#include <unordered_map> 81#include <vector> 82 83#ifndef STRATA_PREFILL_MMQ 84// A build without the llama.cpp sources (no STRATA_NATIVE_EXPERTS): no MMQ, the FP16 expert path everywhere. 85namespace strata::prefill::mmq { 86bool built () {return false; } 87bool supported (int ) {return false; } 88bool fits (int ,int64_t ) {return false; } 89size_t matrix_bytes (int ,int64_t ,int64_t ) {return 0 ; } 90size_t q8_bytes (int64_t ,int64_t ) {return 0 ; } 91void quantize (const float * ,const int32_t * ,void * ,int ,int64_t ,int64_t ,int64_t ,void * ,float * ) {} 92bool fp4_activations (int ) {return false; } 93Context ::Context () {} 94Context ::~Context () {} 95void Context ::run (const Product & ,void * ) {} 96void gather_native (const void * ,const void * ,size_t ,const void * ,size_t ,void * ,void * ,void * ,const void * ,void * ,size_t ) {} 97bool gather_native_group (const GatherGroup & ,size_t ,size_t ,size_t ,size_t ,void * ,size_t ,void * ,size_t ,void * ,size_t , 98void * ,size_t ) {return false; } 99void gather_strata_q2 (const uint8_t * ,void * ,void * ,void * ) {} 100void swiglu (const float * ,float * ,int64_t ,int64_t ,bool ,void * ) {} 101void iota (int32_t * ,int64_t ,void * ) {} 102}// namespace strata::prefill::mmq 103#endif 104#ifndef STRATA_PREFILL_FUSED 105// #136: the fused int8 experts are CUDA-only (HIP and builds without MMQ keep the MMQ / FP16 paths) 106namespace strata::prefill::fused { 107bool built () {return false; } 108bool available () {return false; } 109bool enabled () {return false; } 110bool requested () {return false; } 111size_t act_bytes (int64_t ,int64_t ) {return 0 ; } 112size_t group_bytes (int64_t ,int ) {return 0 ; } 113void quantize_act (const float * ,int64_t ,int64_t ,void * ,void * ) {} 114void group (const int32_t * ,int64_t ,int ,int ,void * ,int32_t * ,int32_t * ,void * ) {} 115void experts (const Batch & ,int ,int64_t ,const void * ,const void * ,const int32_t * ,void * ,float * ,void * ) {} 116bool native_supported (int ,int ) {return false; } 117void quantize_act_native (const float * ,int64_t ,int64_t ,void * ,void * ) {} 118void experts_native (const Batch & ,const NativeGeom & ,int ,int64_t ,const void * ,const void * ,const int32_t * ,void * , 119float * ,void * ) {} 120}// namespace strata::prefill::fused 121#endif 122 123namespace strata::kernels {void iq_dequant_f16_plain_launch (int ,const void * ,int64_t ,uint16_t * ,void * ); } 124 125namespace strata::prefill { 126namespace { 127 128using Clock = std::chrono::steady_clock ; 129 130// 0.1.48, A750 deadlock: SYCL has no cudaHostRegister, so the expert arena is ordinary pageable memory even where the engine 131// calls it "pinned" (pinned.dp.cpp registers nothing). A DMA straight from it, `copy->memcpy(stage, arena_ptr, 2.3 MB)`, makes the 132// Level Zero driver copy through its own staging buffers on the calling thread, and on some prompts that wait never ends (the 133// thread spins in sched_yield inside libze_intel_gpu with the GPU idle; tools: /data/148-intel notes). Only a USM host 134// allocation (the --stream-experts pinned mirror, the B70's) is DMA'd directly; every other expert is copied into one of the 135// stager's pinned buffers by its threads first, the path unpinned experts already take. STRATA_PF_DMA_PAGEABLE=1 restores the 136// direct copy from pageable memory. 137inline bool dma_direct (const core::ExpertSource * src ,int64_t layer ,int64_t expert ,const void * blob ) { 138if (!src -> pinned (layer ,expert ))return false; 139static const bool pageable_ok = [] {const char * v = std::getenv ("STRATA_PF_DMA_PAGEABLE" );return v && v [0 ]== '1' ; }(); 140if (pageable_ok )return true; 141if (blob == nullptr )return false; 142// the answer per 2 MiB bucket (a query costs ~2 us, 10k+ experts a chunk): "host USM" only when both ends of the bucket are, so a bucket 143// that straddles two allocations is never taken for USM 144static thread_local std::unordered_map < uintptr_t ,bool > usm_bucket ; 145const uintptr_t key = (uintptr_t )blob >>21 ; 146const auto it = usm_bucket .find (key ); 147if (it != usm_bucket .end ())return it -> second ; 148const auto ctx = dpct::get_in_order_queue ().get_context (); 149const bool usm = sycl::get_pointer_type ((const void * ) (key <<21 ),ctx )== sycl::usm::alloc::host && 150 sycl::get_pointer_type ((const void * ) (((key + 1 ) <<21 )- 1 ),ctx )== sycl::usm::alloc::host && 151 sycl::get_pointer_type (blob ,ctx )== sycl::usm::alloc::host ; 152usm_bucket .emplace (key ,usm ); 153return usm ; 154} 155constexpr float EPS = 1e-6f ; 156// the shape the engine is compiled for (include/strata/core/geometry.hpp; -DSTRATA_GEOMETRY picks it) 157constexpr 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 ; 158constexpr int64_t C = strata::core::kCompiledGeometry .ssm_conv_channels ,ZV = strata::core::kCompiledGeometry .ssm_value_dim ,HV = strata::core::kCompiledGeometry .ssm_v_heads ; 159// widths the buffers and kernel arguments below are written in (int, as the literals they replace were) 160constexpr int kEmbd = (int ) strata::core::kCompiledGeometry .n_embd ,kFF = (int ) strata::core::kCompiledGeometry .n_ff ,kFF2 = 2 * kFF ; 161constexpr int kNHead = (int ) strata::core::kCompiledGeometry .n_head ,kNKv = (int ) strata::core::kCompiledGeometry .n_head_kv ,kHeadDim = (int ) strata::core::kCompiledGeometry .head_dim ; 162constexpr int kQW = kNHead * kHeadDim ,kQFull = 2 * kQW ,kKvW = kNKv * kHeadDim ; 163static_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" ); 164constexpr int kIdxQHeads = (int ) strata::core::kCompiledGeometry .idx_q_heads ,kIdxK = (int ) strata::core::kCompiledGeometry .idx_key_dim ,kIdxQW = kIdxQHeads * kIdxK ; 165 166// STRATA_PF_HASH_FILE=<path> (debug, off by default): for the first GDN layer of every prompt chunk the host waits for 167// the queue after each stage and writes one line per row "chunk stage row fnv" (the layer input, the projections, the 168// gates, the conv output, the recurrence output) plus the layer's recurrent state, so two runs show which stage of 169// the prefill first differs (CLEAN-6.0). 170inline std::FILE * pf_hash_file () { 171static std::FILE * f = [] { 172const char * p = std::getenv ("STRATA_PF_HASH_FILE" ); 173return p != nullptr && p [0 ]!= 0 ? std::fopen (p ,"w" ) :nullptr ; 174 }(); 175return f ; 176} 177inline uint64_t pf_hash_fnv (const void * p ,size_t bytes ) { 178uint64_t h = 1469598103934665603ull ; 179const auto * b = static_cast < const uint8_t *> (p ); 180for (size_t i = 0 ;i < bytes ;++ i )h = (h ^b [i ])* 1099511628211ull ; 181return h ; 182} 183// plan v0.3 P6: staging holds the largest blob of the pack (a native pack's blobs differ per layer) 184inline int64_t MAXBLOB () {return (int64_t ) strata::kernels::cpu::expert_layout ().max_blob ; } 185constexpr int STAGE = 8 ;// host->device expert staging ring (chunks below stream_all_min()) 186constexpr int kSplitHelpRing = 48 ;// layer split help: the helper stage's ring slots it streams through (at most) 187// Step 3: from this chunk size on, every non-resident expert of every layer streams in a fixed order through a 188// ring_slots()-slot ring (nearly all 512 are routed at such a chunk), so the copy engine keeps working through the 189// attention halves instead of waiting for each layer's routing. 190// #828: STRATA_TEST_PAGEABLE=1 makes every pinned host allocation with a pageable fallback in Prefill::init fail, so the 191// fallbacks (what an LXC container's memlock limit forces) run on a PC that can pin - for ASan / MALLOC_CHECK_=3 runs. 192inline bool force_pageable () { 193static const bool v = [] {const char * e = std::getenv ("STRATA_TEST_PAGEABLE" );return e != nullptr && e [0 ]== '1' ; }(); 194return v ; 195} 196constexpr int RING_MAX = 1024 ;// the arrays; the ring itself is ring_slots(), at most ring_cap() 197// The chunk size from which every expert streams: 1024 since 0.1.30 (was 2048). Measured on the 5070, Q2_0 / IQ2_XS, 198// fixed cache: 1,500-token prompts 621 -> 785 / 612 -> 735 tok/s, 2,000 727 -> 934 / 712 -> 892, 4,000 (its last 199// chunk) 779 -> 912 / 766 -> 844, the same output. Below ~1,000 tokens the output changed on Q2_0 (a smaller chunk 200// takes other kernels), so 1024 is the floor. STRATA_PREFILL_STREAM_MIN overrides (A/B). 201inline int64_t stream_all_min () { 202static const int64_t v = [] {const char * e = std::getenv ("STRATA_PREFILL_STREAM_MIN" );return e ? (int64_t ) std::atoll (e ) : (int64_t )1024 ; }(); 203return v ; 204} 205double g_pinned_share = 1.0 ; 206// SYCL port: the share of (layer, expert) pairs the VRAM cache does not hold (set_nonresident_share, from generate.cpp) 207double g_nonres_share = 0.0 ; 208// The streamed ring: 384 slots when (nearly) every streamed expert is DMA'd from pinned RAM - measured on Q2_0, 209// 8192-token chunks: 96 slots 1153 tok/s, 384 1294 (the next layer's experts arrive during its attention half) - 210// and 96 when a large share goes through host copies (IQ3_S on 64 GB, a third unpinned: 96 slots 1216, 256 1070 - 211// the host copies are the limit and the bigger ring only takes cache slots). STRATA_PREFILL_RING overrides. 212// 213// Those are slots on the pack they were measured on, and a slot is one WHOLE expert blob - a Q2_0 blob is 214// 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 215// 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 216// that card at a 1,024-token chunk when its own buffers would have fitted 6,144. Measured on the 4-way rig, one 217// env var and nothing else: chunk 1,024 -> 6,144, prefill 87 -> 402 tok/s. So the budget is kept in BYTES and the 218// slot count is derived from the pack (`ring_budget_slots`); Q2_0 still resolves to exactly 1024 (fused) and 384, 219// so the pack all of this was tuned on does not move. 220int g_ring_override = 0 ;// #340: set by a layer split (Prefill::set_ring_override); 0 = the rule below 221// #583 (0.1.39b): the auto chunk scan's byte-budget ring (Prefill::set_ring_budget), for requests whose chunk is above 222// 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: 223// on one chunk the smaller ring only slowed it (RTX 5070, 4K prompts: Coder -15%, IQ3_S -5%, IQ3_XXS -2%). 224int g_ring_budget = 0 ; 225int64_t g_ring_small_max = 0 ; 226// #136: the fused experts (STRATA_PF_FUSED=1) launch on a batch of a layer's streamed experts at once, so the ring 227// 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 228// first batch frees. Measured on the 5070, Q2_0, the 4K / 32K code-agent prompts (one run each): fused at 384 slots 229// +5% / +3% over MMQ, at 512 +19-22% / +11-12% (MMQ itself at 512: -2% / -1%). P3: with the fused path's smaller 230// buffers (moe_bufs) 1024 slots - two layers' experts - fit too; 2 pairs each, prompt tok/s at 512 / 1024 slots: 4K 231// 1,512 / 1,605, 32K 2,485 / 2,660 (both chunk 8192), 128K with KV streaming 2,346 / 2,392 (the chunk falls from 232// 8192 to 6144, but more experts stay resident). A native pack likewise when the native kernels (moe_fused_iq.hpp) 233// take any of its layers: IQ2_XS, 4K / 32K, their first version at 384 slots -3% / -6% against MMQ, at 512 +8% / 0%. 234inline bool fused_ring () { 235if (!fused::enabled ())return false; 236if (core::peer_portable ())return false;// multi-GPU: --peer-device keeps the MMQ path and its buffer sizes 237const strata::kernels::cpu::ExpertLayout & lay = strata::kernels::cpu::expert_layout (); 238if (!lay .native )return true; 239// EVERY layer: fused_layout() shrinks the MoE buffers to the fused path's needs, so a layer the native kernels do 240// not cover (Unsloth UD-IQ4_XS's Q8_0 down projections) would run MMQ in them at the full chunk and overflow them 241// (garbage, an illegal memory access or a hung prompt on gfx1151). A pack with such a layer keeps MMQ's buffers; 242// its covered layers still take the fused kernels. 243static const bool all = [& lay ] { 244for (const auto & f :lay .fmt ) 245if (!fused::native_supported (f .gu_type ,f .d_type ))return false; 246return !lay .fmt .empty (); 247 }(); 248return all ; 249} 250// the largest ring: 512 slots; 1024 with the Q2_0 pack's fused experts (P3's smaller buffers, measured there) - the 251// native packs' fused layers were measured at 512 252inline int ring_cap () {return fused_ring ()&& !strata::kernels::cpu::expert_layout ().native ?RING_MAX :512 ; } 253// The ring's budget in bytes: the measured slot counts above, at the blob size they were measured with. It is 254// bytes and not slots because a slot is one whole blob and the blob is the pack's - see the note above. 255inline constexpr uint64_t Q2_0_BLOB = 1382400ull ;// the blob of the pack the ring was tuned on 256inline uint64_t ring_bytes () { 257const uint64_t slots = fused_ring () ?1024ull :384ull ;// #136: a fused ring holds two layers' experts 258return (g_pinned_share >=0.9 ?slots :slots /4 )* Q2_0_BLOB ; 259} 260// ...and what that buys on THIS pack, never past ring_cap(): the slot count `init` lays out, and what the auto 261// chunk scan treats as a full ring. A pack whose blobs are larger than Q2_0's gets fewer slots for the same 262// bytes, which is the point - the ring competes with the expert cache for the same VRAM. 263// 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 264// prompt path's loan on a native pack (fewer ring slots, the rest kept as cache slots, a larger auto chunk), so a long 265// prompt's experts are read through a different mix of resident and streamed groups and its bits differ from 0.1.39's 266// (RTX 5070, IQ3_XXS, 32K prompt: +14% to +26%; teacher-forced against the FP16 prompt path in the same band). 267inline bool ring_bytes_on () { 268static const bool on = [] {const char * v = std::getenv ("STRATA_RING_BYTES" );return v == nullptr || v [0 ]!= '0' ; }(); 269return on ; 270} 271inline int ring_budget_slots () { 272const int64_t per = MAXBLOB (); 273const int64_t n = per > 0 ? (int64_t ) (ring_bytes () / (uint64_t )per ) :0 ; 274const int cap = ring_cap (); 275return (int ) (n <=0 ?0 : (n > cap ?cap :n )); 276} 277inline int ring_slots (size_t T ) { 278const char * v = std::getenv ("STRATA_PREFILL_RING" ); 279#if defined(STRATA_USE_HIP ) 280// S6: with the opt-in RDNA4 matrix-core attention (STRATA_HIP_WMMA=1) a 96-slot ring: measured with it, 9070 XT 281// 4K prompts 718 -> 1,211 tok/s (16K 1,949 -> 2,032), R9700 4K 2,426 -> 2,483 (16K the same) 282static const bool wmma = [] { 283const char * e = std::getenv ("STRATA_HIP_WMMA" ); 284return e != nullptr && e [0 ]== '1' ; 285 }(); 286if (!v && g_ring_override <=0 && wmma )return (int64_t )T >=stream_all_min () ?96 :STAGE ; 287#endif 288// the byte budget as this pack's slots: 1024 fused / 384 not on Q2_0, fewer on a pack with bigger blobs. The 289// unpinned arm stays a slot count (96): it was measured where the host copies are the limit, and there the ring 290// is not what is competing for VRAM. 291// 0.1.39's ring (1024 fused / 384 pinned, 96 when a large share goes through host copies), and the #583 byte 292// budget the auto scan chose for chunks past the size 0.1.39's rule would have picked (set_ring_budget) 293const int pinned_ring = g_pinned_share >=0.9 ? (fused_ring () ?1024 :384 ) :96 ; 294const bool budget = ring_bytes_on ()&& g_ring_budget > 0 && (int64_t )T > g_ring_small_max ; 295const int r = v ? std::atoi (v ) :g_ring_override > 0 ?g_ring_override :budget ?g_ring_budget :pinned_ring ; 296if (v && r == STAGE )return STAGE ;// Explicit opt-in to routed-only staging, including large chunks. 297// SYCL port: the stream-all walk (every non-resident expert of every layer, copied ahead across layers) hung on the 298// B70 in its first large chunk until 2026-10-02 - the stager's and the PLE upload's host waits on queue events, 299// which the Level Zero v2 adapter did not survive (Stager::issued_one, ple_done_seq). It runs since, and reads a 300// 40K prompt 4.8% faster than routed-only staging (1,159 vs 1,106 tok/s, same output): the default again. 301// STRATA_PREFILL_STREAM_ALL=0 keeps routed-only staging, =1 forces the walk. 302// It copies EVERY non-resident expert of a layer, routed or not: with a big host tier (the IQ2_XS: a quarter of the 303// experts in the pinned mirror) that is several times the routed ones, and a 2,184-token prompt fell from ~570 to 304// 254 tok/s. So by default only while the VRAM holds more than 90% of the pairs (the Coder, and its lent slots). 305static const int stream_all_env = [] {const char * e = std::getenv ("STRATA_PREFILL_STREAM_ALL" );return e ? (e [0 ]== '1' ?1 :0 ) :-1 ; }(); 306const bool stream_all_ok = stream_all_env == 1 || (stream_all_env == -1 && g_nonres_share < 0.10 ); 307if (!stream_all_ok )return STAGE ; 308const int big = r < 16 ?16 :r > ring_cap () ?ring_cap () :r ; 309return (int64_t )T >=stream_all_min () ?big :STAGE ; 310} 311// A770 port: STRATA_PF_XMX=2 holds up to a group of staged experts until its launch, so routed-only staging needs 312// that many more slots for the lookahead to keep copying (the slots are only reused once the group's event is in) 313// 151-b70: the fused int8 DPAS expert products (prefill/esimd_moe.dp.cpp, Battlemage). Unset STRATA_PREFILL_MMQ (alias STRATA_PF_I8) is 314// auto on a Battlemage GPU (bmg-g21 / bmg-g31 by architecture id) whose kernels are in the binary, the FP16 chain on every other GPU 315// (Alchemist included); =0 forces the FP16 chain, =1 the int8 chain everywhere it applies (IQ3_S / IQ3_XXS / IQ2_S gate/up with IQ4_NL / 316// Q2_0 down, the 640 x 2560 expert), =auto the per-group choice from the crossover measured on this GPU. The activations are quantized, 317// so the bits differ from the FP16 path (docs/INTEL_INT8_EXPERTS.md: KL 0.0002 nats, top-1 99.7%). 318static_assert(strata::kernels::kXmxGroupMax <= strata::prefill::i8::kMaxGroup ,"the int8 path holds the grouped XMX path's experts: its Layout must be at least as big" ); 319inline const char * i8_env () { 320const char * e = std::getenv ("STRATA_PREFILL_MMQ" ); 321if (e == nullptr || e [0 ]== 0 )e = std::getenv ("STRATA_PF_I8" ); 322return (e != nullptr && e [0 ]!= 0 ) ?e :nullptr ; 323} 324std::atomic < bool > g_i8_failed {false};// an int8 launch threw: the FP16 chain for the rest of the process 325// The chain this queue's prompt experts take: 0 FP16, 1 int8, 2 auto. 326inline int i8_mode (void * cs ) { 327if (g_i8_failed .load (std::memory_order_relaxed ))return 0 ; 328const char * e = i8_env (); 329if (e != nullptr )return strata::prefill::i8::choose_mode (e , false, false); 330return strata::prefill::i8::choose_mode (nullptr , strata::prefill::i8::battlemage (cs ), strata::prefill::i8::available (cs )); 331} 332// ring sizing happens before any queue is at hand: room for the int8 groups whenever the choice could be on 333inline int stage_slots () { 334const char * e = i8_env (); 335const bool i8 = e != nullptr ? strata::prefill::i8::choose_mode (e , false, false)!= 0 : strata::prefill::i8::any_battlemage (); 336return (strata::prefill::xmx::mode ()== 2 || i8 ) ?STAGE + strata::prefill::xmx::kMaxGroup :STAGE ; 337} 338constexpr int DQ = 2 ;// dequantized-expert ring (FP16 gate/up + down) 339// A770 port: STRATA_PF_XMX=1 dequantizes a whole group of experts, then one grouped XMX launch per product 340inline int dq_slots () {return strata::prefill::xmx::mode ()== 1 ? strata::prefill::xmx::kMaxGroup :DQ ; } 341// The BF16-weight projections (hyper-connection, SSM alpha/beta, indexer, router, shared gate, PLE key/value) take 342// BF16 activations here and FP32 ones in decode. STRATA_PREFILL_BF16X2=1 adds each activation's BF16 remainder as a 343// second GEMM (Y = W.hi + W.lo, ~16 mantissa bits): a router that picks its top 10 from the same x decode would. 344// 2 = all but the hyper-connection's; 1 = the hyper-connection's too (its activations are 10240 wide and its up 345// projection writes as much: slower); 0 (the default: opt-in, it changes the prompt path's numbers) = off. 346// `f16_io`: the stage's FP16 prompt path (Prefill::init decides it once per stage, on the stage's own device): FP16 347// activations carry 11 mantissa bits, so the BF16 low part does not apply there. 348inline int bf16x2_mode (bool f16_io ) { 349static const int v = [] { 350const char * e = std::getenv ("STRATA_PREFILL_BF16X2" ); 351return e != nullptr ? std::atoi (e ) :0 ; 352 }(); 353return f16_io ?0 :v ; 354} 355inline bool bf16x2 (bool f16_io ) {return bf16x2_mode (f16_io )!= 0 ; } 356// S23 (opt-in STRATA_HC_UPMIX=1): the hyper-connection read's up projection and gr_mix_r as one kernel (gr_upmix, gfx11); 357// STRATA_HC_UPMIX_CHECK=N also runs the default pair on the first N reads and reports the difference of `mixed` 358static int64_t pf_switch_min_t () {// S23: STRATA_PF_SWITCH_MIN_T=N - the rounding-level prompt switches only on chunks of 359// N or more tokens (shorter prompts keep the default numerics, and their outputs; the switches pay on long ones) 360static const int64_t v = [] {const char * e = std::getenv ("STRATA_PF_SWITCH_MIN_T" );return e ? (int64_t ) std::atoll (e ) : (int64_t )0 ; }(); 361return v ; 362} 363inline bool hc_upmix () { 364static const bool v = [] {const char * e = std::getenv ("STRATA_HC_UPMIX" );return e != nullptr && e [0 ]== '1' ; }(); 365return v ; 366} 367inline bool bf16x2_hc (bool f16_io ) {return bf16x2_mode (f16_io )== 1 ; } 368// S23 (opt-in STRATA_CVEC_FUSE=1): a steered layer's FFN write + control vector + the next half's norm in one pass 369// over R (gr_write_cvec_norm_rs; bitwise the gr_write + cvec_apply + gr_norm_rs it replaces) 370// S23 (opt-in STRATA_PF_HCDOWN=1, on chunks of STRATA_PF_SWITCH_MIN_T+ tokens): the hyper-connection read's down and 371// inject projections as one WMMA GEMM over xn16 (strata_pf_hcdown_bf16), xn16 written with token stride 372// 10240 + 64. Rounding-level (another k order than hipBLASLt): quality-gated. 373inline bool pf_hcdown () { 374static const bool v = [] {const char * e = std::getenv ("STRATA_PF_HCDOWN" );return e && e [0 ]== '1' ; }(); 375return v ; 376} 377constexpr int64_t XN_PAD = 64 ; 378// 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 379// hipBLASLt's own k order (bitwise: strata_pf_hcdown_exact_bf16), xn16 written with token stride 10240 + 64 (the inject 380// projection stays on hipBLASLt, reading that stride) 381inline bool hcd_exact () { 382static const bool v = [] {const char * e = std::getenv ("STRATA_HCD_EXACT" );return e && e [0 ]== '1' ; }(); 383return v ; 384} 385inline bool hc_pad () {return pf_hcdown ()|| hcd_exact (); } 386inline bool cvec_fuse () { 387static const bool v = [] {const char * e = std::getenv ("STRATA_CVEC_FUSE" );return e && e [0 ]== '1' ; }(); 388return v ; 389} 390// S23 (opt-in STRATA_PF_PAD=1 with STRATA_PF_GEMM=1): the FP16 activations of the two K 6144 projections (ssm_out's 391// 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 392// 4 KB-multiple stride; Gemm::native pads the weight the same way). Same bits. 393inline bool pf_pad () { 394static const bool v = [] { 395const char * p = std::getenv ("STRATA_PF_PAD" );const char * g = std::getenv ("STRATA_PF_GEMM" ); 396return p && p [0 ]== '1' && g && g [0 ]== '1' ; 397 }(); 398return v ; 399} 400constexpr int64_t ZV_PAD = 64 ; 401 402// F-1: STRATA_GR_UNFUSED=1 keeps the FP32 copy of the normalized rows (gr_norm + gr_mix), the A/B arm 403inline bool gr_unfused () { 404static const bool v = [] {const char * e = std::getenv ("STRATA_GR_UNFUSED" );return e && e [0 ]== '1' ; }(); 405return v ; 406} 407 408double ms_since (Clock ::time_point t ) {return std::chrono::duration < double , std::milli > (Clock ::now ()- t ).count (); } 409 410// Either cudaMalloc (owned, freed with the object) or a bump allocation from a borrowed region; with no base and 411// no region it only counts, which is how `bytes_needed` sizes the region. 412struct Alloc { 413uint8_t * base = nullptr ; 414uint64_t cap = 0 ,used = 0 ; 415uint64_t failed_bytes = 0 ;///< the take that could not be allocated; the failure message names it 416uint64_t granule = 0 ;///< count_only: each take rounds up to this (cudaMalloc's 2 MiB pages: owned buffers) 417bool count_only = false; 418 std::vector < void *>* owned = nullptr ; 419template < typename T > T * take (size_t n ,bool & ok )try { 420uint64_t bytes = ((uint64_t )n * sizeof (T )+ 256 + 255 )& ~255ull ; 421if (count_only ) { 422if (granule > 0 )bytes = (bytes + granule - 1 ) /granule * granule ; 423used += bytes ; 424return nullptr ; 425 } 426if (base != nullptr ) { 427if (used + bytes > cap ) {ok = false;failed_bytes = bytes ;return nullptr ; } 428T * p = (T * ) (base + used ); 429used += bytes ; 430return p ; 431 } 432void * p = nullptr ; 433if (DPCT_CHECK_ERROR (p = (void * )strata::malloc_device_guarded ( 434bytes , dpct::get_in_order_queue ()))!= 0 ) { 435ok = false;failed_bytes = bytes ;return nullptr ; 436 } 437owned -> push_back (p ); 438used += bytes ; 439return (T * )p ; 440 } 441catch (sycl::exception const & exc ) { 442 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 443 <<", line:" <<__LINE__ << std::endl ; 444 std::exit (1 ); 445 } 446}; 447 448}// namespace 449 450// Step 4 of the prompt-speed plan: the experts the arena could not pin (a third of the streamed ones on IQ3_S) are 451// copied into pinned buffers by these threads, ahead of the launches. Copied in line by the launching thread they 452// 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 453// j-th unpinned expert, in launch order - lands in host buffer j % kRing, which is free again once the DMA of job 454// j - kRing (recorded by the launching thread, `issued`) is done. 455struct Stager { 456// D-5: the pinned ring's depth (STRATA_STAGER_RING, default 16) - how far the host copies can run ahead of the 457// DMAs of the unpinned experts' blobs 458int kRing = 16 ; 459// SYCL port: a job may name the expert instead of a host pointer - the thread reads it from the GGUF itself 460// (`gsrc`). `from` set: the blob is copied by the source itself (CS-T: a GGUF read in place assembles it from its 461// three role slices; a pointer to it would not live as long as the queue) 462struct Job { 463const uint8_t * src ;size_t bytes ; core::ExpertSource * from = nullptr ;int32_t l = 0 ,e = 0 ; 464const core::GgufExpertSource * gsrc = nullptr ; 465 }; 466 std::vector < uint8_t *> buf ; 467 std::vector < char > pinned ; 468 std::vector < std::vector < uint8_t >> pageable ;// the fallback when no more RAM can be pinned 469 std::vector < dpct::event_ptr > dma_done ; 470uint64_t * done_seq = nullptr ;// page-locked: the copy queue's last finished DMA per buffer 471uint64_t * src_seq = nullptr ;// page-locked: the values a copy-engine queue copies into done_seq (it cannot run a fill kernel) 472 std::vector < uint64_t > want ;// the sequence number each buffer's last DMA writes 473uint64_t issue_seq = 0 ; 474 std::vector < Job > jobs ; 475 std::unique_ptr < std::atomic < int > []> ready ; 476size_t ready_cap = 0 ; 477// gen << 32 | n << 16 | next index: a claim is a CAS on the generation it woke for (a thread late from the 478// previous layer can never take a job of this one - the expert pool's issue #29 lesson) 479 std::atomic < uint64_t > head {0 }; 480 std::atomic < int > issued {0 },active {0 }; 481uint32_t gen = 0 ; 482bool quit = false; 483 std::mutex mu ; 484 std::condition_variable cv ; 485 std::vector < std::thread > threads ; 486int device = 0 ; 487 488bool init (size_t blob_bytes ,int nthreads ) { 489if (const char * v = std::getenv ("STRATA_STAGER_RING" ))kRing = std::clamp (std::atoi (v ),2 ,256 ); 490buf .assign ((size_t )kRing ,nullptr ); 491pinned .assign ((size_t )kRing ,0 ); 492dma_done .assign ((size_t )kRing ,nullptr ); 493want .assign ((size_t )kRing ,0 ); 494done_seq = sycl::malloc_host < uint64_t > ((size_t )kRing , dpct::get_in_order_queue ()); 495if (done_seq == nullptr )return false; 496for (int i = 0 ;i < kRing ;++ i )done_seq [i ]= 0 ; 497src_seq = sycl::malloc_host < uint64_t > ((size_t )4 * kRing , dpct::get_in_order_queue ()); 498if (src_seq == nullptr )return false; 499for (int i = 0 ;i < 4 * kRing ;++ i )src_seq [i ]= 0 ; 500pageable .resize (kRing ); 501for (int i = 0 ;i < kRing ;++ i ) { 502/* 503DPCT1048: The original value cudaHostAllocDefault is not 504meaningful in the migrated code and was removed or replaced with 0. 505You may need to check the migrated code. 506*/ 507pinned [i ]= !force_pageable ()&& 508DPCT_CHECK_ERROR ( 509buf [i ]= (unsigned char * )sycl::malloc_host ( 510blob_bytes , dpct::get_in_order_queue ()))== 0 ; 511if (!pinned [i ]) { 512/* 513DPCT1026: The call to cudaGetLastError was removed because 514this functionality is redundant in SYCL. 515*/ 516pageable [(size_t )i ].resize (blob_bytes ); 517buf [i ]= pageable [(size_t )i ].data (); 518 } 519if (DPCT_CHECK_ERROR (dma_done [i ]= new sycl::event ())!= 5200 )return false; 521 } 522device = dpct::get_current_device_id (); 523for (int t = 0 ;t < nthreads ;++ t )threads .emplace_back ([this ] {work (); }); 524return true; 525 } 526 ~Stager () { 527finish (); 528 { std::lock_guard < std::mutex > lk (mu );quit = true; } 529cv .notify_all (); 530for (auto & t :threads )t .join (); 531if (done_seq ) sycl::free (done_seq , dpct::get_in_order_queue ()); 532if (src_seq ) sycl::free (src_seq , dpct::get_in_order_queue ()); 533for (int i = 0 ;i < kRing ;++ i ) { 534if (dma_done [i ]) dpct::destroy_event (dma_done [i ]); 535if (buf [i ]&& pinned [i ]) 536 sycl::free (buf [i ], dpct::get_in_order_queue ()); 537 } 538 } 539void work () { 540/* 541DPCT1093: The "device" device may be not the one intended for use. 542Adjust the selected device if needed. 543*/ 544 dpct::select_device (device ); 545uint32_t seen = 0 ; 546for (;;) { 547 { 548 std::unique_lock < std::mutex > lk (mu ); 549cv .wait (lk , [& ] {return quit || gen != seen ; }); 550if (quit )return ; 551seen = gen ; 552 } 553for (;;) { 554active .fetch_add (1 , std::memory_order_acq_rel ); 555const int j = claim (seen ); 556if (j < 0 ) {active .fetch_sub (1 , std::memory_order_acq_rel );break ; } 557const int b = j %kRing ; 558if (j >=kRing )// job j - kRing's DMA from this buffer is queued 559while (issued .load (std::memory_order_acquire ) <=j - kRing ) std::this_thread::yield (); 560// and done (#385) - for a generation's first kRing jobs that is the previous generation's last DMA from 561// the buffer, which nothing else waits for when a chunk ends without a sync (no MTP) 562while (!buffer_free (b )) std::this_thread::yield (); 563const Job & jb = jobs [(size_t )j ]; 564if (jb .gsrc != nullptr ) { 565if (!jb .gsrc -> read_into (jb .l ,jb .e ,buf [b ],jb .bytes )) { 566 std::fprintf (stderr ,"prefill: reading expert %d of layer %d from the GGUF failed\n" ,jb .e ,jb .l ); 567 std::memset (buf [b ],0 ,jb .bytes ); 568 } 569 }else if (jb .from == nullptr ) { 570 std::memcpy (buf [b ],jb .src ,jb .bytes ); 571 }else if (!jb .from -> copy_blob (jb .l ,jb .e ,buf [b ])) { 572 std::fprintf (stderr ,"prefill: the expert source could not copy expert %d of layer %d\n" ,jb .e ,jb .l ); 573 std::abort (); 574 } 575ready [(size_t )j ].store (1 , std::memory_order_release ); 576active .fetch_sub (1 , std::memory_order_acq_rel ); 577 } 578 } 579 } 580int claim (uint32_t g ) { 581uint64_t cur = head .load (std::memory_order_acquire ); 582for (;;) { 583if ((uint32_t ) (cur >>32 )!= g )return -1 ; 584const int n = (int ) ((cur >>16 )& 0xffff ),j = (int ) (cur & 0xffff ); 585if (j >=n )return -1 ; 586if (head .compare_exchange_weak (cur ,cur + 1 , std::memory_order_acq_rel , std::memory_order_acquire ))return j ; 587 } 588 } 589/// A layer's jobs; the previous layer's are finished (finish()). 590void start (std::vector < Job >&& js ) { 591if (js .empty ())return ; 592 std::lock_guard < std::mutex > lk (mu ); 593jobs = std::move (js ); 594if (ready_cap < jobs .size ()) { 595ready_cap = jobs .size ()* 2 ; 596ready .reset (new std::atomic < int > [ready_cap ]); 597 } 598for (size_t i = 0 ;i < jobs .size ();++ i )ready [i ].store (0 , std::memory_order_relaxed ); 599issued .store (0 ); 600++ gen ; 601head .store ((uint64_t )gen <<32 | (uint64_t )jobs .size () <<16 , std::memory_order_release ); 602cv .notify_all (); 603 } 604/// Job j's bytes, in a pinned buffer (waits for the copy). 605const uint8_t * wait (int j ) { 606while (!ready [(size_t )j ].load (std::memory_order_acquire )) std::this_thread::yield (); 607return buf [j %kRing ]; 608 } 609/// The launching thread queued job j's DMA on `copy`: its buffer is free once that is done. 610/// The launching thread queued job j's DMA on `copy`: its buffer is free once that is done. 611// SYCL port: the copy queue writes a sequence number into page-locked host memory after the DMA and the stager 612// thread polls it, instead of waiting on an event. A stager thread's host wait on the copy queue's events (the 613// CUDA form, cudaEventSynchronize) hung a lent-slot prompt in its first full chunk under the Level Zero v2 adapter 614// once the ring wrapped: no thread was waiting by then, the GPU sat busy - the event a host thread had waited on 615// was still in a queue's wait list (the v1 adapter and a 256-buffer ring, which never waits, both ran). 2026-10-01 616void issued_one (int j , dpct::queue_ptr copy ) { 617const uint64_t s = ++ issue_seq ; 618want [(size_t ) (j %kRing )]= s ; 619if (strata::is_copy_engine_queue (copy )) {// a copy-only command list runs no kernels (a fill is one): a copy of the value 620uint64_t * v = src_seq + (size_t ) (s % (uint64_t ) (4 * kRing )); 621* v = s ; 622copy -> memcpy (done_seq + j %kRing ,v ,sizeof (uint64_t )); 623 }else { 624copy -> fill < uint64_t > (done_seq + j %kRing ,s ,1 ); 625 } 626issued .store (j + 1 , std::memory_order_release ); 627 } 628bool buffer_free (int b )const { 629return * (volatile const uint64_t * ) (done_seq + b ) >=want [(size_t )b ]; 630 } 631/// No job is running after this (the end of a layer, or an early return in the middle of one). 632void finish () { 633head .store ((uint64_t )gen <<32 , std::memory_order_release );// n = 0: nothing more to claim 634issued .store (1 <<30 , std::memory_order_release ); 635while (active .load (std::memory_order_acquire )!= 0 ) std::this_thread::yield (); 636 } 637}; 638 639// multi-GPU: the peer GPU's share of a prompt chunk's experts. Per MoE layer the primary copies its normed 640// activations over P2P, the peer quantizes the rows routed to the experts it holds, runs the same MMQ products the 641// primary would (gathered from its own slots), and copies the result rows back into the primary's Dm rows - the rows 642// are laid out local-first, so the peer's are one contiguous block at the end. 643struct PeerPrefill { 644 core::PeerExperts * peer = nullptr ; 645int dev = -1 ; 646int64_t cap_rows = 0 ,T_max = 0 ; 647 dpct::queue_ptr s = & dpct::get_in_order_queue (); 648 dpct::event_ptr ev_in = 649nullptr ;// on the primary: the activations and the row tables are ready 650 dpct::event_ptr ev_done = 651nullptr ;// on the peer: its rows have landed in the primary's Dm 652// multi-GPU: the result rows go back group by group on a second stream while the next group computes 653 dpct::queue_ptr s_out = & dpct::get_in_order_queue (); 654static constexpr int kGrpEv = NE /16 + 2 ; 655 dpct::event_ptr ev_grp [kGrpEv ]= {}; 656bool out_pending = false;// s_out may still read Dm (the next layer's products wait for it) 657bool out_pipe = true; 658// multi-GPU COMPACT: the peer's per-row buffers hold one GROUP's rows instead of the layer's (a group 659// = up to 16 experts and at most G rows), the result rows double-buffered: ~0.9 GB -> ~0.26 GB on the helper 660// card at 8192-token chunks, and no row cap (every peer-held expert's rows go to the peer). 661// STRATA_PF_PEER_COMPACT=0: the layer-sized buffers (the A/B). 662bool compact = true; 663int64_t G = 0 ; 664void * Xq_g = nullptr ,* Hq_g = nullptr ; 665float * GU_g = nullptr ,* H_g = nullptr ,* Dm_b [2 ]= {}; 666 dpct::event_ptr ev_dm [2 ]= {}; 667bool dm_live [2 ]= {}; 668 std::vector < std::pair < size_t ,size_t >> groups ; 669// multi-GPU PEER STREAMING: a share of the experts the primary would stream over ITS PCIe link in a 670// big chunk is streamed by the peer over its own link instead (into its own ring) and computed there - it halves 671// the primary's copy load and moves expert work to the card that idles through most of the MoE half. 672// STRATA_PF_PEER_STREAM = the share (0 = off), STRATA_PF_PEER_RING = its ring slots. 673double ps_frac = 0.0 ; 674int RP = 0 ; 675 std::vector < uint8_t *> pstage ; 676 std::vector < dpct::event_ptr > pcopied ,pused ; 677 std::vector < char > plive ; 678 dpct::queue_ptr s_cp = & dpct::get_in_order_queue (); 679struct PsEntry {int32_t l ,e ;const uint8_t * blob ; }; 680 std::vector < PsEntry > pseq ;// this chunk's peer-streamed experts, layer by layer in id order 681 std::vector < size_t > pseq_start ; 682 std::vector < char > ps_flag ;// [layer * NE + e]: streamed by the peer in this chunk 683size_t p_issued = 0 ,pk = 0 ; 684int64_t ps_experts = 0 ; 685float * mixed = nullptr ,* GU = nullptr ,* H = nullptr ,* Dm = nullptr ; 686void * Xq = nullptr ,* Hq = nullptr ; 687int32_t * src = nullptr ,* bounds = nullptr ,* ident = nullptr ; 688uint8_t * grp_gu = nullptr ,* grp_d = nullptr ; 689 std::unique_ptr < mmq::Context > ctx ; 690 mmq::Context * run_ctx = nullptr ;// the context its products run in: ctx, or a layer split helper stage's 691// 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 692// upload would queue behind the expert blobs that device's streams already hold (up to a ring of them, ~70 us 693// each - the grouping tables' reason for mapped memory too), and cudaMemcpyPeerAsync would be staged by the 694// driver. `back_at` / `back_rows`: the rows this layer sends back. 695bool p2p = true; 696// The row table and the group bounds go the same way: the primary's are pinned for its own device only (or 697// pageable), and a copy from them on the peer's stream would hold up the host until that stream is idle. 698float * host_x = nullptr ;// T x N activations (mapped, portable) 699float * host_rows = nullptr ;// the peer's result rows (mapped, portable) 700int32_t * host_src = nullptr ;// the peer's rows' tokens (mapped, portable) 701int32_t * host_bounds = nullptr ;// its group bounds (mapped, portable) 702size_t host_x_cap = 0 ,host_rows_cap = 0 ,host_src_cap = 0 ;// elements 703static constexpr size_t kHostBounds = 2 * (NE + NE /16 + 2 )+ 64 ; 704int64_t back_at = 0 ,back_rows = 0 ; 705 std::vector < int32_t > bounds_host ; 706 std::vector < void *> owned ; 707int64_t layers = 0 ,experts = 0 ,rows = 0 ,over_cap = 0 ;// stats 708 ~PeerPrefill () { 709if (dev < 0 )return ; 710int prev = 0 ; 711prev = dpct::get_current_device_id (); 712/* 713DPCT1093: The "dev" device may be not the one intended for use. 714Adjust the selected device if needed. 715*/ 716 dpct::select_device (dev ); 717if (s )s -> wait (); 718ctx .reset (); 719for (void * p :owned ) 720DPCT_CHECK_ERROR (sycl::free (p , dpct::get_in_order_queue ())); 721if (ev_done ) dpct::destroy_event (ev_done ); 722if (s_out )s_out -> wait (); 723for (dpct::event_ptr e :ev_grp )if (e ) dpct::destroy_event (e ); 724for (dpct::event_ptr e :ev_dm )if (e ) dpct::destroy_event (e ); 725if (s_cp )s_cp -> wait (); 726for (dpct::event_ptr e :pcopied )if (e ) dpct::destroy_event (e ); 727for (dpct::event_ptr e :pused )if (e ) dpct::destroy_event (e ); 728if (s_cp ) dpct::get_current_device ().destroy_queue (s_cp ); 729if (s_out ) dpct::get_current_device ().destroy_queue (s_out ); 730if (s ) dpct::get_current_device ().destroy_queue (s ); 731/* 732DPCT1093: The "prev" device may be not the one intended for use. 733Adjust the selected device if needed. 734*/ 735 dpct::select_device (prev ); 736if (ev_in ) dpct::destroy_event (ev_in ); 737if (host_x ) sycl::free (host_x , dpct::get_in_order_queue ()); 738if (host_rows ) sycl::free (host_rows , dpct::get_in_order_queue ()); 739if (host_src ) sycl::free (host_src , dpct::get_in_order_queue ()); 740if (host_bounds ) sycl::free (host_bounds , dpct::get_in_order_queue ()); 741 } 742}; 743 744// SYCL port: how many queries the prompt path hands the FP32 attention kernel at once (STRATA_ATTN_BATCH, default 32; the 745// tensor-core kernel is opt-in and slower here). Its scratch is batch x chunks x n_head x 258 floats, about 0.41 GB at 32 and 746// 1.65 GB at 128 on Flash-Next, independent of the prompt chunk, so the size that init allocates (attn_batch_for) and the size 747// the budget counts (bytes_needed_impl, which sizes the expert cache and the prompt path's loan) must be the same number. 748// 128 reads a prompt 1.1-1.3% faster on two Arc Pro B65s with the lane-cell score phase, but its extra 1.2 GB comes out of 749// the expert cache on every card (an 8 GB A750 most), so the default stays 32. 750static int64_t attn_batch_setting () { 751const char * v = std::getenv ("STRATA_ATTN_BATCH" ); 752const long long n = v ? std::atoll (v ) :32 ; 753return (n >=1 && n <=1024 ) ? (int64_t )n :32LL ; 754} 755// A chunk of T tokens never runs more than T queries at once: the scratch of the rest would sit unused. 756static int64_t attn_batch_for (size_t T ) { 757return std::max < int64_t > (1 , std::min < int64_t > (attn_batch_setting (), (int64_t )T )); 758} 759 760struct Prefill ::Impl { 761const core::WeightTable * wt = nullptr ; 762const core::ModelGeometry * g = nullptr ; 763 core::SessionState * ss = nullptr ; 764 core::ExpertSource * src = nullptr ; 765const core::ExpertCache * cache = nullptr ; 766const int32_t * host_res = nullptr ; 767int64_t T = 0 ,T_max = 0 ; 768bool borrowed = false; 769 dpct::queue_ptr cs = & dpct::get_in_order_queue (), 770copy = & dpct::get_in_order_queue (); 771 std::unique_ptr < sycl::queue > copy_without_profiling ; 772Gemm gemm ; 773 std::vector < void *> owned ; 774// chunk buffers 775float * emb = nullptr ,* R = nullptr ,* xn = nullptr ,* lo = nullptr ,* gated = nullptr ,* inj = nullptr ; 776float * grs = nullptr ;// F-1: the hyper-connection read's row scales (T x 4) 777uint16_t * xn16 = nullptr ,* lo16 = nullptr ; 778float * mixed = nullptr ; 779uint16_t * mixed_bf = nullptr ,* mixed_h = nullptr ; 780// APR (prism.hadamard): per layer, this device's copies of the gate/up (n_embd) and down (n_ff) sign vectors 781// (nullptr: identity signs or not folded), resolved once in init so a prompt chunk reads a pointer 782 std::vector < const float *> had_sx ,had_sh ; 783bool f16_io = false;// HIP, STRATA_HIP_PROMPT_F16=1: this stage's 16-bit GEMMs run FP16 in and out (set in init) 784uint16_t * xn16_lo = nullptr ,* lo16_lo = nullptr ,* mixed_bf_lo = nullptr ;// bf16x2(): the BF16 GEMMs' low parts 785float * bo = nullptr ; 786// GDN 787float * qkv = nullptr ,* z = nullptr ,* ab = nullptr ,* gate = nullptr ,* beta = nullptr ,* hbuf = nullptr ,* y = nullptr ; 788uint16_t * y_h = nullptr ; 789// QSA 790float * Kc = nullptr ,* Vc = nullptr ,* Qf = nullptr ,* q = nullptr ,* idx_raw = nullptr ,* q_idx = nullptr ,* attn = nullptr ; 791uint16_t * attn_h = nullptr ; 792int32_t * steps_dev = nullptr ; 793 std::vector < int32_t > steps_host ; 794int32_t * sel_ids = nullptr ; 795float * sel_scores = nullptr ;// [sel_batch, max_blocks] 796int64_t sel_batch = 256 ,max_blocks = 0 ; 797float * attn_scratch = nullptr ; 798int64_t attn_batch = 32 ,cap = 0 ;// attn_batch: set by carve from the chunk (attn_batch_for) 799// MoE 800float * logits = nullptr ,* w = nullptr ,* GU = nullptr ,* Dm = nullptr ,* sgate = nullptr ,* sup = nullptr , 801* shared = nullptr ,* sg = nullptr ; 802int32_t * ids = nullptr ,* slot_dev = nullptr ,* src_dev = nullptr ; 803uint16_t * Xs = nullptr ,* Hh = nullptr ,* sh_h = nullptr ; 804// step 2b (MMQ): the activations quantized per layer, H in FP32 and its group's quantized rows, the identity 805// row map, the group bounds, the group buffers of gathered experts 806void * Xq = nullptr ,* Hq = nullptr ; 807float * H = nullptr ; 808int32_t * ids_identity = nullptr ,* bounds_dev = nullptr ; 809uint8_t * grp_gu = nullptr ,* grp_d = nullptr ; 810 std::vector < int32_t > bounds_host ; 811 std::unique_ptr < mmq::Context > mmq_ctx ; 812 std::vector < int32_t > ids_host ,slot_host ,src_host ,cnt ,off ; 813// The grouping tables in mapped pinned memory, [ids | slot | src] of T_max * K each, then the MMQ bounds: kernels 814// read and write them in place. A cudaMemcpyAsync of them queues behind the expert blobs the copy stream already 815// holds (up to `ring` of them, ~70 us each), and the GPU idles meanwhile - measured 4.2 s of a 128K prompt's 816// 70 s at the default ring, 0.7 s with a 16-slot one. STRATA_GROUP_COPY=1: the copies (the A/B arm). 817int32_t * grp_host = nullptr ; 818int32_t * grp_dev = nullptr ;// its device alias 819size_t grp_n = 0 ,grp_tk = 0 ;// int32s allocated; T_max * K (the offset of slot, and of src past it) 820uint16_t * dq_gu [strata::prefill::xmx::kMaxGroup ]= {}; 821uint16_t * dq_d [strata::prefill::xmx::kMaxGroup ]= {}; 822uint8_t * stage_dev [RING_MAX ]= {}; 823int ring = STAGE ;// the slots of this layout's ring (ring_slots) 824// 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 825// only write stream_all_min() - 1 of its rows into them; fused_layout() keeps the two in step (#583, #954) 826bool fused_bufs = false; 827 std::unique_ptr < Stager > stager ;// the unpinned experts' host copies (step 4) 828 dpct::event_ptr copied [RING_MAX ]= {},used [RING_MAX ]= {}; 829bool stage_live [RING_MAX ]= {}; 830// the event that releases each ring slot: its own `used`, or - when an MMQ group is gathered in one launch - the 831// `used` of the last slot gathered with it, recorded once for all of them (a later record only waits longer) 832int used_of [RING_MAX ]= {}; 833// PLE 834float * ple_emb = nullptr ; 835 std::vector < float > ple_pageable [2 ];// the fallback when no more RAM can be pinned 836float * ple_emb_host [2 ]= {};// pinned, double-buffered: the next chunk's rows are read while this 837 dpct::event_ptr ple_copied [2 ]= 838 {};// one runs; the event marks that buffer's upload done 839 std::vector < uint32_t > ple_rows [2 ]; 840// SYCL port: each buffer's upload is marked by a sequence number the queue writes into page-locked memory after 841// it, polled by the host - not a host wait on `ple_copied` (a host wait on a queue's event hung the prompt path 842// under the Level Zero v2 adapter once #374 moved it inside the layer loop; see Stager::issued_one) 843uint64_t * ple_done_seq = nullptr ; 844uint64_t ple_want [2 ]= {}; 845uint64_t ple_seq = 0 ; 846float * ple_norm = nullptr ; 847uint8_t * region = nullptr ;// the attention/MoE scratch region (idle while the PLE block runs) 848uint64_t region_bytes = 0 ; 849PrefillStats * stats = nullptr ; 850// KV streaming: one layer's whole K/V, staged from the host copy per layer and chunk (identity layout) 851 strata::kernels::KvHostPools stage ; 852int32_t * ident_table = nullptr ; 853 dpct::queue_ptr kv_copy = & dpct::get_in_order_queue (); 854 dpct::event_ptr kv_released = nullptr ,kv_ready = nullptr ; 855// layer split: the device, and the hand-off to the next stage (two pinned chunk buffers, used in turn) 856int device = -1 ; 857float * hand [2 ]= {}; 858// C-4: the chunk's token ids on the device, for one batched embedding gather 859int32_t * tok_dev = nullptr ; 860 std::vector < int32_t > tok_host ; 861 std::unique_ptr < PeerPrefill > pp ;// multi-GPU: the peer GPU's expert share (set_peer) 862// layer split: the next stage's GPU as a stream-only peer (set_stage_helper); its buffers are that stage's own 863// prompt buffers, bound per prompt, and it takes the place of `pp` for a run it helps 864 std::unique_ptr < PeerPrefill > help_pp ; 865}; 866 867namespace { 868// the staging pool of a streamed session: every page of one layer (same sequence in init and bytes_needed) 869// STRATA_KV_STAGE_OWN (A/B only): the staging pool gets its own allocation instead of borrowed expert slots, so a 870// streamed run lends the prompt path exactly the slots a resident one does (a lent expert runs on the CPU, which 871// rounds differently: without this an A/B compares two expert placements as well as two KV placements) 872bool stage_own () {static const bool v = std::getenv ("STRATA_KV_STAGE_OWN" )!= nullptr ;return v ; } 873void take_stage (Alloc & o_borrowed ,const core::SessionState & ss ,const strata::kernels::QsaShapes & s , 874 strata::kernels::KvHostPools & st ,bool & ok ) { 875const core::QsaState & q0 = ss .qsa_states [ss .qsa_primary ()]; 876if (q0 .kv_mode != 1 )return ; 877if (stage_own ()&& o_borrowed .count_only )return ; 878Alloc own ; 879own .owned = o_borrowed .owned ; 880Alloc & o = stage_own () ?own :o_borrowed ; 881const size_t rows = (size_t )q0 .n_pages * s .n_head_kv * s .page_size ; 882if (q0 .kv_hybrid ) {// K8V4: the three runs of kKvHybrid; pools_of() then reads as the hybrid pools (mode 3) 883st .k_q = o .take < int8_t > (rows * s .head_dim ,ok ); 884st .k_scale = o .take < uint16_t > (rows * (s .head_dim /64 ),ok ); 885st .v_q4 = o .take < uint8_t > (rows * strata::kernels::kv_q4_bytes_per_head ((int )s .head_dim ),ok ); 886 }else if (q0 .kv_q4 ) { 887st .k_q4 = o .take < uint8_t > (rows * strata::kernels::kv_q4_bytes_per_head ((int )s .head_dim ),ok ); 888st .v_q4 = o .take < uint8_t > (rows * strata::kernels::kv_q4_bytes_per_head ((int )s .head_dim ),ok ); 889 }else if (q0 .kv_int8 ) { 890st .k_q = o .take < int8_t > (rows * s .head_dim ,ok ); 891st .v_q = o .take < int8_t > (rows * s .head_dim ,ok ); 892st .k_scale = o .take < uint16_t > (rows * (s .head_dim /64 ),ok ); 893st .v_scale = o .take < uint16_t > (rows * (s .head_dim /64 ),ok ); 894 }else { 895st .k_pool = o .take < uint16_t > (rows * s .head_dim ,ok ); 896st .v_pool = o .take < uint16_t > (rows * s .head_dim ,ok ); 897 } 898} 899strata::kernels::QsaAttnPools pools_of (const strata::kernels::KvHostPools & h ,const int32_t * table ) { 900 strata::kernels::QsaAttnPools p ; 901p .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 ; 902p .k_q4 = h .k_q4 ;p .v_q4 = h .v_q4 ; 903p .page_table = table ; 904return p ; 905} 906}// namespace 907 908 909// ------------------------------------------------------------------------------------------------ 151-b70: int8 or FP16 experts 910// STRATA_PREFILL_MMQ=auto picks per group of experts from the measured cost on THIS GPU: at the first layer of a given expert 911// format the int8 chain (quantize, gate/up, SwiGLU + quantize, down) and the FP16 chain (dequantize, two GEMMs, SwiGLU) are timed on 912// synthetic experts (random blobs of the layer's format and shape) at 16, 32, 64, 128 and 256 rows per expert, and the crossover 913// (the mean rows per expert where the FP16 chain becomes the faster one, interpolated on the cost ratio) is kept, with a flag for 914// how clear the measurement was. It is cached in a small text file (STRATA_CACHE_DIR, else ~/.cache/strata/i8-crossover.txt) keyed by 915// device name, driver, formats and shape, and read back instead of measured when the key matches. 916namespace { 917struct I8Cross {double rows = 0 ;bool confident = false;bool measured = false; }; 918 919std::string i8_cache_file () { 920const char * d = std::getenv ("STRATA_CACHE_DIR" ); 921 std::string dir ; 922if (d && d [0 ])dir = d ; 923else if (const char * h = std::getenv ("HOME" ))dir = std::string (h )+ "/.cache/strata" ; 924else if (const char * a = std::getenv ("LOCALAPPDATA" ))dir = std::string (a )+ "/strata" ; 925else return "" ; 926return dir + "/i8-crossover.txt" ; 927} 928bool i8_cache_read (const std::string & key ,I8Cross & out ) { 929const std::string path = i8_cache_file (); 930if (path .empty ())return false; 931 std::FILE * f = std::fopen (path .c_str (),"r" ); 932if (!f )return false; 933char line [700 ]; 934bool ok = false; 935while (std::fgets (line ,sizeof line ,f )) { 936char k [600 ];double rows ;int conf ; 937if (std::sscanf (line ,"%599[^\t]\t%lf\t%d" ,k ,& rows ,& conf )== 3 && key == k ) {out .rows = rows ;out .confident = conf != 0 ;ok = true; } 938 } 939 std::fclose (f ); 940return ok ; 941} 942void i8_cache_write (const std::string & key ,const I8Cross & c ) { 943const std::string path = i8_cache_file (); 944if (path .empty ())return ; 945const std::string dir = path .substr (0 ,path .rfind ('/' )); 946 std::vector < std::string > keep ;// the other keys' lines 947if (std::FILE * f = std::fopen (path .c_str (),"r" )) { 948char line [700 ]; 949while (std::fgets (line ,sizeof line ,f )) { 950 std::string s (line ); 951if (s .compare (0 ,key .size ()+ 1 ,key + "\t" )!= 0 )keep .push_back (s ); 952 } 953 std::fclose (f ); 954 } 955 std::FILE * f = std::fopen (path .c_str (),"w" ); 956if (!f ) { 957 ::mkdir (dir .c_str (),0755 ); 958f = std::fopen (path .c_str (),"w" ); 959if (!f )return ; 960 } 961for (auto & s :keep ) std::fputs (s .c_str (),f ); 962 std::fprintf (f ,"%s\t%.1f\t%d\n" ,key .c_str (),c .rows ,c .confident ?1 :0 ); 963 std::fclose (f ); 964} 965 966template < class M > 967I8Cross i8_calibrate (M & m ,const strata::kernels::cpu::NativeFmt & f ) { 968namespace i8= strata::prefill::i8; 969 sycl::queue & q = * m .cs ; 970const std::string dev = q .get_device ().template get_info < sycl::info::device::name > ()+ "|" + 971q .get_device ().template get_info < sycl::info::device::driver_version > (); 972char keyb [600 ]; 973 std::snprintf (keyb ,sizeof keyb ,"%s|%d|%d|%lldx%lld" ,dev .c_str (),f .gu_type ,f .d_type , (long long )f .n_ff , (long long )f .n_embd ); 974const std::string key = keyb ; 975I8Cross res ; 976if (i8_cache_read (key ,res )) { 977 std::fprintf (stderr ,"strata: int8 experts: crossover %.0f rows per expert (%s) from the cache for %s\n" ,res .rows , 978res .confident ?"clear" :"not clear" ,key .c_str ()); 979return res ; 980 } 981constexpr int E = 8 ; 982const int rows_list [5 ]= {16 ,32 ,64 ,128 ,256 }; 983const int N = (int )f .n_embd ,NF = (int )f .n_ff ; 984double t8 [5 ]= {},t16 [5 ]= {}; 985const double facs [E ]= {0.15 ,0.35 ,0.6 ,0.85 ,1.1 ,1.4 ,1.8 ,2.45 }; 986double fac [E ]; 987 std::vector < uint8_t *> blobs (E ,nullptr ); 988uint16_t * X = nullptr ,* Hh = nullptr ; 989float * GU = nullptr ,* Dm = nullptr ; 990bool ok = true; 991try { 992// rows per expert are uneven like a real group (a few big experts and many small ones): factors of the mean, mean 1 993for (int i = 0 ;i < E ;++ i ) {fac [i ]= facs [i ] /1.0875 ; } 994size_t rmax = 0 ; 995for (int i = 0 ;i < E ;++ i )rmax += (size_t ) std::max (1.0 ,256.0 * fac [i ]+ 0.5 )+ 8 ;// rows of the largest sample (plus padding) 996for (int i = 0 ;i < E ;++ i )blobs [i ]= sycl::malloc_device < uint8_t > (f .bytes + 256 ,q ); 997X = sycl::malloc_device < uint16_t > (rmax * N ,q ); 998Hh = sycl::malloc_device < uint16_t > (rmax * NF ,q ); 999GU = sycl::malloc_device < float > (rmax * 2 * NF ,q ); 1000Dm = sycl::malloc_device < float > (rmax * N ,q ); 1001for (int i = 0 ;i < E ;++ i )ok = ok && blobs [i ]; 1002ok = ok && X && Hh && GU && Dm ; 1003if (!ok )throw std::runtime_error ("no VRAM for the measurement" ); 1004// synthetic experts: random bytes with a sane fp16 scale at every block start (the cost does not depend on the values) 1005 std::vector < uint8_t > hb (f .bytes + 256 ); 1006uint32_t s = 12345 ; 1007auto rnd = [& ] {s = s * 1664525u + 1013904223u ;return s >>8 ; }; 1008for (size_t i = 0 ;i < hb .size ();++ i )hb [i ]= (uint8_t )rnd (); 1009const int gb = f .gu_type == 21 ?110 :f .gu_type == 18 ?98 :82 ; 1010for (size_t o = 0 ;o + 2 <=f .up_off * 2 && o < hb .size ();o += gb ) {hb [o ]= 0x00 ;hb [o + 1 ]= 0x2C ; } 1011for (size_t o = f .down_off ;o + 2 <=f .bytes ;o += 18 ) {hb [o ]= 0x00 ;hb [o + 1 ]= 0x2C ; } 1012for (int i = 0 ;i < E ;++ i )q .memcpy (blobs [i ],hb .data (),f .bytes ); 1013 std::vector < uint16_t > hx (rmax * N ); 1014for (auto & x :hx )x = (uint16_t ) (0x3400 + (rnd ()& 0x3ff ));// ~0.25..0.5, no zeros 1015q .memcpy (X ,hx .data (),hx .size ()* 2 ); 1016q .wait (); 1017auto timeit = [& ](auto && fn ) { 1018fn ();q .wait (); 1019const auto w0 = std::chrono::steady_clock::now (); 1020while (std::chrono::duration < double > (std::chrono::steady_clock::now ()- w0 ).count ()< 0.02 ) {fn ();q .wait (); } 1021double best = 1e30 ; 1022for (int r = 0 ;r < 4 ;++ r ) { 1023const auto t0 = std::chrono::steady_clock::now (); 1024fn ();q .wait (); 1025best = std::min (best , std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count ()); 1026 } 1027return best ; 1028 }; 1029for (int ri = 0 ;ri < 5 ;++ ri ) { 1030const int R = rows_list [ri ]; 1031int32_t cnt [i8::kMaxGroup ]; 1032for (int i = 0 ;i < E ;++ i )cnt [i ]= std::max (1 , (int ) (R * fac [i ]+ 0.5 )); 1033 i8::Layout lo ; 1034 i8::make_layout (lo ,cnt ,E ); 1035 i8::Workspace ws ; 1036if (!i8::workspace (lo ,N ,NF ,ws ,& q ))throw std::runtime_error ("workspace" ); 1037 std::vector < const uint8_t *> pb (E ); 1038for (int i = 0 ;i < E ;++ i )pb [i ]= blobs [i ]; 1039bool refused = false; 1040t8 [ri ]= timeit ([& ] { 1041 i8::quantize_rows (X ,lo ,N ,ws .xq ,ws .dx ,& q ); 1042if (!i8::gate_up (f .gu_type ,pb .data (),f .up_off ,NF ,lo ,N ,ws .xq ,ws .dx ,GU ,& q ))refused = true; 1043 i8::swiglu_quantize (GU ,lo ,NF ,ws .hq ,ws .dh ,& q ); 1044if (!i8::down (f .d_type ,pb .data (),f .down_off ,N ,lo ,NF ,ws .hq ,ws .dh ,Dm ,& q ))refused = true; 1045 }) /E ; 1046if (refused )throw std::runtime_error ("the int8 kernels refused this format" ); 1047t16 [ri ]= timeit ([& ] { 1048int64_t o = 0 ; 1049for (int i = 0 ;i < E ;++ i ) { 1050const int qd = i %DQ ; 1051 strata::kernels::iq_dequant_expert_f16 (f .gu_type ,f .d_type ,blobs [i ],blobs [i ]+ f .up_off ,blobs [i ]+ f .down_off ,NF ,N , 1052m .dq_gu [qd ],m .dq_d [qd ],& q ); 1053m .gemm .f16 (X + o * N ,m .dq_gu [qd ],GU + o * 2 * NF ,cnt [i ],2 * NF ,N ); 1054 strata::prefill::swiglu_interleaved (GU + o * 2 * NF ,Hh + o * NF ,cnt [i ],& q ); 1055m .gemm .f16 (Hh + o * NF ,m .dq_d [qd ],Dm + o * N ,cnt [i ],N ,NF ); 1056o += cnt [i ]; 1057 } 1058 }) /E ; 1059 } 1060 }catch (const std::exception & e ) { 1061 std::fprintf (stderr ,"strata: int8 experts: the crossover measurement failed (%s): the int8 path is used below 64 rows per expert\n" ,e .what ()); 1062ok = false; 1063 } 1064for (auto * b :blobs )if (b ) sycl::free (b ,q ); 1065if (X ) sycl::free (X ,q ); 1066if (Hh ) sycl::free (Hh ,q ); 1067if (GU ) sycl::free (GU ,q ); 1068if (Dm ) sycl::free (Dm ,q ); 1069if (!ok ) {res .rows = 64 ;res .confident = false;return res ; } 1070// crossover: the first R where the FP16 chain is the faster one, interpolated in log(ratio) between the two bracketing sizes 1071double ratio [5 ]; 1072for (int i = 0 ;i < 5 ;++ i )ratio [i ]= t16 [i ] /t8 [i ];// > 1: int8 faster 1073int first = -1 ; 1074for (int i = 0 ;i < 5 ;++ i )if (ratio [i ]< 1.0 ) {first = i ;break ; } 1075if (first < 0 )res .rows = 512 ;// int8 wins everywhere measured 1076else if (first == 0 )res .rows = 0 ;// FP16 wins even at 16 rows 1077else { 1078const double a = std::log (ratio [first - 1 ]),b = std::log (ratio [first ]); 1079const double t = a / (a - b ); 1080res .rows = std::exp (std::log ((double )rows_list [first - 1 ])+ t * (std::log ((double )rows_list [first ])- std::log ((double )rows_list [first - 1 ]))); 1081 } 1082// clear: the ratio falls with the rows (within 5%) and the samples bracketing the crossover are at least 5% away from 1 1083bool mono = true; 1084for (int i = 1 ;i < 5 ;++ i )if (ratio [i ]> ratio [i - 1 ]* 1.05 )mono = false; 1085res .confident = mono && (first < 0 ?ratio [4 ]> 1.05 :first == 0 ?ratio [0 ]< 0.95 : (ratio [first - 1 ]> 1.05 && ratio [first ]< 0.95 )); 1086res .measured = true; 1087 std::fprintf (stderr ,"strata: int8 experts, measured here (%s): us per expert at 16/32/64/128/256 rows, int8 %.1f/%.1f/%.1f/%.1f/%.1f, FP16 %.1f/%.1f/%.1f/%.1f/%.1f -> crossover %.0f rows per expert (%s)\n" , 1088key .c_str (),t8 [0 ],t8 [1 ],t8 [2 ],t8 [3 ],t8 [4 ],t16 [0 ],t16 [1 ],t16 [2 ],t16 [3 ],t16 [4 ],res .rows ,res .confident ?"clear" :"not clear" ); 1089i8_cache_write (key ,res ); 1090return res ; 1091} 1092}// namespace 1093Prefill ::Prefill () :impl_ (new Impl ) {} 1094Prefill ::~Prefill () { 1095clear_taps (); 1096release (); 1097} 1098 1099// DFlash2 prompt taps (single stage): staging for the completed output of each tapped layer for the last prompt rows; see include/strata/prefill/prefill.hpp 1100bool Prefill ::reserve_taps (const std::vector < int >& layers ,int64_t cap_rows ,int64_t n_embd , std::string & err ) { 1101tap_layers_ = layers ; 1102tap_cap_ = cap_rows ; 1103if (tap_dev_ != nullptr )return true; 1104tap_dev_ = sycl::malloc_device < float > ((size_t )cap_rows * layers .size ()* (size_t )n_embd , dpct::get_in_order_queue ()); 1105if (tap_dev_ == nullptr ) { 1106err = "the prompt staging of the DFlash2 taps does not fit in VRAM" ; 1107return false; 1108 } 1109return true; 1110} 1111 1112void Prefill ::clear_taps () { 1113if (tap_dev_ != nullptr ) { 1114try { sycl::free (tap_dev_ , dpct::get_in_order_queue ()); }catch (...) {} 1115tap_dev_ = nullptr ; 1116 } 1117tap_layers_ .clear (); 1118on_taps = nullptr ; 1119} 1120 1121void Prefill ::reset () { 1122release (); 1123impl_ .reset (new Impl ); 1124stats_ = PrefillStats {}; 1125} 1126 1127void Prefill ::release () { 1128if (!impl_ )return ; 1129if (impl_ -> cs )impl_ -> cs -> wait (); 1130if (impl_ -> copy )impl_ -> copy -> wait (); 1131if (impl_ -> kv_copy )impl_ -> kv_copy -> wait (); 1132for (int i = 0 ;i < RING_MAX ;++ i ) { 1133if (impl_ -> copied [i ]) dpct::destroy_event (impl_ -> copied [i ]); 1134if (impl_ -> used [i ]) dpct::destroy_event (impl_ -> used [i ]); 1135 } 1136for (int b = 0 ;b < 2 ;++ b ) { 1137if (impl_ -> hand [b ]) 1138 sycl::free (impl_ -> hand [b ], dpct::get_in_order_queue ()); 1139if (impl_ -> ple_copied [b ]) dpct::destroy_event (impl_ -> ple_copied [b ]); 1140if (b == 1 && impl_ -> ple_done_seq ) { sycl::free (impl_ -> ple_done_seq , dpct::get_in_order_queue ());impl_ -> ple_done_seq = nullptr ; } 1141if (impl_ -> ple_emb_host [b ]&& impl_ -> ple_pageable [b ].empty ()) 1142 sycl::free (impl_ -> ple_emb_host [b ], dpct::get_in_order_queue ()); 1143 } 1144if (impl_ -> copy_without_profiling ) { 1145impl_ -> copy_without_profiling .reset (); 1146impl_ -> copy = nullptr ; 1147 }else if (impl_ -> copy ) dpct::get_current_device ().destroy_queue (impl_ -> copy ); 1148if (impl_ -> kv_copy ) dpct::get_current_device ().destroy_queue ( 1149impl_ -> kv_copy ); 1150if (impl_ -> kv_released ) dpct::destroy_event (impl_ -> kv_released ); 1151if (impl_ -> kv_ready ) dpct::destroy_event (impl_ -> kv_ready ); 1152if (impl_ -> grp_host ) 1153 sycl::free (impl_ -> grp_host , dpct::get_in_order_queue ()); 1154for (void * p :impl_ -> owned ) 1155DPCT_CHECK_ERROR (sycl::free (p , dpct::get_in_order_queue ())); 1156} 1157 1158namespace { 1159constexpr int64_t GEMM_SCRATCH = 32ll <<20 ;// FP16 elements for the largest dequantized dense weight 1160constexpr size_t GEMM_WS = 32u <<20 ;// cuBLAS workspace 1161 1162// THE ATTENTION HALF AND THE MoE HALF SHARE THEIR BUFFERS. A layer runs its attention (GDN or QSA), writes it back 1163// into the residual, and only then its MoE, so the three sets of scratch are never live at once: one region the size 1164// of the largest holds them all. That is ~260 KB of the ~680 KB a prompt token cost - which is what lets a chunk 1165// grow (every expert is streamed once per chunk, so a bigger chunk streams fewer bytes per token). The sizes are 1166// counted with the same `take` sequence `init` uses; a mismatch makes `init` fail with "do not fit", never overlap. 1167uint64_t gdn_set_bytes (size_t T ) { 1168Alloc a ;a .count_only = true;bool ok = true; 1169a .take < float > (T * C ,ok );a .take < float > (T * ZV ,ok );a .take < float > (T * 2 * HV ,ok );a .take < float > (T * HV ,ok ); 1170a .take < float > (T * HV ,ok );a .take < float > (T * C ,ok );a .take < float > (T * ZV ,ok ); 1171a .take < uint16_t > (T * (ZV + (pf_pad () ?ZV_PAD :0 )),ok ); 1172return a .used ; 1173} 1174uint64_t qsa_set_bytes (size_t T ,int64_t cap ,int64_t max_blocks ,int64_t sel_batch ,int64_t attn_batch , 1175const strata::kernels::QsaShapes & s ) { 1176Alloc a ;a .count_only = true;bool ok = true; 1177a .take < float > (T * kKvW ,ok );a .take < float > (T * kKvW ,ok );a .take < float > (T * kQFull ,ok );a .take < float > (T * kQW ,ok ); 1178a .take < float > (T * kIdxK ,ok );a .take < float > (T * kIdxQW ,ok );a .take < float > (T * kQW ,ok ); 1179a .take < uint16_t > (T * (ZV + (pf_pad () ?ZV_PAD :0 )),ok ); 1180a .take < int32_t > (T * (size_t )cap ,ok ); 1181a .take < float > ((size_t )sel_batch * (size_t )max_blocks ,ok ); 1182a .take < float > ((size_t )attn_batch * strata::kernels::qsa_decode_attn_scratch_floats (cap ,s ),ok ); 1183return a .used ; 1184} 1185// Step 2b: which layers' experts go through MMQ (both weight types covered; the Strata Q2_0 pack always - its blob 1186// is converted to GGUF Q2_0 blocks on the gather), whether any layer keeps the FP16 path (IQ1_M), and the largest 1187// gate/up and down matrices a group buffer slot holds. STRATA_PREFILL_MMQ=0: the FP16 path everywhere (the A/B). 1188constexpr int MMQ_GROUP = 16 ;// experts per MMQ launch (the gather is per expert, as blobs arrive) 1189// 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 1190// product: 640 values). Those bytes meet zero activations, which is harmless only if they decode to finite numbers - 1191// llama.cpp zero-pads after every tensor, and so does a group buffer: this many zeroed bytes follow its last expert. 1192constexpr size_t MMQ_TAIL = 4096 ; 1193struct MmqPlan { 1194bool any = false,fallback = true; 1195 std::vector < char > layer ;// per layer: MMQ 1196 std::vector < char > fo ;// per layer: no MMQ here but the native fused kernels cover its formats 1197// (gfx11: UD-Q4_K_XL's Q4_K / Q5_K and Q5_1 / Q8_0 experts, STRATA_PF_FUSED=1) 1198size_t gu_max = 0 ,d_max = 0 ; 1199}; 1200const MmqPlan & mmq_plan () { 1201static const MmqPlan plan = [] { 1202MmqPlan p ; 1203const auto & lay = strata::kernels::cpu::expert_layout (); 1204const char * env = std::getenv ("STRATA_PREFILL_MMQ" ); 1205const bool on = mmq::built ()&& (env == nullptr || std::atoi (env )!= 0 ); 1206const int64_t layers = lay .native ? (int64_t )lay .fmt .size () :lay .n_layers ; 1207p .layer .assign ((size_t ) std::max < int64_t > (layers ,0 ),0 ); 1208p .fo .assign (p .layer .size (),0 ); 1209p .fallback = !on || layers <=0 ; 1210for (int64_t l = 0 ;on && l < layers ;++ l ) { 1211const int gt = lay .native ?lay .fmt [(size_t )l ].gu_type :42 ,dt = lay .native ?lay .fmt [(size_t )l ].d_type :42 ; 1212// #420: a tile on every GPU for these shapes (gate+up: 1280 rows, down: N rows), else the FP16 path 1213if (!mmq::fits (gt ,kFF2 )|| !mmq::fits (dt ,N )) { 1214p .fallback = true; 1215// the fused path's buffers (Xq, H) exist for it; a chunk it does not take (a small one) keeps the FP16 path 1216if (on && lay .native && fused::native_supported (gt ,dt )) {p .fo [(size_t )l ]= 1 ;p .any = true; } 1217continue ; 1218 } 1219p .layer [(size_t )l ]= 1 ; 1220p .any = true; 1221p .gu_max = std::max (p .gu_max , mmq::matrix_bytes (gt ,kFF2 ,N )); 1222p .d_max = std::max (p .d_max , mmq::matrix_bytes (dt ,N ,kFF )); 1223 } 1224return p ; 1225 }(); 1226return plan ; 1227} 1228// #136 P3: a layout whose chunks run the fused experts (STRATA_PF_FUSED=1, the Q2_0 pack, a streamed chunk of 1229// stream_all_min() tokens or more). Its GU, H and Xq hold only the fused path's grouping tables, int8 H and per-token 1230// 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 1231// lets a bigger chunk or ring fit in the slots the prompt path borrows. A last chunk below stream_all_min() still runs 1232// MMQ in the same buffers, so each keeps MMQ's size for stream_all_min() - 1 tokens. `src`: the layout streams experts 1233// (Prefill::init got an ExpertSource; without one no chunk takes the streamed walk, so no chunk is fused). 1234bool fused_layout (size_t T ,bool src ) { 1235return src && fused_ring ()&& mmq_plan ().any && ring_slots (T )> STAGE && (int64_t )T >=stream_all_min (); 1236} 1237// The MoE buffers MMQ and the fused path share: GU and H in floats, Xq and Hq in bytes. Without `fused` (the 1238// default): MMQ's, for T tokens. 1239struct MoeBufs {size_t gu ,h ,xq ,hq ; }; 1240MoeBufs moe_bufs (size_t T ,int64_t n_expert ,bool fused ) { 1241if (!fused )return {T * K * kFF2 ,T * K * kFF , mmq::q8_bytes ((int64_t ) (T * K ),N ), mmq::q8_bytes ((int64_t ) (T * K ),kFF )}; 1242const size_t ts = (size_t ) std::min < int64_t > ((int64_t )T ,stream_all_min ()- 1 );// MMQ's last small chunk 1243return {std::max (ts * K * kFF2 , (fused::group_bytes ((int64_t ) (T * K ), (int )n_expert )+ 3 ) /4 ), 1244 std::max (ts * K * kFF , (fused::act_bytes ((int64_t ) (T * K ),kFF )+ 3 ) /4 ), 1245 std::max (mmq::q8_bytes ((int64_t ) (ts * K ),N ), fused::act_bytes ((int64_t )T ,N )), 1246 mmq::q8_bytes ((int64_t ) (ts * K ),kFF )}; 1247} 1248uint64_t moe_set_bytes (size_t T ,int64_t n_expert ,bool fused ) { 1249const MmqPlan & mp = mmq_plan (); 1250const MoeBufs mb = moe_bufs (T ,n_expert ,fused ); 1251Alloc a ;a .count_only = true;bool ok = true; 1252a .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 ); 1253a .take < int32_t > (T * K ,ok ); 1254if (mp .fallback )a .take < uint16_t > (T * K * N ,ok ); 1255a .take < float > (mb .gu ,ok ); 1256if (mp .fallback )a .take < uint16_t > (T * K * kFF ,ok ); 1257a .take < float > (T * K * N ,ok );a .take < float > (T * kFF ,ok ); 1258a .take < float > (T * kFF ,ok );a .take < uint16_t > (T * kFF ,ok );a .take < float > (T * N ,ok );a .take < float > (T ,ok ); 1259if (mp .any ) { 1260a .take < uint8_t > (mb .xq ,ok ); 1261a .take < float > (mb .h ,ok ); 1262a .take < uint8_t > (mb .hq ,ok ); 1263 } 1264return a .used ; 1265} 1266} 1267 1268bool Prefill ::init (const core::WeightTable & wt ,const core::ModelGeometry & g , 1269 core::SessionState & ss , core::ExpertSource * src , 1270const core::ExpertCache * cache ,const int32_t * host_res , 1271int64_t chunk ,void * stream , std::string & err ,void * borrow , 1272uint64_t borrow_bytes ,bool borrow_spill )try { 1273if (borrow_spill ) { 1274err = "prefill: a hybrid borrowed/owned layout (--prefill-head-alias) is not in the SYCL port" ; 1275return false; 1276 } 1277Impl & m = * impl_ ; 1278m .wt = & wt ;m .g = & g ;m .ss = & ss ;m .src = src ;m .cache = cache ;m .host_res = host_res ; 1279m .T = chunk ;m .cs = strata::q_of (stream );m .stats = & stats_ ; 1280if (g .n_embd != N || g .hc != HC || g .hc_lr != LR || g .n_expert < 1 || ss .k != K ) { 1281err = "prefill: geometry differs from the artifact's" ;return false; 1282 } 1283 {// APR: the sign vectors on this device, once (hadamard_device_signs takes a mutex and allocates its copy) 1284const strata::kernels::cpu::ExpertLayout & lay = strata::kernels::cpu::expert_layout (); 1285m .had_sx .assign (lay .native ?lay .fmt .size () :0 ,nullptr ); 1286m .had_sh .assign (m .had_sx .size (),nullptr ); 1287for (size_t l = 0 ;l < m .had_sx .size ();++ l ) { 1288if (lay .fmt [l ].had_gu ) 1289m .had_sx [l ]= strata::kernels::hadamard_device_signs (lay .fmt [l ].gu_signs , (int )lay .fmt [l ].n_embd ); 1290if (lay .fmt [l ].had_d ) 1291m .had_sh [l ]= strata::kernels::hadamard_device_signs (lay .fmt [l ].d_signs , (int )lay .fmt [l ].n_ff ); 1292 } 1293 } 1294m .device = dpct::get_current_device_id (); 1295if (static bool said_i8 = false; !said_i8 && i8_mode (m .cs )!= 0 ) { 1296said_i8 = true; 1297 std::fprintf (stderr ,"strata: int8 prompt experts are on (%s); STRATA_PREFILL_MMQ=0 turns them off\n" , 1298i8_env ()== nullptr ?"Battlemage default, auto" :"STRATA_PREFILL_MMQ set" ); 1299 } 1300if (stage_le_ < 0 )stage_le_ = g .n_layers ; 1301if (stage_lb_ < 0 || stage_lb_ >=stage_le_ || stage_le_ > g .n_layers || (stage_le_ < g .n_layers )!= (next_ != nullptr )) { 1302err = "prefill: the stage's layer range is wrong" ; 1303return false; 1304 } 1305for (int b = 0 ;next_ != nullptr && b < 2 ;++ b ) 1306/* 1307DPCT1048: The original value cudaHostAllocPortable is not meaningful 1308in the migrated code and was removed or replaced with 0. You may need to 1309check the migrated code. 1310*/ 1311if (!m .hand [b ]&& 1312DPCT_CHECK_ERROR ( 1313m .hand [b ]= (float * )sycl::malloc_host ( 1314 (size_t )chunk * D * 4 , dpct::get_in_order_queue ()))!= 0 ) { 1315err = "prefill: the layer split's hand-off buffers" ; 1316return false; 1317 } 1318if (m .tok_dev == nullptr ) { 1319/* 1320DPCT1000: Error handling if-stmt was detected but could not be 1321rewritten. 1322*/ 1323if (const dpct::err0 e = DPCT_CHECK_ERROR ( 1324m .tok_dev = sycl::malloc_device < int32_t > ( 1325 (size_t )chunk , dpct::get_in_order_queue ())); 1326e != 0 ) { 1327/* 1328DPCT1009: SYCL reports errors using exceptions and does not use 1329error codes. Please replace the "get_error_string_dummy(...)" with a 1330real error-handling function. 1331*/ 1332/* 1333DPCT1001: The statement could not be removed. 1334*/ 1335err = std::string ("prefill: the token id buffer (" )+ 1336 dpct::get_error_string_dummy (e )+ ")" ; 1337return false; 1338 } 1339m .owned .push_back (m .tok_dev ); 1340m .tok_host .resize ((size_t )chunk ); 1341 } 1342/* 1343DPCT1025: The SYCL queue is created ignoring the flag and priority 1344options. 1345*/ 1346// 0.1.43: the expert copies on the GPU's copy engine when the device has one the SYCL runtime does not use itself 1347// (the Level Zero v2 adapter runs every queue on the compute engine: ~0.8 s of a 4K prompt on a B70 is the compute 1348// engine waiting for its own DMA). nullptr: the ordinary in-order queue. STRATA_COPY_ENGINE=0 turns it off. 1349m .copy = strata::make_copy_engine_queue ("the prompt path's expert" ); 1350const char * copy_profiling = std::getenv ("STRATA_SYCL_PREFILL_COPY_PROFILING" ); 1351if (m .copy == nullptr && copy_profiling && std::strcmp (copy_profiling ,"0" )== 0 ) { 1352m .copy_without_profiling = strata::make_prefill_copy_queue (* m .cs ); 1353m .copy = m .copy_without_profiling .get (); 1354 } 1355if (m .copy == nullptr && 1356DPCT_CHECK_ERROR (m .copy = dpct::get_current_device ().create_queue (true))!= 0 ) { 1357err = "prefill: copy stream" ;return false; 1358 } 1359const size_t T = (size_t )chunk ; 1360m .T_max = chunk ; 1361m .borrowed = borrow != nullptr ; 1362bool ok = true; 1363// one-time: events, the stager, the host buffers (for the largest chunk), the identity page table 1364for (int i = 0 ;i < ring_cap ();++ i ) { 1365if (DPCT_CHECK_ERROR (m .copied [i ]= new sycl::event ())!= 0 )ok = false; 1366if (DPCT_CHECK_ERROR (m .used [i ]= new sycl::event ())!= 0 )ok = false; 1367 } 1368if (!m .stager ) { 1369m .stager = std::make_unique < Stager > (); 1370const int hw = (int ) std::thread::hardware_concurrency (); 1371const char * stv = std::getenv ("STRATA_STAGER_THREADS" );// D-5: the host copy threads of unpinned blobs 1372// A GGUF read in place (UD-Q4_K_XL beyond its RAM budget): most of a chunk's blobs are page faults on the 1373// SSD, so the copies need many reads in flight - 32 threads and a 128-deep ring read a 4K chunk in 29 s 1374// instead of 71 s on an RTX 5070 / NVMe PC (4 threads, 16 deep: the defaults, kept for every other source) 1375bool files = false; 1376for (int64_t l = 0 ;src != nullptr && !files && l < g .n_layers ;++ l ) 1377for (int64_t e = 0 ; !files && e < g .n_expert ;++ e )files = src -> transient (l ,e ); 1378const int threads = stv ? std::clamp (std::atoi (stv ),1 ,32 ) :files ?32 : std::max (2 , std::min (4 ,hw /4 )); 1379if (files && std::getenv ("STRATA_STAGER_RING" )== nullptr )m .stager -> kRing = 4 * threads ; 1380if (!m .stager -> init ((size_t )MAXBLOB (),threads ))ok = false; 1381 } 1382m .steps_host .resize (T * strata::kernels::kStepCount ); 1383m .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 ); 1384 { 1385const size_t need = 3 * T * K + (size_t ) (2 * (m .g -> n_expert + m .g -> n_expert /MMQ_GROUP + 2 )); 1386// SYCL port: the *copy* arm is the default. On the mapped arm the GPU reads these tables straight out of 1387// mapped host memory, per layer; copying them first is measurably faster on a PCIe-attached pair and 1388// token-identical - 4,106 tokens 1,303 -> 1,335 tok/s, 16,380 tokens 1,622 -> 1,665, the 10,938-token chat 1389// prompt 1,576 -> 1,617, decode unchanged (round 46). STRATA_GROUP_COPY=0 restores the mapped arm. 1390const char * gc = std::getenv ("STRATA_GROUP_COPY" ); 1391const bool group_copy = gc == nullptr || gc [0 ]!= '0' ; 1392if (m .grp_n < need && !group_copy ) { 1393if (m .grp_host ) sycl::free (m .grp_host , dpct::get_in_order_queue ()); 1394m .grp_host = m .grp_dev = nullptr ; 1395m .grp_n = m .grp_tk = 0 ; 1396void * h = nullptr ,* d = nullptr ; 1397if (!force_pageable ()&& 1398/* 1399DPCT1048: The original value cudaHostAllocMapped is not 1400meaningful in the migrated code and was removed or replaced with 14010. You may need to check the migrated code. 1402*/ 1403/* 1404DPCT1048: The original value cudaHostAllocPortable is not 1405meaningful in the migrated code and was removed or replaced with 14060. You may need to check the migrated code. 1407*/ 1408DPCT_CHECK_ERROR (h = (void * )sycl::malloc_host ( 1409need * 4 , dpct::get_in_order_queue ()))== 14100 && 1411DPCT_CHECK_ERROR (d = (void * )h )== 0 ) { 1412m .grp_host = (int32_t * )h ; 1413m .grp_dev = (int32_t * )d ; 1414m .grp_n = need ; 1415m .grp_tk = T * K ; 1416 }else {// the copies, as before 1417if (h ) sycl::free (h , dpct::get_in_order_queue ()); 1418/* 1419DPCT1026: The call to cudaGetLastError was removed because 1420this functionality is redundant in SYCL. 1421*/ 1422 } 1423 } 1424 } 1425for (int b = 0 ;b < 2 ;++ b ) { 1426if (!m .ple_emb_host [b ]&& 1427/* 1428DPCT1048: The original value cudaHostAllocDefault is not 1429meaningful in the migrated code and was removed or replaced with 0. 1430You may need to check the migrated code. 1431*/ 1432 (force_pageable ()|| 1433DPCT_CHECK_ERROR ( 1434m .ple_emb_host [b ]= (float * )sycl::malloc_host ( 1435 (size_t )T * N * 4 , dpct::get_in_order_queue ()))!= 0 )) { 1436/* 1437DPCT1026: The call to cudaGetLastError was removed because this 1438functionality is redundant in SYCL. 1439*/ 1440m .ple_pageable [b ].resize ( 1441T * N );// pageable: the upload is staged before it returns 1442m .ple_emb_host [b ]= m .ple_pageable [b ].data (); 1443 } 1444if (!m .ple_copied [b ]&& 1445DPCT_CHECK_ERROR (m .ple_copied [b ]= new sycl::event ())!= 0 ) 1446ok = false; 1447if (!m .ple_done_seq ) { 1448m .ple_done_seq = sycl::malloc_host < uint64_t > (2 , dpct::get_in_order_queue ()); 1449if (m .ple_done_seq )m .ple_done_seq [0 ]= m .ple_done_seq [1 ]= 0 ; 1450else ok = false; 1451 } 1452m .ple_rows [b ].resize (T * strata::kernels::PLE_N_HEADS ); 1453 } 1454if (ss .qsa_states [ss .qsa_primary ()].kv_mode == 1 ) {// KV streaming: the staging pool's identity page table 1455const int64_t pages = ss .qsa_states [ss .qsa_primary ()].n_pages ; 1456 std::vector < int32_t > ident ((size_t )pages ); 1457for (int64_t i = 0 ;i < pages ;++ i )ident [(size_t )i ]= (int32_t )i ; 1458if (DPCT_CHECK_ERROR ( 1459m .ident_table = (int32_t * )sycl::malloc_device ( 1460ident .size ()* 4 , dpct::get_in_order_queue ()))!= 0 || 1461/* 1462DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 1463assuming in the original code the source host memory is pageable 1464memory. If the memory is not pageable, call wait() on event return 1465by memcpy API to ensure synchronization behavior. 1466*/ 1467DPCT_CHECK_ERROR (dpct::get_in_order_queue ().memcpy ( 1468m .ident_table ,ident .data (),ident .size ()* 4 ).wait ())!= 0 ) 1469ok = false; 1470else 1471m .owned .push_back (m .ident_table ); 1472 } 1473if (!ok ) {err = "prefill: host buffers or events for a chunk of " + std::to_string (chunk )+ " tokens" ;return false; } 1474Alloc o ; 1475o .base = (uint8_t * )borrow ; 1476o .cap = borrow_bytes ; 1477o .owned = & m .owned ; 1478 { 1479uint16_t * gs = o .take < uint16_t > ((size_t )GEMM_SCRATCH ,ok ); 1480void * ws = o .take < uint8_t > (GEMM_WS ,ok ); 1481if (!ok ) {err = "prefill: GEMM scratch does not fit" ;return false; } 1482if (!m .gemm .init_external (stream ,gs ,GEMM_SCRATCH ,ws ,GEMM_WS ,err ))return false; 1483// this stage's device decides, once, here (init runs on the stage's own device): its gr_* kernels write the 1484// image its GEMMs read, and set_act_f16 writes that device's symbol 1485const core::OnDevice on_stage (m .device ); 1486m .f16_io = prompt_f16 (); 1487m .gemm .set_f16_io (m .f16_io ); 1488set_act_f16 (m .f16_io ); 1489 } 1490if (!carve (T ,& o )) { 1491size_t fb = 0 ,tb = 0 ; 1492/* 1493DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions 1494for device information which may not be supported by all compilers or 1495runtimes. You may need to adjust the code. 1496*/ 1497 dpct::get_current_device ().get_memory_info (fb ,tb ); 1498/* 1499DPCT1010: SYCL uses exceptions to report errors and does not use 1500the error codes. The cudaGetLastError function call was replaced with 0. 1501You need to rewrite this code. 1502*/ 1503 (void )0 ; 1504err = "prefill: device buffers for a chunk of " + std::to_string (chunk )+ " tokens do not fit (" + 1505 std::to_string (fb >>20 )+ " of " + std::to_string (tb >>20 )+ " MiB free at the failure; " + 1506 std::to_string (o .used >>20 )+ " MiB taken, the failing buffer wanted " + 1507 std::to_string (o .failed_bytes >>20 )+ " MiB)" ; 1508return false; 1509 } 1510return true; 1511} 1512catch (sycl::exception const & exc ) { 1513 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1514 <<", line:" <<__LINE__ << std::endl ; 1515 std::exit (1 ); 1516} 1517 1518// Every device buffer of a chunk of T tokens, from the Alloc `alloc` (after the GEMM scratch and workspace): `init` 1519// once, and `relayout` for a request's own chunk. The order is `bytes_needed`'s. 1520bool Prefill ::carve (size_t T ,void * alloc ) { 1521Impl & m = * impl_ ; 1522Alloc & o = * static_cast < Alloc *> (alloc ); 1523const core::ModelGeometry & g = * m .g ; 1524 core::SessionState & ss = * m .ss ; 1525bool ok = true; 1526m .emb = o .take < float > (T * N ,ok );m .R = o .take < float > (T * D ,ok ); 1527m .xn = gr_unfused () ?o .take < float > (T * D ,ok ) :nullptr ;// F-1: not needed (gr_mix_r reads R) 1528m .grs = o .take < float > (T * HC ,ok ); 1529m .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 ); 1530m .gated = o .take < float > (T * D ,ok );m .inj = o .take < float > (T * HC ,ok ); 1531m .mixed = o .take < float > (T * N ,ok );m .mixed_bf = o .take < uint16_t > (T * N ,ok ); 1532m .mixed_h = o .take < uint16_t > (T * N ,ok );m .bo = o .take < float > (T * N ,ok ); 1533if (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 ); } 1534if (bf16x2 (m .f16_io ))m .mixed_bf_lo = o .take < uint16_t > (T * N ,ok ); 1535m .steps_dev = o .take < int32_t > (T * strata::kernels::kStepCount ,ok ); 1536 strata::kernels::QsaShapes s = core::qsa_shapes (g ); 1537m .cap = strata::kernels::qsa_selection_width (strata::kernels::kTopkMaxCells ,s ); 1538m .attn_batch = attn_batch_for (T ); 1539m .max_blocks = ss .qsa_states [ss .qsa_primary ()].max_cells /s .idx_block + 2 ; 1540 { 1541// one region for the attention half's and the MoE half's scratch (see gdn_set_bytes) 1542const bool fz = fused_layout (T ,m .src != nullptr ); 1543m .fused_bufs = fz ; 1544const MoeBufs mb = moe_bufs (T ,m .g -> n_expert ,fz ); 1545const uint64_t region = std::max ({gdn_set_bytes (T ),qsa_set_bytes (T ,m .cap ,m .max_blocks ,m .sel_batch , 1546m .attn_batch ,s ),moe_set_bytes (T ,m .g -> n_expert ,fz )}); 1547uint8_t * base = o .take < uint8_t > ((size_t )region ,ok ); 1548m .region = base ; 1549m .region_bytes = region ; 1550Alloc a ; 1551a .base = base ;a .cap = region ;a .owned = & m .owned ; 1552m .qkv = a .take < float > (T * C ,ok );m .z = a .take < float > (T * ZV ,ok );m .ab = a .take < float > (T * 2 * HV ,ok ); 1553m .gate = a .take < float > (T * HV ,ok );m .beta = a .take < float > (T * HV ,ok );m .hbuf = a .take < float > (T * C ,ok ); 1554m .y = a .take < float > (T * ZV ,ok );m .y_h = a .take < uint16_t > (T * (ZV + (pf_pad () ?ZV_PAD :0 )),ok ); 1555Alloc b ; 1556b .base = base ;b .cap = region ;b .owned = & m .owned ; 1557m .Kc = b .take < float > (T * kKvW ,ok );m .Vc = b .take < float > (T * kKvW ,ok );m .Qf = b .take < float > (T * kQFull ,ok ); 1558m .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 ); 1559m .attn = b .take < float > (T * ZV ,ok );m .attn_h = b .take < uint16_t > (T * (ZV + (pf_pad () ?ZV_PAD :0 )),ok ); 1560m .sel_ids = b .take < int32_t > (T * (size_t )m .cap ,ok ); 1561m .sel_scores = b .take < float > ((size_t )m .sel_batch * (size_t )m .max_blocks ,ok ); 1562m .attn_scratch = b .take < float > ((size_t )m .attn_batch * strata::kernels::qsa_decode_attn_scratch_floats (m .cap ,s ),ok ); 1563Alloc c ; 1564c .base = base ;c .cap = region ;c .owned = & m .owned ; 1565m .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 ); 1566m .slot_dev = c .take < int32_t > (T * K ,ok );m .src_dev = c .take < int32_t > (T * K ,ok ); 1567const MmqPlan & mp = mmq_plan (); 1568m .Xs = mp .fallback ?c .take < uint16_t > (T * K * N ,ok ) :nullptr ; 1569m .GU = c .take < float > (mb .gu ,ok ); 1570m .Hh = mp .fallback ?c .take < uint16_t > (T * K * kFF ,ok ) :nullptr ; 1571m .Dm = c .take < float > (T * K * N ,ok ); 1572m .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 ); 1573m .shared = c .take < float > (T * N ,ok );m .sg = c .take < float > (T ,ok ); 1574if (mp .any ) { 1575m .Xq = c .take < uint8_t > (mb .xq ,ok ); 1576m .H = c .take < float > (mb .h ,ok ); 1577m .Hq = c .take < uint8_t > (mb .hq ,ok ); 1578 } 1579if (base == nullptr )ok = false; 1580 } 1581for (int i = 0 ;i < dq_slots ();++ i ) {m .dq_gu [i ]= o .take < uint16_t > (kFF2 * kEmbd ,ok );m .dq_d [i ]= o .take < uint16_t > (kEmbd * kFF ,ok ); } 1582if (mmq_plan ().any ) { 1583const MmqPlan & mp = mmq_plan (); 1584m .ids_identity = o .take < int32_t > (T * K ,ok ); 1585m .bounds_dev = o .take < int32_t > ((size_t ) (2 * (m .g -> n_expert + m .g -> n_expert /MMQ_GROUP + 2 )),ok ); 1586m .grp_gu = o .take < uint8_t > (MMQ_GROUP * mp .gu_max + MMQ_TAIL ,ok ); 1587m .grp_d = o .take < uint8_t > (MMQ_GROUP * mp .d_max + MMQ_TAIL ,ok ); 1588// (written at every run's start, not here: when serving, these are live expert-cache slots until a request 1589// lends them - a write now would corrupt a resident expert) 1590if (!m .mmq_ctx )m .mmq_ctx = std::make_unique < mmq::Context > (); 1591 } 1592m .ring = ring_slots (T ); 1593const int ring_n = std::max (m .ring ,stage_slots ());// A770 port: STRATA_PF_XMX=2 holds a group of staged experts 1594if (o .base == nullptr && ring_n > 0 ) { 1595// OWNED buffers: the ring in ONE allocation. 384 separate 2.7 MiB cudaMallocs each round up to a 2 MiB page 1596// (~1.3 MiB a slot, ~0.5 GiB in all) that no count ever saw. A borrowed region keeps its per-slot layout (and 1597// so its price, `bytes_needed`: the loans' slot counts do not move). 1598uint8_t * ring_base = o .take < uint8_t > ((size_t )ring_n * (size_t )MAXBLOB (),ok ); 1599for (int i = 0 ;ok && i < ring_n ;++ i ) { 1600m .stage_dev [i ]= ring_base + (size_t )i * (size_t )MAXBLOB (); 1601m .stage_live [i ]= false; 1602m .used_of [i ]= i ; 1603 } 1604 }else { 1605for (int i = 0 ;i < ring_n ;++ i ) { 1606m .stage_dev [i ]= o .take < uint8_t > ((size_t )MAXBLOB (),ok ); 1607m .stage_live [i ]= false;// a new buffer: nothing of an earlier layout to wait for 1608m .used_of [i ]= i ; 1609 } 1610 } 1611m .ple_emb = o .take < float > (T * N ,ok ); 1612m .ple_norm = o .take < float > ((size_t ) strata::kernels::NG_HC_DIM ,ok ); 1613take_stage (o ,ss ,s ,m .stage ,ok ); 1614m .T = (int64_t )T ; 1615return ok ; 1616} 1617 1618bool Prefill ::relayout (int64_t chunk ,void * borrow ,uint64_t borrow_bytes , 1619 std::string & err ,int64_t /*tail*/ )try { 1620Impl & m = * impl_ ; 1621if (!m .borrowed || borrow == nullptr || chunk <=0 || chunk > m .T_max ) { 1622err = "prefill: relayout needs borrowed buffers and a chunk of at most " + std::to_string (m .T_max ); 1623return false; 1624 } 1625if (DPCT_CHECK_ERROR (m .cs -> wait ())!= 0 || 1626DPCT_CHECK_ERROR (m .copy -> wait ())!= 0 || 1627 (m .kv_copy && DPCT_CHECK_ERROR (m .kv_copy -> wait ())!= 0 )) { 1628err = "prefill: relayout: the stream failed" ; 1629return false; 1630 } 1631bool ok = true; 1632Alloc o ; 1633o .base = (uint8_t * )borrow ; 1634o .cap = borrow_bytes ; 1635o .owned = & m .owned ; 1636uint16_t * gs = o .take < uint16_t > ((size_t )GEMM_SCRATCH ,ok ); 1637void * ws = o .take < uint8_t > (GEMM_WS ,ok ); 1638if (ok )m .gemm .rebind (gs ,GEMM_SCRATCH ,ws ,GEMM_WS ); 1639if (!ok || !carve ((size_t )chunk ,& o )) { 1640size_t fb = 0 ,tb = 0 ; 1641/* 1642DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions 1643for device information which may not be supported by all compilers or 1644runtimes. You may need to adjust the code. 1645*/ 1646 dpct::get_current_device ().get_memory_info (fb ,tb ); 1647/* 1648DPCT1010: SYCL uses exceptions to report errors and does not use 1649the error codes. The cudaGetLastError function call was replaced with 0. 1650You need to rewrite this code. 1651*/ 1652 (void )0 ; 1653err = "prefill: device buffers for a chunk of " + std::to_string (chunk )+ " tokens do not fit (" + 1654 std::to_string (fb >>20 )+ " of " + std::to_string (tb >>20 )+ " MiB free at the failure; " + 1655 std::to_string (o .used >>20 )+ " MiB taken, the failing buffer wanted " + 1656 std::to_string (o .failed_bytes >>20 )+ " MiB)" ; 1657return false; 1658 } 1659return true; 1660} 1661catch (sycl::exception const & exc ) { 1662 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1663 <<", line:" <<__LINE__ << std::endl ; 1664 std::exit (1 ); 1665} 1666 1667int64_t Prefill ::chunk ()const {return impl_ -> T ; } 1668 1669bool Prefill ::draft_kv (core::MtpDrafter & mtp ,const float * R_rows ,const int32_t * next_tokens ,int64_t n ,int64_t cell0 , 1670 std::string & err ,const char ** why ) { 1671Impl & m = * impl_ ; 1672auto decline = [& ](const char * reason ) {if (why != nullptr )* why = reason ;return false; }; 1673static const bool off = [] {const char * v = std::getenv ("STRATA_MTP_BATCH" );return v != nullptr && v [0 ]== '0' ; }(); 1674// A ring (KV streaming: the drafter's window, page p in slot p % n_slots over a host copy) takes the same appends 1675// with its own page table and host copy, as a streamed main layer does; the cells written are those the window can 1676// still reach (r0 below), which the ring holds, so no two of them share a slot. STRATA_MTP_BATCH_RING=0: the 1677// drafter's own pass for a ring (the A/B). 1678static const bool ring_ok = [] {const char * v = std::getenv ("STRATA_MTP_BATCH_RING" );return v == nullptr || v [0 ]!= '0' ; }(); 1679 core::QsaState & st = mtp .kv_state_rw (); 1680if (off )return decline ("STRATA_MTP_BATCH=0" ); 1681if (n <=0 || m .g == nullptr || m .region == nullptr )return decline ("no prompt scratch region on this path" ); 1682if (st .kv_mode != 0 && !(st .kv_mode == 2 && ring_ok )) 1683return 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" ); 1684if (st .kv_hybrid )return decline ("the drafter's K/V is hybrid (kv_hybrid)" ); 1685if (mtp .device ()!= m .device )return decline ("the drafter is on another device than this prefill path" ); 1686const auto t0 = Clock ::now (); 1687const core::ModelGeometry & g = * m .g ; 1688const int64_t Nn = g .n_embd ,HCN = g .hc * g .n_embd ,KV = g .n_head_kv * g .head_dim ; 1689constexpr int kQ8_0 = 8 ;// GGML_TYPE_Q8_0 1690const float * w_ne = mtp .tensor_f32 ("pre_fc_norm_embedding.weight" ); 1691const void * w_fe = mtp .tensor_q8 ("fc_embedding.weight" ); 1692const float * w_nh = mtp .tensor_f32 ("pre_fc_norm_hidden.weight" ); 1693const void * w_fh = mtp .tensor_q8 ("fc_hidden.weight" ); 1694const float * w_hn = mtp .tensor_f32 ("attn_hyper_connection.hc_norm.weight" ); 1695const uint16_t * w_dn = mtp .tensor_bf16 ("attn_hyper_connection.input_mix_weight_down.weight" ); 1696const uint16_t * w_up = mtp .tensor_bf16 ("attn_hyper_connection.input_mix_weight_up.weight" ); 1697const void * w_k = mtp .tensor_q8 ("self_attn.k_proj.weight" ); 1698const void * w_v = mtp .tensor_q8 ("self_attn.v_proj.weight" ); 1699const float * w_kn = mtp .tensor_f32 ("self_attn.k_norm.weight" ); 1700if (!w_ne || !w_fe || !w_nh || !w_fh || !w_hn || !w_dn || !w_up || !w_k || !w_v || !w_kn ) 1701return decline ("a drafter tensor is missing (Q8_0 projections / norms)" ); 1702const core::NativeEmbed * nemb = core::native_embed (); 1703const core::WeightRef * wemb = nemb ?nullptr :m .wt -> find ("token_embd.weight" ); 1704if (!nemb && (wemb == nullptr || wemb -> codebook_iq4nl || wemb -> ne0 != g .n_embd || wemb -> group_elems <=0 || 1705 (wemb -> code_bits != 2 && wemb -> code_bits != 4 && wemb -> code_bits != 8 ))) 1706return decline ("the token embedding is not gatherable on this path" ); 1707// the cells the drafter's window can still reach 1708const int64_t r0 = std::max < int64_t > (0 ,mtp .first_needed ()- cell0 ); 1709if (r0 >=n )return true; 1710// per row: emb/e2 (N), en16 (N half), hn/h2/Rm/gated (HCN), hn16/xn16 (HCN half), lo (LR) + lo16, grs, mixed (N) + 1711// mixed_h, K and V (KV each), the token id 1712// E-9: the drafter's Q8_0 matrices through Q8_1 x Q8_0 MMQ - its own pass's integer dot products (mmvq), so 1713// its K/V stay close to what the drafter computes itself; STRATA_MTP_BATCH_F16=1: FP16 GEMMs (the A/B) 1714static const bool f16_only = [] {const char * v = std::getenv ("STRATA_MTP_BATCH_F16" );return v && v [0 ]== '1' ; }(); 1715const bool q8 = !f16_only && mmq::built ()&& mmq::fits (kQ8_0 ,Nn )&& mmq::fits (kQ8_0 ,KV );// #420 1716const uint64_t per_row = 4 * (2 * Nn + 4 * HCN + LR + HC + Nn + 2 * KV + 1 )+ 2 * (Nn + 2 * HCN + LR + Nn )+ 64 + 1717 (q8 ? (uint64_t ) mmq::q8_bytes (g .hc ,Nn )+ 4 * g .hc :0 ); 1718// SYCL port: B is the batch buffers' capacity, not the row count (each batch uses nb <= B rows), so a short 1719// prompt gets 64-row buffers instead of the per-6-token fallback (19 tokens: 106 ms there, a few ms here) 1720const int64_t cap = (int64_t ) (m .region_bytes /per_row )& ~(int64_t )63 ; 1721if (cap < 64 )return decline ("too little scratch for a 64-row batch" ); 1722int64_t B = std::min < int64_t > (std::max < int64_t > (n - r0 ,64 ),cap ); 1723if (st .kv_mode == 2 )// #453: a ring: one batch's cells must not share a slot (a batch can straddle one page more) 1724B = std::min < int64_t > (B , ((st .n_slots - 1 )* strata::kernels::qsa_real_shapes ().page_size )& ~(int64_t )63 ); 1725if (B < 64 )return decline ("too little scratch for a 64-row batch" ); 1726uint8_t * q = m .region ; 1727auto carve = [& ](size_t bytes ) {void * p = q ;q += (bytes + 255 )& ~(size_t )255 ;return p ; }; 1728float * emb = (float * )carve ((size_t )B * Nn * 4 ); 1729float * e2 = (float * )carve ((size_t )B * Nn * 4 ); 1730uint16_t * en16 = (uint16_t * )carve ((size_t )B * Nn * 2 ); 1731float * hn = (float * )carve ((size_t )B * HCN * 4 ); 1732float * h2 = (float * )carve ((size_t )B * HCN * 4 ); 1733float * Rm = (float * )carve ((size_t )B * HCN * 4 ); 1734float * gated = (float * )carve ((size_t )B * HCN * 4 ); 1735uint16_t * hn16 = (uint16_t * )carve ((size_t )B * HCN * 2 ); 1736uint16_t * xn16 = (uint16_t * )carve ((size_t )B * HCN * 2 ); 1737float * lo = (float * )carve ((size_t )B * LR * 4 ); 1738uint16_t * lo16 = (uint16_t * )carve ((size_t )B * LR * 2 ); 1739float * grs = (float * )carve ((size_t )B * HC * 4 ); 1740float * mixed = (float * )carve ((size_t )B * Nn * 4 ); 1741uint16_t * mixed_h = (uint16_t * )carve ((size_t )B * Nn * 2 ); 1742float * Kc = (float * )carve ((size_t )B * KV * 4 ); 1743float * Vc = (float * )carve ((size_t )B * KV * 4 ); 1744int32_t * tok = (int32_t * )carve ((size_t )B * 4 ); 1745void * xq = q8 ?carve (mmq::q8_bytes (B * g .hc ,Nn )) :nullptr ; 1746int32_t * ident = q8 ? (int32_t * )carve ((size_t )B * g .hc * 4 ) :nullptr ; 1747int32_t * bnd = q8 ? (int32_t * )carve (16 ) :nullptr ; 1748if ((uint64_t ) (q - m .region )> m .region_bytes )return decline ("the batch buffers do not fit the scratch region" ); 1749static const bool timing = std::getenv ("STRATA_DRAFT_TIMING" )!= nullptr ;// debug: where this pass's time goes 1750if (timing )m .cs -> wait (); 1751const auto ti0 = Clock ::now (); 1752if (!mtp .idle (err ))return false;// the drafter's own stream (its graph uploads) before this writes its K/V 1753const double ms_idle = ms_since (ti0 ); 1754const auto tl0 = Clock ::now (); 1755 strata::kernels::QsaShapes s = core::qsa_shapes (g ); 1756 std::vector < int32_t > tk ((size_t )B ); 1757if (q8 ) { 1758if (!m .mmq_ctx )m .mmq_ctx = std::make_unique < mmq::Context > (); 1759 mmq::iota (ident ,B * g .hc ,m .cs ); 1760 } 1761// 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) 1762auto proj = [& ](const float * x ,const uint16_t * x16 ,const void * w ,float * y ,int64_t rows ,int64_t n_out , 1763int64_t k ,int slot ) { 1764if (!q8 ) {m .gemm .native (x16 ,kQ8_0 ,w ,y ,rows ,n_out ,k );return ; } 1765 mmq::quantize (x ,nullptr ,xq ,kQ8_0 ,k ,k ,rows ,m .cs ); 1766 mmq::Product p ; 1767p .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 ); 1768p .n = 1 ;p .xq = xq ;p .bounds = bnd + 2 * slot ;p .ids = ident ;p .total_rows = rows ;p .max_rows = rows ; 1769p .dst = y ;p .ld_dst = n_out ; 1770m .mmq_ctx -> run (p ,m .cs ); 1771 }; 1772for (int64_t b0 = r0 ;b0 < n ;b0 += B ) { 1773const int64_t nb = std::min (B ,n - b0 ),c0 = cell0 + b0 ; 1774for (int64_t i = 0 ;i < nb ;++ i )tk [(size_t )i ]= next_tokens [b0 + i ]; 1775const int32_t bh [4 ]= {0 , (int32_t )nb ,0 , (int32_t ) (nb * g .hc )}; 1776/* 1777DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. 1778While the origin API might be synchronous, it depends on the type of 1779operand memory, so you may need to call wait() on event return by memcpy 1780API to ensure synchronization behavior. 1781*/ 1782if (q8 && DPCT_CHECK_ERROR (m .cs -> memcpy (bnd ,bh ,sizeof bh ))!= 0 ) { 1783err = "prefill: the draft bounds' upload failed" ; 1784return false; 1785 } 1786/* 1787DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. 1788While the origin API might be synchronous, it depends on the type of 1789operand memory, so you may need to call wait() on event return by memcpy 1790API to ensure synchronization behavior. 1791*/ 1792if (DPCT_CHECK_ERROR (m .cs -> memcpy (tok ,tk .data (), (size_t )nb * 4 ))!= 17930 ) { 1794err = "prefill: the draft tokens' upload failed" ; 1795return false; 1796 } 1797// the input branches: the next token's embedding, and this cell's final residual rows 1798if (nemb ) { 1799nemb -> gather_dev (tok ,nb ,emb ,m .cs ); 1800 }else { 1801const auto * codes = (const uint8_t * )wemb -> data ; 1802const auto * scales = (const float * ) (codes + wemb -> codes_bytes ); 1803const auto * offsets = wemb -> has_offset ? (const float * ) (codes + wemb -> codes_bytes + wemb -> scales_bytes ) 1804 :nullptr ; 1805 strata::kernels::embedding_gather_dev (codes ,scales ,offsets ,tok , (int )nb ,wemb -> ne0 ,wemb -> code_bits , 1806wemb -> code_bias ,wemb -> group_elems , 1807 (uint64_t ) (wemb -> ne0 / (8 /wemb -> code_bits )), 1808 (uint64_t ) (wemb -> ne0 /wemb -> group_elems ),emb ,m .cs ); 1809 } 1810rms_rows (emb ,w_ne ,nb ,Nn ,Nn ,EPS ,m .cs ); 1811if (!q8 )to_f16 (emb ,en16 ,nb * Nn ,m .cs ); 1812proj (emb ,en16 ,w_fe ,e2 ,nb ,Nn ,Nn ,0 ); 1813/* 1814DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. 1815While the origin API might be synchronous, it depends on the type of 1816operand memory, so you may need to call wait() on event return by memcpy 1817API to ensure synchronization behavior. 1818*/ 1819m .cs -> memcpy (hn ,R_rows + (size_t )b0 * HCN , (size_t )nb * HCN * 4 ); 1820if (mtp .hnorm_per_stream ())// --mtp-hnorm stream: as the drafter's own pass (mtp.cpp) 1821 strata::kernels::native_qsa_rms_norm_grouped (hn ,w_nh ,hn , (int )Nn , (int )g .hc , (int ) (nb * g .hc ),EPS ,m .cs ); 1822else 1823rms_rows (hn ,w_nh ,nb ,HCN ,HCN ,EPS ,m .cs ); 1824if (!q8 )to_f16 (hn ,hn16 ,nb * HCN ,m .cs ); 1825proj (hn ,hn16 ,w_fh ,h2 ,nb * g .hc ,Nn ,Nn ,1 );// every stream through fc_hidden 1826 strata::kernels::add_streams_broadcast (h2 ,e2 ,Rm ,Nn , (int )g .hc , (int )nb ,m .cs ); 1827// the attention hyper-connection's read (its mixed input only: this pass writes nothing back) 1828gr_norm_rs (Rm ,w_hn ,EPS ,grs ,xn16 ,nb ,m .cs ); 1829m .gemm .bf16 (xn16 ,w_dn ,lo ,nb ,LR ,HCN ); 1830gr_silu (lo ,lo16 ,nb ,m .cs ); 1831m .gemm .bf16 (lo16 ,w_up ,gated ,nb ,HCN ,LR ); 1832gr_mix_r (Rm ,grs ,w_hn ,gated ,mixed ,nullptr ,nb ,m .cs ,mixed_h ); 1833// K and V into the drafter's cache, as the prompt path's QSA layers append theirs 1834proj (mixed ,mixed_h ,w_k ,Kc ,nb ,KV ,Nn ,0 ); 1835proj (mixed ,mixed_h ,w_v ,Vc ,nb ,KV ,Nn ,0 ); 1836rms_rows (Kc ,w_kn ,nb * g .n_head_kv ,g .head_dim ,g .head_dim ,EPS ,m .cs ); 1837rope (Kc ,nb ,g .n_head_kv ,g .head_dim ,KV ,c0 , strata::kernels::rope_scaling (),m .cs ); 1838if (st .kv_rot ) {// rotated as the drafter's own decode stores them (mtp.cpp) 1839 strata::kernels::fwht256_inplace_cuda (Kc ,nb * g .n_head_kv ,m .cs ); 1840 strata::kernels::fwht256_inplace_cuda (Vc ,nb * g .n_head_kv ,m .cs ); 1841 } 1842if (st .kv_q4 ) { 1843 strata::kernels::kv_append_q4 (st .k_q4 ,st .v_q4 ,st .page_table ,c0 ,nb ,Kc ,Vc ,s ,m .cs ,& st .host ); 1844 }else { 1845kv_append (Kc ,Vc ,nb ,c0 ,st .page_table ,s .page_size ,st .kv_int8 ?nullptr :st .k_pool , 1846st .kv_int8 ?nullptr :st .v_pool ,st .k_q ,st .v_q ,st .k_scale ,st .v_scale ,m .cs ,& st .host ); 1847 } 1848 } 1849if (DPCT_CHECK_ERROR (m .cs -> wait ())!= 0 ) { 1850/* 1851DPCT1009: SYCL reports errors using exceptions and does not use 1852error codes. Please replace the "get_error_string_dummy(...)" with a 1853real error-handling function. 1854*/ 1855/* 1856DPCT1010: SYCL uses exceptions to report errors and does not use the 1857error codes. The cudaGetLastError function call was replaced with 0. You 1858need to rewrite this code. 1859*/ 1860err = std::string ("prefill: the draft layer's K/V: " )+ 1861 dpct::get_error_string_dummy (0 ); 1862return false; 1863 } 1864mtp .ms_prefill += ms_since (t0 ); 1865if (timing ) 1866 std::fprintf (stderr ,"strata draft kv: %lld cells from %lld (first needed %lld), batch %lld: drafter idle %.1f ms, " 1867"the batches %.1f ms, all %.1f ms\n" , (long long )n , (long long )cell0 , (long long ) (cell0 + r0 ), 1868 (long long )B ,ms_idle ,ms_since (tl0 ),ms_since (t0 )); 1869return true; 1870} 1871namespace { 1872// Layer split: STRATA_PREFILL_HELP=1 lends the idle stage's GPU (opt-in: the helped rows are computed in another MMQ 1873// grouping and round differently from the default, like STRATA_SPLIT_OWN). Unset or 0: every stage's prompt experts on 1874// its own GPU, as before. 1875bool split_help_env () { 1876static const bool v = [] {const char * e = std::getenv ("STRATA_PREFILL_HELP" );return e != nullptr && std::atoi (e )!= 0 ; }(); 1877return v ; 1878} 1879// The share of a stage's streamed experts the idle stage's GPU takes for a one-chunk prompt of T tokens (0: none). 1880// The streamed bytes are the same at any T; the hand-over (the activations there, the rows back) grows with T and is 1881// paid per layer whatever the share. Measured on 2x RTX 3090 (UD-Q4_K_XL, PCIe 4.0 x16 each, no P2P), fixed shares 1882// 0.2 / 0.3 / 0.4 against none: 1.5K tokens 749 / 820 / 908 (none 675), 3K 1335 / 1437 / 1328 (1262), 4K 1622 / 1620 / 1883// 1440 (1609), 6K 1811 / 1660 / 1471 (2038), 8K 1895 / 1804 / 1663 (2230) - the best share falls with T and from ~4K 1884// none pays, which this rule follows (0.41 at 1.5K, 0.32 at 3K, off from ~3.3K). 1885// STRATA_PREFILL_HELP_FRAC sets the share for every T. 1886double split_help_frac (int64_t T ) { 1887static const double fixed = [] { 1888const char * e = std::getenv ("STRATA_PREFILL_HELP_FRAC" ); 1889return e ? std::clamp (std::atof (e ),0.0 ,1.0 ) :-1.0 ; 1890 }(); 1891if (fixed >=0.0 )return fixed ; 1892const double f = std::min (0.45 ,0.5 - (double )T /16384.0 ); 1893return f >=0.3 ?f :0.0 ; 1894} 1895}// namespace 1896 1897bool Prefill ::set_stage_helper (Prefill * helper , std::string & err )try { 1898Impl & m = * impl_ ; 1899m .help_pp .reset (); 1900if (helper == nullptr || helper == this || !split_help_env ())return true; 1901const Impl & h = * helper -> impl_ ; 1902if (m .device < 0 || h .device < 0 || h .device == m .device || !mmq_plan ().any )return true; 1903auto pp = std::make_unique < PeerPrefill > (); 1904pp -> peer = nullptr ;// stream-only: it holds no experts, it streams a share of this stage's 1905pp -> compact = true; 1906pp -> p2p = false;// the mapped host route, whether or not the cards could reach each other (measured there) 1907pp -> out_pipe = true; 1908bool ok ; 1909 { 1910const core::OnDevice on (m .device ); 1911ok = DPCT_CHECK_ERROR (pp -> ev_in = new sycl::event ())== 0 ; 1912 } 1913int prev = 0 ; 1914prev = dpct::get_current_device_id (); 1915pp -> dev = h .device ; 1916/* 1917DPCT1093: The "pp->dev" device may be not the one intended for use. 1918Adjust the selected device if needed. 1919*/ 1920 dpct::select_device (pp -> dev ); 1921/* 1922DPCT1025: The SYCL queue is created ignoring the flag and priority 1923options. 1924*/ 1925ok = ok && 1926DPCT_CHECK_ERROR ( 1927pp -> s = dpct::get_current_device ().create_queue (true))== 0 && 1928/* 1929DPCT1025: The SYCL queue is created ignoring the flag and priority 1930options. 1931*/ 1932DPCT_CHECK_ERROR ( 1933pp -> s_out = dpct::get_current_device ().create_queue (true))== 0 && 1934/* 1935DPCT1025: The SYCL queue is created ignoring the flag and priority 1936options. 1937*/ 1938DPCT_CHECK_ERROR ( 1939pp -> s_cp = dpct::get_current_device ().create_queue (true))== 0 && 1940DPCT_CHECK_ERROR (pp -> ev_done = new sycl::event ())== 0 ; 1941for (int i = 0 ;ok && i < PeerPrefill ::kGrpEv ;++ i ) 1942ok = DPCT_CHECK_ERROR (pp -> ev_grp [i ]= new sycl::event ())== 0 ; 1943for (int b = 0 ;ok && b < 2 ;++ b ) 1944ok = DPCT_CHECK_ERROR (pp -> ev_dm [b ]= new sycl::event ())== 0 ; 1945// the ring's events; its slots are the helper stage's own ring, bound per prompt (bind_stage_helper) 1946pp -> pcopied .assign ((size_t )kSplitHelpRing ,nullptr ); 1947pp -> pused .assign ((size_t )kSplitHelpRing ,nullptr ); 1948for (int i = 0 ;ok && i < kSplitHelpRing ;++ i ) 1949ok = 1950DPCT_CHECK_ERROR (pp -> pcopied [(size_t )i ]= new sycl::event ())== 0 && 1951DPCT_CHECK_ERROR (pp -> pused [(size_t )i ]= new sycl::event ())== 0 ; 1952/* 1953DPCT1093: The "prev" device may be not the one intended for use. Adjust 1954the selected device if needed. 1955*/ 1956 dpct::select_device (prev ); 1957if (!ok ) {err = "prefill: the layer split's prompt help (streams and events)" ;return false; } 1958helper_ = helper ; 1959m .help_pp = std::move (pp ); 1960return true; 1961} 1962catch (sycl::exception const & exc ) { 1963 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1964 <<", line:" <<__LINE__ << std::endl ; 1965 std::exit (1 ); 1966} 1967 1968// A one-chunk prompt of T tokens on a layer split: binds the stream-only peer to the helper stage's prompt buffers 1969// (that stage idles until this one hands its rows over). False when it cannot help this prompt. 1970bool Prefill ::bind_stage_helper (int64_t T ) { 1971Impl & m = * impl_ ; 1972if (!m .help_pp || helper_ == nullptr || m .pp )return false; 1973const double frac = split_help_frac (T ); 1974if (frac <=0.0 || T < stream_all_min ()|| m .src == nullptr || m .ring <=STAGE || fused_ring ())return false; 1975const strata::kernels::cpu::ExpertLayout & lay = strata::kernels::cpu::expert_layout (); 1976for (int64_t l = stage_lb_ ;l < stage_le_ ;++ l ) { 1977if (!(mmq_plan ().any && mmq_plan ().layer [(size_t )l ]))return false;// the peer computes on MMQ only 1978if (lay .native && fused::native_supported (lay .fmt [(size_t )l ].gu_type ,lay .fmt [(size_t )l ].d_type ))return false; 1979 } 1980Impl & h = * helper_ -> impl_ ; 1981// the helper's buffers must be laid out for this chunk (the serve path lends every stage's at once) 1982if (h .T < T || h .mixed == nullptr || h .Xq == nullptr || h .Hq == nullptr || h .GU == nullptr || h .H == nullptr || 1983h .Dm == nullptr || h .src_dev == nullptr || h .ids_identity == nullptr || h .bounds_dev == nullptr || 1984h .grp_gu == nullptr || h .grp_d == nullptr || !h .mmq_ctx || h .ring <=STAGE ) 1985return false; 1986PeerPrefill & P = * m .help_pp ; 1987P .T_max = T ; 1988P .cap_rows = T * K ; 1989P .G = T ;// one expert never has more rows than the chunk has tokens 1990P .mixed = h .mixed ; 1991P .Xq_g = h .Xq ;// the helper's per-layer buffers hold T * K rows: a group's T fit 1992P .Hq_g = h .Hq ; 1993P .GU_g = h .GU ; 1994P .H_g = h .H ; 1995P .Dm_b [0 ]= h .Dm ; 1996P .Dm_b [1 ]= h .Dm + (size_t )T * N ; 1997P .src = h .src_dev ; 1998P .ident = h .ids_identity ; 1999P .bounds = h .bounds_dev ; 2000P .grp_gu = h .grp_gu ; 2001P .grp_d = h .grp_d ; 2002P .run_ctx = h .mmq_ctx .get (); 2003P .RP = std::min (h .ring ,kSplitHelpRing ); 2004P .pstage .assign (h .stage_dev ,h .stage_dev + P .RP ); 2005P .plive .assign ((size_t )P .RP ,0 ); 2006P .dm_live [0 ]= P .dm_live [1 ]= false; 2007P .out_pending = false; 2008P .ps_frac = frac ; 2009if (!P .p2p ) {// grown once to the largest chunk it helped 2010auto grow = [](auto *& p ,size_t & cap ,size_t n ) { 2011try { 2012if (cap >=n )return true; 2013if (p ) sycl::free (p , dpct::get_in_order_queue ()); 2014p = nullptr ; 2015cap = 0 ; 2016/* 2017DPCT1048: The original value cudaHostAllocPortable is not 2018meaningful in the migrated code and was removed or replaced with 0. 2019You may need to check the migrated code. 2020*/ 2021/* 2022DPCT1048: The original value cudaHostAllocMapped is not 2023meaningful in the migrated code and was removed or replaced with 0. 2024You may need to check the migrated code. 2025*/ 2026if (DPCT_CHECK_ERROR ( 2027p = (std::remove_reference_t < decltype(p )> )sycl::malloc_host ( 2028n * sizeof (* p ), dpct::get_in_order_queue ()))!= 0 ) { 2029/* 2030DPCT1026: The call to cudaGetLastError was removed because 2031this functionality is redundant in SYCL. 2032*/ 2033p = nullptr ; 2034return false; 2035 } 2036cap = n ; 2037return true; 2038 } 2039catch (sycl::exception const & exc ) { 2040 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 2041 <<", line:" <<__LINE__ << std::endl ; 2042 std::exit (1 ); 2043 } 2044 }; 2045size_t bounds_cap = P .host_bounds ?PeerPrefill ::kHostBounds :0 ; 2046if (!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 )|| 2047 !grow (P .host_src ,P .host_src_cap , (size_t )T * K )|| !grow (P .host_bounds ,bounds_cap ,PeerPrefill ::kHostBounds )) 2048return false; 2049 } 2050const core::OnDevice on (P .dev ); 2051 mmq::iota (P .ident ,T * K ,P .s );// the helper's row table: a refill may have overwritten its slots 2052return true; 2053} 2054 2055bool Prefill ::set_peer (core::PeerExperts * peer ,int64_t cap_rows , 2056 std::string & err )try { 2057Impl & m = * impl_ ; 2058if (peer == nullptr || !peer -> valid ()) {m .pp .reset ();return true; } 2059if (!peer -> p2p ()) {err = "prefill peer: the two GPUs cannot access each other (no P2P)" ;return false; } 2060if (!mmq_plan ().any ) {err = "prefill peer: needs the MMQ prompt path" ;return false; } 2061auto pp = std::make_unique < PeerPrefill > (); 2062pp -> peer = peer ; 2063pp -> T_max = m .T_max ; 2064pp -> cap_rows = std::max < int64_t > (1 , std::min < int64_t > (cap_rows ,m .T_max * K )); 2065const int64_t R = pp -> cap_rows ; 2066const MmqPlan & mp = mmq_plan (); 2067if (DPCT_CHECK_ERROR (pp -> ev_in = new sycl::event ())!= 0 ) { 2068err = "prefill peer: event" ;return false; 2069 } 2070int prev = 0 ; 2071prev = dpct::get_current_device_id (); 2072pp -> dev = peer -> device (); 2073/* 2074DPCT1093: The "pp->dev" device may be not the one intended for use. 2075Adjust the selected device if needed. 2076*/ 2077 dpct::select_device (pp -> dev ); 2078/* 2079DPCT1025: The SYCL queue is created ignoring the flag and priority 2080options. 2081*/ 2082bool ok = DPCT_CHECK_ERROR ( 2083pp -> s = dpct::get_current_device ().create_queue (true))== 0 && 2084DPCT_CHECK_ERROR (pp -> ev_done = new sycl::event ())== 0 ; 2085 { 2086const char * v = std::getenv ("STRATA_PF_PEER_OUT_PIPE" );// =0: one copy after the last group (the A/B) 2087pp -> out_pipe = (v == nullptr || std::atoi (v )!= 0 )|| pp -> compact ;// compact always pipes 2088 } 2089if (ok && pp -> out_pipe ) { 2090/* 2091DPCT1025: The SYCL queue is created ignoring the flag and priority 2092options. 2093*/ 2094ok = 2095DPCT_CHECK_ERROR ( 2096pp -> s_out = dpct::get_current_device ().create_queue (true))== 0 ; 2097for (int i = 0 ;ok && i < PeerPrefill ::kGrpEv ;++ i ) 2098ok = DPCT_CHECK_ERROR (pp -> ev_grp [i ]= new sycl::event ())== 0 ; 2099 } 2100auto take = [& ](size_t bytes )-> void * { 2101try { 2102void * p = nullptr ; 2103if (!ok || 2104DPCT_CHECK_ERROR (p = (void * )strata::malloc_device_guarded ( 2105bytes , dpct::get_in_order_queue ()))!= 0 ) { 2106ok = false;return nullptr ; 2107 } 2108pp -> owned .push_back (p ); 2109return p ; 2110 } 2111catch (sycl::exception const & exc ) { 2112 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 2113 <<", line:" <<__LINE__ << std::endl ; 2114 std::exit (1 ); 2115 } 2116 }; 2117pp -> mixed = (float * )take ((size_t )m .T_max * N * 4 ); 2118 { 2119const char * v = std::getenv ("STRATA_PF_PEER_COMPACT" ); 2120pp -> compact = v == nullptr || std::atoi (v )!= 0 ; 2121 } 2122if (pp -> compact ) { 2123pp -> cap_rows = m .T_max * K ;// no row cap: only the row tables grow with it 2124pp -> G = m .T_max ;// one expert never has more rows than the chunk has tokens 2125const int64_t Gr = pp -> G ; 2126pp -> Xq_g = take (mmq::q8_bytes (Gr ,N )); 2127pp -> Hq_g = take (mmq::q8_bytes (Gr ,kFF )); 2128pp -> GU_g = (float * )take ((size_t )Gr * kFF2 * 4 ); 2129pp -> H_g = (float * )take ((size_t )Gr * kFF * 4 ); 2130pp -> Dm_b [0 ]= (float * )take ((size_t )Gr * N * 4 ); 2131pp -> Dm_b [1 ]= (float * )take ((size_t )Gr * N * 4 ); 2132for (int b = 0 ;b < 2 && ok ;++ b ) 2133ok = DPCT_CHECK_ERROR (pp -> ev_dm [b ]= new sycl::event ())== 0 ; 2134const char * fs = std::getenv ("STRATA_PF_PEER_STREAM" ); 2135pp -> ps_frac = fs ? std::atof (fs ) :0.35 ;// measured: 0.25-0.5 all ~1950-1970 at 32K, 0.35 best 2136if (pp -> ps_frac > 0.0 && !mp .fallback && m .T_max >=stream_all_min ()) { 2137pp -> RP = 48 ; 2138if (const char * pr = std::getenv ("STRATA_PF_PEER_RING" );pr != nullptr )pp -> RP = std::atoi (pr ); 2139pp -> pstage .assign ((size_t )pp -> RP ,nullptr ); 2140pp -> pcopied .assign ((size_t )pp -> RP ,nullptr ); 2141pp -> pused .assign ((size_t )pp -> RP ,nullptr ); 2142pp -> plive .assign ((size_t )pp -> RP ,0 ); 2143/* 2144DPCT1025: The SYCL queue is created ignoring the flag and 2145priority options. 2146*/ 2147ok = ok && DPCT_CHECK_ERROR ( 2148pp -> s_cp = dpct::get_current_device ().create_queue ( 2149 true))== 0 ; 2150for (int i = 0 ;ok && i < pp -> RP ;++ i ) { 2151pp -> pstage [(size_t )i ]= (uint8_t * )take ((size_t )MAXBLOB ()); 2152ok = ok && 2153DPCT_CHECK_ERROR (pp -> pcopied [(size_t )i ]= 2154new sycl::event ())== 0 && 2155DPCT_CHECK_ERROR (pp -> pused [(size_t )i ]= 2156new sycl::event ())== 0 ; 2157 } 2158 }else { 2159pp -> ps_frac = 0.0 ; 2160 } 2161 }else { 2162pp -> Xq = take (mmq::q8_bytes (R ,N )); 2163pp -> Hq = take (mmq::q8_bytes (R ,kFF )); 2164pp -> GU = (float * )take ((size_t )R * kFF2 * 4 ); 2165pp -> H = (float * )take ((size_t )R * kFF * 4 ); 2166pp -> Dm = (float * )take ((size_t )R * N * 4 ); 2167 } 2168const int64_t Rt = pp -> cap_rows ; 2169pp -> src = (int32_t * )take ((size_t )Rt * 4 ); 2170pp -> ident = (int32_t * )take ((size_t )Rt * 4 ); 2171pp -> bounds = (int32_t * )take ((size_t ) (2 * (NE + NE /MMQ_GROUP + 2 ))* 4 ); 2172pp -> grp_gu = (uint8_t * )take (MMQ_GROUP * mp .gu_max + MMQ_TAIL ); 2173pp -> grp_d = (uint8_t * )take (MMQ_GROUP * mp .d_max + MMQ_TAIL ); 2174if (ok ) { 2175pp -> ctx = std::make_unique < mmq::Context > (); 2176pp -> run_ctx = pp -> ctx .get (); 2177 mmq::iota (pp -> ident ,pp -> cap_rows ,pp -> s ); 2178ok = DPCT_CHECK_ERROR (pp -> s -> wait ())== 0 ; 2179 } 2180size_t fb = 0 ,tb = 0 ; 2181/* 2182DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions for 2183device information which may not be supported by all compilers or runtimes. 2184You may need to adjust the code. 2185*/ 2186 dpct::get_current_device ().get_memory_info (fb ,tb ); 2187/* 2188DPCT1093: The "prev" device may be not the one intended for use. Adjust 2189the selected device if needed. 2190*/ 2191 dpct::select_device (prev ); 2192if (!ok ) {err = "prefill peer: the peer's buffers do not fit (raise --peer-reserve-mib or lower --peer-prefill-rows)" ;return false; } 2193 std::fprintf (stderr ,"strata prefill: peer GPU %d computes its experts' rows of each prompt chunk (up to %lld rows per " 2194"layer%s); %zu MiB left free on it\n" ,pp -> dev , (long long )pp -> cap_rows , 2195pp -> compact ? (pp -> ps_frac > 0.0 ? (", compact group buffers, streams " + std::to_string ((int ) (pp -> ps_frac * 100 + 0.5 ))+ 2196"% of the primary's streamed experts through a " + std::to_string (pp -> RP )+ "-slot ring" ).c_str () 2197 :", compact group buffers" ) :"" ,fb >>20 ); 2198m .pp = std::move (pp ); 2199return true; 2200} 2201catch (sycl::exception const & exc ) { 2202 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 2203 <<", line:" <<__LINE__ << std::endl ; 2204 std::exit (1 ); 2205} 2206 2207void Prefill ::set_pinned_share (double share ) {g_pinned_share = share ; } 2208void set_nonresident_share (double share ) {g_nonres_share = share ; }// SYCL port (see ring_slots) 2209void Prefill ::set_ring_override (int slots ) {g_ring_override = slots > 0 ?slots :0 ; } 2210void Prefill ::set_ring_budget (int slots ,int64_t small_max ) { 2211g_ring_budget = slots > 0 ?slots :0 ; 2212g_ring_small_max = small_max > 0 ?small_max :0 ; 2213} 2214double Prefill ::pinned_share () {return g_pinned_share ; } 2215int64_t Prefill ::stream_all_min_tokens () {return stream_all_min (); } 2216 2217uint64_t Prefill ::bytes_needed (const core::ModelGeometry & g ,const core::SessionState & ss ,int64_t chunk ,bool src ,int64_t /*tail*/ ) { 2218return bytes_needed_impl (g ,ss ,chunk , false,src ); 2219} 2220// The shared header (include/strata/prefill/prefill.hpp) carries the lent layout's MMQ tail (loan_rules.hpp) and the card's expert share for the 2221// switch-point rule. The SYCL engine has no tail buffers (no MMQ), so these members answer "no tail" (-1, room for any chunk) and the parameters 2222// are accepted and ignored; the interface is kept in step with the header, the layouts behave as before the tail existed. 2223int64_t Prefill ::layout_tail ()const {return -1 ; } 2224int64_t Prefill ::tail_room ()const {return INT64_MAX ; } 2225bool Prefill ::tail_matters (int64_t ,bool ) {return false; } 2226void Prefill ::set_card_expert_share (int64_t ,int64_t ,double ,double ) {} 2227 2228// What `init` really allocates when the prompt path owns its buffers (no loan): every cudaMalloc rounds up to a 2 MiB 2229// page, and the ring is one allocation (carve). `bytes_needed` stays the borrowed region's sum. 2230uint64_t Prefill ::bytes_needed_owned (const core::ModelGeometry & g ,const core::SessionState & ss ,int64_t chunk , 2231bool src ) { 2232return bytes_needed_impl (g ,ss ,chunk , true,src ); 2233} 2234 2235uint64_t Prefill ::bytes_needed_impl (const core::ModelGeometry & g ,const core::SessionState & ss ,int64_t chunk , 2236bool owned_pages ,bool src ,int64_t /*tail*/ ) { 2237// the same allocation sequence as `init`, counted 2238const size_t T = (size_t )chunk ; 2239bool ok = true; 2240Alloc o ; 2241o .count_only = true; 2242if (owned_pages )o .granule = 2ull <<20 ; 2243o .take < uint16_t > ((size_t )GEMM_SCRATCH ,ok ); 2244o .take < uint8_t > (GEMM_WS ,ok ); 2245auto f = [& ](size_t n ) {o .take < float > (n ,ok ); }; 2246// `carve`'s order, buffer for buffer: emb, R, xn, grs, xn16, lo, lo16, gated, inj, mixed, mixed_bf, mixed_h, 2247// bo. This counted `xn` unconditionally (carve takes it only under STRATA_GR_UNFUSED) and never counted 2248// `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 2249// prompt path was told it had less room than it did. Safe - the direction is over-estimating, and `take` 2250// still bounds-checks - but it under-sizes every loan, so every chunk the scan picks is one step smaller. 2251if (ring_bytes_on ()) { 2252f (T * N );f (T * D ); 2253if (gr_unfused ())f (T * D ); 2254f (T * HC ); 2255 }else {// STRATA_RING_BYTES=0: 0.1.39's count 2256f (T * N );f (T * D );f (T * D ); 2257 } 2258o .take < uint16_t > (T * (D + (hc_pad () ?XN_PAD :0 )),ok );f (T * LR );o .take < uint16_t > (T * LR ,ok ); 2259f (T * D );f (T * HC );f (T * N );o .take < uint16_t > (T * N ,ok );o .take < uint16_t > (T * N ,ok );f (T * N ); 2260const bool f16_io = prompt_f16 ();// the current device's mode (the stage's), as Prefill::init will decide it 2261if (bf16x2_hc (f16_io )) {o .take < uint16_t > (T * D ,ok );o .take < uint16_t > (T * LR ,ok ); } 2262if (bf16x2 (f16_io ))o .take < uint16_t > (T * N ,ok ); 2263o .take < int32_t > (T * strata::kernels::kStepCount ,ok ); 2264 strata::kernels::QsaShapes s = core::qsa_shapes (g ); 2265const int64_t cap = strata::kernels::qsa_selection_width (strata::kernels::kTopkMaxCells ,s ); 2266const int64_t max_blocks = ss .qsa_states [ss .qsa_primary ()].max_cells /s .idx_block + 2 ; 2267o .take < uint8_t > ((size_t ) std::max ({gdn_set_bytes (T ),qsa_set_bytes (T ,cap ,max_blocks ,256 ,attn_batch_for (T ),s ), 2268moe_set_bytes (T ,g .n_expert ,fused_layout (T ,src ))}),ok ); 2269for (int i = 0 ;i < dq_slots ();++ i ) {o .take < uint16_t > (kFF2 * kEmbd ,ok );o .take < uint16_t > (kEmbd * kFF ,ok ); } 2270if (mmq_plan ().any ) { 2271const MmqPlan & mp = mmq_plan (); 2272o .take < int32_t > (T * K ,ok ); 2273o .take < int32_t > ((size_t ) (2 * (g .n_expert + g .n_expert /MMQ_GROUP + 2 )),ok ); 2274o .take < uint8_t > (MMQ_GROUP * mp .gu_max + MMQ_TAIL ,ok ); 2275o .take < uint8_t > (MMQ_GROUP * mp .d_max + MMQ_TAIL ,ok ); 2276 } 2277const int ring_n = std::max (ring_slots (T ),stage_slots ()); 2278if (owned_pages ) { 2279if (ring_n > 0 )o .take < uint8_t > ((size_t )ring_n * (size_t )MAXBLOB (),ok );// one allocation 2280 }else { 2281for (int i = 0 ;i < ring_n ;++ i )o .take < uint8_t > ((size_t )MAXBLOB (),ok ); 2282 } 2283f (T * N ); 2284f ((size_t ) strata::kernels::NG_HC_DIM ); 2285 strata::kernels::KvHostPools stage ; 2286take_stage (o ,ss ,s ,stage ,ok ); 2287return o .used + (8u <<20 );// alignment slack 2288} 2289 2290uint64_t Prefill ::bytes_needed_no_ring (const core::ModelGeometry & g ,const core::SessionState & ss ,int64_t chunk , 2291bool src ) { 2292return bytes_needed (g ,ss ,chunk ,src )- (uint64_t )ring_slots ((size_t )chunk )* (uint64_t )MAXBLOB (); 2293} 2294 2295int64_t Prefill ::ring_default_slots () { 2296const int r = g_pinned_share >=0.9 ? (fused_ring () ?1024 :384 ) :96 ; 2297return (int64_t ) std::min (r ,ring_cap ()); 2298} 2299 2300int64_t Prefill ::ring_cap_for (int64_t old_chunk ) { 2301// 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 2302// the chunk at 4096 or less (IQ3_XXS 32K prompts +14% to +26%: 4096/384 -> 6656/56) and lost where 0.1.39 already 2303// read 6144-token chunks (the Coder: 6144/384 -> 7936/199, 32K -12%). From kKeepRingChunk on the ring keeps its 2304// 0.1.39 size and the scan only looks for a bigger chunk next to it (IQ3_XXS unpinned 6144/96 -> 6912/96: +9%). 2305constexpr int64_t kKeepRingChunk = 6144 ; 2306return old_chunk >=kKeepRingChunk ?ring_default_slots () :ring_max_slots (); 2307} 2308 2309// the unpinned arm keeps its measured 96 (the PR's rule; the byte budget would have been ~49 slots on IQ3_S) 2310int64_t Prefill ::ring_max_slots () { 2311return g_pinned_share >=0.9 ? (int64_t )ring_budget_slots () : (int64_t ) std::min (96 ,ring_cap ()); 2312} 2313 2314int64_t Prefill ::ring_slots_for (int64_t chunk ) {return ring_slots ((size_t )chunk ); } 2315 2316bool Prefill ::ring_bytes_enabled () {return ring_bytes_on (); } 2317 2318namespace { 2319 2320const core::WeightRef * need (const core::LayerView & v ,const char * suffix , std::string & err ) { 2321const core::WeightRef * r = v .get (suffix ); 2322if (!r )err = v .name (suffix )+ " is missing" ; 2323return r ; 2324} 2325bool native_proj (Gemm & gm ,const core::WeightRef * w ,const uint16_t * X ,float * Y ,int64_t T ,const std::string & name , 2326 std::string & err ,int64_t ldy = 0 ,int64_t ldx = 0 ) { 2327if (!w -> native_data ) {err = "prefill: " + name + " has no native GGUF blocks (run with --native)" ;return false; } 2328gm .native (X ,w -> native_type ,w -> native_data ,Y ,T ,w -> ne1 ,w -> ne0 ,ldy ,0.0f ,ldx ); 2329return true; 2330} 2331bool bf16_proj (Gemm & gm ,const core::WeightRef * w ,const uint16_t * X ,float * Y ,int64_t T ,const std::string & name , 2332 std::string & err ,int64_t ldy = 0 ,const uint16_t * X_lo = nullptr ,int64_t ldx = 0 ) { 2333if (w -> kind != core::WeightKind ::Bf16InF32 || !w -> data ) {err = "prefill: " + name + " is not a resident BF16 tensor" ;return false; } 2334gm .bf16 (X , (const uint16_t * )w -> data ,Y ,T ,w -> ne1 > 0 ?w -> ne1 :1 ,w -> ne0 ,ldy ,0.0f ,ldx ); 2335if (X_lo )gm .bf16 (X_lo , (const uint16_t * )w -> data ,Y ,T ,w -> ne1 > 0 ?w -> ne1 :1 ,w -> ne0 ,ldy ,1.0f ); 2336return true; 2337} 2338 2339}// namespace 2340 2341namespace { 2342// STRATA_PREFILL_TIMING=1: the prompt path's GPU time by phase. Events are recorded on the compute stream in order; 2343// the time between two consecutive marks is charged to the phase of the first, so a gap where the GPU waits (for the 2344// host's expert grouping, or for an expert's copy) lands on the phase that was waiting. Events are reused: the marks 2345// are folded at every MoE layer's host sync, after which all of them have completed. 2346enum PfPhase {kPfStart ,kPfHc ,kPfGdn ,kPfQsa ,kPfQsaIdx ,kPfQsaSel ,kPfQsaAttn ,kPfRouter ,kPfHostGroup ,kPfGather , 2347kPfWaitCopy ,kPfDequant ,kPfGemmGU ,kPfGemmD ,kPfCombine ,kPfPle ,kPfKvStage ,kPfGdnConv ,kPfGdnRec ,kPfGdnOut , 2348kPfCount }; 2349const char * const kPfNames [kPfCount ]= {"embed+steps" ,"hc read" ,"gdn" ,"qsa proj" ,"qsa indexer" ,"qsa select" , 2350"qsa attn" ,"router+shared" ,"host grouping" ,"gather" ,"wait copy" ,"dequant" , 2351"gemm gate/up" ,"gemm down" ,"combine" ,"ple" ,"kv stage" ,"gdn conv+gates" , 2352"gdn recurrence" ,"gdn out proj" }; 2353struct PfTimer { 2354bool on = std::getenv ("STRATA_PREFILL_TIMING" )!= nullptr ; 2355 std::vector < dpct::event_ptr > ev ; 2356 std::vector < int > ph ; 2357size_t used = 0 ; 2358double ms [kPfCount ]= {}; 2359// STRATA_PREFILL_SYNC=1 (debug): wait for the GPU at every mark and log the phase that just finished, so a hang 2360// names the stage that never completes 2361bool sync = std::getenv ("STRATA_PREFILL_SYNC" )!= nullptr ; 2362long long n_sync = 0 ; 2363void mark (int phase , dpct::queue_ptr s ) { 2364 workload_trace::phase (phase < kPfCount ?kPfNames [phase ] :"unknown" ,s ); 2365if (sync ) { 2366const auto t0 = std::chrono::steady_clock::now (); 2367s -> wait (); 2368 std::fprintf (stderr ,"strata prefill sync: mark %lld phase %s done (waited %.1f ms)\n" ,++ n_sync , 2369phase < kPfCount ?kPfNames [phase ] :"?" , 2370 std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t0 ).count ()); 2371 } 2372if (!on )return ; 2373if (used == ev .size ()) { 2374 dpct::event_ptr e = nullptr ; 2375e = new sycl::event (); 2376ev .push_back (e ); 2377ph .push_back (0 ); 2378 } 2379ph [used ]= phase ; 2380 dpct::sync_barrier (ev [used ],s ); 2381++ used ; 2382 } 2383// every recorded mark has completed (the stream was synchronized): charge the gaps, keep the last mark 2384void fold ()try { 2385if (!on || used < 2 )return ; 2386for (size_t i = 0 ;i + 1 < used ;++ i ) { 2387float t = 0.0f ; 2388if (DPCT_CHECK_ERROR ( 2389t = (ev [i + 1 ] 2390-> get_profiling_info < 2391 sycl::info::event_profiling::command_end > ()- 2392ev [i ] 2393-> get_profiling_info < sycl::info::event_profiling:: 2394command_start > ()) / 23951000000.0f )== 0 )ms [ph [i ]]+= t ; 2396 } 2397 std::swap (ev [0 ],ev [used - 1 ]); 2398 std::swap (ph [0 ],ph [used - 1 ]); 2399used = 1 ; 2400 } 2401catch (sycl::exception const & exc ) { 2402 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 2403 <<", line:" <<__LINE__ << std::endl ; 2404 std::exit (1 ); 2405 } 2406 ~PfTimer () { 2407for (dpct::event_ptr e :ev )DPCT_CHECK_ERROR (dpct::destroy_event (e )); 2408 } 2409}; 2410// multi-GPU: the peer's own timeline (STRATA_PREFILL_TIMING): marks on the peer stream, folded with the primary's 2411enum PePhase {kPeIdle ,kPeMoeIn ,kPeMoeGemm ,kPeMoeOut ,kPeCount }; 2412const char * const kPeNames [kPeCount ]= {"idle" ,"moe in" ,"moe gemm" ,"moe out" }; 2413struct PeTimer { 2414bool on = std::getenv ("STRATA_PREFILL_TIMING" )!= nullptr ; 2415int dev = -1 ; 2416 std::vector < dpct::event_ptr > ev ; 2417 std::vector < int > ph ; 2418size_t used = 0 ; 2419double ms [kPeCount ]= {}; 2420void mark (int phase , dpct::queue_ptr s ) {// the peer device is current 2421if (!on )return ; 2422if (used == ev .size ()) { 2423 dpct::event_ptr e = nullptr ; 2424e = new sycl::event (); 2425ev .push_back (e ); 2426ph .push_back (0 ); 2427 } 2428ph [used ]= phase ; 2429 dpct::sync_barrier (ev [used ],s ); 2430++ used ; 2431 } 2432void fold ()try {// every mark has completed 2433if (!on || used < 2 )return ; 2434for (size_t i = 0 ;i + 1 < used ;++ i ) { 2435float t = 0.0f ; 2436if (DPCT_CHECK_ERROR ( 2437t = (ev [i + 1 ] 2438-> get_profiling_info < 2439 sycl::info::event_profiling::command_end > ()- 2440ev [i ] 2441-> get_profiling_info < sycl::info::event_profiling:: 2442command_start > ()) / 24431000000.0f )== 0 )ms [ph [i ]]+= t ; 2444 } 2445 std::swap (ev [0 ],ev [used - 1 ]); 2446 std::swap (ph [0 ],ph [used - 1 ]); 2447used = 1 ; 2448 } 2449catch (sycl::exception const & exc ) { 2450 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 2451 <<", line:" <<__LINE__ << std::endl ; 2452 std::exit (1 ); 2453 } 2454 ~PeTimer () { 2455if (dev < 0 )return ; 2456int prev = 0 ; 2457prev = dpct::get_current_device_id (); 2458/* 2459DPCT1093: The "dev" device may be not the one intended for use. 2460Adjust the selected device if needed. 2461*/ 2462 dpct::select_device (dev ); 2463for (dpct::event_ptr e :ev )DPCT_CHECK_ERROR (dpct::destroy_event (e )); 2464/* 2465DPCT1093: The "prev" device may be not the one intended for use. 2466Adjust the selected device if needed. 2467*/ 2468 dpct::select_device (prev ); 2469 } 2470}; 2471}// namespace 2472 2473bool Prefill ::run_impl (const int64_t * tokens ,int64_t n ,int64_t pos0 , 2474 std::string & err )try { 2475err .clear (); 2476 strata::kprof::phase ("prompt" ); 2477Impl & m = * impl_ ; 2478const core::OnDevice on_device (m .device ); 2479const core::ModelGeometry & g = * m .g ; 2480 core::SessionState & ss = * m .ss ; 2481const auto t_start = Clock ::now (); 2482const int64_t LB = stage_lb_ ,LE = stage_le_ ; 2483// The direct successor's future lives on the Prefill object. Intermediate 2484// stages therefore do not drain the complete remaining GPU chain here. 2485double host_sync_ms = 0 ,host_chunk_ms = 0 ,host_setup_ms = 0 ;// STRATA_PREFILL_TIMING: the host's share 2486double grp_wait_ms = 0 ,grp_cpu_ms = 0 ;// the per-layer grouping: the drain wait, the host's loops 2487 strata::kernels::QsaShapes s = core::qsa_shapes (g ); 2488// read once (STRATA_KV_PREFETCH=1/0: the next streamed layer's KV prefix is staged on its own stream) 2489static const bool kv_prefetch_on = [] { 2490const char * e = std::getenv ("STRATA_KV_PREFETCH" ); 2491return e ? std::atoi (e )!= 0 : false; 2492 }(); 2493const bool kv_prefetch = kv_prefetch_on ; 2494if (kv_prefetch ) { 2495/* 2496DPCT1025: The SYCL queue is created ignoring the flag and priority 2497options. 2498*/ 2499if ((!m .kv_copy && 2500DPCT_CHECK_ERROR ( 2501m .kv_copy = dpct::get_current_device ().create_queue (true))!= 25020 )|| 2503 (!m .kv_released && 2504DPCT_CHECK_ERROR (m .kv_released = new sycl::event ())!= 0 )|| 2505 (!m .kv_ready && 2506DPCT_CHECK_ERROR (m .kv_ready = new sycl::event ())!= 0 )) { 2507err = "prefill: KV prefetch stream/events" ; 2508return false; 2509 } 2510 } 2511// An early return must drain DMA before the caller refills the borrowed expert slots. 2512struct KvDrain { 2513 dpct::queue_ptr stream ; 2514 ~KvDrain () {if (stream )stream -> wait (); } 2515 }kv_drain {kv_prefetch ?m .kv_copy :& dpct::get_in_order_queue ()}; 2516int64_t kv_prefetches = 0 ; 2517const uint64_t gdn_floats = (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size + 2518 (uint64_t )g .ssm_conv_channels * (g .ssm_d_conv - 1 ); 2519int32_t prev [2 ]= {ss .ple_prev [0 ],ss .ple_prev [1 ]}; 2520// layer split: a prompt of one chunk runs the stages one after the other, so the next stage's GPU idles while 2521// this one reads; it streams and computes a share of this stage's experts then (set_stage_helper), in the 2522// place of a --peer-device peer, and gives the stage back its own buffers when the run ends 2523const bool single_chunk = hand_in_ == nullptr ?n <=m .T :single_chunk_ ; 2524const bool helped = single_chunk && bind_stage_helper (n ); 2525if (helped ) std::swap (m .pp ,m .help_pp ); 2526struct HelpScope { 2527Impl & m ; 2528bool on ; 2529 ~HelpScope () { 2530if (!on )return ; 2531const core::OnDevice d (m .pp -> dev );// its work is done before the stage hands over; settle its streams 2532m .pp -> s_cp -> wait (); 2533m .pp -> s_out -> wait (); 2534m .pp -> s -> wait (); 2535 std::swap (m .pp ,m .help_pp ); 2536 } 2537 }help_scope {m ,helped }; 2538PfTimer pt ; 2539PeTimer pe ; 2540if (m .pp )pe .dev = m .pp -> dev ;else pe .on = false; 2541const dpct::queue_ptr cs = strata::q_of (m .cs ); 2542// the MMQ row table lives in the borrowed cache slots, which the refill after a prompt overwrites with experts: 2543// write it again for every prompt (a layout is reused as long as the chunk and the slots are the same) 2544if (m .ids_identity != nullptr ) mmq::iota (m .ids_identity ,m .T * K ,m .cs ); 2545// The PLE rows of a chunk are read from the model file on the host (an SSD read per missed row): the chunk 2546// after this one is read on a thread while the GPU runs this one, into the other of two buffers. The rows 2547// depend only on the tokens (the two before a position name its n-grams), so this is the same data. 2548const bool ple_on = ss .ple .ready ()&& LB <=1 && 1 < LE ; 2549// the PLE block batched over the chunk: the pinned postops and a BF16 or GGUF-native key (else token by token); 2550// STRATA_PLE_BATCH=0 keeps the per-token block (the A/B) 2551static const bool ple_batch_env = [] { 2552const char * v = std::getenv ("STRATA_PLE_BATCH" ); 2553return v == nullptr || std::atoi (v )!= 0 ; 2554 }(); 2555const bool ple_batch = ple_on && ple_batch_env && strata::kernels::ple_native_postops_enabled ()&& 2556 (ss .ple .w .key_bf16 != nullptr || ss .ple .w .key_native_data != nullptr )&& 2557m .region_bytes / ((uint64_t ) (3 * strata::kernels::NG_HC_DIM + N + 4 )* 4 + (uint64_t )N * 2 + 4096 ) >=64 ; 2558const int32_t prev0 [2 ]= {prev [0 ],prev [1 ]}; 2559// SYCL port: a short first chunk so the GPU starts while the rest of the prompt's PLE rows are still being read 2560// (27k random 4 KB reads per 2k tokens, 330 ms at the drive's ~85k IOPS, otherwise all before the first kernel). 2561// STRATA_PREFILL_FIRST=<tokens> (0: off), default 256 when the prompt is longer than twice that. 2562// Every chunk streams the experts the cache does not hold (a 4K prompt touches nearly all 512 per layer), over PCIe: with 2563// part of the model in the host mirror a short first chunk costs a whole extra pass of that stream (an Arc Pro B70 on 2564// IQ3_S: a 4,095-token prompt 784 -> 1,002 tok/s without it). So the default is 256 only when the cache holds every 2565// expert; STRATA_PREFILL_FIRST=<tokens> decides explicitly. 2566const bool all_cached = m .cache != nullptr && m .g != nullptr && m .cache -> slots () >=m .g -> n_layers * m .g -> n_expert ; 2567static const char * const first_env = std::getenv ("STRATA_PREFILL_FIRST" ); 2568const int64_t first_chunk = first_env ? std::atoll (first_env ) : (all_cached ?256 :0 ); 2569auto chunk_len = [& ](int64_t c0 ) { 2570if (c0 == 0 && first_chunk > 0 && first_chunk < m .T && n > 2 * first_chunk )return first_chunk ; 2571return std::min (m .T ,n - c0 ); 2572 }; 2573auto ple_gather = [& m ,& ss ,tokens ,n ,prev0 ,& chunk_len ](int64_t c0 ,int buf , std::string & e )-> bool { 2574const int64_t T = chunk_len (c0 ); 2575 workload_trace::ContextGuard trace_context (c0 ,T ,-1 ); 2576 workload_trace::Scope trace ("prefill.PLE_IO" ,nullptr ,T ); 2577auto at = [& ](int64_t i ) {return i < 2 ?prev0 [i ] : (int32_t )tokens [i - 2 ]; };// prev0, then the tokens 2578int32_t pv [2 ]= {at (c0 ),at (c0 + 1 )}; 2579for (int64_t t = 0 ;t < T ;++ t ) { 2580const int32_t tok = (int32_t )tokens [c0 + t ]; 2581 strata::kernels::ngram_rows (& tok ,pv ,1 ,ss .ple .consts , 2582m .ple_rows [buf ].data ()+ t * strata::kernels::PLE_N_HEADS ); 2583pv [0 ]= pv [1 ]; 2584pv [1 ]= tok ; 2585 } 2586return ss .ple .table -> gather_batch (m .ple_rows [buf ].data (), (size_t )T ,m .ple_emb_host [buf ],e ); 2587 }; 2588 std::string ple_next_err ; 2589 std::future < bool > ple_next ;// declared after everything it reads: an early return waits for it 2590int ple_buf = 0 ; 2591 2592 std::vector < int > tap_slot ; 2593if (!tap_layers_ .empty ()&& stage_lb_ == 0 && (stage_le_ < 0 || stage_le_ == g .n_layers )) { 2594if (tap_dev_ == nullptr ) { 2595tap_dev_ = sycl::malloc_device < float > ((size_t )tap_cap_ * tap_layers_ .size ()* (size_t )g .n_embd , dpct::get_in_order_queue ()); 2596if (tap_dev_ == nullptr ) {err = "prefill: the DFlash2 tap staging does not fit in VRAM" ;return false; } 2597 } 2598tap_slot .assign ((size_t )g .n_layers ,-1 ); 2599for (size_t i = 0 ;i < tap_layers_ .size ();++ i )tap_slot [(size_t )tap_layers_ [i ]]= (int )i ; 2600 } 2601for (int64_t c0 = 0 ;c0 < n ;c0 += chunk_len (c0 )) { 2602if (should_stop && should_stop ()) {err = "cancelled" ;return false; } 2603if (std::getenv ("STRATA_TRACE" )) { std::fprintf (stderr ,"strata trace: prompt chunk %lld of %lld\n" , (long long )c0 , (long long )n ); std::fflush (stderr ); } 2604const int64_t T = chunk_len (c0 ),p0 = pos0 + c0 ; 2605// DFlash2 prompt taps: the rows of this chunk at positions >= tap_first_ (the drafter looks back one window) 2606const int64_t tap_t0 = tap_dev_ != nullptr ? std::min < int64_t > (T , std::max < int64_t > (0 ,tap_first_ - p0 )) :T ; 2607const int64_t tap_rows = T - tap_t0 ; 2608if (tap_rows > tap_cap_ ) {err = "prefill: the DFlash2 tap staging is smaller than the chunk's tapped rows" ;return false; } 2609 workload_trace::ContextGuard chunk_context (p0 ,T ,-1 ); 2610 workload_trace::Scope chunk_trace ("prefill.chunk" ,cs ,T ); 2611 core::progress_at ("reading the prompt (batched): preparing the chunk from token" ,p0 );// #251 2612++ stats_ .chunks ; 2613pt .mark (kPfStart ,cs ); 2614const auto tsetup = Clock ::now (); 2615auto tlap = tsetup ;// STRATA_PREFILL_TIMING=1: where the host's chunk setup goes 2616auto lap = [& ](const char * what ) { 2617if (pt .on ) { std::fprintf (stderr ,"strata prefill timing: setup %s %.1f ms\n" ,what ,ms_since (tlap ));tlap = Clock ::now (); } 2618 }; 2619if (pt .on ) {m .cs -> wait ();lap ("work queued before the chunk" ); } 2620// ---- embeddings, broadcast to the four streams - or, in a later stage of a layer split, the rows the 2621// previous stage handed on 2622if (hand_in_ != nullptr ) { 2623/* 2624DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy 2625API. While the origin API might be synchronous, it depends on the 2626type of operand memory, so you may need to call wait() on event 2627return by memcpy API to ensure synchronization behavior. 2628*/ 2629if (DPCT_CHECK_ERROR (m .cs -> memcpy (m .R ,hand_in_ + (size_t )c0 * D , 2630 (size_t )T * D * 4 ))!= 0 ) { 2631err = "prefill: the layer split's hand-off upload failed" ; 2632return false; 2633 } 2634 } 2635// C-4: the whole chunk's rows in one gather (the same per-element arithmetic as the per-token path, so the 2636// same bits); a chunk with picture rows, or a token outside the table, takes the per-token path 2637bool batched = hand_in_ == nullptr && m .tok_dev != nullptr ; 2638const core::NativeEmbed * nemb = core::native_embed (); 2639const core::WeightRef * wemb = nemb ?nullptr :m .wt -> find ("token_embd.weight" ); 2640if (batched && nemb == nullptr && 2641 (wemb == nullptr || wemb -> codebook_iq4nl || wemb -> ne0 != g .n_embd || wemb -> group_elems <=0 || 2642 (wemb -> code_bits != 2 && wemb -> code_bits != 4 && wemb -> code_bits != 8 ))) 2643batched = false; 2644for (int64_t t = 0 ;batched && t < T ;++ t ) { 2645const int64_t tok = tokens [c0 + t ]; 2646if ((embd_rows && embd_rows [p0 + t ])|| tok < 0 || (wemb && tok >=wemb -> ne1 ))batched = false; 2647else m .tok_host [(size_t )t ]= (int32_t )tok ; 2648 } 2649if (batched ) { 2650/* 2651DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy 2652API. While the origin API might be synchronous, it depends on the 2653type of operand memory, so you may need to call wait() on event 2654return by memcpy API to ensure synchronization behavior. 2655*/ 2656if (DPCT_CHECK_ERROR (m .cs -> memcpy (m .tok_dev ,m .tok_host .data (), 2657 (size_t )T * sizeof (int32_t )))!= 26580 ) { 2659err = "prefill: the token id upload failed" ; 2660return false; 2661 } 2662lap ("token ids uploaded" ); 2663if (nemb ) { 2664nemb -> gather_dev (m .tok_dev ,T ,m .emb ,m .cs ); 2665if (pt .on ) {m .cs -> wait ();lap ("embedding gather (waited)" ); } 2666 }else { 2667const auto * codes = (const uint8_t * )wemb -> data ; 2668const auto * scales = (const float * ) (codes + wemb -> codes_bytes ); 2669const auto * offsets = wemb -> has_offset ? (const float * ) (codes + wemb -> codes_bytes + wemb -> scales_bytes ) 2670 :nullptr ; 2671 strata::kernels::embedding_gather_dev (codes ,scales ,offsets ,m .tok_dev , (int )T ,wemb -> ne0 , 2672wemb -> code_bits ,wemb -> code_bias ,wemb -> group_elems , 2673 (uint64_t ) (wemb -> ne0 / (8 /wemb -> code_bits )), 2674 (uint64_t ) (wemb -> ne0 /wemb -> group_elems ),m .emb ,m .cs ); 2675 } 2676 } 2677for (int64_t t = 0 ;hand_in_ == nullptr && !batched && t < T ;++ t ) { 2678const float * row = embd_rows ?embd_rows [p0 + t ] :nullptr ; 2679if (row ) { 2680/* 2681DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy 2682API. While the origin API might be synchronous, it depends on 2683the type of operand memory, so you may need to call wait() on 2684event return by memcpy API to ensure synchronization behavior. 2685*/ 2686if (DPCT_CHECK_ERROR ( 2687m .cs -> memcpy (m .emb + t * N ,row , (size_t )N * 4 ))!= 0 ) { 2688err = "prefill: the image embedding upload failed" ; 2689return false; 2690 } 2691 }else if (!core::embed_row (* m .wt ,g ,tokens [c0 + t ],m .emb + t * N ,m .cs ,err )) { 2692return false; 2693 } 2694 } 2695if (hand_in_ == nullptr )gr_broadcast (m .emb ,m .R ,T ,m .cs ); 2696lap ("embeddings" ); 2697// ---- the PLE rows of the whole chunk, one batched SSD request on a thread (see ple_gather). A later chunk's 2698// were read ahead during the previous chunk; the first chunk's are read beside layer 0 - they are needed from 2699// layer 1 on, and gathering them here first left the GPU idle for the whole read (~0.4 s of a 32K prompt) 2700if (ple_on && !ple_next .valid ()) 2701ple_next = std::async (std::launch::async , [& ple_gather ,& ple_next_err ,c0 ,b = ple_buf ] { 2702return ple_gather (c0 ,b ,ple_next_err ); 2703 }); 2704bool ple_pending = ple_on ; 2705// the chunk's rows onto the device just before layer 1 reads them, and the next chunk's gather started 2706auto ple_land = [& ]()-> bool { 2707if (!ple_pending )return true; 2708ple_pending = false; 2709const auto tp = Clock ::now (); 2710if (!ple_next .get ()) { 2711err = ple_next_err ; 2712return false; 2713 } 2714/* 2715DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy 2716API. While the origin API might be synchronous, it depends on the 2717type of operand memory, so you may need to call wait() on event 2718return by memcpy API to ensure synchronization behavior. 2719*/ 2720if (DPCT_CHECK_ERROR (m .cs -> memcpy (m .ple_emb , 2721m .ple_emb_host [ple_buf ], 2722 (size_t )T * N * 4 ))!= 0 || 2723/* 2724DPCT1024: The original code returned the error code that was 2725further consumed by the program logic. This original code was 2726replaced with 0. You may need to rewrite the program logic 2727consuming the error code. 2728*/ 2729DPCT_CHECK_ERROR ((m .ple_want [ple_buf ]= ++ m .ple_seq , 2730m .cs -> fill < uint64_t > (m .ple_done_seq + ple_buf ,m .ple_want [ple_buf ],1 ))) != 0 ) { 2731/* 2732DPCT1009: SYCL reports errors using exceptions and does not 2733use error codes. Please replace the 2734"get_error_string_dummy(...)" with a real error-handling 2735function. 2736*/ 2737/* 2738DPCT1010: SYCL uses exceptions to report errors and does not 2739use the error codes. The cudaGetLastError function call was 2740replaced with 0. You need to rewrite this code. 2741*/ 2742err = std::string ("prefill: the PLE rows' upload failed: " )+ 2743 dpct::get_error_string_dummy (0 ); 2744return false; 2745 } 2746if (c0 + T < n ) {// SYCL port: T, this chunk's length (the first chunk can be shorter: chunk_len) 2747// the other buffer's upload (a chunk ago) is done before the SSD thread refills it 2748if (DPCT_CHECK_ERROR ([& ] { 2749while (* (volatile const uint64_t * ) (m .ple_done_seq + (ple_buf ^1 ))< m .ple_want [ple_buf ^1 ]) 2750 std::this_thread::yield (); 2751 }())!= 0 ) { 2752/* 2753DPCT1009: SYCL reports errors using exceptions and does 2754not use error codes. Please replace the 2755"get_error_string_dummy(...)" with a real error-handling 2756function. 2757*/ 2758/* 2759DPCT1010: SYCL uses exceptions to report errors and does 2760not use the error codes. The cudaGetLastError function call 2761was replaced with 0. You need to rewrite this code. 2762*/ 2763err = 2764 std::string ("prefill: the PLE rows' upload failed: " )+ 2765 dpct::get_error_string_dummy (0 ); 2766return false; 2767 } 2768ple_next = std::async (std::launch::async , [& ple_gather ,& ple_next_err ,c1 = c0 + T ,b = ple_buf ^1 ] { 2769return ple_gather (c1 ,b ,ple_next_err ); 2770 }); 2771 } 2772ple_buf ^=1 ; 2773stats_ .ms_ple += ms_since (tp ); 2774return true; 2775 }; 2776for (int64_t t = 0 ;t < T ;++ t ) {prev [0 ]= prev [1 ];prev [1 ]= (int32_t )tokens [c0 + t ]; } 2777lap ("PLE rows" ); 2778// ---- the QSA step records of every position in the chunk 2779for (int64_t t = 0 ;t < T ;++ t ) strata::kernels::qsa_step_fill (m .steps_host .data ()+ t * strata::kernels::kStepCount ,p0 + t ,s ); 2780/* 2781DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. 2782While the origin API might be synchronous, it depends on the type of 2783operand memory, so you may need to call wait() on event return by memcpy 2784API to ensure synchronization behavior. 2785*/ 2786m .cs -> memcpy (m .steps_dev ,m .steps_host .data (), 2787 (size_t )T * strata::kernels::kStepCount * 4 ); 2788 2789int64_t qsa_index = 0 ,gdn_index = 0 ; 2790for (int64_t l = 0 ;l < LB ;++ l ) (core::is_qsa_layer (g ,l ) ?qsa_index :gdn_index )+= 1 ; 2791lap ("step records" ); 2792int64_t kv_pending = -1 ; 2793auto kv_prefetch_after = [& ](int64_t layer ,int64_t ordinal )-> bool { 2794try { 2795if (!kv_prefetch || p0 <=0 )return true; 2796if (kv_pending >=0 )return true;// one staging pool: the pending prefetch has not been consumed yet 2797for (int64_t l = layer ;l < LE ;++ l ) { 2798if (!core::is_qsa_layer (g ,l ))continue ; 2799const core::QsaState & state = ss .qsa_states [ordinal ]; 2800if (state .kv_mode != 1 ) {++ ordinal ;continue ; } 2801// Reuse one KV pool only after its last attention reader completes. The next layer's 2802// [0, p0) host prefix is immutable throughout this chunk; its new rows are appended later. 2803/* 2804DPCT1024: The original code returned the error code that 2805was further consumed by the program logic. This original code 2806was replaced with 0. You may need to rewrite the program logic 2807consuming the error code. 2808*/ 2809if (DPCT_CHECK_ERROR (dpct::sync_barrier (m .kv_released ,cs ))!= 28100 || 2811DPCT_CHECK_ERROR ((m .kv_copy )-> ext_oneapi_submit_barrier ( 2812 {* m .kv_released }))!= 0 ) { 2813err = "prefill: releasing KV staging pool" ; 2814return false; 2815 } 2816 strata::kernels::kv_stage_from_host (pools_of (m .stage ,m .ident_table ),state .host , 2817 core::qsa_kv_format (state ), (p0 + s .page_size - 1 ) /s .page_size ,s ,m .kv_copy ); 2818/* 2819DPCT1010: SYCL uses exceptions to report errors and does 2820not use the error codes. The cudaPeekAtLastError function call 2821was replaced with 0. You need to rewrite this code. 2822*/ 2823if (0 != 0 || 2824/* 2825DPCT1024: The original code returned the error code 2826that was further consumed by the program logic. This 2827original code was replaced with 0. You may need to rewrite 2828the program logic consuming the error code. 2829*/ 2830DPCT_CHECK_ERROR ( 2831 dpct::sync_barrier (m .kv_ready ,m .kv_copy ))!= 0 ) { 2832err = "prefill: enqueueing KV prefetch" ; 2833return false; 2834 } 2835kv_pending = ordinal ; 2836++ kv_prefetches ; 2837break ; 2838 } 2839return true; 2840 } 2841catch (sycl::exception const & exc ) { 2842 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 2843 <<", line:" <<__LINE__ << std::endl ; 2844 std::exit (1 ); 2845 } 2846 }; 2847if (!kv_prefetch_after (LB ,qsa_index ))return false; 2848// step 3: this chunk's stream - every non-resident expert of every layer, layer by layer in id order (entry 2849// k lands in ring slot k % ring); a copy is issued once the entry `ring` before it is consumed (its slot's 2850// `used` event recorded), so the copy stream never waits on an event that is not queued yet 2851const strata::kernels::cpu::ExpertLayout & lay0 = strata::kernels::cpu::expert_layout (); 2852const bool stream_all = m .ring > STAGE && T >=stream_all_min ()&& m .src != nullptr ; 2853const bool ps_on = stream_all && m .pp && m .pp -> ps_frac > 0.0 ; 2854if (m .pp && !ps_on )m .pp -> ps_flag .clear (); 2855// multi-GPU: the peer's ring - issue its copies up to `limit` / give entries back (the peer device is current) 2856auto p_issue_until = [& ](size_t limit ) { 2857try { 2858PeerPrefill & P = * m .pp ; 2859limit = std::min (limit ,P .pseq .size ()); 2860while (P .p_issued < limit ) { 2861const PeerPrefill ::PsEntry & en = P .pseq [P .p_issued ]; 2862const size_t sl = P .p_issued % (size_t )P .RP ; 2863if (P .plive [sl ])(P .s_cp )-> ext_oneapi_submit_barrier ( 2864 {* P .pused [sl ]}); 2865/* 2866DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy 2867API. While the origin API might be synchronous, it depends on 2868the type of operand memory, so you may need to call wait() on 2869event return by memcpy API to ensure synchronization behavior. 2870*/ 2871P .s_cp -> memcpy ( 2872P .pstage [sl ],en .blob , 2873 (size_t )strata::kernels::cpu::expert_layout ().blob_bytes ( 2874en .l )); 2875 dpct::sync_barrier (P .pcopied [sl ],P .s_cp ); 2876P .plive [sl ]= 1 ; 2877++ P .p_issued ; 2878 } 2879 } 2880catch (sycl::exception const & exc ) { 2881 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 2882 <<", line:" <<__LINE__ << std::endl ; 2883 std::exit (1 ); 2884 } 2885 }; 2886auto p_release_to = [& ](int64_t l ,int32_t e_stop , dpct::queue_ptr ps ) { 2887try { 2888PeerPrefill & P = * m .pp ; 2889while (P .pk < P .pseq_start [(size_t )l + 1 ]&& P .pseq [P .pk ].e < e_stop ) { 2890 dpct::sync_barrier (P .pused [P .pk % (size_t )P .RP ],ps ); 2891++ P .pk ; 2892p_issue_until (P .pk + (size_t )P .RP ); 2893 } 2894 } 2895catch (sycl::exception const & exc ) { 2896 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 2897 <<", line:" <<__LINE__ << std::endl ; 2898 std::exit (1 ); 2899 } 2900 }; 2901struct StreamEntry {int32_t l ,e ;const uint8_t * blob ;int job ; }; 2902 std::vector < StreamEntry > seq ; 2903 std::vector < size_t > seq_start ; 2904size_t issued = 0 ,consumed = 0 ; 2905static const bool plan_reads = [] {const char * v = std::getenv ("STRATA_GGUF_PLAN_READ" );return v && v [0 ]== '1' ; }(); 2906const core::GgufExpertSource * gsrc = plan_reads ?nullptr :dynamic_cast < const core::GgufExpertSource *> (m .src ); 2907if (stream_all ) { 2908seq_start .assign ((size_t )g .n_layers + 1 ,0 ); 2909 std::vector < Stager ::Job > js ; 2910if (ps_on ) { 2911m .pp -> pseq .clear (); 2912m .pp -> pseq_start .assign ((size_t )g .n_layers + 1 ,0 ); 2913m .pp -> ps_flag .assign ((size_t )g .n_layers * m .g -> n_expert ,0 ); 2914m .pp -> p_issued = m .pp -> pk = 0 ; 2915 } 2916double ps_acc = 0.0 ; 2917for (int64_t l = LB ;l < LE ;++ l ) { 2918seq_start [(size_t )l ]= seq .size (); 2919if (ps_on )m .pp -> pseq_start [(size_t )l ]= m .pp -> pseq .size (); 2920for (int32_t e = 0 ;e < m .g -> n_expert ;++ e ) { 2921if (m .host_res && m .cache && m .host_res [(size_t )l * m .g -> n_expert + e ] >=0 )continue ; 2922if (m .pp && m .pp -> peer && m .pp -> peer -> has (l ,e ))continue ;// multi-GPU: computed on (or read from) the peer 2923int job = -1 ; 2924const uint8_t * b = nullptr ; 2925if (gsrc != nullptr ) {// read by the stager's thread when its turn comes (see Stager::Job) 2926job = (int )js .size (); 2927js .push_back ({nullptr , (size_t )lay0 .blob_bytes (l ),nullptr , (int32_t )l ,e ,gsrc }); 2928 }else if (m .src -> transient (l ,e )) {// CS-T: copied by the source into the stager's buffer 2929job = (int )js .size (); 2930js .push_back ({nullptr , (size_t )lay0 .blob_bytes (l ),m .src , (int32_t )l ,e }); 2931 }else { 2932b = m .src -> blob (l ,e ); 2933if (!b ) {err = "prefill: expert source has no blob" ;return false; } 2934if (ps_on && m .src -> pinned (l ,e )) {// multi-GPU: every ps_frac-th one goes to the peer's ring 2935ps_acc += m .pp -> ps_frac ; 2936if (ps_acc >=1.0 ) { 2937ps_acc -= 1.0 ; 2938m .pp -> pseq .push_back ({(int32_t )l ,e ,b }); 2939m .pp -> ps_flag [(size_t )l * m .g -> n_expert + e ]= 1 ; 2940continue ; 2941 } 2942 } 2943if (!dma_direct (m .src ,l ,e ,b )) { 2944job = (int )js .size (); 2945js .push_back ({b , (size_t )lay0 .blob_bytes (l )}); 2946 } 2947 } 2948seq .push_back ({(int32_t )l ,e ,b ,job }); 2949 } 2950 } 2951for (int64_t l = LE ;l <=g .n_layers ;++ l ) { 2952seq_start [(size_t )l ]= seq .size (); 2953if (ps_on )m .pp -> pseq_start [(size_t )l ]= m .pp -> pseq .size (); 2954 } 2955m .stager -> start (std::move (js )); 2956 } 2957struct StagerDone { 2958Stager * st ; 2959 ~StagerDone () {if (st )st -> finish (); } 2960 }chunk_stager_done {stream_all ?m .stager .get () :nullptr }; 2961auto issue_until = [& ](size_t limit ) { 2962try { 2963limit = std::min (limit ,seq .size ()); 2964while (issued < limit ) { 2965const StreamEntry & en = seq [issued ]; 2966const int sl = (int ) (issued % (size_t )m .ring ); 2967const auto th = Clock ::now (); 2968const size_t bytes = (size_t )lay0 .blob_bytes (en .l ); 2969if (m .stage_live [sl ])(m .copy )-> ext_oneapi_submit_barrier ( 2970 {* m .used [m .used_of [sl ]]}); 2971if (en .job < 0 ) { 2972/* 2973DPCT1124: cudaMemcpyAsync is migrated to asynchronous 2974memcpy API. While the origin API might be synchronous, it 2975depends on the type of operand memory, so you may need to 2976call wait() on event return by memcpy API to ensure 2977synchronization behavior. 2978*/ 2979m .copy -> memcpy (m .stage_dev [sl ],en .blob ,bytes ); 2980++ stats_ .experts_dma ; 2981 }else { 2982const uint8_t * hb = m .stager -> wait (en .job ); 2983/* 2984DPCT1124: cudaMemcpyAsync is migrated to asynchronous 2985memcpy API. While the origin API might be synchronous, it 2986depends on the type of operand memory, so you may need to 2987call wait() on event return by memcpy API to ensure 2988synchronization behavior. 2989*/ 2990m .copy -> memcpy (m .stage_dev [sl ],hb ,bytes ); 2991m .stager -> issued_one (en .job ,m .copy ); 2992 } 2993 dpct::sync_barrier (m .copied [sl ],m .copy ); 2994m .stage_live [sl ]= true; 2995stats_ .ms_experts_host += ms_since (th ); 2996++ stats_ .experts_streamed ; 2997++ issued ; 2998 } 2999 } 3000catch (sycl::exception const & exc ) { 3001 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 3002 <<", line:" <<__LINE__ << std::endl ; 3003 std::exit (1 ); 3004 } 3005 }; 3006// D-5: the stream is issued by its own host thread, so the thread launching the layers' kernels never waits 3007// behind a host copy of an unpinned blob (that wait left the GPU idle: the 'wait copy' / 'dequant' time of the 3008// i-quant prompts). The same copies in the same order into the same slots, and a slot is refilled only once 3009// the compute stream has recorded that it is done with it: the same results. STRATA_PREFILL_ISSUER=0: inline. 3010static const bool issuer_on = [] { 3011const char * v = std::getenv ("STRATA_PREFILL_ISSUER" ); 3012return v == nullptr || std::atoi (v )!= 0 ; 3013 }(); 3014 std::atomic < size_t > a_issued {0 },a_consumed {0 }; 3015 std::atomic < bool > a_stop {false}; 3016double iss_ms = 0 ; 3017int64_t iss_streamed = 0 ,iss_dma = 0 ; 3018 std::thread issuer ; 3019struct IssuerJoin { 3020 std::atomic < bool >* stop ; 3021 std::thread * t ; 3022 ~IssuerJoin () {if (t -> joinable ()) {stop -> store (true);t -> join (); } } 3023 }issuer_join {& a_stop ,& issuer }; 3024const bool threaded_issue = stream_all && issuer_on ; 3025if (threaded_issue ) { 3026issuer = std::thread ([& ] { 3027const core::OnDevice od (m .device ); 3028for (size_t idx = 0 ;idx < seq .size ();++ idx ) { 3029while (idx >=a_consumed .load (std::memory_order_acquire )+ (size_t )m .ring ) { 3030if (a_stop .load (std::memory_order_acquire ))return ; 3031 std::this_thread::yield (); 3032 } 3033const StreamEntry & en = seq [idx ]; 3034const int sl = (int ) (idx % (size_t )m .ring ); 3035const auto th = Clock ::now (); 3036const size_t bytes = (size_t )lay0 .blob_bytes (en .l ); 3037if (m .stage_live [sl ])(m .copy )-> ext_oneapi_submit_barrier ( 3038 {* m .used [m .used_of [sl ]]}); 3039if (en .job < 0 ) { 3040/* 3041DPCT1124: cudaMemcpyAsync is migrated to 3042asynchronous memcpy API. While the origin API might be 3043synchronous, it depends on the type of operand memory, 3044so you may need to call wait() on event return by memcpy 3045API to ensure synchronization behavior. 3046*/ 3047m .copy -> memcpy (m .stage_dev [sl ],en .blob ,bytes ); 3048++ iss_dma ; 3049 }else { 3050const uint8_t * hb = m .stager -> wait (en .job ); 3051/* 3052DPCT1124: cudaMemcpyAsync is migrated to 3053asynchronous memcpy API. While the origin API might be 3054synchronous, it depends on the type of operand memory, 3055so you may need to call wait() on event return by memcpy 3056API to ensure synchronization behavior. 3057*/ 3058m .copy -> memcpy (m .stage_dev [sl ],hb ,bytes ); 3059m .stager -> issued_one (en .job ,m .copy ); 3060 } 3061 dpct::sync_barrier (m .copied [sl ],m .copy ); 3062m .stage_live [sl ]= true; 3063iss_ms += ms_since (th ); 3064++ iss_streamed ; 3065a_issued .store (idx + 1 , std::memory_order_release ); 3066 } 3067 }); 3068 }else if (stream_all ) { 3069issue_until ((size_t )m .ring );// layer 0's first experts, behind the embedding and the PLE 3070 } 3071// the consumer's side: entry k's copy is on the copy stream (the thread issued it), then k is given back 3072auto wait_issued = [& ](size_t k ) { 3073if (!threaded_issue )return ; 3074while (a_issued .load (std::memory_order_acquire ) <=k ) std::this_thread::yield (); 3075 }; 3076auto give_back = [& ](size_t upto ) { 3077if (threaded_issue )a_consumed .store (upto , std::memory_order_release ); 3078else issue_until (upto + (size_t )m .ring ); 3079 }; 3080lap ("expert stream plan" ); 3081if (ps_on ) { 3082int pd = 0 ; 3083pd = dpct::get_current_device_id (); 3084/* 3085DPCT1093: The "m.pp->dev" device may be not the one intended for 3086use. Adjust the selected device if needed. 3087*/ 3088 dpct::select_device (m .pp -> dev ); 3089p_issue_until ((size_t )m .pp -> RP ); 3090/* 3091DPCT1093: The "pd" device may be not the one intended for use. 3092Adjust the selected device if needed. 3093*/ 3094 dpct::select_device (pd ); 3095 } 3096host_setup_ms += ms_since (tsetup ); 3097bool normed = false;// F-2: the previous half's write already normed R for this half (grs, xn16) 3098// #579 #613 (opt-in diagnosis, STRATA_PF_STEP_SYNC=1): the compute and copy streams are waited for after each 3099// step named below, a step that took over 250 ms is logged, and a stall's report names the step it is in. 3100// Slower (a sync per step); the bytes are the same. 3101static const bool step_sync = [] {const char * e = std::getenv ("STRATA_PF_STEP_SYNC" );return e && e [0 ]== '1' ; }(); 3102auto pf_step = [& ](const char * what ,int64_t layer ) { 3103try { 3104if (!step_sync )return ; 3105 core::progress_at (what ,layer ,p0 ); 3106const auto ts = Clock ::now (); 3107const dpct::err0 a = DPCT_CHECK_ERROR (m .cs -> wait ()), 3108b = DPCT_CHECK_ERROR (m .copy -> wait ()); 3109const double ms = ms_since (ts ); 3110if (ms > 250.0 || a != 0 || b != 0 ) 3111 std::fprintf (stderr , 3112"strata pf-step: chunk from token %lld, layer " 3113"%lld: %s took %.0f ms (%s / %s)\n" , 3114/* 3115DPCT1009: SYCL reports errors using exceptions 3116and does not use error codes. Please replace the 3117"get_error_string_dummy(...)" with a real 3118error-handling function. 3119*/ 3120 (long long )p0 , (long long )layer ,what ,ms , 3121 dpct::get_error_string_dummy (a ), 3122 dpct::get_error_string_dummy (b )); 3123 } 3124catch (sycl::exception const & exc ) { 3125 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 3126 <<", line:" <<__LINE__ << std::endl ; 3127 std::exit (1 ); 3128 } 3129 }; 3130for (int64_t l = LB ;l < LE ;++ l ) { 3131 core::progress_beat ();// the serve watchdog: a prompt chunk of 8192 tokens is still moving 3132 workload_trace::ContextGuard layer_context (p0 ,T ,l ); 3133 workload_trace::Scope layer_trace ("prefill.layer" ,cs ,T ); 3134if (l > LB )pf_step ("reading the prompt (batched, step sync): the experts and the rest of layer" ,l - 1 ); 3135 core::progress_at ("reading the prompt (batched): layer" ,l ,p0 );// #251: a stall names layer and chunk 3136const core::LayerView v (* m .wt ,l ); 3137if (l == std::max < int64_t > (LB ,1 )&& !ple_land ())return false;// the PLE rows, read from layer 1 on 3138// ---- the PLE block at layer 1, token by token (its conv reads the previous tokens' rows) 3139if (l == 1 && ple_on && ple_batch ) { 3140// the whole chunk at once, in sub-batches carved from the idle scratch region: the key and value 3141// projections as GEMMs (a token at a time they re-read ~52 MB of BF16 key per token on the IQ 3142// files), the rest with the per-token kernels' arithmetic (native_ple_postops_batch) 3143pt .mark (kPfPle ,cs ); 3144const auto tp = Clock ::now (); 3145const strata::kernels::PleWeights & pw = ss .ple .w ; 3146constexpr int64_t HD = strata::kernels::NG_HC_DIM ; 3147const uint64_t per_token = (uint64_t ) (3 * HD + N + 4 )* 4 + (uint64_t )N * (bf16x2 (m .f16_io ) ?4 :2 )+ 4096 ; 3148const int64_t SB = std::min < int64_t > (T , (int64_t ) (m .region_bytes /per_token )); 3149for (int64_t s0 = 0 ;s0 < T ;s0 += SB ) { 3150const int64_t nb = std::min (SB ,T - s0 ); 3151uint8_t * q = m .region ; 3152auto carve_f = [& ](size_t n ) {float * p = (float * )q ;q += (n * 4 + 255 )& ~(size_t )255 ;return p ; }; 3153float * key = carve_f ((size_t )nb * HD ); 3154float * qn = carve_f ((size_t )nb * HD ); 3155float * gated = carve_f ((size_t )nb * HD ); 3156float * val = carve_f ((size_t )nb * N ); 3157float * gate = carve_f ((size_t )nb * 4 ); 3158uint16_t * e16 = (uint16_t * )carve_f ((size_t )nb * N /2 ); 3159uint16_t * e16_lo = bf16x2 (m .f16_io ) ? (uint16_t * )carve_f ((size_t )nb * N /2 ) :nullptr ; 3160const float * emb = m .ple_emb + s0 * N ; 3161if (pw .key_bf16 != nullptr ) { 3162to_bf16 (emb ,e16 ,nb * N ,m .cs ,e16_lo ); 3163m .gemm .bf16 (e16 ,pw .key_bf16 ,key ,nb ,HD ,N ); 3164if (e16_lo )m .gemm .bf16 (e16_lo ,pw .key_bf16 ,key ,nb ,HD ,N ,0 ,1.0f ); 3165 }else { 3166to_f16 (emb ,e16 ,nb * N ,m .cs ); 3167m .gemm .native (e16 ,pw .key_native_type ,pw .key_native_data ,key ,nb ,HD ,N ); 3168to_bf16 (emb ,e16 ,nb * N ,m .cs ,e16_lo ); 3169 } 3170m .gemm .bf16 (e16 ,pw .value_bf16 ,val ,nb ,N ,N ); 3171if (e16_lo )m .gemm .bf16 (e16_lo ,pw .value_bf16 ,val ,nb ,N ,N ,0 ,1.0f ); 3172try { 3173 strata::kernels::native_ple_postops_batch (key ,m .R + s0 * D ,val ,ss .ple .hist ,pw ,qn ,gated , 3174gate , (int )nb ,m .cs ); 3175 }catch (const std::exception & e ) {err = std::string ("prefill PLE: " )+ e .what ();return false; } 3176 } 3177stats_ .ms_ple += ms_since (tp ); 3178 }else if (l == 1 && ple_on ) { 3179pt .mark (kPfPle ,cs ); 3180const auto tp = Clock ::now (); 3181for (int64_t t = 0 ;t < T ;++ t ) { 3182 strata::kernels::PleOut po ; 3183po .normalized = m .ple_norm ; 3184po .result = m .R + t * D ; 3185try { 3186 strata::kernels::ple_block (m .ple_emb + t * N ,m .R + t * D ,ss .ple .hist ,ss .ple .w ,po , 3187ss .ple .scratch ,m .cs ); 3188 }catch (const std::exception & e ) {err = std::string ("prefill PLE: " )+ e .what ();return false; } 3189 strata::kernels::ple_history_advance (ss .ple .hist ,m .ple_norm ,m .cs ); 3190 } 3191stats_ .ms_ple += ms_since (tp ); 3192 } 3193for (int half = 0 ;half < 2 ;++ half ) { 3194// ---- the hyper-connection read of this half 3195const char * pre = half == 0 ?"hc_attn_" :"hc_ffn_" ; 3196const std::string sn = std::string (pre )+ "norm.weight" ,sd = std::string (pre )+ "down.weight" , 3197su = std::string (pre )+ "up.weight" ,si = std::string (pre )+ "inject.weight" ; 3198const core::WeightRef * wn = need (v ,sn .c_str (),err ),* wd = need (v ,sd .c_str (),err ), 3199* wu = need (v ,su .c_str (),err ),* wi = need (v ,si .c_str (),err ); 3200if (!wn || !wd || !wu || !wi )return false; 3201pt .mark (kPfHc ,cs ); 3202// the xn16 token stride of this chunk (the writers of both halves and of the fused write-backs use it) 3203const int64_t ldx = hc_pad ()&& T >= std::max < int64_t > (pf_switch_min_t (),64 )&& !gr_unfused ()&& 3204 !m .xn16_lo ?D + XN_PAD :D ; 3205if (gr_unfused ())gr_norm (m .R , (const float * )wn -> data ,EPS ,m .xn ,m .xn16 ,T ,m .cs ,m .xn16_lo ); 3206else if (!normed )gr_norm_rs (m .R , (const float * )wn -> data ,EPS ,m .grs ,m .xn16 ,T ,m .cs ,m .xn16_lo ,ldx ); 3207normed = false; 3208bool hcd = false; 3209bool hdown = false; 3210if (ldx != D && !pf_hcdown ()) {// STRATA_HCD_EXACT: the exact-order down kernel when hipBLASLt would take 1176 / 1177 3211hdown = wd -> kind == core::WeightKind ::Bf16InF32 && wd -> data && wd -> ne0 == D && wd -> ne1 == LR && 3212m .gemm .bf16_hcd_exact (m .xn16 ,ldx , (const uint16_t * )wd -> data ,m .lo ,T ,LR ,D ); 3213 }else if (ldx != D ) { 3214if (wd -> kind != core::WeightKind ::Bf16InF32 || !wd -> data || wd -> ne0 != D || wd -> ne1 != LR || 3215wi -> kind != core::WeightKind ::Bf16InF32 || !wi -> data || wi -> ne0 != D || wi -> ne1 != HC || 3216 !strata_pf_hcdown_bf16 (m .xn16 ,ldx , (const uint16_t * )wd -> data , (const uint16_t * )wi -> data ,LR , 3217HC ,m .lo ,m .inj ,T ,D ,m .cs )) { 3218err = "prefill: STRATA_PF_HCDOWN could not run the hyper-connection projections" ; 3219return false; 3220 } 3221hcd = true; 3222 } 3223if (!hcd && !hdown && !bf16_proj (m .gemm ,wd ,m .xn16 ,m .lo ,T ,sd ,err ,0 ,m .xn16_lo ,ldx != D ?ldx :0 ))return false; 3224gr_silu (m .lo ,m .lo16 ,T ,m .cs ,m .lo16_lo ); 3225bool upmixed = false; 3226if (hc_upmix ()&& T >=pf_switch_min_t ()&& !gr_unfused ()&& !m .lo16_lo && !m .mixed_bf_lo && 3227wu -> kind == core::WeightKind ::Bf16InF32 && wu -> data && wu -> ne0 == LR && wu -> ne1 == D ) { 3228static int checks = [] {const char * e = std::getenv ("STRATA_HC_UPMIX_CHECK" );return e ? std::atoi (e ) :0 ; }(); 3229if (checks > 0 ) {// the default pair first, kept for the comparison 3230-- checks ; 3231if (!bf16_proj (m .gemm ,wu ,m .lo16 ,m .gated ,T ,su ,err ))return false; 3232gr_mix_r (m .R ,m .grs , (const float * )wn -> data ,m .gated ,m .mixed ,m .mixed_bf ,T ,m .cs ,m .mixed_h ); 3233 std::vector < float > ref ((size_t )T * N ),got ((size_t )T * N ); 3234/* 3235DPCT1124: cudaMemcpyAsync is migrated to 3236asynchronous memcpy API. While the origin API might be 3237synchronous, it depends on the type of operand memory, 3238so you may need to call wait() on event return by memcpy 3239API to ensure synchronization behavior. 3240*/ 3241m .cs -> memcpy (ref .data (),m .mixed ,ref .size ()* 4 ); 3242upmixed = gr_upmix (m .lo16 , (const uint16_t * )wu -> data ,m .R ,m .grs , (const float * )wn -> data , 3243m .mixed ,m .mixed_bf ,m .mixed_h ,T ,m .cs ); 3244/* 3245DPCT1124: cudaMemcpyAsync is migrated to 3246asynchronous memcpy API. While the origin API might be 3247synchronous, it depends on the type of operand memory, 3248so you may need to call wait() on event return by memcpy 3249API to ensure synchronization behavior. 3250*/ 3251m .cs -> memcpy (got .data (),m .mixed ,got .size ()* 4 ); 3252m .cs -> wait (); 3253double e2 = 0 ,r2 = 0 ,emax = 0 ; 3254for (size_t i = 0 ;i < ref .size ();++ i ) { 3255const double dd = (double )got [i ]- ref [i ]; 3256e2 += dd * dd ;r2 += (double )ref [i ]* ref [i ];emax = std::max (emax , std::fabs (dd )); 3257 } 3258 std::fprintf (stderr ,"strata: STRATA_HC_UPMIX_CHECK layer %lld half %d T %lld: mixed rel RMS %.3e, " 3259"max |diff| %.3e (%s)\n" , (long long )l ,half , (long long )T , 3260 std::sqrt (e2 / std::max (r2 ,1e-30 )),emax ,upmixed ?"upmix" :"upmix refused" ); 3261 }else { 3262upmixed = gr_upmix (m .lo16 , (const uint16_t * )wu -> data ,m .R ,m .grs , (const float * )wn -> data , 3263m .mixed ,m .mixed_bf ,m .mixed_h ,T ,m .cs ); 3264 } 3265 } 3266if (!upmixed && !bf16_proj (m .gemm ,wu ,m .lo16 ,m .gated ,T ,su ,err ,0 ,m .lo16_lo ))return false; 3267if (!hcd && !bf16_proj (m .gemm ,wi ,m .xn16 ,m .inj ,T ,si ,err ,0 ,m .xn16_lo ,ldx != D ?ldx :0 ))return false; 3268if (upmixed ) { 3269 }else if (gr_unfused ()) { 3270gr_mix (m .xn ,m .gated ,m .mixed ,m .mixed_bf ,T ,m .cs ,m .mixed_h ,m .mixed_bf_lo ); 3271 }else { 3272gr_mix_r (m .R ,m .grs , (const float * )wn -> data ,m .gated ,m .mixed ,m .mixed_bf ,T ,m .cs ,m .mixed_h , 3273m .mixed_bf_lo ); 3274 } 3275 3276if (half == 0 && !core::is_qsa_layer (g ,l )) { 3277// ======================= GDN ======================= 3278const core::WeightRef * wqkv = need (v ,"attn_qkv.weight" ,err ),* wg = need (v ,"attn_gate.weight" ,err ), 3279* wo = need (v ,"ssm_out.weight" ,err ),* wa = need (v ,"ssm_alpha.weight" ,err ), 3280* wb = need (v ,"ssm_beta.weight" ,err ),* wc = need (v ,"ssm_conv1d.weight" ,err ), 3281* wnm = need (v ,"ssm_norm.weight" ,err ),* wdt = need (v ,"ssm_dt.bias" ,err ), 3282* wsa = need (v ,"ssm_a" ,err ); 3283if (!wqkv || !wg || !wo || !wa || !wb || !wc || !wnm || !wdt || !wsa )return false; 3284pt .mark (kPfGdn ,cs ); 3285float * state = ss .gdn_state + (size_t ) (gdn_index - ss .gdn_ord0 )* gdn_floats ; 3286float * conv = state + (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size ; 3287static int64_t pfh_chunk = -1 ; 3288const bool pfh_on = pf_hash_file ()!= nullptr && gdn_index == 0 ; 3289if (pfh_on )++ pfh_chunk ; 3290auto pfh = [& ](const char * nm ,const void * dev ,int64_t rows ,size_t rowbytes ) { 3291if (!pfh_on )return ; 3292m .cs -> wait (); 3293 std::vector < char > hb ((size_t )rows * rowbytes ); 3294m .cs -> memcpy (hb .data (),dev ,hb .size ()).wait (); 3295for (int64_t r = 0 ;r < rows ;++ r ) 3296 std::fprintf (pf_hash_file (),"%lld %s %lld %016llx\n" , (long long )pfh_chunk ,nm , (long long )r , 3297 (unsigned long long )pf_hash_fnv (hb .data ()+ (size_t )r * rowbytes ,rowbytes )); 3298 std::fflush (pf_hash_file ()); 3299 }; 3300pfh ("mixed" ,m .mixed ,T ,N * 4 ); 3301if (!native_proj (m .gemm ,wqkv ,m .mixed_h ,m .qkv ,T ,v .name ("attn_qkv.weight" ),err ))return false; 3302pfh ("qkv" ,m .qkv ,T ,C * 4 ); 3303if (!native_proj (m .gemm ,wg ,m .mixed_h ,m .z ,T ,v .name ("attn_gate.weight" ),err ))return false; 3304pfh ("z" ,m .z ,T ,ZV * 4 ); 3305if (!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; 3306if (!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; 3307pfh ("ab" ,m .ab ,T ,2 * HV * 4 ); 3308pt .mark (kPfGdnConv ,cs );// "gdn" is the projections in; the rest on their own lines 3309gdn_gates (m .ab , (const float * )wdt -> data , (const float * )wsa -> data ,m .gate ,m .beta ,T ,m .cs ); 3310gdn_conv (conv ,m .qkv , (const float * )wc -> data ,m .hbuf ,T ,EPS ,m .cs ); 3311pfh ("gate" ,m .gate ,T ,HV * 4 ); 3312pfh ("beta" ,m .beta ,T ,HV * 4 ); 3313pfh ("hbuf" ,m .hbuf ,T ,C * 4 ); 3314pt .mark (kPfGdnRec ,cs ); 3315const int64_t ld_y = pf_pad ()&& T >= std::max < int64_t > (pf_switch_min_t (),64 ) ?ZV + ZV_PAD :0 ; 3316gdn_recurrence (state ,m .hbuf ,m .gate ,m .beta ,m .z , (const float * )wnm -> data ,EPS ,m .y ,m .y_h ,T ,m .cs , 3317ld_y ); 3318pfh ("y" ,m .y ,T ,ZV * 4 ); 3319pfh ("state_rec" ,state ,HV , (size_t )g .ssm_state_size * g .ssm_state_size * 4 ); 3320pt .mark (kPfGdnOut ,cs ); 3321if (!native_proj (m .gemm ,wo ,m .y_h ,m .bo ,T ,v .name ("ssm_out.weight" ),err ,0 ,ld_y ))return false; 3322++ gdn_index ; 3323 }else if (half == 0 ) { 3324// ======================= QSA ======================= 3325const core::QsaState & st = ss .qsa_states [qsa_index ]; 3326const core::WeightRef * wq = need (v ,"attn_q.weight" ,err ),* wk = need (v ,"attn_k.weight" ,err ), 3327* wv = need (v ,"attn_v.weight" ,err ),* wo = need (v ,"attn_output.weight" ,err ), 3328* wik = need (v ,"indexer.k_proj.weight" ,err ), 3329* wiq = need (v ,"indexer.q_proj.weight" ,err ), 3330* wqn = need (v ,"attn_q_norm.weight" ,err ),* wkn = need (v ,"attn_k_norm.weight" ,err ), 3331* wiqn = need (v ,"indexer.q_norm.weight" ,err ), 3332* wikn = need (v ,"indexer.k_norm.weight" ,err ); 3333if (!wq || !wk || !wv || !wo || !wik || !wiq || !wqn || !wkn || !wiqn || !wikn )return false; 3334pt .mark (kPfQsa ,cs ); 3335if (!native_proj (m .gemm ,wk ,m .mixed_h ,m .Kc ,T ,v .name ("attn_k.weight" ),err ))return false; 3336if (!native_proj (m .gemm ,wv ,m .mixed_h ,m .Vc ,T ,v .name ("attn_v.weight" ),err ))return false; 3337if (!native_proj (m .gemm ,wq ,m .mixed_h ,m .Qf ,T ,v .name ("attn_q.weight" ),err ))return false; 3338if (!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; 3339if (!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; 3340rms_rows (m .Kc , (const float * )wkn -> data ,T * kNKv ,kHeadDim ,kHeadDim ,EPS ,m .cs ); 3341rope (m .Kc ,T ,kNKv ,kHeadDim ,kKvW ,p0 , strata::kernels::rope_scaling (),m .cs ); 3342// KV streaming: this layer's cells [0, p0) come in from the host copy to the staging pool, and the 3343// chunk's cells go to the host copy, the staging pool, and the VRAM slots of resident blocks 3344const bool staged = st .kv_mode == 1 ; 3345if (staged ) { 3346pt .mark (kPfKvStage ,cs ); 3347if (kv_pending == qsa_index ) { 3348if (DPCT_CHECK_ERROR (cs -> ext_oneapi_submit_barrier ( 3349 {* m .kv_ready }))!= 0 ) { 3350err = "prefill: waiting for KV prefetch" ; 3351return false; 3352 } 3353kv_pending = -1 ; 3354 }else strata::kernels::kv_stage_from_host (pools_of (m .stage ,m .ident_table ),st .host , 3355 core::qsa_kv_format (st ), 3356 (p0 + s .page_size - 1 ) /s .page_size ,s ,m .cs ); 3357pt .mark (kPfQsa ,cs ); 3358pf_step ("reading the prompt (batched, step sync): the K/V staged from RAM at layer" ,l ); 3359 } 3360// #579 #613 (HIP, opt-in A/B, STRATA_KV_HOST_DMA=1): the append writes the staging pool and the 3361// resident slots only, and one DMA copies the chunk's blocks from the staging pool to the host copy 3362// - no kernel writes host memory over PCIe. The bytes every reader sees are the same (the staged 3363// first block is complete; past the chunk's last cell nothing is read until a later append writes 3364// it). CUDA: never. 3365#if defined(STRATA_USE_HIP ) 3366static const bool kv_host_dma = [] {const char * e = std::getenv ("STRATA_KV_HOST_DMA" );return e && e [0 ]== '1' ; }(); 3367#else 3368constexpr bool kv_host_dma = false; 3369#endif 3370const bool host_by_dma = staged && kv_host_dma ; 3371const strata::kernels::KvHostPools * host_w = host_by_dma ?nullptr :& st .host ; 3372if (st .kv_hybrid ) {// K8V4: K INT8 unrotated, V rotated Q4_0 (only V and the output rotate) 3373// streamed: each half writes its part of the host copy and of the staging pool 3374 strata::kernels::fwht256_inplace_cuda (m .Vc ,T * kNKv ,m .cs ); 3375const strata::kernels::KvHostPools hk = strata::kernels::kv_hybrid_k_half (st .host ), 3376hv = strata::kernels::kv_hybrid_v_half (st .host ), 3377sk = strata::kernels::kv_hybrid_k_half (m .stage ), 3378sv = strata::kernels::kv_hybrid_v_half (m .stage ); 3379const bool mirror = st .host .present (); 3380kv_append (m .Kc ,m .Kc ,T ,p0 ,st .page_table ,s .page_size ,nullptr ,nullptr , 3381st .k_q ,st .k_q ,st .k_scale ,st .k_scale ,m .cs ,mirror ?& hk :nullptr , 3382staged ?& sk :nullptr ); 3383 strata::kernels::kv_append_q4 (st .v_q4 ,st .v_q4 ,st .page_table ,p0 ,T ,m .Vc ,m .Vc ,s ,m .cs , 3384mirror ?& hv :nullptr ,staged ?& sv :nullptr ); 3385 }else { 3386if (st .kv_rot ) {// rotated K and V (kv_q4.hpp), the queries below too, the output back 3387 strata::kernels::fwht256_inplace_cuda (m .Kc ,T * kNKv ,m .cs ); 3388 strata::kernels::fwht256_inplace_cuda (m .Vc ,T * kNKv ,m .cs ); 3389 } 3390if (st .kv_q4 ) 3391 strata::kernels::kv_append_q4 (st .k_q4 ,st .v_q4 ,st .page_table ,p0 ,T ,m .Kc ,m .Vc ,s ,m .cs , 3392host_w ,staged ?& m .stage :nullptr ); 3393else 3394kv_append (m .Kc ,m .Vc ,T ,p0 ,st .page_table ,s .page_size ,st .kv_int8 ?nullptr :st .k_pool , 3395st .kv_int8 ?nullptr :st .v_pool ,st .k_q ,st .v_q ,st .k_scale ,st .v_scale ,m .cs , 3396host_w ,staged ?& m .stage :nullptr ); 3397if (host_by_dma ) 3398 strata::kernels::kv_unstage_to_host (pools_of (m .stage ,m .ident_table ),st .host , 3399 core::qsa_kv_format (st ),p0 /s .page_size , 3400 (p0 + T + s .page_size - 1 ) /s .page_size ,s ,m .cs ); 3401 } 3402if (staged )pf_step ("reading the prompt (batched, step sync): the K/V append at layer" ,l ); 3403split_q (m .Qf ,m .q ,T ,m .cs ); 3404rms_rows (m .q , (const float * )wqn -> data ,T * kNHead ,kHeadDim ,kHeadDim ,EPS ,m .cs ); 3405rope (m .q ,T ,kNHead ,kHeadDim ,kQW ,p0 , strata::kernels::rope_scaling (),m .cs ); 3406if (st .kv_rot ) strata::kernels::fwht256_inplace_cuda (m .q ,T * kNHead ,m .cs ); 3407rms_rows (m .q_idx , (const float * )wiqn -> data ,T * kIdxQHeads ,kIdxK ,kIdxK ,EPS ,m .cs ); 3408rope (m .q_idx ,T ,kIdxQHeads ,kIdxK ,kIdxQW ,p0 , strata::kernels::rope_scaling (),m .cs ); 3409// the indexer appends, token by token; then scores + selection for many queries at once: 3410// a query reads completed blocks (final once completed) and `dead` for its own tail block 3411const strata::kernels::QsaIndexerBuffers ib {st .idx_tail ,st .idx_dead ,st .idx_pooled ,st .idx_block_pos }; 3412pt .mark (kPfQsaIdx ,cs ); 3413// C-2: the chunk's appends in three launches instead of one per token (the same end state: 3414// the queries below read it only after the whole chunk is appended). STRATA_INDEXER_PER_TOKEN=1: the old 3415try { 3416static const bool per_token = std::getenv ("STRATA_INDEXER_PER_TOKEN" )!= nullptr ; 3417if (!per_token ) { 3418 strata::kernels::native_qsa_indexer_append_batch (m .idx_raw ,T ,p0 ,0 , (const float * )wikn -> data , 3419EPS ,ib ,s ,st .max_cells , 3420 strata::kernels::rope_scaling (),m .cs ); 3421 } 3422for (int64_t t = 0 ;per_token && t < T ;++ t ) { 3423const int32_t * step_t = m .steps_dev + t * strata::kernels::kStepCount ; 3424 strata::kernels::native_qsa_indexer_append (m .idx_raw + t * kIdxK ,step_t + strata::kernels::kStepPos ,0 , 3425 (const float * )wikn -> data ,EPS ,ib ,s ,st .max_cells , 3426 strata::kernels::rope_scaling (),m .cs ); 3427 } 3428 }catch (const std::exception & e ) {err = std::string ("prefill indexer: " )+ e .what ();return false; } 3429pt .mark (kPfQsaSel ,cs ); 3430for (int64_t t0 = 0 ;t0 < T ;t0 += m .sel_batch ) { 3431const int64_t nb = std::min (m .sel_batch ,T - t0 ); 3432const int32_t * steps0 = m .steps_dev + t0 * strata::kernels::kStepCount ; 3433// C-1: the grid reaches the batch's last query's n_bid (they rise with the position) 3434const int64_t active = (int64_t )m .steps_host [(size_t ) ((t0 + nb - 1 )* strata::kernels::kStepCount + 3435 strata::kernels::kStepNBid )]+ 1 ; 3436// the scores on tensor cores (3xTF32: FP32-level, not bitwise); STRATA_SELECT_OLD=1: the warp kernel 3437static const bool old_sel = std::getenv ("STRATA_SELECT_OLD" )!= nullptr ; 3438// SYCL port: the scores as oneMKL FP32 GEMM tiles (pooled keys x the batch's indexer queries) 3439// and a relu-sum (qsa_block_scores_reduce), FP32-level like the CUDA build's 3xTF32 path. The 3440// tile lives in the attention scratch, which is free until this layer's attention (same 3441// queue). It pays from ~8K cells on a B70 (launch cost below: -2% at 2K, even at 8K, select 3442// 3x faster at 40K), so by default only for a batch reaching 2,048 blocks. 3443// STRATA_SELECT_GEMM=0: the warp kernel always, =1: the GEMM always (on every card). 3444// Unset: the default from 2,048 blocks is for a Battlemage card only. It changes the answers (first-token 3445// KL ~1e-9 on an Arc A750 up to 128K, 1e-5 to 1e-3 on 2x B65), and on the A750 it gained +0.2% to 3446// +0.6% (16K to 128K: its prompts are bound by expert streaming over PCIe), under the 5% bar. 3447static const int sel_gemm_mode = [] {const char * v = std::getenv ("STRATA_SELECT_GEMM" );return v ? std::atoi (v ) :-1 ; }(); 3448static const int64_t sel_gemm_min = [] {const char * v = std::getenv ("STRATA_SELECT_GEMM_MIN" );return v ? (int64_t ) std::atoll (v ) : (int64_t )2048 ; }();// blocks (4 cells each) 3449const bool sel_gemm = sel_gemm_mode > 0 || (sel_gemm_mode < 0 && active >= sel_gemm_min && 3450 strata::intel_gpu_gen (m .cs -> get_device ())== strata::IntelGpuGen ::Battlemage ); 3451const int64_t sel_tile = std::min < int64_t > (8192 , (int64_t ) ((uint64_t )m .attn_batch * 3452 strata::kernels::qsa_decode_attn_scratch_floats (m .cap ,s ) / (uint64_t ) (nb * 4 ))); 3453bool sel_done = false; 3454if (sel_gemm && !old_sel && m .attn_scratch != nullptr && s .idx_dim == 128 && s .idx_n_head == 4 && 3455sel_tile >=256 ) { 3456try { 3457for (int64_t b0 = 0 ;b0 < active ;b0 += sel_tile ) { 3458const int64_t nbk = std::min < int64_t > (sel_tile ,active - b0 ); 3459 oneapi::mkl::blas::column_major::gemm (* m .cs , oneapi::mkl::transpose::trans , 3460 oneapi::mkl::transpose::nontrans ,nbk ,nb * 4 ,128 , 34611.0f ,st .idx_pooled + b0 * 128 ,128 , 3462m .q_idx + t0 * kIdxQW ,128 ,0.0f ,m .attn_scratch , 3463sel_tile ); 3464 strata::kernels::qsa_block_scores_reduce (m .attn_scratch ,sel_tile ,b0 ,nbk ,st .idx_dead , 3465m .q_idx + t0 * kIdxQW ,steps0 ,nb ,m .max_blocks , 3466m .sel_scores ,m .cs ); 3467 } 3468sel_done = true; 3469 }catch (const std::exception & ex ) { 3470static bool said = false; 3471if (!said ) std::fprintf (stderr ,"prefill: the GEMM block scores failed (%s); the warp kernel instead\n" ,ex .what ()); 3472said = true; 3473 } 3474 } 3475if (!sel_done && (old_sel || !strata::kernels::qsa_block_scores_tc (st .idx_pooled ,st .idx_dead ,m .q_idx + t0 * kIdxQW , 3476steps0 ,nb ,m .max_blocks ,s ,m .sel_scores , 3477m .cs ,active ))) 3478 strata::kernels::qsa_block_scores (st .idx_pooled ,st .idx_dead ,m .q_idx + t0 * kIdxQW ,steps0 ,nb , 3479m .max_blocks ,s ,m .sel_scores ,m .cs ,active ); 3480 strata::kernels::qsa_block_topk (m .sel_scores ,steps0 ,nb ,m .max_blocks ,m .cap ,s , 3481m .sel_ids + t0 * m .cap ,m .cs ,active ); 3482 } 3483// STRATA_SEL_OVERLAP (debug, D-1's question): how much do neighbouring queries' selections share? 3484// Per tile of 16 queries: the union of their selected cells against the sum of their widths. 3485if (static const bool ovl = std::getenv ("STRATA_SEL_OVERLAP" )!= nullptr ;ovl && qsa_index == 0 ) { 3486 std::vector < int32_t > ids ((size_t ) (T * m .cap )); 3487/* 3488DPCT1124: cudaMemcpyAsync is migrated to 3489asynchronous memcpy API. While the origin API might be 3490synchronous, it depends on the type of operand memory, 3491so you may need to call wait() on event return by memcpy 3492API to ensure synchronization behavior. 3493*/ 3494m .cs -> memcpy (ids .data (),m .sel_ids ,ids .size ()* 4 ); 3495m .cs -> wait (); 3496double sum_w = 0 ,sum_u = 0 ; 3497for (int64_t t0 = 0 ;t0 + 16 <=T ;t0 += 16 ) { 3498 std::vector < int32_t > u ; 3499for (int64_t t = t0 ;t < t0 + 16 ;++ t ) { 3500const int64_t w = m .steps_host [(size_t ) (t * strata::kernels::kStepCount + strata::kernels::kStepWidth )]; 3501sum_w += (double )w ; 3502u .insert (u .end (),ids .begin ()+ t * m .cap ,ids .begin ()+ t * m .cap + w ); 3503 } 3504 std::sort (u .begin (),u .end ()); 3505sum_u += (double ) (std::unique (u .begin (),u .end ())- u .begin ()); 3506 } 3507 std::fprintf (stderr ,"strata prefill: selection overlap at %lld: 16-query tiles read %.1f%% of the " 3508"cells one query at a time does\n" , (long long )p0 ,sum_w > 0 ?100.0 * sum_u /sum_w :0.0 ); 3509 } 3510// STRATA_IDX_FP16_CHECK: would FP16 pooled indexer keys select the same cells? (the KV-streaming 3511// design's last question). Every query is selected again from the pooled keys and `dead` rounded 3512// to fp16 (exactly what an fp16 store reads back); the agreement with the fp32 selection is 3513// printed cumulatively after each chunk's last QSA layer. Debug: syncs per layer. 3514if (static const bool f16chk = std::getenv ("STRATA_IDX_FP16_CHECK" )!= nullptr ;f16chk ) { 3515static float * pooled16 = nullptr ,* dead16 = nullptr ; 3516static int32_t * ids16 = nullptr ; 3517static double shared = 0 ,cells = 0 ; 3518static long long queries = 0 ,same = 0 ,sel_queries = 0 ; 3519const int64_t rows = st .idx_pooled_rows ; 3520if (pooled16 == nullptr && 3521 (DPCT_CHECK_ERROR ( 3522pooled16 = (float * )sycl::malloc_device ( 3523 (size_t )rows * s .idx_dim * 4 , 3524 dpct::get_in_order_queue ()))!= 0 || 3525DPCT_CHECK_ERROR ( 3526dead16 = (float * )sycl::malloc_device ( 3527 (size_t )s .idx_dim * 4 , 3528 dpct::get_in_order_queue ()))!= 0 || 3529DPCT_CHECK_ERROR ( 3530ids16 = (int32_t * )sycl::malloc_device ( 3531 (size_t )(m .T * m .cap )* 4 , 3532 dpct::get_in_order_queue ()))!= 0 )) { 3533err = "STRATA_IDX_FP16_CHECK: no room for its buffers" ; 3534return false; 3535 } 3536round_f16 (st .idx_pooled ,pooled16 ,rows * s .idx_dim ,m .cs ); 3537round_f16 (st .idx_dead ,dead16 ,s .idx_dim ,m .cs ); 3538for (int64_t t0 = 0 ;t0 < T ;t0 += m .sel_batch ) { 3539const int64_t nb = std::min (m .sel_batch ,T - t0 ); 3540const int32_t * steps0 = m .steps_dev + t0 * strata::kernels::kStepCount ; 3541 strata::kernels::qsa_block_scores (pooled16 ,dead16 ,m .q_idx + t0 * kIdxQW ,steps0 ,nb , 3542m .max_blocks ,s ,m .sel_scores ,m .cs ); 3543 strata::kernels::qsa_block_topk (m .sel_scores ,steps0 ,nb ,m .max_blocks ,m .cap ,s , 3544ids16 + t0 * m .cap ,m .cs ); 3545 } 3546 std::vector < int32_t > a ((size_t ) (T * m .cap )),b ((size_t ) (T * m .cap )); 3547/* 3548DPCT1124: cudaMemcpyAsync is migrated to 3549asynchronous memcpy API. While the origin API might be 3550synchronous, it depends on the type of operand memory, 3551so you may need to call wait() on event return by memcpy 3552API to ensure synchronization behavior. 3553*/ 3554m .cs -> memcpy (a .data (),m .sel_ids ,a .size ()* 4 ); 3555/* 3556DPCT1124: cudaMemcpyAsync is migrated to 3557asynchronous memcpy API. While the origin API might be 3558synchronous, it depends on the type of operand memory, 3559so you may need to call wait() on event return by memcpy 3560API to ensure synchronization behavior. 3561*/ 3562m .cs -> memcpy (b .data (),ids16 ,b .size ()* 4 ); 3563m .cs -> wait (); 3564for (int64_t t = 0 ;t < T ;++ t ) { 3565const int64_t w = m .steps_host [(size_t ) (t * strata::kernels::kStepCount + strata::kernels::kStepWidth )]; 3566const int32_t * x = a .data ()+ t * m .cap ,* y = b .data ()+ t * m .cap ; 3567int64_t i = 0 ,j = 0 ,c = 0 ; 3568while (i < w && j < w ) { 3569if (x [i ]== y [j ]) {++ c ;++ i ;++ j ; }else if (x [i ]< y [j ])++ i ;else ++ j ; 3570 } 3571++ queries ; 3572same += c == w ; 3573if (p0 + t + 1 > m .cap ) {++ sel_queries ;shared += (double )c ;cells += (double )w ; } 3574 } 3575if (qsa_index + 1 == g .n_qsa_layers ()) 3576 std::fprintf (stderr ,"strata prefill: FP16 indexer keys: %lld of %lld selections identical; " 3577"where the selection is sparse, %.4f%% of cells shared (%lld queries)\n" , 3578same ,queries ,cells > 0 ?100.0 * shared /cells :100.0 ,sel_queries ); 3579 } 3580// STRATA_QSA_DUMP=<file>: append every QSA layer's selected cells for the prompt's last 3581// STRATA_QSA_DUMP_LAST (4096) positions - records of int32 {qsa layer, pos0, T, cap} + T*cap cells, 3582// for tools/qsa_locality.py (how local the sparse attention's reads are: the KV-streaming question) 3583if (static const char * dump = std::getenv ("STRATA_QSA_DUMP" );dump != nullptr ) { 3584static const long long last = std::getenv ("STRATA_QSA_DUMP_LAST" ) 3585 ? std::atoll (std::getenv ("STRATA_QSA_DUMP_LAST" )) :4096 ; 3586if (p0 + T > pos0 + n - last ) { 3587 std::vector < int32_t > h ((size_t ) (T * m .cap )); 3588/* 3589DPCT1124: cudaMemcpyAsync is migrated to 3590asynchronous memcpy API. While the origin API might 3591be synchronous, it depends on the type of operand 3592memory, so you may need to call wait() on event 3593return by memcpy API to ensure synchronization 3594behavior. 3595*/ 3596m .cs -> memcpy (h .data (),m .sel_ids ,h .size ()* 4 ); 3597m .cs -> wait (); 3598if (std::FILE * f = std::fopen (dump ,"ab" )) { 3599const int32_t hdr [4 ]= {(int32_t )qsa_index , (int32_t )p0 , (int32_t )T , (int32_t )m .cap }; 3600 std::fwrite (hdr ,4 ,4 ,f ); 3601 std::fwrite (h .data (),4 ,h .size (),f ); 3602 std::fclose (f ); 3603 } 3604 } 3605 } 3606const strata::kernels::QsaAttnPools pools = staged ?pools_of (m .stage ,m .ident_table ) 3607 : core::qsa_attn_pools (st ); 3608pt .mark (kPfQsaAttn ,cs ); 3609// perf-review D-1: the whole chunk on tensor cores, one block per (query, KV head), FP32-level 3610// accuracy but not bitwise (qsa_prompt_attn.hpp). Q4_0 KV, or STRATA_PROMPT_ATTN_OLD=1: the 3611// decode kernel, 32 queries at a time (K8V4 runs the tensor kernel's mode 3: INT8 K, 3612// V dequantized from its q4_0 blocks to fp16 at gather) 3613static const bool old_attn = std::getenv ("STRATA_PROMPT_ATTN_OLD" )!= nullptr ; 3614// STRATA_DUMP_SEL=<file>: the selected cells of every prompt position of the first QSA layer of the 3615// last chunk (int32 T, cap, then T*cap ids and T widths) - the input to the grouped-gather study 3616if (static const char * dsel = std::getenv ("STRATA_DUMP_SEL" );dsel && c0 + T >=n && qsa_index == 0 ) { 3617m .cs -> wait (); 3618 std::vector < int32_t > ids_h ((size_t )T * m .cap ),st_h ((size_t )T * strata::kernels::kStepCount ); 3619m .cs -> memcpy (ids_h .data (),m .sel_ids ,ids_h .size ()* 4 ).wait (); 3620m .cs -> memcpy (st_h .data (),m .steps_dev ,st_h .size ()* 4 ).wait (); 3621if (FILE * f = std::fopen (dsel ,"wb" )) { 3622const int32_t hdr [2 ]= {(int32_t )T , (int32_t )m .cap }; 3623 std::fwrite (hdr ,4 ,2 ,f ); 3624 std::fwrite (ids_h .data (),4 ,ids_h .size (),f ); 3625for (int64_t t = 0 ;t < T ;++ t ) { 3626const int32_t w = st_h [(size_t )t * strata::kernels::kStepCount + strata::kernels::kStepWidth ]; 3627 std::fwrite (& w ,4 ,1 ,f ); 3628 } 3629 std::fclose (f ); 3630 std::fprintf (stderr ,"strata: selection of %lld positions dumped to %s\n" , (long long )T ,dsel ); 3631 } 3632 } 3633if (old_attn || !strata::kernels::qsa_prompt_attn_batch (m .q ,pools ,m .sel_ids ,m .steps_dev ,m .cap ,s , 3634m .attn ,T ,m .cs )) 3635for (int64_t t0 = 0 ;t0 < T ;t0 += m .attn_batch ) { 3636const int64_t nb = std::min (m .attn_batch ,T - t0 ); 3637#ifdef STRATA_SYCL_TLA_ATTN 3638static const bool tla_attn = [] {const char * v = std::getenv ("STRATA_SYCL_TLA_ATTN" );return v && v [0 ]== '1' ; }(); 3639if (tla_attn && nb == 32 && m .cap == 2051 && 3640 strata::kernels::qsa_prompt_attn_tla_batch (m .q + t0 * kQW ,pools ,m .sel_ids + t0 * m .cap , 3641m .steps_dev + t0 * strata::kernels::kStepCount ,m .cap ,s ,m .attn_scratch , 3642m .attn + t0 * ZV ,nb ,m .cs ))continue ; 3643#endif 3644// SYCL port: the scores one work-item per cell (qsa_prompt_attn_percell, 128-cell chunks; 3645// FP32, not bitwise with the warp kernel). STRATA_ATTN_PERCELL=0: the warp kernel. 3646static const bool percell = [] {const char * v = std::getenv ("STRATA_ATTN_PERCELL" );return !v || v [0 ]!= '0' ; }(); 3647if (percell ) { 3648 strata::kernels::qsa_prompt_attn_percell (m .q + t0 * ZV ,pools ,m .sel_ids + t0 * m .cap , 3649m .steps_dev + t0 * strata::kernels::kStepCount ,m .cap , 3650s ,m .attn_scratch ,m .attn + t0 * ZV ,nb ,m .cs ); 3651continue ; 3652 } 3653 strata::kernels::qsa_decode_attn_batch (m .q + t0 * kQW ,pools ,m .sel_ids + t0 * m .cap , 3654m .steps_dev + t0 * strata::kernels::kStepCount ,m .cap , 3655s ,m .attn_scratch ,m .attn + t0 * kQW ,nb ,m .cs ); 3656 } 3657if (st .kv_rot || st .kv_hybrid ) strata::kernels::fwht256_inplace_cuda (m .attn ,T * kNHead ,m .cs ); 3658pt .mark (kPfQsa ,cs ); 3659const int64_t ld_a = pf_pad ()&& T >= std::max < int64_t > (pf_switch_min_t (),64 ) ?ZV + ZV_PAD :0 ; 3660gate_attn (m .attn ,m .Qf ,m .attn_h ,T ,m .cs ,ld_a ); 3661if (!native_proj (m .gemm ,wo ,m .attn_h ,m .bo ,T ,v .name ("attn_output.weight" ),err ,0 ,ld_a ))return false; 3662++ qsa_index ; 3663if (!kv_prefetch_after (l + 1 ,qsa_index ))return false; 3664 }else { 3665// ======================= MoE ======================= 3666const core::WeightRef * wr = need (v ,"ffn_gate_inp.weight" ,err ), 3667* wgi = need (v ,"ffn_gate_inp_shexp.weight" ,err ), 3668* wsg = need (v ,"ffn_gate_shexp.weight" ,err ), 3669* wsu = need (v ,"ffn_up_shexp.weight" ,err ), 3670* wsd = need (v ,"ffn_down_shexp.weight" ,err ); 3671if (!wr || !wgi || !wsg || !wsu || !wsd )return false; 3672pt .mark (kPfRouter ,cs ); 3673if (!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; 3674route (m .logits ,m .ids ,m .w ,T ,m .g -> n_expert ,m .cs ); 3675// the shared expert and its scalar gate 3676if (!native_proj (m .gemm ,wsg ,m .mixed_h ,m .sgate ,T ,v .name ("ffn_gate_shexp.weight" ),err ))return false; 3677if (!native_proj (m .gemm ,wsu ,m .mixed_h ,m .sup ,T ,v .name ("ffn_up_shexp.weight" ),err ))return false; 3678swiglu_pair (m .sgate ,m .sup ,m .sh_h ,T ,m .cs ); 3679if (!native_proj (m .gemm ,wsd ,m .sh_h ,m .shared ,T ,v .name ("ffn_down_shexp.weight" ),err ))return false; 3680if (wgi -> kind != core::WeightKind ::Bf16InF32 ) {err = "prefill: shared gate is not BF16" ;return false; } 3681m .gemm .bf16 (m .mixed_bf , (const uint16_t * )wgi -> data ,m .sg ,T ,1 ,N ); 3682if (m .mixed_bf_lo )m .gemm .bf16 (m .mixed_bf_lo , (const uint16_t * )wgi -> data ,m .sg ,T ,1 ,N ,0 ,1.0f ); 3683// #136: STRATA_PF_FUSED=1 - the Q2_0 pack's experts on the fused int8 kernels (moe_fused.hpp), 3684// grouped on the GPU: no host sync. Only where every expert's place is known before the routing - 3685// the streamed walk, in which every non-resident expert of the layer comes through the ring in id 3686// order - and where the MMQ buffers exist: they hold the fused path's own (the per-token int8 3687// activations in Xq, the int8 H in H, the grouping tables in GU). Chunks below stream_all_min() 3688// keep MMQ; without the variable nothing here runs. A native pack's layer takes the native kernels 3689// (moe_fused_iq.hpp) where they cover its two formats, else MMQ (or the FP16 path: IQ1_M). 3690const strata::kernels::cpu::ExpertLayout & lay = strata::kernels::cpu::expert_layout (); 3691const bool use_mmq = mmq_plan ().any && mmq_plan ().layer [(size_t )l ]; 3692// APR (prism.hadamard): folded gate/up take H (s * x) on the gathered fp16 rows, folded down H (s * h) on 3693// the fp16 SwiGLU output, both rotated in fp16 storage with fp32 arithmetic (as the CUDA FP16 path does). 3694// The fused int8 products and the MMQ path do not rotate; they take only formats of unfolded layers. 3695const bool had_gu = lay .native && lay .fmt [(size_t )l ].had_gu ; 3696const bool had_d = lay .native && lay .fmt [(size_t )l ].had_d ; 3697const int had_block = lay .native ?lay .fmt [(size_t )l ].had_block :0 ; 3698const float * had_sx = had_gu ?m .had_sx [(size_t )l ] :nullptr ; 3699const float * had_sh = had_d ?m .had_sh [(size_t )l ] :nullptr ; 3700auto had_h = [& ](int64_t row0 ,int64_t nrows ) { 3701if (had_d ) strata::kernels::hadamard_rows_f16 (m .Hh + row0 * kFF ,nrows ,kFF ,had_block ,had_sh ,m .cs ); 3702 }; 3703const int mmq_gt = lay .native ?lay .fmt [(size_t )l ].gu_type :42 ; 3704const int mmq_dt = lay .native ?lay .fmt [(size_t )l ].d_type :42 ; 3705// --peer-device: MMQ only, whether or not the peer took the prompt path (set_peer can decline), as 3706// fused_ring() sized the ring and the buffers for it 3707const bool no_peer = !core::peer_portable (); 3708const bool fused_only = mmq_plan ().any && mmq_plan ().fo [(size_t )l ]; 3709const bool fused_nat = (use_mmq || fused_only )&& stream_all && no_peer && lay .native && fused::native_supported (mmq_gt ,mmq_dt ); 3710const bool fused_l = (use_mmq && stream_all && no_peer && !lay .native && fused::enabled ())|| fused_nat ; 3711// #583 / #954: the fused layout's GU/H/Xq hold the grouping tables and the int8 rows, sized for 3712// stream_all_min() - 1 tokens of MMQ's rows, so a layer that takes MMQ or the FP16 path at the FULL 3713// chunk would write T*K rows into a (stream_all_min() - 1)*K-row buffer: an illegal access, or a kernel 3714// that never returns (the first ck() to see it is `prefill mmq: iota`, one prompt later). fused_layout() 3715// and fused_ring() keep the shrink and this decision in step; this is the backstop for anything that 3716// drifts: a clear error, never a hang. 3717// STRATA_DBG_FORCE_SLOW_LAYER=1 (a test of the backstop): layer 0 counts as one the fused path does not take 3718static const bool force_slow = [] {const char * e = std::getenv ("STRATA_DBG_FORCE_SLOW_LAYER" );return e && e [0 ]== '1' ; }(); 3719if ((!fused_l || (force_slow && l == 0 ))&& m .fused_bufs && T >=stream_all_min ()) { 3720err = "prefill: the fused layout's MoE buffers are too small for layer " + std::to_string (l )+ 3721"'s expert path at a chunk of " + std::to_string (T )+ " tokens" ; 3722return false; 3723 } 3724size_t n_order = 0 ;// the routed experts (the debug report; unknown when fused) 3725bool peer_now = false;// multi-GPU: the peer computed rows of this layer (MMQ path only) 3726if (fused_l ) { 3727if (static bool said = false; !said ) { 3728said = true; 3729 std::fprintf (stderr ,"strata: prompt experts on the fused int8 kernels (STRATA_PF_FUSED=1, " 3730"#136)\n" ); 3731 } 3732pt .mark (kPfGather ,cs ); 3733// the layer's input to int8 once per token; the rows of each expert from the router's ids 3734if (fused_nat ) fused::quantize_act_native (m .mixed ,T ,N ,m .Xq ,m .cs ); 3735else fused::quantize_act (m .mixed ,T ,N ,m .Xq ,m .cs ); 3736 fused::group (m .ids ,T * K , (int )K , (int )m .g -> n_expert ,m .GU ,m .slot_dev ,m .src_dev ,m .cs ); 3737// launches over the experts in id order, each at most kMaxBatch experts of which at most a 3738// third of the ring streamed: the next batch's blobs arrive while one computes. An expert 3739// the routing did not pick has no tiles; its ring slot is given back with its batch. 3740const size_t per = (size_t ) std::max (1 ,m .ring /3 ); 3741size_t k = seq_start [(size_t )l ]; 3742const size_t kend = seq_start [(size_t )l + 1 ]; 3743for (int32_t e = 0 ;e < m .g -> n_expert ;) { 3744 fused::Batch b ; 3745b .e0 = e ; 3746const size_t k0 = k ; 3747for (;e < m .g -> n_expert && e - b .e0 < fused::kMaxBatch ;++ e ) { 3748if (k < kend && seq [k ].e == e ) { 3749if (k - k0 == per )break ; 3750b .blob [e - b .e0 ]= m .stage_dev [k % (size_t )m .ring ]; 3751++ k ; 3752 }else {// not streamed: resident (the walk streams all others) 3753b .blob [e - b .e0 ]= m .cache -> device_slot (m .host_res [(size_t )l * m .g -> n_expert + e ]); 3754// counted whether routed or not (the routing stays on the GPU): at a streamed 3755// chunk's size (>= 1024 tokens x 10 of 512) nearly every expert is routed 3756++ stats_ .experts_resident ; 3757 } 3758 } 3759b .e1 = e ; 3760if (k > k0 ) { 3761// one copy stream, in order: the batch's last blob covers the others 3762pt .mark (kPfWaitCopy ,cs ); 3763wait_issued (k - 1 ); 3764 (m .cs )-> ext_oneapi_submit_barrier ( 3765 {* m .copied [(k - 1 ) % (size_t )m .ring ]}); 3766 } 3767pt .mark (kPfGemmGU ,cs ); 3768if (fused_nat ) { 3769const auto & f = lay .fmt [(size_t )l ]; 3770const fused::NativeGeom ng {f .gu_type ,f .d_type ,f .gu_row ,f .d_row ,f .up_off ,f .down_off }; 3771 fused::experts_native (b ,ng , (int )m .g -> n_expert ,T * K ,m .GU ,m .Xq ,m .src_dev ,m .H , 3772m .Dm ,m .cs ); 3773 }else { 3774 fused::experts (b , (int )m .g -> n_expert ,T * K ,m .GU ,m .Xq ,m .src_dev ,m .H ,m .Dm ,m .cs ); 3775 } 3776for (size_t kk = k0 ;kk < k ;++ kk ) { 3777 dpct::sync_barrier (m .used [kk % (size_t )m .ring ], 3778m .cs ); 3779m .used_of [kk % (size_t )m .ring ]= (int ) (kk % (size_t )m .ring ); 3780 } 3781if (k > k0 ) { 3782consumed = k ; 3783give_back (consumed ); 3784 } 3785 } 3786 }else { 3787// group the (token, k) pairs by expert on the host 3788pt .mark (kPfHostGroup ,cs ); 3789// (the sync below also orders this layer's writes of slot/src/bounds after the previous 3790// layer's kernels that read them) 3791const bool grp_mapped = m .grp_host != nullptr ; 3792int32_t * ids_h = grp_mapped ?m .grp_host :m .ids_host .data (); 3793int32_t * slot_h = grp_mapped ?m .grp_host + m .grp_tk :m .slot_host .data (); 3794int32_t * src_h = grp_mapped ?m .grp_host + 2 * m .grp_tk :m .src_host .data (); 3795if (grp_mapped )copy_i32 (m .grp_dev ,m .ids ,T * K ,m .cs ); 3796/* 3797DPCT1124: cudaMemcpyAsync is migrated to 3798asynchronous memcpy API. While the origin API might be 3799synchronous, it depends on the type of operand memory, 3800so you may need to call wait() on event return by memcpy 3801API to ensure synchronization behavior. 3802*/ 3803else m .cs -> memcpy (m .ids_host .data (),m .ids , 3804 (size_t )T * K * 4 ); 3805// #579: a stall here is the GPU (this layer's attention and router, or the previous layer's 3806// work), not the host: the watchdog's report says so (only its text changes) 3807 core::progress_at ("reading the prompt (batched): waiting for the GPU (attention, router) at layer" , 3808l ,p0 ); 3809m .cs -> wait (); 3810 core::progress_at ("reading the prompt (batched): layer" ,l ,p0 ); 3811pt .fold (); 3812if (pe .on ) {// the peer's marks so far are done: the primary waited for its last rows 3813/* 3814DPCT1093: The "pe.dev" device may be not the one 3815intended for use. Adjust the selected device if 3816needed. 3817*/ 3818/* 3819DPCT1093: The "pd" device may be not the one 3820intended for use. Adjust the selected device if 3821needed. 3822*/ 3823int pd = 0 ;pd = dpct::get_current_device_id (); 3824 dpct::select_device (pe .dev );m .pp -> s -> wait (); 3825pe .fold (); dpct::select_device (pd ); 3826 } 3827 std::fill (m .cnt .begin (),m .cnt .end (),0 ); 3828for (int64_t i = 0 ;i < T * K ;++ i ) { 3829const int32_t e = ids_h [(size_t )i ]; 3830if (e < 0 || e >=m .g -> n_expert ) {err = "prefill: routed id out of range" ;return false; } 3831++ m .cnt [(size_t )e ]; 3832 } 3833// multi-GPU: the rows of the experts the peer computes go last, as one block [rows_local, T*K) 3834const bool pre_mmq = mmq_plan ().any && mmq_plan ().layer [(size_t )l ]; 3835 std::vector < char > on_peer ; 3836int64_t rows_local = T * K ,rows_peer = 0 ; 3837if (m .pp && pre_mmq ) { 3838on_peer .assign ((size_t )m .g -> n_expert ,0 ); 3839for (int32_t e = 0 ;e < m .g -> n_expert ;++ e ) { 3840const int32_t c = m .cnt [(size_t )e ]; 3841if (c > 0 && !m .pp -> ps_flag .empty ()&& m .pp -> ps_flag [(size_t )l * m .g -> n_expert + e ]) {// peer-streamed 3842on_peer [(size_t )e ]= 2 ; 3843rows_peer += c ; 3844continue ; 3845 } 3846if (c == 0 || (m .host_res && m .cache && m .host_res [(size_t )l * m .g -> n_expert + e ] >=0 )|| 3847 !m .pp -> peer || !m .pp -> peer -> has (l ,e )) 3848continue ; 3849if (rows_peer + c > m .pp -> cap_rows ) {++ m .pp -> over_cap ;continue ; } 3850on_peer [(size_t )e ]= 1 ; 3851rows_peer += c ; 3852 } 3853rows_local = T * K - rows_peer ; 3854 } 3855 { 3856int32_t r = 0 ; 3857for (int32_t e = 0 ;e < m .g -> n_expert ;++ e ) 3858if (on_peer .empty ()|| !on_peer [(size_t )e ]) {m .off [(size_t )e ]= r ;r += m .cnt [(size_t )e ]; } 3859// the peer's rows in order_peer's order (peer-held, then peer-streamed): its groups need them contiguous 3860for (int kind = 1 ;kind <=2 && !on_peer .empty ();++ kind ) 3861for (int32_t e = 0 ;e < m .g -> n_expert ;++ e ) 3862if (on_peer [(size_t )e ]== kind ) {m .off [(size_t )e ]= r ;r += m .cnt [(size_t )e ]; } 3863m .off [(size_t )m .g -> n_expert ]= r ; 3864 } 3865 std::vector < int32_t > fill (m .off .begin (),m .off .end ()- 1 ); 3866for (int64_t i = 0 ;i < T * K ;++ i ) { 3867const int32_t e = ids_h [(size_t )i ]; 3868const int32_t p = fill [(size_t )e ]++ ; 3869slot_h [(size_t )i ]= p ; 3870src_h [(size_t )p ]= (int32_t ) (i /K ); 3871 } 3872// the experts, in id order: resident ones from VRAM, the others through the staging ring 3873 std::vector < int32_t > order ,order_peer ; 3874for (int32_t e = 0 ;e < m .g -> n_expert ;++ e ) 3875if (m .cnt [(size_t )e ]> 0 && (on_peer .empty ()|| on_peer [(size_t )e ]!= 2 )) 3876 (!on_peer .empty ()&& on_peer [(size_t )e ] ?order_peer :order ).push_back (e ); 3877for (int32_t e = 0 ;e < m .g -> n_expert && !on_peer .empty ();++ e )// the peer-streamed ones last: 3878if (on_peer [(size_t )e ]== 2 )order_peer .push_back (e );// their copies get the most time 3879// Aurora (STRATA_MMQ_RESIDENT_SORT_NE=1, opt-in): a layer whose experts are ALL resident and 3880// run through MMQ groups takes them in row-count order, so each 16-expert group's max_rows 3881// (its padded tile rows) is close to its experts' own; slot/src/off are rebuilt coherently 3882// before the upload, the routed ids, weights and the within-expert row order stay as they are. 3883if (detail::mmq_resident_sort_eligible (detail::mmq_resident_sort_requested ()&& on_peer .empty (),use_mmq ,lay .native , 3884m .cache != nullptr ,m .host_res ?m .host_res + (size_t )l * m .g -> n_expert :nullptr , 3885m .g -> n_expert ,stream_all , !stream_all || seq_start [(size_t )l ]== seq_start [(size_t )l + 1 ])) 3886 detail::mmq_resident_sort_rows (ids_h ,T * K , (int32_t )K ,m .cnt ,m .off ,order ,slot_h ,src_h ); 3887if (grp_mapped ) { 3888copy_i32 (m .slot_dev ,m .grp_dev + m .grp_tk ,T * K ,m .cs ); 3889copy_i32 (m .src_dev ,m .grp_dev + 2 * m .grp_tk ,T * K ,m .cs ); 3890 }else { 3891/* 3892DPCT1124: cudaMemcpyAsync is migrated to 3893asynchronous memcpy API. While the origin API might 3894be synchronous, it depends on the type of operand 3895memory, so you may need to call wait() on event 3896return by memcpy API to ensure synchronization 3897behavior. 3898*/ 3899m .cs -> memcpy (m .slot_dev ,m .slot_host .data (), 3900 (size_t )T * K * 4 ); 3901/* 3902DPCT1124: cudaMemcpyAsync is migrated to 3903asynchronous memcpy API. While the origin API might 3904be synchronous, it depends on the type of operand 3905memory, so you may need to call wait() on event 3906return by memcpy API to ensure synchronization 3907behavior. 3908*/ 3909m .cs -> memcpy (m .src_dev ,m .src_host .data (), 3910 (size_t )T * K * 4 ); 3911 } 3912n_order = order .size (); 3913const size_t mmq_gub = use_mmq ? mmq::matrix_bytes (mmq_gt ,kFF2 ,N ) :0 ; 3914const size_t mmq_db = use_mmq ? mmq::matrix_bytes (mmq_dt ,N ,kFF ) :0 ; 3915pt .mark (kPfGather ,cs ); 3916if (use_mmq ) { 3917// step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed` 3918 mmq::quantize (m .mixed ,m .src_dev ,m .Xq ,mmq_gt ,N ,N ,T * K ,m .cs ); 3919// each group's rows: absolute bounds (gate/up reads the layer's rows), relative ones (down 3920// reads the group's own quantized H) 3921const size_t n = order .size (),ng = (n + MMQ_GROUP - 1 ) /MMQ_GROUP ; 3922m .bounds_host .resize (n + 1 + ng * (MMQ_GROUP + 1 )); 3923for (size_t j = 0 ;j < n ;++ j )m .bounds_host [j ]= m .off [(size_t )order [j ]]; 3924m .bounds_host [n ]= (int32_t )rows_local ; 3925for (size_t g = 0 ;g < ng ;++ g ) 3926for (size_t i = 0 ;i <=MMQ_GROUP ;++ i ) 3927m .bounds_host [n + 1 + g * (MMQ_GROUP + 1 )+ i ]= 3928m .bounds_host [std::min (n ,g * MMQ_GROUP + i )]- m .bounds_host [g * MMQ_GROUP ]; 3929if (grp_mapped ) { 3930int32_t * bh = m .grp_host + 3 * m .grp_tk ; 3931 std::memcpy (bh ,m .bounds_host .data (),m .bounds_host .size ()* 4 ); 3932copy_i32 (m .bounds_dev ,m .grp_dev + 3 * m .grp_tk , (int64_t )m .bounds_host .size (),m .cs ); 3933 }else { 3934/* 3935DPCT1124: cudaMemcpyAsync is migrated to 3936asynchronous memcpy API. While the origin API 3937might be synchronous, it depends on the type of 3938operand memory, so you may need to call wait() 3939on event return by memcpy API to ensure 3940synchronization behavior. 3941*/ 3942m .cs -> memcpy (m .bounds_dev ,m .bounds_host .data (), 3943m .bounds_host .size ()* 4 ); 3944 } 3945 }else { 3946gather_rows16 (m .mixed_h ,m .src_dev ,m .Xs ,T * K ,N ,m .cs ); 3947// APR: Xs is this layer's private gathered copy (rotated in fp16 storage, fp32 arithmetic) 3948if (had_gu ) strata::kernels::hadamard_rows_f16 (m .Xs ,T * K ,N ,had_block ,had_sx ,m .cs ); 3949 } 3950// multi-GPU: the peer's share, enqueued before the primary's own experts so both cards work at once 3951peer_now = use_mmq && !order_peer .empty (); 3952if (peer_now ) { 3953PeerPrefill & P = * m .pp ; 3954/* 3955DPCT1124: cudaMemcpyAsync is migrated to 3956asynchronous memcpy API. While the origin API might 3957be synchronous, it depends on the type of operand 3958memory, so you may need to call wait() on event 3959return by memcpy API to ensure synchronization 3960behavior. 3961*/ 3962if (!P .p2p )m .cs -> memcpy (P .host_x ,m .mixed , 3963 (size_t )T * N * 4 ); 3964 dpct::sync_barrier (P .ev_in ,m .cs ); 3965int prevd = 0 ; 3966prevd = dpct::get_current_device_id (); 3967/* 3968DPCT1093: The "P.dev" device may be not the one 3969intended for use. Adjust the selected device if 3970needed. 3971*/ 3972 dpct::select_device (P .dev ); 3973const dpct::queue_ptr ps = P .s ; 3974ps -> ext_oneapi_submit_barrier ({* P .ev_in }); 3975if (P .out_pending ) { 3976ps -> ext_oneapi_submit_barrier ({* P .ev_done }); 3977P .out_pending = false; 3978 } 3979pe .mark (kPeMoeIn ,ps ); 3980/* 3981DPCT1124: cudaMemcpyPeerAsync is migrated to 3982asynchronous memcpy API. While the origin API might 3983be synchronous, it depends on the type of operand 3984memory, so you may need to call wait() on event 3985return by memcpy API to ensure synchronization 3986behavior. 3987*/ 3988if (P .p2p ) dpct::async_dpct_memcpy ( 3989P .mixed ,P .dev ,m .mixed ,prevd , 3990 (size_t )T * N * 4 ,* ps ); 3991else copy_f32_wide (P .mixed ,P .host_x ,T * N ,ps ); 3992P .back_at = rows_local ; 3993P .back_rows = rows_peer ; 3994if (P .p2p ) { 3995/* 3996DPCT1124: cudaMemcpyAsync is migrated to 3997asynchronous memcpy API. While the origin API 3998might be synchronous, it depends on the type of 3999operand memory, so you may need to call wait() 4000on event return by memcpy API to ensure 4001synchronization behavior. 4002*/ 4003ps -> memcpy ( 4004P .src , 4005src_h + rows_local ,// multi-GPU: the mapped 4006// table when on 4007 (size_t )rows_peer * 4 ); 4008 }else { 4009 std::memcpy (P .host_src ,src_h + rows_local , (size_t )rows_peer * 4 ); 4010copy_i32 (P .src ,P .host_src ,rows_peer ,ps ); 4011 } 4012const size_t n = order_peer .size (); 4013if (P .compact ) { 4014// groups of up to MMQ_GROUP experts and at most G rows, each computed from its own rows 4015P .groups .clear (); 4016 { 4017size_t g0 = 0 ; 4018int64_t gr = 0 ; 4019for (size_t j = 0 ;j < n ;++ j ) { 4020const int64_t c = m .cnt [(size_t )order_peer [j ]]; 4021if (j > g0 && (j - g0 == (size_t )MMQ_GROUP || gr + c > P .G )) {P .groups .push_back ({g0 ,j });g0 = j ;gr = 0 ; } 4022gr += c ; 4023 } 4024if (n > g0 )P .groups .push_back ({g0 ,n }); 4025 } 4026const size_t ng = P .groups .size (); 4027P .bounds_host .resize (n + 1 + ng * (MMQ_GROUP + 1 )); 4028for (size_t j = 0 ;j < n ;++ j )P .bounds_host [j ]= m .off [(size_t )order_peer [j ]]- (int32_t )rows_local ; 4029P .bounds_host [n ]= (int32_t )rows_peer ; 4030for (size_t g2 = 0 ;g2 < ng ;++ g2 ) 4031for (size_t i = 0 ;i <=MMQ_GROUP ;++ i ) 4032P .bounds_host [n + 1 + g2 * (MMQ_GROUP + 1 )+ i ]= 4033P .bounds_host [std::min (P .groups [g2 ].second ,P .groups [g2 ].first + i )]- 4034P .bounds_host [P .groups [g2 ].first ]; 4035if (P .p2p || P .bounds_host .size ()> PeerPrefill ::kHostBounds ) { 4036/* 4037DPCT1124: cudaMemcpyAsync is migrated 4038to asynchronous memcpy API. While the origin 4039API might be synchronous, it depends on the 4040type of operand memory, so you may need to 4041call wait() on event return by memcpy API to 4042ensure synchronization behavior. 4043*/ 4044ps -> memcpy (P .bounds ,P .bounds_host .data (), 4045P .bounds_host .size ()* 4 ); 4046 }else { 4047 std::memcpy (P .host_bounds ,P .bounds_host .data (),P .bounds_host .size ()* 4 ); 4048copy_i32 (P .bounds ,P .host_bounds , (int64_t )P .bounds_host .size (),ps ); 4049 } 4050pe .mark (kPeMoeGemm ,ps ); 4051const auto & f = lay .fmt [(size_t )l ]; 4052for (size_t g2 = 0 ;g2 < ng ;++ g2 ) { 4053const size_t j0 = P .groups [g2 ].first ,j1 = P .groups [g2 ].second ; 4054const int ngx = (int ) (j1 - j0 ); 4055int64_t maxr = 0 ; 4056for (size_t j = j0 ;j < j1 ;++ j ) { 4057const int32_t e = order_peer [j ]; 4058maxr = std::max < int64_t > (maxr ,m .cnt [(size_t )e ]); 4059const uint8_t * bd = nullptr ; 4060int psl = -1 ; 4061if (on_peer [(size_t )e ]== 2 ) {// from the peer's ring 4062p_release_to (l ,e ,ps ); 4063if (P .pk >=P .pseq_start [(size_t )l + 1 ]|| P .pseq [P .pk ].e != e ) { 4064err = "prefill: a peer-streamed expert is not next in the peer's ring" ; 4065/* 4066DPCT1093: The "prevd" device 4067may be not the one intended for 4068use. Adjust the selected device 4069if needed. 4070*/ 4071 dpct::select_device (prevd ); 4072return false; 4073 } 4074psl = (int ) (P .pk % (size_t )P .RP ); 4075ps -> ext_oneapi_submit_barrier ( 4076 {* P .pcopied [(size_t )psl ]}); 4077bd = P .pstage [(size_t )psl ]; 4078++ P .ps_experts ; 4079 }else { 4080bd = P .peer -> slot_ptr (l ,e ); 4081 } 4082const size_t q = j - j0 ; 4083if (lay .native ) 4084 mmq::gather_native (bd ,bd + f .up_off ,mmq_gub /2 ,bd + f .down_off ,mmq_db , 4085P .grp_gu + q * mmq_gub ,P .grp_d + q * mmq_db ,ps ); 4086else 4087 mmq::gather_strata_q2 (bd ,P .grp_gu + q * mmq_gub ,P .grp_d + q * mmq_db ,ps ); 4088if (psl >=0 ) {// the slot is free once gathered 4089 dpct::sync_barrier ( 4090P .pused [(size_t )psl ],ps ); 4091++ P .pk ; 4092p_issue_until (P .pk + (size_t )P .RP ); 4093 } 4094 } 4095const int64_t r0 = P .bounds_host [j0 ],nr = P .bounds_host [j1 ]- r0 ; 4096if (nr <=0 )continue ; 4097const int32_t * rel = P .bounds + n + 1 + g2 * (MMQ_GROUP + 1 ); 4098ps -> memset (P .grp_gu + (size_t )ngx * mmq_gub , 40990 ,MMQ_TAIL ); 4100ps -> memset (P .grp_d + (size_t )ngx * mmq_db , 41010 ,MMQ_TAIL ); 4102 mmq::quantize (P .mixed ,P .src + r0 ,P .Xq_g ,mmq_gt ,N ,N ,nr ,ps ); 4103 mmq::Product gu ; 4104gu .w = P .grp_gu ;gu .type = mmq_gt ;gu .w_rows = kFF2 ;gu .w_cols = N ;gu .expert_bytes = mmq_gub ; 4105gu .n = ngx ;gu .xq = P .Xq_g ;gu .bounds = rel ;gu .ids = P .ident ; 4106gu .total_rows = nr ;gu .max_rows = maxr ;gu .dst = P .GU_g ;gu .ld_dst = kFF2 ; 4107P .run_ctx -> run (gu ,ps ); 4108 mmq::swiglu (P .GU_g ,P .H_g ,nr ,kFF , !lay .native ,ps ); 4109 mmq::quantize (P .H_g ,nullptr ,P .Hq_g ,mmq_dt ,kFF ,kFF ,nr ,ps ); 4110const int b = (int ) (g2 & 1 ); 4111if (P .dm_live [b ]) 4112ps -> ext_oneapi_submit_barrier ( 4113 {* P .ev_dm [b ]});// its last rows 4114// have left 4115 mmq::Product dn ; 4116dn .w = P .grp_d ;dn .type = mmq_dt ;dn .w_rows = N ;dn .w_cols = kFF ;dn .expert_bytes = mmq_db ; 4117dn .n = ngx ;dn .xq = P .Hq_g ;dn .bounds = rel ; 4118dn .ids = P .ident ;dn .total_rows = nr ;dn .max_rows = maxr ;dn .dst = P .Dm_b [b ]; 4119dn .ld_dst = N ; 4120P .run_ctx -> run (dn ,ps ); 4121 dpct::sync_barrier ( 4122P .ev_grp [g2 %PeerPrefill ::kGrpEv ],ps ); 4123 (P .s_out )-> ext_oneapi_submit_barrier ( 4124 {* P .ev_grp [g2 %PeerPrefill ::kGrpEv ]}); 4125if (P .p2p ) 4126/* 4127DPCT1124: cudaMemcpyPeerAsync is 4128migrated to asynchronous memcpy API. 4129While the origin API might be 4130synchronous, it depends on the type of 4131operand memory, so you may need to call 4132wait() on event return by memcpy API to 4133ensure synchronization behavior. 4134*/ 4135 dpct::async_dpct_memcpy ( 4136m .Dm + 4137 (size_t )(rows_local + r0 )* N , 4138prevd ,P .Dm_b [b ],P .dev , 4139 (size_t )nr * N * 4 ,* (P .s_out )); 4140else // the primary reads them when it combines (below) 4141/* 4142DPCT1124: cudaMemcpyAsync is 4143migrated to asynchronous memcpy API. 4144While the origin API might be 4145synchronous, it depends on the type of 4146operand memory, so you may need to call 4147wait() on event return by memcpy API to 4148ensure synchronization behavior. 4149*/ 4150P .s_out -> memcpy ( 4151P .host_rows + (size_t )r0 * N , 4152P .Dm_b [b ], (size_t )nr * N * 4 ); 4153 dpct::sync_barrier (P .ev_dm [b ],P .s_out ); 4154P .dm_live [b ]= true; 4155 } 4156 }else { 4157const size_t ng = (n + MMQ_GROUP - 1 ) /MMQ_GROUP ; 4158P .bounds_host .resize (n + 1 + ng * (MMQ_GROUP + 1 )); 4159for (size_t j = 0 ;j < n ;++ j )P .bounds_host [j ]= m .off [(size_t )order_peer [j ]]- (int32_t )rows_local ; 4160P .bounds_host [n ]= (int32_t )rows_peer ; 4161for (size_t g2 = 0 ;g2 < ng ;++ g2 ) 4162for (size_t i = 0 ;i <=MMQ_GROUP ;++ i ) 4163P .bounds_host [n + 1 + g2 * (MMQ_GROUP + 1 )+ i ]= 4164P .bounds_host [std::min (n ,g2 * MMQ_GROUP + i )]- P .bounds_host [g2 * MMQ_GROUP ]; 4165if (P .p2p || P .bounds_host .size ()> PeerPrefill ::kHostBounds ) { 4166/* 4167DPCT1124: cudaMemcpyAsync is migrated 4168to asynchronous memcpy API. While the origin 4169API might be synchronous, it depends on the 4170type of operand memory, so you may need to 4171call wait() on event return by memcpy API to 4172ensure synchronization behavior. 4173*/ 4174ps -> memcpy (P .bounds ,P .bounds_host .data (), 4175P .bounds_host .size ()* 4 ); 4176 }else { 4177 std::memcpy (P .host_bounds ,P .bounds_host .data (),P .bounds_host .size ()* 4 ); 4178copy_i32 (P .bounds ,P .host_bounds , (int64_t )P .bounds_host .size (),ps ); 4179 } 4180 mmq::quantize (P .mixed ,P .src ,P .Xq ,mmq_gt ,N ,N ,rows_peer ,ps ); 4181pe .mark (kPeMoeGemm ,ps ); 4182const auto & f = lay .fmt [(size_t )l ]; 4183for (size_t j = 0 ;j < n ;++ j ) { 4184const int32_t e = order_peer [j ]; 4185const uint8_t * bd = P .peer -> slot_ptr (l ,e ); 4186const size_t q = j %MMQ_GROUP ; 4187if (lay .native ) 4188 mmq::gather_native (bd ,bd + f .up_off ,mmq_gub /2 ,bd + f .down_off ,mmq_db , 4189P .grp_gu + q * mmq_gub ,P .grp_d + q * mmq_db ,ps ); 4190else 4191 mmq::gather_strata_q2 (bd ,P .grp_gu + q * mmq_gub ,P .grp_d + q * mmq_db ,ps ); 4192if (q + 1 < MMQ_GROUP && j + 1 < n )continue ; 4193const size_t j0 = j - q ,g2 = j0 /MMQ_GROUP ; 4194const int ngx = (int ) (q + 1 ); 4195const int64_t r0 = P .bounds_host [j0 ],nr = P .bounds_host [j + 1 ]- r0 ; 4196int64_t maxr = 0 ; 4197for (size_t i = j0 ;i <=j ;++ i )maxr = std::max < int64_t > (maxr ,m .cnt [(size_t )order_peer [i ]]); 4198ps -> memset (P .grp_gu + (size_t )ngx * mmq_gub , 41990 ,MMQ_TAIL ); 4200ps -> memset (P .grp_d + (size_t )ngx * mmq_db , 42010 ,MMQ_TAIL ); 4202 mmq::Product gu ; 4203gu .w = P .grp_gu ;gu .type = mmq_gt ;gu .w_rows = kFF2 ;gu .w_cols = N ;gu .expert_bytes = mmq_gub ; 4204gu .n = ngx ;gu .xq = P .Xq ;gu .bounds = P .bounds + j0 ;gu .ids = P .ident ; 4205gu .total_rows = rows_peer ;gu .max_rows = maxr ;gu .dst = P .GU ;gu .ld_dst = kFF2 ; 4206P .run_ctx -> run (gu ,ps ); 4207 mmq::swiglu (P .GU + r0 * kFF2 ,P .H + r0 * kFF ,nr ,kFF , !lay .native ,ps ); 4208 mmq::quantize (P .H + r0 * kFF ,nullptr ,P .Hq ,mmq_dt ,kFF ,kFF ,nr ,ps ); 4209 mmq::Product dn ; 4210dn .w = P .grp_d ;dn .type = mmq_dt ;dn .w_rows = N ;dn .w_cols = kFF ;dn .expert_bytes = mmq_db ; 4211dn .n = ngx ;dn .xq = P .Hq ;dn .bounds = P .bounds + n + 1 + g2 * (MMQ_GROUP + 1 ); 4212dn .ids = P .ident ;dn .total_rows = nr ;dn .max_rows = maxr ;dn .dst = P .Dm + r0 * N ; 4213dn .ld_dst = N ; 4214P .run_ctx -> run (dn ,ps ); 4215if (P .out_pipe && nr > 0 ) {// this group's rows go back while the next group computes 4216 dpct::sync_barrier (P .ev_grp [g2 ],ps ); 4217 (P .s_out )-> ext_oneapi_submit_barrier ( 4218 {* P .ev_grp [g2 ]}); 4219/* 4220DPCT1124: cudaMemcpyPeerAsync is 4221migrated to asynchronous memcpy API. 4222While the origin API might be 4223synchronous, it depends on the type of 4224operand memory, so you may need to call 4225wait() on event return by memcpy API to 4226ensure synchronization behavior. 4227*/ 4228 dpct::async_dpct_memcpy ( 4229m .Dm + 4230 (size_t )(rows_local + r0 )* N , 4231prevd ,P .Dm + (size_t )r0 * N ,P .dev , 4232 (size_t )nr * N * 4 ,* (P .s_out )); 4233 } 4234 } 4235 } 4236pe .mark (kPeMoeOut ,ps ); 4237if (P .out_pipe ) { 4238 dpct::sync_barrier (P .ev_done ,P .s_out ); 4239P .out_pending = true; 4240 }else { 4241/* 4242DPCT1124: cudaMemcpyPeerAsync is migrated to 4243asynchronous memcpy API. While the origin API 4244might be synchronous, it depends on the type of 4245operand memory, so you may need to call wait() 4246on event return by memcpy API to ensure 4247synchronization behavior. 4248*/ 4249 dpct::async_dpct_memcpy ( 4250m .Dm + (size_t )rows_local * N ,prevd ,P .Dm , 4251P .dev , (size_t )rows_peer * N * 4 ,* ps ); 4252 dpct::sync_barrier (P .ev_done ,ps ); 4253 } 4254pe .mark (kPeIdle ,ps ); 4255/* 4256DPCT1093: The "prevd" device may be not the one 4257intended for use. Adjust the selected device if 4258needed. 4259*/ 4260 dpct::select_device (prevd ); 4261++ P .layers ; 4262P .experts += (int64_t )n ; 4263P .rows += rows_peer ; 4264 } 4265if (ps_on ) {// multi-GPU: this layer's peer-ring entries the routing did not pick give their slots back 4266int pd = 0 ; 4267pd = dpct::get_current_device_id (); 4268/* 4269DPCT1093: The "m.pp->dev" device may be not the 4270one intended for use. Adjust the selected device if 4271needed. 4272*/ 4273 dpct::select_device (m .pp -> dev ); 4274p_release_to (l , (int32_t )m .g -> n_expert ,m .pp -> s ); 4275/* 4276DPCT1093: The "pd" device may be not the one 4277intended for use. Adjust the selected device if 4278needed. 4279*/ 4280 dpct::select_device (pd ); 4281 } 4282// Stage ahead: the copy stream moves blobs host -> device while the compute stream works. 4283int stage_next = 0 ; 4284 std::vector < int > stage_of (order .size (),-1 ); 4285// the unpinned ones are copied to pinned buffers by the stager's threads, in this order 4286 std::vector < int > job_of (order .size (),-1 ); 4287if (!stream_all ) { 4288 std::vector < Stager ::Job > js ; 4289for (size_t j = 0 ;j < order .size ();++ j ) { 4290const int32_t e = order [j ]; 4291if (m .host_res && m .cache && m .host_res [(size_t )l * m .g -> n_expert + e ] >=0 )continue ; 4292 {const uint8_t * pb = m .src -> pinned (l ,e ) ?m .src -> blob (l ,e ) :nullptr ;if (dma_direct (m .src ,l ,e ,pb ))continue ; } 4293job_of [j ]= (int )js .size (); 4294if (gsrc != nullptr ) {// SYCL port: --stream-experts - the stager's thread reads it from the GGUF 4295js .push_back ({nullptr , (size_t )lay .blob_bytes (l ),nullptr , (int32_t )l ,e ,gsrc }); 4296continue ; 4297 } 4298if (m .src -> transient (l ,e )) {// CS-T: copied by the source 4299js .push_back ({nullptr , (size_t )lay .blob_bytes (l ),m .src , (int32_t )l ,e }); 4300continue ; 4301 } 4302const uint8_t * b = m .src -> blob (l ,e ); 4303if (!b ) {err = "prefill: expert source has no blob" ;return false; } 4304js .push_back ({b , (size_t )lay .blob_bytes (l )}); 4305 } 4306m .stager -> start (std::move (js )); 4307 } 4308StagerDone stager_done {stream_all ?nullptr :m .stager .get ()}; 4309static const bool f16_pair_env = [] {const char * v = std::getenv ("STRATA_SYCL_F16_EXPERT_PAIR" );return v && v [0 ]== '1' ; }(); 4310const bool f16_pairs = f16_pair_env && lay .native && !use_mmq && strata::prefill::xmx::mode ()== 0 ; 4311 strata::prefill::f16_expert_pair::Pair f16_pending {}; 4312int f16_n = 0 ; 4313int f16_slots [2 ]= {-1 ,-1 }; 4314auto flush_f16 = [& ]() { 4315if (f16_n == 0 )return ; 4316if (f16_n == 2 ) { 4317pt .mark (kPfGemmGU ,cs ); 4318 strata::prefill::f16_expert_pair::gu (* m .cs ,f16_pending ); 4319pt .mark (kPfGemmD ,cs ); 4320 strata::prefill::f16_expert_pair::down (* m .cs ,f16_pending ); 4321 }else { 4322const auto & p = f16_pending .v [0 ]; 4323 strata::kernels::iq_dequant_f16_plain_launch (42 ,p .wdown ,2560 * 640 ,m .dq_d [0 ],m .cs ); 4324pt .mark (kPfGemmGU ,cs ); 4325m .gemm .f16 (p .x ,p .wgu ,p .gu ,p .T ,1280 ,2560 ); 4326swiglu_interleaved (p .gu ,p .h ,p .T ,m .cs ); 4327pt .mark (kPfGemmD ,cs ); 4328m .gemm .f16 (p .h ,m .dq_d [0 ],p .y ,p .T ,2560 ,640 ); 4329 } 4330// Release only after the last encoded Down read, before its staging slot is refilled. 4331for (int i = 0 ;i < f16_n ;++ i )if (f16_slots [i ] >=0 ) { 4332const int slot = f16_slots [i ]; 4333 dpct::sync_barrier (m .used [slot ],m .cs ); 4334m .used_of [slot ]= slot ; 4335 } 4336f16_n = 0 ; 4337 }; 4338auto stage_one = [& ](size_t j )-> bool { 4339try { 4340const int32_t e = order [j ]; 4341const bool resident = m .host_res && m .cache && m .host_res [(size_t )l * m .g -> n_expert + e ] >=0 ; 4342if (resident )return true; 4343const int sl = stage_next ; 4344if (f16_n && f16_slots [0 ]== sl )flush_f16 (); 4345stage_next = (stage_next + 1 ) %stage_slots (); 4346const auto th = Clock ::now (); 4347const uint8_t * pb0 = m .src -> pinned (l ,e ) ?m .src -> blob (l ,e ) :nullptr ; 4348const bool pinned = dma_direct (m .src ,l ,e ,pb0 );// pinned: never transient 4349const uint8_t * b = pinned ?m .src -> blob (l ,e ) :nullptr ; 4350if (pinned && !b ) {err = "prefill: expert source has no blob" ;return false; } 4351if (pinned ) { 4352// DMA straight from the page-locked arena: the copy stream only waits for the slot 4353if (m .stage_live [sl ])(m .copy ) 4354-> ext_oneapi_submit_barrier ( 4355 {* m .used [m .used_of [sl ]]}); 4356/* 4357DPCT1124: cudaMemcpyAsync is migrated to 4358asynchronous memcpy API. While the origin API 4359might be synchronous, it depends on the type of 4360operand memory, so you may need to call wait() 4361on event return by memcpy API to ensure 4362synchronization behavior. 4363*/ 4364m .copy -> memcpy (m .stage_dev [sl ],b , 4365 (size_t )lay .blob_bytes (l )); 4366++ stats_ .experts_dma ; 4367 }else { 4368// copied to a pinned buffer by the stager (waits only if it is behind), then DMA 4369const uint8_t * hb = m .stager -> wait (job_of [j ]); 4370if (m .stage_live [sl ])(m .copy ) 4371-> ext_oneapi_submit_barrier ( 4372 {* m .used [m .used_of [sl ]]}); 4373/* 4374DPCT1124: cudaMemcpyAsync is migrated to 4375asynchronous memcpy API. While the origin API 4376might be synchronous, it depends on the type of 4377operand memory, so you may need to call wait() 4378on event return by memcpy API to ensure 4379synchronization behavior. 4380*/ 4381m .copy -> memcpy (m .stage_dev [sl ],hb , 4382 (size_t )lay .blob_bytes (l )); 4383m .stager -> issued_one (job_of [j ],m .copy ); 4384 } 4385 dpct::sync_barrier (m .copied [sl ],m .copy ); 4386m .stage_live [sl ]= true; 4387stage_of [j ]= sl ; 4388stats_ .ms_experts_host += ms_since (th ); 4389++ stats_ .experts_streamed ; 4390return true; 4391 } 4392catch (sycl::exception const & exc ) { 4393 std::cerr <<exc .what () 4394 <<"Exception caught at file:" <<__FILE__ 4395 <<", line:" <<__LINE__ << std::endl ; 4396 std::exit (1 ); 4397 } 4398 }; 4399// In the streamed walk an MMQ group is gathered in ONE launch, after ONE wait on its last 4400// streamed copy (the copy stream is in order), and its ring slots are released by ONE event. A 4401// wait and a record per expert put ~10 us of GPU bubble each on the compute stream under WDDM 4402// (226 ms of a 32K prompt on an NVFP4 pack). The same bytes into the same group slots. A ring 4403// entry the routing skipped inside an open group first gathers what the group holds so far 4404// (`flush`), so no more than a group's entries are ever held back from the issuer. 4405// STRATA_PREFILL_GROUP_GATHER=0: one gather, one wait and one record per expert. 4406static const bool group_env = [] { 4407const char * v = std::getenv ("STRATA_PREFILL_GROUP_GATHER" ); 4408return v == nullptr || std::atoi (v )!= 0 ; 4409 }(); 4410const bool group_gather = group_env && stream_all && use_mmq && lay .native && 4411MMQ_GROUP <= mmq::kGatherGroupMax ; 4412 mmq::GatherGroup gg ; 4413int gg_slots [MMQ_GROUP ]; 4414int gg_nslots = 0 ;// ring slots gathered by the next flush 4415auto flush = [& ]() { 4416try { 4417if (gg .n <=gg .first )return ; 4418const auto & f = lay .fmt [(size_t )l ]; 4419if (gg_nslots > 0 ) {// the copies land in order: the last one covers the others 4420pt .mark (kPfWaitCopy ,cs ); 4421 (m .cs )-> ext_oneapi_submit_barrier ( 4422 {* m .copied [gg_slots [gg_nslots - 1 ]]}); 4423pt .mark (kPfDequant ,cs ); 4424 } 4425if (!mmq::gather_native_group (gg ,f .up_off ,mmq_gub /2 ,f .down_off ,mmq_db ,m .grp_gu ,mmq_gub , 4426m .grp_d ,mmq_db ,m .cs )) { 4427for (int i = gg .first ;i < gg .n ;++ i ) {// not 16-byte aligned: one at a time 4428const uint8_t * b = gg .blob [i ]; 4429 mmq::gather_native (b ,b + f .up_off ,mmq_gub /2 ,b + f .down_off ,mmq_db , 4430m .grp_gu + i * mmq_gub ,m .grp_d + i * mmq_db ,m .cs ); 4431 } 4432 } 4433if (gg_nslots > 0 ) { 4434const int rel = gg_slots [gg_nslots - 1 ]; 4435 dpct::sync_barrier (m .used [rel ],m .cs ); 4436for (int i = 0 ;i < gg_nslots ;++ i )m .used_of [gg_slots [i ]]= rel ; 4437 } 4438gg_nslots = 0 ; 4439gg .first = gg .n ; 4440 } 4441catch (sycl::exception const & exc ) { 4442 std::cerr <<exc .what () 4443 <<"Exception caught at file:" <<__FILE__ 4444 <<", line:" <<__LINE__ << std::endl ; 4445 std::exit (1 ); 4446 } 4447 }; 4448// A770 port, STRATA_PF_XMX=2 (streamed walk, native pack, FP16 path): the experts' quantized 4449// blobs are held until a group of kXmxGroupMax, then each product runs over the group in one 4450// launch that decodes the weights itself. Their ring slots are released by ONE event after 4451// the group's down product, and nothing is given back to the issuer while any are held. 4452// (the formats the parity test covers: gate/up IQ3_XXS / IQ3_S / IQ2_S / IQ4_XS, down IQ4_NL / Q2_0; 4453// a layer in another format keeps the dequantize + oneMKL path) 4454auto xmx2_fmt = [& ]() { 4455if (!lay .native )return false; 4456const int gt = lay .fmt [(size_t )l ].gu_type ,dt = lay .fmt [(size_t )l ].d_type ; 4457if ((gt == 144 || gt == 145 )&& (dt == 144 || dt == 146 ))return true;// Gyro's trellis experts (rotated above) 4458return (gt == 18 || gt == 21 || gt == 22 || gt == 23 )&& (dt == 20 || dt == 42 ); 4459 }; 4460const bool xmx2_only = strata::prefill::xmx::mode ()== 2 && !use_mmq && xmx2_fmt (); 4461// 151-b70: the fused int8 DPAS products (IQ3_S gate/up, IQ4_NL down, the 640 x 2560 expert), the same 4462// held group of staged experts as above 4463const int i8m = i8_mode (m .cs ); 4464const bool i8on = !xmx2_only && i8m != 0 && !use_mmq && lay .native && !had_gu && !had_d && 4465 (lay .fmt [(size_t )l ].gu_type == 21 || lay .fmt [(size_t )l ].gu_type == 18 || lay .fmt [(size_t )l ].gu_type == 22 )&& 4466 (lay .fmt [(size_t )l ].d_type == 20 || lay .fmt [(size_t )l ].d_type == 42 )&& 4467lay .fmt [(size_t )l ].n_ff == 640 && lay .fmt [(size_t )l ].n_embd == 2560 && 4468 strata::prefill::i8::available (m .cs ); 4469const bool xmx2 = xmx2_only || i8on ; 4470if (i8_env ()!= nullptr && i8m != 0 && lay .native ) { 4471static std::set < std::tuple < int ,int ,int ,int ,int >> said_fmt ; 4472const auto & ff = lay .fmt [(size_t )l ]; 4473if (said_fmt .insert ({ff .gu_type ,ff .d_type , (int )ff .n_ff , (int )ff .n_embd , (int )i8on }).second ) 4474 std::fprintf (stderr ,"strata: layer %lld experts gate/up type %d, down type %d, n_ff %d, n_embd %d -> int8 path %s\n" , 4475 (long long )l ,ff .gu_type ,ff .d_type , (int )ff .n_ff , (int )ff .n_embd ,i8on ?"yes" :"no" ); 4476 } 4477if (strata::prefill::xmx::mode ()== 2 && !xmx2 ) { 4478static bool said = false; 4479if (!said ) { 4480said = true; 4481 std::fprintf (stderr ,"strata: STRATA_PF_XMX=2 not taken at layer %lld (stream_all %d, mmq %d, " 4482"native %d, formats %d/%d)\n" , (long long )l , (int )stream_all , 4483 (int )use_mmq , (int )lay .native ,lay .native ?lay .fmt [(size_t )l ].gu_type :-1 , 4484lay .native ?lay .fmt [(size_t )l ].d_type :-1 ); 4485 } 4486 } 4487const uint8_t * xg_g [strata::kernels::kXmxGroupMax ]; 4488const uint8_t * xg_u [strata::kernels::kXmxGroupMax ]; 4489const uint8_t * xg_d [strata::kernels::kXmxGroupMax ]; 4490int32_t xg_c [strata::kernels::kXmxGroupMax ]; 4491int xg_slots [strata::kernels::kXmxGroupMax ]; 4492int xg_n = 0 ,xg_ns = 0 ; 4493int64_t xg_r0 = 0 ; 4494auto xflush = [& ]() { 4495if (xg_n == 0 )return ; 4496const auto & f = lay .fmt [(size_t )l ]; 4497int64_t nr = 0 ; 4498for (int i = 0 ;i < xg_n ;++ i )nr += xg_c [i ]; 4499if (i8on ) { 4500// STRATA_PREFILL_MMQ=1: always; =auto: while the group's mean rows per expert are under the crossover 4501// measured on this GPU (i8_calibrate); a group above it takes the FP16 chain below 4502bool done8 = false; 4503try { 4504bool use_i8 = true; 4505if (i8m == 2 ) { 4506static std::map < std::tuple < const void * ,int ,int > ,I8Cross > xover ;// per queue (a layer split has a card per queue) 4507auto it = xover .find ({(const void * )m .cs ,f .gu_type ,f .d_type }); 4508if (it == xover .end ())it = xover .emplace (std::make_tuple ((const void * )m .cs ,f .gu_type ,f .d_type ),i8_calibrate (m ,f )).first ; 4509use_i8 = (double )nr /xg_n < it -> second .rows ; 4510static long groups_i8 = 0 ,groups_fp = 0 ; 4511 (use_i8 ?groups_i8 :groups_fp )+= 1 ; 4512if (static bool said_n = false; !said_n && groups_i8 + groups_fp >=500 ) { 4513said_n = true; 4514 std::fprintf (stderr ,"strata: int8 experts (auto): %ld groups took the int8 chain, %ld the FP16 chain\n" ,groups_i8 ,groups_fp ); 4515 } 4516 } 4517if (use_i8 ) { 4518if (static bool said = false; !said ) { 4519said = true; 4520 std::fprintf (stderr ,"strata: prompt experts on the fused int8 DPAS products (STRATA_PREFILL_MMQ=%s)\n" , 4521i8m == 2 ?"auto" :"1" ); 4522 } 4523namespace i8= strata::prefill::i8; 4524 i8::Layout lo8 ; 4525 i8::make_layout (lo8 ,xg_c ,xg_n ); 4526 i8::Workspace ws8 ; 4527pt .mark (kPfGemmGU ,cs ); 4528if (i8::workspace (lo8 , (int )N ,f .n_ff ,ws8 ,m .cs )) { 4529 i8::quantize_rows (m .Xs + xg_r0 * N ,lo8 , (int )N ,ws8 .xq ,ws8 .dx ,m .cs ); 4530if (i8::gate_up (f .gu_type ,xg_g ,f .up_off ,f .n_ff ,lo8 , (int )N ,ws8 .xq ,ws8 .dx ,m .GU + xg_r0 * 1280 ,m .cs )) { 4531 i8::swiglu_quantize (m .GU + xg_r0 * 1280 ,lo8 ,f .n_ff ,ws8 .hq ,ws8 .dh ,m .cs ); 4532pt .mark (kPfGemmD ,cs ); 4533done8 = i8::down (f .d_type ,xg_g ,f .down_off , (int )N ,lo8 ,f .n_ff ,ws8 .hq ,ws8 .dh ,m .Dm + xg_r0 * N ,m .cs ); 4534 } 4535 } 4536if (!done8 ) { 4537if (static bool said_f = false; !said_f ) { 4538said_f = true; 4539 std::fprintf (stderr ,"strata: the int8 expert products could not run (layer %lld, no workspace or a format they do not handle): the FP16 chain is used\n" , (long long )l ); 4540 } 4541 } 4542 } 4543 }catch (const std::exception & ex ) {// the kernels are not in this binary for this device, or a launch failed: the FP16 chain, for good 4544done8 = false; 4545if (!g_i8_failed .exchange (true)) 4546 std::fprintf (stderr ,"strata: the int8 expert kernels failed to launch (%s): the FP16 expert chain is used from here\n" ,ex .what ()); 4547 } 4548if (!done8 ) {// the FP16 chain: dequantize, two oneMKL GEMMs, SwiGLU, per expert 4549int64_t o = xg_r0 ; 4550for (int i = 0 ;i < xg_n ;++ i ) { 4551const int qd = i %DQ ; 4552pt .mark (kPfDequant ,cs ); 4553 strata::kernels::iq_dequant_expert_f16 (f .gu_type ,f .d_type ,xg_g [i ],xg_u [i ],xg_d [i ],f .n_ff ,f .n_embd , 4554m .dq_gu [qd ],m .dq_d [qd ],m .cs ); 4555pt .mark (kPfGemmGU ,cs ); 4556m .gemm .f16 (m .Xs + o * N ,m .dq_gu [qd ],m .GU + o * kFF2 ,xg_c [i ],kFF2 ,N ); 4557swiglu_interleaved (m .GU + o * kFF2 ,m .Hh + o * kFF ,xg_c [i ],m .cs ); 4558had_h (o ,xg_c [i ]); 4559pt .mark (kPfGemmD ,cs ); 4560m .gemm .f16 (m .Hh + o * kFF ,m .dq_d [qd ],m .Dm + o * N ,xg_c [i ],N ,kFF ); 4561o += xg_c [i ]; 4562 } 4563 } 4564if (xg_ns > 0 ) { 4565const int rel = xg_slots [xg_ns - 1 ]; 4566 dpct::sync_barrier (m .used [rel ],m .cs ); 4567for (int i = 0 ;i < xg_ns ;++ i )m .used_of [xg_slots [i ]]= rel ; 4568 } 4569xg_n = 0 ; 4570xg_ns = 0 ; 4571return ; 4572 } 4573if (static bool said = false; !said ) { 4574said = true; 4575 std::fprintf (stderr ,"strata: prompt experts on the fused grouped XMX (STRATA_PF_XMX=2)\n" ); 4576 } 4577// measured (xmx_group_parity, 16 experts): the fused launch wins below ~200 rows per 4578// expert, dequantize + oneMKL above (gate/up 0.67-0.76x at 320); STRATA_PF_XMX_ROWS moves it 4579static const int xg_max = [] { 4580const char * v = std::getenv ("STRATA_PF_XMX_ROWS" ); 4581return v ? std::atoi (v ) :200 ; 4582 }(); 4583if (nr /xg_n < xg_max ) { 4584pt .mark (kPfGemmGU ,cs ); 4585 strata::kernels::iq_xmx_grouped (f .gu_type ,xg_g ,xg_u ,xg_c ,xg_n ,m .Xs + xg_r0 * N , 4586m .GU + xg_r0 * kFF2 ,kFF2 , (int )N ,m .cs ); 4587swiglu_interleaved (m .GU + xg_r0 * kFF2 ,m .Hh + xg_r0 * kFF ,nr ,m .cs ); 4588had_h (xg_r0 ,nr ); 4589pt .mark (kPfGemmD ,cs ); 4590 strata::kernels::iq_xmx_grouped (f .d_type ,xg_d ,nullptr ,xg_c ,xg_n ,m .Hh + xg_r0 * kFF , 4591m .Dm + xg_r0 * N , (int )N ,kFF ,m .cs ); 4592 }else { 4593int64_t o = xg_r0 ; 4594for (int i = 0 ;i < xg_n ;++ i ) { 4595const int q = i %DQ ; 4596pt .mark (kPfDequant ,cs ); 4597 strata::kernels::iq_dequant_gu_f16 (f .gu_type ,xg_g [i ],xg_u [i ],f .n_ff ,f .n_embd , 4598m .dq_gu [q ],m .cs ); 4599 strata::kernels::iq_dequant_f16 (f .d_type ,xg_d [i ],f .n_embd * f .n_ff ,m .dq_d [q ],m .cs ); 4600pt .mark (kPfGemmGU ,cs ); 4601m .gemm .f16 (m .Xs + o * N ,m .dq_gu [q ],m .GU + o * kFF2 ,xg_c [i ],kFF2 ,N ); 4602swiglu_interleaved (m .GU + o * kFF2 ,m .Hh + o * kFF ,xg_c [i ],m .cs ); 4603had_h (o ,xg_c [i ]); 4604pt .mark (kPfGemmD ,cs ); 4605m .gemm .f16 (m .Hh + o * kFF ,m .dq_d [q ],m .Dm + o * N ,xg_c [i ],N ,kFF ); 4606o += xg_c [i ]; 4607 } 4608 } 4609if (xg_ns > 0 ) { 4610const int rel = xg_slots [xg_ns - 1 ]; 4611 dpct::sync_barrier (m .used [rel ],m .cs ); 4612for (int i = 0 ;i < xg_ns ;++ i )m .used_of [xg_slots [i ]]= rel ; 4613 } 4614xg_n = 0 ; 4615xg_ns = 0 ; 4616 }; 4617// one expert's products from its blob on the device; `slot` (a ring slot, or -1 for a resident 4618// expert) is released once the blob is read 4619auto compute = [& ](size_t j ,const uint8_t * blob_dev , 4620int slot )-> bool { 4621try { 4622const int32_t e = order [j ]; 4623pt .mark (kPfDequant ,cs ); 4624if (use_mmq ) { 4625// gather the expert into its group slot (GGUF blocks, unchanged or converted) 4626const size_t q = j %MMQ_GROUP ; 4627if (group_gather ) { 4628gg .blob [q ]= blob_dev ; 4629gg .n = (int )q + 1 ; 4630if (slot >=0 )gg_slots [gg_nslots ++ ]= slot ; 4631if (q + 1 < MMQ_GROUP && j + 1 < order .size ())return true; 4632flush (); 4633gg = mmq::GatherGroup {}; 4634 }else if (lay .native ) { 4635const auto & f = lay .fmt [(size_t )l ]; 4636 mmq::gather_native (blob_dev ,blob_dev + f .up_off ,mmq_gub /2 ,blob_dev + f .down_off , 4637mmq_db ,m .grp_gu + q * mmq_gub ,m .grp_d + q * mmq_db ,m .cs ); 4638 }else { 4639 mmq::gather_strata_q2 (blob_dev ,m .grp_gu + q * mmq_gub ,m .grp_d + q * mmq_db ,m .cs ); 4640 } 4641if (slot >=0 && !group_gather ) { 4642 dpct::sync_barrier (m .used [slot ],m .cs ); 4643m .used_of [slot ]= slot ; 4644 } 4645if (q + 1 < MMQ_GROUP && j + 1 < order .size ())return true; 4646// the group's products: gate/up, swiglu, the group's H to q8_1, down 4647const size_t j0 = j - q ,g = j0 /MMQ_GROUP ,n = order .size (); 4648const int ngx = (int ) (q + 1 ); 4649const int64_t r0 = m .bounds_host [j0 ],nr = m .bounds_host [j + 1 ]- r0 ; 4650int64_t maxr = 0 ; 4651for (size_t i = j0 ;i <=j ;++ i )maxr = std::max < int64_t > (maxr ,m .cnt [(size_t )order [i ]]); 4652pt .mark (kPfGemmGU ,cs ); 4653// the zeroed tail after the group's last expert (see MMQ_TAIL) 4654m .cs -> memset (m .grp_gu + (size_t )ngx * mmq_gub , 46550 ,MMQ_TAIL ); 4656m .cs -> memset (m .grp_d + (size_t )ngx * mmq_db ,0 , 4657MMQ_TAIL ); 4658 mmq::Product gu ; 4659gu .w = m .grp_gu ;gu .type = mmq_gt ;gu .w_rows = kFF2 ;gu .w_cols = N ;gu .expert_bytes = mmq_gub ; 4660gu .n = ngx ;gu .xq = m .Xq ;gu .bounds = m .bounds_dev + j0 ;gu .ids = m .ids_identity ; 4661gu .total_rows = T * K ;gu .max_rows = maxr ;gu .dst = m .GU ;gu .ld_dst = kFF2 ; 4662m .mmq_ctx -> run (gu ,m .cs ); 4663 mmq::swiglu (m .GU + r0 * kFF2 ,m .H + r0 * kFF ,nr ,kFF , !lay .native ,m .cs ); 4664pt .mark (kPfGemmD ,cs ); 4665 mmq::quantize (m .H + r0 * kFF ,nullptr ,m .Hq ,mmq_dt ,kFF ,kFF ,nr ,m .cs ); 4666 mmq::Product dn ; 4667dn .w = m .grp_d ;dn .type = mmq_dt ;dn .w_rows = N ;dn .w_cols = kFF ;dn .expert_bytes = mmq_db ; 4668dn .n = ngx ;dn .xq = m .Hq ;dn .bounds = m .bounds_dev + n + 1 + g * (MMQ_GROUP + 1 ); 4669dn .ids = m .ids_identity ;dn .total_rows = nr ;dn .max_rows = maxr ;dn .dst = m .Dm + r0 * N ; 4670dn .ld_dst = N ; 4671m .mmq_ctx -> run (dn ,m .cs ); 4672return true; 4673 } 4674if (xmx2 ) { 4675const auto & f = lay .fmt [(size_t )l ]; 4676if (xg_n == 0 )xg_r0 = m .off [(size_t )e ]; 4677xg_g [xg_n ]= blob_dev ; 4678xg_u [xg_n ]= blob_dev + f .up_off ; 4679xg_d [xg_n ]= blob_dev + f .down_off ; 4680xg_c [xg_n ]= m .cnt [(size_t )e ]; 4681++ xg_n ; 4682if (slot >=0 )xg_slots [xg_ns ++ ]= slot ; 4683if (xg_n == strata::kernels::kXmxGroupMax || j + 1 == order .size ())xflush (); 4684return true; 4685 } 4686if (f16_pairs ) { 4687const auto & f = lay .fmt [(size_t )l ]; 4688const int64_t o0 = m .off [(size_t )e ],ne = m .cnt [(size_t )e ]; 4689if ((f .gu_type == 16 || f .gu_type == 22 )&& f .d_type == 42 && 4690f .n_ff == 640 && f .n_embd == 2560 && ne > 0 && ne <=16 ) { 4691const int q = f16_n ; 4692 strata::kernels::iq_dequant_gu_f16 (f .gu_type ,blob_dev ,blob_dev + f .up_off , 4693f .n_ff ,f .n_embd ,m .dq_gu [q ],m .cs ); 4694f16_pending .v [q ]= {m .Xs + o0 * N ,m .dq_gu [q ],blob_dev + f .down_off , 4695m .GU + o0 * 1280 ,m .Hh + o0 * 640 ,m .Dm + o0 * N , (int )ne }; 4696f16_slots [q ]= slot ; 4697if (++ f16_n == 2 )flush_f16 (); 4698return true; 4699 } 4700flush_f16 (); 4701 } 4702const bool xmx_on = strata::prefill::xmx::mode ()== 1 ; 4703const int q = (int ) (j % (size_t )dq_slots ()); 4704if (lay .native ) { 4705// plan v0.3 P6: a native pack's layer, dequantized by llama.cpp's own formulas 4706const auto & f = lay .fmt [(size_t )l ]; 4707// 0.1.43: both matrices in one launch (the same values; STRATA_PF_DQ_FUSED=0: two launches) 4708static const bool dq_one = [] {const char * v = std::getenv ("STRATA_PF_DQ_FUSED" );return !(v && v [0 ]== '0' ); }(); 4709if (dq_one && !f16_pairs ) { 4710 strata::kernels::iq_dequant_expert_f16 (f .gu_type ,f .d_type ,blob_dev ,blob_dev + f .up_off , 4711blob_dev + f .down_off ,f .n_ff ,f .n_embd ,m .dq_gu [q ], 4712m .dq_d [q ],m .cs ); 4713 }else { 4714 strata::kernels::iq_dequant_gu_f16 (f .gu_type ,blob_dev ,blob_dev + f .up_off ,f .n_ff ,f .n_embd , 4715m .dq_gu [q ],m .cs ); 4716if (f16_pairs && f .d_type == 42 ) strata::kernels::iq_dequant_f16_plain_launch (f .d_type ,blob_dev + f .down_off ,f .n_embd * f .n_ff ,m .dq_d [q ],m .cs ); 4717else 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 ); 4718 } 4719 }else { 4720blob_dequant_f16 (blob_dev ,m .dq_gu [q ],m .dq_d [q ],m .cs ); 4721 } 4722if (slot >=0 ) { 4723 dpct::sync_barrier (m .used [slot ],m .cs ); 4724m .used_of [slot ]= slot ; 4725 } 4726if (xmx_on ) { 4727if (static bool said = false; !said ) { 4728said = true; 4729 std::fprintf (stderr ,"strata: prompt experts on the grouped XMX GEMM (STRATA_PF_XMX=1)\n" ); 4730 } 4731// A770 port: the group's experts sit in dq slots 0..q, their rows back to back from 4732// the first one's (the order is by id and so are the offsets) 4733if (q + 1 < dq_slots ()&& j + 1 < order .size ())return true; 4734const size_t j0 = j - (size_t )q ; 4735const int ng = q + 1 ; 4736int32_t gc [strata::prefill::xmx::kMaxGroup ]; 4737const uint16_t * wg [strata::prefill::xmx::kMaxGroup ]; 4738const uint16_t * wd [strata::prefill::xmx::kMaxGroup ]; 4739int64_t nr = 0 ; 4740for (int i = 0 ;i < ng ;++ i ) { 4741gc [i ]= m .cnt [(size_t )order [j0 + (size_t )i ]]; 4742wg [i ]= m .dq_gu [i ];wd [i ]= m .dq_d [i ]; 4743nr += gc [i ]; 4744 } 4745const int64_t r0 = m .off [(size_t )order [j0 ]]; 4746pt .mark (kPfGemmGU ,cs ); 4747if (nr /ng < strata::prefill::xmx::gu_max_mean ()) { 4748 strata::prefill::xmx::grouped_f16 (m .Xs + r0 * N ,wg ,gc ,ng ,m .GU + r0 * kFF2 ,kFF2 , 4749 (int )N ,m .cs ); 4750 }else { 4751int64_t o = r0 ; 4752for (int i = 0 ;i < ng ;++ i ) { 4753m .gemm .f16 (m .Xs + o * N ,wg [i ],m .GU + o * kFF2 ,gc [i ],kFF2 ,N ); 4754o += gc [i ]; 4755 } 4756 } 4757swiglu_interleaved (m .GU + r0 * kFF2 ,m .Hh + r0 * kFF ,nr ,m .cs ); 4758had_h (r0 ,nr ); 4759pt .mark (kPfGemmD ,cs ); 4760 strata::prefill::xmx::grouped_f16 (m .Hh + r0 * kFF ,wd ,gc ,ng ,m .Dm + r0 * N , (int )N ,kFF , 4761m .cs ); 4762return true; 4763 } 4764const int64_t o0 = m .off [(size_t )e ],ne = m .cnt [(size_t )e ]; 4765pt .mark (kPfGemmGU ,cs ); 4766m .gemm .f16 (m .Xs + o0 * N ,m .dq_gu [q ],m .GU + o0 * kFF2 ,ne ,kFF2 ,N ); 4767swiglu_interleaved (m .GU + o0 * kFF2 ,m .Hh + o0 * kFF ,ne ,m .cs ); 4768had_h (o0 ,ne ); 4769pt .mark (kPfGemmD ,cs ); 4770m .gemm .f16 (m .Hh + o0 * kFF ,m .dq_d [q ],m .Dm + o0 * N ,ne ,N ,kFF ); 4771return true; 4772 } 4773catch (sycl::exception const & exc ) { 4774 std::cerr <<exc .what () 4775 <<"Exception caught at file:" <<__FILE__ 4776 <<", line:" <<__LINE__ << std::endl ; 4777 std::exit (1 ); 4778 } 4779 }; 4780if (!stream_all ) { 4781size_t staged = 0 ; 4782const size_t lookahead = STAGE - 1 ; 4783for (size_t j = 0 ;j < order .size ();++ j ) { 4784while (staged < order .size ()&& staged <=j + lookahead ) { 4785if (!stage_one (staged ))return false; 4786++ staged ; 4787 } 4788const int32_t e = order [j ]; 4789if (stage_of [j ]< 0 ) { 4790++ stats_ .experts_resident ; 4791if (!compute (j ,m .cache -> device_slot (m .host_res [(size_t )l * m .g -> n_expert + e ]),-1 ))return false; 4792 }else { 4793pt .mark (kPfWaitCopy ,cs ); 4794 (m .cs )-> ext_oneapi_submit_barrier ( 4795 {* m .copied [stage_of [j ]]}); 4796if (!compute (j ,m .stage_dev [stage_of [j ]],stage_of [j ]))return false; 4797 } 4798 } 4799 }else { 4800// the streamed walk: this layer's entries [k, kend) in id order; an entry the routing did not 4801// pick only gives its slot back 4802size_t k = seq_start [(size_t )l ]; 4803const size_t kend = seq_start [(size_t )l + 1 ]; 4804auto release_to = [& ](int32_t e_stop ) { 4805try { 4806while (k < kend && seq [k ].e < e_stop ) { 4807if (f16_n )flush_f16 (); 4808if (gg_nslots > 0 )flush ();// the open group's slots get their event first 4809if (xg_n > 0 )xflush ();// the open group's slots get their event first 4810const int sl = (int ) (k % (size_t )m .ring ); 4811 dpct::sync_barrier (m .used [sl ],m .cs ); 4812m .used_of [sl ]= sl ; 4813consumed = ++ k ; 4814give_back (consumed ); 4815 } 4816 } 4817catch (sycl::exception const & exc ) { 4818 std::cerr 4819 <<exc .what () 4820 <<"Exception caught at file:" <<__FILE__ 4821 <<", line:" <<__LINE__ << std::endl ; 4822 std::exit (1 ); 4823 } 4824 }; 4825for (size_t j = 0 ;j < order .size ();++ j ) { 4826const int32_t e = order [j ]; 4827release_to (e ); 4828if (k < kend && seq [k ].e == e ) { 4829const int sl = (int ) (k % (size_t )m .ring ); 4830wait_issued (k ); 4831if (!group_gather ) { 4832pt .mark (kPfWaitCopy ,cs ); 4833 (m .cs )-> ext_oneapi_submit_barrier ( 4834 {* m .copied [sl ]}); 4835 } 4836if (!compute (j ,m .stage_dev [sl ],sl ))return false; 4837consumed = ++ k ; 4838if ((!group_gather || gg_nslots == 0 )&& xg_ns == 0 && f16_n == 0 )give_back (consumed );// its group was gathered 4839 }else { 4840const bool r0 = m .host_res && m .cache && m .host_res [(size_t )l * m .g -> n_expert + e ] >=0 ; 4841const uint8_t * bp = r0 ?m .cache -> device_slot (m .host_res [(size_t )l * m .g -> n_expert + e ]) 4842 : (m .pp && m .pp -> peer ?m .pp -> peer -> slot_ptr (l ,e ) :nullptr );// over the cap: P2P 4843if (bp == nullptr ) {err = "prefill: an expert is neither resident, streamed nor on the peer" ;return false; } 4844++ stats_ .experts_resident ; 4845if (!compute (j ,bp ,-1 ))return false; 4846if (group_gather && gg_nslots == 0 )give_back (consumed ); 4847 } 4848 } 4849release_to (m .g -> n_expert ); 4850xflush (); 4851give_back (consumed ); 4852 } 4853flush_f16 (); 4854if (stream_all && f16_pairs )give_back (consumed ); 4855 } 4856pt .mark (kPfCombine ,cs ); 4857if (peer_now ) {// multi-GPU: the peer's rows are in Dm (or, without P2P, in host memory) 4858 (m .cs )-> ext_oneapi_submit_barrier ({* m .pp -> ev_done }); 4859if (!m .pp -> p2p ) 4860copy_f32_wide (m .Dm + (size_t )m .pp -> back_at * N ,m .pp -> host_rows ,m .pp -> back_rows * N ,m .cs ); 4861 } 4862moe_combine (m .Dm ,m .slot_dev ,m .w ,m .shared ,m .sg ,m .bo ,T ,m .cs ); 4863// debug: STRATA_DBG_NAN=1 reports the first layer of a chunk whose MoE produced non-finite values 4864if (static const bool dbg = std::getenv ("STRATA_DBG_NAN" )!= nullptr ;dbg ) { 4865m .cs -> wait (); 4866auto bad = [& ](const float * d ,int64_t n ) { 4867try { 4868 std::vector < float > h ((size_t )n ); 4869 dpct::get_in_order_queue () 4870 .memcpy (h .data (),d , (size_t )n * 4 ) 4871 .wait (); 4872int64_t c = 0 ; 4873for (float v :h )c += !std::isfinite (v ); 4874return c ; 4875 } 4876catch (sycl::exception const & exc ) { 4877 std::cerr <<exc .what () 4878 <<"Exception caught at file:" <<__FILE__ 4879 <<", line:" <<__LINE__ << std::endl ; 4880 std::exit (1 ); 4881 } 4882 }; 4883// (fused: GU and H hold the grouping tables and int8 rows, not floats) 4884const int64_t bgu = fused_l ?0 :bad (m .GU ,T * K * kFF2 ),bdm = bad (m .Dm ,T * K * N ), 4885bbo = bad (m .bo ,T * N ); 4886const int64_t bh = m .H && !fused_l ?bad (m .H ,T * K * kFF ) :-1 ; 4887// the fp16 inputs of the experts' GEMMs: the gathered activations and the last dequantized 4888// gate/up (non-finite count, largest finite magnitude) 4889auto bad16 = [& ](const uint16_t * d ,int64_t n ,double & mx ) { 4890 std::vector < uint16_t > h ((size_t )n ); 4891 dpct::get_in_order_queue ().memcpy (h .data (),d , (size_t )n * 2 ).wait (); 4892int64_t c = 0 ; 4893mx = 0 ; 4894for (uint16_t v :h ) { 4895if ((v & 0x7c00 )== 0x7c00 ) {++ c ;continue ; } 4896const int e = (v >>10 )& 0x1f ; 4897const double a = e ? std::ldexp (1.0 + (v & 0x3ff ) /1024.0 ,e - 15 ) : std::ldexp ((v & 0x3ff ) /1024.0 ,-14 ); 4898mx = std::max (mx ,a ); 4899 } 4900return c ; 4901 }; 4902double mxs = 0 ,mxq = 0 ; 4903const int64_t bxs = (!use_mmq && m .Xs ) ?bad16 (m .Xs ,T * K * N ,mxs ) :-1 ; 4904const int64_t bdq = (!use_mmq && m .dq_gu [0 ]) ?bad16 (m .dq_gu [0 ], (int64_t )kFF2 * N ,mxq ) :-1 ; 4905static int64_t reported = -1 ; 4906if ((bgu || bdm || bbo || bh > 0 )&& reported != stats_ .chunks ) 4907 std::fprintf (stderr ,"strata dbg: layer %lld fp16 inputs: activations %lld non-finite (max %.3g), " 4908"dequantized gate/up %lld non-finite (max %.3g)\n" , (long long )l , (long long )bxs ,mxs , 4909 (long long )bdq ,mxq ); 4910if ((bgu || bdm || bbo || bh > 0 )&& reported != stats_ .chunks ) { 4911reported = stats_ .chunks ; 4912 std::fprintf (stderr ,"strata dbg: layer %lld (mmq %d, types %d/%d, %zu experts): non-finite GU %lld " 4913"H %lld Dm %lld bo %lld of T %lld\n" , (long long )l , (int )use_mmq ,mmq_gt ,mmq_dt , 4914n_order , (long long )bgu , (long long )bh , (long long )bdm , (long long )bbo , 4915 (long long )T ); 4916 } 4917 } 4918 } 4919// ---- the hyper-connection write of this half; F-2: fused with the next half's norm when nothing else 4920// touches R in between (not the stage's last half, not before the PLE block of layer 1, not under a 4921// control vector) 4922const int64_t nl = half == 0 ?l :l + 1 ; 4923const bool steered = half == 1 && strata::kernels::cvec ().covers (l ); 4924const float * cv_dir = nullptr ,* cv_s = nullptr ; 4925const int * cv_on = nullptr ; 4926const bool cv_fused = steered && cvec_fuse ()&& !gr_unfused ()&& nl < LE && !(nl == 1 && ple_on )&& 4927 strata::kernels::cvec ().n_embd == N && strata::kernels::cvec ().hc == HC && 4928 strata::kernels::cvec_tables (& cv_dir ,& cv_s ,& cv_on ); 4929const bool fuse = !gr_unfused ()&& nl < LE && !(half == 1 && nl == 1 && ple_on )&& (!steered || cv_fused ); 4930const core::WeightRef * wnn = nullptr ; 4931if (fuse ) { 4932const core::LayerView vn (* m .wt ,nl ); 4933wnn = need (vn ,half == 0 ?"hc_ffn_norm.weight" :"hc_attn_norm.weight" ,err ); 4934if (!wnn )return false; 4935 } 4936if (wnn && cv_fused ) { 4937// STRATA_CVEC_FUSE_CHECK=N: on the first N fused writes, also run the three-kernel path on a copy 4938// of R and report whether R, the row scales and the BF16 image are bit-identical 4939static int checks = [] {const char * e = std::getenv ("STRATA_CVEC_FUSE_CHECK" );return e ? std::atoi (e ) :0 ; }(); 4940if (checks > 0 ) { 4941-- checks ; 4942float * Rc = nullptr ,* rc = nullptr ; 4943uint16_t * xc = nullptr ; 4944Rc = (float * )sycl::malloc_device ( 4945 (size_t )T * D * 4 , dpct::get_in_order_queue ()); 4946rc = (float * )sycl::malloc_device ( 4947 (size_t )T * HC * 4 , dpct::get_in_order_queue ()); 4948xc = (uint16_t * )sycl::malloc_device ( 4949 (size_t )T * D * 2 , dpct::get_in_order_queue ()); 4950/* 4951DPCT1124: cudaMemcpyAsync is migrated to 4952asynchronous memcpy API. While the origin API might be 4953synchronous, it depends on the type of operand memory, 4954so you may need to call wait() on event return by memcpy 4955API to ensure synchronization behavior. 4956*/ 4957m .cs -> memcpy (Rc ,m .R , (size_t )T * D * 4 ); 4958gr_write (Rc ,m .bo ,m .inj ,HC ,T ,m .cs ); 4959 strata::kernels::cvec_apply (Rc ,l ,T ,D ,nullptr ,0 ,nullptr ,0 , false,m .cs ); 4960gr_norm_rs (Rc , (const float * )wnn -> data ,EPS ,rc ,xc ,T ,m .cs ,nullptr ,D ); 4961gr_write_cvec_norm_rs (m .R ,m .bo ,m .inj ,HC ,cv_dir + l * N ,cv_s + l ,cv_on , 4962 strata::kernels::cvec ().mode , (const float * )wnn -> data ,EPS ,m .grs , 4963m .xn16 ,T ,m .cs ,m .xn16_lo ,ldx ); 4964 std::vector < float > a ((size_t )T * D ),b ((size_t )T * D ),ra ((size_t )T * HC ),rb ((size_t )T * HC ); 4965 std::vector < uint16_t > xa ((size_t )T * D ),xb ((size_t )T * D ); 4966/* 4967DPCT1124: cudaMemcpyAsync is migrated to 4968asynchronous memcpy API. While the origin API might be 4969synchronous, it depends on the type of operand memory, 4970so you may need to call wait() on event return by memcpy 4971API to ensure synchronization behavior. 4972*/ 4973m .cs -> memcpy (a .data (),m .R ,a .size ()* 4 ); 4974/* 4975DPCT1124: cudaMemcpyAsync is migrated to 4976asynchronous memcpy API. While the origin API might be 4977synchronous, it depends on the type of operand memory, 4978so you may need to call wait() on event return by memcpy 4979API to ensure synchronization behavior. 4980*/ 4981m .cs -> memcpy (b .data (),Rc ,b .size ()* 4 ); 4982/* 4983DPCT1124: cudaMemcpyAsync is migrated to 4984asynchronous memcpy API. While the origin API might be 4985synchronous, it depends on the type of operand memory, 4986so you may need to call wait() on event return by memcpy 4987API to ensure synchronization behavior. 4988*/ 4989m .cs -> memcpy (ra .data (),m .grs ,ra .size ()* 4 ); 4990/* 4991DPCT1124: cudaMemcpyAsync is migrated to 4992asynchronous memcpy API. While the origin API might be 4993synchronous, it depends on the type of operand memory, 4994so you may need to call wait() on event return by memcpy 4995API to ensure synchronization behavior. 4996*/ 4997m .cs -> memcpy (rb .data (),rc ,rb .size ()* 4 ); 4998/* 4999DPCT1124: cudaMemcpyAsync is migrated to 5000asynchronous memcpy API. While the origin API might be 5001synchronous, it depends on the type of operand memory, 5002so you may need to call wait() on event return by memcpy 5003API to ensure synchronization behavior. 5004*/ 5005m .cs -> memcpy (xa .data (),m .xn16 ,xa .size ()* 2 ); 5006/* 5007DPCT1124: cudaMemcpyAsync is migrated to 5008asynchronous memcpy API. While the origin API might be 5009synchronous, it depends on the type of operand memory, 5010so you may need to call wait() on event return by memcpy 5011API to ensure synchronization behavior. 5012*/ 5013m .cs -> memcpy (xb .data (),xc ,xb .size ()* 2 ); 5014m .cs -> wait (); 5015 sycl::free (Rc , dpct::get_in_order_queue ()); 5016 sycl::free (rc , dpct::get_in_order_queue ()); 5017 sycl::free (xc , dpct::get_in_order_queue ()); 5018 std::fprintf (stderr ,"strata: STRATA_CVEC_FUSE_CHECK layer %lld T %lld: R %s, rs %s, xn16 %s\n" , 5019 (long long )l , (long long )T , 5020 std::memcmp (a .data (),b .data (),a .size ()* 4 ) ?"DIFFERS" :"identical" , 5021 std::memcmp (ra .data (),rb .data (),ra .size ()* 4 ) ?"DIFFERS" :"identical" , 5022 std::memcmp (xa .data (),xb .data (),xa .size ()* 2 ) ?"DIFFERS" :"identical" ); 5023 }else 5024gr_write_cvec_norm_rs (m .R ,m .bo ,m .inj ,HC ,cv_dir + l * N ,cv_s + l ,cv_on , 5025 strata::kernels::cvec ().mode , (const float * )wnn -> data ,EPS ,m .grs ,m .xn16 , 5026T ,m .cs ,m .xn16_lo ,ldx ); 5027normed = true; 5028 }else if (wnn ) { 5029gr_write_norm_rs (m .R ,m .bo ,m .inj ,HC , (const float * )wnn -> data ,EPS ,m .grs ,m .xn16 ,T ,m .cs , 5030m .xn16_lo ,ldx ); 5031normed = true; 5032 }else { 5033gr_write (m .R ,m .bo ,m .inj ,HC ,T ,m .cs ); 5034 } 5035if (steered && !cv_fused )// --control-vector-scaled 5036 strata::kernels::cvec_apply (m .R ,l ,T ,D ,nullptr ,0 ,nullptr ,0 , false,m .cs ); 5037if (half == 1 && tap_rows > 0 && tap_slot [(size_t )l ] >=0 )// DFlash2: this layer's completed output, mean of the streams 5038 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_layers_ .size ()* N ,N , 5039 (int )HC , (int )tap_rows ,m .cs ); 5040 } 5041 } 5042if (!ple_land ())return false;// a stage that ends before layer 1: the rows land anyway, the next gather starts 5043if (issuer .joinable ()) { 5044issuer .join (); 5045stats_ .ms_experts_host += iss_ms ; 5046stats_ .experts_streamed += iss_streamed ; 5047stats_ .experts_dma += iss_dma ; 5048 } 5049stats_ .tokens += T ; 5050 core::progress_at ("reading the prompt (batched): finishing the chunk from token" ,p0 ); 5051pt .mark (kPfStart ,cs ); 5052if (next_ != nullptr ) { 5053// The current hand-off slot was used two chunks ago. 5054float * h = m .hand [hand_buf_ ]; 5055/* 5056DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy 5057API. While the origin API might be synchronous, it depends on the 5058type of operand memory, so you may need to call wait() on event 5059return by memcpy API to ensure synchronization behavior. 5060*/ 5061if (DPCT_CHECK_ERROR (m .cs -> memcpy (h ,m .R , (size_t )T * D * 4 ))!= 50620 || 5063DPCT_CHECK_ERROR (m .cs -> wait ())!= 0 ) { 5064/* 5065DPCT1009: SYCL reports errors using exceptions and does not 5066use error codes. Please replace the 5067"get_error_string_dummy(...)" with a real error-handling 5068function. 5069*/ 5070/* 5071DPCT1010: SYCL uses exceptions to report errors and does not 5072use the error codes. The cudaGetLastError function call was 5073replaced with 0. You need to rewrite this code. 5074*/ 5075err = std::string ("prefill: the layer split's hand-off: " )+ 5076 dpct::get_error_string_dummy (0 ); 5077return false; 5078 } 5079// Wait only for the DIRECT successor's previous chunk. That successor 5080// may already have forwarded its older chunk to later GPUs. 5081if (on_stage_chunk && !on_stage_chunk (p0 + T ,err ))return false; 5082if (next_run_ .valid ()&& !next_run_ .get ()) {err = next_err_ ;return false; } 5083next_err_ .clear (); 5084next_ -> hand_in_ = h ; 5085next_ -> single_chunk_ = single_chunk ; 5086next_run_ = std::async (std::launch::async , [this ,tokens ,c0 ,T ,p0 ] { 5087return next_ -> run_impl (tokens + c0 ,T ,p0 ,next_err_ ); 5088 }); 5089hand_buf_ ^=1 ; 5090continue ;// the last stage reports the chunk (on_chunk) 5091 } 5092if (const char * dump = std::getenv ("STRATA_PREFILL_DUMP_R" )) {// debug: the final residuals, every 64th 5093m .cs -> wait ();// position (A/B quality of this path) 5094if (std::FILE * f = std::fopen (dump ,c0 == 0 ?"wb" :"ab" )) { 5095 std::vector < float > row ((size_t )D ); 5096for (int64_t t = (64 - p0 %64 ) %64 ;t < T ;t += 64 ) { 5097 dpct::get_in_order_queue () 5098 .memcpy (row .data (),m .R + t * D , (size_t )D * 4 ) 5099 .wait (); 5100const int64_t pos = p0 + t ; 5101 std::fwrite (& pos ,sizeof pos ,1 ,f ); 5102 std::fwrite (row .data (),4 ,row .size (),f ); 5103 } 5104 std::fclose (f ); 5105 } 5106 } 5107if (const char * dump = std::getenv ("STRATA_PREFILL_DUMP_R_ALL" )) { 5108// S25 (draft-layer distillation data, opt-in): every position's final multi-stream residual as BF16 5109// (round-to-nearest-even), rows in position order, appended across chunks and requests: [n][hc*n_embd] 5110m .cs -> wait (); 5111if (std::FILE * f = std::fopen (dump ,"ab" )) { 5112constexpr int64_t kRows = 512 ; 5113 std::vector < float > rows ((size_t ) (kRows * D )); 5114 std::vector < uint16_t > out ((size_t ) (kRows * D )); 5115for (int64_t t0 = 0 ;t0 < T ;t0 += kRows ) { 5116const int64_t nr = std::min < int64_t > (kRows ,T - t0 ); 5117 dpct::get_in_order_queue () 5118 .memcpy (rows .data (),m .R + t0 * D , (size_t )(nr * D )* 4 ) 5119 .wait (); 5120for (int64_t i = 0 ;i < nr * D ;++ i ) { 5121uint32_t u ; 5122 std::memcpy (& u ,& rows [(size_t )i ],4 ); 5123u += 0x7fffu + ((u >>16 )& 1u ); 5124out [(size_t )i ]= (uint16_t ) (u >>16 ); 5125 } 5126 std::fwrite (out .data (),2 , (size_t ) (nr * D ),f ); 5127 } 5128 std::fclose (f ); 5129 } 5130 } 5131if (tap_rows > 0 && on_taps ) { 5132m .cs -> wait (); 5133if (!on_taps (tap_dev_ ,tap_rows ,p0 + tap_t0 ,err ))return false; 5134 } 5135if (on_chunk || on_stage_chunk ) { 5136const auto toc = Clock ::now (); 5137if (DPCT_CHECK_ERROR (m .cs -> wait ())!= 0 ) { 5138/* 5139DPCT1009: SYCL reports errors using exceptions and does not 5140use error codes. Please replace the 5141"get_error_string_dummy(...)" with a real error-handling 5142function. 5143*/ 5144/* 5145DPCT1010: SYCL uses exceptions to report errors and does not 5146use the error codes. The cudaGetLastError function call was 5147replaced with 0. You need to rewrite this code. 5148*/ 5149err = 5150 std::string ("prefill: " )+ dpct::get_error_string_dummy (0 ); 5151return false; 5152 } 5153const auto toc2 = Clock ::now (); 5154if (on_stage_chunk && !on_stage_chunk (p0 + T ,err ))return false; 5155if (on_chunk && !on_chunk (m .R ,T ,p0 ,err ))return false; 5156host_sync_ms += std::chrono::duration < double , std::milli > (toc2 - toc ).count (); 5157host_chunk_ms += ms_since (toc2 ); 5158 } 5159 } 5160// Do not drain the successor here. This is the overlap: an intermediate 5161// stage can return while later GPUs are still processing the previous chunk. 5162ss .ple_prev [0 ]= prev [0 ]; 5163ss .ple_prev [1 ]= prev [1 ]; 5164if (std::getenv ("STRATA_DBG_NAN" )!= nullptr ) {// debug: the state the prompt leaves for the token path 5165m .cs -> wait (); 5166auto bad = [& ](const float * d ,int64_t n ) { 5167try { 5168 std::vector < float > h ((size_t )n ); 5169 dpct::get_in_order_queue () 5170 .memcpy (h .data (),d , (size_t )n * 4 ) 5171 .wait (); 5172int64_t c = 0 ; 5173double mx = 0 ; 5174for (float v :h ) {c += !std::isfinite (v );if (std::isfinite (v ))mx = std::max (mx , (double ) std::fabs (v )); } 5175 std::fprintf (stderr ," %lld non-finite (max |x| %.3g)" , (long long )c ,mx ); 5176 } 5177catch (sycl::exception const & exc ) { 5178 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 5179 <<", line:" <<__LINE__ << std::endl ; 5180 std::exit (1 ); 5181 } 5182 }; 5183const int64_t last = (n - 1 ) %m .T ; 5184 std::fprintf (stderr ,"strata dbg: prompt end: last residual row" ); 5185bad (m .R + last * D ,D ); 5186if (ss .ple .ready ()) { std::fprintf (stderr ,"; PLE history" );bad (ss .ple .hist , (int64_t ) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM ); } 5187 std::fprintf (stderr ,"; GDN state 0" ); 5188bad (ss .gdn_state ,64 * 1024 ); 5189 std::fprintf (stderr ,"\n" ); 5190 } 5191if (DPCT_CHECK_ERROR (m .cs -> wait ())!= 0 ) { 5192/* 5193DPCT1009: SYCL reports errors using exceptions and does not use 5194error codes. Please replace the "get_error_string_dummy(...)" with a 5195real error-handling function. 5196*/ 5197/* 5198DPCT1010: SYCL uses exceptions to report errors and does not use the 5199error codes. The cudaGetLastError function call was replaced with 0. You 5200need to rewrite this code. 5201*/ 5202err = std::string ("prefill: " )+ dpct::get_error_string_dummy (0 ); 5203return false; 5204 } 5205// (PR #121) an expert copy that failed on the copy stream surfaces here, not in the next request 5206/* 5207DPCT1000: Error handling if-stmt was detected but could not be 5208rewritten. 5209*/ 5210if (const dpct::err0 cst = DPCT_CHECK_ERROR (m .copy -> wait ());cst != 0 ) { 5211/* 5212DPCT1009: SYCL reports errors using exceptions and does not use 5213error codes. Please replace the "get_error_string_dummy(...)" with a 5214real error-handling function. 5215*/ 5216/* 5217DPCT1001: The statement could not be removed. 5218*/ 5219err = std::string ("prefill: expert copy stream: " )+ 5220 dpct::get_error_string_dummy (cst ); 5221return false; 5222 } 5223if (kv_prefetch ) { 5224/* 5225DPCT1000: Error handling if-stmt was detected but could not be 5226rewritten. 5227*/ 5228if (const dpct::err0 cst = DPCT_CHECK_ERROR (m .kv_copy -> wait ()); 5229cst != 0 ) { 5230/* 5231DPCT1009: SYCL reports errors using exceptions and does not use 5232error codes. Please replace the "get_error_string_dummy(...)" with a 5233real error-handling function. 5234*/ 5235/* 5236DPCT1001: The statement could not be removed. 5237*/ 5238err = std::string ("prefill: KV prefetch stream: " )+ 5239 dpct::get_error_string_dummy (cst ); 5240return false; 5241 } 5242 std::fprintf (stderr ,"strata KV prefetch: %lld layer prefixes, single existing staging pool\n" , 5243 (long long )kv_prefetches ); 5244 } 5245stats_ .ms_total += ms_since (t_start ); 5246 strata::kprof::window_end ("prompt" );// STRATA_KPROF=1: the per-kernel table of this prompt 5247if (pt .on ) { 5248pt .fold (); 5249double total = 0.0 ; 5250for (double v :pt .ms )total += v ; 5251 std::string line ; 5252char b [96 ]; 5253for (int i = 0 ;i < kPfCount ;++ i ) { 5254if (pt .ms [i ] <=0.0 )continue ; 5255 std::snprintf (b ,sizeof b ," %s %.0f (%.1f%%)" ,kPfNames [i ],pt .ms [i ],total > 0 ?100.0 * pt .ms [i ] /total :0.0 ); 5256line += b ; 5257 } 5258 std::fprintf (stderr ,"strata prefill timing: %lld tokens, GPU timeline %.0f ms, wall %.0f ms, host staging %.0f ms:%s\n" , 5259 (long long )n ,total ,ms_since (t_start ),stats_ .ms_experts_host ,line .c_str ()); 5260 std::fprintf (stderr ,"strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) %.0f ms, " 5261"waiting for each chunk %.0f ms, after each chunk (the draft layer, progress) %.0f ms, " 5262"PLE %.0f ms\n" ,host_setup_ms ,host_sync_ms ,host_chunk_ms ,stats_ .ms_ple ); 5263if (pe .on ) { 5264/* 5265DPCT1093: The "pe.dev" device may be not the one intended for 5266use. Adjust the selected device if needed. 5267*/ 5268/* 5269DPCT1093: The "pd" device may be not the one intended for use. 5270Adjust the selected device if needed. 5271*/ 5272int pd = 0 ;pd = dpct::get_current_device_id (); 5273 dpct::select_device (pe .dev );m .pp -> s -> wait ();pe .fold (); 5274 dpct::select_device (pd ); 5275 std::string pl ; 5276for (int i = 0 ;i < kPeCount ;++ i ) { 5277 std::snprintf (b ,sizeof b ," %s %.0f" ,kPeNames [i ],pe .ms [i ]); 5278pl += b ; 5279 } 5280 std::fprintf (stderr ,"strata prefill timing (peer GPU, ms):%s; MoE layers %lld, rows/layer %.0f of %lld cap, experts/layer %.0f, " 5281"over the cap %lld\n" ,pl .c_str (), (long long )m .pp -> layers , 5282m .pp -> layers ? (double )m .pp -> rows /m .pp -> layers :0.0 , (long long )m .pp -> cap_rows , 5283m .pp -> layers ? (double )m .pp -> experts /m .pp -> layers :0.0 , (long long )m .pp -> over_cap ); 5284if (m .pp -> ps_frac > 0.0 ) 5285 std::fprintf (stderr ,"strata prefill timing: peer-streamed experts %lld (%.0f per MoE layer)\n" , 5286 (long long )m .pp -> ps_experts ,m .pp -> layers ? (double )m .pp -> ps_experts /m .pp -> layers :0.0 ); 5287 } 5288 } 5289if (std::getenv ("STRATA_STATE_HASH_GDN" )!= nullptr ) {// debug: the GDN states as the prompt path leaves them 5290m .cs -> wait (); 5291 std::vector < uint8_t > b ((size_t )gdn_floats * 4 ); 5292 std::string line ; 5293char h [8 ]; 5294for (int64_t i = 0 ;i < ss .gdn_alloc ;++ i ) { 5295 dpct::get_in_order_queue () 5296 .memcpy (b .data (),ss .gdn_state + (size_t )i * gdn_floats , 5297b .size ()) 5298 .wait (); 5299uint64_t x = 1469598103934665603ull ; 5300for (uint8_t c :b )x = (x ^c )* 1099511628211ull ; 5301 std::snprintf (h ,sizeof (h ),"%04llx " , (unsigned long long ) (x & 0xffff )); 5302line += h ; 5303 } 5304 std::fprintf (stderr ,"strata prefill: GDN_HASH %s\n" ,line .c_str ()); 5305 } 5306return true; 5307} 5308catch (sycl::exception const & exc ) { 5309 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 5310 <<", line:" <<__LINE__ << std::endl ; 5311 std::exit (1 ); 5312} 5313 5314bool Prefill ::drain_pipeline (std::string & err ) { 5315bool ok = true; 5316 5317if (next_run_ .valid ()) { 5318if (!next_run_ .get ()) { 5319err = next_err_ ; 5320ok = false; 5321 } 5322 } 5323 5324if (next_ != nullptr ) { 5325 std::string tail_err ; 5326if (!next_ -> drain_pipeline (tail_err )) { 5327if (ok )err = tail_err ; 5328ok = false; 5329 } 5330 } 5331 5332return ok ; 5333} 5334 5335bool Prefill ::run (const int64_t * tokens ,int64_t n ,int64_t pos0 , std::string & err ) { 5336static strata::kernels::two_pass::RequestStatus tp_status (std::getenv ("STRATA_SELECT_TWO_PASS" )); 5337 (void )tp_status .on ("SYCL" );// the two-pass scorer is CUDA-only: say once that a set switch is not used 5338const bool body_ok = run_impl (tokens ,n ,pos0 ,err ); 5339 5340 std::string drain_err ; 5341const bool drain_ok = drain_pipeline (drain_err ); 5342 5343if (!body_ok )return false; 5344if (!drain_ok ) { 5345err = drain_err ; 5346return false; 5347 } 5348return true; 5349} 5350 5351}// namespace strata::prefill