okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
a8a51b280
main
1#include "private_mtp_demand.hpp" 2#define DPCT_COMPAT_RT_VERSION 12080 3#include "strata/workload_trace.hpp" 4// src/program/generate.cpp - P2.S6: `strata generate`. 5// 6// THE DRIVER, and the first program in this project that answers a question. 7// Everything below it is a component; this is the thing that composes them into 8// a token: 9// 10// embed_row(token) -> 48 captured layer graphs (the CPU expert pool 11// behind the doorbell) -> lm_head(R) -> sample -> 12// embed_row(next) -> ... 13// 14// WHAT IT IS NOT. There is no tokenizer here. `pack/full/tokenizer/` and 15// `tools/strata_tokenizer.py` exist, and a C++ BPE is Phase 1's deliverable 16// rather than this program's, so the prompt arrives as IDS via 17// `--tokens`. That is not a placeholder: it is exactly what Gate C1 needs, 18// because C1 compares logits against llama.cpp on the SAME ids, and a tokenizer 19// on only one side of that comparison is a second variable. 20// 21// AND IT IS PHASE 2, so hit rate is `h = 0` and the number it prints is slow on 22// purpose 23// (`phase-2-correct-engine.md:5-9`). What it is FOR is the honest tok/s figure 24// and the logit dump. 25 26#define DPCT_PROFILING_ENABLED 27#include <sycl/sycl.hpp> 28#include <dpct/dpct.hpp> 29#include "strata/sycl_queue.hpp" 30#include "strata/uc_probe.hpp" 31#include "strata/pipeline_auto.hpp" 32#include "strata/sycl_doorbell.hpp" 33#include "strata/core/arch_defaults.hpp" 34#include "strata/core/dma_batch.hpp" 35#include "strata/core/device.hpp" 36#include "strata/core/geometry.hpp" 37#include "strata/core/remote_expert_opt.hpp" 38#include "strata/core/expert_cache.hpp" 39#include "strata/core/short_cache.hpp" 40#include "strata/core/conversation_snapshot.hpp" 41#include "strata/core/conversation_file.hpp" 42#include "strata/core/conversation_memory.hpp" 43#include "strata/core/coupled_draft.hpp" 44#include "strata/core/expert_source.hpp" 45#include "strata/core/gguf_expert_source.hpp" 46namespace strata::prefill {void set_nonresident_share (double share ); }// SYCL port: prefill.cpp 47#include "strata/kernels/resident_plan_mirror.hpp" 48#include "strata/core/pinned.hpp" 49#include "strata/core/remote_experts.hpp" 50#include "strata/core/on_device.hpp" 51#include "b60_layout_host.hpp" 52#include "strata/core/peer_experts.hpp" 53#include "strata/core/layer.hpp" 54#include "strata/core/layout.hpp" 55#include "strata/core/session.hpp" 56#include "strata/core/weights.hpp" 57#include "strata/kernels/cpu/expert.hpp" 58#include "strata/kernels/cpu/pool.hpp" 59#include "strata/kernels/cpu/expert_layout.hpp" 60#include "strata/kernels/cpu/hadamard.hpp" 61#include "strata/kernels/ngram.hpp" 62#include "strata/kernels/iq_kernels.hpp" 63#include "strata/kernels/s2_expert_grouped.hpp" 64#include "strata/kernels/sampler.hpp" 65#include "strata/kernels/verify_kernels.hpp" 66#include "strata/kernels/elementwise.hpp" 67#include "strata/kernels/shared_expert.hpp" 68#include "strata/kernels/native_moe.hpp" 69#include "strata/kernels/native_gdn.hpp" 70#include "strata/kernels/native_router.hpp" 71#include "strata/kernels/native_qsa.hpp" 72#include "strata/kernels/native_qsa_indexer.hpp" 73#include "strata/kernels/native_rope.hpp" 74#include "strata/kernels/mrope.hpp" 75#include "strata/kernels/kv_q4.hpp" 76#include "strata/program/adapt_decay.hpp" 77#include "strata/program/split_rules.hpp" 78#include "strata/kernels/qsa.hpp" 79#include "strata/core/native_head.hpp" 80#include "strata/core/verify.hpp" 81#include "strata/core/mtp.hpp" 82#include "strata/core/dflash2.hpp" 83#include "strata/spec/window_rule.hpp" 84#include "strata/prefill/prefill.hpp" 85#include "strata/core/native_dense.hpp" 86#include "strata/program/logits_selection.hpp" 87#include "strata/program/conv_cache.hpp" 88#include "strata/program/message_boundary.hpp" 89#include "strata/spec/draft_policy.hpp" 90#include "strata/spec/draft_source.hpp" 91#include "strata/spec/suffix_drafter.hpp" 92#include "strata/kernels/cvec.hpp" 93#include "strata/core/progress.hpp" 94#include "strata/core/device.hpp" 95#include "strata/core/emulate.hpp" 96#ifndef NOMINMAX 97#define NOMINMAX // gguf_reader.hpp includes windows.h 98#endif 99#include "strata/artifact/gguf_reader.hpp" 100#include "strata/core/family_layout.hpp" 101#if defined(_WIN32 ) 102#include <windows.h> 103#include <psapi.h> 104#include <io.h> 105#else 106#include <unistd.h> 107#include <cerrno> 108#include <sys/stat.h> 109#include <sys/sysmacros.h> 110#endif 111 112#include <array> 113#include <chrono> 114#include <algorithm> 115#include <memory> 116#include <iostream> 117#include <functional> 118#include <future> 119#include <thread> 120#include <atomic> 121#include <condition_variable> 122#include <deque> 123#include <map> 124#include <mutex> 125#include <optional> 126#include <new> 127#include <charconv> 128#include <cmath> 129#include <limits> 130#include <cstdio> 131#include <cstdlib> 132#include <cstring> 133#include <filesystem> 134#include <fstream> 135#include <sstream> 136#include <string> 137#include <set> 138#include <vector> 139 140namespace { 141bool sycl_mirror_adapt () { 142static const bool enabled = [] { 143const char * v = std::getenv ("STRATA_SYCL_MIRROR_ADAPT" ); 144return v && v [0 ]== '1' ; 145 }(); 146return enabled ; 147} 148 149// Windows' WDDM driver model: native Windows, or WSL2 (its GPU goes through /dev/dxg to the Windows driver). There, 150// pinning a large arena into two CUDA contexts leaves WDDM refusing every later allocation (the 5080 + 3090 rig); 151// a Linux driver has no such limit (#253: the 8 GiB cap cost a 4090 + 3060 split 3x of its prompt speed). 152bool under_wddm () { 153#ifdef _WIN32 154return true; 155#else 156static const bool dxg = std::filesystem::exists ("/dev/dxg" ); 157return dxg ; 158#endif 159} 160 161// #620 #486: " (N MiB of M MiB VRAM free on this GPU)" for an allocation's failure message (clears the error first) 162std::string vram_free_note ()try { 163/* 164DPCT1010: SYCL uses exceptions to report errors and does not use the 165error codes. The cudaGetLastError function call was replaced with 0. You 166need to rewrite this code. 167*/ 168 (void )0 ; 169size_t free_b = 0 ,total_b = 0 ; 170/* 171DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions for 172device information which may not be supported by all compilers or runtimes. 173You may need to adjust the code. 174*/ 175if (DPCT_CHECK_ERROR ( 176 dpct::get_current_device ().get_memory_info (free_b ,total_b ))!= 0 ) { 177/* 178DPCT1010: SYCL uses exceptions to report errors and does not use 179the error codes. The cudaGetLastError function call was replaced with 0. 180You need to rewrite this code. 181*/ 182 (void )0 ; 183return {}; 184 } 185char buf [96 ]; 186 std::snprintf (buf ,sizeof buf ," (%llu MiB of %llu MiB VRAM free on this GPU)" , (unsigned long long ) (free_b >>20 ), 187 (unsigned long long ) (total_b >>20 )); 188return buf ; 189} 190catch (sycl::exception const & exc ) { 191 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 192 <<", line:" <<__LINE__ << std::endl ; 193 std::exit (1 ); 194} 195 196// perf-review D-4: the lent slots are refilled with queued copies and one wait; STRATA_REFILL_BLOCKING=1 waits on each 197// A file-backed arena on AMD (STRATA_ARENA_MMAP; the engine raises ROCclr's pin-in-place threshold, see main): an 198// adaptive swap copies one expert straight from the mapped file. Through ROCclr's staging that copy blocks the host 199// (decode windows of 150+ ms); instead the batch's pages are locked here for the async copies and unlocked when they 200// have landed (unpin_blobs), so the release that follows can hand them back. Neighbouring experts share a page and 201// a copy from a range only PART of which is registered fails ("invalid argument"), so the page ranges are merged 202// first and each merged span is registered once. A span that does not register is copied through the staging 203// path. Portable: a layer split copies to either card. 204// Whether pin_blobs locks anything (AMD on Linux with STRATA_ARENA_MMAP=1): the callers only gather the swaps' spans 205// then - `blob()` is not free (it counts reads, and the file tier may assemble the blob), so the default runs skip it. 206bool pin_blobs_on () { 207#if (defined(STRATA_USE_HIP )|| defined(STRATA_HIP_GFX906 ))&& !defined(_WIN32 ) 208static const bool on = std::getenv ("STRATA_ARENA_MMAP" )&& std::getenv ("STRATA_ARENA_MMAP" )[0 ]== '1' ; 209return on ; 210#else 211return false; 212#endif 213} 214// #884 (HIP, opt-in STRATA_HIP_ADAPT_KERNEL_COPY=1): an adaptive swap's host-to-device copy as a kernel on the refill stream 215// instead of a copy-engine (SDMA) memcpy. 2x RX 6900 XT hung after a long prompt only with the MMQ prompt path, adaptive swaps 216// AND SDMA together (any one off avoids it; the barrier packet that never passes is a ROCm-side problem, #884). This keeps 217// the swaps off SDMA without turning SDMA off for the prompt read (HSA_ENABLE_SDMA=0 costs 10-24% of it). Needs the source to 218// be mapped, 16-byte aligned memory (the registered arena); anything else takes the normal cudaMemcpyAsync. 219dpct::err0 adapt_copy_h2d (void * dst ,const void * src ,size_t bytes , 220 dpct::queue_ptr st )try { 221#if defined(STRATA_USE_HIP ) 222static const bool kernel = [] { 223const char * e = std::getenv ("STRATA_HIP_ADAPT_KERNEL_COPY" ); 224const bool on = e != nullptr && e [0 ]== '1' ; 225if (on ) std::fprintf (stderr ,"strata: STRATA_HIP_ADAPT_KERNEL_COPY=1: adaptive swaps copy with a kernel, not SDMA (#884)\n" ); 226return on ; 227 }(); 228if (kernel && bytes %16 == 0 && ((uintptr_t )src & 15 )== 0 && ((uintptr_t )dst & 15 )== 0 ) { 229void * dsrc = nullptr ; 230if (cudaHostGetDevicePointer (& dsrc ,const_cast < void *> (src ),0 )== cudaSuccess && dsrc != nullptr ) { 231 strata::kernels::copy_from_mapped ((float * )dst , (const float * )dsrc , (int64_t ) (bytes /4 ), (void * )st ); 232return cudaGetLastError (); 233 } 234 (void )cudaGetLastError ();// not registered / not mapped: the ordinary copy 235 } 236#endif 237/* 238DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While 239the origin API might be synchronous, it depends on the type of operand 240memory, so you may need to call wait() on event return by memcpy API to 241ensure synchronization behavior. 242*/ 243return DPCT_CHECK_ERROR (st -> memcpy (dst ,src ,bytes )); 244} 245catch (sycl::exception const & exc ) { 246 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 247 <<", line:" <<__LINE__ << std::endl ; 248 std::exit (1 ); 249} 250int pin_blobs (std::vector < std::pair < uintptr_t ,uintptr_t >> r , std::vector < void *>& live ) { 251int failed = 0 ;// ranges left pageable (a copy from them still works, through the driver's staging) 252#if (defined(STRATA_USE_HIP )|| defined(STRATA_HIP_GFX906 ))&& !defined(_WIN32 ) 253if (!pin_blobs_on ()|| r .empty ())return 0 ; 254for (auto & [a ,e ] :r ) {a &= ~(uintptr_t )4095 ;e = (e + 4095 )& ~(uintptr_t )4095 ; } 255 std::sort (r .begin (),r .end ()); 256size_t k = 0 ; 257for (size_t i = 1 ;i < r .size ();++ i ) { 258if (r [i ].first <=r [k ].second )r [k ].second = std::max (r [k ].second ,r [i ].second ); 259else r [++ k ]= r [i ]; 260 } 261r .resize (k + 1 ); 262for (const auto & [a ,e ] :r ) { 263if (cudaHostRegister ((void * )a , (size_t ) (e - a ),cudaHostRegisterReadOnly |cudaHostRegisterPortable )== 264cudaSuccess ) 265live .push_back ((void * )a ); 266else { 267 (void )cudaGetLastError (); 268++ failed ; 269 } 270 } 271#else 272 (void )r ; (void )live ; 273#endif 274return failed ; 275} 276void unpin_blobs (std::vector < void *>& v ) { 277/* 278DPCT1027: The call to cudaHostUnregister was replaced with 0 because 279SYCL currently does not support registering of existing host memory for use 280by device. Use USM to allocate memory for use by host and device. 281*/ 282for (void * p :v )(void )0 ; 283/* 284DPCT1010: SYCL uses exceptions to report errors and does not use the 285error codes. The cudaGetLastError function call was replaced with 0. You 286need to rewrite this code. 287*/ 288 (void )0 ; 289v .clear (); 290} 291 292// STRATA_RSS_TRACE=1: the process's mapped file pages (the arena) at a startup step - who reads the arena back 293void rss_probe (const char * where ) { 294static const bool on = std::getenv ("STRATA_RSS_TRACE" )!= nullptr ; 295if (!on )return ; 296FILE * f = std::fopen ("/proc/self/status" ,"r" ); 297if (!f )return ; 298char line [256 ]; 299long long kb = -1 ; 300while (std::fgets (line ,sizeof line ,f )) 301if (std::strncmp (line ,"RssFile:" ,8 )== 0 ) {kb = std::atoll (line + 8 );break ; } 302 std::fclose (f ); 303 std::fprintf (stderr ,"strata rss: %s: RssFile %.2f GiB\n" ,where , (double )kb / (1024.0 * 1024.0 )); 304 std::fflush (stderr ); 305} 306 307bool refill_blocking () { 308static const bool v = std::getenv ("STRATA_REFILL_BLOCKING" )!= nullptr ; 309return v ; 310} 311 312using Clock = std::chrono::steady_clock ; 313 314// --pipeline-windows: every STRATA_PIPELINE_* test and tuning variable (THETA, FORCE_MISS, SWITCH, LOG, TRACE, DOOM_SKIP, 315// LOOKUP_PON, PRESTAGE, AGREE, SNAP_OVERLAP) is read only with STRATA_PIPELINE_DEBUG=1; without it the defaults apply. 316// The one plain line a start ends with when the expert cache got no VRAM at all (set where "no VRAM is left for the expert cache" is found, printed where the 317// verifier then refuses to start): what did not fit and what to lower. 318static std::string g_no_cache_hint ; 319static void print_start_refusal (const char * who ,const std::string & err ) { 320if (!g_no_cache_hint .empty ()&& err .rfind ("verify: needs the profile-filled" ,0 )== 0 ) 321 std::fprintf (stderr ,"%s: cannot start: %s\n" ,who ,g_no_cache_hint .c_str ()); 322else 323 std::fprintf (stderr ,"%s: %s\n" ,who ,err .c_str ()); 324} 325 326static const char * pipe_dbg_env (const char * name ) { 327static const bool on = [] {const char * v = std::getenv ("STRATA_PIPELINE_DEBUG" );return v != nullptr && v [0 ]!= 0 && v [0 ]!= '0' ; }(); 328return on ? std::getenv (name ) :nullptr ; 329} 330 331// The resident RAM mode and the adaptive tier. A swap copies `in` (held in RAM) into the slot of `out` (held only 332// by that slot). Before the slot is overwritten, `out`'s bytes are copied back from it into an exchange buffer, so 333// the CPU computes `out` from RAM while the swap is in flight; when the swap has landed, `commit_exchanges` moves 334// them into `in`'s place in RAM. The RAM copy then again holds exactly the experts no core slot does, and no swap 335// reads the file. Swaps that need no exchange (`out` in the lend region is held in RAM already; or `in` is not) go 336// on as before; ones beyond the buffers' room wait for a later round. Runs on the adaptive tier's thread while the 337// GPU commits and drafts: the copies back are on its stream, and waited for before the refills are queued. 338// 339// With a layer split, `host_res` holds slot numbers of WHICHEVER cache owns the layer, so the copy back must read the 340// owning card's cache on that card's stream: `locate(layer)` names them (cache, stream, device; -1 = CUDA0). Reading 341// a later stage's slot number out of CUDA0's cache copied another expert's bytes into RAM - the resident mode with a 342// split then computed some experts from the wrong weights after the first adaptive swaps (garbage output). 343struct SwapHome { 344 strata::core::ExpertCache * cache ; 345 dpct::queue_ptr stream ; 346int dev ; 347}; 348template < class Swap ,class Locate > 349bool resident_stage_swaps (strata::core::FileExpertSource & src , 350const std::vector < int32_t > & host_res , 351int64_t n_expert , std::vector < Swap > & swaps , 352Locate locate )try { 353if (!src .complement_ready ()|| swaps .empty ())return true; 354struct Staged {int32_t layer ,in ,out ;int64_t q ; }; 355 std::vector < Staged > staged ; 356 std::vector < SwapHome > used ; 357 std::vector < Swap > kept ; 358kept .reserve (swaps .size ()); 359for (const Swap & s :swaps ) { 360if (!src .has_resident (s .layer ,s .in )|| src .has_resident (s .layer ,s .out )) {kept .push_back (s );continue ; } 361const int64_t q = (int64_t )staged .size (); 362if (q >=src .exchange_capacity ())continue ; 363const int32_t slot = host_res [(size_t )s .layer * (size_t )n_expert + (size_t )s .out ]; 364if (slot < 0 )continue ; 365const SwapHome home = locate (s .layer ); 366const strata::core::OnDevice on (home .dev ); 367// the evicted expert's bytes go back into exchange buffer q BEFORE its slot is overwritten 368// (CUDA: cudaMemcpyAsync D2H on the owning card's stream; the dpct migration had dropped the call) 369try { 370home .stream -> memcpy (src .exchange_buffer (q ),home .cache -> device_slot (slot ), 371 (size_t ) strata::kernels::cpu::expert_layout ().blob_bytes (s .layer )); 372 }catch (sycl::exception const & e ) { 373 std::fprintf (stderr ,"strata: copy back of layer %d slot %d (device %d) failed: %s\n" , (int )s .layer , 374 (int )slot ,home .dev ,e .what ()); 375return false; 376 } 377bool seen = false; 378for (const SwapHome & u :used )seen = seen || u .stream == home .stream ; 379if (!seen )used .push_back (home ); 380staged .push_back ({s .layer ,s .in ,s .out ,q }); 381kept .push_back (s ); 382 } 383if (!staged .empty ()) { 384for (const SwapHome & u :used ) { 385const strata::core::OnDevice on (u .dev ); 386try { 387u .stream -> wait (); 388 }catch (sycl::exception const & e ) { 389 std::fprintf (stderr ,"strata: copy back sync (device %d) failed: %s\n" ,u .dev ,e .what ()); 390return false; 391 } 392 } 393// STRATA_CHECK_SWAPS=1 (a test aid): each evicted expert's exchange buffer must hold the model file's bytes 394if (const char * chk = std::getenv ("STRATA_CHECK_SWAPS" );chk != nullptr && chk [0 ]!= '\0' && chk [0 ]!= '0' ) { 395static std::atomic < int64_t > n_ok {0 },n_bad {0 }; 396 std::vector < uint8_t > ref ; 397int64_t bad = 0 ; 398for (const Staged & x :staged ) { 399ref .resize ((size_t ) strata::kernels::cpu::expert_layout ().blob_bytes (x .layer )); 400if (!src .copy_blob_from_file (x .layer ,x .out ,ref .data ())|| 401 std::memcmp (ref .data (),src .exchange_buffer (x .q ),ref .size ())!= 0 ) { 402++ bad ; 403 std::fprintf (stderr ,"strata: STRATA_CHECK_SWAPS: layer %d expert %d: the exchange buffer differs from the file\n" , 404 (int )x .layer , (int )x .out ); 405 }else { 406++ n_ok ; 407 } 408 } 409n_bad += bad ; 410 std::fprintf (stderr ,"strata: STRATA_CHECK_SWAPS: %zu staged, %lld differ (total %lld ok, %lld differ)\n" , 411staged .size (), (long long )bad , (long long )n_ok .load (), (long long )n_bad .load ()); 412 } 413for (const Staged & x :staged ) 414if (!src .stage_exchange (x .layer ,x .in ,x .out ,x .q )) { 415 std::fprintf (stderr ,"strata: stage_exchange refused layer %d in %d out %d\n" , (int )x .layer , 416 (int )x .in , (int )x .out ); 417return false; 418 } 419 } 420swaps .swap (kept ); 421return true; 422} 423catch (sycl::exception const & exc ) { 424 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 425 <<", line:" <<__LINE__ << std::endl ; 426 std::exit (1 ); 427} 428 429struct Options { 430 std::string pack = "pack/full" ; 431 std::vector < int64_t > tokens ;// the prompt, PRE-TOKENIZED 432int64_t max_new = 16 ; 433int64_t max_context = 4096 ; 434bool greedy = true; 435uint64_t seed = 0 ; 436int top_k = 20 ; 437float top_p = 0.95f ; 438float temperature = 1.0f ; 439 std::string dump_logits ;// one line of logits per generated position 440int64_t logits_stride = 1 ;// storage selection; all prompt tokens remain conditioned 441/// **THE RESIDUAL, SO THE HEAD CAN BE CHECKED WITHOUT THE LAYERS.** 442/// 443/// C1 fails (LEDGER L116) and the pipeline is `embed -> 48 layers -> head`. Dumping `R` splits it in half: 444/// the head is one norm, two bf16 projections and one 794 MB GEMV, all of which can be recomputed in Python 445/// from the manifest. If Python agrees with the engine on the same `R`, the head is right and the layers 446/// are wrong; if it disagrees, the head is wrong. Nothing else in the engine can be split that cheaply. 447 std::string ple_gguf ;// the ORIGINAL second GGUF shard: the PLE table is not in the pack 448bool no_ple = false;// explicit diagnostic ablation; never a normal inference default 449bool stream_token = false;// R2.6 experiment: ordered work on the session stream 450bool check_logits = false;// optional full-vocabulary finite scan 451bool gr_fp32_activations = false;// pinned CUDA single-token BF16 activation contract 452bool gr_native_mmvf = false;// pinned projection reduction tree as well as FP32 inputs 453bool native_bf16 = false;// SSM gates, router and indexer projections only 454bool native_bf16_extra = false;// PLE value and shared expert scalar gate 455bool native_ple_key = false;// unchanged Q2_0 key and CUDA Q8_1 activations 456bool native_moe_combine = false;// pinned fused CUDA weighted reduction 457bool native_gdn = false;// pinned CUDA recurrence and preprocessing 458bool native_flash_attn_short = false;// diagnostic pinned attention, context <=256 459bool native_qsa_indexer = false;// pinned F16 key cache and F32 pooling 460bool native_qsa = false;// pinned F32 QSA norms and gate 461/// THE CONTEXT EXTENSION (rope scaling, rope_scaling.hpp). These knobs resolve to ONE process config, 462/// set once before `session_init` builds the rope table and the graphs capture the kernels. There is 463/// deliberately no per-request form: K sits in the cache POST-RoPE, so one cache must never mix two 464/// scalings. Precedence: an EXPLICIT flag over the model file's rope keys over the struct defaults - 465/// `none` and `1` are explicit values (the opt-outs), the absent flag is not. 466 std::string rope_scaling ;///< --rope-scaling none|linear|yarn (llama.cpp's names); empty = the flag is absent 467double rope_scale = 0 ;///< --rope-scale F: the extension factor; 0 = the flag is absent (the model file's, else 1 = off) 468double rope_freq_base = 0 ;///< --rope-freq-base N: 0 = the model's (1e7) 469double rope_freq_scale = 0 ;///< --rope-freq-scale F: the raw ggml knob; 0 = 1/--rope-scale 470double yarn_orig_ctx = 0 ;///< --yarn-orig-ctx N: 0 = the model's, else 262144 471double yarn_ext_factor = -1.0 ;///< --yarn-ext-factor F: <0 = auto (1 for yarn, 0 otherwise) 472double yarn_attn_factor = 1.0 ;///< --yarn-attn-factor F 473double yarn_beta_fast = 32.0 ;///< --yarn-beta-fast F 474double yarn_beta_slow = 1.0 ;///< --yarn-beta-slow F 475bool native_rope = false;// pinned text-only CUDA rotary arithmetic 476bool native_ple_postops = false;// pinned PLE postprojection arithmetic 477bool native_router = false;// pinned fused 512-expert top-10 router 478bool cpu_oracle_q8_0 = false;// pinned x86 activation scales/codes at both expert stages 479 std::string native_head_gguf ;// native output.weight experiment; same model shard as the pack 480 std::vector < std::string > native_dense_gguf ;// repeat for native GDN/QSA projection shards 481/// Every shard of --native's model (strata::gguf_split_paths: the metadata shard first; a missing shard is an 482/// error) and of --native-head-gguf's (the same list unless that names another model). 483 std::vector < std::string > native_shards ,native_head_shards ; 484/// Plan v0.3 P1: the whole native arithmetic set as ONE switch (model shard 1). It enables exactly the 485/// combination recorded in bench/results/2026-09-23-attention-ple plus the native indexer, and never the 486/// <=256-token attention adapter. It becomes the default once P0 shows it is not slower. 487 std::string native_preset ; 488/// The token embedding from this GGUF instead of --native's (tools/embd_bf16_pack.py: BF16 as shipped) 489 std::string embd_gguf ; 490/// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM. 491 std::string ple_io = "direct" ; 492bool ple_io_explicit = false;///< --ple-io was given: the engine only warns when direct measures slow 493int64_t ple_row_cache = 1 <<20 ;///< bounded row cache (rows of 90 B); 0 disables 494int ple_inflight = 256 ;// the prompt path reads a chunk's rows at once: 64 left the SSD half idle (32K: 303 -> 189 ms) 495double ple_delay_us = 0 ;///< fault injection: every row read completes no earlier than this 496bool ple_sync_submit = false;///< A/B arm: submit reads on the token thread, no I/O worker 497 std::string kv = "fp16" ;///< plan v0.3 P7: KV storage, fp16 (default) or int8 (half the VRAM) 498int64_t kv_resident = 0 ;///< KV streaming: resident cells per QSA layer (0: all in VRAM) 499bool kv_grow = false;///< the elastic K/V (--kv-grow, STRATA_KV_GROW=1; kvg_ensure) 500 std::string dump_residual ; 501/// The head input, `bb.mixed`. It exists so the head can be SPLIT: steps 1-4 (the per-stream norm, the two 502/// bf16 projections and the stream mean) recompute cheaply in Python, and only the 794 MB GEMV does not. 503 std::string dump_mixed ; 504/// One residual snapshot per layer per position: `n_layers * hc * n_embd` floats per position, appended in 505/// position order. This is the C1 BISECTION LADDER - it is what `llama-debug --tensor-filter l_last` prints 506/// for the reference, so the first layer whose `sum` diverges is the layer that holds the bug. It needs the 507/// captured path (the expert pool only exists there), so it is refused with `--no-capture`. 508 std::string dump_layers ; 509/// `2 * n_embd + 2 * hc` floats per layer per position: the attention half's block output, the MoE half's, 510/// and the two injection vectors. It separates `linear_attn_out-<l>` from `ffn_out-<l>`, which the residual 511/// ladder cannot. **CAPTURED INTO THE LAYER GRAPHS**, so it must be armed before `session_capture`. 512 std::string dump_halves ; 513/// P0.S8's routing trace, and a prerequisite the Phase 3 plan names explicitly. One record per layer per 514/// position: `int32 layer, int32 k, k int32 ids, k float weights`. It is what a hit-rate curve for a 515/// candidate VRAM expert cache is computed from, and it needs no new kernels - the doorbell already 516/// publishes exactly this much to pinned memory. 517 std::string dump_routing ; 518bool no_capture = false;// run the layers directly instead of replaying graphs 519bool no_pool = false;// skip the CPU expert pool: the GPU-only floor 520bool sync_every_layer = false; 521/// Per-stage CUDA-event timings inside the layer halves. `--no-capture` only: an event recorded inside a 522/// stream capture is silently dropped, so the captured path cannot carry this. 523bool stage_timing = false; 524/// Launch the 48 captured `pre` graphs back to back with no host work between them and report the pure GPU 525/// time per token. This is the only measurement that separates host-bound from GPU-bound, because the 526/// stage events include every gap where the GPU waited for the host. 527bool graph_only = false; 528bool gpu_only_full = false;///< R0.3: pre + post + head, the true per-token GPU floor 529int pool_workers = 0 ;///< R2.2: 0 = "all physical cores minus the host's"; >0 overrides 530/// #272: the pool's core layout; `all` (the default) is the layout it always had, auto / p-cores are opt-in 531 strata::kernels::cpu::PoolAffinity pool_affinity = strata::kernels::cpu::PoolAffinity ::All ; 532/// --host-core first|last (STRATA_HOST_CORE): the host thread's core (see HostCore in pool.hpp) 533 std::string host_core ; 534/// --pool-cores LIST (STRATA_POOL_CORES; experimental, off by default): the logical processors the pool workers are pinned to 535 std::string pool_cores ; 536/// R2.2's first half, as an A/B arm. **ON by default**, because the measurement that justifies it is the 537/// pool's own drain: 33.7 GB/s against 5/6 x 44.14 = 36.8 for five workers, on a machine whose sixth core 538/// is reserved for a host thread that has nothing to do while the drain runs. 539bool no_host_worker = false; 540bool coupled_draft = strata::core::coupled_draft_env ();///< Coupled draft sampling for MTP drafter under sampling 541bool mmap_experts = false;///< R2.1: opt OUT of the resident arena, back to MapViewOfFile 542 std::string shared_expert_arena ;///< Linux: optional file backing for the resident arena shared by processes 543bool resident_cpu_experts = false;///< mmap-backed static-cache misses copied into ordinary RAM 544bool stream_experts = false;///< SYCL port: no host arena; blobs read from the GGUF on demand (all experts in VRAM) 545/// `--resident-experts` (the low-RAM PC's resident mode, chosen by setup): `--resident-cpu-experts` with the copy 546/// page-locked when the driver allows (else locked in the working set), 4 GiB of RAM headroom, and plain mmap 547/// (with a warning) when even the experts no slot holds do not fit. 548bool resident_pin = false; 549uint64_t resident_headroom = 8ull <<30 ; 550bool resident_soft = false; 551bool resident_cpu_explicit = false;///< #384: --resident-cpu-experts given by itself (not only implied) 552/// CS-T `--resident-budget-gib N`: the resident mode with a RAM budget - the N GiB of experts the GPU cache does 553/// not hold that the expert profile ranks hottest are copied into RAM, the rest are read from the files in place 554/// (the GGUF shards when the pack has no experts.bin). 0 = the whole complement (--resident-experts). 555uint64_t resident_budget = 0 ; 556/// R4: slots of VRAM-resident experts. **0 = off, and off is the default.** 557/// **THE COMMENT THAT USED TO BE HERE WAS FALSE AND ROUND 328 MEASURED IT.** It said "the cache has no 558/// consumer yet - `moe_hit_grouped_s2` does not exist - so switching it on costs the fill traffic and 559/// saves nothing". The kernel exists (`src/kernels/cuda/s2_expert_grouped.cu`), it is wired at line ~660 560/// via `expert_hit_run`, and switching the cache on **does** move work off the CPU pool: the drain fell 561/// **19.076 -> 10.312 ms/token** at 4096 per-layer slots, for **-2.7 ms/token** end to end. What was 562/// true is that the ADMISSION POLICY gave every slot to the first position, which is why the earlier 563/// measurement found nothing - see `expert_cache_per_layer`. 564int expert_cache = 0 ; 565 std::array < int ,3 > expert_cache_remote {};///< CUDA1..3 slots; CUDA0 keeps dense/state/MTP 566 std::array < bool ,3 > expert_cache_remote_auto {}; 567bool remote_expert_opt = false;///< optional optimization of the existing remote-expert decode path 568 std::string expert_cache_remote_placement = "stripe" ;///< stripe experts or assign complete layers to CUDA1..3 569bool expert_cache_cpu_order = false; 570/// **R4.2g. ROUND 328 MEASURED THAT THE GLOBAL ADMISSION POLICY CANNOT WORK, AND THIS IS THE FIX.** 571/// The default policy hands out slots in arrival order from one counter shared by all 48 layers, so the 572/// first `n_slots` distinct pairs - about 26 LAYERS OF POSITION 0 - take every slot and hits are confined 573/// to them. Measured at 256 slots: **1781 of 60000 = 2.97%**, against **21.4%** for 8 slots per layer and 574/// **70.4%** for 64, from `Memory/cache_allocation.py` on the same run's routing. Off by default. 575bool expert_cache_per_layer = false; 576/// Multi-GPU: a second expert tier on CUDA device `peer_device` (-1 = off), `peer_reserve_mib` left free 577/// there, `peer_slots` caps its size (0 = as many as fit), `peer_adapt_swaps` per adaptive round 578/// (-1 = adapt_swaps). 579int peer_device = -1 ; 580int peer_reserve_mib = 600 ; 581int64_t peer_slots = 0 ; 582int peer_adapt_swaps = -1 ; 583/// the prompt path's rows per layer the peer computes: -1 = half of chunk x top-k, 0 = the prompt path stays on 584/// the primary 585int64_t peer_prefill_rows = -1 ; 586/// The PLE gather's prefetch, as an A/B arm. The gather measured 2.10-2.61 ms/token because its sixteen 587/// row reads are sixteen SEPARATE page faults into a 26.8 GB mapping; see `ple_prefetch_enable`. 588bool no_ple_prefetch = false; 589/// R4.2e: a `profile.bin` from `tools/make_profile.py`. **When given, it decides residency instead of the 590/// compulsory-miss policy**, which is the whole point: a profile ranked by routing frequency over a whole 591/// trace is what the plan's `h = 0.6447` refers to, and compulsory-miss measured 0.4864 because it fills 592/// with whatever the prompt touched FIRST. Empty means no profile. 593 std::string expert_profile ; 594/// #477 (--serve, opt-in): where to save what the adaptive tier learned, as a profile `--expert-profile` reads 595/// (the resident experts first, then the routing counted since the start); on QUIT and every 596/// `expert_profile_save_min` minutes between requests. Empty (the default): nothing is counted or written. 597 std::string expert_profile_save ; 598double expert_profile_save_min = 10.0 ; 599/// R4.2d: **ON by default**, because the measurement is unambiguous and the alternative is known-broken. 600/// Without it, 17 of 10,562 layers had the hit work done when the pool returned; with it, 9,190. The 601/// A/B arm is `--no-hit-poke`. 602bool no_hit_poke = false; 603/// R0.9: capture each layer as THREE graphs and time them from outside the capture, which is the only 604/// valid way to get a per-stage table on the real graph. Prints and exits; it is a measurement, not a run. 605bool gpu_stages = false; 606bool stats = false; 607bool shared_late = false;///< plan v0.3 P3 A/B: shared expert inside post[l] (old order) 608bool keep_canonical = false;///< plan v0.3 P1 A/B: load canonical copies of natively served tensors 609bool no_token_graph = false;///< plan v0.3 P3 A/B: two graphs per layer instead of one per token 610bool no_fused_gr = false;///< plan v0.3 P3 A/B: the six-kernel native gr_read + separate gr_write 611bool no_fast_attn = false;///< plan v0.3 P3 A/B: gather + one-block-per-head QSA attention 612bool no_publish_kernel = false;///< plan v0.3 P3 A/B: memcpy nodes for the doorbell and QSA step 613bool no_fused_gdn = false;///< plan v0.3 P3 A/B: llama.cpp-layout GDN step + separate out norm 614bool no_fast_select = false;///< plan v0.3 P7 A/B: FP64 row scores + bit-serial cell top-k 615/// Plan v0.3 P4: `--expert-cache auto` sizes the VRAM tier from what is free after the weights, the session 616/// and the KV state, minus this reserve for the graphs, the hit scratch and the head. 617int vram_reserve_mib = 700 ; 618bool vram_reserve_given = false;///< --vram-reserve-mib on the command line (#496: no smaller automatic reserve) 619/// #533 (opt-in): the expert cache in physical segments (CUDA virtual memory management), so the serve loop's 620/// `VRAM <reserve_mib>` command can give part of it back to other programs and take it again. Off: one cudaMalloc. 621bool vram_elastic = false; 622int64_t vram_segment_mib = 512 ; 623/// `--vram-reserve-later-mib N`: the reserve on a layer split's later cards (default: the same as the first). 624/// A card that drives no display needs less than the one the monitors are on. 625int vram_reserve_later_mib = -1 ; 626/// Plan v0.3 P5: batched prompt processing in chunks of this many tokens (0 = the token path). 627int64_t prefill_chunk = 0 ; 628/// `--prefill N` (a number, not auto): the person's chunk, which the cache sizing leaves alone. 629bool prefill_given = false; 630/// `--prefill auto`: the largest chunk (up to 8192) whose buffers the expert cache can lend. Every expert a chunk 631/// routes to is streamed once per chunk, so a bigger chunk streams fewer bytes per token (the "ubatch" effect). 632bool prefill_auto = false; 633/// #282, opt-in: the largest chunk `--prefill auto` may take - 8192 by default; `--prefill auto:16384` or 634/// `auto:32768` (or STRATA_PREFILL_AUTO_MAX) lets it go further, never past the context 635int64_t prefill_auto_max = 8192 ; 636bool no_split_rows = false;///< plan v0.3 P4 A/B: one whole expert per pool thread 637/// Plan v0.3 P5: the prompt path borrows the top expert-cache slots for its buffers and refills them after 638/// the prompt (default); `--no-prefill-borrow` reserves the buffers' VRAM for the whole session instead. 639bool no_prefill_borrow = false; 640/// Plan v0.3 P5 validation: batch only positions [0, P) and run the rest of the prompt through the token path 641/// (teacher-forced), so the logits of positions >= P - which depend on the batched state - can be scored 642/// against the oracle at many positions. 0 = the whole prompt but the last position. 643int64_t prefill_until = 0 ; 644/// Plan v0.3 P6: after every processed position, append the residual after the last layer (hc x n_embd 645/// floats, the MTP draft head's input) to this file. Token path only. 646 std::string dump_final_r ; 647/// Plan v0.3 P6: speculative decoding with a verify window of this many tokens (the last accepted token and 648/// spec-1 drafts); 0 = plain decode. `spec_oracle` drafts from a token file (the expected continuation, for 649/// the exactness test); `spec_corrupt` N > 0 replaces every Nth draft with a wrong token. 650int spec = 0 ; 651/// --serve runs up to this many sequences at once, one token each per batch window (0 = off). A request 652/// sent as `BGEN <slot> <max_new> ...` reads its prompt and its first token through the usual path, then 653/// continues in slot <slot> of the batch windows (`BT <slot> <id>` lines, then `BDONE <slot> ...`). 654int batch = 0 ; 655/// With an explicit --layer-split, every GPU loads only its own layers' dense weights instead of the whole 656/// model's: the VRAM they took goes back to the expert cache (opt-in) 657bool trim_stage_weights = false; 658/// The --batch slots in this many groups pipelined through the stages of a layer split (stage k 659/// runs one group while stage k+1 runs another). 1 = every slot in one window, stage after stage. 660/// 0: not given (two Arc B-series cards with 8 or more slots pipeline 2 groups, anything else 1), -1: `auto` (the most 661/// groups, at most one per stage, that divide the slots - the engine's other builds' rule), else the number asked for. 662int batch_groups = 0 ; 663bool batch_mtp = false;///< --batch-mtp / STRATA_BATCH_MTP=1 (opt-in): one MTP proposal per batch slot 664 std::string spec_oracle ; 665int spec_corrupt = 0 ; 666/// Benchmarks and A/B checks (eddoursul's fork, F19): the run emits this continuation (token ids) instead of 667/// the window's argmax, and a draft is accepted when it matches it, so runs with different speculation 668/// settings process the same text. 669 std::string spec_follow ; 670/// Per verify window: a line with its size, a hash of its final residual rows and its argmaxes. 671 std::string window_hashes ; 672/// Plan v0.3 P6: the MTP draft layer's runtime directory (tools/mtp_rt.py); drafts come from it. 673 std::string mtp ; 674int64_t mtp_window = 32768 ;///< the draft layer attends to the last N cells (0 = every cell) 675/// Plan v0.3 P6: the share (0..1) of each layer's distinct missed experts the GPU reads over PCIe from the 676/// pinned arena while the CPU computes the rest (verify windows). 677double pcie_frac = -1.0 ;///< < 0: the model's default (0.2 direct for the Q2_0 pack, 0.55 DMA for native packs) 678bool pcie_frac_auto = false;///< STRATA_PCIE_FRAC_DEFAULT=auto, single card, no --pcie-frac: the share is refined in the first decode windows (PcieAuto) 679double pcie_probe_gbps = 0.0 ;///< the start-up probe's reading (for PcieAuto) 680 std::string pcie_mode = "auto" ;///< auto | dma | kernel | direct 681/// Plan v0.3 P6: every `adapt_every` rounds, swap up to `adapt_swaps` of the most-routed missing experts into 682/// the VRAM tier in place of the least-routed resident ones (decayed counts). 0 = static residency. 683int adapt_every = 4 ; 684float adapt_decay = 0.7f ;///< the usage counts are multiplied by this after each adaptation (--adapt-decay) 685/// --adapt-async 1 (--serve with the resident RAM mode; opt-in): the adaptive tier's rounds advance between verify 686/// windows on a helper thread instead of one window waiting for a whole round (see the tier in the --serve block). 687/// Not bit-exact run to run. 0 = the blocking tier. 688int adapt_async = 0 ; 689/// Plan v0.3 P6: a draft enters the verify window only while every draft before it (and itself) has at least 690/// this probability under the draft layer; 0 = always --spec-1 drafts. 691double spec_min_p = 0.0 ; 692/// Stop when the model emits an end-of-turn token (<|endoftext|> 248044, <|im_end|> 248046, or --eos-ids). 693bool stop_eos = false; 694 std::vector < int64_t > eos_ids = {248044 ,248046 }; 695bool spec_split = false;///< opt-in split verify window (the overlap study: exact, ~7% slower) 696/// --serve, multi-GPU layer split: "K" or "K1,K2,.." (the first layer of each later stage) or "auto" (placed 697/// from each GPU's free VRAM); empty = one GPU 698 std::string layer_split ; 699/// the later stages' devices "D1,D2,.." (default: the next visible GPUs; "0" with one K: both stages on this 700/// GPU, sharing everything - the bit-exact A/B of the hand-off) 701 std::string split_device ; 702/// --split-skip-if-fits (opt-in; the server passes it for a config's "split_skip_if_fits"): with 703/// --layer-split auto, run on CUDA0 alone when it holds every profiled expert pair plus the whole session (KV), 704/// the drafter and the reserve - a split then only adds hand-offs (two RDNA4 cards: 1,384 vs 1,794 tok/s at 4K) 705bool split_skip_if_fits = false; 706/// Plan v0.3 P8: stay resident and take requests on stdin (see the --serve block in main). 707bool serve = false; 708/// The vision path: keep a per-cell (t, h, w) rotary position table so --serve can take GENI requests. 709bool vision = false; 710int adapt_swaps = 96 ; 711/// --serve: how many conversation checkpoints to keep between requests (0 = every request reads its whole 712/// prompt again, the v0.1.2 behaviour). One is the GDN recurrence of the 36 layers, the QSA indexer tails and 713/// the PLE history (~118 MB of host RAM); the KV cache itself is positional and stays where it is. 714int prompt_cache = 6 ; 715int64_t conversation_cache_mib = 0 ;// opt-in host RAM for independent conversations 716int conversation_cache_slots = 4 ; 717int64_t conversation_cache_min_free_mib = 2560 ; 718/// --serve SAVE: disk space a session file must leave free where it is written (MiB; 0 = no check) 719int64_t session_min_free_mib = 4096 ; 720/// --serve: also keep a checkpoint every N freshly read prompt tokens (0 = only at the last turn boundary) 721int64_t prompt_cache_every = 16384 ; 722bool prompt_cache_tail = false;// optional extra checkpoint at an existing near-tail chunk boundary 723/// --serve: a prompt read from token 0 is also checkpointed at its first turn boundary - the end of the system 724/// prompt, which every chat of the same client shares - when that is at least N tokens (0 = never) 725int64_t prompt_cache_root = 2048 ; 726/// --serve: the token that opens a chat turn (<|im_start|>). The last one in a prompt is where the chat's 727/// history ends and the new assistant turn begins, which is the checkpoint the next request can reuse. 728int64_t turn_token = 248045 ; 729/// --serve (#458, opt-in): the role token of a short turn the server puts right before the new assistant turn 730/// (the "system" of a trailing reasoning-effort turn). When the turn before the last <|im_start|> opens with it, 731/// the checkpoint goes in front of that turn instead, so it holds the conversation and not the effort text. 732/// -1 = off (the checkpoint at the last <|im_start|>, as before). 733int64_t tail_role_token = -1 ; 734/// --serve: a text part of the prompt of at most N tokens (a chat message, the assistant header, a short tool 735/// result) goes through the verify windows, S tokens at a time, instead of the batched prompt path (0 = always 736/// the batched path) 737int64_t short_read = 64 ; 738/// --pipeline-windows N (--serve, a layer split on exactly two GPUs): 1 = a prompt's short reads through 739/// the verify windows run with the stages overlapped (stage 0 reads window K+1 while stage 1 reads window K); 740/// 2 = the decode windows too: stage 0 runs window K+1 speculatively while stage 1 verifies window K (rolled back 741/// when K is not accepted as guessed). 0 = off (the stages take turns). -1 (not given) = automatic: 2 when both 742/// GPUs of the two-stage split are Battlemage (Xe2) cards and the MTP drafter runs (spec >= 2), else 0. 743int pipeline_windows = -1 ; 744/// The suffix drafter (prompt lookup): when the text being written repeats an earlier stretch of the context (code 745/// edits, quoted input, tool-call JSON) by at least this many tokens, the window may be filled with what followed 746/// it there instead of the MTP's drafts, where the MTP's own first guess agrees and the draft policy expects it to 747/// pay (strata/spec/draft_policy.hpp). On by default; 0 = MTP only. 748int suffix_draft = 3 ; 749/// The MTP's own window cap (0 = --spec): with --spec 6 --mtp-max-t 4 the long windows come from suffix matches. 750int mtp_max_t = 0 ; 751/// --lookup-chain K (opt-in, 0 = off): prompt lookup CHAINED after the MTP's proposal. The suffix drafter matches 752/// the context followed by the MTP's drafts and appends up to K of the tokens that followed that match to the same 753/// verify window (the window grows to at most 8). Greedy verification keeps the output; its own counts are kept. 754int lookup_chain = 0 ; 755int lookup_chain_min = 3 ;///< --lookup-chain-min M: the shortest match (in tokens, drafts included) it extends on 756/// --mtp-hnorm stream (opt-in): the draft layer's pre_fc_norm_hidden normalizes each hyper-connection stream on 757/// its own (llama.cpp's qwen4exp MTP graph) instead of one RMS over all four (the default, tools/mtp_probe.py). 758bool mtp_hnorm_stream = false; 759/// --mtp-q4 (opt-in): the draft layer's projections and draft head from 4-bit copies (fewer bytes per draft step) 760 std::string mtp_q4 ;///< "" (off), all, proj (the projections only) or head (the draft head only) 761/// --mtp-draft-vocab FILE (opt-in): the draft head's token subset from FILE instead of <mtp>/draft_vocab.bin 762 std::string mtp_draft_vocab ; 763/// --draft dflash2 --draft-model PACK (Qwen3.8-Flash-Next, the Q4_0 pack of tools/dflash2_pack.py --q4_0): the DFlash2 block drafter drafts; no MTP layer is 764/// loaded with it (--draft-fallback none, the only mode of this build; --mtp DIR still names DIR/draft_vocab.bin). --draft-conf P ends the window where the 765/// product of the selector's probabilities falls below P; --draft-cap N caps the window. 766 std::string draft ,draft_model ,draft_fallback = "none" ; 767double draft_conf = 0.6 ;///< Arc default 0.6 (A750 serve sweeps: 0.35 was the clear loser, 0.6 ties MTP); --draft-conf P changes it, 0 = the window of --spec-min-p 768int draft_cap = 0 ; 769/// A control vector on the residual stream (strata/kernels/cvec.hpp), with llama.cpp's flags: the 770/// `experimental-speed-projection` profile passes `--control-vector-scaled FILE:1.0 --control-vector-layer-range 771/// 4 44 --cvec-mode project --cvec-dir per-layer`. None by default; --serve switches a loaded one per request. 772 std::vector < std::pair < std::string ,float >> cvec_files ; 773int cvec_first = -1 ,cvec_last = -1 ;///< llama.cpp's defaults: 1 .. the last layer 774int cvec_mode = 1 ;///< 0 = project, 1 = add (llama.cpp's default) 775int cvec_single = -1 ;///< --cvec-dir single:L (project mode): layer L's direction everywhere 776}; 777 778void usage () { 779 std::fprintf (stderr , 780"strata generate --pack DIR --tokens \"1,2,3\" [options]\n" 781"\n" 782" --pack DIR the pack directory (default pack/full)\n" 783" --tokens LIST the prompt as comma-separated token IDS (required)\n" 784" --tokens-file PATH pretokenized prompt, commas or whitespace (alternative to --tokens)\n" 785" --ple-gguf PATH required PLE table (original second GGUF shard); with --native, the model's\n" 786" shard that holds per_layer_token_embd.weight when not given\n" 787" --no-ple explicit diagnostic ablation of the PLE layer\n" 788" --ple-io direct|mmap|ram n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n" 789" reads, the table never enters RAM or the file cache; mmap: A/B arm;\n" 790" ram: mmap with the whole table locked in RAM at start (Linux/macOS)\n" 791" --ple-row-cache N bounded cache of fetched rows, 90 B each (default 1048576; 0 = off)\n" 792" --ple-inflight N outstanding SSD reads (default 256)\n" 793" --ple-delay-us U fault injection: each row read completes no earlier than U us\n" 794" --ple-sync-submit A/B arm: submit table reads on the token thread (default: an I/O thread)\n" 795" --kv fp16|int8 KV storage (plan v0.3 P7): int8 codes + fp16 scale per 64 values, half the\n" 796" VRAM; default fp16 until gate G-C accepts int8\n" 797" --kv q4_0 4-bit K/V after a Hadamard rotation (PR #21): half of int8's memory,\n" 798" slightly lower precision (see bench/results/2026-09-27-kv-q4)\n" 799" --kv k8v4 hybrid: INT8 K (exact attention scores) + rotated Q4_0 V, 816 B/cell\n" 800" (vs int8's 1,056); streams with --kv-resident too\n" 801" --kv-resident N KV streaming: keep N cells of each QSA layer in VRAM (min 20480) and the\n" 802" whole K/V in pinned RAM; the freed VRAM goes to expert slots. 0 (default):\n" 803" all of it in VRAM. A context of N cells or fewer is not streamed\n" 804" --kv-grow the K/V takes VRAM only for the cells the requests reach and the expert\n" 805" cache holds the rest, giving slots back as the context grows (one GPU, with\n" 806" --expert-profile; STRATA_KV_GROW=1/0 also). Default: the whole --max-context\n" 807" allocated at start\n" 808" --stream-token enqueue token work on the session stream (experimental)\n" 809" --check-logits copy and check all logits in the stream-token path\n" 810" --gr-fp32-activations experimental CUDA-oracle GR activation precision\n" 811" --gr-native-mmvf experimental pinned GR norm/projections; implies FP32 activations\n" 812" --native-bf16 experimental CUDA-oracle SSM/router/indexer BF16 projections\n" 813" --native-bf16-extra experimental CUDA-oracle PLE/shared gate BF16 projections\n" 814" --native-ple-key experimental native PLE key; requires --native-dense-gguf\n" 815" --native-moe-combine experimental pinned CUDA routed/shared combination\n" 816" --native-gdn experimental pinned CUDA GDN norms/gates/recurrence\n" 817" --native-flash-attn-short diagnostic pinned vector attention; --max-context <=256\n" 818" --native-qsa-indexer experimental pinned indexer key cache and pooling\n" 819" --native-qsa experimental pinned QSA normalization and output gate\n" 820" --native-rope experimental pinned text-only CUDA rotary arithmetic\n" 821" --native-ple-postops experimental pinned PLE postprojection arithmetic\n" 822" --native-router experimental pinned CUDA 512-expert top-10 routing\n" 823" --cpu-oracle-q8-0 experimental pinned CPU expert quantization and dot reduction\n" 824" --native SHARD1 every full-context native path at once (plan v0.3 P1): stream-token,\n" 825" GR MMVF, BF16, head, dense + PLE key, MoE combine, GDN, router, QSA,\n" 826" indexer, RoPE, PLE postops, and the CPU q8_0 contract unless the\n" 827" expert cache is on. Individual --native-* flags stay for A/B.\n" 828" --native-head-gguf PATH native Q5_K head from model shard 1; requires --stream-token\n" 829" --embd-gguf PATH the token embedding from this GGUF instead of --native's (tools/embd_bf16_pack.py:\n" 830" BF16 as the checkpoint ships it; mapped host memory, no VRAM)\n" 831" --native-dense-gguf PATH native GDN/QSA/shared projections; repeat for each source model shard\n" 832" --expert-cache-cpu-order experimental GPU expert reduction matching CPU order\n" 833" --max-new N tokens to generate (default 16)\n" 834" --max-context N KV/state capacity (default 4096)\n" 835" --rope-scaling T extend the context past the trained one: none, linear\n" 836" (position interpolation) or yarn - llama.cpp's types and names.\n" 837" Default: the model file's rope keys, else none. Fixed at startup:\n" 838" K in the cache is post-RoPE, so one run one scaling\n" 839" --rope-scale F the extension factor for linear/yarn (default: the model file's\n" 840" factor, else 1 = off)\n" 841" --rope-freq-base N the raw ggml knobs: the frequency base (0 = the model's 1e7) and\n" 842" --rope-freq-scale F the angle shrink (0 = 1/--rope-scale)\n" 843" --yarn-orig-ctx N the trained context the correction targets (0 = 262144)\n" 844" --yarn-ext-factor F --yarn-attn-factor F --yarn-beta-fast F --yarn-beta-slow F\n" 845" YaRN's knobs; defaults: -1 (auto: 1 for yarn), 1, 32, 1\n" 846" --greedy argmax (the default)\n" 847" --seed S enable sampling with this Philox seed\n" 848" --top-k N --top-p F --temperature F\n" 849" --dump-logits PATH write one line of raw logits per position\n" 850" --logits-stride N store every Nth row plus final input (default 1); N>1 requires --max-new 1\n" 851" --dump-residual PATH write the final R (hc x n_embd, f32) for head bisection\n" 852" --dump-layers PATH write R after EVERY layer, per position: the C1 bisection ladder\n" 853" --dump-halves PATH write both halves' block_out and inject per layer: the half bisection\n" 854" --dump-routing PATH write the routed expert ids and weights per layer per position (P0.S8)\n" 855" --no-capture run the layers directly instead of replaying graphs\n" 856" --shared-late A/B: shared expert after the CPU pool (default: overlapped with it)\n" 857" --keep-canonical A/B: also load canonical copies of natively served tensors (more VRAM)\n" 858" --vision --serve takes images too (GENI requests; embeddings from strata-vision)\n" 859" --prompt-cache N --serve: keep N conversation checkpoints between requests (default 6, ~118 MB\n" 860" of RAM each; 0 = read every prompt from the start)\n" 861" --conversation-cache-mib N --serve: RAM budget for parked conversations (default 0 = off)\n" 862" --conversation-cache-slots N --serve: at most N parked conversations (default 4)\n" 863" --conversation-cache-min-free-mib N --serve: physical RAM floor when parking or restoring a\n" 864" session file (default 2560)\n" 865" --session-min-free-mib N --serve: disk space a SAVE must leave free (default 4096; 0 = no check)\n" 866" --vram-elastic --serve (#533, opt-in, NVIDIA): the expert cache in segments (--vram-segment-mib,\n" 867" default 512), so the command `VRAM <reserve_mib>` (the server's POST /v1/vram) can\n" 868" give VRAM back to other programs between requests and take it back later\n" 869" --batch N / --slots N --serve (opt-in): up to N requests decode together in batch slots (2..8\n" 870" normally; --batch-mtp waves more through eight-row windows),\n" 871" each slot with its own session (VRAM like the main one); docs/BATCHING.md\n" 872" --batch-mtp --batch (opt-in, one GPU, needs --mtp and --spec): each slot also verifies one MTP\n" 873" proposal per window (STRATA_BATCH_MTP=1 does the same); needs VRAM per slot\n" 874" --batch-groups G --batch with a layer split: the slots in G groups pipelined through the GPUs\n" 875" --pipeline-windows N --serve with a layer split on two GPUs (default 2 on two Arc B-series cards with\n" 876" the MTP drafter, else 0): one conversation's verify windows\n" 877" with the GPUs overlapped - 1 = the prompt's short reads, 2 = decode as well\n" 878" (stage 0 runs the next window while stage 1 verifies this one); docs/MULTI_GPU.md\n" 879" --trim-stage-weights an explicit --layer-split: each GPU loads only its own layers' dense weights\n" 880" --prompt-cache-every N --serve: also checkpoint every N fresh prompt tokens (default 16384, 0 = off)\n" 881" --prompt-cache-tail --serve, single GPU: one extra checkpoint near the prompt's end, at an existing\n" 882" chunk boundary (default off; requires --prompt-cache and --prompt-cache-every > 0)\n" 883" --turn-token ID --serve: the token that opens a chat turn (default 248045, <|im_start|>)\n" 884" --tail-role-token ID --serve: a turn of this role right before the last turn is left out of\n" 885" the conversation checkpoint (a trailing effort turn; default -1 = off)\n" 886" --short-read N --serve: read at most N fresh text tokens through the decode windows instead\n" 887" of the batched prompt path (default 64, 0 = off)\n" 888" --suffix-draft N prompt lookup: draft from an earlier repeat of the last N+ tokens of context\n" 889" when it pays (default 3; 0 = MTP only)\n" 890" --mtp-max-t M cap the MTP's windows at M tokens (0 = --spec; longer ones come from suffixes)\n" 891" --lookup-chain K opt-in: after the MTP's drafts, add up to K prompt-lookup drafts that continue\n" 892" them (the window grows to at most 8; default 0 = off)\n" 893" --lookup-chain-min M the shortest context match --lookup-chain extends on (default 3)\n" 894" --mtp-hnorm pooled|stream the draft layer's hidden-input norm: one RMS over all four streams\n" 895" (default) or one per stream (llama.cpp's MTP graph)\n" 896" --mtp-q4 all|proj|head opt-in: the draft layer's projections and/or draft head as 4-bit copies\n" 897" --mtp-draft-vocab FILE opt-in: the draft head's token subset (default <mtp>/draft_vocab.bin)\n" 898" --draft mtp|dflash2 the draft source (default mtp); dflash2 needs --draft-model PACK (tools/dflash2_pack.py --q4_0), --spec 2 or more and\n" 899" --mtp DIR (for DIR/draft_vocab.bin); no MTP layer is loaded (--draft-fallback none, the only mode here)\n" 900" --draft-conf P with --draft dflash2: end the window where the product of the selector's probabilities falls below P (default 0.6 on this build)\n" 901" --draft-cap N with --draft dflash2: the widest window\n" 902" --control-vector-scaled FILE:SCALE[,...] a control vector GGUF on the residual stream (llama.cpp's\n" 903" format; --control-vector FILE = scale 1). --serve: requests switch it (cvec=0|1)\n" 904" --control-vector-layer-range A B the layers it follows (inclusive; default 1 .. the last)\n" 905" --cvec-mode add|project h += s v (default) or h -= s (h.v) v with v unit\n" 906" --cvec-dir per-layer|single:L each layer's own direction (default) or layer L's everywhere (project)\n" 907" --no-token-graph A/B: two graphs per layer (the host launches each) instead of one per token\n" 908" --no-fused-gr A/B: the six-kernel hyper-connection read and a separate write (native)\n" 909" --prefill CHUNK batched prompt processing in chunks of CHUNK tokens (needs --native); auto =\n" 910" the largest chunk up to 8192 whose buffers the expert cache can lend;\n" 911" auto:16384 / auto:32768 (or STRATA_PREFILL_AUTO_MAX) allow bigger ones\n" 912" --no-pool skip the CPU expert pool (the GPU-only floor)\n" 913" --sync-every-layer debug: synchronise after every layer\n" 914" --ple-gguf PATH the n-gram/PLE shard. WITHOUT IT LAYER 1's PLE IS SILENTLY SKIPPED,\n" 915" which changes every number downstream - pass it for any real run\n" 916" --dump-mixed PATH write the post-attention residual (n_embd, f32)\n" 917" --stage-timing per-stage KERNEL-COUNT shares. NOT a time profile: an uncaptured\n" 918" event interval includes host gaps, so run with --gpu-only-full first\n" 919" --graph-only MEASURE: replay the 48 `pre` graphs only. OMITS the 48 `post` graphs\n" 920" and the LM head, so it is NOT the GPU floor (R0.3, Memory/ERRORS.md A4)\n" 921" --gpu-only-full MEASURE: replay pre+post for all 48 layers plus the LM head, no pool.\n" 922" THE TRUE PER-TOKEN GPU FLOOR. Quote this one, not --graph-only.\n" 923" --stats print the per-stage breakdown\n" 924" --spec-follow PATH benchmarks: emit this continuation (token ids) instead of the argmax and\n" 925" accept the drafts that match it, so speculation settings compare on the\n" 926" same text (with --spec; not --serve)\n" 927" --window-hashes PATH per verify window, a line with its index, position, size, a 64-bit hash of\n" 928" its final residual rows and its argmaxes: two builds that do the same\n" 929" arithmetic write the same file (use with --spec-follow, --adapt-every 0)\n" 930" --gpu-stages R0.9: capture the layer as three graphs (mixer / ffn+router / post)\n" 931" and time them from OUTSIDE the capture. The per-stage table on the\n" 932" real graph that --stage-timing cannot give. Prints and exits.\n" 933" --expert-profile P R4.2e: pre-load the VRAM tier from a `profile.bin` (see\n" 934" tools/make_profile.py) instead of admitting on first use.\n" 935" --expert-profile-save P --serve, #477: save what the adaptive tier learned (the experts in\n" 936" VRAM, then the routing counted since the start) as a profile at P, on\n" 937" QUIT and every --expert-profile-save-every MIN minutes (default 10;\n" 938" 0 = on QUIT only) between requests; start from it with --expert-profile P\n" 939" --no-hit-poke R4.2d's A/B arm. The hit path pokes the driver once right after its\n" 940" launch so the GPU starts while the CPU pool runs; without it the work\n" 941" waits for the next driver entry and does not overlap at all.\n" 942" --no-ple-prefetch A/B arm: read the PLE table's sixteen rows one at a time, instead of\n" 943" issuing them in one PrefetchVirtualMemory call.\n" 944" --expert-cache N R4: keep N expert blobs resident in VRAM and compute their rows on the\n" 945" GPU via `moe_hit_grouped_s2`. DEFAULT 0. Measured at 4096 slots\n" 946" with --expert-cache-per-layer: 54.4%% hits, CPU pool drain 19.1 -> 10.3\n" 947" ms/token, -2.7 ms/token end to end.\n" 948" --expert-cache-device1 N|auto fill CUDA1 with N experts or as many as fit\n" 949" --expert-cache-device2 N|auto fill CUDA2 with more experts\n" 950" --expert-cache-device3 N|auto fill CUDA3 with more experts\n" 951" --remote-expert-opt enable remote-expert decode optimizations (serve mode)\n" 952" --expert-cache-remote-placement stripe|layer distribute expert ranks or whole\n" 953" layers across CUDA1..3 (default: stripe)\n" 954" --peer-device N a second GPU as an adaptive expert-cache tier (rows over P2P; it also\n" 955" computes its experts' prompt rows). Not with --layer-split or\n" 956" --expert-cache-device1..3. Default output unchanged without it.\n" 957" --peer-reserve-mib N VRAM the peer tier leaves free on its card (default 600)\n" 958" --peer-slots N expert slots on the peer (default: what fits)\n" 959" --peer-adapt-swaps N peer cache swaps per adaptation step (default: --adapt-swaps)\n" 960" --peer-prefill-rows N prompt rows per layer the peer computes (default half of chunk x top-k;\n" 961" 0 = the prompt path stays on the primary)\n" 962" --expert-cache-per-layer R4.2g: give each layer its OWN slots instead of letting the first\n" 963" position take all of them. The default policy fills in arrival order\n" 964" from one shared counter, so 256 slots went to ~26 layers of position 0\n" 965" and measured **2.97%%**. Per-layer, the same routing gives 21.4%% at 8\n" 966" slots/layer and 70.4%% at 64. On a native pack, N is still the budget of N\n" 967" largest blobs; each layer's slots are that layer's own blob.\n" 968" --no-host-worker R2.2: the A/B arm. By default the HOST THREAD joins the drain, so the\n" 969" pool is six threads on six cores instead of five plus an idle core;\n" 970" this flag restores the five-worker form for comparison on `pool phases`.\n" 971" --pool-workers N R2.2: CPU expert pool worker count. Default 0 = every physical core\n" 972" except the one the host loop spins on (with --pool-affinity auto or\n" 973" p-cores on a hybrid CPU: P-cores minus 1). A sweep is how the pool's\n" 974" deviation from `cpu_s2` is attributed.\n" 975" --host-core WHERE The host thread's core: first (the default: the first physical core, as always) or\n" 976" last (the last physical core, the workers on the others). Windows sends a GPU's\n" 977" interrupts to one logical processor, usually the first, and every copy that lands\n" 978" raises one: a spinning host there waits for them. Moves threads only, never a\n" 979" result. Not on hybrid CPUs (STRATA_HOST_CORE sets it too).\n" 980" --pool-cores LIST Experimental, off by default: pin the CPU workers to exactly these logical\n" 981" processors (0,2,4,6 or 2-14:2). Two entries on one core, or the host's own, are\n" 982" kept with a warning. STRATA_POOL_CORES sets it too.\n" 983" --pool-affinity MODE Worker CPU affinity: all (default: one worker per physical core, as\n" 984" always), auto (hybrid CPUs: P-cores first, then their SMT siblings,\n" 985" then E-cores) or p-cores (P-cores and their siblings only).\n" 986" --coupled-draft enable coupled draft sampling for MTP drafter under sampling (STRATA_SPEC_COUPLED)\n" 987" --no-coupled-draft disable coupled draft sampling (propose argmax drafts)\n" 988" --mmap-experts R2.1: opt OUT of the resident expert arena, back to MapViewOfFile.\n" 989" --stream-experts no host arena: experts read from the GGUF on demand (needs a native pack and\n" 990" a VRAM cache that holds every expert; for machines with less RAM than experts)\n" 991" The A/B arm: the mmap's rate depends on the OS page cache holding\n" 992" 34 GB, and measured 71.97 vs 34.78 ms/token cold vs warm.\n" 993" --shared-expert-arena FILE Linux: back the resident arena with one MAP_SHARED file.\n" 994" Put this file on /dev/shm, not ordinary SSD storage.\n" 995" A small header binds an existing backing file to the same pack.\n" 996" --resident-cpu-experts with mmap and a static profile, keep the experts the GPU cache does not\n" 997" hold resident in ordinary RAM (and the prompt path's lend region as far as\n" 998" RAM allows); adaptive swaps exchange them, so none is read from the file again.\n" 999" --resident-experts the low-RAM PC's resident mode (setup): --mmap-experts --resident-cpu-experts\n" 1000" with the copy page-locked when possible, 4 GiB headroom, plain mmap if it\n" 1001" does not fit. Same answers as --mmap-experts for the same placement.\n" 1002" --adapt-async 1 --serve with the resident RAM mode (opt-in): the adaptive tier's swaps\n" 1003" advance between verify windows instead of a window waiting for a whole\n" 1004" round. Not bit-exact run to run. 0 (default) = the blocking tier.\n" ); 1005} 1006 1007// --lookup-chain: the context's last tokens for the draft sources (at most 64), the MTP's pending drafts last 1008int chain_tail (const strata::spec::SuffixDrafter & sfx ,const int32_t * pending ,int n_pending , std::vector < int32_t >& tail ) { 1009const std::vector < int32_t >& h = sfx .history (); 1010const int keep = std::max (0 , std::min ((int )h .size (),64 - n_pending )); 1011tail .assign (h .end ()- keep ,h .end ()); 1012tail .insert (tail .end (),pending ,pending + n_pending ); 1013return (int )tail .size (); 1014} 1015 1016// --lookup-chain: the registered extra draft sources (strata/spec/draft_source.hpp) see the committed context too 1017void extra_sources_reset () { 1018for (auto & src : strata::spec::extra_draft_sources ())src -> reset (); 1019} 1020void extra_sources_append (const int32_t * t ,size_t n ) { 1021for (auto & src : strata::spec::extra_draft_sources ())src -> append (t ,n ); 1022} 1023 1024bool parse_i64_list (const char * s , std::vector < int64_t >& out , std::string & err ) { 1025out .clear (); 1026 std::string text (s ); 1027for (char & c :text )if (c == ',' )c = ' ' ; 1028 std::istringstream input (text ); 1029 std::string token ; 1030while (input >>token ) { 1031int32_t id = 0 ; 1032const auto parsed = std::from_chars (token .data (),token .data ()+ token .size (),id ); 1033if (parsed .ec != std::errc {}|| parsed .ptr != token .data ()+ token .size ()|| id < 0 ) { 1034err = "invalid token id: expected an integer in [0, 2147483647]" ; 1035out .clear (); 1036return false; 1037 } 1038out .push_back (id ); 1039 } 1040if (out .empty ()) {err = "token list was empty" ;return false; } 1041return true; 1042} 1043 1044/// The pool's adapter plus the wall-clock it spent, so the report can say how much of the token was the CPU. 1045struct Drive { 1046 strata::core::ExpertDispatch d ; 1047double cpu_ms = 0 ; 1048int64_t calls = 0 ; 1049/// THE ROUTING TRACE, which is P0.S8 and a stated prerequisite of Phase 3. `drive_pool` is called once 1050/// per layer from the main loop - the workers live inside `expert_pool_dispatch` - so a single FILE* here 1051/// needs no locking. `d.layers` is the CURRENT layer on entry (the adapter increments it as it walks the 1052/// blob), which is why the layer index comes from there rather than from a counter of our own. 1053 std::FILE * routing = nullptr ; 1054}; 1055 1056void drive_pool (void * user ,const float * x_f ,const int32_t * ids ,const float * weights ,int64_t n_embd ,int64_t k , 1057float * out ) { 1058Drive * t = (Drive * )user ; 1059const Clock ::time_point a = Clock ::now (); 1060 strata::core::expert_pool_dispatch (& t -> d ,x_f ,ids ,weights ,n_embd ,k ,out ); 1061t -> cpu_ms += std::chrono::duration < double , std::milli > (Clock ::now ()- a ).count (); 1062++ t -> calls ; 1063// THE ROUTING TRACE. Written AFTER the dispatch so the layer index is still this layer's: `d.layers` is 1064// advanced by the adapter as it consumes the blob, and reading it after the call is the same value the 1065// dispatch used. Record = int32 layer, int32 k, k int32 ids, k float weights. 1066if (t -> routing != nullptr ) { 1067// **`d.layers` HAS ALREADY BEEN ADVANCED BY THE TIME THIS RUNS, AND THE FIRST TRACE WAS OFF BY ONE 1068// BECAUSE OF IT.** The adapter walks the blob by incrementing `d.layers` as it consumes each layer's 1069// experts, so after the dispatch it holds the NEXT layer's index. `tools/make_profile.py` caught it 1070// with a bounds check when the trace turned out to span 1..48 instead of 0..47. The hit-rate CURVE was 1071// unaffected - it is a per-layer split, and shifting every layer by one preserves both metrics - but 1072// anything keyed on the layer index, which is exactly what a cache profile is, would have been wrong. 1073const int32_t layer_idx = (int32_t ) (t -> d .layers - 1 ); 1074if (layer_idx < 0 || layer_idx >= strata::core::kCompiledGeometry .n_layers ) { 1075 std::fprintf (stderr ,"strata generate: the routing trace saw layer %d, outside 0..47\n" ,layer_idx ); 1076return ; 1077 } 1078const int32_t rec [2 ]= {layer_idx , (int32_t )k }; 1079 std::fwrite (rec ,sizeof rec ,1 ,t -> routing ); 1080 std::fwrite (ids ,sizeof (int32_t ), (size_t )k ,t -> routing ); 1081 std::fwrite (weights ,sizeof (float ), (size_t )k ,t -> routing ); 1082 } 1083} 1084 1085/// Plan v0.3 P6: the pool for a verify window. 1086void drive_pool_multi (void * user ,const float * x_f ,const int32_t * ids ,int64_t n_tok ,int64_t k ,float * out , 1087int64_t layer ) { 1088Drive * t = (Drive * )user ; 1089t -> d .layers = layer ; 1090const Clock ::time_point a = Clock ::now (); 1091 strata::core::expert_pool_dispatch_multi (t -> d ,x_f ,ids ,n_tok ,k ,out ); 1092t -> cpu_ms += std::chrono::duration < double , std::milli > (Clock ::now ()- a ).count (); 1093++ t -> calls ; 1094// the routing trace for the serve path: the same record format drive_pool writes (layer, k, ids, weights), 1095// one record per token. The multi dispatch fuses the router weights into the kernel and does not surface 1096// them, so records carry unit weights: tools/make_profile.py ranks pairs by routed frequency, which is the 1097// signal that matters; a one-shot --dump-routing run records true weights if a weighted ranking is wanted. 1098if (t -> routing != nullptr && layer >=0 && layer < strata::core::kCompiledGeometry .n_layers ) { 1099for (int64_t tok = 0 ;tok < n_tok ;++ tok ) { 1100const int32_t rec [2 ]= {(int32_t )layer , (int32_t )k }; 1101 std::fwrite (rec ,sizeof rec ,1 ,t -> routing ); 1102 std::fwrite (ids + tok * k ,sizeof (int32_t ), (size_t )k ,t -> routing ); 1103static const float one [64 ]= {};// k <= 64 in a verify window; zeros read as unit weights 1104 std::fwrite (one ,sizeof (float ), (size_t )k ,t -> routing ); 1105 } 1106 } 1107} 1108 1109/// Layer split: every verify stage shares one Drive (its counters, usage and failure flags); the GPU plan, the expert 1110/// cache and the PCIe share the pool uses for a layer are those of the stage that runs it. 1111struct SplitDrive { 1112static constexpr int kMax = 8 ; 1113Drive * base = nullptr ; 1114int n = 0 ;///< stages 1115int64_t end [kMax ]= {};///< stage i runs the layers from end[i - 1] (0) below end[i] 1116 strata::core::GpuPlanSink * plan [kMax ]= {}; 1117const uint8_t * cache_base [kMax ]= {}; 1118const uint64_t * cache_slot_off [kMax ]= {}; 1119int pcie_num [kMax ]= {}; 1120}; 1121void drive_pool_split (void * user ,const float * x_f ,const int32_t * ids ,int64_t n_tok ,int64_t k ,float * out , 1122int64_t layer ) { 1123SplitDrive * s = (SplitDrive * )user ; 1124int st = 0 ; 1125while (st + 1 < s -> n && layer >=s -> end [st ])++ st ; 1126Drive & d = * s -> base ; 1127d .d .plan = s -> plan [st ]; 1128d .d .cache_base = s -> cache_base [st ]; 1129d .d .cache_slot_off = s -> cache_slot_off [st ]; 1130d .d .pcie_num = s -> pcie_num [st ]; 1131drive_pool_multi (s -> base ,x_f ,ids ,n_tok ,k ,out ,layer ); 1132} 1133 1134/// Layer split across GPUs: a later stage on its own device, with its own copy of the dense weights, a session, an 1135/// expert cache for its layers, a verify window and a prompt path; the last one also holds the head (the drafter 1136/// lives on its device too). 1137struct GpuStage { 1138int dev = 0 ; 1139int64_t lb = 0 ,le = 0 ; 1140double pcie_frac = 0.0 ; 1141 strata::core::WeightTable wt ; 1142 strata::core::NativeDense dense ; 1143 strata::core::NativeHead head ; 1144 strata::core::SessionState ss ; 1145 dpct::queue_ptr stream = & dpct::get_in_order_queue (); 1146 strata::core::ExpertCache cache ; 1147 std::vector < std::pair < int32_t ,int32_t >> profile ;///< its layers' share of the profile, hottest first 1148int32_t * d_res = nullptr ;///< the residency table on its device 1149 strata::core::Verifier ver ; 1150 strata::core::Verifier ver_b ;///< --pipeline-windows: the odd windows' verifier 1151 strata::prefill::Prefill sp ; 1152 dpct::queue_ptr adapt_stream = & dpct::get_in_order_queue (); 1153 dpct::event_ptr adapt_ev = nullptr ; 1154bool adapt_live = false;///< swaps of this request are in flight on it 1155int32_t * mrope = nullptr ;///< --vision: the image-position table on its device 1156}; 1157 1158// ---- issue #31: what the watchdog prints before it stops a stalled engine 1159struct MemSample { 1160unsigned long long faults = 0 ,rss_mib = 0 ,avail_mib = 0 ,commit_mib = 0 ;// faults: hard (Linux) / all (Windows) 1161}; 1162MemSample mem_sample () { 1163MemSample m ; 1164#if defined(_WIN32 ) 1165PROCESS_MEMORY_COUNTERS pmc {}; 1166if (K32GetProcessMemoryInfo (GetCurrentProcess (),& pmc ,sizeof pmc )) { 1167m .faults = pmc .PageFaultCount ; 1168m .rss_mib = pmc .WorkingSetSize >>20 ; 1169m .commit_mib = pmc .PagefileUsage >>20 ; 1170 } 1171MEMORYSTATUSEX ms {}; 1172ms .dwLength = sizeof ms ; 1173if (GlobalMemoryStatusEx (& ms ))m .avail_mib = ms .ullAvailPhys >>20 ; 1174#else 1175if (std::FILE * f = std::fopen ("/proc/self/stat" ,"r" )) { 1176char buf [4096 ]; 1177const size_t n = std::fread (buf ,1 ,sizeof buf - 1 ,f ); 1178buf [n ]= 0 ; 1179 std::fclose (f ); 1180const char * s = std::strrchr (buf ,')' );// fields after the command name: 3 state ... 12 majflt 1181for (int field = 2 ;s && field < 12 ;++ field )s = std::strchr (s + 1 ,' ' ); 1182if (s )m .faults = std::strtoull (s + 1 ,nullptr ,10 ); 1183 } 1184auto kb = [](const char * path ,const char * key )-> unsigned long long { 1185unsigned long long v = 0 ; 1186if (std::FILE * f = std::fopen (path ,"r" )) { 1187char line [256 ]; 1188const size_t kl = std::strlen (key ); 1189while (std::fgets (line ,sizeof line ,f )) 1190if (std::strncmp (line ,key ,kl )== 0 ) {v = std::strtoull (line + kl ,nullptr ,10 );break ; } 1191 std::fclose (f ); 1192 } 1193return v ; 1194 }; 1195m .rss_mib = kb ("/proc/self/status" ,"VmRSS:" ) >>10 ; 1196m .commit_mib = kb ("/proc/self/status" ,"VmSwap:" ) >>10 ; 1197m .avail_mib = kb ("/proc/meminfo" ,"MemAvailable:" ) >>10 ; 1198#endif 1199return m ; 1200} 1201 1202// the stage the watchdog names: "<where> <detail>", and the prompt chunk a batched read is in (#251) 1203std::string stage_text () { 1204const strata::core::Progress & p = strata::core::progress (); 1205 std::string s = std::string (p .where .load ())+ " " + std::to_string ((long long )p .detail .load ()); 1206if (const int64_t c = p .chunk .load ();c >=0 )s += " of the prompt chunk from token " + std::to_string ((long long )c ); 1207return s ; 1208} 1209 1210#if !defined(_WIN32 ) 1211// #605: whether `path` is on a rotational disk (1), not (0) or unknown (-1), from sysfs; `dev` is the disk's name 1212int on_rotational_disk (const std::string & path , std::string & dev ) { 1213struct stat st {}; 1214if (::stat (path .c_str (),& st )!= 0 )return -1 ; 1215char sys [64 ]; 1216 std::snprintf (sys ,sizeof sys ,"/sys/dev/block/%u:%u" , (unsigned )major (st .st_dev ), (unsigned )minor (st .st_dev )); 1217 std::error_code ec ; 1218 std::filesystem::path p = std::filesystem::canonical (sys ,ec ); 1219for (int up = 0 ; !ec && up < 2 ;++ up ,p = p .parent_path ()) {// a partition has its disk's queue 1220 std::ifstream q (p /"queue" /"rotational" ); 1221int r = -1 ; 1222if (q >>r ) { 1223dev = p .filename ().string (); 1224return r ; 1225 } 1226 } 1227return -1 ; 1228} 1229 1230// #605: the engine's threads in uninterruptible sleep (state D - almost always waiting for the disk), and where 1231// (wchan): 16 threads in blk_io_schedule is a disk that cannot keep up, not a deadlock in the engine 1232void disk_wait_threads (std::FILE * f ) { 1233 std::map < std::string ,int > where ; 1234int waiting = 0 ,threads = 0 ; 1235 std::error_code ec ; 1236for (const auto & e : std::filesystem::directory_iterator ("/proc/self/task" ,ec )) { 1237++ threads ; 1238 std::ifstream st (e .path () /"stat" ); 1239 std::string line ; 1240 std::getline (st ,line ); 1241const size_t rp = line .rfind (')' ); 1242if (rp == std::string::npos || rp + 2 >=line .size ()|| line [rp + 2 ]!= 'D' )continue ; 1243++ waiting ; 1244 std::ifstream w (e .path () /"wchan" ); 1245 std::string wc ; 1246 std::getline (w ,wc ); 1247++ where [wc .empty ()|| wc == "0" ?"?" :wc ]; 1248 } 1249if (threads == 0 )return ; 1250 std::string list ; 1251for (const auto & [name ,n ] :where )list += (list .empty () ?" (" :", " )+ name + " x" + std::to_string (n ); 1252if (!list .empty ())list += ")" ; 1253 std::fprintf (f ," threads waiting on the disk (state D): %d of %d%s%s\n" ,waiting ,threads ,list .c_str (), 1254waiting > 0 ?" - the engine is waiting for the drive: a rotational or failing disk with --ple-io " 1255"direct (#605: --ple-io ram), or a drive too slow for the reads asked of it" :"" ); 1256} 1257#endif 1258 1259// --pipeline-windows: what the watchdog prints about the pipelined decode loop (set while it runs) 1260struct PlDiag { 1261 strata::core::Verifier * v [2 ][2 ]= {}; 1262 std::atomic < int > a_seq {0 },a_bits {0 },b_bits {0 },d_bits {0 },chain_kind {0 },doomed {0 },ending {0 },chain_live {0 }; 1263 std::atomic < long long > iters {0 }; 1264}; 1265PlDiag g_pl_diag ; 1266void pl_diag_print (std::FILE * f ) { 1267PlDiag & d = g_pl_diag ; 1268auto bits = [](int b ,char * o ) { 1269 std::snprintf (o ,16 ,"%c%c%c%c%c%c" ,b & 1 ?'R' :'-' ,b & 2 ?'L' :'-' ,b & 4 ?'F' :'-' ,b & 8 ?'C' :'-' , 1270b & 16 ?'S' :'-' ,b & 32 ?'V' :'-' ); 1271return (const char * )o ; 1272 }; 1273char ba [16 ],bb [16 ],bd [16 ]; 1274 std::fprintf (f ," pipelined loop: %lld iterations; A seq %d [%s] B [%s] D [%s] (Ready Launched Finished Committed " 1275"S1-launched S1-done); chain kind %d live %d; doomed %d ending %d\n" ,d .iters .load (),d .a_seq .load (), 1276bits (d .a_bits .load (),ba ),bits (d .b_bits .load (),bb ),bits (d .d_bits .load (),bd ),d .chain_kind .load (), 1277d .chain_live .load (),d .doomed .load (),d .ending .load ()); 1278const char * names [2 ][2 ]= {{"stage 0 even" ,"stage 0 odd" }, {"stage 1 even" ,"stage 1 odd" }}; 1279for (int st = 0 ;st < 2 ;++ st ) 1280for (int par = 0 ;par < 2 ;++ par ) 1281if (d .v [st ][par ]!= nullptr )d .v [st ][par ]-> diag_pipelined (f ,names [st ][par ]); 1282} 1283 1284void stall_report (std::FILE * f ,uint64_t layers_during ) { 1285 strata::core::Progress & p = strata::core::progress (); 1286 std::fprintf (f ,"strata serve: stall report (engine %s): stage \"%s\" for %lld s; %llu layers served since the " 1287"last finished step (0 = stopped, more = slow)\n" ,STRATA_VERSION ,stage_text ().c_str (), 1288 (long long ) ((strata::core::progress_now_ms ()- p .since_ms .load ()) /1000 ), 1289 (unsigned long long )layers_during ); 1290for (int pass = 0 ;pass < 2 ;++ pass ) { 1291if (pass == 1 ) { 1292 std::this_thread::sleep_for (std::chrono::seconds (2 )); 1293 std::fprintf (f ," 2 s later:\n" ); 1294 } 1295if (auto fn = strata::core::diag_pool_fn ().load ())fn (f ); 1296if (auto fn = strata::core::diag_verify_fn ().load ())fn (f ); 1297if (auto fn = strata::core::diag_pipeline_fn ().load ())fn (f ); 1298#if !defined(_WIN32 ) 1299disk_wait_threads (f ); 1300#endif 1301const MemSample m = mem_sample (); 1302 std::fprintf (f ," memory: %llu MiB resident, %llu MiB %s, %llu MiB RAM available; %llu %s\n" ,m .rss_mib , 1303m .commit_mib , 1304#if defined(_WIN32 ) 1305"committed" ,m .avail_mib ,m .faults ,"page faults so far" 1306#else 1307"in swap" ,m .avail_mib ,m .faults ,"major page faults so far" 1308#endif 1309 ); 1310 std::fflush (f ); 1311 } 1312#if defined(_WIN32 ) 1313// every thread's stack, to read against this build's PDB: a few MB beside the engine's working directory 1314if (HMODULE dbg = LoadLibraryA ("dbghelp.dll" )) { 1315using Fn = BOOL (WINAPI * )(HANDLE ,DWORD ,HANDLE ,int ,void * ,void * ,void * ); 1316if (auto write = (Fn )GetProcAddress (dbg ,"MiniDumpWriteDump" )) { 1317char path [64 ]; 1318 std::snprintf (path ,sizeof path ,"strata-stall-%lu.dmp" , (unsigned long )GetCurrentProcessId ()); 1319HANDLE h = CreateFileA (path ,GENERIC_WRITE ,0 ,nullptr ,CREATE_ALWAYS ,FILE_ATTRIBUTE_NORMAL ,nullptr ); 1320if (h != INVALID_HANDLE_VALUE ) { 1321const int kThreadInfo = 0x1000 ;// MiniDumpWithThreadInfo; MiniDumpNormal = 0 1322const BOOL ok = write (GetCurrentProcess (),GetCurrentProcessId (),h ,kThreadInfo ,nullptr ,nullptr ,nullptr ); 1323CloseHandle (h ); 1324char full [MAX_PATH ]; 1325if (!GetFullPathNameA (path ,MAX_PATH ,full ,nullptr )) std::snprintf (full ,sizeof full ,"%s" ,path ); 1326 std::fprintf (f ," %s the thread stacks to %s (attach it to the issue)\n" ,ok ?"wrote" :"could not write" , 1327full ); 1328 } 1329 } 1330 } 1331#endif 1332} 1333 1334/// STRATA_TRACE=1: the VRAM left at a step of the startup (finds what fills the card after the cache is sized) 1335void mem_mark (const char * where ) { 1336static const bool on = std::getenv ("STRATA_TRACE" )!= nullptr ; 1337if (!on )return ; 1338size_t free_b = 0 ,total_b = 0 ; 1339/* 1340DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions for 1341device information which may not be supported by all compilers or runtimes. 1342You may need to adjust the code. 1343*/ 1344 dpct::get_current_device ().get_memory_info (free_b ,total_b ); 1345 std::fprintf (stderr ,"strata trace: %lld MiB free after %s\n" , (long long ) (free_b >>20 ),where ); 1346} 1347 1348/// #463's A/B: STRATA_ADAPT_NOWAIT=1 lets a verify window start before the adaptive tier's copies have landed (0.1.37) 1349bool adapt_nowait () { 1350static const bool v = [] {const char * e = std::getenv ("STRATA_ADAPT_NOWAIT" );return e && e [0 ]== '1' ; }(); 1351return v ; 1352} 1353 1354/// #463 without the stall: a verify window takes the adaptive tier's previous swaps only once they are this many windows 1355/// old, and then waits for their copies (which have landed by then). The window that first computes a swapped-in expert on 1356/// the GPU depends only on the window count, as with #463's wait, so the answers are as reproducible. Default 1 = #463 and 1357/// 0.1.39 (the very next window waits for the copies: ~4.6 ms per window on an RTX 2060 SUPER over PCIe 3.0 x8); lag 2 is 1358/// opt-in (STRATA_ADAPT_LAG=2). The batch paths, --pipeline-windows and the peer tier are not lagged. (#764) 1359int adapt_lag () { 1360static const int v = [] {const char * e = std::getenv ("STRATA_ADAPT_LAG" );return e ? std::max (1 , std::atoi (e )) :1 ; }(); 1361return v ; 1362} 1363 1364/// --adapt-async: one background job at a time (the asynchronous adaptive tier's copies and memcpys). `post` hands 1365/// it over, `idle` says whether it has finished; the owner never posts while a job runs. 1366class JobThread { 1367public : 1368JobThread () :th_ ([this ] {loop (); }) {} 1369 ~JobThread () { 1370 { std::lock_guard < std::mutex > lk (mu_ );quit_ = true; } 1371cv_ .notify_one (); 1372th_ .join (); 1373 } 1374JobThread (const JobThread & )= delete ; 1375JobThread & operator= (const JobThread & )= delete ; 1376void post (std::function < void ()> f ) { 1377 { 1378 std::lock_guard < std::mutex > lk (mu_ ); 1379job_ = std::move (f ); 1380has_ = true; 1381done_ .store (false, std::memory_order_release ); 1382 } 1383cv_ .notify_one (); 1384 } 1385bool idle ()const {return done_ .load (std::memory_order_acquire ); } 1386void wait ()const {while (!idle ()) std::this_thread::yield (); } 1387private : 1388// The second logical processor of the last physical core that has two: an SMT sibling no pool worker or host loop 1389// is pinned to (the pool takes the first of every core but the first, the host the first core), or -1. 1390static int smt_spare_cpu () { 1391#if defined(_WIN32 ) 1392DWORD len = 0 ; 1393GetLogicalProcessorInformationEx (RelationProcessorCore ,nullptr ,& len ); 1394if (len == 0 )return -1 ; 1395 std::vector < char > buf (len ); 1396if (!GetLogicalProcessorInformationEx (RelationProcessorCore , (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX )buf .data (), 1397& len )) 1398return -1 ; 1399int best = -1 ,core = 0 ; 1400for (const char * p = buf .data ();p < buf .data ()+ len ; 1401p += ((const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX * )p )-> Size ,++ core ) { 1402const auto * e = (const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX * )p ; 1403const GROUP_AFFINITY & ga = e -> Processor .GroupMask [0 ]; 1404int seen = 0 ; 1405for (int bit = 0 ;bit < 64 ;++ bit ) 1406if ((ga .Mask & (1ull <<bit ))&& ++ seen == 2 && core > 0 )best = ga .Group * 64 + bit ; 1407 } 1408return best ; 1409#else 1410return -1 ; 1411#endif 1412 } 1413void loop () { 1414// the job's memcpys stay off the host's core and the pool's: by default the spare SMT sibling of the last 1415// two-thread core (Windows); STRATA_ADAPT_JOB_CPU=<logical cpu>, or -1 for no pinning 1416const char * c = std::getenv ("STRATA_ADAPT_JOB_CPU" ); 1417const int cpu = c != nullptr ? std::atoi (c ) :smt_spare_cpu (); 1418if (cpu >=0 ) (void ) strata::kernels::cpu::pin_current_thread (cpu ); 1419for (;;) { 1420 std::function < void ()> f ; 1421 { 1422 std::unique_lock < std::mutex > lk (mu_ ); 1423cv_ .wait (lk , [& ] {return has_ || quit_ ; }); 1424if (!has_ )return ; 1425f = std::move (job_ ); 1426has_ = false; 1427 } 1428f (); 1429done_ .store (true, std::memory_order_release ); 1430 } 1431 } 1432 std::mutex mu_ ; 1433 std::condition_variable cv_ ; 1434 std::function < void ()> job_ ; 1435bool has_ = false,quit_ = false; 1436 std::atomic < bool > done_ {true}; 1437 std::thread th_ ;// last: started once the members above exist 1438}; 1439 1440// ---- --serve's conversation cache. A chat or an agent sends the whole conversation again with every request, and 1441// reading it again is what made a long session wait minutes for every turn. What a sequence leaves behind splits in 1442// two, and only one half needs copying: 1443// * POSITIONAL state - the KV cache of the 12 QSA layers and their pooled indexer keys, the draft layer's KV. A 1444// cell is written once for its position and read only by later positions (the block scores take `dead` for the 1445// block being filled, never its pooled row), so rewinding to a position just means writing from there again. 1446// * RUNNING state - the 36 GDN recurrences and conv histories, each QSA layer's indexer tail (the unfinished 1447// block's raw keys) and the PLE's normalized history. Each describes "everything so far" and cannot be 1448// rewound, so a checkpoint is a copy of exactly these: ~118 MB, the same set the verifier snapshots to roll 1449// back rejected drafts. 1450// A checkpoint is only valid while the positional cells below it still hold ITS tokens, so the serve loop keeps 1451// just the checkpoints that are prefixes of the tokens the session holds now. 1452using ImgKey = strata::core::ConversationImageKey ; 1453using ConvCheckpoint = strata::core::ConversationCheckpoint ; 1454 1455uint64_t fnv1a (const void * data ,size_t n ,uint64_t h = 1469598103934665603ull ) { 1456const uint8_t * p = (const uint8_t * )data ; 1457for (size_t i = 0 ;i < n ;++ i ) {h ^=p [i ];h *=1099511628211ull ; } 1458return h ; 1459} 1460 1461using ConvStateSizes = strata::core::ConversationStateSizes ; 1462 1463ConvStateSizes conv_state_sizes (const strata::core::ModelGeometry & g ,const strata::core::SessionState & ss ) { 1464ConvStateSizes z ; 1465 std::string error ; 1466// a split stage's session owns only its layer range's state (see SessionState's carve note); the geometry 1467// and the carve have already passed engine validation 1468 strata::core::conversation_session_sizes (g ,ss ,z ,error ); 1469return z ; 1470} 1471 1472/// Copies the running state out (this session's carve only). The caller has synchronized the device. 1473bool checkpoint_save (ConvCheckpoint & c ,const strata::core::SessionState & ss ,const strata::core::ModelGeometry & g ) { 1474 std::string error ; 1475if (strata::core::conversation_checkpoint_save (c ,ss ,g ,error ))return true; 1476 std::fprintf (stderr ,"strata serve: checkpoint save: %s\n" ,error .c_str ());// the caller's ERR has no reason 1477return false; 1478} 1479 1480/// #3350: a conversation checkpoint is an optimization, like parking. After a failed save: true when the failure was 1481/// only the copy's memory (a host or driver allocation, which does not stick), so the caller goes on without that 1482/// checkpoint; false when the GPU itself is unwell (a sticky error comes back from the synchronize), which still ends 1483/// the request as before. 1484bool checkpoint_failure_is_survivable () { 1485// SYCL has no sticky error state to clear: the queues either drain or throw (a lost device) 1486try { 1487 dpct::get_current_device ().queues_wait_and_throw (); 1488return true; 1489 }catch (...) { 1490return false; 1491 } 1492} 1493 1494/// Puts a checkpoint's running state back; the positional cells below it are the caller's to guarantee. 1495bool checkpoint_restore (const ConvCheckpoint & c , strata::core::SessionState & ss ,const strata::core::ModelGeometry & g ) { 1496 std::string error ; 1497if (strata::core::conversation_checkpoint_restore (c ,ss ,g ,error ))return true; 1498 std::fprintf (stderr ,"strata serve: checkpoint restore: %s\n" ,error .c_str ()); 1499return false; 1500} 1501 1502// --control-vector-scaled: llama.cpp's `common_control_vector_load` (every file's `direction.<l>` times its scale, 1503// summed; layer 0 has none) and `llama_adapter_cvec::apply` with the projection-mode patch (project: the unit 1504// direction and its norm as the scale), into the tables `cvec_upload` takes. `summary` is what INFO reports; 1505// `digest` identifies the uploaded tables, mode and range exactly (a session file is bound to it). 1506bool load_control_vectors (const Options & o ,const strata::core::ModelGeometry & g , std::string & summary , 1507uint64_t & digest , std::string & err ) { 1508const int64_t L = g .n_layers ,N = g .n_embd ; 1509 std::vector < float > data ((size_t ) (L * N ),0.0f ); 1510 std::vector < bool > have ((size_t )L , false); 1511for (const auto & [path ,scale ] :o .cvec_files ) { 1512try { 1513 strata::GgufFile f (path ); 1514const strata::MetaValue * arch = f .get ("general.architecture" ); 1515if (arch == nullptr || arch -> s != "controlvector" ) { 1516err = path + ": not a control vector GGUF (general.architecture is not 'controlvector')" ; 1517return false; 1518 } 1519const strata::MetaValue * hint = f .get ("controlvector.model_hint" ); 1520if (hint != nullptr && hint -> s != "qwen4exp" ) 1521 std::fprintf (stderr ,"strata generate: %s was made for '%s', not qwen4exp\n" ,path .c_str (),hint -> s .c_str ()); 1522int found = 0 ; 1523for (const strata::TensorInfo & t :f .tensors ()) { 1524if (t .name .rfind ("direction." ,0 )!= 0 )continue ; 1525const long l = std::strtol (t .name .c_str ()+ 10 ,nullptr ,10 ); 1526if (l < 1 || l >=L )continue ;// layer 0 has no vector; past the model is ignored, as in llama.cpp 1527if (t .type != 0 || t .elements ()!= (uint64_t )N ) { 1528err = path + ": " + t .name + " must be " + std::to_string ((long long )N )+ " f32" ; 1529return false; 1530 } 1531const float * src = reinterpret_cast < const float *> (f .tensor_data (t )); 1532for (int64_t j = 0 ;j < N ;++ j )data [(size_t ) (l * N + j )]+= scale * src [j ]; 1533have [(size_t )l ]= true; 1534++ found ; 1535 } 1536if (found == 0 ) {err = path + ": no direction.<layer> tensors" ;return false; } 1537 }catch (const std::exception & e ) { 1538err = e .what (); 1539return false; 1540 } 1541 } 1542const int first = o .cvec_first <=0 ?1 :o .cvec_first ; 1543const int last = (o .cvec_last <=0 || o .cvec_last >=L ) ? (int )L - 1 :o .cvec_last ; 1544const int single = o .cvec_mode == 0 ?o .cvec_single :-1 ; 1545if (single >=0 && (single >=L || !have [(size_t )single ])) { 1546err = "--cvec-dir single:" + std::to_string (single )+ ": the vector has no direction for that layer" ; 1547return false; 1548 } 1549 std::vector < float > dir ((size_t ) (L * N ),0.0f ),s ((size_t )L ,0.0f ); 1550int steered = 0 ; 1551for (int64_t l = first ;l <=last ;++ l ) { 1552const int64_t src = single >=0 ?single :l ; 1553if (!have [(size_t )src ])continue ; 1554const float * d = data .data ()+ (size_t ) (src * N ); 1555if (o .cvec_mode == 0 ) { 1556double nrm = 0.0 ; 1557for (int64_t j = 0 ;j < N ;++ j )nrm += (double )d [j ]* d [j ]; 1558nrm = std::sqrt (nrm ); 1559if (nrm <=0.0 )continue ; 1560s [(size_t )l ]= (float )nrm ; 1561for (int64_t j = 0 ;j < N ;++ j )dir [(size_t ) (l * N + j )]= (float ) (d [j ] /nrm ); 1562 }else { 1563s [(size_t )l ]= 1.0f ; 1564 std::copy (d ,d + N ,dir .begin ()+ (size_t ) (l * N )); 1565 } 1566++ steered ; 1567 } 1568if (steered == 0 ) {err = "the control vector has no direction in layers " + std::to_string (first )+ ".." + std::to_string (last );return false; } 1569if (!strata::kernels::cvec_upload (dir ,s ,o .cvec_mode ,first ,last ,N ,g .hc ,err ))return false; 1570 { 1571 strata::core::SessionIdentityBuilder b (0x43564543ull );// "CVEC" 1572b .i64 ("mode" ,o .cvec_mode ); 1573b .i64 ("first" ,first ); 1574b .i64 ("last" ,last ); 1575b .i64 ("single" ,single ); 1576b .bytes ("dir" ,dir .data (),dir .size ()* sizeof (float )); 1577b .bytes ("scale" ,s .data (),s .size ()* sizeof (float )); 1578digest = b .digest (); 1579if (digest == 0 )digest = 1 ;// 0 means "none loaded" 1580 } 1581summary = std::string (o .cvec_mode == 0 ?"project" :"add" )+ ":" + std::to_string (first )+ "-" + std::to_string (last )+ 1582 (single >=0 ?":single" + std::to_string (single ) :"" ); 1583// the line llama.cpp's patched build prints, so a log shows the same thing 1584 std::fprintf (stderr ,"strata generate: control vector mode = %s, dir = %s, layers %d..%d (%d steered)\n" , 1585o .cvec_mode == 0 ?"project" :"add" ,single >=0 ?"single" :"per-layer" ,first ,last ,steered ); 1586return true; 1587} 1588 1589// The effective host->device bandwidth of the PCIe link: copies from pinned host memory, as the expert arena's 1590// reads are. The native default share (0.55) was measured on x16 links (~26-28 GB/s); a x8 card in a x8 slot 1591// carries about half of that. Returns < 0 when the probe cannot run (then the caller keeps the default). 1592// 1593// #485: a single timed burst read an x16 PCIe 4 link (RTX A3000 laptop) at 18.5, 6.9 and 5.8 GB/s in three starts - 1594// a link still in a low-power state, other DMA, a context not yet up to speed - and the low reading set the share. 1595// Such a disturbance only ever slows a copy: nothing makes a correctly timed copy faster than the link carries. So 1596// the same 1 GiB is now copied as four bursts of 256 MiB, timed one by one, and the fastest is the link's figure (the 1597// median would still follow a disturbance that lasts through half the bursts). Each burst takes ~10 ms on an x16 1598// PCIe 4 link, so the probe takes no longer than the one 1 GiB burst did. `samples`, when given, gets every 1599// burst's reading for the log. 1600double probe_pcie_h2d_gbps (std::string * samples = nullptr ,bool pin_source = false)try { 1601constexpr size_t kBytes = 256ull <<20 ; 1602constexpr int kBursts = 4 ; 1603void * h = nullptr ; 1604void * d = nullptr ; 1605// PR #1669: a pageable source made the copy engine fault on a layer split (VM_NOT_FOUND), so a split pins it. A single card keeps the 1606// pageable source of 0.1.41: pinned reads 1.7x faster, which moves the default pcie_frac (A750 0.28 -> 0.47, 10% slower decode). 1607if (DPCT_CHECK_ERROR (h = pin_source ? (void * )sycl::malloc_host (kBytes , dpct::get_in_order_queue ()) : (void * )malloc (kBytes ))!= 0 || h == nullptr )return -1.0 ; 1608if (DPCT_CHECK_ERROR (d = (void * )sycl::malloc_device ( 1609kBytes , dpct::get_in_order_queue ()))!= 0 ) { 1610if (pin_source ) sycl::free (h , dpct::get_in_order_queue ());else free (h ); 1611return -1.0 ; 1612 } 1613 std::memset (h ,0 ,kBytes );// fault the pages in before timing 1614 dpct::get_in_order_queue ().memcpy ( 1615d ,h ,kBytes ).wait ();// warmup: context up, copy engine primed 1616float ms [kBursts ]= {}; 1617#if defined(STRATA_USE_HIP )&& defined(_WIN32 ) 1618// Windows HIP: the events do not bracket the copies there (an RX 6800 read 3,300-26,000 GB/s, so every link kept 1619// the x16 share), so each burst is timed on the host between two synchronizes: 256 MiB takes ~10 ms, so the 1620// synchronize around it hardly matters 1621bool ok = cudaDeviceSynchronize ()== cudaSuccess ; 1622for (int b = 0 ;b < kBursts && ok ;++ b ) { 1623const Clock ::time_point t0 = Clock ::now (); 1624cudaMemcpyAsync (d ,h ,kBytes ,cudaMemcpyHostToDevice ); 1625ok = cudaDeviceSynchronize ()== cudaSuccess ; 1626ms [b ]= (float ) std::chrono::duration < double , std::milli > (Clock ::now ()- t0 ).count (); 1627 } 1628#else 1629// the bursts run back to back on the stream, an event between each two 1630 dpct::event_ptr ev [kBursts + 1 ]; 1631int n_ev = 0 ; 1632while (n_ev <=kBursts && 1633DPCT_CHECK_ERROR (ev [n_ev ]= new sycl::event ())== 0 )++ n_ev ; 1634bool ok = n_ev == kBursts + 1 ; 1635if (ok ) { 1636 dpct::sync_barrier (ev [0 ]); 1637for (int b = 0 ;b < kBursts ;++ b ) { 1638/* 1639DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy 1640API. While the origin API might be synchronous, it depends on the 1641type of operand memory, so you may need to call wait() on event 1642return by memcpy API to ensure synchronization behavior. 1643*/ 1644 dpct::get_in_order_queue ().memcpy (d ,h ,kBytes ).wait (); 1645 dpct::sync_barrier (ev [b + 1 ]); 1646 } 1647ok = DPCT_CHECK_ERROR (ev [kBursts ]-> wait_and_throw ())== 0 ; 1648for (int b = 0 ;b < kBursts && ok ;++ b )ok = 1649DPCT_CHECK_ERROR ( 1650ms [b ]= 1651 (ev [b + 1 ] 1652-> get_profiling_info < 1653 sycl::info::event_profiling::command_end > ()- 1654ev [b ] 1655-> get_profiling_info < 1656 sycl::info::event_profiling::command_start > ()) / 16571000000.0f )== 0 ; 1658 } 1659for (int i = 0 ;i < n_ev ;++ i ) dpct::destroy_event (ev [i ]); 1660#endif 1661double bw = -1.0 ; 1662if (samples != nullptr )samples -> clear (); 1663for (int b = 0 ;b < kBursts && ok ;++ b ) { 1664const double s = ms [b ]> 0.01f ? (double )kBytes / (ms [b ]* 1e-3 ) /1e9 :-1.0 ; 1665bw = std::max (bw ,s ); 1666if (samples != nullptr ) { 1667char buf [32 ]; 1668 std::snprintf (buf ,sizeof (buf ),"%s%.1f" ,b == 0 ?"" :" " ,s ); 1669* samples += buf ; 1670 } 1671 } 1672/* 1673DPCT1010: SYCL uses exceptions to report errors and does not use the 1674error codes. The cudaGetLastError function call was replaced with 0. You 1675need to rewrite this code. 1676*/ 1677if (!ok )(void )0 ; 1678 sycl::free (d , dpct::get_in_order_queue ()); 1679if (pin_source ) sycl::free (h , dpct::get_in_order_queue ());else free (h ); 1680return bw ; 1681} 1682catch (sycl::exception const & exc ) { 1683 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1684 <<", line:" <<__LINE__ << std::endl ; 1685 std::exit (1 ); 1686} 1687 1688// The PCIe share of the missed experts for a link measured at `gbps`: `base` (the share measured on x16 links) from 1689// 20 GB/s up, and below that in proportion to the bandwidth, so the time the link spends on its share stays about 1690// what the x16 share costs. Continuous (#485): before, 19.9 GB/s gave 0.42 and 20.0 the full 0.55 (and 4.0 GB/s 1691// gave 0.08, 3.9 none), so a reading near either edge moved the share by a quarter of its range. From 20 GB/s up 1692// (an x16 PCIe 4/5 link: ~26-28 GB/s) the share is unchanged. 1693double pcie_frac_for_gbps (double gbps ,double base ,double ref_gbps = 20.0 ) { 1694return gbps <=0.0 ?base :base * std::min (1.0 ,gbps /ref_gbps ); 1695} 1696 1697// 0.1.42 (CUDA) / 0.1.48 (SYCL, opt-in STRATA_PCIE_FRAC_DEFAULT=auto): the share refined from what the CPU pool measures in 1698// the first decode windows. The balance share of the missed experts is link / (link + 1.85 x CPU rate); the link is the 1699// start-up probe, the CPU rate the expert bytes over the pool's wall time per missed expert (ms_run / multi_misses). 1700// Three updates at most (after 48, then 96 and 96 more windows), each rounded to 0.05. 1701struct PcieAuto { 1702static constexpr double kPoolFactor = 1.85 ; 1703bool on = false; 1704double link_gbps = 0.0 ,blob_bytes = 0.0 ; 1705double mark_ms = 0.0 ; 1706int64_t mark_jobs = 0 ; 1707double acc_ms = 0.0 ; 1708int64_t acc_jobs = 0 ; 1709int acc_win = 0 ,updates = 0 ; 1710void mark (double ms_run ,int64_t jobs ) {mark_ms = ms_run ;mark_jobs = jobs ; } 1711/// After a decode window: the new share, or -1 while there is nothing to change. `tc_us`/`rate` get the reading. 1712double window (double ms_run ,int64_t jobs ,double cur ,double * tc_us ,double * rate ) { 1713if (!on )return -1.0 ; 1714acc_ms += ms_run - mark_ms ; 1715acc_jobs += jobs - mark_jobs ; 1716mark (ms_run ,jobs ); 1717++ acc_win ; 1718if (acc_win < (updates == 0 ?48 :96 ))return -1.0 ; 1719if (acc_jobs < 300 ) {// too few missed experts to read the pool's speed (everything hits): look again 1720if (acc_win >=2000 )on = false; 1721return -1.0 ; 1722 } 1723const double tc = acc_ms * 1000.0 / (double )acc_jobs ; 1724acc_ms = 0.0 ; 1725acc_jobs = 0 ; 1726acc_win = 0 ; 1727if (++ updates >=3 )on = false; 1728if (!(tc > 1.0 )|| !(blob_bytes > 0.0 )|| !(link_gbps > 0.0 ))return -1.0 ; 1729const double r = blob_bytes / (tc * 1e-6 ) /1e9 ; 1730const double f = std::min (0.60 , std::max (0.10 , std::round (link_gbps / (link_gbps + kPoolFactor * r )* 20.0 ) /20.0 )); 1731* tc_us = tc ; 1732* rate = r ; 1733return std::fabs (f - cur )< 0.025 ?-1.0 :f ; 1734 } 1735}; 1736 1737}// namespace 1738 1739// #1425 #1549 #1629: --ple-io direct (the default) does unbuffered random reads of the n-gram table; on some drives 1740// (DRAM-less NVMe, Windows unbuffered I/O) they run at 34 MB/s or 4-8 tok/s and a prompt reads layer 1 for minutes. 1741// Rows per second of a short cold probe: a few batches of random rows through the same batched reader a prompt chunk 1742// uses, stopped after ~0.6 s. Returns <= 0 when nothing could be measured. 1743static double ple_direct_rows_per_s (strata::kernels::PleTable & t ) { 1744const uint64_t n = t .rows (); 1745if (n < 4096 )return -1.0 ; 1746constexpr size_t kTok = 4 ;// 64 rows a batch 1747 std::vector < uint32_t > rows (kTok * 16 ); 1748 std::vector < float > out (kTok * strata::kernels::NG_N_EMBD ); 1749uint64_t x = 0x9E3779B97F4A7C15ull ^n ; 1750const auto t0 = std::chrono::steady_clock::now (); 1751uint64_t done = 0 ; 1752double el = 0 ; 1753for (int b = 0 ;b < 64 ;++ b ) { 1754for (auto & r :rows ) {x ^=x <<13 ;x ^=x >>7 ;x ^=x <<17 ;r = (uint32_t ) (x %n ); } 1755 std::string e ; 1756if (!t .gather_batch (rows .data (),kTok ,out .data (),e ))return -1.0 ; 1757done += rows .size (); 1758el = std::chrono::duration < double > (std::chrono::steady_clock::now ()- t0 ).count (); 1759if (el > 0.6 )break ; 1760 } 1761return el > 0 ? (double )done /el :-1.0 ; 1762} 1763 1764// #1980: a start-up refusal ends the process here instead of returning from main. Returning ran main's destructors 1765// (the stages' caches, queues and Level Zero objects) in an order the UR loader did not survive: 2x Arc Pro B60, every 1766// REFUSED start segfaulted in libur_loader after its message, and a trimmed one also left an xe page fault (bcs CAT error) 1767// on the second card that hung the next start. The device work queued so far finishes first; nothing is freed. 1768[[noreturn ]]static void refuse_exit (int code ) { 1769 std::fflush (stdout ); 1770 std::fflush (stderr ); 1771try { 1772for (unsigned int d = 0 ;d < dpct::device_count ();++ d ) dpct::get_device (d ).queues_wait_and_throw (); 1773 }catch (...) { 1774 } 1775 std::fflush (stderr ); 1776 std::_Exit (code ); 1777} 1778 1779int main (int argc ,char ** argv )try { 1780// **UNBUFFERED, BECAUSE THE INTERESTING OUTPUT IS THE OUTPUT BEFORE A CRASH.** `stdout` redirected to a 1781// pipe or a file is block-buffered, so a program that dies loses every line it had already printed - which 1782// turns "it crashed at step 7" into "it crashed somewhere", and the difference is a debugging session. 1783 std::setvbuf (stdout ,nullptr ,_IONBF ,0 ); 1784// `strata --version` / `-V` (also `strata generate --version`): the version and nothing else, before any GPU is touched, as the CUDA 1785// and HIP engines have answered it. `strata update` runs it as the engine's smoke test, and the Intel package build runs it with 1786// an empty environment. 1787for (int i = 1 ;i < argc && i < 3 ;++ i ) { 1788if (std::strcmp (argv [i ],"--version" )== 0 || std::strcmp (argv [i ],"-V" )== 0 ) { 1789 std::printf ("strata %s\n" ,STRATA_VERSION ); 1790return 0 ; 1791 } 1792// `strata --families`: the GGUF architectures this build runs (setup asks before it installs one). The Intel engine has no 1793// qwen35moe path (src/qwen35 is CUDA and HIP only), so it names Flash-Next's alone, as the CUDA build without STRATA_HAVE_QWEN35. 1794if (std::strcmp (argv [i ],"--families" )== 0 ) { 1795 std::printf ("qwen4exp\n" ); 1796return 0 ; 1797 } 1798// `strata --geometry`: the name of the model shape the kernels are compiled for (the geometry header's kGeometryName: flash_next for the default build); 1799// Control checks it against the shape of the package's signed manifest (strata_control/shape_engine.py) 1800if (std::strcmp (argv [i ],"--geometry" )== 0 ) { 1801 std::printf ("%s\n" , strata::core::kGeometryName ); 1802return 0 ; 1803 } 1804 } 1805#if (defined(STRATA_USE_HIP )|| defined(STRATA_HIP_GFX906 ))&& !defined(_WIN32 ) 1806// AMD, a file-backed arena (STRATA_ARENA_MMAP): ROCclr copies a pageable source of 1 MiB or more by locking its 1807// pages in place (a GPU userptr), and keeps them - so every expert the VRAM fill copied from the mapped 1808// experts.bin stayed resident, the release of the VRAM-held ones was undone by the driver at once, and a 1809// 32 GB PC ran with ~0.3 GB free: the kernel swapped, and a turn's checkpoint took 25-80 s. Above this size 1810// ROCclr stages through its own pinned buffers instead; decode is unchanged (49.06 vs 49.16 ms/window). 1811if (std::getenv ("STRATA_ARENA_MMAP" )&& std::getenv ("STRATA_ARENA_MMAP" )[0 ]== '1' ) 1812setenv ("GPU_PINNED_MIN_XFER_SIZE" ,"1000000" ,0 );// MiB; an explicit setting wins 1813#endif 1814// Load every CUDA kernel when the context is created, before the expert cache takes the free VRAM. With the 1815// default lazy loading, a kernel first used mid-prompt (MMQ for IQ3_XXS at 64K+ on a 12 GB card) found no VRAM 1816// left for its code and the engine ended ("out of memory: cudaFuncSetAttribute"). Costs ~30 MB of VRAM. 1817if (std::getenv ("CUDA_MODULE_LOADING" )== nullptr ) { 1818#if defined(_WIN32 ) 1819_putenv_s ("CUDA_MODULE_LOADING" ,"EAGER" ); 1820#else 1821setenv ("CUDA_MODULE_LOADING" ,"EAGER" ,0 ); 1822#endif 1823 } 1824 strata::uc_probe ("start" );// test only: STRATA_UC_PROBE=1 times four kernels (uc_probe.hpp) 1825Options o ; 1826bool borrow_explicit = false;// SYCL port: --prefill-borrow / --no-prefill-borrow given (else chosen by context) 1827bool have_tokens = false; 1828bool have_logits_stride = false; 1829for (int i = 1 ;i < argc ;++ i ) { 1830const std::string a = argv [i ]; 1831auto next = [& ](const char * what )-> const char * { 1832if (i + 1 >=argc ) { std::fprintf (stderr ,"%s needs a value\n" ,what ); std::exit (2 ); } 1833return argv [++ i ]; 1834 }; 1835bool parsed = true; 1836if (a == "--help" || a == "-h" ) {usage ();return 0 ; } 1837else if (a == "--pack" )o .pack = next ("--pack" ); 1838else if (a == "--tokens" ) { 1839if (have_tokens ) { std::fprintf (stderr ,"supply one token input only\n" );return 2 ; } 1840 std::string e ; 1841if (!parse_i64_list (next ("--tokens" ),o .tokens ,e )) { std::fprintf (stderr ,"%s\n" ,e .c_str ());return 2 ; } 1842have_tokens = true; 1843 } 1844else if (a == "--tokens-file" ) { 1845if (have_tokens ) { std::fprintf (stderr ,"supply one token input only\n" );return 2 ; } 1846 std::ifstream input (next ("--tokens-file" )); 1847if (!input ) { std::fprintf (stderr ,"cannot open token file\n" );return 2 ; } 1848 std::string text ((std::istreambuf_iterator < char > (input )), std::istreambuf_iterator < char > ()); 1849if (input .bad ()) { std::fprintf (stderr ,"cannot read token file\n" );return 2 ; } 1850 std::string error ; 1851if (text .find ('\0' )!= std::string::npos || !parse_i64_list (text .c_str (),o .tokens ,error )) { 1852 std::fprintf (stderr ,"malformed token file: %s\n" ,error .c_str ());return 2 ; 1853 } 1854have_tokens = true; 1855 } 1856else if (a == "--max-new" )o .max_new = std::atoll (next ("--max-new" )); 1857else if (a == "--max-context" )o .max_context = std::atoll (next ("--max-context" )); 1858else if (a == "--rope-scaling" )o .rope_scaling = next ("--rope-scaling" ); 1859else if (a == "--rope-scale" )o .rope_scale = std::atof (next ("--rope-scale" )); 1860else if (a == "--rope-freq-base" )o .rope_freq_base = std::atof (next ("--rope-freq-base" )); 1861else if (a == "--rope-freq-scale" )o .rope_freq_scale = std::atof (next ("--rope-freq-scale" )); 1862else if (a == "--yarn-orig-ctx" )o .yarn_orig_ctx = std::atof (next ("--yarn-orig-ctx" )); 1863else if (a == "--yarn-ext-factor" )o .yarn_ext_factor = std::atof (next ("--yarn-ext-factor" )); 1864else if (a == "--yarn-attn-factor" )o .yarn_attn_factor = std::atof (next ("--yarn-attn-factor" )); 1865else if (a == "--yarn-beta-fast" )o .yarn_beta_fast = std::atof (next ("--yarn-beta-fast" )); 1866else if (a == "--yarn-beta-slow" )o .yarn_beta_slow = std::atof (next ("--yarn-beta-slow" )); 1867else if (a == "--greedy" )o .greedy = true; 1868else if (a == "--seed" ) {o .seed = (uint64_t ) std::atoll (next ("--seed" ));o .greedy = false; } 1869else if (a == "--top-k" )o .top_k = std::atoi (next ("--top-k" )); 1870else if (a == "--top-p" )o .top_p = (float ) std::atof (next ("--top-p" )); 1871else if (a == "--temperature" )o .temperature = (float ) std::atof (next ("--temperature" )); 1872else if (a == "--dump-logits" )o .dump_logits = next ("--dump-logits" ); 1873else if (a == "--logits-stride" ) { 1874if (have_logits_stride ) { std::fprintf (stderr ,"--logits-stride must be supplied only once\n" );return 2 ; } 1875if (!strata::program::logits_selection::parse_stride (next ("--logits-stride" ),o .logits_stride )) { 1876 std::fprintf (stderr ,"--logits-stride requires a positive decimal int64\n" );return 2 ; 1877 } 1878have_logits_stride = true; 1879 } 1880else if (a == "--dump-residual" )o .dump_residual = next ("--dump-residual" ); 1881else if (a == "--dump-mixed" )o .dump_mixed = next ("--dump-mixed" ); 1882else if (a == "--dump-layers" )o .dump_layers = next ("--dump-layers" ); 1883else if (a == "--dump-halves" )o .dump_halves = next ("--dump-halves" ); 1884else if (a == "--dump-routing" )o .dump_routing = next ("--dump-routing" ); 1885else if (a == "--ple-gguf" )o .ple_gguf = next ("--ple-gguf" ); 1886else if (a == "--no-ple" )o .no_ple = true; 1887else if (a == "--ple-io" ) {o .ple_io = next ("--ple-io" );o .ple_io_explicit = true; } 1888else if (a == "--ple-row-cache" )o .ple_row_cache = std::atoll (next ("--ple-row-cache" )); 1889else if (a == "--ple-inflight" )o .ple_inflight = std::atoi (next ("--ple-inflight" )); 1890else if (a == "--ple-delay-us" )o .ple_delay_us = std::atof (next ("--ple-delay-us" )); 1891else if (a == "--ple-sync-submit" )o .ple_sync_submit = true; 1892else if (a == "--kv" )o .kv = next ("--kv" ); 1893else if (a == "--kv-resident" )o .kv_resident = std::atoll (next ("--kv-resident" )); 1894else if (a == "--kv-grow" )o .kv_grow = true; 1895else if (a == "--no-kv-grow" )o .kv_grow = false; 1896else if (a == "--stream-token" )o .stream_token = true; 1897else if (a == "--check-logits" )o .check_logits = true; 1898else if (a == "--gr-fp32-activations" )o .gr_fp32_activations = true; 1899else if (a == "--gr-native-mmvf" )o .gr_native_mmvf = true; 1900else if (a == "--native-bf16" )o .native_bf16 = true; 1901else if (a == "--native-bf16-extra" )o .native_bf16_extra = true; 1902else if (a == "--native-ple-key" )o .native_ple_key = true; 1903else if (a == "--native-moe-combine" )o .native_moe_combine = true; 1904else if (a == "--native-gdn" )o .native_gdn = true; 1905else if (a == "--native-flash-attn-short" )o .native_flash_attn_short = true; 1906else if (a == "--native-qsa-indexer" )o .native_qsa_indexer = true; 1907else if (a == "--native-qsa" )o .native_qsa = true; 1908else if (a == "--native-rope" )o .native_rope = true; 1909else if (a == "--native-ple-postops" )o .native_ple_postops = true; 1910else if (a == "--native-router" )o .native_router = true; 1911else if (a == "--cpu-oracle-q8-0" )o .cpu_oracle_q8_0 = true; 1912else if (a == "--native" )o .native_preset = next ("--native" ); 1913else if (a == "--native-head-gguf" )o .native_head_gguf = next ("--native-head-gguf" ); 1914else if (a == "--embd-gguf" )o .embd_gguf = next ("--embd-gguf" ); 1915else if (a == "--native-dense-gguf" )o .native_dense_gguf .push_back (next ("--native-dense-gguf" )); 1916else if (a == "--no-capture" )o .no_capture = true; 1917else if (a == "--no-pool" )o .no_pool = true; 1918else if (a == "--sync-every-layer" )o .sync_every_layer = true; 1919else if (a == "--stage-timing" )o .stage_timing = true; 1920else if (a == "--graph-only" )o .graph_only = true; 1921else if (a == "--gpu-only-full" )o .gpu_only_full = true; 1922else if (a == "--pool-workers" )o .pool_workers = std::atoi (next ("--pool-workers" )); 1923else if (a == "--pool-cores" )o .pool_cores = next ("--pool-cores" ); 1924else if (a == "--host-core" ) { 1925o .host_core = next ("--host-core" ); 1926if (o .host_core != "first" && o .host_core != "last" ) { 1927 std::fprintf (stderr ,"strata generate: unknown --host-core value '%s' (expected first or last)\n" ,o .host_core .c_str ()); 1928return 2 ; 1929 } 1930 } 1931else if (a == "--pool-affinity" ) { 1932const std::string v = next ("--pool-affinity" ); 1933if (v == "auto" )o .pool_affinity = strata::kernels::cpu::PoolAffinity ::Auto ; 1934else if (v == "p-cores" || v == "pcores" )o .pool_affinity = strata::kernels::cpu::PoolAffinity ::PCores ; 1935else if (v == "all" )o .pool_affinity = strata::kernels::cpu::PoolAffinity ::All ; 1936else { 1937 std::fprintf (stderr ,"strata generate: unknown --pool-affinity value '%s' (expected auto, p-cores, or all)\n" ,v .c_str ()); 1938return 2 ; 1939 } 1940 } 1941else if (a == "--no-host-worker" )o .no_host_worker = true; 1942else if (a == "--no-ple-prefetch" )o .no_ple_prefetch = true; 1943else if (a == "--coupled-draft" )o .coupled_draft = true; 1944else if (a == "--no-coupled-draft" )o .coupled_draft = false; 1945else parsed = false; 1946// The chain continues here in a second statement: one chain of 120+ `else if` passed MSVC's limit of 128 1947// nested blocks (C1061). The order of the tests and what each does are unchanged. 1948if (!parsed ) { 1949if (a == "--expert-cache" ) { 1950const std::string v = next ("--expert-cache" ); 1951o .expert_cache = (v == "auto" ) ?-1 : std::atoi (v .c_str ()); 1952 } 1953else if (a == "--expert-cache-device1" || a == "--expert-cache-device2" || a == "--expert-cache-device3" ) { 1954const size_t r = (size_t ) (a .back ()- '1' ); 1955const std::string v = next (a .c_str ()); 1956o .expert_cache_remote_auto [r ]= v == "auto" ; 1957o .expert_cache_remote [r ]= v == "auto" ? std::numeric_limits < int > ::max () : std::atoi (v .c_str ()); 1958 } 1959else if (a == "--remote-expert-opt" )o .remote_expert_opt = true; 1960else if (a == "--expert-cache-remote-placement" ) 1961o .expert_cache_remote_placement = next ("--expert-cache-remote-placement" ); 1962else if (a == "--vram-reserve-mib" ) {o .vram_reserve_mib = std::atoi (next ("--vram-reserve-mib" ));o .vram_reserve_given = true; } 1963else if (a == "--vram-reserve-later-mib" ) 1964o .vram_reserve_later_mib = std::atoi (next ("--vram-reserve-later-mib" )); 1965else if (a == "--prefill" ) { 1966const std::string v = next ("--prefill" ); 1967o .prefill_auto = v == "auto" || v .rfind ("auto:" ,0 )== 0 ; 1968// #282: auto:N (N = 16384 or 32768) or STRATA_PREFILL_AUTO_MAX lets auto take chunks above 8192 1969const char * env_max = std::getenv ("STRATA_PREFILL_AUTO_MAX" ); 1970const long long want_max = v .rfind ("auto:" ,0 )== 0 ? std::atoll (v .c_str ()+ 5 ) 1971 : (o .prefill_auto && env_max != nullptr ? std::atoll (env_max ) :8192 ); 1972o .prefill_auto_max = want_max >=32768 ?32768 :want_max >=16384 ?16384 :8192 ; 1973o .prefill_chunk = o .prefill_auto ?o .prefill_auto_max : std::atoll (v .c_str ()); 1974o .prefill_given = !o .prefill_auto && o .prefill_chunk > 0 ; 1975 } 1976else if (a == "--no-split-rows" )o .no_split_rows = true; 1977else if (a == "--no-prefill-borrow" ) {o .no_prefill_borrow = true;borrow_explicit = true; } 1978else if (a == "--prefill-borrow" ) {o .no_prefill_borrow = false;borrow_explicit = true; } 1979else if (a == "--vram-elastic" )o .vram_elastic = true; 1980else if (a == "--vram-segment-mib" )o .vram_segment_mib = std::atoll (next ("--vram-segment-mib" )); 1981else if (a == "--prefill-until" )o .prefill_until = std::atoll (next ("--prefill-until" )); 1982else if (a == "--dump-final-r" )o .dump_final_r = next ("--dump-final-r" ); 1983else if (a == "--spec" )o .spec = std::atoi (next ("--spec" )); 1984else if (a == "--batch" )o .batch = std::atoi (next ("--batch" )); 1985else if (a == "--slots" )o .batch = std::atoi (next ("--slots" ));// the same as --batch 1986else if (a == "--trim-stage-weights" )o .trim_stage_weights = true; 1987else if (a == "--batch-groups" ) { 1988const std::string bg = next ("--batch-groups" ); 1989o .batch_groups = bg == "auto" ?-1 : std::atoi (bg .c_str ()); 1990 } 1991else if (a == "--batch-mtp" )o .batch_mtp = true; 1992else if (a == "--spec-oracle" )o .spec_oracle = next ("--spec-oracle" ); 1993else if (a == "--spec-corrupt" )o .spec_corrupt = std::atoi (next ("--spec-corrupt" )); 1994else if (a == "--spec-follow" )o .spec_follow = next ("--spec-follow" ); 1995else if (a == "--window-hashes" )o .window_hashes = next ("--window-hashes" ); 1996else if (a == "--mtp" )o .mtp = next ("--mtp" ); 1997else if (a == "--mtp-window" )o .mtp_window = std::atoll (next ("--mtp-window" )); 1998else if (a == "--pcie-frac" )o .pcie_frac = std::atof (next ("--pcie-frac" )); 1999else if (a == "--adapt-every" )o .adapt_every = std::atoi (next ("--adapt-every" )); 2000else if (a == "--adapt-decay" )o .adapt_decay = strata::program::adapt_decay_checked (std::atof (next ("--adapt-decay" )));// #1284: outside 0..1 -> 0.7, said 2001else if (a == "--adapt-async" )o .adapt_async = std::atoi (next ("--adapt-async" ))!= 0 ?1 :0 ; 2002else if (a == "--spec-min-p" )o .spec_min_p = std::atof (next ("--spec-min-p" )); 2003else if (a == "--stop-eos" )o .stop_eos = true; 2004else if (a == "--spec-split" )o .spec_split = true; 2005else if (a == "--layer-split" )o .layer_split = next ("--layer-split" ); 2006else if (a == "--split-device" )o .split_device = next ("--split-device" ); 2007else if (a == "--split-skip-if-fits" )o .split_skip_if_fits = true; 2008else if (a == "--pcie-mode" )o .pcie_mode = next ("--pcie-mode" ); 2009else if (a == "--serve" )o .serve = true; 2010else if (a == "--vision" )o .vision = true; 2011else if (a == "--prompt-cache" )o .prompt_cache = std::max (0 , std::atoi (next ("--prompt-cache" ))); 2012else if (a == "--conversation-cache-mib" || a == "--conversation-cache-slots" || 2013a == "--conversation-cache-min-free-mib" || a == "--session-min-free-mib" ) { 2014const std::string value = next (a .c_str ()); 2015int64_t number = 0 ; 2016const auto result = std::from_chars (value .data (),value .data ()+ value .size (),number ); 2017const int64_t limit = a == "--conversation-cache-slots" ?INT32_MAX :INT64_MAX / (1024 * 1024 ); 2018if (result .ec != std::errc {}|| result .ptr != value .data ()+ value .size ()|| number < 0 || number > limit ) { 2019 std::fprintf (stderr ,"%s needs a nonnegative integer within range\n" ,a .c_str ()); 2020return 2 ; 2021 } 2022if (a == "--conversation-cache-mib" )o .conversation_cache_mib = number ; 2023else if (a == "--conversation-cache-min-free-mib" )o .conversation_cache_min_free_mib = number ; 2024else if (a == "--session-min-free-mib" )o .session_min_free_mib = number ; 2025else o .conversation_cache_slots = (int )number ; 2026 } 2027else if (a == "--prompt-cache-tail" )o .prompt_cache_tail = true; 2028else if (a == "--prompt-cache-every" )o .prompt_cache_every = std::max (0LL , std::atoll (next ("--prompt-cache-every" ))); 2029else if (a == "--prompt-cache-root" )o .prompt_cache_root = std::max (0LL , std::atoll (next ("--prompt-cache-root" ))); 2030else if (a == "--turn-token" )o .turn_token = std::atoll (next ("--turn-token" )); 2031else if (a == "--tail-role-token" )o .tail_role_token = std::atoll (next ("--tail-role-token" )); 2032else if (a == "--short-read" )o .short_read = std::max (0LL , std::atoll (next ("--short-read" ))); 2033else if (a == "--pipeline-windows" )o .pipeline_windows = std::max (0 , std::min (2 , std::atoi (next ("--pipeline-windows" )))); 2034else if (a == "--suffix-draft" )o .suffix_draft = std::max (0 , std::atoi (next ("--suffix-draft" ))); 2035else if (a == "--mtp-max-t" )o .mtp_max_t = std::max (0 , std::atoi (next ("--mtp-max-t" ))); 2036else if (a == "--lookup-chain" )o .lookup_chain = std::clamp (std::atoi (next ("--lookup-chain" )),0 ,7 ); 2037else if (a == "--lookup-chain-min" )o .lookup_chain_min = std::max (3 , std::atoi (next ("--lookup-chain-min" ))); 2038else if (a == "--mtp-hnorm" ) { 2039const std::string v = next ("--mtp-hnorm" ); 2040if (v != "pooled" && v != "stream" ) { 2041 std::fprintf (stderr ,"strata generate: --mtp-hnorm takes pooled or stream\n" ); 2042return 2 ; 2043 } 2044o .mtp_hnorm_stream = v == "stream" ; 2045 } 2046else if (a == "--mtp-q4" ) { 2047o .mtp_q4 = next ("--mtp-q4" ); 2048if (o .mtp_q4 != "all" && o .mtp_q4 != "proj" && o .mtp_q4 != "head" ) { 2049 std::fprintf (stderr ,"strata generate: --mtp-q4 takes all, proj or head\n" ); 2050return 2 ; 2051 } 2052 } 2053else if (a == "--mtp-draft-vocab" )o .mtp_draft_vocab = next ("--mtp-draft-vocab" ); 2054else if (a == "--draft" )o .draft = next ("--draft" ); 2055else if (a == "--draft-model" )o .draft_model = next ("--draft-model" ); 2056else if (a == "--draft-fallback" ) { 2057o .draft_fallback = next ("--draft-fallback" ); 2058if (o .draft_fallback != "none" ) { 2059 std::fprintf (stderr ,"strata generate: --draft-fallback: only none is supported on this build (DFlash2 never runs beside an MTP layer here)\n" ); 2060 std::exit (2 ); 2061 } 2062 } 2063else if (a == "--draft-conf" )o .draft_conf = std::clamp (std::atof (next ("--draft-conf" )),0.0 ,1.0 ); 2064else if (a == "--draft-cap" )o .draft_cap = std::max (0 , std::atoi (next ("--draft-cap" ))); 2065else if (a == "--control-vector" )o .cvec_files .push_back ({next ("--control-vector" ),1.0f }); 2066else if (a == "--control-vector-scaled" ) { 2067// FILE:SCALE, comma-separated; the LAST colon splits, so a Windows path (C:\...) keeps its drive 2068 std::stringstream list (next ("--control-vector-scaled" )); 2069 std::string item ; 2070while (std::getline (list ,item ,',' )) { 2071const size_t colon = item .rfind (':' ); 2072char * end = nullptr ; 2073const float sc = colon == std::string::npos ?0.0f : std::strtof (item .c_str ()+ colon + 1 ,& end ); 2074if (colon == std::string::npos || colon == 0 || end == item .c_str ()+ colon + 1 || * end != '\0' ) { 2075 std::fprintf (stderr ,"--control-vector-scaled: expected FILE:SCALE, got '%s'\n" ,item .c_str ()); 2076return 2 ; 2077 } 2078o .cvec_files .push_back ({item .substr (0 ,colon ),sc }); 2079 } 2080 } 2081else if (a == "--control-vector-layer-range" ) { 2082o .cvec_first = std::atoi (next ("--control-vector-layer-range" )); 2083o .cvec_last = std::atoi (next ("--control-vector-layer-range" )); 2084 } 2085else if (a == "--cvec-mode" ) { 2086const std::string m = next ("--cvec-mode" ); 2087if (m == "project" )o .cvec_mode = 0 ; 2088else if (m == "add" )o .cvec_mode = 1 ; 2089else { std::fprintf (stderr ,"--cvec-mode: add or project, got '%s'\n" ,m .c_str ());return 2 ; } 2090 } 2091else if (a == "--cvec-dir" ) { 2092const std::string d = next ("--cvec-dir" ); 2093if (d == "per-layer" )o .cvec_single = -1 ; 2094else if (d .rfind ("single:" ,0 )== 0 )o .cvec_single = std::atoi (d .c_str ()+ 7 ); 2095else { std::fprintf (stderr ,"--cvec-dir: per-layer or single:L, got '%s'\n" ,d .c_str ());return 2 ; } 2096 } 2097else if (a == "--no-spec-split" )o .spec_split = false; 2098else if (a == "--eos-ids" ) { 2099 std::string e ; 2100if (!parse_i64_list (next ("--eos-ids" ),o .eos_ids ,e )) { std::fprintf (stderr ,"--eos-ids: %s\n" ,e .c_str ());return 2 ; } 2101o .stop_eos = true; 2102 } 2103else if (a == "--adapt-swaps" )o .adapt_swaps = std::atoi (next ("--adapt-swaps" )); 2104else if (a == "--expert-cache-cpu-order" )o .expert_cache_cpu_order = true; 2105else if (a == "--expert-cache-per-layer" )o .expert_cache_per_layer = true; 2106else if (a == "--peer-device" )o .peer_device = std::atoi (next ("--peer-device" )); 2107else if (a == "--peer-reserve-mib" )o .peer_reserve_mib = std::atoi (next ("--peer-reserve-mib" )); 2108else if (a == "--peer-slots" )o .peer_slots = std::atoll (next ("--peer-slots" )); 2109else if (a == "--peer-adapt-swaps" )o .peer_adapt_swaps = std::atoi (next ("--peer-adapt-swaps" )); 2110else if (a == "--peer-prefill-rows" )o .peer_prefill_rows = std::atoll (next ("--peer-prefill-rows" )); 2111else if (a == "--no-hit-poke" )o .no_hit_poke = true; 2112else if (a == "--expert-profile" )o .expert_profile = next ("--expert-profile" ); 2113else if (a == "--expert-profile-save" )o .expert_profile_save = next ("--expert-profile-save" ); 2114else if (a == "--expert-profile-save-every" ) 2115o .expert_profile_save_min = std::atof (next ("--expert-profile-save-every" )); 2116else if (a == "--gpu-stages" )o .gpu_stages = true; 2117else if (a == "--mmap-experts" )o .mmap_experts = true; 2118else if (a == "--shared-expert-arena" )o .shared_expert_arena = next ("--shared-expert-arena" ); 2119else if (a == "--resident-cpu-experts" )o .resident_cpu_experts = o .resident_cpu_explicit = true; 2120else if (a == "--stream-experts" )o .stream_experts = true; 2121else if (a == "--resident-experts" ) { 2122o .mmap_experts = o .resident_cpu_experts = o .resident_pin = o .resident_soft = true; 2123o .resident_headroom = 4ull <<30 ; 2124// A/B arms: STRATA_RESIDENT_PIN=0 keeps the copy pageable (the --resident-cpu-experts form); 2125// STRATA_RESIDENT_HEADROOM_GIB=N leaves N GiB of the available RAM free instead of 4 2126if (const char * v = std::getenv ("STRATA_RESIDENT_PIN" );v != nullptr && std::string (v )== "0" ) 2127o .resident_pin = false; 2128if (const char * v = std::getenv ("STRATA_RESIDENT_HEADROOM_GIB" );v != nullptr && std::atof (v ) >=0.0 ) 2129o .resident_headroom = (uint64_t ) (std::atof (v )* 1073741824.0 ); 2130 } 2131else if (a == "--resident-budget-gib" ) { 2132const double gib = std::atof (next ("--resident-budget-gib" )); 2133if (!(gib > 0.0 )) { std::fprintf (stderr ,"strata generate: --resident-budget-gib needs N > 0\n" );return 2 ; } 2134o .resident_budget = (uint64_t ) (gib * 1073741824.0 ); 2135o .mmap_experts = o .resident_cpu_experts = o .resident_pin = true; 2136o .resident_headroom = 4ull <<30 ; 2137if (const char * v = std::getenv ("STRATA_RESIDENT_PIN" );v != nullptr && std::string (v )== "0" ) 2138o .resident_pin = false; 2139if (const char * v = std::getenv ("STRATA_RESIDENT_HEADROOM_GIB" );v != nullptr && std::atof (v ) >=0.0 ) 2140o .resident_headroom = (uint64_t ) (std::atof (v )* 1073741824.0 ); 2141 } 2142else if (a == "--stats" )o .stats = true; 2143else if (a == "--shared-late" )o .shared_late = true; 2144else if (a == "--keep-canonical" )o .keep_canonical = true; 2145else if (a == "--no-token-graph" )o .no_token_graph = true; 2146else if (a == "--no-fused-gr" )o .no_fused_gr = true; 2147else if (a == "--no-fast-attn" )o .no_fast_attn = true; 2148else if (a == "--no-publish-kernel" )o .no_publish_kernel = true; 2149else if (a == "--no-fused-gdn" )o .no_fused_gdn = true; 2150else if (a == "--no-fast-select" )o .no_fast_select = true; 2151else { 2152// An unknown flag is an ERROR and not a warning: a typo'd `--max-neww` that silently generated 16 2153// tokens would look like a working run. 2154 std::fprintf (stderr ,"unknown argument: %s\n" ,a .c_str ()); 2155usage (); 2156return 2 ; 2157 } 2158 } 2159 } 2160#if defined(STRATA_USE_HIP ) 2161 {// gfx1151 (Strix Halo): the switches that are exact there are on by default (strata/core/arch_defaults.hpp); before 2162// any engine code reads its switches (they are read at first use), and the user's own settings are kept 2163cudaDeviceProp ad {}; 2164if (cudaGetDeviceProperties (& ad ,0 )== cudaSuccess ) strata::core::apply_arch_defaults (ad .gcnArchName ); 2165else (void )cudaGetLastError (); 2166 } 2167#endif 2168 strata::core::set_coupled_draft (o .coupled_draft ); 2169 {// --host-core / STRATA_HOST_CORE, before the pool and the session pin any thread 2170 std::string hc = o .host_core ; 2171if (hc .empty ()) 2172if (const char * e = std::getenv ("STRATA_HOST_CORE" ))hc = e ; 2173if (hc == "last" ) strata::kernels::cpu::set_host_core (strata::kernels::cpu::HostCore ::Last ); 2174 } 2175 {// --pool-cores / STRATA_POOL_CORES (experimental, off by default), before the pool is built; a list that cannot be read is 2176// said and left out (recommend, never force) 2177 std::string pc = o .pool_cores ; 2178if (pc .empty ()) 2179if (const char * e = std::getenv ("STRATA_POOL_CORES" ))pc = e ; 2180if (!pc .empty ()) { 2181 std::vector < int > cpus ; 2182 std::string perr ; 2183if (strata::kernels::cpu::parse_pool_cores (pc ,cpus ,perr )) strata::kernels::cpu::set_pool_cores (cpus ); 2184else std::fprintf (stderr ,"strata generate: --pool-cores: %s; the pool uses its default placement\n" ,perr .c_str ()); 2185 } 2186 } 2187 strata::core::set_peer_portable (o .peer_device >=1 );// multi-GPU: the Portable flag on mapped host buffers only with a peer device (before any allocation) 2188if (o .serve && o .conversation_cache_mib > 0 && (o .prompt_cache == 0 || o .conversation_cache_slots == 0 )) 2189 std::fprintf (stderr ,"strata serve: warning: conversation caching is disabled by %s\n" , 2190o .prompt_cache == 0 ?"--prompt-cache 0" :"--conversation-cache-slots 0" ); 2191// parking with --layer-split saves every stage (SavedConversation::stage_images) 2192// Layer split (multi-GPU): the later stages run layers [K_i, K_i+1) on their own GPUs (--split-device, default 2193// the next visible ones); "auto" places the K from each GPU's free VRAM once the weights are in (below). KV 2194// streaming and images (the server's GPU encoder) run across a split, also with parking and --batch. Across 2195// GPUs, not yet: control vectors, the helper caches (--expert-cache-remote), and lending cache slots to the 2196// prompt path (each stage's prompt path has its own buffers). 2197// --pcie-frac given: that one share is every stage's (the stages' own link probes are skipped), so a split over 2198// a fast and a slow link cannot set the two apart from the command line (#485) 2199const bool pcie_given = o .pcie_frac >=0.0 ; 2200 std::vector < int64_t > split_at ; 2201 std::vector < int > split_devs ; 2202bool split_auto = false,split_same = false; 2203if (!o .layer_split .empty ()) { 2204int n_dev = 1 ; 2205if (DPCT_CHECK_ERROR (n_dev = dpct::device_count ())!= 0 || n_dev < 1 ) 2206n_dev = 1 ; 2207/* 2208DPCT1026: The call to cudaGetLastError was removed because this 2209functionality is redundant in SYCL. 2210*/ 2211auto ints = [](const std::string & str ,auto & out )-> bool { 2212using V = typename std::decay_t < decltype(out )> ::value_type ; 2213size_t a = 0 ; 2214while (a < str .size ()) { 2215size_t b = str .find (',' ,a ); 2216if (b == std::string::npos )b = str .size (); 2217const std::string t = str .substr (a ,b - a ); 2218if (t .empty ()|| t .find_first_not_of ("0123456789" )!= std::string::npos )return false; 2219out .push_back ((V ) std::atoll (t .c_str ())); 2220a = b + 1 ; 2221 } 2222return !out .empty (); 2223 }; 2224split_auto = o .layer_split == "auto" ; 2225bool ok = o .serve && (split_auto || ints (o .layer_split ,split_at )); 2226// SYCL port: a stage is a GPU of the PRIMARY device's backend. Everything else that the runtime lists is 2227// not a stage: the batch slots load the OpenCL adapter as well, so on a two-card `xe` box 2228// dpct::device_count() then reports the CPU and the OpenCL view of the same two cards (5 devices), and an 2229// automatic split tried to put a stage on the CPU ("layer split, CUDA2 weights: the weight arena does not 2230// fit ... 0 MiB of 160876 MiB free on that card") instead of working. 2231const auto stage_dev = [](int d )-> bool { 2232try { 2233const sycl::device dev = dpct::get_device (d ); 2234return dev .is_gpu ()&& dev .get_backend ()== dpct::get_device (0 ).get_backend (); 2235 }catch (...) { 2236return false; 2237 } 2238 }; 2239if (ok && !o .split_device .empty ())ok = ints (o .split_device ,split_devs ); 2240else if (ok ) 2241for (int d = 1 ;d < n_dev && (split_auto || split_devs .size ()< split_at .size ());++ d ) 2242if (!split_auto || stage_dev (d ))split_devs .push_back (d ); 2243if (ok && !split_auto && split_devs .empty ()&& split_at .size ()== 1 )split_devs .push_back (0 );// one GPU 2244split_same = ok && split_devs .size ()== 1 && split_devs [0 ]== 0 && !split_auto ; 2245if (split_same && o .conversation_cache_mib > 0 && o .conversation_cache_slots > 0 && o .prompt_cache > 0 ) { 2246 std::fprintf (stderr ,"strata serve: conversation parking does not support a layer split on one GPU " 2247"(--split-device 0); disable parking with --conversation-cache-mib 0\n" ); 2248return 2 ; 2249 } 2250if (ok && split_auto && split_devs .empty ()) { 2251 std::fprintf (stderr ,"strata generate: --layer-split auto: one GPU visible, so no split\n" ); 2252o .layer_split .clear (); 2253split_auto = false; 2254 }else if (ok ) { 2255ok = (split_auto || split_at .size ()== split_devs .size ())&& split_devs .size ()< (size_t )SplitDrive ::kMax ; 2256for (size_t i = 0 ;ok && i < split_at .size ();++ i )ok = split_at [i ] >=2 && (i == 0 || split_at [i ]> split_at [i - 1 ]); 2257for (size_t i = 0 ;ok && !split_same && i < split_devs .size ();++ i ) { 2258ok = split_devs [i ]> 0 && split_devs [i ]< n_dev ; 2259for (size_t j = 0 ;ok && j < i ;++ j )ok = split_devs [i ]!= split_devs [j ]; 2260 } 2261 } 2262if (!ok ) { 2263 std::fprintf (stderr ,"strata generate: --layer-split K[,K2..]|auto needs --serve, rising K from 2, and one " 2264"distinct GPU per K in --split-device (1..%d; or 0 with one K: the same GPU). K is the " 2265"FIRST LAYER of each later GPU, not a count of layers per card: \"24,36,42\" for 4 " 2266"GPUs, not \"24,12,6,6\" (got \"%s\")\n" ,n_dev - 1 ,o .layer_split .c_str ()); 2267return 2 ; 2268 } 2269 } 2270bool multi_gpu = !split_devs .empty ()&& !split_same ;// cleared by --split-skip-if-fits before any stage loads 2271bool split_own_auto = false;// #340: the split keeps own prompt buffers by its rule (not --no-prefill-borrow) 2272if (o .mmap_experts && !o .shared_expert_arena .empty ()) { 2273 std::fprintf (stderr ,"strata generate: --shared-expert-arena backs the resident arena and cannot be used with --mmap-experts\n" ); 2274return 2 ; 2275 } 2276if (o .resident_cpu_experts && (!o .mmap_experts || o .expert_profile .empty ())) { 2277 std::fprintf (stderr ,"strata generate: --resident-cpu-experts requires --mmap-experts and a static --expert-profile\n" ); 2278return 2 ; 2279 } 2280const bool remote_caches = o .expert_cache_remote [0 ]> 0 || o .expert_cache_remote [1 ]> 0 || 2281o .expert_cache_remote [2 ]> 0 ; 2282// A layer split keeps the resident RAM mode: every stage's GPU cache is left out of the RAM copy, and an adaptive 2283// swap copies an evicted expert back from the card that owns its layer (resident_stage_swaps). 2284if (o .resident_cpu_experts && remote_caches ) { 2285 std::fprintf (stderr ,"strata generate: --resident-cpu-experts does not support remote expert caches\n" ); 2286return 2 ; 2287 } 2288// the helper-GPU expert caches (--expert-cache-remote, docs/SECOND_GPU.md): CUDA1..3 on one GPU; with a layer 2289// split, the visible GPUs no stage runs on, in order 2290int remote_dev [3 ]= {1 ,2 ,3 }; 2291if (multi_gpu ) { 2292if (o .expert_profile .empty ()) { 2293 std::fprintf (stderr ,"strata generate: a layer split across GPUs needs --expert-profile\n" ); 2294return 2 ; 2295 } 2296// A STAGE'S PROMPT PATH BORROWS FROM THAT STAGE'S OWN EXPERT CACHE. This used to set 2297// `no_prefill_borrow = true` - "each stage's prompt path has its own buffers" - which is true, but it is 2298// a reason to give each stage its own LOAN, not a reason to make every stage withhold a chunk-sized 2299// reserve from its cache for the whole session. Forced on, it also collapsed `--prefill auto` to 2048 2300// (below) and skipped the lend arm, so a stage paid for its prompt buffers twice over: once in VRAM it 2301// never got back, once in the smaller chunk. At `--prefill 5524` that reserve is 3.8 GiB per stage, 2302// more than either 8 GB card had - which is how adding two GPUs to the two 12 GB ones lost 260K. 2303// The loan is the tail of the stage's own cache (see `PfPart` in the serve block); outside the prompt 2304// that tail is expert cache, so a large chunk costs a stage nothing permanent. 2305// #340 - BUT A LOAN IS NOT FREE PER REQUEST: every stage streams the lent experts during the prompt and 2306// copies them back after it, so on cards that hold (nearly) every expert of their layers a 2K prompt read 2307// 37% slower than 0.1.29's own buffers (2x RX 9070 XT / R9700: 1570 -> 990 tok/s; 2x A5000 in #340: -35%). 2308// So a split keeps 0.1.29's own buffers (2048-token chunks, priced into the split search) when they are a 2309// small part of every card - at most 12% of its VRAM (16 GB and larger cards) - and borrows on smaller cards, 2310// where the reserve would cost the cache (and the context) the paragraph above is about. Measured with own 2311// buffers on the 9070 XT + R9700: 2K 1588 tok/s, 16K 2006 (0.1.29 1568 / 1935, 0.1.31 993 / 1852). 2312// OPT-IN (the owner's choice for 0.1.32): own buffers change which experts a full card keeps resident, so the 2313// split's output differs from 0.1.31's; the default borrows as 0.1.31 did - with the concurrent refill and the 2314// 96-blob split ring that alone gave 2K +27%, 16K +5% over 0.1.31, decode unchanged, output identical. 2315// STRATA_SPLIT_OWN=auto: the 12% rule above; 1: own buffers on any cards; unset/0: borrow. 2316// --split-skip-if-fits keeps the loans (it can fall back to one GPU, which must stay as it is). 2317const char * own_env = std::getenv ("STRATA_SPLIT_OWN" ); 2318if (!o .no_prefill_borrow && !o .split_skip_if_fits && own_env != nullptr && own_env [0 ]!= '0' ) { 2319const char * v = std::string (own_env )== "auto" ?nullptr :own_env ; 2320bool own = v ?v [0 ]== '1' : true; 2321// the buffers of a 2048-token chunk (or the --prefill one) + a 96-blob ring (as split_pf_mib prices them) 2322const int64_t own_chunk = o .prefill_auto || o .prefill_chunk <=0 ?2048 :o .prefill_chunk ; 2323const int64_t reserve_mib = 160 + (own_chunk * 680 ) /1024 + 96 * 4 ; 2324 std::string why ; 2325if (!v ) { 2326 std::vector < int > devs = {0 }; 2327for (const int d :split_devs )devs .push_back (d ); 2328for (const int d :devs ) { 2329 dpct::device_info prop {}; 2330/* 2331DPCT1026: The call to cudaGetLastError was removed 2332because this functionality is redundant in SYCL. 2333*/ 2334if (DPCT_CHECK_ERROR ( 2335 dpct::get_device (d ).get_device_info (prop ))!= 0 ) { 2336 ;own = false;break ; 2337 } 2338const int64_t total_mib = 2339 (int64_t )(prop .get_global_mem_size () >>20 ); 2340if (reserve_mib * 100 > 12 * total_mib ) { 2341own = false; 2342why = "CUDA" + std::to_string (d )+ " has " + std::to_string (total_mib )+ " MiB" ; 2343break ; 2344 } 2345 } 2346 } 2347if (own ) { 2348o .no_prefill_borrow = true; 2349split_own_auto = true; 2350 std::fprintf (stderr ,"strata generate: layer split: every stage keeps its own prompt buffers (~%lld MiB " 2351"each, %lld-token chunks)%s\n" , (long long )reserve_mib , (long long )own_chunk , 2352v ?" (STRATA_SPLIT_OWN=1)" :"" ); 2353 }else if (!why .empty ()) { 2354 std::fprintf (stderr ,"strata generate: layer split: the prompt paths borrow from the caches (%s)\n" , 2355why .c_str ()); 2356 } 2357 } 2358int n_vis = 1 ; 2359if (DPCT_CHECK_ERROR (n_vis = dpct::device_count ())!= 0 || n_vis < 1 ) 2360n_vis = 1 ; 2361/* 2362DPCT1026: The call to cudaGetLastError was removed because this 2363functionality is redundant in SYCL. 2364*/ 2365int next_free = 1 ; 2366for (int r = 0 ;r < 3 ;++ r ) { 2367if (o .expert_cache_remote [(size_t )r ] <=0 )continue ; 2368while (next_free < n_vis && 2369 std::find (split_devs .begin (),split_devs .end (),next_free )!= split_devs .end ())++ next_free ; 2370if (next_free >=n_vis ) { 2371 std::fprintf (stderr ,"strata generate: --expert-cache-remote with a layer split needs a GPU that runs no " 2372"stage (%d visible, %zu used by the split)\n" ,n_vis ,split_devs .size ()+ 1 ); 2373return 2 ; 2374 } 2375remote_dev [r ]= next_free ++ ; 2376 } 2377 std::string devs ; 2378for (const int d :split_devs )devs += (devs .empty () ?"" :"," )+ std::to_string (d ); 2379 std::fprintf (stderr ,"strata generate: layer split across %zu GPUs: CUDA0, then CUDA%s (split %s)\n" , 2380split_devs .size ()+ 1 ,devs .c_str (),o .layer_split .c_str ()); 2381 } 2382// SYCL port (the B70, 2026-09-30): lending cache slots to the prompt path costs ~1 s per prompt (2,184 tokens: 2383// 610 vs 792 tok/s) but is what keeps every expert in VRAM at a long context - 80,000 tokens without it: the 2384// reserve for the KV and the chunk buffers evicts ~1,900 experts, prompt 790 tok/s and decode 2 tok/s after it; 2385// with it: 1,062 tok/s and 39.5 tok/s after it. So by default only above a 32K context; the flags still decide. 2386// (0.1.31-0.1.32: borrowing hung in the first chunk of a long prompt; the prompt path's stager waited on the copy 2387// queue's events from its own threads, which the Level Zero v2 adapter did not survive once its ring wrapped - 2388// prefill.cpp, Stager::issued_one. Fixed 2026-10-01: a 40K prompt borrowing reads at 1,144 tok/s and decodes at 2389// 69 tok/s after it, against 1,201 / 65 with its own buffers.) 2390// 2391// 2026-10-08 (the A770): borrowing is BROKEN on Alchemist. Its prompt buffers are carved from the top of the 2392// ~10 GiB expert-cache allocation, and oneMKL's BF16 GEMM reads a wrong tile when an operand lies more than 4 GiB 2393// into its allocation (docs/INTEL.md); the borrowed operands hit that, so from the first full prefill chunk the 2394// router read garbage and prefill failed ("prefill: routed id out of range") or the engine segfaulted (measured: 2395// a 236-token prompt, mirrored and mmap configs alike). Keep Alchemist's prompt path on its own buffers (its own 2396// allocation, reserved exactly by owned_prefill_mib) and keep an automatic chunk under 4 GiB, until the SYCL BLAS 2397// stages operands as the CUDA/HIP shims do. Battlemage keeps the old default (its long prompts were measured 2398// correct with borrowing). --prefill-borrow overrides, for testing the staging fix. A layer split keeps its rule. 2399if (!borrow_explicit ) { 2400static const bool alchemist = [] { 2401try { 2402// PCI device ids, the same table setup_intel.py uses: 56a0 A770, 56a1 A750, 56a2 A580, 56a5 A380, 2403// 56a6 A310, 5690 A770M 2404const unsigned id = dpct::get_current_device ().get_info < sycl::ext::intel::info::device::device_id > (); 2405// Only a card with room for an expert cache past 4 GiB can hit it: on an 8 GB A750 the cache was 0.34 GiB 2406// and the own-buffers reservation cost experts (prompt 72 -> 52 tok/s, decode -6%, 4K prompt, 4 rounds) 2407if (dpct::get_current_device ().get_info < sycl::info::device::global_mem_size > ()< (12ull <<30 ))return false; 2408switch (id & 0xffffu ) { 2409case 0x56a0 :case 0x56a1 :case 0x56a2 :case 0x56a5 :case 0x56a6 :case 0x5690 :return true; 2410default :return false; 2411 } 2412 }catch (...) {return false; } 2413 }(); 2414if (!multi_gpu && alchemist ) { 2415o .no_prefill_borrow = true; 2416if (o .prefill_auto && o .prefill_chunk > 2048 )o .prefill_chunk = o .prefill_auto_max = 2048 ; 2417 }else { 2418o .no_prefill_borrow = o .max_context <=32768 ; 2419 } 2420 } 2421#if defined(STRATA_USE_HIP ) 2422 { 2423// every GPU this run uses must be an architecture the binary has code for (a gfx1100 build on a gfx1201 2424// card would otherwise fail later with "invalid device function") 2425 std::vector < int > used {0 }; 2426if (multi_gpu )used .insert (used .end (),split_devs .begin (),split_devs .end ()); 2427for (int r = 0 ;r < 3 ;++ r ) 2428if (o .expert_cache_remote [(size_t )r ]> 0 )used .push_back (remote_dev [r ]); 2429for (const int d :used ) { 2430if (const std::string why = strata::core::gpu_arch_problem (d ); !why .empty ()) { 2431 std::fprintf (stderr ,"strata generate: %s\n" ,why .c_str ()); 2432return 1 ; 2433 } 2434 } 2435 } 2436#endif 2437if (o .prefill_auto && (o .no_prefill_borrow || o .expert_profile .empty ())) { 2438o .prefill_auto = false;// nothing to lend from: the buffers are reserved for the session, so keep them small 2439o .prefill_chunk = 2048 ; 2440 } 2441if (!have_tokens && o .serve ) {// plan v0.3 P8: requests bring their own tokens 2442o .tokens = {248045 }; 2443o .max_new = 1 ; 2444have_tokens = true; 2445o .stop_eos = true; 2446 } 2447if (!have_tokens ) { 2448 std::fprintf (stderr ,"strata generate: --tokens is required (this build has no tokenizer; see the " 2449"header of src/program/generate.cpp)\n" ); 2450usage (); 2451return 2 ; 2452 } 2453 2454if ((o .ple_io != "direct" && o .ple_io != "mmap" && o .ple_io != "ram" )|| o .ple_row_cache < 0 || o .ple_inflight < 1 || 2455o .ple_inflight > 1024 || !(o .ple_delay_us >=0 )) { 2456 std::fprintf (stderr ,"strata generate: invalid --ple-io/--ple-row-cache/--ple-inflight/--ple-delay-us\n" ); 2457return 2 ; 2458 } 2459#if defined(_WIN32 ) 2460if (o .ple_io == "ram" ) { 2461 std::fprintf (stderr ,"strata generate: --ple-io ram is not available on Windows (no mlock); use --ple-io mmap\n" ); 2462return 2 ; 2463 } 2464#endif 2465if (o .kv == "q4" )o .kv = "q4_0" ; 2466if (o .kv != "fp16" && o .kv != "int8" && o .kv != "q4_0" && o .kv != "k8v4" ) { 2467 std::fprintf (stderr ,"strata generate: --kv must be fp16, int8, q4_0 or k8v4\n" ); 2468return 2 ; 2469 } 2470 strata::core::qsa_set_kv_int8 (o .kv == "int8" ); 2471 strata::core::qsa_set_kv_q4 (o .kv == "q4_0" );// PR #21: 4-bit codes after a Hadamard rotation (kv_q4.hpp) 2472// STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation --kv q4_0 already uses. Opt-in: first-token KL to 2473// fp16 K/V improved on an NVFP4 pack (0.0066 -> 0.0051) but not on IQ2_XS (0.0022 -> 0.0054) 2474const char * kv_rot = std::getenv ("STRATA_KV_ROT" ); 2475 strata::core::qsa_set_kv_int8_rotate (kv_rot != nullptr && kv_rot [0 ]== '1' ); 2476if (kv_rot != nullptr && kv_rot [0 ]== '1' && o .kv == "int8" ) 2477 std::fprintf (stderr ,"strata generate: STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation (opt-in)\n" ); 2478 strata::core::qsa_set_kv_hybrid (o .kv == "k8v4" );// K8V4: INT8 K + rotated Q4_0 V, 816 B/cell 2479if (o .kv_resident < 0 ) { 2480 std::fprintf (stderr ,"strata generate: --kv-resident must be >= 0\n" ); 2481return 2 ; 2482 } 2483 strata::core::qsa_set_kv_resident (o .kv_resident ); 2484// Prompt lookup (the suffix drafter, on by default): the MTP keeps its --spec windows and a lookup window may be 2485// up to 2 tokens longer; the draft policy (strata/spec/draft_policy.hpp) takes one only where it pays. Code 2486// edits +6-11%, ordinary text unchanged (bench/results/2026-09-27-spec). --suffix-draft 0 turns it off. 2487if (o .suffix_draft > 0 && o .spec >=2 && o .mtp_max_t == 0 ) { 2488o .mtp_max_t = o .spec ; 2489o .spec = std::min (o .spec + 2 ,8 );// kVerifyMaxT 2490 } 2491// --lookup-chain (opt-in): the MTP keeps its windows; a lookup chained after its drafts may lengthen one by up to K 2492if (o .lookup_chain > 0 && o .spec >=2 ) { 2493if (o .mtp_max_t == 0 )o .mtp_max_t = o .spec ; 2494o .spec = std::max (o .spec , std::min (o .mtp_max_t + o .lookup_chain ,8 ));// kVerifyMaxT 2495 } 2496 strata::spin_drafts_need_long_bound (o .spec >=2 && o .mtp .empty ());// spin_max: drafting without MTP waits long 2497 strata::core::layer_set_shared_early (!o .shared_late ); 2498if (!o .native_preset .empty ()) { 2499try { 2500// every shard of the model (<name>-0000N-of-0000M.gguf beside --native). A missing shard is an error 2501// here: it used to be skipped, leaving a model with some tensors absent and a later error, or none. 2502o .native_shards = strata::gguf_split_paths (o .native_preset ); 2503// a model family Strata recognises but has no engine path for yet (Qwen3.6-35B-A3B) is refused here, 2504// with a message that says so, before anything else about the file is judged 2505 { 2506const strata::GgufFile meta (o .native_shards .front ()); 2507const std::string why = strata::model_family_not_supported (strata::model_family (meta )); 2508if (strata::model_family (meta )!= strata::ModelFamily ::Unknown && !why .empty ()) { 2509 std::fprintf (stderr ,"strata generate: --native %s: %s\n" ,o .native_preset .c_str (),why .c_str ()); 2510return 2 ; 2511 } 2512 } 2513// --ple-gguf defaults to the shard that holds the PLE table, found by name: shard 2 of the ISTA files 2514// and of Unsloth's UD-Q4_K_XL, shard 1 of Swift's 2515if (o .ple_gguf .empty ()&& !o .no_ple ) { 2516const strata::GgufModel model (o .native_shards ); 2517size_t at = 0 ; 2518if (model .find ("per_layer_token_embd.weight" ,& at )!= nullptr )o .ple_gguf = o .native_shards [at ]; 2519 } 2520 }catch (const std::exception & e ) { 2521 std::fprintf (stderr ,"strata generate: --native %s: %s\n" ,o .native_preset .c_str (),e .what ()); 2522return 2 ; 2523 } 2524if (o .no_ple || o .ple_gguf .empty ()) { 2525 std::fprintf (stderr ,"strata generate: --native requires --ple-gguf (the PLE key is native too), and no " 2526"shard of the model holds per_layer_token_embd.weight\n" ); 2527return 2 ; 2528 } 2529o .stream_token = true; 2530o .gr_native_mmvf = true; 2531o .native_bf16 = o .native_bf16_extra = true; 2532o .native_ple_key = o .native_moe_combine = o .native_gdn = o .native_router = true; 2533o .native_qsa = o .native_qsa_indexer = o .native_rope = o .native_ple_postops = true; 2534if (o .native_head_gguf .empty ())o .native_head_gguf = o .native_preset ; 2535if (o .native_dense_gguf .empty ()) { 2536// every shard of the model (<name>-0000N-of-0000M.gguf beside --native), then the PLE shard: a split 2537// may put any layer in any shard (Swift's GGUFs: layers 13-47 in shard 2, the PLE table in shard 1) 2538o .native_dense_gguf = o .native_shards ; 2539// a PLE-only table (tools/ple_fp8_pack.py: architecture strata-ple) holds no projections 2540bool ple_only = false; 2541try { 2542 strata::GgufFile pg (o .ple_gguf ); 2543if (const strata::MetaValue * v = pg .get ("general.architecture" ))ple_only = v -> s == "strata-ple" ; 2544 }catch (const std::exception & ) {} 2545if (!ple_only && 2546 std::find (o .native_dense_gguf .begin (),o .native_dense_gguf .end (),o .ple_gguf )== o .native_dense_gguf .end ()) 2547o .native_dense_gguf .push_back (o .ple_gguf ); 2548 } 2549// Plan v0.3 (24 Sep): the CPU experts stay on the VNNI kernel. The llama.cpp-CPU-exact q8_0 contract 2550// cost 27.0 vs 17.2 ms/token of pool time and G-C does not need it; `--cpu-oracle-q8-0` still selects it. 2551 } 2552if (o .logits_stride > 1 && (o .max_new != 1 || o .dump_logits .empty ())) { 2553 std::fprintf (stderr ,"strata generate: --logits-stride > 1 requires --max-new 1 and --dump-logits\n" ); 2554return 2 ; 2555 } 2556if (o .no_ple && !o .ple_gguf .empty ()) { 2557 std::fprintf (stderr ,"strata generate: --no-ple and --ple-gguf are mutually exclusive\n" ); 2558return 2 ; 2559 } 2560if (o .native_ple_postops && o .no_ple ) { 2561 std::fprintf (stderr ,"strata generate: --native-ple-postops requires PLE enabled\n" ); 2562return 2 ; 2563 } 2564if (!o .no_ple && o .ple_gguf .empty ()) { 2565 std::fprintf (stderr ,"strata generate: --ple-gguf is required; --no-ple explicitly enables a diagnostic ablation\n" ); 2566return 2 ; 2567 } 2568// P7 audit: positions, cells and pooled-block indices are cast to int32 on the device path. 2569if (o .max_context > 2147483647LL - 8 ) { 2570 std::fprintf (stderr ,"strata generate: --max-context must be below 2^31\n" ); 2571return 2 ; 2572 } 2573if (o .max_new <=0 || o .max_context <=0 || o .max_new > o .max_context || 2574o .tokens .size ()> (size_t ) (o .max_context - o .max_new )) { 2575 std::fprintf (stderr ,"strata generate: positive --max-new and --max-context must fit the prompt and generation\n" ); 2576return 2 ; 2577 } 2578// THE ROPE KNOBS (rope_scaling.hpp). Anything invalid dies here, at second zero, rather than becoming a 2579// NaN angle inside one of the twelve QSA layers. Only the RANGES are checked - the config itself is 2580// resolved after the model file has had its say, right before session_init. 2581 strata::kernels::RopeScaling rope_cfg ;// type filled here; the rest at the resolution below 2582 { 2583using RST = strata::kernels::RopeScalingType ; 2584// an absent --rope-scaling (the empty default) leaves the type to the model file's rope keys, 2585// resolved below; anything present must be one of the three names 2586if (o .rope_scaling == "none" )rope_cfg .type = RST ::None ; 2587else if (o .rope_scaling == "linear" )rope_cfg .type = RST ::Linear ; 2588else if (o .rope_scaling == "yarn" )rope_cfg .type = RST ::YaRN ; 2589else if (!o .rope_scaling .empty ()) { 2590 std::fprintf (stderr ,"strata generate: --rope-scaling must be none, linear or yarn (got '%s')\n" , 2591o .rope_scaling .c_str ()); 2592return 2 ; 2593 } 2594// every knob FINITE first: `atof("nan")` is NaN, and a NaN passes every range comparison below 2595for (const double v : {o .rope_scale ,o .rope_freq_base ,o .rope_freq_scale ,o .yarn_orig_ctx ,o .yarn_ext_factor , 2596o .yarn_attn_factor ,o .yarn_beta_fast ,o .yarn_beta_slow }) 2597if (!std::isfinite (v )) { 2598 std::fprintf (stderr ,"strata generate: a rope scaling knob is not a finite number (%g)\n" ,v ); 2599return 2 ; 2600 } 2601// 0 is the absent default; an explicit factor must extend, not shrink 2602if (o .rope_scale != 0 && o .rope_scale < 1.0 ) { 2603 std::fprintf (stderr ,"strata generate: --rope-scale %g must be >= 1 (it extends the context, not shrinks it)\n" , 2604o .rope_scale ); 2605return 2 ; 2606 } 2607if (o .rope_freq_base != 0 && o .rope_freq_base <=1.0 ) { 2608 std::fprintf (stderr ,"strata generate: --rope-freq-base must be a base above 1 (0 = the model's)\n" ); 2609return 2 ; 2610 } 2611if (o .rope_freq_scale < 0 || o .yarn_orig_ctx < 0 || o .yarn_ext_factor < -1.0 || o .yarn_attn_factor <=0 || 2612o .yarn_beta_fast <=0 || o .yarn_beta_slow <=0 ) { 2613 std::fprintf (stderr ,"strata generate: invalid rope scaling knob (see usage: --yarn-ext-factor <0 = auto, " 2614"--yarn-orig-ctx 0 = default, the rest positive)\n" ); 2615return 2 ; 2616 } 2617 } 2618if (!std::isfinite (o .temperature )|| o .temperature < 0 || !std::isfinite (o .top_p )|| 2619o .top_p <=0 || o .top_p > 1 || o .top_k < 0 || o .expert_cache < -1 || 2620o .pool_workers < 0 || std::any_of (o .expert_cache_remote .begin (),o .expert_cache_remote .end (), 2621 [](int slots ) {return slots < 0 ; })|| 2622 (o .expert_cache_remote [1 ]> 0 && o .expert_cache_remote [0 ]== 0 )|| 2623 (o .expert_cache_remote [2 ]> 0 && o .expert_cache_remote [1 ]== 0 )) { 2624 std::fprintf (stderr ,"strata generate: invalid sampling or resource parameter\n" ); 2625return 2 ; 2626 } 2627if (o .expert_cache_remote_placement != "stripe" && o .expert_cache_remote_placement != "layer" ) { 2628 std::fprintf (stderr ,"strata generate: --expert-cache-remote-placement must be stripe or layer\n" ); 2629return 2 ; 2630 } 2631if (o .remote_expert_opt && !o .serve ) { 2632 std::fprintf (stderr ,"strata generate: --remote-expert-opt requires --serve\n" ); 2633return 2 ; 2634 } 2635// the peer tier is the second card's only user: a layer split or a remote expert cache would put a second engine 2636// part (and a second copy of the same experts) on it 2637if (o .peer_device >=1 && (!o .layer_split .empty ()|| o .expert_cache_remote [0 ]> 0 )) { 2638 std::fprintf (stderr ,"strata generate: --peer-device cannot be combined with %s\n" , 2639 !o .layer_split .empty () ?"--layer-split (use one or the other)" 2640 :"--expert-cache-device1..3 (the peer tier already caches experts there)" ); 2641return 2 ; 2642 } 2643 2644if (o .native_flash_attn_short && o .max_context > 256 ) { 2645 std::fprintf (stderr ,"strata generate: --native-flash-attn-short requires --max-context <=256\n" ); 2646return 2 ; 2647 } 2648if (o .native_flash_attn_short && (o .gpu_only_full || o .graph_only || o .gpu_stages )) { 2649 std::fprintf (stderr ,"strata generate: --native-flash-attn-short requires the normal decode loop for status validation\n" ); 2650return 2 ; 2651 } 2652// The whole-model graph measurements replay every layer through CUDA0's session, which a layer split carves to 2653// CUDA0's own range - the answer would read another stage's state. Refused here rather than at the call, so 2654// the reason is visible before 55 GB is loaded. 2655if (multi_gpu && (o .gpu_only_full || o .gpu_stages )) { 2656 std::fprintf (stderr ,"strata generate: --gpu-only-full and --gpu-stages replay the whole model through one " 2657"session, which a layer split does not have; run them without --layer-split\n" ); 2658return 2 ; 2659 } 2660if (!o .native_head_gguf .empty ()) { 2661try { 2662o .native_head_shards = o .native_head_gguf == o .native_preset ?o .native_shards 2663 : strata::gguf_split_paths (o .native_head_gguf ); 2664 }catch (const std::exception & e ) { 2665 std::fprintf (stderr ,"strata generate: --native-head-gguf %s: %s\n" ,o .native_head_gguf .c_str (),e .what ()); 2666return 2 ; 2667 } 2668 } 2669if (o .native_ple_key && (o .native_dense_gguf .empty ()|| o .no_ple )) { 2670 std::fprintf (stderr ,"strata generate: --native-ple-key requires PLE and --native-dense-gguf\n" ); 2671return 2 ; 2672 } 2673if (o .cpu_oracle_q8_0 && (o .expert_cache != 0 || !o .expert_profile .empty ())) { 2674 std::fprintf (stderr ,"strata generate: --cpu-oracle-q8-0 cannot be combined with --expert-cache or --expert-profile until the GPU expert contract matches\n" ); 2675return 2 ; 2676 } 2677 2678// **BEFORE ANYTHING ELSE.** The CPU expert kernel is AVX-512 (VNNI + VBMI) and its translation unit is 2679// compiled `/arch:AVX512`, so on a CPU without those features it does not fail - it executes an illegal 2680// instruction at some unpredictable token. Refusing at second zero is the whole point of P2.S3's check. 2681 strata::kernels::cpu::expert_set_oracle_q8_0 (o .cpu_oracle_q8_0 ); 2682// ... and nothing runs on a CPU without AVX2: every CPU expert kernel is AVX2 at least (the AVX-512 ones are 2683// chosen above it), and so is ggml-cpu in the release build, which the native pack's layout load initializes 2684// next. Refused here, by name, rather than an illegal instruction in the first expert. 2685// The experimental older-CPU build (STRATA_ISA_FLOOR=avx|none, compiled on that PC; #394 #595 #623) has ggml-cpu 2686// for that floor, so a native pack's experts run there on ggml-cpu (every AVX2 kernel is behind cpu_avx2_ok). 2687const char * isa_floor = strata::kernels::cpu::isa_floor_build (); 2688if (!strata::kernels::cpu::cpu_avx2_ok ()&& isa_floor [0 ]== '\0' ) { 2689 std::fprintf (stderr ,"strata generate: this CPU (%s) does not support AVX2 with FMA and F16C, which this engine's " 2690"CPU expert kernels need; Strata runs on Intel Haswell (2013), AMD Zen (2017) or newer. " 2691"Older CPUs are EXPERIMENTAL and slow: setup compiles an engine for them on this PC " 2692"(STRATA_ISA_FLOOR, see \"Older CPUs\" in docs/INSTALL.md)\n" , 2693 strata::kernels::cpu::cpu_name ().c_str ()); 2694return 2 ; 2695 } 2696if (isa_floor [0 ]!= '\0' ) { 2697const bool avx_floor = std::strcmp (isa_floor ,"avx" )== 0 ; 2698if (avx_floor ? !strata::kernels::cpu::cpu_avx1_ok () : !strata::kernels::cpu::cpu_sse42_ok ()) { 2699 std::fprintf (stderr ,"strata generate: this engine is the older-CPU build for %s, which this CPU (%s) does " 2700"not have%s\n" ,avx_floor ?"AVX" :"SSE4.2 with POPCNT" , 2701 strata::kernels::cpu::cpu_name ().c_str (), 2702avx_floor ?"; compile it with STRATA_ISA_FLOOR=none" :"" ); 2703return 2 ; 2704 } 2705if (!strata::kernels::cpu::cpu_avx2_ok ()) 2706 std::fprintf (stderr ,"strata generate: EXPERIMENTAL older-CPU build (ggml-cpu for %s): this CPU has no AVX2, " 2707"so the CPU's experts run on ggml-cpu's kernels - expect it to be slow\n" ,isa_floor ); 2708else 2709 std::fprintf (stderr ,"strata generate: this is the older-CPU build (ggml-cpu for %s); this CPU has AVX2, " 2710"and the normal build is faster on it\n" ,isa_floor ); 2711 } 2712 2713 std::string err ; 2714if (!o .native_head_gguf .empty ()&& !o .stream_token ) { 2715 std::fprintf (stderr ,"--native-head-gguf requires --stream-token\n" ); 2716return 2 ; 2717 } 2718// Plan v0.3 P6: where the experts live. A native pack (tools/iq_pack.py: the IQ2_XS / IQ3_XXS files) keeps 2719// every quantized tensor in its GGUF form, so it needs --native (the dense projections, head and embedding 2720// come from the model file) and runs its experts in verify windows only (--spec). 2721 { 2722const strata::core::ModelGeometry & g0 = strata::core::kCompiledGeometry ; 2723if (!strata::kernels::cpu::expert_layout_load (o .pack ,g0 .n_layers ,g0 .n_expert ,err )) { 2724 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 2725return 1 ; 2726 } 2727// Every layer's formats must have GPU expert kernels and a prompt-path dequantizer, checked here, before 2728// anything is allocated: an unsupported down type used to exit from inside the first verify window, and 2729// an unsupported dequant type left the prompt path's fp16 buffer unwritten. 2730const auto & lay = strata::kernels::cpu::expert_layout (); 2731for (int64_t l = 0 ;lay .native && l < (int64_t )lay .fmt .size ();++ l ) { 2732const auto & f = lay .fmt [(size_t )l ]; 2733if (!strata::kernels::native_expert_supported (f .gu_type ,f .d_type ,f .n_embd ,f .n_ff )) { 2734 std::fprintf (stderr ,"strata generate: layer %lld's experts are %s/%s (ggml types %d/%d), which this " 2735"engine has no GPU kernels for\n" , (long long )l , 2736 strata::ggml_type_name ((uint32_t )f .gu_type ), strata::ggml_type_name ((uint32_t )f .d_type ), 2737f .gu_type ,f .d_type ); 2738return 1 ; 2739 } 2740 } 2741// APR (prism.hadamard) packs (Gyro): every expert path rotates its activations (CPU pool: native_quant_act / _h; 2742// GPU verify and the prompt's FP16 chain: hadamard_rows). Validated on the Arc A750 (SYCL, JIT build). 2743if (strata::kernels::cpu::hadamard_spec ().any ()) 2744 std::fprintf (stderr ,"strata generate: APR pack: Hadamard-folded experts (block %d)\n" , 2745 strata::kernels::cpu::hadamard_spec ().block ); 2746 } 2747const bool native_pack = strata::kernels::cpu::expert_layout ().native ; 2748// STRATA_EARLY_REMOTE_CONTEXTS=1: create EVERY secondary context here, like CUDA1's. Under WSL2 the driver's 2749// pinned/mapped host budget (dxg gpadl, ~1 GiB) is spent by CUDA0's weights and MTP before the later loop runs, 2750// and a new context then fails with cudaErrorMemoryAllocation (CUDA2: "cudaSetDevice(2) failed: out of memory"). 2751const char * early_env = std::getenv ("STRATA_EARLY_REMOTE_CONTEXTS" ); 2752const bool early_remote = early_env && early_env [0 ]== '1' ; 2753for (int r = 0 ;r < 3 ;++ r )if (o .expert_cache_remote [(size_t )r ]> 0 && (r == 0 || early_remote )) { 2754// Keep CUDA1's proven startup order: initialise its context before 2755// allocating GPU0 weights or mapping the large host expert arena. 2756double free_gib = 0 ; 2757if (!strata::core::RemoteExperts ::preflight (remote_dev [r ],free_gib ,err )) { 2758 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 2759return 1 ; 2760 } 2761 std::fprintf (stderr ,"strata generate: CUDA%d context ready, %.2f GiB free before expert arena registration\n" , 2762remote_dev [r ],free_gib ); 2763 } 2764// plan v0.3 P6: the PCIe share of the missed experts, measured per kind of pack (the paper, finding on PCIe). 2765// PR #44: a x8 link carries half of what the native default assumes - the GPU's SMs read that share over the 2766// link (the copy kernel, since 0.1.14), so on a slower link it must shrink or the window waits for it. The 2767// real H2D bandwidth is probed once; from 20 GB/s up (x16 PCIe 4/5) the measured default stays. The canonical 2768// pack's 0.2 was never measured against the link, so it is left alone. `--calibrate` measures it outright. 2769const bool pcie_explicit = o .pcie_frac >=0.0 ; 2770if (o .pcie_frac < 0.0 ) { 2771const double base = native_pack ?0.55 :0.2 ; 2772 std::string bursts ; 2773const double bw = native_pack ?probe_pcie_h2d_gbps (& bursts ,multi_gpu ) :-1.0 ; 2774if (!native_pack ) { 2775o .pcie_frac = base ; 2776 }else if (bw > 0.0 ) { 2777// Gyro's trellis experts: the CPU pool decodes them at ~8 GB/s (48 cycles a block on AVX2, compute bound, a third of the 2778// i-quants' rate), so the link carries a bigger share of the misses than the 20 GB/s reference says. Measured on the 2779// Arc A750 (10.5 GB/s link): 0.29 -> 12.8 tok/s, 0.45 -> 15.5, 0.60 -> 15.2 (5 interleaved pairs each). The reference 2780// for these packs is 12 GB/s: 10.5 GB/s gives 0.48; from 12 GB/s up the measured 0.55 stays. 2781bool trellis = false; 2782 { 2783const auto & lay = strata::kernels::cpu::expert_layout (); 2784for (size_t l = 0 ;lay .native && l < lay .fmt .size ();++ l )trellis = trellis || lay .fmt [l ].gu_type >=144 ; 2785 } 2786o .pcie_frac = pcie_frac_for_gbps (bw ,base ,trellis ?12.0 :20.0 ); 2787 std::fprintf (stderr ,"strata generate: PCIe probe: %.1f GB/s host->device (best of %s) -> pcie_frac %.2f " 2788"(default %.2f)\n" ,bw ,bursts .c_str (),o .pcie_frac ,base ); 2789 {// PcieAuto on SYCL: opt-in (STRATA_PCIE_FRAC_DEFAULT=auto), one card, not the xe NO_HOST path 2790const char * pfd = std::getenv ("STRATA_PCIE_FRAC_DEFAULT" ); 2791o .pcie_frac_auto = pfd != nullptr && std::strcmp (pfd ,"auto" )== 0 && o .layer_split .empty (); 2792o .pcie_probe_gbps = bw ; 2793 } 2794 }else { 2795o .pcie_frac = base ; 2796 std::fprintf (stderr ,"strata generate: PCIe probe failed -> pcie_frac default %.2f\n" ,base ); 2797 } 2798 } 2799// SYCL port, Arc on the xe driver (Arc Pro B60/B65/B70, B580): the GPU page-faults when a kernel reads ordinary 2800// (pageable) host memory, and the card times the job out (seen on a B70: Timedout job, Fault response -EINVAL, 2801// faulted address in the CPU's mmap range). Without --stream-experts the experts outside the VRAM cache stay in a 2802// pageable arena that the PCIe share (--pcie-frac) hands to the GPU. Recommend, never force: the default share 2803// becomes 0 (the CPU computes those misses) and an explicit --pcie-frac is kept with a warning. 2804if (strata::intel_gpu_driver ()== "xe" && !o .stream_experts ) { 2805if (!pcie_explicit ) { 2806o .pcie_frac = 0.0 ; 2807 std::fprintf (stderr ,"strata generate: xe driver without --stream-experts: the GPU faults on pageable host " 2808"memory, so --pcie-frac defaults to 0 here (the CPU computes the experts outside VRAM). " 2809"Use --stream-experts, as setup configures it, to let the GPU read a pinned mirror\n" ); 2810 }else if (o .pcie_frac > 0.0 ) { 2811 std::fprintf (stderr ,"strata generate: WARNING: --pcie-frac %.2f on the xe driver without --stream-experts " 2812"makes the GPU read pageable host memory; that page-faulted and hung an Arc Pro B70 " 2813"(Timedout job, device lost). Use --stream-experts, as setup configures it, or " 2814"--pcie-frac 0\n" ,o .pcie_frac ); 2815 } 2816 } 2817// the canonical Q2_0 pack's CPU kernels are AVX-512 only; a native pack runs on AVX2 CPUs as well 2818if (!native_pack ) { 2819// #2347 (the CUDA engine has this too): a --pack folder without native_experts.txt is read as the canonical Q2_0 pack, whose CPU 2820// kernel needs AVX-512; on an AVX2 CPU (Ryzen 5000, Intel 12th-14th gen) that reads as "this CPU is too old" when the folder is 2821// simply not the native pack (a half-built pack, the wrong folder). Say so before the refusal. 2822if (!strata::kernels::cpu::cpu_features ().usable ()) { 2823 std::error_code ec ; 2824const std::filesystem::path pk (o .pack ); 2825 std::fprintf (stderr ,"strata generate: %s has no native_experts.txt, so it is read as the canonical Q2_0 " 2826"pack, whose CPU kernel needs AVX-512.\n" 2827" An NVFP4, i-quant or Unsloth pack has that file in the folder given as --pack " 2828"and runs on an AVX2 CPU as well;\n" , 2829o .pack .c_str ()); 2830if (std::filesystem::exists (pk /"pack" /"native_experts.txt" ,ec )) 2831 std::fprintf (stderr ," it is in %s: use that folder as --pack.\n" , (pk /"pack" ).generic_string ().c_str ()); 2832else 2833 std::fprintf (stderr ," if this is one of those packs, the folder is incomplete or the wrong one " 2834"(build it again with tools/iq_pack.py, or run setup again).\n" ); 2835 } 2836 strata::kernels::cpu::cpu_require_expert_support (); 2837 }else if (!strata::kernels::cpu::cpu_avx512_ok ()) 2838 std::fprintf (stderr ,"strata generate: this CPU has no AVX-512: the expert kernels run on %s " 2839"(multi-token for the i-quant gate/up rows)\n" , 2840 !strata::kernels::cpu::cpu_avx2_ok () ?"ggml-cpu vec_dot (no AVX2: the older-CPU build)" 2841 : std::getenv ("STRATA_NO_IQ256" )== nullptr ?"AVX-2" :"ggml-cpu vec_dot (STRATA_NO_IQ256 set)" ); 2842// the compiled shape; a native model's file replaces it below with its own metadata (read_geometry), which a 2843// pruned variant (GSQ-RCO Coder, fewer than 512 experts) differs from 2844 strata::core::ModelGeometry g = strata::core::kCompiledGeometry ; 2845 strata::kernels::PleConsts ple_consts_run = strata::kernels::ple_artifact_consts ();// the model file's PLE hash constants when it has them 2846int64_t K = g .n_expert_used ; 2847// THE ROPE CONFIG RESOLVES HERE, BEFORE ANY WEIGHT MOVES - the CLI and the model file have both spoken, 2848// and `session_init` below builds the rope table from it and captures the kernels reading its constants 2849// (rope_scaling.hpp); the only hard constraint is "set before that", and dying on a bad rope key beats 2850// scanning gigabytes of shards first. Precedence: an EXPLICIT flag over the model file's rope keys over 2851// the struct defaults. The empty --rope-scaling and the 0 --rope-scale mean the flag is absent, so the 2852// model file decides; an explicit value - `none` and `1` included, the opt-outs - wins over the model file. 2853 { 2854// The model file's rope keys (llama.cpp's names under the arch prefix), when it carries any - the 2855// artifact today ships none, so this is a no-op defaults channel for future fine-tunes. 2856 std::string gguf_rope_type ; 2857double gguf_rope_base = 0 ,gguf_rope_factor = 0 ,gguf_rope_orig_ctx = 0 ; 2858if (!o .native_preset .empty ()) { 2859// The geometry is the model file's (core::geometry_from_gguf: every "<arch>.*" shape key), checked 2860// against the shapes this engine's kernels are built for. The expert count and top-k are run-time 2861// sizes: a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10. 2862try { 2863 strata::GgufFile model_gguf (o .native_shards .front ());// the metadata shard 2864 std::string gerr ; 2865if (!strata::core::geometry_from_gguf (model_gguf ,g ,K ,gerr )) { 2866 std::fprintf (stderr ,"strata generate: %s\n" ,gerr .c_str ()); 2867return 1 ; 2868 } 2869const std::string mismatch = strata::core::compiled_geometry_mismatch (g ); 2870if (!mismatch .empty ()) { 2871 std::fprintf (stderr ,"strata generate: %s: %s\n" ,o .native_preset .c_str (),mismatch .c_str ()); 2872return 1 ; 2873 } 2874const std::string p = std::string (strata::model_family_arch (g .family ))+ "." ; 2875if (const strata::MetaValue * v = model_gguf .get (p + "rope.freq_base" ))gguf_rope_base = v -> num (); 2876if (const strata::MetaValue * v = model_gguf .get (p + "rope.scaling.type" ))gguf_rope_type = v -> s ; 2877if (const strata::MetaValue * v = model_gguf .get (p + "rope.scaling.factor" ))gguf_rope_factor = v -> num (); 2878if (const strata::MetaValue * v = model_gguf .get (p + "rope.scaling.original_context_length" )) 2879gguf_rope_orig_ctx = v -> num (); 2880// The PLE hash constants (multipliers, head sizes, head offsets) when the file carries them; the artifact's 2881// own values stay the default for a file that does not. 2882 { 2883auto arr = [& ](const char * k , std::vector < uint64_t >& out ) { 2884const strata::MetaValue * v = model_gguf .get (p + k ); 2885if (v == nullptr || v -> type != strata::MetaType ::ARRAY )return false; 2886for (const strata::MetaValue & e :v -> items )out .push_back (e .u ); 2887return true; 2888 }; 2889 std::vector < uint64_t > pm ,pv ,po ; 2890const bool a1 = arr ("ple.layer_multipliers" ,pm ),a2 = arr ("ple.head_vocab_sizes" ,pv ),a3 = arr ("ple.head_offsets" ,po ); 2891if (a1 || a2 || a3 ) { 2892 std::string perr ; 2893if (!(a1 && a2 && a3 )|| !strata::kernels::ple_consts_from_arrays (pm ,pv ,po ,0 ,ple_consts_run ,perr )) { 2894 std::fprintf (stderr ,"strata generate: %s: the PLE hash constants in the model file are not usable: %s\n" , 2895o .native_preset .c_str (), (a1 && a2 && a3 ) ?perr .c_str () :"one of the three arrays is missing" ); 2896return 1 ; 2897 } 2898 } 2899 } 2900 }catch (const std::exception & e ) { 2901 std::fprintf (stderr ,"strata generate: reading the model's geometry from %s: %s\n" , 2902o .native_preset .c_str (),e .what ()); 2903return 1 ; 2904 } 2905 } 2906using RST = strata::kernels::RopeScalingType ; 2907if (!o .rope_scaling .empty ()) { 2908// the early validation pinned the spelling; `none` here is the CLI opting OUT of the model file's keys 2909if (o .rope_scaling == "linear" )rope_cfg .type = RST ::Linear ; 2910else if (o .rope_scaling == "yarn" )rope_cfg .type = RST ::YaRN ; 2911else rope_cfg .type = RST ::None ; 2912 }else if (!gguf_rope_type .empty ()) { 2913if (gguf_rope_type == "linear" )rope_cfg .type = RST ::Linear ; 2914else if (gguf_rope_type == "yarn" )rope_cfg .type = RST ::YaRN ; 2915else if (gguf_rope_type != "none" ) { 2916 std::fprintf (stderr ,"strata generate: %s carries rope.scaling.type '%s' - none, linear or yarn only\n" , 2917o .native_preset .c_str (),gguf_rope_type .c_str ()); 2918return 2 ; 2919 } 2920 } 2921if (o .rope_scale > 0 )rope_cfg .factor = o .rope_scale ;// an explicit factor, 1 included 2922else if (gguf_rope_factor > 1.0 )rope_cfg .factor = gguf_rope_factor ; 2923if (o .rope_freq_base > 0 )rope_cfg .freq_base = o .rope_freq_base ; 2924else if (gguf_rope_base > 1.0 )rope_cfg .freq_base = gguf_rope_base ; 2925if (o .yarn_orig_ctx > 0 )rope_cfg .orig_ctx = o .yarn_orig_ctx ; 2926else if (gguf_rope_orig_ctx >=1 )rope_cfg .orig_ctx = gguf_rope_orig_ctx ; 2927rope_cfg .freq_scale_in = o .rope_freq_scale ; 2928rope_cfg .ext_factor = o .yarn_ext_factor >=0 ?o .yarn_ext_factor 2929 : (rope_cfg .type == RST ::YaRN ?1.0 :0.0 ); 2930rope_cfg .attn_factor = o .yarn_attn_factor ; 2931rope_cfg .beta_fast = o .yarn_beta_fast ; 2932rope_cfg .beta_slow = o .yarn_beta_slow ; 2933if (rope_cfg .type == RST ::None ) { 2934// none is the trained rotation, exactly: the scaling knobs are inert (the table builder and 2935// `kernel_args` ignore them), and resetting them keeps the logged/queried config honest. Only the 2936// frequency base survives - it is the rotation itself, not a scaling knob. 2937const bool knobs = o .rope_scale > 1.0 || o .rope_freq_scale > 0 || o .yarn_ext_factor > 0 || 2938o .yarn_attn_factor != 1.0 ; 2939const double base = rope_cfg .freq_base ; 2940rope_cfg = strata::kernels::RopeScaling {}; 2941rope_cfg .freq_base = base ; 2942if (knobs ) 2943 std::fprintf (stderr ,"strata generate: note: no rope scaling is active (none), so --rope-scale, " 2944"--rope-freq-scale and the --yarn-* knobs have no effect\n" ); 2945 } 2946// THE RESOLVED CONFIG IS VALIDATED AS A WHOLE, with the one rule every rotation site also applies 2947// (rope_scaling.hpp): the CLI ranges above cannot see a model-file value, nor a combination such as a 2948// --rope-freq-scale that turns the resolved factor non-finite. 2949if (const char * why = strata::kernels::rope_scaling_invalid (rope_cfg )) { 2950 std::fprintf (stderr ,"strata generate: invalid rope scaling configuration: %s (type %s, factor %g, " 2951"freq_scale %g, base %g, original context %g)\n" , 2952why ,rope_cfg .type == RST ::YaRN ?"yarn" :rope_cfg .type == RST ::Linear ?"linear" :"none" , 2953rope_cfg .factor ,rope_cfg .freq_scale (),rope_cfg .freq_base ,rope_cfg .orig_ctx ); 2954return 2 ; 2955 } 2956 strata::kernels::rope_scaling_set (rope_cfg ); 2957if (rope_cfg .type != RST ::None ) { 2958const char * tn = rope_cfg .type == RST ::YaRN ?"yarn" :"linear" ; 2959 std::fprintf (stderr , 2960"strata generate: rope scaling %s, factor %.6g (freq_scale %.6g, base %.6g, mscale %.6f), " 2961"--max-context %lld against a trained context of %.0f\n" , 2962tn ,rope_cfg .factor ,rope_cfg .freq_scale (),rope_cfg .freq_base ,rope_cfg .mscale (), 2963 (long long )o .max_context ,rope_cfg .orig_ctx ); 2964if ((double )o .max_context <=rope_cfg .orig_ctx ) 2965 std::fprintf (stderr , 2966"strata generate: note: the context is within the trained %.0f - no position needs the " 2967"extension, and the resolved scaling still applies to every angle\n" , 2968rope_cfg .orig_ctx ); 2969// only when there IS a magnitude correction: YaRN's log term (ext_factor != 0) or an explicit 2970// --yarn-attn-factor; plain linear (mscale 1) has none, and saying otherwise was TODO 22 2971if (rope_cfg .mscale ()!= 1.0 ) 2972 std::fprintf (stderr , 2973"strata generate: note: the %s magnitude correction scales cos and sin by %.6f " 2974"at every position\n" , 2975rope_cfg .type == RST ::YaRN ?"YaRN" :"--yarn-attn-factor" ,rope_cfg .mscale ()); 2976 } 2977 } 2978 strata::core::NativeEmbed native_embed ; 2979if (native_pack ) { 2980if (o .native_preset .empty ()|| o .spec < 2 || o .keep_canonical || 2981 (o .prefill_chunk <=0 && o .tokens .size ()> 1 )) { 2982 std::fprintf (stderr ,"strata generate: %s is a native (IQ) pack: it needs --native SHARD1, --spec T (T >= 2) " 2983"and --prefill CHUNK\n" ,o .pack .c_str ()); 2984return 2 ; 2985 } 2986const auto embed_t0 = std::chrono::steady_clock::now (); 2987if (!native_embed .load (o .embd_gguf .empty () ?o .native_shards : std::vector < std::string > {o .embd_gguf },g .n_embd , 2988g .n_vocab ,err )) { 2989 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 2990return 1 ; 2991 } 2992 strata::core::set_native_embed (& native_embed ); 2993 std::fprintf (stderr ,"strata generate: native pack: %s experts (largest blob %.2f MB), token embedding " 2994"%s in mapped host memory (%.0f MiB, %.1f s)\n" , 2995o .pack .c_str (), (double ) strata::kernels::cpu::expert_layout ().max_blob /1e6 , 2996 strata::ggml_type_name ((uint32_t )native_embed .type ()), (double )native_embed .bytes () /1048576.0 , 2997 std::chrono::duration < double > (std::chrono::steady_clock::now ()- embed_t0 ).count ()); 2998 } 2999// Plan v0.3 P1: tensors served in native form are not also loaded in canonical form (~2.7 GB of VRAM back 3000// to the expert cache with --native). `--keep-canonical` loads both, as before. 3001 std::set < std::string > skip ; 3002if (!o .keep_canonical ) { 3003if (!o .native_dense_gguf .empty ()&& 3004 !strata::core::NativeDense ::served_names (o .native_dense_gguf ,o .native_ple_key ,skip ,err )) { 3005 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 3006return 1 ; 3007 } 3008if (!o .native_head_gguf .empty ())skip .insert ("output.weight" ); 3009// the PLE module validates its canonical key at construction (8 MB); a native pack has none to load 3010if (!native_pack )skip .erase ("blk.1.ple_key.weight" ); 3011// #326: a --compat-bf16 pack (OrcaRouter IQ3_XXS) keeps its BF16 key in the arena 3012if (native_pack && !strata::core::NativeDense ::keep_unquantized_ple_key (o .pack ,skip ,err )) { 3013 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 3014return 1 ; 3015 } 3016if (native_pack )skip .insert ("token_embd.weight" ); 3017 } 3018// Layer split: every GPU holds only the dense weights of ITS layers (the PLE tensors stay everywhere). 3019// Without this each card keeps a full copy (~3.4 GB for the Coder) that its stage never reads - VRAM the 3020// expert cache wants. Opt-in, STRATA_STAGE_TRIM=1, on HIP and CUDA alike: measured on 2x MI50 (PR #639), 3021// and the default waits for its author's re-run of the release branch on his cards. 3022const std::set < std::string > skip_base = skip ; 3023// --trim-stage-weights (PR #559) is the same switch as STRATA_STAGE_TRIM=1 (PR #639) 3024const bool trim_asked = o .trim_stage_weights || [] { 3025const char * v = std::getenv ("STRATA_STAGE_TRIM" ); 3026return v != nullptr && v [0 ]!= 0 && std::string (v )!= "0" ; 3027 }(); 3028// CUDA0'S ARENA IS BUILT BEFORE THE SPLIT IS KNOWN. The prompt path's PLE tables are read out of it, here, 3029// and `auto` does not choose its split points until 590 lines below - so CUDA0 can still only trim an 3030// explicit --layer-split. It is also the cheapest card to leave alone: it runs layers 0..split_at[0] on 3031// the device with the most room, and on the 4-way IQ3_S rig the trim buys it 4598 -> 4608 slots. The VRAM 3032// is on the later cards (CUDA2 1241 -> 2485, CUDA3 533 -> 1772), and THEIR weights load after the search, 3033// so they trim under `auto` too - see the block past it. 3034const bool stage_trim = trim_asked && multi_gpu && !split_auto && !split_at .empty (); 3035if (o .trim_stage_weights && !multi_gpu ) 3036 std::fprintf (stderr ,"strata generate: --trim-stage-weights needs a layer split across GPUs (ignored)\n" ); 3037// Only `--layer-split auto` WITH the trim asked loads the later stages' weights after the split search (they can 3038// only be trimmed once the split is known). Every other run keeps the 0.1.39 order: weights first, then the 3039// search - so without the trim nothing about a split moves. 3040const bool late_weights = trim_asked && multi_gpu && split_auto ; 3041// keep_routers: CUDA0 with --mmap-experts keeps every layer's router (ffn_gate_inp, ~2.5 MiB a layer) - the file 3042// tier's routing-aware prefetch (RouterLookahead, below) copies all of them from CUDA0's arena, and would 3043// otherwise turn itself off 3044auto add_foreign = [& ](int64_t lb ,int64_t le , std::set < std::string >& out ,bool keep_routers ) { 3045 std::FILE * f = std::fopen ((o .pack + "/index.txt" ).c_str (),"rb" ); 3046if (!f )return ; 3047char line [1024 ],name [256 ]; 3048while (std::fgets (line ,sizeof line ,f )) { 3049if (line [0 ]== '#' || std::sscanf (line ,"%255s" ,name )!= 1 )continue ; 3050const std::string n = name ; 3051if (n .rfind ("blk." ,0 )!= 0 || n .find ("ple" )!= std::string::npos )continue ; 3052if (keep_routers && n .ends_with (".ffn_gate_inp.weight" ))continue ; 3053const int64_t l = std::atoll (name + 4 ); 3054if (l < lb || l >=le )out .insert (n ); 3055 } 3056 std::fclose (f ); 3057 }; 3058if (stage_trim ) { 3059add_foreign (0 ,split_at [0 ],skip ,o .mmap_experts ); 3060 strata::core::NativeDense ::set_layer_range (0 , (int )split_at [0 ]); 3061 std::fprintf (stderr ,"strata generate: layer split: CUDA0 loads the dense weights of layers 0-%lld only\n" , 3062 (long long )split_at [0 ]- 1 ); 3063 } 3064uint64_t pool_bytes = 0 ; 3065if (!strata::core::WeightTable ::pool_bytes (o .pack ,pool_bytes ,err ,skip .empty () ?nullptr :& skip )) { 3066 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 3067return 1 ; 3068 } 3069void * arena = nullptr ; 3070/* 3071DPCT1000: Error handling if-stmt was detected but could not be 3072rewritten. 3073*/ 3074if (const dpct::err0 ce = 3075DPCT_CHECK_ERROR (arena = (void * )strata::malloc_device_guarded ( 3076pool_bytes , dpct::get_in_order_queue ())); 3077ce != 0 ) { 3078// #486: the arena is the first large allocation and its size does not depend on the context, so what is 3079// missing is held by something else: say how much was free 3080/* 3081DPCT1026: The call to cudaGetLastError was removed because this 3082functionality is redundant in SYCL. 3083*/ 3084/* 3085DPCT1001: The statement could not be removed. 3086*/ 3087size_t free_b = 0 ,total_b = 0 ; 3088/* 3089DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions 3090for device information which may not be supported by all compilers or 3091runtimes. You may need to adjust the code. 3092*/ 3093 dpct::get_current_device ().get_memory_info (free_b ,total_b ); 3094 std::fprintf ( 3095stderr , 3096"strata generate: cudaMalloc(%llu) for the weight arena failed " 3097"(%s): %llu MiB of %llu " 3098"MiB VRAM free on this GPU. The arena is allocated first, before " 3099"the KV and expert " 3100"caches: another program (or an engine that is still exiting) " 3101"holds the rest - " 3102"nvidia-smi / rocm-smi lists them\n" , 3103/* 3104DPCT1009: SYCL reports errors using exceptions and does not use 3105error codes. Please replace the "get_error_string_dummy(...)" with a 3106real error-handling function. 3107*/ 3108 (unsigned long long )pool_bytes , dpct::get_error_string_dummy (ce ), 3109 (unsigned long long )(free_b >>20 ), 3110 (unsigned long long )(total_b >>20 )); 3111return 1 ; 3112 } 3113auto load_t0 = std::chrono::steady_clock::now (); 3114auto load_s = [& ] { 3115const auto t = std::chrono::steady_clock::now (); 3116const double s = std::chrono::duration < double > (t - load_t0 ).count (); 3117load_t0 = t ; 3118return s ; 3119 }; 3120 strata::core::WeightTable wt ; 3121if (!wt .load (o .pack ,arena ,pool_bytes ,err ,skip .empty () ?nullptr :& skip )) { 3122 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 3123return 1 ; 3124 } 3125 std::fprintf (stderr ,"strata generate: %llu MiB of weights loaded from %s in %.1f s (%zu canonical tensors " 3126"skipped: served natively)\n" , 3127 (unsigned long long ) (pool_bytes >>20 ),o .pack .c_str (),load_s (),skip .size ()); 3128 strata::uc_probe ("weights" ); 3129 3130 strata::core::NativeDense native_dense ; 3131if (!o .native_dense_gguf .empty ()) { 3132if (!native_dense .load (o .native_dense_gguf ,wt ,err ,o .native_ple_key )) { 3133 std::fprintf (stderr ,"strata generate: native dense projections: %s\n" ,err .c_str ()); 3134return 1 ; 3135 } 3136 std::fprintf (stderr ,"strata generate: %zu native projection matrices, %.2f MiB of weights, in %.1f s\n" , 3137native_dense .tensor_count (), (double )native_dense .weight_bytes () / (1024.0 * 1024.0 ),load_s ()); 3138 } 3139 3140 strata::uc_probe ("native-dense" ); 3141 strata::kernels::gr_set_fp32_activations (o .gr_fp32_activations ); 3142 strata::kernels::gr_set_native_mmvf (o .gr_native_mmvf ); 3143// Plan v0.3 P3: the fused hyper-connection read rides the native (FP32-activation) contract; the per-stage 3144// and dump measurements need the unfused layout of R, so they keep the old kernels. 3145 strata::core::layer_set_fast_attn (!o .no_fast_attn ); 3146 strata::core::layer_set_publish_kernel (!o .no_publish_kernel ); 3147 strata::core::layer_set_fused_gdn (!o .no_fused_gdn ); 3148 strata::core::layer_set_fast_select (!o .no_fast_select ); 3149 strata::core::layer_set_fused_gr (o .gr_native_mmvf && !o .no_fused_gr && !o .gpu_stages && o .dump_layers .empty ()&& 3150o .dump_halves .empty ()&& !o .stage_timing ); 3151 strata::core::layer_set_native_bf16 (o .native_bf16 ); 3152 strata::core::layer_set_native_flash_attn_short (o .native_flash_attn_short ); 3153 strata::kernels::ple_set_native_bf16 (o .native_bf16_extra ); 3154 strata::kernels::shared_expert_set_native_bf16 (o .native_bf16_extra ); 3155 strata::kernels::native_moe_combine_set_enabled (o .native_moe_combine ); 3156 strata::kernels::native_gdn_set_enabled (o .native_gdn ); 3157 strata::kernels::native_router_set_enabled (o .native_router ); 3158 strata::kernels::native_qsa_set_enabled (o .native_qsa ); 3159 strata::kernels::native_qsa_indexer_set_enabled (o .native_qsa_indexer ); 3160 strata::kernels::native_rope_set_enabled (o .native_rope ); 3161// The vision path: every rope kernel reads a cell's (t, h, w) from this table (strata/kernels/mrope.hpp). It is 3162// the identity until an image request, and it is set here, before any CUDA graph captures a rope kernel. 3163int32_t * d_mrope = nullptr ; 3164 std::vector < int32_t > mrope_host ; 3165if (o .vision ) { 3166const int64_t cells = o .max_context + 64 ; 3167mrope_host .resize ((size_t )cells * 3 ); 3168for (int64_t c = 0 ;c < cells ;++ c ) 3169mrope_host [(size_t )c * 3 ]= mrope_host [(size_t )c * 3 + 1 ]= mrope_host [(size_t )c * 3 + 2 ]= (int32_t )c ; 3170if (DPCT_CHECK_ERROR ( 3171d_mrope = sycl::malloc_device < int32_t > ( 3172mrope_host .size (), dpct::get_in_order_queue ()))!= 0 || 3173/* 3174DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 3175assuming in the original code the source host memory is pageable 3176memory. If the memory is not pageable, call wait() on event return 3177by memcpy API to ensure synchronization behavior. 3178*/ 3179DPCT_CHECK_ERROR (dpct::get_in_order_queue ().memcpy ( 3180d_mrope ,mrope_host .data (), 3181mrope_host .size ()* sizeof (int32_t )).wait ())!= 0 ) { 3182 std::fprintf (stderr ,"strata generate: cannot allocate the image position table\n" ); 3183return 1 ; 3184 } 3185 strata::kernels::mrope_table_set (d_mrope ); 3186 } 3187 strata::kernels::ple_set_native_postops (o .native_ple_postops ); 3188// before session_init: every graph captured from here on has the vector's kernels where it applies 3189 std::string cvec_summary = "0" ; 3190uint64_t cvec_digest = 0 ;// a session file is bound to the loaded vector (0: none) 3191if (!o .cvec_files .empty ()) { 3192 std::string ce ; 3193if (!load_control_vectors (o ,g ,cvec_summary ,cvec_digest ,ce )) { 3194 std::fprintf (stderr ,"strata generate: control vector: %s\n" ,ce .c_str ()); 3195return 2 ; 3196 } 3197 } 3198if (o .max_context < (int64_t )o .tokens .size ()+ o .max_new ) { 3199 std::fprintf (stderr ,"strata generate: --max-context %lld cannot hold %zu prompt + %lld new tokens\n" , 3200 (long long )o .max_context ,o .tokens .size (), (long long )o .max_new ); 3201return 2 ; 3202 } 3203 3204 strata::core::SessionState ss ; 3205void * sbuf = nullptr ;// allocated after the layer-split search, sized to CUDA0's own layer range (the carve) 3206// **THE ENGINE RAN ON THE LEGACY DEFAULT STREAM, WHICH ON WDDM IS THE SLOW PATH.** All four session 3207// calls - `session_capture`, `session_replay`, `session_token` and `session_loop` - were handed `nullptr`, 3208// i.e. stream 0. `bench/micro/kernel_costs.cu` measures what that costs: EVERY kernel it launches through 3209// a wrapper comes back at 28-31 us REGARDLESS OF SIZE, `scale_inplace` on 2,048 floats and `silu_inplace` 3210// on 10,240 floats being indistinguishable, which is a fixed per-launch cost and not execution. 3211// `bench/micro/graph_node_cost.cu` measures the same kernels on a real stream at 3.63 us ungrapped and 3212// 0.805 us inside a graph. **That is an ~8x penalty on every launch in the engine.** 3213 dpct::queue_ptr main_stream = & dpct::get_in_order_queue (); 3214/* 3215DPCT1025: The SYCL queue is created ignoring the flag and priority 3216options. 3217*/ 3218if (DPCT_CHECK_ERROR ( 3219main_stream = dpct::get_current_device ().create_queue (true))!= 0 ) { 3220 std::fprintf (stderr ,"strata generate: cannot create the main stream\n" ); 3221return 1 ; 3222 } 3223void * const main_cs = (void * )main_stream ; 3224 3225// ---- **THE HALF-LEVEL DUMP HAS TO BE ARMED BEFORE `session_capture`, AND THE LADDER MUST NOT BE.** The 3226// half copies are issued from inside `block_layer_pre`/`block_layer_post`, so they are only ever enqueued 3227// while a graph is being CAPTURED - arming `ss.block.dump` afterwards would produce a file of zeros that 3228// reads exactly like a wrong answer. The ladder is the opposite: `session_loop` enqueues it per token on 3229// the replay stream, so it must be armed after capture to stay out of the graph. 3230const uint64_t half_stride = (uint64_t )2 * g .n_embd + (uint64_t )2 * g .hc + 3231 (uint64_t )g .n_head * g .head_dim + 3232 (uint64_t )5 * g .n_head_kv * g .head_dim + 8 ; 3233 std::FILE * half_dump = nullptr ; 3234float * half_stage = nullptr ; 3235if (!o .dump_halves .empty ()) { 3236half_dump = std::fopen (o .dump_halves .c_str (),"wb" ); 3237if (half_dump == nullptr ) { 3238 std::fprintf (stderr ,"strata generate: cannot write %s\n" ,o .dump_halves .c_str ()); 3239return 1 ; 3240 } 3241const size_t n = (size_t )g .n_layers * (size_t )half_stride ; 3242/* 3243DPCT1048: The original value cudaHostAllocDefault is not meaningful 3244in the migrated code and was removed or replaced with 0. You may need to 3245check the migrated code. 3246*/ 3247if (DPCT_CHECK_ERROR (half_stage = sycl::malloc_host < float > ( 3248n , dpct::get_in_order_queue ()))!= 0 ) { 3249 std::fprintf (stderr ,"strata generate: cannot pin the half-dump staging buffer\n" ); 3250return 1 ; 3251 } 3252ss .block .dump = half_stage ; 3253 } 3254 3255 strata::core::Doorbell db ; 3256if (strata::core::doorbell_init (g ,K ,db )== 0 ) { 3257 std::fprintf (stderr ,"strata generate: doorbell_init failed\n" ); 3258return 1 ; 3259 } 3260ss .db = & db ; 3261 3262// ================================ THE PLE ================================ 3263// 3264// **ITS ABSENCE IS WHY GATE C1 FAILED** (LEDGER L123): layer 1 carries six `blk.1.ple_*` tensors, the whole 3265// module was built and parity-tested, and nothing called it. Everything below is construction - the table 3266// is a mapping of the ORIGINAL second GGUF shard, the six weights are already loaded in the arena, and the 3267// three buffers are the only allocation. 3268 strata::kernels::PleTable ple_table ; 3269 std::vector < float > ple_emb_host ((size_t ) strata::kernels::NG_N_EMBD ); 3270float * ple_emb_dev = nullptr ; 3271float * ple_scratch = nullptr ; 3272if (!o .ple_gguf .empty ()) { 3273 strata::kernels::PleIoOptions pio ; 3274pio .mode = o .ple_io == "mmap" || o .ple_io == "ram" ? strata::kernels::PleIo ::Mmap : strata::kernels::PleIo ::Direct ; 3275pio .lock = o .ple_io == "ram" ; 3276const auto tpl = Clock ::now (); 3277pio .max_inflight = (uint32_t )o .ple_inflight ; 3278pio .cache_rows = (uint64_t )o .ple_row_cache ; 3279pio .io_thread = !o .ple_sync_submit ; 3280// Keep the SSD awake while rows are being asked for (PleReader::set_keepalive): some SSDs stall the first 3281// reads 50-150 ms after ~250 ms without a command. STRATA_SSD_KEEPALIVE = ms without a read before one 3282// page is read anyway (default 100, 0 = off), STRATA_SSD_KEEPALIVE_WINDOW = seconds after the last row 3283// request that this goes on (default 60; then the SSD may sleep until the next request). 3284 { 3285const char * ka = std::getenv ("STRATA_SSD_KEEPALIVE" ); 3286const char * kw = std::getenv ("STRATA_SSD_KEEPALIVE_WINDOW" ); 3287pio .keepalive_ms = ka != nullptr && * ka ? std::clamp (std::atof (ka ),0.0 ,10000.0 ) :100.0 ; 3288pio .keepalive_window_s = kw != nullptr && * kw ? std::clamp (std::atof (kw ),1.0 ,86400.0 ) :60.0 ; 3289if (pio .mode != strata::kernels::PleIo ::Direct || !pio .io_thread )pio .keepalive_ms = 0 ; 3290 } 3291if (!ple_table .open (o .ple_gguf ,err ,pio )) { 3292 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 3293return 1 ; 3294 } 3295// Recommend, never force: when the default direct reads measure slow, switch to the mapped reads (40-100x 3296// faster on the reporters' drives); an explicit --ple-io direct is kept and only warned about. 3297if (pio .mode == strata::kernels::PleIo ::Direct && std::getenv ("STRATA_PLE_PROBE" )== nullptr ) { 3298constexpr double kSlowRowsPerS = 15000.0 ;// ~60 MB/s of 4 KiB pages; a healthy NVMe is >100k 3299const double rps = ple_direct_rows_per_s (ple_table ); 3300if (rps >=kSlowRowsPerS ) 3301 std::fprintf (stderr ,"strata generate: PLE direct read probe: %.0f rows/s (fine)\n" ,rps ); 3302if (rps > 0 && rps < kSlowRowsPerS ) { 3303// #1984 #1971 #2040: on no platform is the switch made on its own. Windows: the mapped reads stalled prompts (the first chunk waits for 16 serial page faults 3304// a token from a cold table with no progress mark). Linux SATA SSD: the 15K rows/s bar is NVMe-calibrated, a SATA SSD 3305// tops out at 10-14K with direct's 16 reads in flight and mapped reads were 7x slower. The switch is only made when asked for 3306// (STRATA_PLE_AUTO_MMAP=1, the 0.1.42 behaviour); otherwise the slow probe warns and direct is kept. 3307bool auto_mmap = !o .ple_io_explicit ; 3308if (const char * am = std::getenv ("STRATA_PLE_AUTO_MMAP" );am == nullptr || std::atoi (am )== 0 )auto_mmap = false; 3309if (auto_mmap ) { 3310 std::fprintf (stderr ,"strata generate: --ple-io direct measures slow here (%.0f rows/s, about %.0f MB/s of " 3311"random 4 KiB reads): using --ple-io mmap instead (the OS file cache holds the pages; " 3312"--ple-io direct forces the old mode, --ple-io ram keeps the table in RAM)\n" , 3313rps ,rps * 4096.0 /1e6 ); 3314ple_table .close (); 3315pio .mode = strata::kernels::PleIo ::Mmap ; 3316pio .keepalive_ms = 0 ; 3317if (!ple_table .open (o .ple_gguf ,err ,pio )) { 3318 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 3319return 1 ; 3320 } 3321 }else { 3322 std::fprintf (stderr ,"strata generate: WARNING: --ple-io direct measures slow here (%.0f rows/s, about %.0f " 3323"MB/s of random 4 KiB reads): a prompt can spend minutes reading layer 1 and trip the " 3324"stall watchdog (#1425, #1629). --ple-io mmap was 40-100x faster on some DRAM-less NVMe drives but 7x slower on a SATA SSD (#2040), so it is not chosen for you; " 3325"--ple-io ram needs the RAM for the table%s\n" ,rps ,rps * 4096.0 /1e6 , 3326o .ple_io_explicit ?"" :" (kept direct: pass --ple-io mmap or --ple-io ram to change it; in a config file's \"args\" they are two entries: \"--ple-io\", \"mmap\")" ); 3327 } 3328 } 3329 } 3330#if !defined(_WIN32 ) 3331if (pio .mode == strata::kernels::PleIo ::Direct ) { 3332// #605: --ple-io direct's random reads (up to --ple-inflight at once) are for SSDs; a rotational disk 3333// can take longer than the stall watchdog's 60 s for one prompt chunk's rows. Recommended, not forced. 3334 std::string dev ; 3335if (!under_wddm ()&& on_rotational_disk (o .ple_gguf ,dev )== 1 )// (WSL's virtual disk says rotational) 3336 std::fprintf (stderr ,"strata generate: WARNING: the n-gram table (%s) is on a rotational disk (%s): " 3337"--ple-io direct reads it at random and can stall a prompt for minutes (#605). " 3338"--ple-io ram (it then needs RAM for the table) or the model on an SSD is " 3339"recommended\n" ,o .ple_gguf .c_str (),dev .c_str ()); 3340 } 3341#endif 3342if (pio .lock ) 3343 std::fprintf (stderr ,"strata generate: PLE table %s (--ple-io ram) in %.1f s\n" , 3344ple_table .locked () ?"locked in RAM" :"loaded (not locked)" , 3345 std::chrono::duration < double > (Clock ::now ()- tpl ).count ()); 3346if (pio .keepalive_ms > 0 ) 3347 std::fprintf (stderr ,"strata generate: the SSD is kept awake while rows are read: one page of the table after " 3348"%.0f ms without a read, until %.0f s after the last request " 3349"(STRATA_SSD_KEEPALIVE=0 turns it off)\n" ,pio .keepalive_ms ,pio .keepalive_window_s ); 3350else if (pio .mode == strata::kernels::PleIo ::Direct ) 3351 std::fprintf (stderr ,"strata generate: SSD keep-alive off: the SSD may fall asleep between reads\n" ); 3352const strata::core::WeightRef * wk = wt .find ("blk.1.ple_key.weight" ); 3353const strata::core::WeightRef * wv = wt .find ("blk.1.ple_value.weight" ); 3354const strata::core::WeightRef * wnk = wt .find ("blk.1.ple_norm_key.weight" ); 3355const strata::core::WeightRef * wnq = wt .find ("blk.1.ple_norm_query.weight" ); 3356const strata::core::WeightRef * wnc = wt .find ("blk.1.ple_norm_conv.weight" ); 3357const strata::core::WeightRef * wc = wt .find ("blk.1.ple_conv1d.weight" ); 3358if (!wk || !wv || !wnk || !wnq || !wnc || !wc ) { 3359 std::fprintf (stderr ,"strata generate: the pack has no blk.1.ple_* tensors, so the PLE cannot be " 3360"wired - and running without it is a DIFFERENT MODEL (LEDGER L123)\n" ); 3361return 1 ; 3362 } 3363// `ple_key` is S2 and the loader has already widened its scales to f32, so the two planes are located 3364// by the sizes the `WeightRef` records rather than re-derived - the same rule `plane_ptrs` follows. 3365if (!wk -> quantized ()) { 3366// plan v0.3 P6: the IQ model files' BF16 key (the pack's extra.bin, raw BF16) 3367ss .ple .w .key_bf16 = (const uint16_t * )wk -> data ; 3368 }else if (wk -> data != nullptr ) { 3369ss .ple .w .key_codes = (const uint8_t * )wk -> data ; 3370ss .ple .w .key_scales = (const float * ) ((const uint8_t * )wk -> data + wk -> codes_bytes ); 3371 } 3372if (o .native_ple_key && wk -> quantized ()) { 3373if (!wk -> native_data || (wk -> native_type != 42 && wk -> native_type != 18 && wk -> native_type != 23 && 3374wk -> native_type != 8 )|| !wk -> native_q8_1 ) { 3375 std::fprintf (stderr ,"strata generate: native PLE key is absent or incompatible\n" ); 3376return 1 ; 3377 } 3378ss .ple .w .key_native_data = wk -> native_data ; 3379ss .ple .w .key_native_type = wk -> native_type ; 3380ss .ple .w .key_native_q8_1 = wk -> native_q8_1 ; 3381 } 3382ss .ple .w .value_bf16 = (const uint16_t * )wv -> data ; 3383ss .ple .w .norm_key = (const float * )wnk -> data ; 3384ss .ple .w .norm_query = (const float * )wnq -> data ; 3385ss .ple .w .norm_conv = (const float * )wnc -> data ; 3386// The conv1d kernel reads F16, so this cast is a claim about the pack's storage. A checkpoint that keeps 3387// the tensor F32 (Q8_0, UD-Q4_K_XL) would hand the kernel the low halves of the f32 words - not an error, 3388// a plausible wrong layer-1 routing. tools/iq_pack.py narrows it (index kind 3); a pack that did not is 3389// refused here (#255, gopinath87607). F16 is index kind 5 or 3 (F16InF32) in a native pack and kind 0 3390// (verbatim 2-byte F16) in the canonical Q2_0 pack; BF16 (kind 4) has the same size and is not F16. 3391const bool f16 = wc -> kind == strata::core::WeightKind ::F16InF32 || 3392 (wc -> kind == strata::core::WeightKind ::Verbatim && wc -> code_bits == 0 ); 3393if (!f16 || wc -> bytes != (uint64_t )wc -> elements * 2 ) { 3394 std::fprintf (stderr ,"strata generate: blk.1.ple_conv1d.weight is not stored as F16 (pack index kind %d, " 3395"%llu B for %lld values); the PLE conv1d kernel reads F16 - repack with " 3396"tools/iq_pack.py\n" , 3397 (int )wc -> kind , (unsigned long long )wc -> bytes , (long long )wc -> elements ); 3398return 1 ; 3399 } 3400ss .ple .w .conv1d_f16 = (const uint16_t * )wc -> data ; 3401ss .ple .consts = ple_consts_run ; 3402for (int h = 0 ;h < strata::kernels::PLE_N_HEADS ;++ h ) {// the hash may only reach rows the table has 3403if (ple_consts_run .offset [h ]+ ple_consts_run .vocab [h ]> ple_table .rows ()) { 3404 std::fprintf (stderr ,"strata generate: PLE head %d reaches row %llu but the table has %llu rows (the model file's hash constants do not fit its PLE table)\n" , 3405h , (unsigned long long ) (ple_consts_run .offset [h ]+ ple_consts_run .vocab [h ]), (unsigned long long )ple_table .rows ()); 3406return 1 ; 3407 } 3408 } 3409if (o .ple_delay_us > 0 )ple_table .set_injected_delay_us (o .ple_delay_us ); 3410ss .ple .table = & ple_table ; 3411ss .ple .token = & ss .ple_token ; 3412ss .ple .prev = ss .ple_prev ; 3413// `ss.ple.hist` and the ready() check wait for `session_init`, which carves the history - the session is 3414// now allocated after the layer-split search (see the carve), and the wiring lands there 3415ss .ple .emb_host = ple_emb_host .data (); 3416if (DPCT_CHECK_ERROR (ple_emb_dev = (float * )sycl::malloc_device ( 3417 (size_t )strata::kernels::NG_N_EMBD * 4 , 3418 dpct::get_in_order_queue ()))!= 0 || 3419DPCT_CHECK_ERROR (ple_scratch = (float * )sycl::malloc_device ( 3420 strata::core::ple_run_scratch_bytes (), 3421 dpct::get_in_order_queue ()))!= 0 ) { 3422 std::fprintf (stderr ,"strata generate: the PLE buffers failed\n" ); 3423return 1 ; 3424 } 3425ss .ple .emb_dev = ple_emb_dev ; 3426ss .ple .scratch = ple_scratch ; 3427 }else { 3428 std::fprintf (stderr , 3429"strata generate: PLE OFF by explicit --no-ple diagnostic request.\n" 3430" The tokens below are NOT this model's; this is only useful for A/B measurement.\n" ); 3431 } 3432 3433float * d_parts = nullptr ; 3434if (DPCT_CHECK_ERROR ( 3435d_parts = (float * )sycl::malloc_device ( 3436 (size_t )K * g .n_embd * 4 , dpct::get_in_order_queue ()))!= 0 || 3437DPCT_CHECK_ERROR (dpct::get_in_order_queue () 3438 .memset (d_parts ,0 , (size_t )K * g .n_embd * 4 ) 3439 .wait ())!= 0 ) { 3440 std::fprintf (stderr ,"strata generate: the parts buffer failed\n" ); 3441return 1 ; 3442 } 3443 3444// ---- --split-skip-if-fits: before any later stage loads, does CUDA0 alone hold every profiled pair? What it 3445// still has to allocate on one GPU is the whole session (the KV of every layer), the drafter and the head 3446// (kDrafterMib below), the verify windows and the reserve; the prompt path borrows from the cache. If the 3447// profile's pairs fit in what is left, a split would only add the hand-offs: run on CUDA0 alone. 3448if (multi_gpu && split_auto && o .split_skip_if_fits ) { 3449 std::vector < std::pair < int32_t ,int32_t >> prof ; 3450int64_t pslots = 0 ; 3451 std::string perr ; 3452const bool remote = o .expert_cache_remote [0 ]> 0 || o .expert_cache_remote [1 ]> 0 || o .expert_cache_remote [2 ]> 0 ; 3453if (remote || o .expert_profile .empty ()|| 3454 !strata::core::read_expert_profile (o .expert_profile ,g .n_layers ,g .n_expert ,prof ,pslots ,perr )) { 3455 std::fprintf (stderr ,"strata generate: --split-skip-if-fits: %s; the split stays\n" , 3456remote ?"remote expert caches are in use" :perr .empty () ?"no expert profile" :perr .c_str ()); 3457 }else { 3458const auto & lay = strata::kernels::cpu::expert_layout (); 3459int64_t pairs_bytes = 0 ; 3460for (const auto & pr :prof ) 3461pairs_bytes += native_pack ? ((int64_t )lay .blob_bytes (pr .first )+ 255 ) /256 * 256 : (int64_t )lay .max_blob ; 3462size_t fb = 0 ,tb = 0 ; 3463/* 3464DPCT1106: 'cudaMemGetInfo' was migrated with the Intel 3465extensions for device information which may not be supported by all 3466compilers or runtimes. You may need to adjust the code. 3467*/ 3468 dpct::get_current_device ().get_memory_info (fb ,tb ); 3469const int64_t session = (int64_t ) strata::core::session_bytes (g ,o .max_context ,K ,0 ,g .n_layers ); 3470const int64_t held_back = session + (((int64_t )o .vram_reserve_mib + 1000 + 96 ) <<20 );// + drafter/head, windows 3471const int64_t room = (int64_t )fb - held_back ; 3472 dpct::device_info dp {}; 3473 dpct::get_device (0 ).get_device_info (dp ); 3474if (pairs_bytes <=room ) { 3475 std::fprintf (stderr , 3476"strata generate: layer split skipped " 3477"(--split-skip-if-fits): CUDA0 (%s) holds all " 3478"%zu profiled pairs (%.2f GiB) with the session " 3479"(%.2f GiB, %lld-token context), " 3480"the drafter and the reserve: %.2f GiB free, %.2f " 3481"GiB to spare - one GPU\n" , 3482dp .get_name (),prof .size (), 3483 (double )pairs_bytes /1073741824.0 , 3484 (double )session /1073741824.0 , 3485 (long long )o .max_context , 3486 (double )fb /1073741824.0 , 3487 (double )(room - pairs_bytes ) /1073741824.0 ); 3488multi_gpu = false; 3489split_auto = false; 3490split_devs .clear (); 3491split_at .clear (); 3492o .layer_split .clear (); 3493 }else { 3494 std::fprintf (stderr , 3495"strata generate: --split-skip-if-fits: CUDA0 " 3496"(%s) would hold only %.2f of the " 3497"profile's %.2f GiB (%.2f GiB free, %.2f GiB for " 3498"the session, drafter and " 3499"reserve): the split stays\n" , 3500dp .get_name (), 3501 (double )std::max < int64_t > (room ,0 ) /1073741824.0 , 3502 (double )pairs_bytes /1073741824.0 , 3503 (double )fb /1073741824.0 , 3504 (double )held_back /1073741824.0 ); 3505 } 3506 } 3507 } 3508 strata::core::Verifier ::set_commit_async (!multi_gpu );// see Verifier::set_commit_async 3509// --pipeline-windows: one conversation's windows with the two stages of a layer split overlapped. Decided 3510// here, before any stage sizes its expert cache (the second verifier per stage and the snapshots are allocated 3511// after the caches, so their room is kept out of them). What it does not support turns it off, said once. 3512// Not given: on by default (2) for a split of exactly two Battlemage (Xe2) cards, found from the devices' 3513// architecture ids (strata::intel_gpu_gen), with --serve and the MTP drafter; a single card, an Arc A-series card or 3514// anything the pipeline does not support stays serial, said nothing. STRATA_PIPELINE_AUTO=0 or 3515// --pipeline-windows 0 turns it off. 3516if (o .pipeline_windows < 0 ) { 3517static const char * ae = std::getenv ("STRATA_PIPELINE_AUTO" ); 3518const auto battlemage = [](int d )-> bool { 3519try { 3520return strata::intel_gpu_gen (dpct::get_device (d ))== strata::IntelGpuGen ::Battlemage ; 3521 }catch (...) { 3522return false; 3523 } 3524 }; 3525 strata::PipelineAutoInputs in ; 3526in .serve = o .serve ;in .multi_gpu = multi_gpu ;in .split_same = split_same ; 3527in .later_stages = (unsigned )split_devs .size (); 3528in .auto_off = ae != nullptr && std::atoi (ae )== 0 ; 3529in .has_mtp = !o .mtp .empty ();in .spec = o .spec ;in .batch = o .batch ; 3530in .peer_device = o .peer_device >=1 ;// the same test as the validation below 3531in .helper_caches = o .expert_cache_remote [0 ]> 0 || o .expert_cache_remote [1 ]> 0 || o .expert_cache_remote [2 ]> 0 ; 3532if (split_devs .size ()== 1 ) {// the devices are looked at only for a split the pipeline could take 3533in .first_is_battlemage = battlemage (0 ); 3534in .later_is_battlemage = battlemage (split_devs [0 ]); 3535 } 3536const bool on = strata::pipeline_auto_on (in ); 3537o .pipeline_windows = on ?2 :0 ; 3538if (on ) 3539 std::fprintf (stderr ,"strata generate: --pipeline-windows 2 is on by default for a layer split across two Arc " 3540"B-series cards (--pipeline-windows 0 or STRATA_PIPELINE_AUTO=0 turns it off)\n" ); 3541 } 3542if (o .pipeline_windows > 0 ) { 3543const bool helpers = o .expert_cache_remote [0 ]> 0 || o .expert_cache_remote [1 ]> 0 || o .expert_cache_remote [2 ]> 0 ; 3544const char * off = !o .serve ?"it needs --serve" 3545 :split_same ?"it needs each stage of the layer split on its own GPU" 3546 : !multi_gpu ?"it needs a layer split on two GPUs" 3547 :split_devs .size ()!= 1 ?"it needs a layer split into exactly two stages" 3548 :o .mtp .empty ()|| o .spec < 2 ?"it needs the MTP drafter (--mtp, --spec)" 3549 :o .batch != 0 ?"not with --batch slots" 3550 :o .peer_device >=1 ?"not with --peer-device" 3551 :helpers ?"not with the helper caches (--expert-cache-device1..3, --remote-expert-opt)" 3552 :nullptr ; 3553if (off != nullptr ) { 3554 std::fprintf (stderr ,"strata generate: --pipeline-windows %d is off: %s\n" ,o .pipeline_windows ,off ); 3555o .pipeline_windows = 0 ; 3556 } 3557 } 3558// ---- layer split across GPUs: each later stage's own copy of the dense weights, its session and (the last) the 3559// head, made on its device before the host arena is mapped (as the drafter below, for the same WDDM reason) 3560 std::vector < std::unique_ptr < GpuStage >> stages ; 3561// One stage's dense weights on its device (the caller has made it current): `trim` = only layers [lb, le). 3562auto load_stage_weights = [& ](GpuStage & st ,int64_t lb ,int64_t le , 3563bool trim )-> bool { 3564try { 3565 std::set < std::string > skip_s = skip_base ; 3566uint64_t pool_s = pool_bytes ; 3567if (trim ) { 3568add_foreign (lb ,le ,skip_s , false); 3569 strata::core::NativeDense ::set_layer_range ((int )lb , (int )le ); 3570if (!strata::core::WeightTable ::pool_bytes (o .pack ,pool_s ,err ,& skip_s )) { 3571 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 3572return false; 3573 } 3574 std::fprintf (stderr ,"strata generate: layer split: CUDA%d loads the dense weights of layers %lld-%lld only\n" , 3575st .dev , (long long )lb , (long long )le - 1 ); 3576 }else { 3577skip_s = skip ; 3578 } 3579void * arena_s = nullptr ; 3580if (DPCT_CHECK_ERROR (arena_s = (void * )strata::malloc_device_guarded ( 3581pool_s , dpct::get_in_order_queue ()))!= 0 || 3582 !st .wt .load (o .pack ,arena_s ,pool_s ,err , 3583skip_s .empty () ?nullptr :& skip_s )) { 3584/* 3585DPCT1026: The call to cudaGetLastError was removed because this 3586functionality is redundant in SYCL. 3587*/ 3588size_t free_b = 0 ,total_b = 0 ;// #486: what that card had free 3589/* 3590DPCT1106: 'cudaMemGetInfo' was migrated with the Intel 3591extensions for device information which may not be supported by all 3592compilers or runtimes. You may need to adjust the code. 3593*/ 3594 dpct::get_current_device ().get_memory_info (free_b ,total_b ); 3595 std::fprintf (stderr ,"strata generate: layer split, CUDA%d weights: %s (%llu MiB needed, %llu MiB of %llu " 3596"MiB free on that card)\n" ,st .dev , 3597err .empty () ?"the weight arena does not fit" :err .c_str (), 3598 (unsigned long long ) (pool_s >>20 ), (unsigned long long ) (free_b >>20 ), 3599 (unsigned long long ) (total_b >>20 )); 3600return false; 3601 } 3602if (!o .native_dense_gguf .empty ()&& !st .dense .load (o .native_dense_gguf ,st .wt ,err ,o .native_ple_key )) { 3603 std::fprintf (stderr ,"strata generate: layer split, CUDA%d native dense projections: %s\n" ,st .dev , 3604err .c_str ()); 3605return false; 3606 } 3607return true; 3608 } 3609catch (sycl::exception const & exc ) { 3610 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 3611 <<", line:" <<__LINE__ << std::endl ; 3612 std::exit (1 ); 3613 } 3614 }; 3615for (size_t i = 0 ;multi_gpu && i < split_devs .size ();++ i ) { 3616stages .push_back (std::make_unique < GpuStage > ()); 3617GpuStage & st = * stages .back (); 3618st .dev = split_devs [i ]; 3619double free_gib = 0 ; 3620if (!strata::core::RemoteExperts ::preflight (st .dev ,free_gib ,err )) { 3621 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 3622return 1 ; 3623 } 3624const strata::core::OnDevice on (st .dev ); 3625// Later stages' weights load here (0.1.39), except `--layer-split auto` with the trim asked: those load after 3626// the split search (see late_weights), so `auto` can trim them too. 3627if (!late_weights ) { 3628const int64_t lb = stage_trim ?split_at [i ] :0 ; 3629const int64_t le = stage_trim ? (i + 1 < split_at .size () ?split_at [i + 1 ] :g .n_layers ) :0 ; 3630if (!load_stage_weights (st ,lb ,le ,stage_trim ))return 1 ; 3631 } 3632// THE SESSION AND THE HEAD WAIT FOR THE SPLIT SEARCH. `session_bytes` prices a stage's session by its 3633// LAYER RANGE (the carve - every stage used to hold all 48 layers' state whatever it ran), so the 3634// sessions are allocated after the search below has set `st.lb`/`st.le`; the last stage's head follows. 3635/* 3636DPCT1025: The SYCL queue is created ignoring the flag and priority 3637options. 3638*/ 3639if (DPCT_CHECK_ERROR ( 3640st .stream = dpct::get_current_device ().create_queue (true))!= 36410 || 3642/* 3643DPCT1025: The SYCL queue is created ignoring the flag and 3644priority options. 3645*/ 3646DPCT_CHECK_ERROR ( 3647st .adapt_stream = 3648 dpct::get_current_device ().create_queue (true))!= 0 || 3649DPCT_CHECK_ERROR (st .adapt_ev = new sycl::event ())!= 0 ) { 3650 std::fprintf (stderr ,"strata generate: layer split, CUDA%d: its streams failed\n" ,st .dev ); 3651return 1 ; 3652 } 3653// a control vector (the speed projection): its tables on this device too - the stage's layers apply it here 3654if (!strata::kernels::cvec_replicate (err )) { 3655 std::fprintf (stderr ,"strata generate: layer split, CUDA%d: %s\n" ,st .dev ,err .c_str ()); 3656return 1 ; 3657 } 3658// --vision: this device's image-position table (the identity until a picture request), read by every rope 3659// kernel its stage runs - set before any of its graphs is captured 3660if (o .vision ) { 3661if (DPCT_CHECK_ERROR ( 3662st .mrope = sycl::malloc_device < int32_t > ( 3663mrope_host .size (), dpct::get_in_order_queue ()))!= 0 || 3664/* 3665DPCT1114: cudaMemcpy is migrated to asynchronization 3666memcpy, assuming in the original code the source host memory is 3667pageable memory. If the memory is not pageable, call wait() on 3668event return by memcpy API to ensure synchronization behavior. 3669*/ 3670DPCT_CHECK_ERROR (dpct::get_in_order_queue ().memcpy ( 3671st .mrope ,mrope_host .data (), 3672mrope_host .size ()* sizeof (int32_t )).wait ())!= 0 ) { 3673 std::fprintf (stderr ,"strata generate: layer split, CUDA%d: the image position table failed\n" ,st .dev ); 3674return 1 ; 3675 } 3676 strata::kernels::mrope_table_set (st .mrope ); 3677 } 3678// its own PCIe share of the missed experts (the same rule as CUDA0's above: its link is probed). A given 3679// --pcie-frac is every stage's share and skips these probes (pcie_given); there is no per-stage setting yet. 3680st .pcie_frac = o .pcie_frac ; 3681if (!pcie_given && native_pack ) { 3682 std::string bursts ; 3683const double bw = probe_pcie_h2d_gbps (& bursts , true); 3684if (bw > 0.0 )st .pcie_frac = pcie_frac_for_gbps (bw ,0.55 ); 3685 std::fprintf (stderr ,"strata generate: layer split: CUDA%d PCIe probe %.1f GB/s (best of %s) -> pcie_frac " 3686"%.2f\n" ,st .dev ,bw ,bursts .c_str (),st .pcie_frac ); 3687 } 3688if (!late_weights ) { 3689size_t fb = 0 ,tb = 0 ; 3690/* 3691DPCT1106: 'cudaMemGetInfo' was migrated with the Intel 3692extensions for device information which may not be supported by all 3693compilers or runtimes. You may need to adjust the code. 3694*/ 3695 dpct::get_current_device ().get_memory_info (fb ,tb ); 3696 std::fprintf (stderr ,"strata generate: layer split: CUDA%d holds its weights; %.2f GiB free (its session " 3697"follows the split search)\n" ,st .dev , (double )fb /1073741824.0 ); 3698 } 3699 } 3700GpuStage * const last_st = stages .empty () ?nullptr :stages .back ().get (); 3701 3702 std::vector < std::pair < int32_t ,int32_t >> profile ; 3703if (!o .expert_profile .empty ()) { 3704int64_t pslots = 0 ; 3705if (!strata::core::read_expert_profile (o .expert_profile ,g .n_layers ,g .n_expert ,profile ,pslots ,err )) { 3706 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 3707return 1 ; 3708 } 3709// An explicit number truncates the ranked list ("what would 2,000 slots give" without rebuilding the 3710// file). `--expert-cache 0` used to take the count the profile was built for; the profile now ranks 3711// every pair (issue #46: a card that holds more than the old 8,000 used to stop there), so it means auto. 3712if (o .expert_cache == 0 )o .expert_cache = -1 ; 3713// Multi-GPU: STRATA_PEER_HOT=<f> gives the peer card a share f of the HOT pairs, so both cards 3714// compute routed experts every layer (the primary alone did ~25 of ~30 per layer-window). Of the first 3715// STRATA_PEER_HOT_AT (default 8700, ~ the primary's slots) ranks, every pair with floor((r+1)f) > floor(rf) 3716// moves to just after that point: the primary fills past them, the peer (which takes what the primary does 3717// not hold, in order) gets them first. 3718if (o .peer_device >=1 ) {// default 0.45 (measured: 0.3-0.6 all better than 0; 0 = off, e.g. for the gate) 3719const char * ph = std::getenv ("STRATA_PEER_HOT" ); 3720const double f = ph ? std::atof (ph ) :0.45 ; 3721const char * pa = std::getenv ("STRATA_PEER_HOT_AT" ); 3722const size_t at = std::min (profile .size (), (size_t ) (pa ? std::atoll (pa ) :8700 )); 3723if (f > 0.0 && f < 1.0 && at > 0 ) { 3724 std::vector < std::pair < int32_t ,int32_t >> keep ,moved ; 3725for (size_t r = 0 ;r < at ;++ r ) { 3726const bool to_peer = (int64_t ) ((double ) (r + 1 )* f )> (int64_t ) ((double )r * f ); 3727 (to_peer ?moved :keep ).push_back (profile [r ]); 3728 } 3729const size_t n_moved = moved .size (); 3730// the primary's share continues with the ranks after `at` until it is full; then the moved ones 3731 std::vector < std::pair < int32_t ,int32_t >> out ; 3732out .reserve (profile .size ()); 3733out .insert (out .end (),keep .begin (),keep .end ()); 3734const size_t fill = std::min (profile .size (),at + n_moved );// what the primary still takes 3735out .insert (out .end (),profile .begin ()+ (long )at ,profile .begin ()+ (long )fill ); 3736out .insert (out .end (),moved .begin (),moved .end ()); 3737out .insert (out .end (),profile .begin ()+ (long )fill ,profile .end ()); 3738profile .swap (out ); 3739 std::fprintf (stderr ,"strata generate: STRATA_PEER_HOT %.2f: %zu of the first %zu ranked pairs moved " 3740"behind rank %zu (the peer's)\n" ,f ,n_moved ,at ,fill ); 3741 } 3742 } 3743 strata::uc_probe ("after-profile" ); 3744 std::fprintf (stderr ,"strata generate: profile %s: %zu ranked pairs, built for %lld slots\n" , 3745o .expert_profile .c_str (),profile .size (), (long long )pslots ); 3746 } 3747// #477: the whole ranking as loaded, the prior of --expert-profile-save's order (a layer split keeps only 3748// CUDA0's pairs in `profile` below). Empty without --expert-profile-save. 3749 std::vector < std::pair < int32_t ,int32_t >> profile_loaded ; 3750if (!o .expert_profile_save .empty ())profile_loaded = profile ; 3751// ---- layer split across GPUs: "auto" places the split points by a cost model of one decode window, measured on 3752// the 5080 + 3090 rig (bench/results/2026-09-29-layer-split): 3753// - every layer costs its GPU a time inversely proportional to SMs x clock (0.33 ms on an RTX 5080, 0.50 on a 3754// 3090: the per-layer round trip and kernels, not the bytes - both cards have ~950 GB/s); 3755// - an expert no cache holds costs ~190 ms per unit of routed mass: the CPU pool in decode and the PCIe stream 3756// in prompts (fitted: the sweep's best K, 26-28, is where one more layer on the faster card stops paying 3757// for the ~0.1% of the mass it pushes out of its cache); 3758// - which experts a cache holds: its layers' profiled pairs, hottest first, until its free VRAM (less the 3759// reserve, the prompt path's buffers and, on a later GPU, 1 GiB for its windows and the drafter) is used; 3760// the routed mass a cache holds follows the COVERAGE CURVE below, not the (r+1)^-1.2 this used to use. 3761// Up to 4 GPUs every placement is tried; beyond, the layers are shared in proportion to speed. 3762// A FOUR-WAY PLACEMENT USED TO BE THE PROPORTIONAL GUESS AND NOTHING ELSE. That formula reads only 3763// `layer_ms`, so on four GPUs the free VRAM a placement leaves for expert caches - the whole point of 3764// the search - never entered it. It does now; see the ns == 4 branch below. 3765// STRATA_SPLIT_MISS_MS tunes the miss cost (a slower CPU: higher). 3766// THE PROMPT PATH'S BUFFERS ARE BORROWED FROM THE CACHE, NOT WITHHELD BESIDE IT. With borrowing the cache 3767// is sized first and at full size, and the prompt path is laid out in the tail of it (`Prefill::relayout`), 3768// so it withholds no VRAM of its own and this reserve is zero. Only without borrowing - no profile to fill 3769// a cache from, or --no-prefill-borrow - do the buffers take a reserve, and then this estimate stands in 3770// for buffers that cannot be priced exactly yet because the sessions do not exist. `plan_lend` uses the 3771// exact `Prefill::bytes_needed` as soon as it can. 3772const bool pf_borrow = !o .no_prefill_borrow && !o .expert_profile .empty (); 3773// (#340: the estimate predates the streamed ring: from 1024-token chunks the prompt path also holds a ring of 3774// whole expert blobs, which a split without borrowing sizes at 96 (Prefill::set_ring_override below) and books 3775// here - without it a `--no-prefill-borrow` split filled the cards and the draft head no longer fit) 3776const int64_t split_ring_mib = 3777 (multi_gpu && !pf_borrow && o .prefill_chunk >=1024 ) 3778 ? (int64_t ) ((96ull * (uint64_t ) strata::kernels::cpu::expert_layout ().max_blob + (1ull <<20 )- 1 ) >>20 ) 3779 :0 ; 3780if (split_ring_mib > 0 ) strata::prefill::Prefill ::set_ring_override (96 ); 3781const int64_t split_pf_mib = 3782 (o .prefill_chunk > 0 && !pf_borrow ) ?160 + (o .prefill_chunk * 680 ) /1024 + split_ring_mib :0 ; 3783// ---- WHAT A STAGE RESERVES, AND ON WHICH STAGE. The flat 1 GiB this used to withhold from EVERY stage 3784// after the first was booked "for its windows and the drafter", but the windows measure 75 MiB ("window up 3785// to 6 tokens, 74.1 MiB of device buffers", on every boot) and the drafter is loaded on ONE stage - the 3786// last one, which is also the only one that holds the head. On the two identical 8 GB cards that GiB was 3787// the entire difference between CUDA0's cache and CUDA1's: 814 slots against 188, 2026-09-30. Both of 3788// those allocations are already made before a stage's cache is sized, so what has to be held back here is 3789// the windows and - only on the stage that carries them - the drafter and the head. 3790const int64_t kWindowMib = 96 ;// the verify windows; 75 MiB measured, rounded up 3791const int64_t kDrafterMib = 1000 ;// the MTP drafter (839 MiB) + the head, on the last stage only 3792// --pipeline-windows: a second verifier on every stage (its arena alone is 70-75 MiB and its graphs come on top: 3793// 64 MiB left two RTX 5070 Ti under Linux short of it) and, with the decode pipelined, two copies of the first 3794// stage's GDN state (sized from its session where the first card's cache is sized; this is the split search's 3795// estimate). Allocated after the caches, so kept out of them. 3796const int64_t kPipeWindowMib = o .pipeline_windows > 0 ?160 :0 ; 3797const int64_t kPipeSnapMib = o .pipeline_windows >=2 ?96 :0 ;// ~3 MiB per GDN layer, twice, ~15 layers 3798auto gdn_snapshot_bytes = [& ](const strata::core::SessionState & s0 )-> size_t { 3799return (size_t )s0 .gdn_alloc * ((size_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size + 3800 (size_t )g .ssm_conv_channels * (g .ssm_d_conv - 1 ))* sizeof (float ); 3801 }; 3802// #340: with the own prompt buffers chosen by the split's rule (not asked for with --no-prefill-borrow) the 3803// boundary is searched as the borrowing configuration would (no reserve): the reserve then only makes the caches 3804// smaller, which measured cost no decode (K=28 on 9070 XT + R9700: 58.4 tok/s own vs 58.5 borrowing), while a 3805// search with the reserve moved the boundary to K=32 and decode to 54.8. STRATA_SPLIT_OWN_PLACE=reserve: the 3806// search sees the reserve. 3807// ---- `--layer-split auto` with the trim asked: a later stage's weights load after this search, so its arena is 3808// not in `cudaMemGetInfo` yet. Price it from the pack index as the full (untrimmed) copy the search has always 3809// seen on the card (`pool_bytes` reads the index and allocates nothing), so the split it picks is the split it 3810// has always picked: this buys cache, not a different placement. Every other run has its weights loaded: 0. 3811 std::vector < uint64_t > stage_pool (stages .size ()+ 1 ,0 ); 3812if (late_weights ) 3813for (size_t i = 1 ;i < stage_pool .size ();++ i )stage_pool [i ]= pool_bytes ; 3814static const bool place_with_reserve = [] { 3815const char * v = std::getenv ("STRATA_SPLIT_OWN_PLACE" ); 3816return v != nullptr && std::string (v )== "reserve" ; 3817 }(); 3818auto stage_room = [& ](int dev ,bool later ,bool drafter , 3819bool search = false)-> int64_t { 3820try { 3821const strata::core::OnDevice on (dev ); 3822size_t fb = 0 ,tb = 0 ; 3823 dpct::get_current_device ().get_memory_info (fb ,tb );// #423 (tmking01): dpct dropped cudaMemGetInfo here 3824/* 3825DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions 3826for device information which may not be supported by all compilers or 3827runtimes. You may need to adjust the code. 3828*/ 3829 3830const int64_t pf = search && split_own_auto && !place_with_reserve ?0 :split_pf_mib ; 3831const int64_t base_reserve = 3832later && o .vram_reserve_later_mib >=0 ?o .vram_reserve_later_mib :o .vram_reserve_mib ; 3833const int64_t reserve = (base_reserve + pf + (later ?kWindowMib :kPipeSnapMib )+ 3834kPipeWindowMib + (drafter ?kDrafterMib :0 )) <<20 ; 3835return std::max < int64_t > ((int64_t )fb - reserve ,0 ); 3836 } 3837catch (sycl::exception const & exc ) { 3838 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 3839 <<", line:" <<__LINE__ << std::endl ; 3840 std::exit (1 ); 3841 } 3842 }; 3843if (multi_gpu && split_auto ) { 3844const auto & lay = strata::kernels::cpu::expert_layout (); 3845const int ns = (int )stages .size ()+ 1 ; 3846 std::vector < int64_t > cap ((size_t )ns ),used ((size_t )ns ); 3847 std::vector < double > layer_ms ((size_t )ns ); 3848for (int i = 0 ;i < ns ;++ i ) { 3849const int dev = i == 0 ?0 :stages [(size_t )i - 1 ]-> dev ; 3850cap [(size_t )i ]= stage_room (i == 0 ?-1 :dev ,i > 0 ,i + 1 == ns , true); 3851if (late_weights )cap [(size_t )i ]= std::max < int64_t > (cap [(size_t )i ]- (int64_t )stage_pool [(size_t )i ],0 ); 3852int sms = 0 ,khz = 0 ; 3853sms = dpct::get_device (dev ).get_max_compute_units (); 3854if (DPCT_CHECK_ERROR ( 3855khz = dpct::get_device (dev ).get_max_clock_frequency ())!= 38560 || 3857khz <=0 )khz = 1800000 ; 3858/* 3859DPCT1026: The call to cudaGetLastError was removed because this 3860functionality is redundant in SYCL. 3861*/ 3862const double speed = 3863 std::max (1.0 , (double )sms * (double )khz /1e6 );// SMs x GHz 3864layer_ms [(size_t )i ]= 0.33 * (84.0 * 2.617 ) /speed ; 3865 std::fprintf (stderr ,"strata generate: layer split auto: CUDA%d %d SMs at %.2f GHz -> %.2f ms per layer, " 3866"%.2f GiB free before its session carve\n" ,dev ,sms ,khz /1e6 ,layer_ms [(size_t )i ], 3867 (double )cap [(size_t )i ] /1073741824.0 ); 3868 } 3869const double miss_ms = std::getenv ("STRATA_SPLIT_MISS_MS" ) ? std::atof (std::getenv ("STRATA_SPLIT_MISS_MS" )) :190.0 ; 3870// ---- THE COVERAGE CURVE: HOW MUCH ROUTED MASS A CACHE HOLDS, AND WHY IT IS NO LONGER A POWER LAW. 3871// 3872// `mass[r]` used to be (r+1)^-1.2, fitted to the 5080+3090 sweep. That fit is still right ON THE RIG IT 3873// WAS FITTED TO - at 20,000 pairs held it predicts 99.35% of the routed mass and that rig measured 99.4%. 3874// It is wrong on the IQ3_S 4-way rig, badly: it claims the top 5,805 pairs hold 94.9% of the mass, and 3875// that rig measures 69.2% (four boots, 14.9M decode lookups). No exponent reconciles them, because the 3876// curve is a property of the MODEL'S ROUTING, not a universal constant - and the profile file carries 3877// only a RANKING, with no counts, so it cannot be read off the data either. (tools/make_profile.py has 3878// the frequencies, and drops them; see the note there.) 3879// 3880// What the two rigs do agree on is that the hit rate follows the HELD COUNT and almost nothing else: two 3881// different splits held 14,541 and 14,384 pairs and measured 92.2% and 89.8% of the routed mass. So the 3882// curve is taken over the held FRACTION f, as H(f) = 1 - (1 - f)^b, and each rank's mass is that curve's 3883// increment, which makes any prefix of N pairs sum to exactly H(N/total) while a cache holding 3884// colder-than-prefix pairs still scores below it. 3885// 3886// b = 3 IS CHOSEN TO LEAVE THE PREVIOUSLY VALIDATED REGIME WHERE IT WAS. At 20,000 held (f = 0.8138) it 3887// gives 99.35%, against the old fit's 99.35% and that rig's measured 99.4% - the 2-GPU placement is 3888// untouched. At f = 0.59 it gives 93.2% against 92.2% measured. Below f ~ 0.5 the two curves diverge, 3889// and that is the whole point: it is exactly the regime where the old one was wrong, and where it told 3890// the search that stranding a card's VRAM costs almost nothing. 3891// 3892// THE CURVE IS A FIT TO ONE MODEL'S TRAFFIC. STRATA_SPLIT_COVER_B overrides b for a model whose routing 3893// is sharper or flatter, and STRATA_SPLIT_MISS_MS still scales the miss cost it feeds. 3894const size_t n_ranked = profile .size (); 3895const double cover_b = std::getenv ("STRATA_SPLIT_COVER_B" ) ? std::atof (std::getenv ("STRATA_SPLIT_COVER_B" )) :3.0 ; 3896 std::vector < double > mass (n_ranked ); 3897double total_mass = 0 ; 3898// Up to 3 GPUs the 0.1.39 curve (r+1)^-1.2 is kept, so 2- and 3-GPU placements do not move (the new curve is a 3899// fit to a 4-way rig and was not measured on them); STRATA_SPLIT_COVER_B asks for the coverage curve at any 3900// GPU count. 3901const bool coverage_curve = ns >=4 || std::getenv ("STRATA_SPLIT_COVER_B" )!= nullptr ; 3902for (size_t r = 0 ;r < n_ranked ;++ r ) { 3903if (!coverage_curve ) { 3904total_mass += (mass [r ]= std::pow ((double )r + 1.0 ,-1.2 )); 3905continue ; 3906 } 3907const double hi = std::pow (1.0 - (double )r / (double )n_ranked ,cover_b ); 3908const double lo = std::pow (1.0 - (double ) (r + 1 ) / (double )n_ranked ,cover_b ); 3909total_mass += (mass [r ]= hi - lo ); 3910 } 3911auto cost = [& ](int64_t l )-> int64_t { 3912return native_pack ? ((int64_t )lay .blob_bytes (l )+ 255 ) /256 * 256 : (int64_t )lay .max_blob ; 3913 }; 3914// the predicted window time (ms) of a placement, and the routed mass its caches hold 3915auto predict = [& ](const std::vector < int64_t >& at ,double & held_mass ,int64_t & held )-> double { 3916// THE CARVE, PRICED: a placement gives stage i the layers [lb, le), and that range's session is a 3917// real cost on its device - subtracted here so the search knows what it leaves for experts. This 3918// is why the sessions are allocated after the search: `session_bytes` is pure arithmetic. 3919 std::vector < int64_t > capr ((size_t )ns ); 3920for (int i = 0 ;i < ns ;++ i ) { 3921const int64_t lb = i == 0 ?0 :at [(size_t )i - 1 ]; 3922const int64_t le = i + 1 < ns ?at [(size_t )i ] :g .n_layers ; 3923capr [(size_t )i ]= cap [(size_t )i ]- (int64_t ) strata::core::session_bytes (g ,o .max_context ,K ,lb ,le ); 3924 } 3925 std::fill (used .begin (),used .end (),0 ); 3926held_mass = 0 ; 3927held = 0 ; 3928 std::vector < bool > full ((size_t )ns , false); 3929for (size_t r = 0 ;r < profile .size ();++ r ) { 3930const int64_t l = profile [r ].first ; 3931int st = 0 ; 3932while (st + 1 < ns && l >=at [(size_t )st ])++ st ; 3933if (full [(size_t )st ])continue ; 3934if (used [(size_t )st ]+ cost (l )> capr [(size_t )st ]) {full [(size_t )st ]= true;continue ; }// as the fill 3935used [(size_t )st ]+= cost (l ); 3936held_mass += mass [r ]; 3937++ held ; 3938 } 3939held_mass /= std::max (total_mass ,1e-9 ); 3940double ms = miss_ms * (1.0 - held_mass ); 3941for (int i = 0 ;i < ns ;++ i ) { 3942const int64_t lb = i == 0 ?0 :at [(size_t )i - 1 ],le = i + 1 < ns ?at [(size_t )i ] :g .n_layers ; 3943ms += (double ) (le - lb )* layer_ms [(size_t )i ]; 3944 } 3945return ms ; 3946 }; 3947 std::vector < int64_t > best ,at ((size_t )ns - 1 ); 3948double best_ms = 1e30 ,best_mass = 0 ; 3949int64_t best_held = 0 ,tried = 0 ; 3950// #1440: of the placements within STRATA_SPLIT_HEADROOM_TOL (default 0.2%) of the best predicted time, the one 3951// whose tightest card keeps the most VRAM beyond all its layers' experts (split_rules::pick_with_headroom). 3952// On by default here (a full xe card moves buffers to system memory instead of failing); STRATA_SPLIT_HEADROOM=0 3953// keeps the first best, as before. 3954static const bool split_headroom = [] { 3955const char * v = std::getenv ("STRATA_SPLIT_HEADROOM" ); 3956return v == nullptr || std::atoi (v )!= 0 ; 3957 }(); 3958const double headroom_tol = 3959 std::getenv ("STRATA_SPLIT_HEADROOM_TOL" ) ? std::atof (std::getenv ("STRATA_SPLIT_HEADROOM_TOL" )) :0.002 ; 3960 std::vector < int64_t > need_prefix ((size_t )g .n_layers + 1 ,0 ); 3961for (int64_t l = 0 ;l < g .n_layers ;++ l ) 3962need_prefix [(size_t )l + 1 ]= need_prefix [(size_t )l ]+ (int64_t )g .n_expert * cost (l ); 3963auto range_session = [& ](int64_t lb ,int64_t le )-> int64_t { 3964return (int64_t ) strata::core::session_bytes (g ,o .max_context ,K ,lb ,le ); 3965 }; 3966 std::vector < strata::program::split_rules::Placement > scored ; 3967 std::vector < double > scored_mass ; 3968 std::vector < int64_t > scored_held ; 3969auto score = [& ](const std::vector < int64_t >& cuts ,double ms ,double hm ,int64_t held ) { 3970if (!split_headroom )return ; 3971scored .push_back ({cuts ,ms , strata::program::split_rules::min_spare (cuts ,g .n_layers ,cap ,need_prefix , 3972range_session )}); 3973scored_mass .push_back (hm ); 3974scored_held .push_back (held ); 3975 }; 3976auto consider = [& ]() { 3977double hm = 0 ; 3978int64_t held = 0 ; 3979const double ms = predict (at ,hm ,held ); 3980++ tried ; 3981score (at ,ms ,hm ,held ); 3982if (ms < best_ms ) {best = at ;best_ms = ms ;best_mass = hm ;best_held = held ; } 3983 }; 3984const int64_t L = g .n_layers ; 3985// share the layers in proportion to speed: the fallback beyond four GPUs, and the only placement a 3986// model too small to hold four stages has (see the ns == 4 branch). 3987auto proportional = [& ]() { 3988double total = 0 ; 3989for (const double c :layer_ms )total += 1.0 /c ; 3990double acc = 0 ; 3991for (int i = 0 ;i + 1 < ns ;++ i ) { 3992acc += 1.0 /layer_ms [(size_t )i ]; 3993at [(size_t )i ]= std::clamp < int64_t > ((int64_t ) std::llround (acc /total * (double )L ), 3994i == 0 ?2 :at [(size_t )i - 1 ]+ 1 ,L - (ns - 1 - i )); 3995 } 3996consider (); 3997 }; 3998if (ns == 2 ) { 3999for (int64_t k = 2 ;k < L ;++ k ) {at [0 ]= k ;consider (); } 4000 }else if (ns == 3 ) { 4001for (int64_t k1 = 2 ;k1 + 1 < L ;++ k1 ) 4002for (int64_t k2 = k1 + 1 ;k2 < L ;++ k2 ) {at [0 ]= k1 ;at [1 ]= k2 ;consider (); } 4003 }else if (ns == 4 ) { 4004// ---- EVERY FOUR-WAY PLACEMENT IS TRIED. This branch used to share the layers in proportion to 4005// speed and score that ONE candidate, and that formula reads only `layer_ms` - never the free VRAM. 4006// So on a four-GPU rig cache capacity did not influence the placement AT ALL, and the card with 4007// the most room left could be handed the fewest layers: on the 3060/3060/5060/5060 box CUDA1 ended 4008// up with 1,841 MiB no cache could use while CUDA2 ran 15 layers it could only hold a third of. 4009// All C(L-3,3) placements - 15,180 at 48 layers - are now scored. 4010// 4011// A STAGE'S FILL DEPENDS ONLY ON ITS OWN RANGE AND ITS OWN FREE VRAM. `predict` hands each ranked 4012// pair to the one stage that owns its layer and each stage stops at its first pair that does not 4013// fit, so the four fills are independent and a placement's held mass is a SUM over its four 4014// ranges. That is what makes this affordable: each distinct range is walked once and memoised, 4015// 1,121 walks instead of 15,180 - measured at 14 ms against 740 ms, for the same answer. 4016// `le` runs to L inclusive, so a row is L+1 wide - keying on a stride of L would put the last 4017// stage's [lb, L) one past the end of the vector. 4018// 4019// NOTE: on v0.1.39 the search only runs under `--layer-split auto`, where every card still holds 4020// the whole model's dense weights, so `cap[i]` is already net of them and the stage's room is what 4021// `predict` subtracts - the session. (On the branch this came from the carve reached `auto` too, 4022// and each stage's own weight bytes were taken off here as well.) 4023const size_t stride = (size_t )L + 1 ; 4024 std::vector < double > held_mass_at ((size_t )ns * (size_t )L * stride ,-1.0 ); 4025 std::vector < int64_t > held_at (held_mass_at .size (),0 ); 4026auto range_hold = [& ](int i ,int64_t lb ,int64_t le )-> size_t { 4027const size_t key = ((size_t )i * (size_t )L + (size_t )lb )* stride + (size_t )le ; 4028if (held_mass_at [key ]< 0.0 ) { 4029// one stage's own carve, exactly as `predict` prices it 4030const int64_t room = cap [(size_t )i ]- 4031 (int64_t ) strata::core::session_bytes (g ,o .max_context ,K ,lb ,le ); 4032double hm = 0 ; 4033int64_t used = 0 ,cnt = 0 ; 4034for (size_t r = 0 ;r < profile .size ();++ r ) { 4035const int64_t l = profile [r ].first ; 4036if (l < lb || l >=le )continue ; 4037if (used + cost (l )> room )break ;// the fill stops exactly where predict's does 4038used += cost (l ); 4039hm += mass [r ]; 4040++ cnt ; 4041 } 4042held_mass_at [key ]= hm ; 4043held_at [key ]= cnt ; 4044 } 4045return key ; 4046 }; 4047const double denom = std::max (total_mass ,1e-9 ); 4048for (int64_t k1 = 2 ;k1 + 2 < L ;++ k1 ) 4049for (int64_t k2 = k1 + 1 ;k2 + 1 < L ;++ k2 ) 4050for (int64_t k3 = k2 + 1 ;k3 < L ;++ k3 ) { 4051const size_t a = range_hold (0 ,0 ,k1 ),b = range_hold (1 ,k1 ,k2 ); 4052const size_t c = range_hold (2 ,k2 ,k3 ),d = range_hold (3 ,k3 ,L ); 4053const double hm = held_mass_at [a ]+ held_mass_at [b ]+ held_mass_at [c ]+ held_mass_at [d ]; 4054const double ms = miss_ms * (1.0 - hm /denom )+ 4055 (double )k1 * layer_ms [0 ]+ (double ) (k2 - k1 )* layer_ms [1 ]+ 4056 (double ) (k3 - k2 )* layer_ms [2 ]+ (double ) (L - k3 )* layer_ms [3 ]; 4057++ tried ; 4058score ({k1 ,k2 ,k3 },ms ,hm /denom ,held_at [a ]+ held_at [b ]+ held_at [c ]+ held_at [d ]); 4059if (ms < best_ms ) { 4060best = {k1 ,k2 ,k3 }; 4061best_ms = ms ; 4062best_mass = hm /denom ; 4063best_held = held_at [a ]+ held_at [b ]+ held_at [c ]+ held_at [d ]; 4064 } 4065 } 4066// Four stages into fewer than five layers: nothing was enumerated, so keep the old guess rather 4067// than leave `best` empty - an empty split would leave every stage's lb/le unset. 4068if (best .empty ())proportional (); 4069 }else { 4070// Beyond four GPUs the placements outnumber any budget worth spending at startup (C(46,4) is 4071// 163,185 at five). Nothing on this rig reaches it. 4072proportional (); 4073 } 4074if (split_headroom && scored .size ()> 1 ) { 4075const size_t first = strata::program::split_rules::fastest (scored ); 4076const size_t pick = strata::program::split_rules::pick_with_headroom (scored ,headroom_tol ); 4077if (pick != first && scored [first ].cuts == best ) { 4078auto fmt_k = [](const std::vector < int64_t >& v ) { 4079 std::string s ; 4080for (const int64_t k :v )s += (s .empty () ?"" :"," )+ std::to_string (k ); 4081return s ; 4082 }; 4083 std::fprintf (stderr ,"strata generate: layer split auto: K=%s instead of K=%s (predicted %.1f vs %.1f ms): its " 4084"tightest card keeps %.2f GiB beyond all its layers' experts, against %.2f GiB " 4085"(#1440: a full card can page to system memory); STRATA_SPLIT_HEADROOM=0 keeps K=%s\n" , 4086fmt_k (scored [pick ].cuts ).c_str (),fmt_k (best ).c_str (),scored [pick ].ms ,best_ms , 4087 (double )scored [pick ].min_spare /1073741824.0 , 4088 (double )scored [first ].min_spare /1073741824.0 ,fmt_k (best ).c_str ()); 4089best = scored [pick ].cuts ; 4090best_ms = scored [pick ].ms ; 4091best_mass = scored_mass [pick ]; 4092best_held = scored_held [pick ]; 4093 } 4094 } 4095split_at = best ; 4096 std::string ks ; 4097for (const int64_t k :split_at )ks += (ks .empty () ?"" :"," )+ std::to_string (k ); 4098 std::fprintf (stderr ,"strata generate: layer split auto: K=%s - predicted %.1f ms per decode window; the caches " 4099"hold %lld of %zu profiled pairs (~%.1f%% of the routed mass), best of %lld placements\n" , 4100ks .c_str (),best_ms , (long long )best_held ,profile .size (),100.0 * best_mass , (long long )tried ); 4101 } 4102for (size_t i = 0 ;i < split_at .size ();++ i ) 4103if (split_at [i ] >=g .n_layers ) { 4104 std::fprintf (stderr ,"strata generate: --layer-split: layer %lld is past the last (%lld)\n" , 4105 (long long )split_at [i ], (long long ) (g .n_layers - 1 )); 4106return 2 ; 4107 } 4108// the stage that runs a layer (0: CUDA0's) 4109auto stage_of = [& ](int64_t l )-> int { 4110int st = 0 ; 4111while (st < (int )split_at .size ()&& l >=split_at [(size_t )st ])++ st ; 4112return st ; 4113 }; 4114// the whole ranking, hottest first, before each stage takes its own layers' share: the resident RAM copy ranks 4115// the experts no GPU holds over ALL the layers (with CUDA0's share alone, a copy that did not fit kept only layers 4116// 0..K-1's experts and read every later layer's from the files) 4117 std::vector < std::pair < int32_t ,int32_t >> profile_all ; 4118if (multi_gpu ) { 4119profile_all = profile ; 4120 std::vector < std::pair < int32_t ,int32_t >> mine ; 4121for (const auto & pr :profile ) { 4122const int st = stage_of (pr .first ); 4123 (st == 0 ?mine :stages [(size_t )st - 1 ]-> profile ).push_back (pr ); 4124 } 4125profile .swap (mine ); 4126for (size_t i = 0 ;i < stages .size ();++ i ) { 4127stages [i ]-> lb = split_at [i ]; 4128stages [i ]-> le = i + 1 < stages .size () ?split_at [i + 1 ] :g .n_layers ; 4129 } 4130 } 4131 4132// ---- `--layer-split auto` with the trim asked: THE STAGES' WEIGHTS, NOW THAT THE SPLIT IS KNOWN. Each later card 4133// loads the dense weights of the layers it runs and nothing else (before this they loaded in the loop above, a 4134// full copy per card: on the 4-way IQ3_S rig CUDA1 3650 expert slots, CUDA2 1241, CUDA3 533 and a 768-token prompt 4135// chunk; carved 4608 / 2485 / 1772 and 6144). The search priced these arenas from the pack index (`stage_pool`). 4136if (late_weights ) 4137for (size_t i = 0 ;i < stages .size ();++ i ) { 4138GpuStage & st = * stages [i ]; 4139const strata::core::OnDevice on (st .dev ); 4140if (!load_stage_weights (st ,st .lb ,st .le , true))return 1 ; 4141size_t fb = 0 ,tb = 0 ; 4142/* 4143DPCT1106: 'cudaMemGetInfo' was migrated with the Intel 4144extensions for device information which may not be supported by all 4145compilers or runtimes. You may need to adjust the code. 4146*/ 4147 dpct::get_current_device ().get_memory_info (fb ,tb ); 4148 std::fprintf (stderr ,"strata generate: layer split: CUDA%d holds its weights; %.2f GiB free (its session " 4149"follows)\n" ,st .dev , (double )fb /1073741824.0 ); 4150 } 4151 4152// ---- CUDA0's session, and the stages' sessions: sized to each device's own layer range (the carve). A 4153// stage that runs [lb, le) carves only those layers' GDN rows and QSA pools - before the carve every stage 4154// held all 48 layers' state whatever layers it ran, which is the same disease the chunked-QSA-prefill PR 4155// fixed in llama.cpp: allocation sized by the whole model instead of the device's own work. 4156// A context the sessions cannot hold in VRAM is not a reason to stop (owner rule: a long context and requests at once never shrink the context, they run 4157// slower): with no --kv-resident given, the K/V streams from RAM, the resident window as large as the card leaves room for. 4158// Needed: every session (the main one and each request slot), what loads after them (the draft layer, the native head, the verify buffers), the reserve, 4159// the prompt path's smallest own buffers (chunk 256) and a cache of 128 slots. 4160if (o .kv_resident <=0 && o .max_context > 20480 && !multi_gpu && !o .kv_grow && o .expert_cache != 0 ) { 4161const int64_t kLateLoadMib = (!o .mtp .empty ()|| o .draft == "dflash2" ) ?1500 :700 ;// Arc A750: MTP 835 + head 417 + verify 70 + the rest; DFlash2 alone is about the same 4162const int64_t blob_b = (int64_t ) strata::kernels::cpu::expert_layout ().max_blob ; 4163const int64_t n_sess = 1 + std::max (o .batch ,0 ); 4164const int64_t reserve_b = (int64_t ) (o .vram_reserve_given ?o .vram_reserve_mib : std::min (o .vram_reserve_mib ,300 )) <<20 ; 4165const int64_t fixed_b = (kLateLoadMib <<20 )+ reserve_b + ((160 + (256 * 680 ) /1024 ) <<20 )+ 128 * blob_b ; 4166size_t free_k = 0 ,total_k = 0 ; 4167free_k = strata::core::device_free_bytes (); (void )total_k ; 4168auto need_at = [& ](int64_t res )-> int64_t { 4169 strata::core::qsa_set_kv_resident (res ); 4170return n_sess * (int64_t ) strata::core::session_bytes (g ,o .max_context ,K ,0 ,g .n_layers )+ fixed_b ; 4171 }; 4172int64_t pick = strata::core::pick_kv_resident (o .max_context , (int64_t )free_k ,need_at ); 4173if (pick > 0 ) { 4174// the pinned RAM the streamed K/V takes (it is a copy of the whole context per session): 1.8 GB a session at 128K int8 4175int64_t host_avail = -1 ; 4176if (std::FILE * mf = std::fopen ("/proc/meminfo" ,"r" )) { 4177char line [256 ]; 4178while (std::fgets (line ,sizeof (line ),mf )) { 4179long long kb = 0 ; 4180if (std::sscanf (line ,"MemAvailable: %lld kB" ,& kb )== 1 ) {host_avail = (int64_t )kb <<10 ;break ; } 4181 } 4182 std::fclose (mf ); 4183 } 4184const int64_t host_need = n_sess * (int64_t )o .max_context * 13 * 1056 + (6ll <<30 ); 4185if (host_avail >=0 && host_avail < host_need ) { 4186 std::fprintf (stderr ,"strata generate: the context does not fit in VRAM and %.1f GiB of free RAM is less than the %.1f GiB KV streaming would take: not turned on\n" , 4187 (double )host_avail /1073741824.0 , (double )host_need /1073741824.0 ); 4188pick = 0 ; 4189 }else { 4190 std::fprintf (stderr ,"strata generate: %lld tokens of context in %lld sessions do not fit in the %.2f GiB free: KV streaming on, %lld cells a layer in VRAM " 4191"(--kv-resident %lld; the rest of the K/V in RAM, so decode and prompts run slower)\n" , 4192 (long long )o .max_context , (long long )n_sess , (double )free_k /1073741824.0 , (long long )pick , (long long )pick ); 4193 } 4194 } 4195o .kv_resident = pick ; 4196 strata::core::qsa_set_kv_resident (o .kv_resident ); 4197 } 4198 { 4199const strata::core::OnDevice on0 (0 ); 4200const int64_t hi0 = multi_gpu ?split_at [0 ] :-1 ; 4201// the elastic K/V (--kv-grow, see kvg_ensure): one GPU, the whole K/V in VRAM (no streaming), a profiled cache 4202// that can give slots up, and every expert in RAM for the CPU to compute the ones it gives up 4203 { 4204const char * ev = std::getenv ("STRATA_KV_GROW" ); 4205bool remote = false; 4206for (const int r :o .expert_cache_remote )remote = remote || r > 0 ; 4207const bool asked = ev != nullptr && ev [0 ]!= '\0' ?ev [0 ]!= '0' :o .kv_grow ; 4208const bool on = asked && !multi_gpu && o .kv_resident <=0 && 4209 !o .expert_profile .empty ()&& !o .resident_cpu_experts && o .expert_cache != 0 && !remote && 4210 strata::core::vmm_available ()&& 4211// the batch slots carve their own K/V and --vram-elastic's cache is not one VMM range 4212o .batch == 0 && !o .vram_elastic && o .peer_device < 0 ; 4213if (asked && !on ) 4214 std::fprintf (stderr ,"strata generate: --kv-grow is off (one GPU, a profile, the whole K/V in VRAM, " 4215"every expert in RAM, no --batch, --vram-elastic or --peer-device)\n" ); 4216const char * iv = std::getenv ("STRATA_KV_GROW_INIT" ); 4217 strata::core::qsa_set_kv_elastic (on ,iv != nullptr && std::atoll (iv )> 0 ? std::atoll (iv ) :16384 ); 4218 strata::core::ExpertCache ::set_vmm (on ); 4219 } 4220if (DPCT_CHECK_ERROR ( 4221sbuf = (void * )sycl::malloc_device ( 4222 strata::core::session_bytes (g ,o .max_context ,K ,0 ,hi0 ), 4223 dpct::get_in_order_queue ()))!= 0 ) { 4224 std::fprintf (stderr ,"strata generate: session state allocation failed\n" ); 4225return 1 ; 4226 } 4227if (strata::core::session_init (g ,o .max_context ,K ,sbuf ,ss ,0 ,hi0 )== 0 ) { 4228 std::fprintf (stderr ,"strata generate: session_init failed\n" ); 4229return 1 ; 4230 } 4231if (g .n_qsa_layers ()> 0 && ss .qsa_states [ss .qsa_primary ()].kv_mode == 1 ) 4232 std::fprintf (stderr ,"strata generate: KV streaming: %lld of %lld cells per QSA layer in VRAM, the K/V in " 4233"%.2f GiB of pinned RAM\n" , 4234 (long long ) (ss .qsa_states [ss .qsa_primary ()].n_slots * 4 ), 4235 (long long )o .max_context , (double ) strata::core::qsa_kv_host_bytes () /1073741824.0 ); 4236// the PLE block above built everything but the history, which session_init has just carved 4237ss .ple .hist = ss .ple_hist ; 4238// (#167) generate mode starts from an empty sequence, and nothing else zeroes this state before the prompt 4239// path or the verifier reads it (--serve zeroes it per request when nothing is reused) 4240 strata::core::session_zero (ss ,g ,nullptr ,main_cs ); 4241if (DPCT_CHECK_ERROR ( 4242 dpct::get_current_device ().queues_wait_and_throw ())!= 0 ) { 4243 std::fprintf (stderr ,"strata generate: zeroing the session state failed\n" ); 4244return 1 ; 4245 } 4246if (!o .ple_gguf .empty ()) { 4247if (!ss .ple .ready ()) { 4248 std::fprintf (stderr ,"strata generate: the PLE run is not ready after construction\n" ); 4249return 1 ; 4250 } 4251 std::fprintf (stderr ,"strata generate: PLE on, table %llu rows of %s\n" , 4252 (unsigned long long )ple_table .rows (),o .ple_gguf .c_str ()); 4253 } 4254 } 4255for (size_t i = 0 ;i < stages .size ();++ i ) { 4256GpuStage & st = * stages [i ]; 4257const strata::core::OnDevice on (st .dev ); 4258void * sbuf_s = nullptr ; 4259if (DPCT_CHECK_ERROR (sbuf_s = (void * )sycl::malloc_device ( 4260 strata::core::session_bytes (g ,o .max_context , 4261K ,st .lb ,st .le ), 4262 dpct::get_in_order_queue ()))!= 0 || 4263 strata::core::session_init (g ,o .max_context ,K ,sbuf_s ,st .ss , 4264st .lb ,st .le )== 0 ) { 4265 std::fprintf (stderr ,"strata generate: layer split, CUDA%d: the session state failed\n" ,st .dev ); 4266return 1 ; 4267 } 4268const bool last = i + 1 == stages .size (); 4269const strata::core::WeightRef * wo_s = st .wt .find ("output.weight" ); 4270if (wo_s == nullptr || 4271 (last && !o .native_head_gguf .empty ()&& !st .head .load (o .native_head_shards ,g .n_embd ,wo_s -> ne1 ,err ))) { 4272 std::fprintf (stderr ,"strata generate: layer split, CUDA%d head: %s%s\n" ,st .dev , 4273wo_s == nullptr ?"output.weight is missing" :err .c_str (), 4274wo_s == nullptr ?"" :vram_free_note ().c_str ()); 4275return 1 ; 4276 } 4277size_t fb = 0 ,tb = 0 ; 4278/* 4279DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions 4280for device information which may not be supported by all compilers or 4281runtimes. You may need to adjust the code. 4282*/ 4283 dpct::get_current_device ().get_memory_info (fb ,tb ); 4284 std::fprintf (stderr ,"strata generate: layer split: CUDA%d holds its weights, session [%lld, %lld)%s; " 4285"%.2f GiB free\n" ,st .dev , (long long )st .lb , (long long )st .le , 4286last ?" and the head" :"" , (double )fb /1073741824.0 ); 4287 } 4288 4289// --batch: every stage carves o.batch more sessions like its own (same layer range and context), one per 4290// slot of the batch windows. Before the expert cache is sized, so `--expert-cache auto` leaves them room. 4291// Recommend, never force: a count the engine cannot run is said and adjusted (or batching left off) - the 4292// engine still starts and serves one request at a time. 4293// --batch-mtp / STRATA_BATCH_MTP=1 (opt-in): a slot also verifies one MTP proposal per window. Recommend, never 4294// force: when it cannot run it is said and left off (plain batching still starts); default off = exactly 0.1.39. 4295const char * batch_mtp_env = std::getenv ("STRATA_BATCH_MTP" ); 4296bool batch_mtp = o .batch_mtp || (batch_mtp_env != nullptr && batch_mtp_env [0 ]!= '\0' && batch_mtp_env [0 ]!= '0' ); 4297if (batch_mtp ) { 4298const char * why = o .batch < 2 ?"it needs --batch 2 or more" :o .mtp .empty () ?"it needs --mtp" 4299 :o .spec < 2 ?"it needs --spec T (T >= 2)" : (multi_gpu || split_same || !stages .empty ()) 4300 ?"it is for one GPU (no layer split or helper) for now" : !o .serve ?"it needs --serve" :nullptr ; 4301if (why != nullptr ) { 4302 std::fprintf (stderr ,"strata generate: WARNING: --batch-mtp is off: %s\n" ,why ); 4303batch_mtp = false; 4304 } 4305 } 4306 std::vector < std::vector < std::unique_ptr < strata::core::SessionState >>> bslot_ss ; 4307if (o .batch != 0 ) { 4308const int cap = strata::kernels::kVerifyMaxT ; 4309const char * off = !o .serve ?"it needs --serve" :o .batch < 2 ?"it needs 2 or more slots" 4310 :split_same ?"it needs each stage of a layer split on its own GPU" :nullptr ; 4311if (off != nullptr ) { 4312 std::fprintf (stderr ,"strata generate: WARNING: --batch %d is off: %s\n" ,o .batch ,off ); 4313o .batch = 0 ; 4314 }else if (o .batch > cap && !batch_mtp ) { 4315 std::fprintf (stderr ,"strata generate: WARNING: --batch %d: a batch window holds at most %d rows, so %d " 4316"slots\n" ,o .batch ,cap ,cap ); 4317o .batch = cap ; 4318 } 4319 } 4320if (o .batch > 0 && o .batch_groups <=0 ) {// not given, or `auto` 4321const bool given_auto = o .batch_groups < 0 ; 4322int g = 1 ; 4323if (!stages .empty ()) { 4324const auto battlemage = [](int d )-> bool { 4325try {return strata::intel_gpu_gen (dpct::get_device (d ))== strata::IntelGpuGen ::Battlemage ; }catch (...) {return false; } 4326 }; 4327const bool two_b = stages .size ()== 1 && battlemage (0 )&& battlemage (stages [0 ]-> dev ); 4328static const char * ga = std::getenv ("STRATA_BATCH_GROUPS_AUTO" ); 4329const bool off = ga != nullptr && std::atoi (ga )== 0 ; 4330if (two_b && o .batch >=8 && o .batch %2 == 0 && !off ) { 4331g = 2 ; 4332 std::fprintf (stderr ,"strata generate: --batch-groups 2 by default: %d slots over a layer split on two Arc B-series " 4333"cards (--batch-groups 1 or STRATA_BATCH_GROUPS_AUTO=0 turns it off)\n" ,o .batch ); 4334 }else if (given_auto ) { 4335for (int d = 2 ;d <= (int )stages .size ()+ 1 && d <=o .batch ;++ d ) 4336if (o .batch %d == 0 )g = d ; 4337 } 4338 } 4339o .batch_groups = g ; 4340 } 4341if (o .batch > 0 && o .batch_groups > 1 && (stages .empty ()|| o .batch %o .batch_groups != 0 )) { 4342 std::fprintf (stderr ,"strata generate: WARNING: --batch-groups %d needs a layer split and to divide --batch %d; " 4343"one group\n" ,o .batch_groups ,o .batch ); 4344o .batch_groups = 1 ; 4345 } 4346if (o .batch > 0 ) { 4347bslot_ss .resize (1 + stages .size ()); 4348int fit = o .batch ;// the slots every stage could carve 4349uint64_t bytes0 = 0 ; 4350for (size_t k = 0 ;k < bslot_ss .size ();++ k ) { 4351const int dev = k == 0 ?0 :stages [k - 1 ]-> dev ; 4352const int64_t lo = k == 0 ?0 :stages [k - 1 ]-> lb ; 4353const int64_t hi = k == 0 ? (multi_gpu ?split_at [0 ] :-1 ) :stages [k - 1 ]-> le ; 4354const strata::core::OnDevice on_k (dev ); 4355const uint64_t bytes = strata::core::session_bytes (g ,o .max_context ,K ,lo ,hi ); 4356if (k == 0 )bytes0 = bytes ; 4357for (int b = 0 ;b < fit ;++ b ) { 4358auto u = std::make_unique < strata::core::SessionState > (); 4359void * buf = nullptr ; 4360if (DPCT_CHECK_ERROR (buf = (void * )sycl::malloc_device ( 4361bytes , dpct::get_in_order_queue ()))!= 43620 || 4363 strata::core::session_init (g ,o .max_context ,K ,buf ,* u ,lo , 4364hi )== 0 ) { 4365/* 4366DPCT1026: The call to cudaGetLastError was removed 4367because this functionality is redundant in SYCL. 4368*/ 4369if (buf != nullptr ) 4370 sycl::free (buf , dpct::get_in_order_queue ()); 4371size_t fb = 0 ,tb = 0 ; 4372/* 4373DPCT1106: 'cudaMemGetInfo' was migrated with the Intel 4374extensions for device information which may not be supported 4375by all compilers or runtimes. You may need to adjust the 4376code. 4377*/ 4378 dpct::get_current_device ().get_memory_info (fb ,tb ); 4379 std::fprintf (stderr ,"strata generate: WARNING: --batch %d: slot %d's session does not fit on CUDA%d " 4380"(%.2f GiB each, %.2f GiB free); %d slot%s\n" ,o .batch ,b ,dev , 4381 (double )bytes /1073741824.0 , (double )fb /1073741824.0 ,b ,b == 1 ?"" :"s" ); 4382fit = b ; 4383break ; 4384 } 4385 strata::core::session_zero (* u ,g ,nullptr ,nullptr ); 4386bslot_ss [k ].push_back (std::move (u )); 4387 } 4388 dpct::get_current_device ().queues_wait_and_throw (); 4389size_t fb = 0 ,tb = 0 ; 4390/* 4391DPCT1106: 'cudaMemGetInfo' was migrated with the Intel 4392extensions for device information which may not be supported by all 4393compilers or runtimes. You may need to adjust the code. 4394*/ 4395 dpct::get_current_device ().get_memory_info (fb ,tb ); 4396 std::fprintf (stderr ,"strata generate: --batch: %d slot sessions on CUDA%d (%.2f GiB each); %.2f GiB free\n" , 4397 (int )bslot_ss [k ].size (),dev , (double )bytes /1073741824.0 , (double )fb /1073741824.0 ); 4398 } 4399for (auto & v :bslot_ss )if ((int )v .size ()> fit )v .resize ((size_t )fit );// the same count on every stage 4400if (fit < 2 ) { 4401 std::fprintf (stderr ,"strata generate: WARNING: --batch is off: not two slot sessions fit (a smaller " 4402"--max-context or KV streaming, --kv-resident, makes them smaller)\n" ); 4403bslot_ss .clear (); 4404o .batch = 0 ; 4405 }else { 4406o .batch = fit ; 4407if (o .batch_groups > 1 && o .batch %o .batch_groups != 0 )o .batch_groups = 1 ; 4408// the sessions' VRAM is the expert cache's: say what it costs (docs/BATCHING.md has the measured trade) 4409 std::fprintf (stderr ,"strata generate: --batch %d: the slot sessions take %.2f GiB of VRAM on CUDA0 that the " 4410"expert cache would otherwise hold\n" ,o .batch , 4411 (double )bytes0 * o .batch /1073741824.0 ); 4412 } 4413 } 4414 4415// Secure MTP's CUDA0 allocations before the large host arena is registered with both CUDA contexts. 4416// In particular WDDM can refuse the draft weights after mapping tens of GiB of host pages. 4417// --draft dflash2: the MTP layer is NOT loaded and every "is there an MTP" test below sees --mtp as absent; DFlash2 drafts alone. The draft vocabulary file 4418// is taken from the --mtp directory. Anything DFlash2 cannot do here is an error at start, never a silent MTP. 4419 strata::core::Dflash2Drafter df2 ; 4420bool use_df2 = false; 4421 std::string df2_vocab_file ; 4422if (o .draft == "dflash2" ) { 4423if ((o .mtp .empty ()&& o .mtp_draft_vocab .empty ())|| o .spec < 2 || o .draft_model .empty ()) { 4424 std::fprintf (stderr ,"strata generate: --draft dflash2 needs --draft-model PACK, --spec 2 or more and --mtp DIR (for DIR/draft_vocab.bin) or --mtp-draft-vocab FILE\n" ); 4425return 2 ; 4426 } 4427df2_vocab_file = o .mtp_draft_vocab .empty () ?o .mtp + "/draft_vocab.bin" :o .mtp_draft_vocab ; 4428o .mtp .clear (); 4429if (o .draft_cap > 0 && o .spec > o .draft_cap ) { 4430 std::fprintf (stderr ,"strata generate: --draft dflash2: windows capped at %d tokens (--draft-cap)\n" ,o .draft_cap ); 4431o .spec = o .draft_cap ; 4432 } 4433 }else if (!o .draft .empty ()&& o .draft != "mtp" ) { 4434 std::fprintf (stderr ,"strata generate: --draft takes mtp or dflash2\n" ); 4435return 2 ; 4436 } 4437 strata::core::MtpDrafter mtp ; 4438// the draft layer's geometry (the canonical model's MTP head), `static` because MtpDrafter keeps a reference; the batch 4439// slots' draft-KV copies use this one too 4440static const strata::core::ModelGeometry draft_geometry = strata::core::kCompiledGeometry ; 4441 std::vector < std::unique_ptr < strata::core::MtpDrafter >> slot_mtp ; 4442if (!o .mtp .empty ()) { 4443if (o .spec < 2 ) { 4444 std::fprintf (stderr ,"strata generate: --mtp is ignored without --spec T (T >= 2)\n" ); 4445o .mtp .clear (); 4446 } 4447if (!o .mtp .empty ())mtp .set_prompt_len ((int64_t )o .tokens .size ()); 4448mtp .set_hnorm_per_stream (o .mtp_hnorm_stream );// --mtp-hnorm stream (opt-in), before any capture 4449mtp .set_q4 (o .mtp_q4 == "all" || o .mtp_q4 == "proj" ,o .mtp_q4 == "all" || o .mtp_q4 == "head" );// before load 4450if (!o .mtp_draft_vocab .empty ())mtp .set_draft_vocab (o .mtp_draft_vocab ); 4451// the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned, 4452// so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference 4453// with a layer split across GPUs the drafter reads the last stage's residual: it lives on that device 4454const strata::core::OnDevice on_mtp (last_st ?last_st -> dev :-1 ); 4455// --pipeline-windows 2: 8 rows (the chain runs on past the window in flight: its drafts, its bonus token and 4456// the next window's drafts), and the round/step graphs carry the forcing kernel 4457const int mtp_t = o .pipeline_windows >=2 ? strata::kernels::kVerifyMaxT :o .spec ; 4458if (o .pipeline_windows >=2 )mtp .set_force_capture (true); 4459if (!o .mtp .empty ()&& !mtp .load (o .mtp ,draft_geometry ,last_st ?last_st -> ss :ss ,mtp_t ,err ,o .mtp_window )) { std::fprintf (stderr ,"strata generate: %s%s\n" ,err .c_str (),vram_free_note ().c_str ());return 1 ; } 4460mtp .set_ple_session (& ss ); 4461if (batch_mtp ) { 4462for (int b = 0 ;b < o .batch ;++ b ) { 4463auto d = std::make_unique < strata::core::MtpDrafter > (); 4464if (!d -> load (o .mtp ,draft_geometry ,* bslot_ss [0 ][(size_t )b ],o .spec ,err ,o .mtp_window ,& mtp )) { 4465 std::fprintf (stderr ,"strata generate: batch MTP slot %d: %s%s\n" ,b ,err .c_str (), 4466vram_free_note ().c_str ()); 4467return 1 ; 4468 } 4469d -> set_max_drafts (1 );// the first candidate verifies one proposal per slot 4470d -> set_ple_session (bslot_ss [0 ][(size_t )b ].get ()); 4471slot_mtp .push_back (std::move (d )); 4472 } 4473 } 4474 } 4475if (o .draft == "dflash2" ) { 4476if (multi_gpu || o .batch > 0 || o .pipeline_windows > 0 ) { 4477 std::fprintf (stderr ,"strata generate: --draft dflash2 is for one card and one request at a time (not --batch, --pipeline-windows or a layer split) in this build\n" ); 4478return 2 ; 4479 } 4480if (!df2 .load (o .draft_model ,0 ,err )) { 4481 std::fprintf (stderr ,"strata generate: --draft dflash2: %s. DFlash2 needs about 1.2 GiB of VRAM; there is no MTP to draft instead, so the start ends here%s\n" , 4482err .c_str (),vram_free_note ().c_str ()); 4483return 1 ; 4484 } 4485use_df2 = true; 4486 } 4487// THE HEAD BEFORE THE CACHE, AND BEFORE THE ARENA. The expert cache takes what is free minus the reserve, so 4488// everything allocated after it comes out of the reserve. The native head (~0.5 GB with IQ3_S) was loaded after 4489// it and ate most of the 700 MiB: 128K IQ3_S ended with 30 MiB free, the driver paged, and a request stalled for 4490// good at its first verify window. Loaded first, the cache is sized around it. #620: and before the expert 4491// arena registers tens of GiB of host pages, like the drafter above - WDDM then refused the head's cudaMalloc on 4492// a 16 GB card with the desktop on the iGPU ("native head upload: out of memory" with GiBs free). 4493const strata::core::WeightRef * wo = wt .find ("output.weight" ); 4494if (wo == nullptr ) { std::fprintf (stderr ,"strata generate: output.weight is missing\n" );return 1 ; } 4495const int64_t n_vocab = wo -> ne1 ; 4496 strata::core::NativeHead native_head ; 4497if (!o .native_head_gguf .empty ()&& !multi_gpu ) {// a layer split's head is on its last stage 4498const auto head_t0 = std::chrono::steady_clock::now (); 4499if (!native_head .load (o .native_head_shards ,g .n_embd ,n_vocab ,err )) { 4500 std::fprintf (stderr ,"strata generate: %s%s\n" ,err .c_str (),vram_free_note ().c_str ()); 4501return 1 ; 4502 } 4503 std::fprintf (stderr ,"strata generate: experimental native Q5_K head, %llu bytes, in %.1f s\n" , 4504 (unsigned long long )native_head .weight_bytes (), 4505 std::chrono::duration < double > (std::chrono::steady_clock::now ()- head_t0 ).count ()); 4506 } 4507 strata::uc_probe ("after-head" ); 4508 b60_private::Layouts b60_layouts (size_t (o .vram_reserve_mib )* 1024 * 1024 ); 4509if (strata::kernels::b60_layout_requested ()&& strata::kernels::b60_single_actor_requested ()){ 4510const char * nh = std::getenv ("STRATA_VERIFY_NO_HOST" ); 4511const char * dp = std::getenv ("STRATA_VERIFY_DEVICE_PLAN" ); 4512const char * pr = std::getenv ("STRATA_PRIVATE_PACKED_REGISTER" ); 4513if (!o .serve || !native_pack || multi_gpu || !split_devs .empty ()|| o .pipeline_windows || !o .no_prefill_borrow || o .batch > 0 || o .prompt_cache != 0 || o .spec > 6 || o .adapt_async || !nh || std::strcmp (nh ,"1" )|| !dp || std::strcmp (dp ,"1" )|| !pr || std::strcmp (pr ,"1" )|| g .n_layers != 48 || g .n_expert != 512 || g .n_embd != 2560 || g .n_ff != 640 || g .hc != 4 || g .hc_lr != 320 ) 4514throw std::invalid_argument ("B60 single layout requires the fixed single-device no-host decode scene" ); 4515b60_layouts .prepare_single (wt ,native_head ,strata::kernels::cpu::expert_layout ()); 4516 } 4517 std::vector < float > logits ((size_t )n_vocab ); 4518float * d_logits = nullptr ; 4519if (DPCT_CHECK_ERROR ( 4520d_logits = (float * )sycl::malloc_device ( 4521 (size_t )n_vocab * 4 , dpct::get_in_order_queue ()))!= 0 ) { 4522/* 4523DPCT1010: SYCL uses exceptions to report errors and does not use 4524the error codes. The cudaGetLastError function call was replaced with 0. 4525You need to rewrite this code. 4526*/ 4527 (void )0 ; 4528 std::fprintf (stderr ,"strata generate: the logits buffer failed%s\n" ,vram_free_note ().c_str ()); 4529return 1 ; 4530 } 4531// Create the additional contexts after MTP has secured CUDA0 memory, but 4532// before the host arena maps its expert pages into their address spaces. 4533for (int r = 1 ;r < 3 ;++ r )if (o .expert_cache_remote [(size_t )r ]> 0 && !early_remote ) { 4534double free_gib = 0 ; 4535if (!strata::core::RemoteExperts ::preflight (remote_dev [r ],free_gib ,err )) { 4536 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 4537return 1 ; 4538 } 4539 std::fprintf (stderr ,"strata generate: CUDA%d context ready, %.2f GiB free before expert arena registration\n" , 4540remote_dev [r ],free_gib ); 4541 } 4542 4543// ---- the CPU expert pool 4544// 4545// R2.1: the experts are loaded into a RESIDENT ARENA by default. The mmap path is kept behind 4546// `--mmap-experts` because it is the A/B arm, not because it is competitive. 4547// 4548// The reasoning is the review's C1 and it is now measured on both sides. `FileExpertSource` maps the 34 GB 4549// file, and mapped file pages are the first thing the OS reclaims; the engine's rate then depends on whether 4550// the standby list happens to hold `experts.bin`, which is why two consecutive runs of the SAME BINARY with 4551// the SAME FLAGS measured 71.97 and 34.78 ms/token in the pool (7.54 vs 12.18 tok/s). The arena is 4552// anonymous memory the engine owns, and the pool runs at 19.41 ms/token - 1.79x better than the warm mmap 4553// and 3.7x better than the cold one. 4554// 4555// IT IS NOT PINNED, and that is reported rather than hidden: `cudaHostRegister` on 31.64 GiB fails with 4556// "out of memory" (you cannot pin 34 of 63 GB) and the arena falls back to 4 KB anonymous pages. That is 4557// fine for the CPU pool - which is all that exists today - and NOT fine for Phase 3, whose cache fills and 4558// CPU/PCIe miss split need the GPU to DMA out of this arena. Read `note()` when that lands. 4559// 4560// The earlier "the arena does not fit" conclusion was WRONG and is worth recording: the failure was a stale 4561// CUDA error left set by the failed `cudaHostRegister` and read later by `gr_read`'s launch check. See the 4562// note in `pinned.cu`. 4563 strata::core::FileExpertSource src ; 4564 {// the card, and whether this build has code for it (a binary built for other GPUs fails at its first kernel 4565// otherwise, after the whole expert arena has loaded) - before the arena starts loading 4566int dev = 0 ; 4567 dpct::device_info p {}; 4568const bool named = 4569DPCT_CHECK_ERROR (dev = dpct::get_current_device_id ())== 0 && 4570DPCT_CHECK_ERROR (dpct::get_device (dev ).get_device_info (p ))== 0 ; 4571/* 4572DPCT1010: SYCL uses exceptions to report errors and does not use 4573the error codes. The cudaGetLastError function call was replaced with 0. 4574You need to rewrite this code. 4575*/ 4576if (!named )0 ; 4577const char * name = 4578named && p .get_name ()[0 ] ?p .get_name () :"(an unnamed GPU)" ; 4579#if defined(STRATA_USE_HIP ) 4580 std::fprintf (stderr ,"strata generate: GPU %d: %s (%s)\n" ,dev ,name ,named ?p .gcnArchName :"?" ); 4581#if defined(_WIN32 ) 4582// #468 #461: which HIP runtime was loaded - the bundled one beside the exe, or an AMD driver's System32 copy 4583if (HMODULE h = GetModuleHandleA ("amdhip64_7.dll" )) { 4584char path [MAX_PATH ]= {}; 4585if (GetModuleFileNameA (h ,path ,MAX_PATH )> 0 ) 4586 std::fprintf (stderr ,"strata generate: HIP runtime %s\n" ,path ); 4587 } 4588#endif 4589#else 4590 std::fprintf ( 4591stderr ,"strata generate: GPU %d: %s, compute capability %d.%d%s\n" , 4592dev ,name , 4593/* 4594DPCT1005: The SYCL device version is different from CUDA 4595Compute Compatibility. You may need to rewrite this code. 4596*/ 4597 strata::cc_major_of (p .get_major_version ()), 4598 strata::cc_minor_of (p .get_minor_version ()), 4599 strata::emulated_cc () 4600 ?" (STRATA_EMULATE_CC: a test mode, the card is emulated)" 4601 :"" ); 4602// (the CUDA runtime/headers mismatch warning, #542, lives in src/program/generate.cpp; a SYCL port has no CUDA runtime to mismatch; sycl/tools/fixups.py keeps this block out) 4603#endif 4604const std::string e = strata::core::device_code_error (); 4605if (!e .empty ()) { 4606 std::fprintf ( 4607stderr , 4608"strata generate: this engine has no code for %s (sm_%d%d): %s " 4609"- rebuild it for this " 4610/* 4611DPCT1005: The SYCL device version is different from CUDA 4612Compute Compatibility. You may need to rewrite this code. 4613*/ 4614"card (setup does: START-HERE.bat --setup)\n" , 4615name ,p .get_major_version (),p .get_minor_version (),e .c_str ()); 4616return 1 ; 4617 } 4618 } 4619 strata::core::ArenaExpertSource arena_src ; 4620 strata::core::GgufExpertSource gguf_src ; 4621 strata::core::ExpertSource * srcp = nullptr ; 4622if (o .stream_experts && !o .mmap_experts ) { 4623// the SYCL port: a card that holds every expert needs no host copy of them, and a 23 GiB machine cannot 4624// hold one. The profile fill reads each blob once from the shard; nothing reads from here afterwards 4625// unless a slot is lent to the prefill and refilled (the experts no slot holds: the pinned host mirror). 4626if (!native_pack || o .native_preset .empty ()) { 4627 std::fprintf (stderr ,"strata generate: --stream-experts needs a native (IQ) pack and --native SHARD1\n" ); 4628return 2 ; 4629 } 4630if (!gguf_src .open (o .native_preset ,g .n_layers ,g .n_expert ,err )) { 4631 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 4632return 1 ; 4633 } 4634 std::fprintf (stderr ,"strata generate: experts streamed from the GGUF on demand (--stream-experts): no host " 4635"arena; every expert must fit the VRAM cache\n" ); 4636srcp = & gguf_src ; 4637 }else if (o .mmap_experts ) { 4638// FileExpertSource maps the pack's experts.bin: a canonical pack has it; a native (IQ) pack has it when 4639// built with `tools/iq_pack.py --experts-bin` (the per-layer blob sizes of its layout, PR #121). The low-RAM 4640// mode: the experts come from the file through the OS cache instead of a pinned copy in RAM, for a PC whose 4641// GPU holds most of them but whose RAM cannot hold them all. 4642// CS-T: a native pack without experts.bin maps the model's GGUF shards instead (native_experts.txt's spans, 4643// checked against the files first) - no 30-77 GB copy of the experts on the disk 4644src .set_gguf (o .native_preset ); 4645if (const char * v = std::getenv ("STRATA_FETCH_THREADS" );v != nullptr && std::atoi (v )> 0 ) 4646src .set_fetch_threads (std::atoi (v )); 4647if (!src .open (o .pack ,g .n_layers ,g .n_expert ,err )) { 4648 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 4649return 1 ; 4650 } 4651 std::fprintf (stderr ,"strata generate: experts via mmap (--mmap-experts; %s)\n" , 4652src .gguf_mode () ?"the GGUF shards in place, no experts.bin" :"the A/B arm of R2.1" ); 4653// #286: with a RAM budget the hottest experts live in it, and the rest are read from the drive unbuffered 4654// when the file cache could not keep them beside the budget anyway (a 32 GB PC) - the mapped reads' page 4655// faults are small requests on the critical path, and their pages take the RAM the budget was sized for 4656// #773: without a RAM budget there is no RAM copy and the file cache IS the expert tier (measured on a 4657// 32 GB, 2 x 16 GB rig: forcing unbuffered reads there re-read 163-629 GB from the drive and halved the 4658// speed), so STRATA_UNBUFFERED_LOAD=1 is not honoured in that mode 4659if (o .resident_budget > 0 ) { 4660 std::string why ; 4661const bool ub = src .set_unbuffered (o .resident_budget ,why ); 4662 std::fprintf (stderr ,"strata generate: the file tier reads %s (%s)\n" , 4663ub ?"unbuffered" :"through the file cache" ,why .c_str ()); 4664 }else if (const char * env = std::getenv ("STRATA_UNBUFFERED_LOAD" );env != nullptr && env [0 ]!= '\0' && 4665env [0 ]!= '0' ) { 4666 std::fprintf (stderr ,"strata generate: the file tier reads through the file cache (STRATA_UNBUFFERED_LOAD=%s " 4667"ignored: without --resident-budget-gib the file cache holds the experts)\n" ,env ); 4668 } 4669srcp = & src ; 4670 }else { 4671arena_src .set_gguf (o .native_preset );// plan v0.3 P6: a native pack may take its experts from shard 1 4672// Under WDDM (Windows, WSL2), a multi-GPU run (a layer split, or remote experts) starts with at most 8 GiB of 4673// mapped host pages: pinning all of it into two contexts leaves WDDM refusing every later allocation - 4674// measured on the 5080 + 3090 rig: cudaMemGetInfo and the next cudaMalloc fail. Unregistered layers remain 4675// in the resident arena; their streamed experts go through the pinned staging ring. A Linux driver has no 4676// such limit, so there the whole arena is pinned (#253). STRATA_ARENA_PIN_GIB overrides both ways. 4677const int pin_env = strata::core::arena_pin_cap_gib ();// -1 unset, -2 "auto" (#243, Windows sliced pin) 4678const bool pin_wddm_cap = pin_env < 0 && (o .expert_cache_remote [0 ]> 0 || multi_gpu )&& under_wddm (); 4679const uint64_t pin_limit = pin_env >=0 ? (uint64_t )pin_env <<30 :pin_wddm_cap ? (8ull <<30 ) :0 ; 4680if (pin_env >=0 ) 4681 std::fprintf (stderr ,"strata generate: STRATA_ARENA_PIN_GIB=%d: %s\n" ,pin_env , 4682pin_env == 0 ?"the whole expert arena is pinned" :"the expert arena's pinning is capped" ); 4683else if (pin_wddm_cap ) 4684 std::fprintf (stderr ,"strata generate: multi-GPU under WDDM: at most 8 GiB of the expert arena is pinned " 4685"(STRATA_ARENA_PIN_GIB changes it)\n" ); 4686if (!arena_src .open (o .pack ,g .n_layers ,g .n_expert ,/*threads=*/ 6 ,err ,pin_limit , 4687o .shared_expert_arena )) { 4688 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 4689return 1 ; 4690 } 4691if (!arena_src .ram_warning ().empty ())// #633: said before the load's numbers, which it explains 4692 std::fprintf (stderr ,"strata generate: WARNING: %s\n" ,arena_src .ram_warning ().c_str ()); 4693 std::fprintf (stderr ,"strata generate: expert arena: %s\n" ,arena_src .note ().c_str ()); 4694 std::fprintf (stderr ,"strata generate: loaded %.2f GiB at %.2f GiB/s\n" , 4695 (double ) strata::kernels::cpu::expert_layout ().total / (1024.0 * 1024 * 1024 ), 4696arena_src .load_gib_per_second ()); 4697// A rate under ~0.2 GiB/s is not the hardware. Task Scheduler / service contexts throttle this 4698// read+fill about 24x (measured 0.05 vs 1.42 GiB/s for the same binary, args and cache state; the 4699// scheduler's defaults - Below normal priority and a least-privilege token - were the only 4700// difference between the runs). Say so instead of letting the user blame the disk; see 4701// docs/DETAILS.md, "Running it at startup (Task Scheduler)". 4702#ifdef _WIN32 // a Windows launch context; elsewhere a load this slow is the disk 4703if (arena_src .load_gib_per_second ()> 0.0 && arena_src .load_gib_per_second ()< 0.2 ) { 4704 std::fprintf (stderr , 4705"strata generate: hint: ~24x below what this hardware streams from a normal " 4706"launch. If Strata is started by Task Scheduler or a service, register the task " 4707"with Priority 4 (Normal) and 'Run with highest privileges' - the scheduler's " 4708"defaults (Below normal + a least-privilege token) throttle the load. See " 4709"docs/DETAILS.md ('Running it at startup').\n" ); 4710 } 4711#endif 4712srcp = & arena_src ; 4713 } 4714 strata::kernels::cpu::ExpertPool pool (o .pool_workers ,/*pin=*/ true,/*host_works=*/ !o .no_host_worker ,o .pool_affinity ); 4715if (pool .is_hybrid ()&& pool .affinity ()!= strata::kernels::cpu::PoolAffinity ::All ) { 4716const char * aff_str = pool .affinity ()== strata::kernels::cpu::PoolAffinity ::PCores ?"p-cores" : 4717pool .affinity ()== strata::kernels::cpu::PoolAffinity ::All ?"all" :"auto" ; 4718 std::fprintf (stderr ,"strata generate: hybrid CPU detected (%d P-cores / %d threads, %d E-cores), pool workers: %d, affinity: %s\n" , 4719pool .p_cores (),pool .p_threads (),pool .e_cores (),pool .workers (),aff_str ); 4720 } 4721 {// where the threads run (--host-core) 4722const strata::kernels::cpu::CpuTopology ht = strata::kernels::cpu::detect_cpu_topology (true,o .pool_affinity ); 4723 std::string on ; 4724for (int i = 0 ;i < pool .workers ()&& i < (int )ht .worker_cores .size ();++ i ) 4725on += (i > 0 ?"," :"" )+ std::to_string (ht .worker_cores [(size_t )i ]); 4726 std::fprintf (stderr ,"strata generate: %d pool workers on logical processors %s, the host thread on %d%s " 4727"(--host-core %s)\n" ,pool .workers (),on .c_str (),ht .host_core , 4728pool .host_works () ?" (draining too)" :"" , 4729 strata::kernels::cpu::host_core_setting ()== strata::kernels::cpu::HostCore ::Last ?"last" :"first" ); 4730// the same facts in plain words, and whether each worker has a physical core of its own 4731 std::fprintf (stderr ,"strata generate: %s\n" ,pool .placement_line ().c_str ()); 4732 } 4733if (o .no_ple_prefetch ) strata::kernels::ple_prefetch_enable (false); 4734// ---- R4's slot storage. Allocated AFTER the weights and the session, so `cudaMemGetInfo` inside `open` 4735// sees the memory this process actually has left rather than the card's idle figure - and refuses with both 4736// numbers if the slots do not fit, instead of handing back a cache smaller than it was asked for. 4737mem_mark ("the weights, the session and the drafter" ); 4738 strata::core::ExpertCache xcache ; 4739// THE HEAD BEFORE THE CACHE: the native head and the logits are allocated above, before the expert arena (#620) 4740const bool auto_cache = o .expert_cache < 0 ; 4741bool reserve_adapted = false;// #496: the auto sizing lowered the reserve so a small card's cache fits 4742// --pipeline-windows: what it allocates on CUDA0 after the cache (see kPipeWindowMib) 4743const int64_t pipe_first = o .pipeline_windows <=0 ?0 4744 : (kPipeWindowMib <<20 )+ (o .pipeline_windows >=2 ?2 * (int64_t )gdn_snapshot_bytes (ss ) :0 ); 4745if (pipe_first > 0 ) 4746 std::fprintf (stderr ,"strata generate: --pipeline-windows %d: %lld MiB of CUDA0 kept out of the expert cache " 4747"(the second verifier%s)\n" ,o .pipeline_windows , (long long ) (pipe_first >>20 ), 4748o .pipeline_windows >=2 ?", the GDN snapshots" :"" ); 4749// The MiB the prompt path's OWN buffers (no loan) take, which the cache sizing leaves out. 0.1.39's rule is 4750// 160 + chunk * 680 / 1024 (~16 GiB at 24576 against ~2.4 GiB really allocated); STRATA_OWNED_PRICE=exact prices the 4751// real allocation instead (Prefill::bytes_needed_owned: 2 MiB pages, the ring in one piece, as PR #796 measured) 4752// and gives that cache the difference. A recommendation to try, so it is not the default. 4753auto owned_prefill_mib = [& ]()-> int64_t { 4754if (!(o .prefill_chunk > 0 && !pf_borrow ))return 0 ; 4755static const bool exact = [] {const char * v = std::getenv ("STRATA_OWNED_PRICE" );return v != nullptr && std::string (v )== "exact" ; }(); 4756if (!exact )return 160 + (o .prefill_chunk * 680 ) /1024 ; 4757const int64_t mib = ((int64_t ) strata::prefill::Prefill ::bytes_needed_owned (g ,ss ,o .prefill_chunk )+ (1 <<20 )- 1 ) >>20 ; 4758 std::fprintf (stderr ,"strata generate: STRATA_OWNED_PRICE=exact: the prompt path's own buffers for a %lld-token chunk: %lld MiB (the 0.1.39 rule: %lld MiB)\n" , 4759 (long long )o .prefill_chunk , (long long )mib , (long long ) (160 + (o .prefill_chunk * 680 ) /1024 )); 4760return mib + 64 ;// a margin for the allocator 4761 }; 4762if (o .expert_cache < 0 ) { 4763size_t free_b = 0 ,total_b = 0 ; 4764free_b = strata::core::device_free_bytes (); (void )total_b ; 4765// Plan v0.3 P5: the batched prompt path's chunk buffers are allocated later, so they are reserved here - 4766// under WDDM an over-subscribed allocation does not fail, it pages to system memory and crawls. 4767// (with borrowing - the default with a profile - the prompt path lends cache slots instead; `pf_borrow` is 4768// the predicate a local `borrow` was here, hoisted above so both cache-size branches read the same one) 4769int64_t prefill_mib = owned_prefill_mib (); 4770// the draft layer's head and logits are allocated when it binds, after this: 0.1.27's CJK subset made them 4771// ~110-180 MiB larger, and out of the reserve they left 16 GB cards below the stall line (#199) 4772int64_t mtp_bind = (!o .mtp .empty ()&& native_head .loaded ()) 4773 ? (int64_t )mtp .bind_bytes (native_head .row_bytes (),n_vocab ) :0 ; 4774for (const auto & d :slot_mtp ) 4775mtp_bind += (int64_t )d -> bind_bytes (native_head .row_bytes (),n_vocab ); 4776if (use_df2 && native_head .loaded ()) {// DFlash2's draft head rows and ids (from the vocabulary file), its logits, 48 MiB of margin 4777int64_t bytes = (int64_t ) std::min (o .spec , (int ) strata::kernels::kVerifyMaxT )* n_vocab * (int64_t )sizeof (float ); 4778if (FILE * vf = std::fopen (df2_vocab_file .c_str (),"rb" )) { 4779 std::fseek (vf ,0 ,SEEK_END ); 4780const long size = std::ftell (vf ); 4781 std::fclose (vf ); 4782if (size >=4 && size %4 == 0 )bytes += (int64_t ) (size /4 )* (int64_t )native_head .row_bytes ()+ (int64_t )size ; 4783 } 4784mtp_bind += bytes + (48 <<20 ); 4785 } 4786const int64_t reserve = (((int64_t )o .vram_reserve_mib + prefill_mib ) <<20 )+ mtp_bind + pipe_first ; 4787const int64_t blob = (int64_t ) strata::kernels::cpu::expert_layout ().max_blob ; 4788int64_t slots = ((int64_t )free_b - reserve ) /blob ; 4789if (!profile .empty ())slots = std::min < int64_t > (slots , (int64_t )profile .size ()); 4790o .expert_cache = (int ) std::max < int64_t > (slots ,0 ); 4791 std::fprintf (stderr ,"strata generate: expert cache auto: %.2f GiB free, %d MiB reserved (+%lld MiB for the " 4792"draft head) -> %d slots\n" , 4793 (double )free_b /1073741824.0 ,o .vram_reserve_mib , (long long ) (mtp_bind >>20 ),o .expert_cache ); 4794// #496: the verify window cannot start without a cache (#174), and a cache too small to lend the prompt path 4795// a 256-token chunk's buffers (plus the 128 slots a loan leaves; one slot without --prefill) makes it 4796// allocate its own on top - more than the reserve. When the default reserve leaves less than that (a 6 GB 4797// card), the reserve shrinks to what leaves exactly that cache, down to kSmallReserveMib: what is allocated 4798// after the cache - the prompt path's own part, the verify buffers, the draft head - comes out of the reserve, 4799// and below ~550 MiB a card ends with less than the 256 MiB the serve check calls LOW (IQ3_XXS, 32K, a 300 MiB 4800// reserve: 5 MiB left), so the cache gets no more than it needs, and the serve check says so plainly when it 4801// ends LOW (`reserve_adapted`). A reserve given on the command line is kept. No slot at all: the start 4802// stops, saying what is short and what makes room. A card the default reserve leaves that much is sized as 4803// before. 4804constexpr int kSmallReserveMib = 300 ; 4805const int64_t min_slots = (o .prefill_chunk > 0 && pf_borrow ) 4806 ? ((int64_t ) strata::prefill::Prefill ::bytes_needed (g ,ss ,256 )+ blob - 1 ) /blob + 128 :1 ; 4807if (o .expert_cache < min_slots && !o .vram_reserve_given && o .vram_reserve_mib > kSmallReserveMib ) { 4808// the largest reserve (in MiB) that still leaves min_slots 4809const int64_t fit_mib = ((int64_t )free_b - mtp_bind - pipe_first - min_slots * blob ) / (1 <<20 )- prefill_mib ; 4810if (fit_mib >=kSmallReserveMib ) { 4811const int r = (int ) std::min < int64_t > (fit_mib ,o .vram_reserve_mib ); 4812int64_t s2 = ((int64_t )free_b - ((((int64_t )r + prefill_mib ) <<20 )+ mtp_bind + pipe_first )) /blob ; 4813if (!profile .empty ())s2 = std::min < int64_t > (s2 , (int64_t )profile .size ()); 4814 std::fprintf (stderr ,"strata generate: expert cache auto: the %d MiB reserve leaves too few slots on " 4815"this card (a working cache needs %lld): a %d MiB reserve instead -> %lld slots\n" , 4816o .vram_reserve_mib , (long long )min_slots ,r , (long long )s2 ); 4817o .vram_reserve_mib = r ; 4818o .expert_cache = (int )s2 ; 4819reserve_adapted = true; 4820 } 4821 } 4822// Requests at once and a long context never make a start refuse when it can run slower (owner rule). Still short of a working cache, the speed knobs 4823// go first, in this order: the prompt path's own chunk (its buffers are 160 + 0.66 MiB a token, 1182 MiB at 2048; --prefill N is the person's and stays), 4824// then a reserve that was asked for (down to kSmallReserveMib, the one a small card runs on). The cache keeps what is left; only a start that 4825// has no slot even then is refused, below. 4826constexpr int64_t kWorkCacheSlots = 128 ;// below this the cache is too small to be worth its name (the prompt path cannot lend, every miss goes to the CPU) 4827constexpr int64_t kMinChunk = 256 ; 4828// (only a start that would stop: no slot, or - sized for a loan - too few slots to lend the prompt path its chunk, so that it allocates its own on top 4829// of a cache that took the VRAM; a start that runs is left as it was sized) 4830if (o .expert_cache < min_slots && o .prefill_chunk > 0 ) { 4831const strata::core::ShortCache sc = strata::core::size_short_cache ( 4832 (int64_t )free_b ,o .vram_reserve_mib ,o .vram_reserve_given ,kSmallReserveMib , 4833pf_borrow ? std::min < int64_t > (o .prefill_chunk ,1024 ) :o .prefill_chunk ,// (what the loan-less path takes when nothing can be lent) 4834o .prefill_given ,kMinChunk ,kWorkCacheSlots ,mtp_bind ,pipe_first ,blob , (int64_t )profile .size ()); 4835const int64_t chunk = sc .chunk ,reserve_mib = sc .reserve_mib ,n = sc .slots ; 4836if (n > o .expert_cache || (pf_borrow && n > 0 )) { 4837 std::fprintf (stderr ,"strata generate: expert cache auto: short of VRAM, so the start runs slower instead of stopping: %s%s%s -> %lld slots\n" , 4838chunk != o .prefill_chunk ? ("prompt chunk " + std::to_string (o .prefill_chunk )+ " -> " + std::to_string (chunk )+ " tokens" ).c_str () :"" , 4839chunk != o .prefill_chunk && reserve_mib != o .vram_reserve_mib ?", " :"" , 4840reserve_mib != o .vram_reserve_mib ? ("reserve " + std::to_string (o .vram_reserve_mib )+ " -> " + std::to_string (reserve_mib )+ " MiB" ).c_str () :"" , 4841 (long long )n ); 4842if (reserve_mib != o .vram_reserve_mib )reserve_adapted = true; 4843if (pf_borrow )o .prefill_auto = false;// the chunk is the person's-sized now: its own buffers, no loan to size it from 4844o .prefill_chunk = chunk ; 4845o .vram_reserve_mib = (int )reserve_mib ; 4846o .expert_cache = (int )n ; 4847prefill_mib = owned_prefill_mib (); 4848 }else if (pf_borrow && n == 0 ) { 4849o .expert_cache = 0 ;// sized for a loan that cannot happen, and no slot once the prompt path's own buffers are priced: the refusal below says so 4850 } 4851 } 4852if (o .expert_cache == 0 ) { 4853// what is short, and what makes room: the numbers a small card picks from 4854const int64_t at_reserve = o .vram_reserve_given ?o .vram_reserve_mib 4855 : std::min (o .vram_reserve_mib ,kSmallReserveMib ); 4856const int64_t need_b = (((int64_t )at_reserve + prefill_mib ) <<20 )+ mtp_bind + pipe_first + min_slots * blob ; 4857const int64_t short_mib = std::max < int64_t > (1 , (need_b - (int64_t )free_b + (1 <<20 )- 1 ) >>20 ); 4858const int64_t session_mib = 4859 (int64_t ) (strata::core::session_bytes (g ,o .max_context ,K ,0 ,g .n_layers ) >>20 ); 4860const std::string reserve_tip = 4861o .vram_reserve_given && o .vram_reserve_mib > kSmallReserveMib 4862 ?", a smaller --vram-reserve-mib (" + std::to_string (o .vram_reserve_mib )+ " now; " + 4863 std::to_string (kSmallReserveMib )+ " is enough on a small card)" 4864 : std::string (); 4865 std::fprintf (stderr ,"strata generate: no VRAM is left for the expert cache: it needs at least %lld slots " 4866"(%lld MiB), about %lld MiB more than this card has free. To make room: a smaller " 4867"--max-context (the session, mostly its KV cache, takes %lld MiB at %lld tokens), " 4868"--kv q4_0, the English draft subset (setup --draft-vocab en; the draft head takes " 4869"%lld MiB now)%s, images on the CPU, or close other programs that use the GPU\n" , 4870 (long long )min_slots , (long long ) ((min_slots * blob ) >>20 ), (long long )short_mib , 4871 (long long )session_mib , (long long )o .max_context , (long long ) (mtp_bind >>20 ), 4872reserve_tip .c_str ()); 4873g_no_cache_hint = "this card cannot hold even the smallest start: with prompt chunks of 256 tokens and the reserve at " + std::to_string (at_reserve )+ 4874" MiB, the expert cache still needs " + std::to_string (min_slots * blob >>20 )+ " MiB and the card is about " + std::to_string (short_mib )+ 4875" MiB short. Taken: " + (o .batch > 1 ? std::to_string (o .batch )+ " request slots " + std::to_string (o .batch * session_mib )+ " MiB, " : std::string ())+ 4876"the context " + std::to_string (session_mib )+ " MiB at " + std::to_string (o .max_context )+ " tokens, the draft head " + 4877 std::to_string (mtp_bind >>20 )+ " MiB. Lower " + (o .batch > 1 ?"the number of requests at once (--batch / parallel), " :"" )+ 4878"use --kv q4_0 (smaller K/V), turn off the draft layer, or close other programs that use the GPU" ; 4879 } 4880 }else if (multi_gpu && o .expert_cache > 0 ) { 4881// an explicit cache size leaves room for the prompt path's buffers and the reserve, or the first prompt 4882// fails with "device buffers ... do not fit" (with borrowing - the default with a profile - the path lends 4883// slots instead and `prefill_mib` is 0, so only the reserve is checked) 4884size_t free_b = 0 ,total_b = 0 ; 4885free_b = strata::core::device_free_bytes (); (void )total_b ; 4886const int64_t prefill_mib = owned_prefill_mib (); 4887const int64_t reserve = (((int64_t )o .vram_reserve_mib + prefill_mib ) <<20 )+ pipe_first ; 4888const int64_t fit = std::max < int64_t > (((int64_t )free_b - reserve ) / (int64_t ) strata::kernels::cpu::expert_layout ().max_blob ,0 ); 4889if (o .expert_cache > fit ) { 4890// a WARNING that names the knob: the user asked for this size, and gets fewer slots 4891 std::fprintf (stderr ,"strata generate: WARNING: layer split: --expert-cache %d leaves no room for the " 4892"prompt path's buffers (%lld MiB) and the %d MiB reserve on CUDA0: %lld slots instead " 4893"(a smaller --vram-reserve-mib leaves more of them)\n" ,o .expert_cache , 4894 (long long )prefill_mib ,o .vram_reserve_mib , (long long )fit ); 4895o .expert_cache = (int )fit ; 4896 } 4897 } 4898// plan v0.3 P6: a native pack's blobs differ per layer, so the same VRAM holds more experts than slots of 4899// the largest blob would. The shared cache below sizes slots in profile order. 4900// #369: that list does not match --expert-cache-per-layer. A range is layer * quota + n, so a size cut for 4901// one layer can land in another layer's slot. Every expert in a layer is one size, so the per-layer list is 4902// `quota` copies of that layer's own blob, in layer order. `--expert-cache N` stays the budget of N largest 4903// blobs, and the quota is however many copies of every layer fit in it. 4904 std::vector < int64_t > sized_slots ; 4905uint64_t per_layer_bytes = 0 ; 4906if (native_pack && o .expert_cache > 0 && o .expert_cache_per_layer ) { 4907size_t free_b = 0 ,total_b = 0 ; 4908/* 4909DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions 4910for device information which may not be supported by all compilers or 4911runtimes. You may need to adjust the code. 4912*/ 4913 dpct::get_current_device ().get_memory_info (free_b ,total_b ); 4914const auto & lay = strata::kernels::cpu::expert_layout (); 4915const int asked = o .expert_cache ; 4916const uint64_t budget = (uint64_t )asked * lay .max_blob ; 4917size_t free_room = free_b > ((size_t )o .vram_reserve_mib <<20 ) ?free_b - ((size_t )o .vram_reserve_mib <<20 ) :0 ; 4918const uint64_t cap = std::min < uint64_t > (budget , (uint64_t )free_room ); 4919uint64_t sum = 0 ; 4920for (int64_t l = 0 ;l < g .n_layers ;++ l ) 4921sum += (lay .blob_bytes (l )+ 255 ) /256 * 256 ; 4922int64_t q = sum > 0 ? (int64_t ) (cap /sum ) :0 ; 4923if (q > g .n_expert )q = g .n_expert ; 4924if (q > 0 ) { 4925per_layer_bytes = sum ; 4926sized_slots .reserve ((size_t )q * (size_t )g .n_layers ); 4927for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 4928const int64_t b = (int64_t )lay .blob_bytes (l ); 4929for (int64_t s = 0 ;s < q ;++ s )sized_slots .push_back (b ); 4930 } 4931o .expert_cache = (int )sized_slots .size (); 4932 std::fprintf (stderr ,"strata generate: per-layer slots use each layer's blob: %d uniform slots " 4933"(%.2f GiB) -> %d slots, %lld per layer (%.2f GiB)\n" , 4934asked , (double )budget /1073741824.0 ,o .expert_cache , (long long )q , 4935 (double ) ((uint64_t )q * per_layer_bytes ) /1073741824.0 ); 4936 } 4937 }else if (native_pack && o .expert_cache > 0 && !profile .empty ()) { 4938size_t free_b = 0 ,total_b = 0 ; 4939free_b = strata::core::device_free_bytes (); (void )total_b ; 4940const auto & lay = strata::kernels::cpu::expert_layout (); 4941const uint64_t budget = (uint64_t )o .expert_cache * lay .max_blob ;// what the uniform sizing granted 4942uint64_t used = 0 ; 4943const size_t keep_free = ((size_t )o .vram_reserve_mib <<20 )+ (size_t )pipe_first ; 4944size_t free_room = free_b > keep_free ?free_b - keep_free :0 ; 4945const uint64_t cap = std::min < uint64_t > (budget , (uint64_t )free_room ); 4946for (const auto & pr :profile ) { 4947const uint64_t b = (lay .blob_bytes (pr .first )+ 255 ) /256 * 256 ; 4948if (used + b > cap )break ; 4949used += b ; 4950sized_slots .push_back ((int64_t )lay .blob_bytes (pr .first )); 4951 } 4952// #831: the sized-slots loop walks the profile's pairs, so the profile's length is the ceiling; an explicit 4953// --expert-cache above it used to be cut with no word. A warning only (what is allocated does not change). 4954if (!auto_cache && o .expert_cache > 0 && sized_slots .size ()== profile .size ()&& (size_t )o .expert_cache > profile .size ()) 4955 std::fprintf (stderr ,"strata generate: WARNING: --expert-cache %d is more than the %zu pairs of the profile %s: " 4956"%zu slots (the profile is the ceiling on a native pack; a profile that ranks every " 4957"(layer, expert) pair lifts it - tools/make_profile.py)\n" ,o .expert_cache , 4958profile .size (),o .expert_profile .c_str (),profile .size ()); 4959o .expert_cache = (int )sized_slots .size (); 4960 } 4961// #533: --vram-elastic: the cache in physical segments (the VRAM command resizes it between requests). One GPU, 4962// no helper caches, serve mode: anything else keeps the one cudaMalloc, said once. 4963if (o .vram_elastic ) { 4964const char * why = !o .serve ?"it works between requests of --serve" 4965 :multi_gpu ?"a layer split has a cache per GPU" 4966 : std::any_of (o .expert_cache_remote .begin (),o .expert_cache_remote .end (), 4967 [](int n ) {return n > 0 ; }) ?"the helper caches on other GPUs" 4968 :o .vram_segment_mib < 64 ?"--vram-segment-mib is below 64" :nullptr ; 4969#if defined(STRATA_USE_HIP ) 4970if (why == nullptr )why = "it is NVIDIA-only for now" ; 4971#endif 4972if (why != nullptr ) { 4973 std::fprintf (stderr ,"strata generate: --vram-elastic is off: %s\n" ,why ); 4974o .vram_elastic = false; 4975 }else { 4976xcache .set_segment_bytes (o .vram_segment_mib <<20 ); 4977 } 4978 } 4979if (o .expert_cache > 0 ) { 4980// keep the first `keep_bytes` of the cache (the profile's hottest experts first); false when nothing is left 4981auto shrink_to = [& ](int64_t keep_bytes )-> bool { 4982if (keep_bytes <=0 ) {o .expert_cache = 0 ;sized_slots .clear ();return false; } 4983if (per_layer_bytes > 0 ) { 4984// Cutting the list short would put one layer's blob in the next layer's range. 4985const auto & lay = strata::kernels::cpu::expert_layout (); 4986int64_t q = keep_bytes / (int64_t )per_layer_bytes ; 4987if (q > g .n_expert )q = g .n_expert ; 4988sized_slots .clear (); 4989if (q <=0 ) {o .expert_cache = 0 ;return false; } 4990for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 4991const int64_t b = (int64_t )lay .blob_bytes (l ); 4992for (int64_t s = 0 ;s < q ;++ s )sized_slots .push_back (b ); 4993 } 4994o .expert_cache = (int )sized_slots .size (); 4995return true; 4996 } 4997if (!sized_slots .empty ()) { 4998int64_t used = 0 ; 4999size_t keep = 0 ; 5000while (keep < sized_slots .size ()&& used + (sized_slots [keep ]+ 255 ) /256 * 256 <=keep_bytes ) 5001used += (sized_slots [keep ++ ]+ 255 ) /256 * 256 ; 5002sized_slots .resize (keep ); 5003o .expert_cache = (int )keep ; 5004 }else { 5005o .expert_cache = (int ) (keep_bytes / (int64_t ) strata::kernels::cpu::expert_layout ().max_blob ); 5006 } 5007if (o .expert_cache <=0 ) {o .expert_cache = 0 ;sized_slots .clear ();return false; } 5008return true; 5009 }; 5010auto cache_bytes = [& ]()-> int64_t { 5011if (sized_slots .empty ())return (int64_t )o .expert_cache * (int64_t ) strata::kernels::cpu::expert_layout ().max_blob ; 5012int64_t b = 0 ; 5013for (const int64_t s :sized_slots )b += (s + 255 ) /256 * 256 ; 5014return b ; 5015 }; 5016// With `--expert-cache auto` the reserve must still be free once the slots are WRITTEN: under WDDM an 5017// allocation is not resident until it is touched, and the free figure read before it can be ~1 GB too 5018// high. A cache sized from it filled the card to 0 MiB, the driver then paged, and a request that needed a 5019// page back while the verify graph spun on a host flag never finished. So the slots are zeroed and the 5020// free figure read again; while it is short of the reserve the cache is reopened smaller. 5021// STRATA_TEST_CACHE_FAIL=N: the first N opens fail as an out-of-commit cudaMalloc does (tests the retry) 5022int fake_fails = std::getenv ("STRATA_TEST_CACHE_FAIL" ) ? std::atoi (std::getenv ("STRATA_TEST_CACHE_FAIL" )) :0 ; 5023int failed = 0 ; 5024int zero_reads = 0 ; 5025for (int attempt = 0 ;;++ attempt ) { 5026bool ok = false; 5027if (fake_fails > 0 ) { 5028-- fake_fails ; 5029err = "ExpertCache: cudaMalloc failed: out of memory (STRATA_TEST_CACHE_FAIL)" ; 5030 }else { 5031ok = sized_slots .empty () 5032 ?xcache .open (o .expert_cache ,g .n_layers ,g .n_expert , (int64_t ) strata::kernels::cpu::expert_layout ().max_blob ,err ) 5033 :xcache .open_sized (sized_slots ,g .n_layers ,g .n_expert ,err ); 5034 } 5035if (!ok ) { 5036// Issue #60: on Windows a device allocation is also charged to the system commit (RAM + page file), 5037// so with a small page file the cache's one big cudaMalloc fails while the VRAM is free. An auto 5038// cache then tries three quarters of the size, a few times, instead of stopping the engine. 5039char commit [96 ]= "" ; 5040#if defined(_WIN32 ) 5041MEMORYSTATUSEX ms {}; 5042ms .dwLength = sizeof ms ; 5043if (GlobalMemoryStatusEx (& ms )) 5044 std::snprintf (commit ,sizeof commit ," (Windows has %.1f GiB of commit left: RAM + page file)" , 5045 (double )ms .ullAvailPageFile /1073741824.0 ); 5046#endif 5047if (auto_cache && failed < 8 && shrink_to (cache_bytes () /4 * 3 )) { 5048++ failed ; 5049 std::fprintf (stderr ,"strata generate: %s%s; trying a smaller expert cache: %d slots\n" ,err .c_str (), 5050commit ,o .expert_cache ); 5051continue ; 5052 } 5053 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 5054#if defined(_WIN32 ) 5055 std::fprintf (stderr ,"strata generate: on Windows the graphics card's memory also needs room in the page " 5056"file: set it to \"System managed\" (System > About > Advanced system settings > " 5057"Performance > Advanced > Virtual memory), or lower --expert-cache\n" ); 5058#endif 5059return 1 ; 5060 } 5061if (!auto_cache || attempt - failed >=6 )break ; 5062if (uint8_t * slot0 = xcache .device_slot (0 )) strata::big_fill_zero (dpct::get_in_order_queue (),slot0 , (size_t )xcache .bytes ()); 5063 dpct::get_current_device ().queues_wait_and_throw (); 5064size_t free_b = 0 ,total_b = 0 ; 5065free_b = strata::core::device_free_bytes (); (void )total_b ; 5066const int64_t want = ((int64_t )o .vram_reserve_mib <<20 )+ pipe_first ; 5067if ((int64_t )free_b >=want - (64ll <<20 ))break ; 5068// short by (want - free); a figure of 0 only says "at least": the first two such reads give back 1 GiB 5069// each (under WDDM the free figure read before the allocation runs ~0.7 GiB high), later ones a quarter 5070int64_t give = want - (int64_t )free_b + (64ll <<20 ); 5071if (free_b < ((size_t )16 <<20 )) 5072give = std::max < int64_t > (give ,++ zero_reads <=2 ?1ll <<30 :xcache .bytes () /4 ); 5073const int64_t keep_bytes = xcache .bytes ()- give ; 5074 std::fprintf (stderr ,"strata generate: only %lld MiB free once the slots are written (reserve %d MiB); " 5075"shrinking the expert cache\n" , (long long ) (free_b >>20 ),o .vram_reserve_mib ); 5076xcache .close (); 5077if (!shrink_to (keep_bytes ))break ; 5078 } 5079if (failed > 0 && o .expert_cache > 0 ) 5080 std::fprintf (stderr ,"strata generate: expert cache: %d slots (%.2f GiB) after %d smaller tries - a bigger " 5081"page file lets it use more of the free VRAM\n" , 5082o .expert_cache , (double )xcache .bytes () /1073741824.0 ,failed ); 5083 } 5084if (o .expert_cache > 0 ) { 5085 std::fprintf (stderr ,"strata generate: expert cache %lld slots, %.2f GiB of VRAM; policy is\n" , 5086 (long long )xcache .slots (),xcache .gib ()); 5087mem_mark ("opening the expert cache" ); 5088xcache .set_per_layer_admission (o .expert_cache_per_layer ); 5089// Round 328 warned here that the GPU hit path was wrong (tokens diverged from a cache-off run from 5090// token 0). That fault was fixed long since (native_expert_parity, expert_parity, the grouped kernels' 5091// tests), and the warning outlived it (issue #23). What remains is rounding: a GPU expert and the CPU's 5092// compute the same quantized expert with different float order, so a near-tie can flip. Measured teacher- 5093// forced on 2,557 tokens (bench/results/2026-09-27-cache-parity): 95-98% same top-1, and perplexity equal 5094// (on - off = -0.005 +- 0.005 nats). Neither output is more correct than the other. 5095 std::fprintf (stderr , 5096"strata generate: the GPU computes the experts in the cache; it rounds differently from the CPU,\n" 5097" so a reply can differ slightly from a run without the cache (same quality:\n" 5098" bench/results/2026-09-27-cache-parity).\n" ); 5099if (o .expert_cache_per_layer ) { 5100int64_t lo = 0 ,hi = 0 ; 5101xcache .layer_slot_range (0 ,lo ,hi ); 5102 std::fprintf (stderr ," R4.2g PER-LAYER: each layer owns %lld slots (%lld..%lld).\n" , 5103 (long long ) (hi - lo ), (long long )lo , (long long ) (hi - 1 )); 5104 }else if (profile .empty ()) { 5105 std::fprintf (stderr ," compulsory-miss (fills with whatever the run routes first).\n" ); 5106 }else { 5107 std::fprintf (stderr ," PROFILE, ranked by routing frequency, no eviction.\n" ); 5108 } 5109 } 5110// ---- R4.2e: fill the tier from the profile. This is the only place the plan is applied, and it runs 5111// ONCE: with `slots` pairs and `slots` slots the cache is full when this returns, so the decode-time 5112// admission finds no room and every non-profiled expert stays a CPU miss. That is what makes the profile 5113// the policy rather than a hint. 5114int64_t prefilled = 0 ; 5115 std::function < void (const char * )> verify_all_slots ;// STRATA_VERIFY_ALL_SLOTS (debug), set by the pipelined fill 5116if (!profile .empty ()&& srcp != nullptr ) { 5117// #369 (dag08): per layer, a full layer skips only its own pairs - each layer takes its hottest experts until 5118// its range is full (one full layer used to end the whole fill, leaving most layers empty) 5119const bool per_layer = xcache .per_layer_admission (); 5120const int64_t want = per_layer ? (int64_t )profile .size () 5121 : std::min < int64_t > ((int64_t )profile .size (),xcache .slots ()); 5122const auto tfill = std::chrono::steady_clock::now (); 5123uint64_t fill_bytes = 0 ; 5124// SYCL port: from the GGUF (--stream-experts) the fill is a pipeline. The serial form read each expert's three 5125// slices, copied it, and waited for the copy before the next read (~18,000 experts, neither the SSD nor PCIe 5126// kept busy). Here the slots are admitted first (the same profile order, so the same placement), the reads go 5127// in file order by worker threads into page-locked batches, and a batch's copies run while the next batch is 5128// read. STRATA_FILL_SERIAL=1: the serial form. 5129const bool piped = srcp == & gguf_src && !per_layer && std::getenv ("STRATA_FILL_SERIAL" )== nullptr ; 5130if (piped ) { 5131struct Fill {int32_t slot ;int32_t l ,e ; }; 5132 std::vector < Fill > fills ; 5133fills .reserve ((size_t )want ); 5134for (int64_t i = 0 ;i < want ;++ i ) { 5135const int32_t slot = xcache .admit (profile [(size_t )i ].first ,profile [(size_t )i ].second ); 5136if (slot == strata::core::kNotResident )break ; 5137fills .push_back ({slot , (int32_t )profile [(size_t )i ].first , (int32_t )profile [(size_t )i ].second }); 5138 } 5139 std::sort (fills .begin (),fills .end (), [](const Fill & a ,const Fill & b ) { 5140return a .l != b .l ?a .l < b .l :a .e < b .e ;// file order: each tensor read front to back 5141 }); 5142const auto & lay = strata::kernels::cpu::expert_layout (); 5143constexpr size_t kBatch = 64 ; 5144const size_t blob_cap = (size_t )lay .max_blob ; 5145 sycl::queue & q = dpct::get_in_order_queue (); 5146uint8_t * pin = sycl::malloc_host < uint8_t > (2 * kBatch * blob_cap ,q ); 5147if (pin == nullptr ) { 5148 std::fprintf (stderr ,"strata generate: the profile fill could not pin %zu MiB\n" , 5149 (2 * kBatch * blob_cap ) >>20 ); 5150return 1 ; 5151 } 5152const int nthreads = std::max (2 , std::min (8 , (int ) std::thread::hardware_concurrency ())); 5153 sycl::event done [2 ]; 5154bool read_ok = true; 5155for (size_t b0 = 0 ,k = 0 ;b0 < fills .size ()&& read_ok ;b0 += kBatch ,++ k ) { 5156const size_t n = std::min (kBatch ,fills .size ()- b0 ); 5157uint8_t * set = pin + (k %2 )* kBatch * blob_cap ; 5158done [k %2 ].wait ();// the copies that last read this half are finished 5159 std::atomic < size_t > next {0 }; 5160 std::atomic < bool > ok {true}; 5161 std::vector < std::thread > ts ; 5162for (int t = 0 ;t < nthreads ;++ t ) 5163ts .emplace_back ([& ] { 5164for (size_t j ; (j = next .fetch_add (1 ))< n ;) { 5165const Fill & f = fills [b0 + j ]; 5166if (!gguf_src .read_into (f .l ,f .e ,set + j * blob_cap ,blob_cap ))ok = false; 5167 } 5168 }); 5169for (auto & t :ts )t .join (); 5170if (!ok ) {read_ok = false;break ; } 5171for (size_t j = 0 ;j < n ;++ j ) { 5172const Fill & f = fills [b0 + j ]; 5173const size_t nb = (size_t )lay .blob_bytes (f .l ); 5174done [k %2 ]= q .memcpy (xcache .device_slot (f .slot ),set + j * blob_cap ,nb ); 5175fill_bytes += nb ; 5176 } 5177 } 5178q .wait (); 5179 sycl::free (pin ,q ); 5180if (!read_ok ) { 5181 std::fprintf (stderr ,"strata generate: the profile fill could not read an expert from the GGUF\n" ); 5182return 1 ; 5183 } 5184prefilled = (int64_t )fills .size (); 5185if (std::getenv ("STRATA_VERIFY_ALL_SLOTS" )!= nullptr ) {// debug: every filled slot read back and compared with the GGUF 5186auto fl = std::make_shared < std::vector < Fill >> (fills ); 5187verify_all_slots = [& ,fl ,blob_cap ](const char * when ) { 5188 sycl::queue & vq = dpct::get_in_order_queue (); 5189vq .wait (); 5190 std::vector < uint8_t > want_b (blob_cap ),got_b (blob_cap ); 5191int64_t bad = 0 ,first_bad = -1 ; 5192for (size_t i = 0 ;i < fl -> size ();++ i ) { 5193const Fill & f = (* fl )[i ]; 5194const size_t nb = (size_t )lay .blob_bytes (f .l ); 5195if (!gguf_src .read_into (f .l ,f .e ,want_b .data (),blob_cap )) {++ bad ;continue ; } 5196vq .memcpy (got_b .data (),xcache .device_slot (f .slot ),nb ).wait (); 5197if (std::memcmp (want_b .data (),got_b .data (),nb )!= 0 ) { 5198if (first_bad < 0 )first_bad = (int64_t )i ; 5199++ bad ; 5200size_t nd = 0 ,fd = nb ,ld = 0 ; 5201for (size_t x = 0 ;x < nb ;++ x ) 5202if (want_b [x ]!= got_b [x ]) {++ nd ;if (fd == nb )fd = x ;ld = x ; } 5203if (std::getenv ("STRATA_VERIFY_FIND" )!= nullptr && bad <=2 && fd + 4160 < nb ) {// whose blob is the wrong data? 5204const uint8_t * probe = got_b .data ()+ fd + 4096 ; 5205 std::vector < uint8_t > other (blob_cap ); 5206for (size_t j = 0 ;j < fl -> size ();++ j ) { 5207const Fill & g2 = (* fl )[j ]; 5208if (!gguf_src .read_into (g2 .l ,g2 .e ,other .data (),blob_cap ))continue ; 5209const size_t nb2 = (size_t )lay .blob_bytes (g2 .l ); 5210const void * hit = memmem (other .data (),nb2 ,probe ,64 ); 5211if (hit != nullptr ) 5212 std::fprintf (stderr ," the wrong data at byte %zu is expert (layer %d, expert %d), slot %d (fill %zu), byte %zu of its blob\n" , 5213fd + 4096 , (int )g2 .l , (int )g2 .e , (int )g2 .slot ,j , (size_t ) ((const uint8_t * )hit - other .data ())); 5214 } 5215 } 5216if (const char * dd = std::getenv ("STRATA_VERIFY_DUMP" );dd != nullptr && bad == 1 ) { 5217const std::string base = std::string (dd )+ "/slot" + std::to_string (f .slot ); 5218if (FILE * fo = std::fopen ((base + ".got" ).c_str (),"wb" )) { std::fwrite (got_b .data (),1 ,nb ,fo ); std::fclose (fo ); } 5219if (FILE * fo = std::fopen ((base + ".want" ).c_str (),"wb" )) { std::fwrite (want_b .data (),1 ,nb ,fo ); std::fclose (fo ); } 5220 } 5221 std::fprintf (stderr ,"strata generate: STRATA_VERIFY_ALL_SLOTS (%s): fill %zu (layer %d expert %d) slot %d at %p: %zu of %zu bytes differ, first at %zu, last at %zu\n" , 5222when ,i , (int )f .l , (int )f .e , (int )f .slot , (const void * )xcache .device_slot (f .slot ),nd ,nb ,fd ,ld ); 5223 } 5224 } 5225 std::fprintf (stderr ,"strata generate: STRATA_VERIFY_ALL_SLOTS (%s): %lld of %zu slots differ from the GGUF (first at fill %lld)\n" , 5226when , (long long )bad ,fl -> size (), (long long )first_bad ); 5227 }; 5228verify_all_slots ("after the fill" ); 5229 } 5230 } 5231// #286: an unbuffered file tier reads the pairs in batches of 64, the next batch while this one is copied 5232 std::future < void > ahead ; 5233auto read_batch = [& ](int64_t at ) {src .prefetch_pairs (profile .data ()+ at , std::min < int64_t > (64 ,want - at )); }; 5234// mapped reads: advise the next `fill_ahead` pairs so their reads overlap; STRATA_FILL_AHEAD=0 turns it off 5235int64_t fill_ahead = 0 ; 5236if (!piped && !per_layer && srcp == & src && !src .unbuffered ()) { 5237const char * v = std::getenv ("STRATA_FILL_AHEAD" ); 5238fill_ahead = v == nullptr ?256 : std::max (0 , std::atoi (v )); 5239if (fill_ahead > 0 && !src .advise_pairs (profile .data (), std::min < int64_t > (fill_ahead ,want )))fill_ahead = 0 ; 5240 std::fprintf (stderr ,"strata generate: the profile fill asks for %lld pairs ahead (STRATA_FILL_AHEAD)\n" , 5241 (long long )fill_ahead ); 5242 } 5243for (int64_t i = 0 ;i < want && !piped ;++ i ) { 5244if (!per_layer && srcp == & src && src .unbuffered ()&& i %64 == 0 ) { 5245if (ahead .valid ())ahead .get (); 5246else read_batch (i ); 5247if (i + 64 < want )ahead = std::async (std::launch::async ,read_batch ,i + 64 ); 5248 } 5249if (fill_ahead > 0 && i + fill_ahead < want ) (void )src .advise_pairs (profile .data ()+ i + fill_ahead ,1 ); 5250const int32_t slot = xcache .admit (profile [(size_t )i ].first ,profile [(size_t )i ].second ); 5251if (slot == strata::core::kNotResident ) { 5252if (per_layer )continue ; 5253break ; 5254 } 5255const uint8_t * b = srcp -> blob (profile [(size_t )i ].first ,profile [(size_t )i ].second ); 5256if (b == nullptr || !xcache .fill_slot_blocking (slot ,b ,err , 5257 (int64_t ) strata::kernels::cpu::expert_layout ().blob_bytes (profile [(size_t )i ].first ))) { 5258 std::fprintf (stderr ,"strata generate: the profile fill failed at pair %lld: %s\n" , 5259 (long long )i ,err .c_str ()); 5260return 1 ; 5261 } 5262++ prefilled ; 5263fill_bytes += (uint64_t ) strata::kernels::cpu::expert_layout ().blob_bytes (profile [(size_t )i ].first ); 5264 } 5265const double fill_s = std::chrono::duration < double > (std::chrono::steady_clock::now ()- tfill ).count (); 5266 std::fprintf (stderr ,"strata generate: profile fill: %.2f GiB in %.1f s (%.2f GB/s, %s)\n" , 5267 (double )fill_bytes /1073741824.0 ,fill_s ,fill_s > 0 ? (double )fill_bytes /1e9 /fill_s :0.0 , 5268piped ?"pipelined" :"serial" ); 5269// **AND ONE SLOT IS READ BACK AND COMPARED.** A residency table that is right about indices and wrong 5270// about bytes produces a plausible token, which is this project's most expensive failure mode; the 5271// cache's own `verify_slot` is the check and it costs one 1.38 MB D2H at startup. 5272if (prefilled > 0 && !xcache .verify_slot (xcache .slot_of (profile [0 ].first ,profile [0 ].second ), 5273srcp -> blob (profile [0 ].first ,profile [0 ].second ),err , 5274 (int64_t ) strata::kernels::cpu::expert_layout ().blob_bytes (profile [0 ].first ))) { 5275 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 5276return 1 ; 5277 } 5278 strata::uc_probe ("after-fill" ); 5279mem_mark ("the profile fill" ); 5280 std::fprintf (stderr ,"strata generate: pre-filled %lld of %lld slots from the profile in %.1f s (%.0f MB/s); " 5281"slot 0 verified\n" , 5282 (long long )prefilled , (long long ) (per_layer ?xcache .slots () :want ),fill_s , 5283fill_s > 0 ? (double )fill_bytes /1e6 /fill_s :0.0 ); 5284 } 5285// SYCL port, plan item 2: the experts that did not fit VRAM, mirrored once in pinned host memory the GPU reads 5286// over PCIe (--stream-experts has no host copy otherwise: each routed miss was an SSD read). The share of misses 5287// the GPU takes is --pcie-frac; STRATA_MIRROR_MIB caps the mirror (default: MemAvailable less 4 GiB), 0 = off. 5288unsigned long long * mirror_table_d = nullptr ;// [n_layers][n_expert] device-readable mirror addresses (0 = none) 5289int64_t unmirrored_misses = 0 ; 5290if (o .stream_experts && srcp == & gguf_src && o .expert_cache > 0 ) { 5291// #1054, #1440: with a layer split the mirror holds only the first GPU's layers. The pinned memory belongs to 5292// this GPU's context, and the later stages' caches do not exist yet (every later-stage expert would count as a 5293// miss: 20 GiB of RAM for experts the other card then holds, or one 39 GiB pinned allocation that fails). 5294const int64_t mirror_end = multi_gpu && !split_at .empty () ?split_at [0 ] :g .n_layers ; 5295 std::vector < std::pair < int64_t ,int64_t >> miss ; 5296size_t n_true_miss = 0 ;// the experts no slot holds; what follows them in `miss` are the lend candidates (below) 5297for (const auto & pr :profile )// the profile's order: the most-routed misses first, if the cap is reached 5298if (pr .first < mirror_end && xcache .slot_of (pr .first ,pr .second )== strata::core::kNotResident ) 5299miss .push_back ({pr .first ,pr .second }); 5300for (int64_t l = 0 ;l < mirror_end ;++ l )// pairs the profile does not list at all 5301for (int64_t e = 0 ;e < g .n_expert ;++ e ) 5302if (xcache .slot_of (l ,e )== strata::core::kNotResident && 5303 std::find (miss .begin (),miss .end (), std::pair < int64_t ,int64_t > {l ,e })== miss .end ()) 5304miss .push_back ({l ,e }); 5305n_true_miss = miss .size (); 5306// 0.1.43: the experts in the last slots - the ones a prompt's loan takes (Prefill::relayout lends the TAIL of the 5307// cache) - are mirrored too, after the real misses (the cap drops them first). A lent expert is streamed during 5308// the prompt and put back after it; from the GGUF that was a pread at ~2.3 GB/s per expert (~1 s for a 4K prompt's 5309// 930 slots, 0.26 s for a 600-token prompt's 284), from the pinned mirror it is a DMA. Their mirror entries are never 5310// read by a decode window: it only looks at a mirror address for an expert that has no slot. 5311// STRATA_LEND_MIRROR=0 turns it off; =N: the last N slots (default 10% of the cache with a loan, at most 1,200). 5312if (!o .no_prefill_borrow && o .prefill_chunk > 0 && !multi_gpu ) { 5313const char * lm = std::getenv ("STRATA_LEND_MIRROR" ); 5314const int64_t want_tail = lm ? std::atoll (lm ) : std::min < int64_t > (xcache .slots () /10 ,1200 ); 5315if (want_tail > 0 ) { 5316const int64_t first_tail = xcache .slots ()- std::min < int64_t > (want_tail ,xcache .slots ()); 5317for (int64_t l = 0 ;l < mirror_end ;++ l ) 5318for (int64_t e = 0 ;e < g .n_expert ;++ e ) 5319if (const int64_t sl = xcache .slot_of (l ,e );sl != strata::core::kNotResident && sl >=first_tail ) 5320miss .push_back ({l ,e }); 5321 } 5322 } 5323uint64_t avail = 0 ; 5324if (FILE * f = std::fopen ("/proc/meminfo" ,"r" )) { 5325char key [64 ];unsigned long long kb = 0 ; 5326while (std::fscanf (f ,"%63s %llu kB" ,key ,& kb )== 2 ) 5327if (std::strcmp (key ,"MemAvailable:" )== 0 ) {avail = kb <<10 ;break ; } 5328 std::fclose (f ); 5329 } 5330const char * mv = std::getenv ("STRATA_MIRROR_MIB" ); 5331const uint64_t cap = mv ? (uint64_t ) std::atoll (mv ) <<20 : (avail > (4ull <<30 ) ?avail - (4ull <<30 ) :0 ); 5332if (!miss .empty ()&& cap > 0 ) { 5333const auto tm = Clock ::now (); 5334const int64_t got = gguf_src .mirror (miss ,cap ,8 ,err ); 5335if (got < 0 ) { 5336 std::fprintf (stderr ,"strata generate: mirroring the experts missing from VRAM: %s (they stay on the SSD)\n" , 5337err .c_str ()); 5338err .clear (); 5339 }else { 5340 std::fprintf (stderr ,"strata generate: %lld of %zu experts missing from VRAM (+ %zu in the prompt loan's slots) mirrored in pinned host memory " 5341"(%.2f GiB, %.1f s); the GPU reads them over PCIe\n" , (long long )got ,n_true_miss ,miss .size ()- n_true_miss , 5342 (double )gguf_src .mirrored_bytes () /1073741824.0 , 5343 std::chrono::duration < double > (Clock ::now ()- tm ).count ()); 5344// the device-built verify plan's view of it: each (layer, expert) -> its mirror address, 0 = none 5345 std::vector < unsigned long long > tab ((size_t ) (g .n_layers * g .n_expert ),0ull ); 5346for (int64_t l = 0 ;l < g .n_layers ;++ l ) 5347for (int64_t e = 0 ;e < g .n_expert ;++ e ) 5348if (gguf_src .pinned (l ,e )) 5349tab [(size_t ) (l * g .n_expert + e )]= (unsigned long long )gguf_src .device_alias (l ,e ); 5350mirror_table_d = sycl::malloc_device < unsigned long long > (tab .size (), dpct::get_in_order_queue ()); 5351 dpct::get_in_order_queue ().memcpy (mirror_table_d ,tab .data (),tab .size ()* sizeof (unsigned long long )).wait (); 5352 } 5353 } 5354unmirrored_misses = (int64_t )n_true_miss - (int64_t ) (gguf_src .mirrored_bytes () ? std::count_if (miss .begin (),miss .begin ()+ (ptrdiff_t )n_true_miss , 5355 [& ](const std::pair < int64_t ,int64_t >& pr ) {return gguf_src .pinned (pr .first ,pr .second ); }) :0 ); 5356const bool no_host = [] {const char * v = std::getenv ("STRATA_VERIFY_NO_HOST" );return v && * v && std::strcmp (v ,"0" )!= 0 ; }(); 5357if (unmirrored_misses > 0 && no_host ) { 5358 std::fprintf (stderr ,"strata generate: REFUSED: %lld experts are neither in VRAM nor mirrored; with STRATA_VERIFY_NO_HOST " 5359"the device plan cannot run them and generation would lack a safe host fallback - raise " 5360"STRATA_MIRROR_MIB or the free RAM, or lower --max-context\n" , (long long )unmirrored_misses ); 5361refuse_exit (2 ); 5362 } 5363// The same rule after the start: the mirror holds the start's misses only, so an expert an adaptive swap moves 5364// out of VRAM would be in neither, and the device plan would wait for a host that never serves it (every token 5365// 0 after a --batch window had counted misses and the tier swapped). 5366if (!miss .empty ()&& no_host && o .adapt_every > 0 && o .adapt_swaps > 0 && !sycl_mirror_adapt ()) { 5367 std::fprintf (stderr ,"strata generate: adaptive swaps off: with STRATA_VERIFY_NO_HOST an expert they move out of " 5368"VRAM would be neither there nor mirrored\n" ); 5369o .adapt_every = 0 ; 5370 } 5371 } 5372 5373if (sycl_mirror_adapt ()) { 5374if (!o .serve || !o .stream_experts || srcp != & gguf_src || !stages .empty ()|| 5375o .peer_device >=0 || remote_caches || 5376 !o .no_prefill_borrow || o .vram_elastic || !mirror_table_d || unmirrored_misses || 5377o .adapt_every <=0 || o .adapt_swaps <=0 || o .adapt_swaps > 96 || 5378 !o .expert_profile_save .empty ()) { 5379 std::fprintf (stderr ,"SYCL mirror adaptive cache requires single-device complete stream mirror, no borrow/elastic/profile save\n" ); 5380return 1 ; 5381 } 5382 std::fprintf (stderr ,"SYCL mirror adaptive cache: sync exchange; %lld slots, %lld cache bytes, %llu mirror bytes\n" , 5383 (long long )xcache .slots (), (long long )xcache .bytes (), (unsigned long long )gguf_src .mirrored_bytes ()); 5384 } 5385 5386for (auto & stp :stages ) { 5387GpuStage & st = * stp ; 5388const auto & lay = strata::kernels::cpu::expert_layout (); 5389// the drafter and the head are already allocated by now (they load above, before this), so what is left 5390// to hold back is the windows - and `free_b` has already lost the drafter. 5391const int64_t room = stage_room (st .dev , true, false); 5392const strata::core::OnDevice on (st .dev ); 5393 { 5394size_t fb = 0 ,tb = 0 ; 5395/* 5396DPCT1106: 'cudaMemGetInfo' was migrated with the Intel 5397extensions for device information which may not be supported by all 5398compilers or runtimes. You may need to adjust the code. 5399*/ 5400 dpct::get_current_device ().get_memory_info (fb ,tb ); 5401 std::fprintf (stderr ,"strata generate: layer split, CUDA%d: %.2f GiB free of %.2f, room for experts %.2f GiB\n" , 5402st .dev , (double )fb /1073741824.0 , (double )tb /1073741824.0 , (double )room /1073741824.0 ); 5403 } 5404 std::vector < int64_t > sized ; 5405int64_t used = 0 ; 5406for (const auto & pr :st .profile ) { 5407const int64_t b = native_pack ? ((int64_t )lay .blob_bytes (pr .first )+ 255 ) /256 * 256 : (int64_t )lay .max_blob ; 5408if (used + b > room )break ; 5409used += b ; 5410sized .push_back ((int64_t )lay .blob_bytes (pr .first )); 5411 } 5412// #841: a stage's cache can fail to open with the VRAM free (the card's allocation is also charged to the 5413// Windows commit, or the free figure ran high): it is tried again with 90% of the slots, up to 3 times, each 5414// try said. Nothing changes when the first open works. 5415bool stage_open = false; 5416for (int attempt = 0 ; !sized .empty ();++ attempt ) { 5417stage_open = native_pack ?st .cache .open_sized (sized ,g .n_layers ,g .n_expert ,err ) 5418 :st .cache .open ((int64_t )sized .size (),g .n_layers ,g .n_expert , (int64_t )lay .max_blob ,err ); 5419if (stage_open || attempt >=3 )break ; 5420/* 5421DPCT1010: SYCL uses exceptions to report errors and does not 5422use the error codes. The cudaGetLastError function call was replaced 5423with 0. You need to rewrite this code. 5424*/ 5425 (void )0 ; 5426const size_t keep = sized .size ()* 9 /10 ; 5427 std::fprintf (stderr ,"strata generate: layer split, CUDA%d expert cache: %s; trying %zu of %zu slots " 5428"(try %d of 3)\n" ,st .dev ,err .c_str (),keep ,sized .size (),attempt + 1 ); 5429if (keep == 0 )break ; 5430st .cache .close (); 5431sized .resize (keep ); 5432 } 5433if (!stage_open ) { 5434 std::fprintf (stderr ,"strata generate: layer split, CUDA%d expert cache: %s\n" ,st .dev , 5435sized .empty () ?"no room" :err .c_str ()); 5436return 1 ; 5437 } 5438int64_t filled = 0 ; 5439for (const auto & pr :st .profile ) { 5440if (filled >=st .cache .slots ())break ; 5441const int32_t slot = st .cache .admit (pr .first ,pr .second ); 5442if (slot == strata::core::kNotResident )break ; 5443const uint8_t * b = srcp -> blob (pr .first ,pr .second ); 5444if (b == nullptr || !st .cache .fill_slot_blocking (slot ,b ,err , (int64_t )lay .blob_bytes (pr .first ))) { 5445 std::fprintf (stderr ,"strata generate: layer split, CUDA%d profile fill failed at pair %lld: %s\n" , 5446st .dev , (long long )filled ,err .c_str ()); 5447return 1 ; 5448 } 5449++ filled ; 5450 } 5451if (filled == 0 || !st .cache .verify_slot (st .cache .slot_of (st .profile [0 ].first ,st .profile [0 ].second ), 5452srcp -> blob (st .profile [0 ].first ,st .profile [0 ].second ),err , 5453 (int64_t )lay .blob_bytes (st .profile [0 ].first ))) { 5454 std::fprintf (stderr ,"strata generate: layer split, CUDA%d expert cache: %s\n" ,st .dev , 5455filled == 0 ?"nothing filled" :err .c_str ()); 5456return 1 ; 5457 } 5458 std::fprintf (stderr ,"strata generate: layer split: CUDA%d runs layers %lld-%lld, expert cache %lld slots " 5459"(%.2f GiB), %lld of its %zu profiled pairs; slot 0 verified\n" , 5460st .dev , (long long )st .lb , (long long ) (st .le - 1 ), (long long )st .cache .slots (),st .cache .gib (), 5461 (long long )filled ,st .profile .size ()); 5462 } 5463if (multi_gpu ) 5464 std::fprintf (stderr ,"strata generate: layer split: CUDA0 runs layers 0-%lld\n" , (long long ) (split_at [0 ]- 1 )); 5465// #1980: the host mirror and the "REFUSED" count above cover the first stage only. A later stage whose cache does not 5466// hold all of its layers' experts has no mirror entry for the rest, and with STRATA_VERIFY_NO_HOST no host answers for 5467// them: the device plan reads a bad address and the card is lost at the first verify window (2x Arc Pro B60, xe CAT 5468// fault). Refuse at the start with the same message, and say how to get a complete load. 5469if (multi_gpu ) { 5470const bool no_host_split = [] {const char * v = std::getenv ("STRATA_VERIFY_NO_HOST" );return v && * v && std::strcmp (v ,"0" )!= 0 ; }(); 5471int64_t later_misses = 0 ; 5472for (auto & stp :stages ) { 5473const GpuStage & st = * stp ; 5474later_misses += std::max < int64_t > (0 , (st .le - st .lb )* g .n_expert - (int64_t )st .cache .slots ()); 5475 } 5476if (later_misses > 0 && no_host_split ) { 5477 std::fprintf (stderr ,"strata generate: REFUSED: %lld experts of the later layer-split stages are neither in VRAM nor mirrored " 5478"(the host mirror covers the first stage only); with STRATA_VERIFY_NO_HOST the device plan cannot run them " 5479"and the card is lost at the first verify window - set STRATA_STAGE_TRIM=1 (with --layer-split N) to free " 5480"each card's duplicate dense weights, lower --max-context or --vram-reserve-mib, or unset " 5481"STRATA_VERIFY_NO_HOST\n" , (long long )later_misses ); 5482refuse_exit (2 ); 5483 } 5484if (later_misses > 0 ) 5485 std::fprintf (stderr ,"strata generate: layer split: %lld experts of the later stages are not in VRAM (served by the host)\n" , 5486 (long long )later_misses ); 5487 } 5488 5489 std::array < strata::core::RemoteExperts ,3 > remote_experts ; 5490 std::unique_ptr < strata::core::RemoteExpertOpt > remote_opt ; 5491if (o .remote_expert_opt && o .expert_cache_remote [0 ]> 0 )remote_opt = std::make_unique < strata::core::RemoteExpertOpt > (); 5492const bool multi_remote = o .expert_cache_remote [1 ]> 0 || o .expert_cache_remote [2 ]> 0 ; 5493if (o .expert_cache_remote [0 ]> 0 ) { 5494if (o .expert_cache <=0 || profile .empty ()|| o .no_pool ) { 5495 std::fprintf (stderr ,"strata generate: remote experts need --expert-profile, " 5496"a CUDA0 expert cache and the expert pool\n" ); 5497return 2 ; 5498 } 5499 std::vector < std::pair < int32_t ,int32_t >> ranked = profile ; 5500if (!stages .empty ()) {// a layer split: CUDA0's share of the profile, then the later stages' pairs no cache holds 5501for (auto & st :stages ) 5502for (const auto & pr :st -> profile ) 5503if (st -> cache .slot_of (pr .first ,pr .second )< 0 )ranked .push_back (pr ); 5504 } 5505if (multi_remote || std::any_of (o .expert_cache_remote_auto .begin (),o .expert_cache_remote_auto .end (), 5506 [](bool automatic ) {return automatic ; })) { 5507// The shipped frequency profile names only 8000 of 24576 experts. Once exhausted, 5508// fill remaining VRAM from unranked pairs in expert-then-layer order: this spreads 5509// the tail across all layers instead of concentrating it on layer zero. 5510 std::vector < uint8_t > seen ((size_t )g .n_layers * (size_t )g .n_expert ,0 ); 5511for (const auto & pair :ranked ) 5512if (pair .first >=0 && pair .first < g .n_layers && pair .second >=0 && pair .second < g .n_expert ) 5513seen [(size_t )pair .first * (size_t )g .n_expert + (size_t )pair .second ]= 1 ; 5514for (int64_t e = 0 ;e < g .n_expert ;++ e ) 5515for (int64_t l = 0 ;l < g .n_layers ;++ l ) 5516if (!seen [(size_t )l * (size_t )g .n_expert + (size_t )e ]) 5517ranked .emplace_back ((int32_t )l , (int32_t )e ); 5518 std::fprintf (stderr ,"strata generate: remote ranking: %zu profiled pairs, " 5519"%zu other pairs to fill CUDA1..3\n" ,profile .size (),ranked .size ()- profile .size ()); 5520 } 5521 std::array < std::vector < std::pair < int32_t ,int32_t >> ,3 > by_device ; 5522if (multi_remote ) { 5523// Either stripe experts for parallel GPU work, or give each layer one 5524// secondary GPU to reduce switches and transfers over shared USB4. 5525 std::vector < uint8_t > assigned ((size_t )g .n_layers * (size_t )g .n_expert ,0 ); 5526const int devices = 1 + (o .expert_cache_remote [1 ]> 0 )+ (o .expert_cache_remote [2 ]> 0 ); 5527int next = 0 ; 5528for (const auto & pair :ranked ) { 5529if (pair .first < 0 || pair .first >=g .n_layers || pair .second < 0 || pair .second >=g .n_expert || 5530xcache .slot_of (pair .first ,pair .second ) >=0 )continue ; 5531const size_t index = (size_t )pair .first * (size_t )g .n_expert + (size_t )pair .second ; 5532if (assigned [index ])continue ; 5533int target = -1 ; 5534if (o .expert_cache_remote_placement == "layer" ) { 5535target = pair .first %devices ; 5536// Other layers' owners may still have room: keep scanning ranks. 5537if (by_device [(size_t )target ].size () >= 5538 (size_t )o .expert_cache_remote [(size_t )target ])continue ; 5539 }else { 5540for (int i = 0 ;i < devices ;++ i ) { 5541const int r = (next + i ) %devices ; 5542if (by_device [(size_t )r ].size ()< (size_t )o .expert_cache_remote [(size_t )r ]) { 5543target = r ; 5544break ; 5545 } 5546 } 5547if (target < 0 )break ; 5548 } 5549assigned [index ]= 1 ; 5550by_device [(size_t )target ].push_back (pair ); 5551next = (target + 1 ) %devices ; 5552 } 5553 std::fprintf (stderr ,"strata generate: remote ranks %s across %d CUDA devices\n" , 5554o .expert_cache_remote_placement == "layer" ?"grouped by layer" :"striped" ,devices ); 5555 }else { 5556by_device [0 ]= std::move (ranked ); 5557 } 5558 std::vector < uint8_t > claimed ((size_t )g .n_layers * (size_t )g .n_expert ,0 ); 5559for (auto & st :stages )// a layer split: what a stage's cache holds is no helper's 5560for (const auto & pr :st -> profile ) 5561if (st -> cache .slot_of (pr .first ,pr .second ) >=0 ) 5562claimed [(size_t )pr .first * (size_t )g .n_expert + (size_t )pr .second ]= 1 ; 5563for (int r = 0 ;r < 3 ;++ r )if (o .expert_cache_remote [(size_t )r ]> 0 ) { 5564if (remote_opt )remote_opt -> attach (remote_experts [(size_t )r ]); 5565if (!remote_experts [(size_t )r ].open (remote_dev [r ],o .expert_cache_remote [(size_t )r ], 5566g .n_layers ,g .n_expert ,by_device [(size_t )r ],xcache ,* srcp ,claimed ,err , 5567o .expert_cache_remote_auto [(size_t )r ])) { 5568 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 5569return 1 ; 5570 } 5571 std::fprintf (stderr ,"strata generate: CUDA%d: %lld additional experts, %.2f GiB; " 5572"results return through pinned host rows\n" ,remote_dev [r ], 5573 (long long )remote_experts [(size_t )r ].resident (),remote_experts [(size_t )r ].gib ()); 5574 } 5575 } 5576 5577// ---- Multi-GPU: the second GPU's expert tier, filled with the ranked pairs the primary does not hold 5578 strata::core::PeerExperts peer ; 5579if (o .peer_device >=1 ) { 5580if (profile .empty ()|| srcp == nullptr || o .expert_cache <=0 ) { 5581 std::fprintf (stderr ,"strata generate: --peer-device needs --expert-profile and the expert cache\n" ); 5582return 1 ; 5583 } 5584const auto tp0 = Clock ::now (); 5585if (!peer .open (o .peer_device ,profile ,xcache ,* srcp ,g .n_layers ,g .n_expert ,o .peer_reserve_mib ,o .peer_slots , 5586err )) { 5587 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 5588return 1 ; 5589 } 5590 std::fprintf (stderr ,"strata generate: peer GPU %d: %lld experts, %.2f GiB (filled in %.1f s); with the primary's " 5591"%lld that is %lld of %lld on the GPUs\n" ,o .peer_device , (long long )peer .resident (),peer .gib (), 5592 std::chrono::duration < double > (Clock ::now ()- tp0 ).count (), (long long )xcache .slots (), 5593 (long long ) (peer .resident ()+ xcache .slots ()), (long long ) (g .n_layers * g .n_expert )); 5594 } 5595 5596if (remote_opt && !remote_opt -> init (err )) { std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ());return 1 ; } 5597Drive drive ; 5598// #731 (opt-in, STRATA_DISJOINT_ADAPT=1): the adaptive tiers leave an expert a helper GPU holds out of the primary's 5599// promotion candidates (it would sit in both caches). Asked live, from the helper's own cache (RemoteExperts::holds, 5600// #854), so an expert the helper's tier swaps in or out later is followed - never a copy taken at load. 5601const bool disjoint_adapt = [] {const char * v = std::getenv ("STRATA_DISJOINT_ADAPT" );return v != nullptr && std::atoi (v )!= 0 ; }(); 5602auto helper_holds = [& ](int64_t l ,int32_t e )-> bool { 5603if (!disjoint_adapt )return false; 5604for (int r = 0 ;r < drive .d .remote_count ;++ r ) 5605if (drive .d .remote [r ]-> holds (l ,e ))return true; 5606return false; 5607 }; 5608for (int r = 0 ;r < 3 ;++ r )if (o .expert_cache_remote [(size_t )r ]> 0 ) 5609drive .d .remote [drive .d .remote_count ++ ]= & remote_experts [(size_t )r ]; 5610drive .d .peer = peer .valid () ?& peer :nullptr ; 5611drive .d .hit_cpu_order = o .expert_cache_cpu_order ; 5612drive .d .split_rows = !o .no_split_rows ; 5613drive .d .pool = & pool ; 5614drive .d .src = srcp ; 5615drive .d .n_expert = g .n_expert ; 5616drive .d .jobs .resize ((size_t )K ); 5617// CS-T: routing-aware prefetch of the file tier (the GGUF in place): the next layer's router on this layer's MoE 5618// input predicts its experts and their pages are warmed meanwhile. It only warms pages; STRATA_LOOKAHEAD=0 is 5619// the A/B arm, STRATA_LOOKAHEAD_K the experts per token (default 10). 5620 strata::core::RouterLookahead lookahead ; 5621if (srcp == & src && src .warms ()&& [] {const char * v = std::getenv ("STRATA_LOOKAHEAD" );return v == nullptr || std::atoi (v )!= 0 ; }()) { 5622 std::vector < std::vector < uint16_t >> routers ((size_t )g .n_layers ); 5623bool ok = true; 5624for (int64_t l = 0 ;l < g .n_layers && ok ;++ l ) { 5625const strata::core::WeightRef * w = wt .find ("blk." + std::to_string (l )+ ".ffn_gate_inp.weight" ); 5626ok = w != nullptr && w -> kind == strata::core::WeightKind ::Bf16InF32 && 5627w -> bytes == (uint64_t ) (g .n_expert * g .n_embd )* 2 ; 5628if (!ok )break ; 5629routers [(size_t )l ].resize ((size_t ) (g .n_expert * g .n_embd )); 5630ok = DPCT_CHECK_ERROR (dpct::get_in_order_queue () 5631 .memcpy (routers [(size_t )l ].data (), 5632w -> data , (size_t )w -> bytes ) 5633 .wait ())== 0 ; 5634 } 5635const char * kv = std::getenv ("STRATA_LOOKAHEAD_K" ); 5636if (ok && lookahead .start (std::move (routers ),g .n_embd ,g .n_expert ,kv ? std::atoi (kv ) :10 ,& src ,err )) { 5637drive .d .lookahead = & lookahead ; 5638 std::fprintf (stderr ,"strata generate: routing-aware prefetch of the file tier on (the next layer's router)\n" ); 5639 }else { 5640/* 5641DPCT1010: SYCL uses exceptions to report errors and does not 5642use the error codes. The cudaGetLastError function call was replaced 5643with 0. You need to rewrite this code. 5644*/ 5645 (void )0 ; 5646 std::fprintf (stderr ,"strata generate: routing-aware prefetch off (%s)\n" , 5647ok ?err .c_str () :"the routers are not BF16 in the arena" ); 5648err .clear (); 5649 } 5650 } 5651// ---- R4.2c: THE HIT PATH. Every one of these is required for `hits_ready()`, which is all-or-nothing on 5652// purpose: a half-configured hit path would compute some experts twice and others not at all, and a token 5653// built on that is wrong rather than refused. 5654void * hit_scratch = nullptr ; 5655int32_t * d_hit_slot = nullptr ; 5656int32_t * d_hit_dst = nullptr ; 5657uint8_t * d_hit_q8 = nullptr ; 5658float * d_hit_q8_scale = nullptr ;///< R4.2h: the fp32 activation scales the CPU path also uses 5659float * d_hit_out = nullptr ; 5660if (o .expert_cache > 0 && !o .no_pool ) { 5661const uint64_t sb = strata::kernels::moe_hit_grouped_scratch_bytes (K ,g .n_embd , strata::kernels::cpu::FF ); 5662if (DPCT_CHECK_ERROR (hit_scratch = (void * )sycl::malloc_device ( 5663 (size_t )sb , dpct::get_in_order_queue ()))!= 56640 || 5665DPCT_CHECK_ERROR (d_hit_slot = sycl::malloc_device < int32_t > ( 5666 (size_t )K , dpct::get_in_order_queue ()))!= 0 || 5667DPCT_CHECK_ERROR (d_hit_dst = sycl::malloc_device < int32_t > ( 5668 (size_t )K , dpct::get_in_order_queue ()))!= 0 || 5669DPCT_CHECK_ERROR (d_hit_q8 = (uint8_t * )sycl::malloc_device ( 5670 (size_t )(g .n_embd /32 )* 34 , 5671 dpct::get_in_order_queue ()))!= 0 || 5672// R4.2h: the fp32 activation scales. Without this the GPU's hits 5673// use the block's fp16 `d` while the CPU's misses use 5674// `ActQ::scale`, which is fp32 - a 4.761e-04 relative disagreement 5675// on every chunk, and the reason enabling the cache changed the 5676// tokens. 5677DPCT_CHECK_ERROR (d_hit_q8_scale = sycl::malloc_device < float > ( 5678 (size_t )(g .n_embd /32 ), 5679 dpct::get_in_order_queue ()))!= 0 || 5680DPCT_CHECK_ERROR (d_hit_out = (float * )sycl::malloc_device ( 5681 (size_t )K * g .n_embd * 4 , 5682 dpct::get_in_order_queue ()))!= 0 ) { 5683 std::fprintf (stderr ,"strata generate: the R4 hit path could not allocate its device buffers\n" ); 5684return 1 ; 5685 } 5686drive .d .cache = & xcache ; 5687drive .d .cache_stream = main_cs ; 5688drive .d .cache_base = (const uint8_t * )xcache .device_slot (0 ); 5689drive .d .cache_blob = (int64_t ) strata::kernels::cpu::expert_layout ().max_blob ; 5690drive .d .cache_slot_off = xcache .slot_offsets (); 5691drive .d .hit_scratch = hit_scratch ; 5692drive .d .parts_out = d_parts ; 5693drive .d .hit_out = d_hit_out ; 5694drive .d .parts_elems = K * g .n_embd ; 5695drive .d .mixed = ss .block .mixed ; 5696drive .d .x_q8_0_hit = d_hit_q8 ; 5697drive .d .x_q8_0_hit_scale = d_hit_q8_scale ; 5698drive .d .d_slot = d_hit_slot ; 5699drive .d .d_dst = d_hit_dst ; 5700drive .d .h_slot .resize ((size_t )K ); 5701 dpct::event_ptr hit_done = nullptr ; 5702if (DPCT_CHECK_ERROR (hit_done = new sycl::event ())!= 0 ) { 5703 std::fprintf (stderr ,"strata generate: the hit path could not create its probe event\n" ); 5704return 1 ; 5705 } 5706drive .d .hit_done = (void * )hit_done ; 5707drive .d .hit_poke = !o .no_hit_poke ; 5708drive .d .h_dst .resize ((size_t )K ); 5709mem_mark ("the R4 hit path" ); 5710 std::fprintf (stderr ,"strata generate: R4 hit path ON - resident experts are computed on the GPU\n" ); 5711 } 5712// ---- P0.S8: the routing trace. Only meaningful with the pool running, because the ids arrive through 5713// the doorbell that the pool consumes - so `--no-pool` is refused rather than silently producing an empty 5714// file that would read as "the router selected nothing". 5715// ---- PER-STAGE TIMING. `--no-capture` only: an event recorded inside a stream capture is silently 5716// dropped, so a captured graph cannot carry these events and the numbers would be zeros that read as 5717// "every stage is free". Refusing is the fix. 5718if (o .stage_timing ) { 5719if (!o .no_capture ) { 5720 std::fprintf (stderr ,"strata generate: --stage-timing records CUDA events inside the layer path, " 5721"and an event record inside a stream capture is silently dropped. Pass " 5722"--no-capture as well.\n" ); 5723return 2 ; 5724 } 5725if (!strata::core::stage_timing_enable ()) { 5726 std::fprintf (stderr ,"strata generate: stage_timing_enable failed\n" ); 5727return 1 ; 5728 } 5729 strata::core::stage_timing_name (0 ,"gr_read (attn)" ); 5730 strata::core::stage_timing_name (1 ,"attention block" ); 5731 strata::core::stage_timing_name (2 ,"gr_write (attn)" ); 5732 strata::core::stage_timing_name (3 ,"gr_read (ffn)" ); 5733 strata::core::stage_timing_name (4 ,"moe_route" ); 5734 strata::core::stage_timing_name (5 ,"moe_finish" ); 5735 strata::core::stage_timing_name (6 ,"gr_write (ffn)" ); 5736// The GDN block's internals. It is 36 of the 48 layers, 0.96 ms each, and its entire weight traffic 5737// is ~26 MB - so ~0.11 ms at the measured read rate. ~13 tiny latency-bound launches live in it and 5738// a single "attention block" number cannot say which one costs anything. 5739 strata::core::stage_timing_name (8 ," gdn: quantize x" ); 5740 strata::core::stage_timing_name (9 ," gdn: qkv gemv" ); 5741 strata::core::stage_timing_name (10 ," gdn: conv+silu" ); 5742 strata::core::stage_timing_name (11 ," gdn: l2 norms" ); 5743 strata::core::stage_timing_name (12 ," gdn: alpha/beta/gate" ); 5744 strata::core::stage_timing_name (13 ," gdn: gdn_step" ); 5745 strata::core::stage_timing_name (14 ," gdn: z + out_norm" ); 5746 strata::core::stage_timing_name (15 ," gdn: out gemv" ); 5747 } 5748 std::FILE * routing = nullptr ; 5749if (!o .dump_routing .empty ()) { 5750if (o .no_pool ) { 5751 std::fprintf (stderr ,"strata generate: --dump-routing needs the expert pool; the routed ids reach " 5752"the host through the doorbell the pool reads. Drop --no-pool.\n" ); 5753return 2 ; 5754 } 5755routing = std::fopen (o .dump_routing .c_str (),"wb" ); 5756if (routing == nullptr ) { 5757 std::fprintf (stderr ,"strata generate: cannot write %s\n" ,o .dump_routing .c_str ()); 5758return 1 ; 5759 } 5760drive .routing = routing ; 5761 } 5762 strata::core::PoolFn pool_fn = o .no_pool ?nullptr :& drive_pool ; 5763// The hit hook rides the same switch as the pool: with no pool there is no `parts` staging to 5764// write into, and a hit path with nowhere to write is a wrong token rather than an error. 5765 strata::core::HitFn hit_fn = 5766 (o .no_pool || o .expert_cache <=0 ) ?nullptr :& strata::core::expert_hit_run ; 5767void * pool_user = o .no_pool ?nullptr : (void * )& drive ; 5768 std::fprintf (stderr ,"strata generate: %d expert-pool workers%s%s\n" ,pool .workers (), 5769pool .host_works () ?" + the host thread" :"" , 5770o .no_pool ?" (UNUSED: --no-pool)" :"" ); 5771 5772// **THE MISALIGNMENT WARNING THAT STOOD HERE IS GONE, BECAUSE THE MISALIGNMENT IS FIXED.** 5773// 5774// It said the tokens were not the model's, and it was true: `session_loop` handed layer `l`'s expert 5775// outputs to layer `l+1`, which multiplied them by layer `l+1`'s router weights (LEDGER L100). The loop 5776// now runs a captured PAIR per layer - `pre[l]` ending with the router and the doorbell, then the CPU 5777// pool, then `post[l]` which combines those experts with THAT layer's weights - so layer `l`'s experts meet 5778// layer `l`'s routing. The generated ids changed the moment it landed, which is what a correctness fix 5779// looks like from the outside. 5780// 5781// The cost is real and is recorded rather than hidden: the window for the CPU pool is now whatever GPU 5782// work follows the ring inside `pre[l]`, which is the shared expert and nothing else - 0.038 ms against 5783// 0.514 ms of CPU work per layer. A per-layer CPU expert pool cannot be hidden behind a strictly serial 5784// residual chain; the CPU term is answered by Phase 3's VRAM expert cache, not by this pipeline. 5785 5786// ---- the graphs 5787 strata::core::SessionGraphs gr ; 5788if (!o .no_capture && !native_pack ) {// plan v0.3 P6: a native pack runs verify windows only 5789// a layer split's CUDA0 session owns only [0, split_at[0]), so its graphs cover that range; the 5790// whole-model replay paths (`session_loop`, the plain generate loop) refuse rather than read another 5791// stage's state - a split runs its layers on the stages' verifiers (serve) or prefill stage chain 5792if (!strata::core::session_capture (wt ,g ,ss ,d_parts ,gr ,err ,/*split=*/ o .gpu_stages ,0 , 5793multi_gpu ?split_at [0 ] :-1 )) { 5794 std::fprintf (stderr ,"strata generate: session_capture: %s\n" ,err .c_str ()); 5795return 1 ; 5796 } 5797 } 5798 5799// **`--no-capture` AND THE EXPERTS ARE MUTUALLY EXCLUSIVE, AND SILENTLY SO.** 5800// 5801// The CPU expert pool is wired into `session_loop` - the host loop around the captured graphs - and 5802// `session_token` has no pool hook at all. So `--no-capture` did not merely change HOW the layers were 5803// launched: it ran the whole model with `parts` left at whatever the buffer held, which is ZERO, and the 5804// only symptom was `expert blobs 0` in a stats line nobody had to read. A run that silently omits the 5805// routed experts is not a slow measurement of this model, it is a measurement of a different model. 5806// 5807// Refusing is the fix. `--no-pool` is the explicit way to say "I want the GPU-only floor". 5808if (o .no_capture && !o .no_pool ) { 5809 std::fprintf (stderr , 5810"strata generate: --no-capture runs `session_token`, which has NO CPU expert pool hook, so " 5811"the routed experts would silently contribute nothing. Pass --no-pool as well if the " 5812"GPU-only floor is what you want.\n" ); 5813return 2 ; 5814 } 5815// The ladder is written by `session_loop`, and `session_token` does not touch the staging buffer at all - so 5816// accepting the flag there would produce a file of uninitialised memory, which reads as a wrong answer rather 5817// than as a mistake. `--no-capture` without `--no-pool` is already refused above, so this catches the pair. 5818if (o .no_capture && !o .dump_layers .empty ()) { 5819 std::fprintf (stderr , 5820"strata generate: --dump-layers is written by `session_loop`; `--no-capture` runs " 5821"`session_token` instead, which never fills the staging buffer. Drop one of the two.\n" ); 5822return 2 ; 5823 } 5824if (o .no_capture && !o .dump_halves .empty ()) { 5825 std::fprintf (stderr , 5826"strata generate: --dump-halves is CAPTURED into the layer graphs, so it needs the " 5827"captured path; `--no-capture` never records it. Drop one of the two.\n" ); 5828return 2 ; 5829 } 5830 5831 strata::uc_probe ("cache-done" ); 5832mem_mark ("the expert cache and the graphs" ); 5833 std::fprintf (stderr ,"strata generate: session is up (engine %s)\n" ,STRATA_VERSION ); 5834if (verify_all_slots )verify_all_slots ("session up" ); 5835auto run_head = [& ](void * stream )-> bool { 5836if (!native_head .loaded ()) 5837return strata::core::lm_head (wt ,g ,ss .block ,d_logits ,stream ,err ); 5838return strata::core::lm_head_mix (wt ,g ,ss .block ,stream ,err )&& 5839native_head .run (ss .block .mixed ,d_logits ,stream ,err ); 5840 }; 5841float * d_emb = nullptr ; 5842if (DPCT_CHECK_ERROR ( 5843d_emb = (float * )sycl::malloc_device ( 5844 (size_t )g .n_embd * 4 , dpct::get_in_order_queue ()))!= 0 ) { 5845 std::fprintf (stderr ,"strata generate: the embedding buffer failed\n" ); 5846return 1 ; 5847 } 5848// **`sample_tokens` TAKES DEVICE POINTERS.** It is a kernel launch; `logits` and `out` are both read and 5849// written on the device. Passing `logits.data()` - the host vector - faults inside the kernel and the 5850// error surfaces at the NEXT synchronising call, which here was the next token's `embed_row`, reporting an 5851// illegal access on a weight plane. Nothing in the parameter names said device. 5852int * d_next = nullptr ; 5853if (DPCT_CHECK_ERROR (d_next = sycl::malloc_device < int > ( 58541 , dpct::get_in_order_queue ()))!= 0 ) { 5855 std::fprintf (stderr ,"strata generate: the sampler output buffer failed\n" ); 5856return 1 ; 5857 } 5858 5859// **`R` IS BOTH THE INPUT AND THE OUTPUT, SO THE NEW TOKEN'S EMBEDDING HAS TO REPLACE THE OLD RESIDUAL.** 5860// At `pos == 0` that is `session_zero`, which is the reference's own initial condition - the embedding 5861// broadcast to all `hc` streams. After that `session_zero` would also wipe the recurrence, so the 5862// broadcast is done directly. Getting this wrong is invisible for exactly one token. 5863void * token_stream = o .stream_token ?main_cs :nullptr ; 5864auto put_input = [& ](int64_t tok ,int64_t pos )-> bool { 5865try { 5866if (!strata::core::embed_row (wt ,g ,tok ,d_emb ,token_stream ,err )) { 5867 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 5868return false; 5869 } 5870if (pos == 0 ) { 5871 strata::core::session_zero (ss ,g ,d_emb ,token_stream ); 5872 }else { 5873for (int64_t c = 0 ;c < g .hc ;++ c ) 5874/* 5875DPCT1124: cudaMemcpyAsync is migrated to asynchronous 5876memcpy API. While the origin API might be synchronous, it 5877depends on the type of operand memory, so you may need to call 5878wait() on event return by memcpy API to ensure synchronization 5879behavior. 5880*/ 5881if (DPCT_CHECK_ERROR (strata::q_of (token_stream )-> memcpy ( 5882ss .R + (size_t )c * g .n_embd ,d_emb , 5883 (size_t )g .n_embd * 4 ))!= 0 ) { 5884 std::fprintf (stderr ,"strata generate: the residual broadcast failed\n" ); 5885return false; 5886 } 5887 } 5888return o .stream_token || 5889DPCT_CHECK_ERROR ( 5890 dpct::get_current_device ().queues_wait_and_throw ())== 0 ; 5891 } 5892catch (sycl::exception const & exc ) { 5893 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 5894 <<", line:" <<__LINE__ << std::endl ; 5895 std::exit (1 ); 5896 } 5897 }; 5898 5899 strata::kernels::SamplerParams sp ; 5900sp .greedy = o .greedy ; 5901sp .seed = o .seed ; 5902sp .top_k = o .top_k ; 5903sp .top_p = o .top_p ; 5904sp .temperature = o .temperature ; 5905// what this run actually samples with (the speculative loop below gets the same parameters); serve samples 5906// per request instead 5907if (!o .serve ) { 5908if (sp .greedy || sp .temperature <=0.0f ) 5909 std::fprintf (stderr ,"strata generate: sampling greedy\n" ); 5910else 5911 std::fprintf (stderr ,"strata generate: sampling temperature=%g top_k=%d top_p=%g seed=%llu\n" , 5912 (double )sp .temperature ,sp .top_k > 0 && sp .top_k < 64 ?sp .top_k :64 , (double )sp .top_p , 5913 (unsigned long long )sp .seed ); 5914 } 5915 5916 std::FILE * dump = nullptr ; 5917// The logits header is written WITH THE FIRST ROW, not at open: a native pack never reaches the 5918// per-token dump site, and a header promising rows that were never written is worse than no file. 5919int32_t hdr [2 ]= {0 ,0 }; 5920bool hdr_written = false; 5921const int64_t dump_positions = (int64_t )o .tokens .size ()- 1 + o .max_new ; 5922if (!o .dump_logits .empty ()) { 5923if (dump_positions > INT32_MAX || n_vocab > INT32_MAX ) { 5924 std::fprintf (stderr ,"strata generate: logits dump dimensions exceed int32\n" ); 5925return 2 ; 5926 } 5927dump = std::fopen (o .dump_logits .c_str (),"wb" ); 5928if (dump == nullptr ) { 5929 std::fprintf (stderr ,"strata generate: cannot write %s\n" ,o .dump_logits .c_str ()); 5930return 1 ; 5931 } 5932// **THE COUNT IS `n_prompt - 1 + max_new`, NOT `n_prompt + max_new`.** The loop writes one row per 5933// position from 0, and it stops once `produced` holds `max_new` tokens - and `produced` only starts 5934// receiving at position `n_prompt - 1`. So a 5-token prompt with `--max-new 6` writes 10 rows, and the 5935// header used to claim 11. A header that describes a different file from the one written is the same 5936// class of defect as a self-check that verifies the wrong invariant: anything reading the count instead 5937// of the size gets a wrong answer that looks authoritative. `tools/logits_identical.py` caught it by 5938// parsing the header and refusing the file. 5939const int32_t n_rows = (int32_t ) strata::program::logits_selection::row_count (dump_positions ,o .logits_stride ); 5940hdr [0 ]= n_vocab ;hdr [1 ]= n_rows ; 5941 } 5942 5943// ---- THE C1 ORACLE: ONE RESIDUAL SNAPSHOT PER LAYER PER POSITION, so the engine can be bisected against 5944// `llama-debug`'s `l_last-<il>` node instead of against a single end-to-end perplexity. The buffer is 5945// PINNED because `session_loop` enqueues a device-to-host copy into it after every layer and the transfer 5946// would otherwise be staged through a pageable bounce buffer on the critical path. 5947 std::FILE * layer_dump = nullptr ; 5948float * layer_stage = nullptr ; 5949const size_t layer_floats = (size_t ) (g .n_layers + 1 )* (size_t )g .hc * (size_t )g .n_embd ; 5950if (!o .dump_layers .empty ()) { 5951layer_dump = std::fopen (o .dump_layers .c_str (),"wb" ); 5952if (layer_dump == nullptr ) { 5953 std::fprintf (stderr ,"strata generate: cannot write %s\n" ,o .dump_layers .c_str ()); 5954return 1 ; 5955 } 5956/* 5957DPCT1048: The original value cudaHostAllocDefault is not meaningful 5958in the migrated code and was removed or replaced with 0. You may need to 5959check the migrated code. 5960*/ 5961if (DPCT_CHECK_ERROR (layer_stage = sycl::malloc_host < float > ( 5962layer_floats , dpct::get_in_order_queue ()))!= 59630 ) { 5964 std::fprintf (stderr ,"strata generate: cannot pin the layer-dump staging buffer\n" ); 5965return 1 ; 5966 } 5967 } 5968 5969// ---- prefill is the DECODE PATH ONE TOKEN AT A TIME, which `phase-2-correct-engine.md:12-13` says is 5970// fine here: "process the prompt through the decode-style graphs in small batches; a 19K-token prompt will 5971// take minutes". A real batched prefill is P2.S6's other half and is not this. 5972// 5973// **THE LOOP IS `feed -> 48 layers -> head -> sample -> feed`, AND THE FIRST GENERATED TOKEN COMES FROM THE 5974// LAST *PROMPT* POSITION.** The first version sampled only on the decode positions, so `produced` was 5975// still empty when the first generated position asked for `produced.back()` - an out-of-bounds read on an 5976// empty vector. Teacher forcing below is what makes the distinction unnecessary to special-case: for every 5977// position before the last prompt one, the next input is the PROMPT's next token, and after that it is the 5978// sampled one. 5979 std::vector < int64_t > produced ; 5980double total_ms = 0 ; 5981double prefill_ms = 0 ;// positions 0 .. n_prompt-2: prompt tokens that only condition 5982const Clock ::time_point t_start = Clock ::now (); 5983double ttft_ms = 0 ; 5984const int64_t n_prompt = (int64_t )o .tokens .size (); 5985int64_t tok = o .tokens [0 ]; 5986 5987// ---- THE PURE-GPU MEASUREMENT. `session_replay` launches all 48 `pre` graphs back to back on one stream 5988// with NO host work between them - no doorbell poll, no pool, no parts copy - so what it times is the GPU 5989// executing the layer sequence and nothing else. It had been declared, defined and never called since the 5990// day it was written. 5991// 5992// **THIS IS THE MEASUREMENT THAT SAYS WHETHER THE ENGINE IS HOST-BOUND OR GPU-BOUND**, and the stage table 5993// cannot answer it: those events measure the interval between two marks on a stream, which includes every 5994// gap where the GPU sat idle waiting for the host to enqueue the next kernel. In `--no-capture` those gaps 5995// are the host's launch latency and they are proportional to the KERNEL COUNT rather than to any work, so 5996// the no-capture stage shares are shares of kernel count - which is why the attention block, with the most 5997// kernels, looks like 55% of the token there. 5998// ---- R0.9: THE PER-STAGE TABLE ON THE CAPTURED GRAPH. 5999if (o .gpu_stages ) { 6000 strata::core::doorbell_reset (db ); 6001double mix = 0 ,ffn = 0 ,post = 0 ; 6002if (!strata::core::session_replay_stages (g ,0 ,0 ,ss ,gr ,main_cs ,mix ,ffn ,post ,err )) { 6003// #610: a native (IQ) pack captures no per-layer graphs; the serve path times its window's stages 6004 std::fprintf (stderr ,"strata generate: %s%s\n" ,err .c_str (), 6005native_pack ?" - a native (IQ) pack has no per-layer graphs to replay. Its decode window's GPU " 6006"stages are printed per request by the serve path instead: STRATA_VERIFY_PROFILE=1 " 6007"STRATA_DECODE_TIMING=1 with --serve (docs/DETAILS.md, \"Where a decode window's " 6008"time goes\")" :"" ); 6009return 1 ; 6010 } 6011const int reps = 20 ; 6012double t_mix = 0 ,t_ffn = 0 ,t_post = 0 ; 6013for (int r = 0 ;r < reps ;++ r ) { 6014if (!strata::core::session_replay_stages (g ,0 ,0 ,ss ,gr ,main_cs ,mix ,ffn ,post ,err )) { 6015 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 6016return 1 ; 6017 } 6018t_mix += mix ; 6019t_ffn += ffn ; 6020t_post += post ; 6021 } 6022const double tot = t_mix + t_ffn + t_post ; 6023 std::printf ("\nper-stage GPU time on the CAPTURED graph, one token over %lld layers\n" , 6024 (long long )g .n_layers ); 6025 std::printf (" %-22s %9.3f ms/token %8.3f ms/layer %6.1f%%\n" ,"mixer (gr_read+attn+gr_write)" , 6026t_mix /reps ,t_mix /reps / (double )g .n_layers ,100.0 * t_mix /tot ); 6027 std::printf (" %-22s %9.3f ms/token %8.3f ms/layer %6.1f%%\n" ,"ffn front + router" , 6028t_ffn /reps ,t_ffn /reps / (double )g .n_layers ,100.0 * t_ffn /tot ); 6029 std::printf (" %-22s %9.3f ms/token %8.3f ms/layer %6.1f%%\n" ,"post (moe_finish+gr_write)" , 6030t_post /reps ,t_post /reps / (double )g .n_layers ,100.0 * t_post /tot ); 6031 std::printf (" %-22s %9.3f ms/token\n" ,"sum of the three" ,tot /reps ); 6032 6033// ---- AND THE MIXER BY LAYER KIND, because 36 of the 48 are GDN and 12 are QSA and a total cannot 6034// separate them. Round 309's uncaptured table put GDN at 10.88 ms for 36 layers against QSA's 4.56 for 6035// 12, which would make the recurrence the largest single R3 target - and that table had `moe_finish` 6036// wrong by 4x, so the ratio is re-derived here from the captured graph rather than inherited. 6037 { 6038// **ACCUMULATED OVER `reps`, NOT MEASURED ONCE AND THEN DIVIDED.** The first version called the 6039// per-layer replay a single time and printed `gdn / reps`, which reported GDN at 0.480 ms/token 6040// against a mixer total of 14.039 - a factor of exactly `reps`, and the tell was that 6041// 0.480 + 0.220 = 0.700 = 14.039 / 20. 6042 std::vector < double > acc ((size_t )g .n_layers ,0.0 ),per ; 6043double f2 = 0 ,p2 = 0 ; 6044for (int r = 0 ;r < reps ;++ r ) { 6045if (!strata::core::session_replay_stages_per_layer (g ,0 ,0 ,ss ,gr ,main_cs ,per ,f2 ,p2 ,err )) { 6046 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 6047return 1 ; 6048 } 6049for (int64_t l = 0 ;l < g .n_layers ;++ l )acc [(size_t )l ]+= per [(size_t )l ]; 6050 } 6051double gdn = 0 ,qsa = 0 ,worst = 0 ; 6052int64_t ng = 0 ,nq = 0 ,worst_l = 0 ; 6053for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 6054const double v = acc [(size_t )l ] /reps ; 6055if (strata::core::is_qsa_layer (g ,l )) {qsa += v ;++ nq ; } 6056else {gdn += v ;++ ng ; } 6057if (v > worst ) {worst = v ;worst_l = l ; } 6058 } 6059 std::printf ("\n the mixer by layer kind, averaged over %d runs\n" ,reps ); 6060 std::printf (" %-22s %9.3f ms/token %8.3f ms/layer (%lld layers)\n" ,"GDN layers" , 6061gdn ,ng ?gdn / (double )ng :0.0 , (long long )ng ); 6062 std::printf (" %-22s %9.3f ms/token %8.3f ms/layer (%lld layers)\n" ,"QSA layers" , 6063qsa ,nq ?qsa / (double )nq :0.0 , (long long )nq ); 6064 std::printf (" %-22s layer %lld at %.3f ms\n" ,"worst mixer layer" , (long long )worst_l ,worst ); 6065 std::printf (" %-22s %9.3f ms/token (must equal the mixer above)\n" ,"GDN + QSA" ,gdn + qsa ); 6066 } 6067 6068// ================================ R0.11: THE FIVE STAGES SEPARATELY ================================ 6069// 6070// Prefixes 1..5 are replayed per layer with the residual restored between them, and consecutive 6071// differences are the per-stage times. **THE CHECK IS THAT THE FIVE SUM TO THE THREE-GRAPH TOTAL** - 6072// the same independent-restatement test that caught round 320's divide-by-reps bug, and it is the only 6073// reason to believe a table built out of differences. 6074 { 6075 std::vector < double > acc5 (5 ,0.0 ),per ,s5 ; 6076for (int r = 0 ;r < reps ;++ r ) { 6077if (!strata::core::session_replay_stage_prefixes (g ,0 ,0 ,ss ,gr ,main_cs ,s5 ,per ,err )) { 6078 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 6079return 1 ; 6080 } 6081for (int k = 0 ;k < 5 ;++ k )acc5 [(size_t )k ]+= s5 [(size_t )k ]; 6082 } 6083static const char * sn [5 ]= {"0 gr_read (attn)" ,"1 attention" ,"2 gr_write (attn)" , 6084"3 gr_read (ffn)" ,"4 moe_route (router)" }; 6085const char * kind [5 ]= {"GR" ,"ATTN" ,"GR" ,"GR" ,"ROUTER" }; 6086double tot5 = 0 ,gr_ms = 0 ; 6087 std::printf ("\n the five stages separately, by differencing prefixes\n" ); 6088 std::printf (" %-24s %-8s %10s %10s %8s\n" ,"stage" ,"kind" ,"ms/token" ,"ms/layer" ,"share" ); 6089for (int k = 0 ;k < 5 ;++ k ) { 6090const double v = acc5 [(size_t )k ] /reps ; 6091tot5 += v ; 6092if (k != 1 && k != 4 )gr_ms += v ; 6093 std::printf (" %-24s %-8s %10.3f %10.4f %7.1f%%\n" ,sn [k ],kind [k ],v , 6094v / (double )g .n_layers ,0.0 ); 6095 } 6096for (int k = 0 ;k < 5 ;++ k ) { 6097const double v = acc5 [(size_t )k ] /reps ; 6098 (void )v ; 6099 } 6100 std::printf (" %-24s %-8s %10.3f\n" ,"sum of the five" ,"" ,tot5 ); 6101 std::printf (" %-24s %-8s %10.3f <- R3.3's target is <= 3 ms for all four passes\n" , 6102"GR passes (0,2,3)" ,"GR" ,gr_ms ); 6103 std::printf ("\n the three-graph total above was %.3f ms/token; the five must account for it.\n" , 6104tot /reps ); 6105 6106// ================================ R3.5c: THE SAME TABLE, A DIFFERENT WAY ================================ 6107// 6108// The differencing table above mixes five graphs per layer, so stage 4's interval carries the launch 6109// of the FULL five-stage graph while stage 3's carries a four-stage one. This sweep launches ONE 6110// graph type per layer and nothing else, so that bias cannot exist. **If the two disagree, the 6111// difference IS the bias and this one is right** - and stage 4 is the router, so it is exactly the 6112// number that must not be wrong. 6113 { 6114double sweep [6 ]= {0 ,0 ,0 ,0 ,0 ,0 }; 6115for (int k = 1 ;k <=5 ;++ k ) { 6116double acc = 0 ,one = 0 ; 6117for (int r = 0 ;r < reps ;++ r ) { 6118if (!strata::core::session_replay_stage_sweep (g ,0 ,0 ,ss ,gr ,main_cs ,k ,one ,err )) { 6119 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 6120return 1 ; 6121 } 6122acc += one ; 6123 } 6124sweep [k ]= acc /reps ; 6125 } 6126 std::printf ("\n the same five stages, by SWEEPING each prefix back to back (no graph switching)\n" ); 6127 std::printf (" %-24s %10s %10s %12s\n" ,"stage" ,"prefix sweep" ,"difference" ,"bias" ); 6128static const char * sn2 [5 ]= {"0 gr_read (attn)" ,"1 attention" ,"2 gr_write (attn)" , 6129"3 gr_read (ffn)" ,"4 moe_route (router)" }; 6130for (int k = 0 ;k < 5 ;++ k ) { 6131const double sw = sweep [k + 1 ]- sweep [k ]; 6132const double df = acc5 [(size_t )k ] /reps ; 6133 std::printf (" %-24s %10.3f %10.3f %11.1f%%\n" ,sn2 [k ],sw ,df , 6134sw != 0.0 ?100.0 * (df /sw - 1.0 ) :0.0 ); 6135 } 6136 std::printf (" %-24s %10.3f (full pre, 48 layers)\n" ,"prefix 5 total" ,sweep [5 ]); 6137 } 6138 } 6139 std::printf ("\n compare `--gpu-only-full`, which replays the same work as TWO graphs per layer. The\n" ); 6140 std::printf (" three sum slightly above it because each launch carries the driver's gap.\n" ); 6141 strata::core::session_graphs_free (gr ); 6142 strata::core::doorbell_free (db ); 6143 sycl::free (d_next , dpct::get_in_order_queue ()); 6144return 0 ; 6145 } 6146 6147if (o .graph_only ) { 6148 strata::core::doorbell_reset (db ); 6149// one warm pass so the first launch does not pay for page mapping 6150if (!strata::core::session_replay (g ,0 ,0 ,ss ,gr ,main_cs ,err )) { 6151 std::fprintf (stderr ,"strata generate: session_replay warm: %s\n" ,err .c_str ()); 6152return 1 ; 6153 } 6154if (DPCT_CHECK_ERROR ( 6155 dpct::get_current_device ().queues_wait_and_throw ())!= 0 ) { 6156 std::fprintf (stderr ,"strata generate: session_replay warm faulted\n" ); 6157return 1 ; 6158 } 6159const int reps = 20 ; 6160const Clock ::time_point t0 = Clock ::now (); 6161for (int r = 0 ;r < reps ;++ r ) { 6162if (!strata::core::session_replay (g ,0 ,0 ,ss ,gr ,main_cs ,err )) { 6163 std::fprintf (stderr ,"strata generate: session_replay: %s\n" ,err .c_str ()); 6164return 1 ; 6165 } 6166 } 6167if (DPCT_CHECK_ERROR ( 6168 dpct::get_current_device ().queues_wait_and_throw ())!= 0 ) { 6169/* 6170DPCT1009: SYCL reports errors using exceptions and does not use 6171error codes. Please replace the "get_error_string_dummy(...)" with a 6172real error-handling function. 6173*/ 6174/* 6175DPCT1010: SYCL uses exceptions to report errors and does not 6176use the error codes. The cudaGetLastError function call was replaced 6177with 0. You need to rewrite this code. 6178*/ 6179 std::fprintf (stderr , 6180"strata generate: session_replay faulted: %s\n" , 6181 dpct::get_error_string_dummy (0 )); 6182return 1 ; 6183 } 6184const double ms = std::chrono::duration < double , std::milli > (Clock ::now ()- t0 ).count () / (double )reps ; 6185 std::printf ("pre graphs only %8.2f ms per token over %lld layers -> %.2f tok/s of GPU work\n" ,ms , 6186 (long long )g .n_layers ,ms > 0 ?1000.0 /ms :0.0 ); 6187 std::printf (" %8.3f ms per layer\n" ,ms / (double )g .n_layers ); 6188return 0 ; 6189 } 6190 6191// ---- R0.3: THE TRUE PER-TOKEN GPU FLOOR. 6192// 6193// `--graph-only` above launches ONLY `gr.execs[l]`, the `pre` graphs. It omits the 48 `post` graphs - the 6194// shared expert, the combine and the second `gr_write` - and the LM head. Everything this project published 6195// as "39.8 ms pure GPU" came from that loop while being described as the whole GPU, which also made the 6196// "host's share = 49.4 - 39.8 = 9.6 ms" figure wrong by however much the missing work costs. See 6197// Memory/ERRORS.md A4/A5. 6198// 6199// This flag is what "pure GPU" has to mean, and it replaces that number everywhere. No pool runs, so 6200// `parts` keeps whatever the buffer holds and the timing is GPU work alone. 6201if (o .gpu_only_full ) { 6202 strata::core::doorbell_reset (db ); 6203const int reps = 20 ; 6204double ms_layers = 0 ,ms_head = 0 ; 6205for (int r = -1 ;r < reps ;++ r ) {// r == -1 is the warm pass, not counted 6206const Clock ::time_point t0 = Clock ::now (); 6207if (!strata::core::session_replay_full (g ,0 ,0 ,ss ,gr ,main_cs ,err )) { 6208 std::fprintf (stderr ,"strata generate: session_replay_full: %s\n" ,err .c_str ()); 6209return 1 ; 6210 } 6211// The sync is INSIDE the interval on purpose: it is the wait for the GPU, so t1 - t0 is GPU time. 6212if (DPCT_CHECK_ERROR (strata::q_of (main_cs )-> wait ())!= 0 ) { 6213 std::fprintf ( 6214stderr , 6215"strata generate: gpu-only-full layers faulted: %s\n" , 6216/* 6217DPCT1009: SYCL reports errors using exceptions and does 6218not use error codes. Please replace the 6219"get_error_string_dummy(...)" with a real error-handling 6220function. 6221*/ 6222/* 6223DPCT1010: SYCL uses exceptions to report errors and 6224does not use the error codes. The cudaGetLastError function 6225call was replaced with 0. You need to rewrite this code. 6226*/ 6227 dpct::get_error_string_dummy (0 )); 6228return 1 ; 6229 } 6230const Clock ::time_point t1 = Clock ::now (); 6231if (!run_head (main_cs )) { 6232 std::fprintf (stderr ,"strata generate: gpu-only-full lm_head: %s\n" ,err .c_str ()); 6233return 1 ; 6234 } 6235if (DPCT_CHECK_ERROR (strata::q_of (main_cs )-> wait ())!= 0 ) { 6236 std::fprintf ( 6237stderr ,"strata generate: gpu-only-full head faulted: %s\n" , 6238/* 6239DPCT1009: SYCL reports errors using exceptions and does 6240not use error codes. Please replace the 6241"get_error_string_dummy(...)" with a real error-handling 6242function. 6243*/ 6244/* 6245DPCT1010: SYCL uses exceptions to report errors and 6246does not use the error codes. The cudaGetLastError function 6247call was replaced with 0. You need to rewrite this code. 6248*/ 6249 dpct::get_error_string_dummy (0 )); 6250return 1 ; 6251 } 6252const Clock ::time_point t2 = Clock ::now (); 6253if (r < 0 )continue ; 6254ms_layers += std::chrono::duration < double , std::milli > (t1 - t0 ).count (); 6255ms_head += std::chrono::duration < double , std::milli > (t2 - t1 ).count (); 6256 } 6257ms_layers /= (double )reps ; 6258ms_head /= (double )reps ; 6259const double ms = ms_layers + ms_head ; 6260 std::printf ("GPU floor pre+post+head %7.2f ms per token -> %.2f tok/s of GPU work\n" ,ms , 6261ms > 0 ?1000.0 /ms :0.0 ); 6262 std::printf (" %8.3f ms layers (%lld x pre+post)\n" ,ms_layers , (long long )g .n_layers ); 6263 std::printf (" %8.3f ms per layer\n" ,ms_layers / (double )g .n_layers ); 6264 std::printf (" %8.3f ms LM head\n" ,ms_head ); 6265return 0 ; 6266 } 6267 6268// ---- **THE TOKEN PATH ALLOCATES NOTHING (P2.T10, review finding H3).** 6269// 6270// `session_loop` used to allocate its pinned staging buffer, its probe event and its host pin ON EVERY 6271// TOKEN, and `cudaFreeHost` at the end of each call implicitly synchronises the device - so every token 6272// finished with a device-wide sync nobody asked for. The scratch is created once here and reused; it also 6273// owns the host pin for the whole session rather than taking and releasing it per token. 6274 strata::core::SessionLoopScratch loop_scratch ; 6275struct ScratchFree { 6276 strata::core::SessionLoopScratch * p ; 6277 ~ScratchFree () {if (p != nullptr )p -> free (); } 6278 }scratch_free {& loop_scratch }; 6279// Initialised unconditionally, including under --no-pool: the loop validates the scratch it is handed, so 6280// passing a default-constructed one is an error rather than a fallback. (It was, and the guard caught it - 6281// which is the point of the guard.) One allocation at setup either way. 6282if (!loop_scratch .init ((size_t )K * g .n_embd * 4 ,err )) { 6283 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 6284return 1 ; 6285 } 6286// Plan v0.3 P3: the whole token as ONE graph whenever nothing needs a host step between the ring and post[l] 6287// (the VRAM expert tier and the per-layer dumps do). `--no-token-graph` keeps two graphs per layer. 6288 strata::core::TokenGraph tgraph ; 6289struct TokenGraphFree { 6290 strata::core::TokenGraph * p ; 6291 ~TokenGraphFree () { strata::core::token_graph_free (* p ); } 6292 }tgraph_free {& tgraph }; 6293// Plan v0.3 P4: with a PROFILE-filled cache the residency is static, so the hit decision moves onto the 6294// device and the token graph keeps it. (A cache filled on demand still needs the per-layer host path.) 6295 std::vector < int32_t > host_res ; 6296// The residency table is read by kernels on non-blocking streams, which do not wait for the legacy stream a plain 6297// cudaMemcpy runs on, and a pageable copy can return before its DMA has landed: each upload waits for its own copy 6298// (the current device's legacy stream, stream 0 - nothing else; HIP has no cudaStreamLegacy name, #550). 6299auto res_put = [& host_res ](int32_t * dst )-> dpct::err0 { 6300// SYCL port: the in-order queue's memcpy, waited for: the copy is complete when this returns 6301try { 6302 dpct::get_in_order_queue ().memcpy (dst ,host_res .data (),host_res .size ()* sizeof (int32_t )).wait (); 6303return 0 ; 6304 }catch (sycl::exception const & exc ) { 6305 std::cerr <<exc .what () <<" (res_put)" << std::endl ; 6306return 1 ; 6307 } 6308 }; 6309int32_t * d_res = nullptr ; 6310int32_t * d_hit_count = nullptr ; 6311 strata::core::TokenHits thits ; 6312const bool graph_hits = hit_fn != nullptr && !profile .empty ()&& !o .no_pool ; 6313if (graph_hits && !o .no_capture && !o .no_token_graph && layer_dump == nullptr && half_dump == nullptr ) { 6314host_res .assign ((size_t ) (g .n_layers * g .n_expert ), strata::core::kNotResident ); 6315int64_t resident = 0 ; 6316for (int64_t l = 0 ;l < g .n_layers ;++ l ) 6317for (int64_t e = 0 ;e < g .n_expert ;++ e ) { 6318const int st = multi_gpu ?stage_of (l ) :0 ; 6319const int32_t slot = st > 0 ?stages [(size_t )st - 1 ]-> cache .slot_of (l ,e ) :xcache .slot_of (l ,e ); 6320host_res [(size_t ) (l * g .n_expert + e )]= slot ; 6321if (slot != strata::core::kNotResident )++ resident ; 6322 } 6323if (DPCT_CHECK_ERROR ( 6324d_res = sycl::malloc_device < int32_t > ( 6325host_res .size (), dpct::get_in_order_queue ()))!= 0 || 6326DPCT_CHECK_ERROR (d_hit_count = sycl::malloc_device < int32_t > ( 63271 , dpct::get_in_order_queue ()))!= 0 || 6328res_put (d_res )!= 0 ) { 6329 std::fprintf (stderr ,"strata generate: the device residency table could not be staged\n" ); 6330return 1 ; 6331 } 6332thits .d_res = d_res ; 6333thits .n_expert = g .n_expert ; 6334// a file-backed arena (STRATA_ARENA_MMAP): the experts no GPU holds are the ones the CPU pool and the 6335// prompt path will read - start reading them now instead of faulting them in 4 KB at a time mid-request 6336// ... and the ones a GPU holds are handed back first (STRATA_ARENA_RELEASE=0 keeps them): the fill read the 6337// whole arena, and left mapped and referenced it crowds every other allocation into swap 6338 { 6339static const bool keep = std::getenv ("STRATA_ARENA_RELEASE" )&& std::getenv ("STRATA_ARENA_RELEASE" )[0 ]== '0' ; 6340rss_probe ("before the release" ); 6341uint64_t released = 0 ; 6342if (!keep ) 6343for (size_t i = 0 ;i < host_res .size ();++ i ) 6344if (host_res [i ]!= strata::core::kNotResident ) 6345released += srcp -> release ((int64_t )i /g .n_expert , (int64_t )i %g .n_expert ); 6346if (released > 0 ) 6347 std::fprintf (stderr ,"strata generate: expert arena: %.2f GiB of VRAM-held experts handed back to the OS\n" , 6348 (double )released / (1024.0 * 1024.0 * 1024.0 )); 6349rss_probe ("after the release" ); 6350int64_t pf = 0 ; 6351for (size_t i = 0 ;i < host_res .size ();++ i ) 6352if (host_res [i ]== strata::core::kNotResident ) { 6353srcp -> prefetch ((int64_t )i /g .n_expert , (int64_t )i %g .n_expert ); 6354++ pf ; 6355 } 6356 (void )pf ; 6357rss_probe ("after the prefetch hints" ); 6358 } 6359for (auto & st :stages ) {// layer split across GPUs: the same table on every device 6360const strata::core::OnDevice on (st -> dev ); 6361if (DPCT_CHECK_ERROR ( 6362st -> d_res = sycl::malloc_device < int32_t > ( 6363host_res .size (), dpct::get_in_order_queue ()))!= 0 || 6364res_put (st -> d_res )!= 0 ) { 6365 std::fprintf (stderr ,"strata generate: layer split: CUDA%d residency table failed\n" ,st -> dev ); 6366return 1 ; 6367 } 6368 } 6369thits .cache_base = drive .d .cache_base ; 6370thits .blob = drive .d .cache_blob ; 6371thits .d_slot = drive .d .d_slot ; 6372thits .d_dst = drive .d .d_dst ; 6373thits .d_count = d_hit_count ; 6374thits .x_q8 = drive .d .x_q8_0_hit ; 6375thits .x_scale = drive .d .x_q8_0_hit_scale ; 6376thits .scratch = drive .d .hit_scratch ; 6377thits .hit_out = drive .d .hit_out ; 6378drive .d .host_res = host_res .data (); 6379 std::fprintf (stderr ,"strata generate: token graph hit path: %lld resident experts, decided on the device\n" , 6380 (long long )resident ); 6381 } 6382if (!o .no_capture && !o .no_token_graph && layer_dump == nullptr && half_dump == nullptr && 6383 (hit_fn == nullptr || thits .on ())&& !native_pack && !multi_gpu ) {// a split's token graph cannot span stages 6384if (!strata::core::session_capture_token (wt ,g ,ss ,d_parts ,loop_scratch .y_miss ,loop_scratch .parts_bytes , 6385tgraph ,err ,thits .on () ?& thits :nullptr )) { 6386 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 6387return 1 ; 6388 } 6389 std::fprintf (stderr ,"strata generate: token graph captured (48 layers, one launch per token)\n" ); 6390 } 6391 6392// ================================ WHERE THE HOST TERM GOES, PER TOKEN ================================ 6393// 6394// **`--gpu-only-full` MEASURES THE 48 LAYER GRAPHS AND THE LM HEAD AND NOTHING ELSE.** It never enters 6395// this loop, so it does not run `ple_stage_token`, `embed_row`, the whole-vocabulary logits readback, the 6396// NaN scan or the sampler - and `--no-pool --stats` against that floor was being read as "the per-layer 6397// round trip costs 12.4 ms" when an unknown part of it is per TOKEN, not per layer. That is the same error 6398// the review catalogued as A4/A5, one level down: a difference between two measurements attributed to a 6399// mechanism that neither of them isolates. 6400// 6401// Six accumulators, because the six have different fixes. Reported in `--stats` as ms/token. **The 6402// boundary after the layer loop is the one that matters**: without it the head's interval swallows all 48 6403// layers and the report reads as "head = 50 ms", which is not a thing that can happen to 1.4 ms of GPU 6404// work. That is not hypothetical - it is what the first version of this printed. 6405double ms_ple = 0 ,ms_embed = 0 ,ms_layers = 0 ,ms_head = 0 ,ms_readback = 0 ,ms_sample = 0 ; 6406int64_t phase_tokens = 0 ; 6407 6408// ================================ plan v0.3 P8: THE PERSISTENT ENGINE (--serve) ================================ 6409// 6410// The weights, the expert arena and the VRAM tier load once; then requests arrive on stdin, one per line, 6411// 6412// GEN <max_new> <id,id,...> 6413// 6414// and each generated token is written to stdout as `T <id>` as soon as its verify window is done, followed by 6415// 6416// DONE <generated> <prompt_tokens> <prompt_ms> <decode_ms> <stop|length|cancel> <drafts accepted> 6417// <drafts offered> <prompt tokens reused> ... <prompt tokens read> (see the DONE line below; #471) 6418// 6419// Before that, `RESUME <n>` (n prompt tokens are not read again), `PP <position> <prompt_tokens> <ms> <tok/s>` 6420// after every prompt chunk, and `REUSED <n>` once the prompt is read. (`ERR <message>` instead when a request 6421// cannot run; `STOP` ends the running request at its next step; `QUIT` ends the process.) A request continues 6422// from the live session or the longest conversation checkpoint its prompt starts with (see ConvCheckpoint), 6423// otherwise from an empty sequence (`session_zero`); the rest of the prompt goes through the batched prompt path 6424// and its last token through the first verify window - the path all three model files share. Decoding is greedy. 6425// The expert-cache slots (from the end of the cache) that hold the prompt path's buffers for a chunk, and the 6426// bytes from the first of them to the end. 6427// the share of expert bytes the arena could pin (sizes the prompt path's streamed ring and its lend cap) 6428if (srcp != nullptr && o .prefill_chunk > 0 ) { 6429uint64_t pinned = 0 ,total = 0 ; 6430const auto & lay = strata::kernels::cpu::expert_layout (); 6431for (int64_t l = 0 ;l < g .n_layers ;++ l ) 6432for (int64_t e = 0 ;e < g .n_expert ;++ e ) { 6433const uint64_t b = lay .blob_bytes (l ); 6434total += b ; 6435if (srcp -> pinned (l ,e ))pinned += b ; 6436 } 6437 strata::prefill::Prefill ::set_pinned_share (total ? (double )pinned / (double )total :1.0 ); 6438// SYCL port: the pairs outside the VRAM cache decide the prompt path's stream-all walk (prefill.cpp ring_slots) 6439int64_t nonres = 0 ; 6440for (const int32_t r :host_res )nonres += r < 0 ; 6441 strata::prefill::set_nonresident_share (host_res .empty () ?1.0 : (double )nonres / (double )host_res .size ()); 6442 } 6443// bytes -> slots for CUDA0's cache: exact when it knows its per-slot offsets (a native pack's blobs differ 6444// per layer), otherwise max_blob each. 6445auto slots_from_bytes = [& ](uint64_t need )-> int64_t { 6446const int64_t blob = (int64_t ) strata::kernels::cpu::expert_layout ().max_blob ; 6447int64_t k = (int64_t ) ((need + (uint64_t )blob - 1 ) / (uint64_t )blob ); 6448if (xcache .slot_offsets ()!= nullptr ) {// sized slots: take slots from the end until they hold `need` 6449k = 0 ; 6450while (k < xcache .slots ()&& 6451 (uint64_t ) (xcache .bytes ()- (int64_t )xcache .slot_offsets ()[xcache .slots ()- k ])< need )++ k ; 6452 } 6453return k ; 6454 }; 6455// ...and its inverse, for the ring's room: the bytes the cache's last `k` slots hold. k can arrive <= 0: the 6456// caller's lend budget is `min(slots - 128, pct * slots / 100)` and goes negative on a cache smaller than 128 6457// slots, where `slots - k` would index slot_offsets() past its end. Such a cache lends nothing, so say so. 6458auto bytes_from_slots = [& ](int64_t k )-> uint64_t { 6459if (k <=0 )return 0 ; 6460if (xcache .slot_offsets ()!= nullptr ) 6461return (uint64_t ) (xcache .bytes ()- (int64_t )xcache .slot_offsets ()[xcache .slots ()- k ]); 6462return (uint64_t )k * (uint64_t ) strata::kernels::cpu::expert_layout ().max_blob ; 6463 }; 6464auto lend_slots = [& ](int64_t c )-> int64_t { 6465return slots_from_bytes (strata::prefill::Prefill ::bytes_needed (g ,ss ,c )); 6466 }; 6467// `lend_bytes` went with the single-cache serve loan: a participant's loan is priced by `part_bytes` from its 6468// OWN cache, and the only other user of the old helper was the serve path's own relayout. 6469auto request_chunk = [](int64_t tokens ,int64_t max_chunk )-> int64_t { 6470if (tokens <=0 || max_chunk <=0 )return 0 ; 6471const int64_t rounded = tokens > std::numeric_limits < int64_t > ::max ()- 255 6472 ?tokens 6473 : ((tokens + 255 ) /256 )* 256 ; 6474return std::min (max_chunk ,rounded ); 6475 }; 6476// STRATA_PREFILL_EQUAL=1 (opt-in, PR #693): a segment of `tokens` reads in n = ceil(tokens / max_chunk) chunks of EQUAL 6477// size (ceil(tokens / n) rounded up to 256) instead of full chunks and a short last one. A chunk of 6478// stream_all_min_tokens() or more streams every expert the GPU does not hold, whatever its length, so a prompt's cost 6479// is its number of such chunks and equal chunks borrow no more slots than that count needs. A last chunk below 6480// stream_all_min_tokens() stays as it is (it moves only the experts its own tokens route to). Used ONLY where a 6481// segment's chunk is chosen (the serve lend, generate's prompt); `request_chunk` is unchanged because 6482// STRATA_SPLIT_SMALL_OWN uses it too. The chunk geometry changes the rounding, so it is off by default. 6483static const bool equal_chunks = [] {const char * e = std::getenv ("STRATA_PREFILL_EQUAL" );return e != nullptr && e [0 ]== '1' ; }(); 6484auto equal_chunk = [& ](int64_t tokens ,int64_t max_chunk )-> int64_t { 6485const int64_t plain = request_chunk (tokens ,max_chunk ); 6486if (!equal_chunks || tokens <=0 || max_chunk <=0 )return plain ; 6487const int64_t n = tokens /max_chunk + (tokens %max_chunk != 0 ); 6488const int64_t last = tokens - (n - 1 )* max_chunk ; 6489if (n <=1 || last < strata::prefill::Prefill ::stream_all_min_tokens ())return plain ; 6490const int64_t per = tokens /n + (tokens %n != 0 ); 6491const int64_t rounded = per > std::numeric_limits < int64_t > ::max ()- 255 ?per : ((per + 255 ) /256 )* 256 ; 6492return std::min (max_chunk ,rounded ); 6493 }; 6494// The prompt path's chunk and the slots it borrows for its buffers: the requested chunk halved until it fits, 6495// or with --prefill auto the largest chunk whose buffers take at most kAutoLendPct % of the slots (a 6496// lent slot's expert is streamed during the prompt and refilled after it; measured on a 12 GB card, 32K Q2_0 6497// prompt: 4096 791 tok/s, 6144 878, 8192 973 with 69% of the slots lent). A request lends only what its own 6498// prompt needs (Prefill::relayout), so a big chunk costs short prompts nothing. 0 = none fits. 6499// at 8192-token chunks nearly every expert streams anyway, so a lent slot costs little: 90% when the 6500// copies are DMA from pinned RAM (Q2_0 8192 + a 384-slot ring: 1283 tok/s), 85% when host copies are the 6501// limit (lending more only streams more through them). STRATA_PREFILL_LEND_PCT overrides (tuning). 6502// Hoisted out of plan_lend: the serve path's per-stage loans obey the same cap, one participant at a time. 6503const int64_t kAutoLendPct = [] { 6504const char * v = std::getenv ("STRATA_PREFILL_LEND_PCT" ); 6505return v ? (int64_t ) std::atoi (v ) 6506 : (int64_t ) (strata::prefill::Prefill ::pinned_share () >=0.9 ?90 :85 ); 6507 }(); 6508// The largest chunk --prefill auto may pick: the operator's ceiling (--prefill auto:N) and never past the 6509// context, but a bare `auto` always reaches 8192. 32768 and 16384 stay opt-in (#282): a 32K prompt with 6510// IQ2_XS (RTX 5090, 64K context) read at 5,624 tok/s in 8192-token chunks and 6,465 in one 32768 chunk (40K 6511// -> 18K experts streamed; an NVFP4 pack at 262K: 3,535 -> 5,201). 6512const int64_t auto_ceiling = std::max < int64_t > (8192 , std::min < int64_t > (o .prefill_auto_max ,o .max_context )); 6513// The auto scan used to walk a fixed list of sizes - 32768, 16384, 8192, 6144, ... - and take the first that 6514// fit. That list is coarse exactly where a rig needs it: this one affords ~8,700 tokens and was handed 8192, 6515// and 8704 is not on it. `bytes_needed` is a sum of (T x positive constant) terms plus a max of such sums, 6516// so it rises monotonically with T, and so does every test the scan applies - which makes the largest size 6517// that fits a bisection on the 256-token grid the prompt path already works on (`request_chunk` rounds up to 6518// it). log2(32768/256) = 7 probes, against the list's 10, at one `bytes_needed` per probe. 6519auto biggest_chunk = [](int64_t ceiling ,auto && ok )-> int64_t { 6520if (ceiling < 256 )return 0 ; 6521int64_t lo = 1 ,hi = ceiling /256 ,best = 0 ;// n = T / 256, and ok() is monotone in n 6522while (lo <=hi ) { 6523const int64_t mid = lo + (hi - lo ) /2 ; 6524if (ok (mid * 256 )) {best = mid * 256 ;lo = mid + 1 ; }else hi = mid - 1 ; 6525 } 6526return best ; 6527 }; 6528auto plan_lend = [& ](int64_t & chunk )-> int64_t { 6529auto slots_for = lend_slots ; 6530// 0.1.39's list with its ring (also the size up to which a prompt keeps that ring under #583) 6531auto old_rule = [& ]()-> int64_t { 6532 strata::prefill::Prefill ::set_ring_budget (0 ,0 ); 6533static constexpr int64_t kAutoChunks []= {32768 ,16384 ,8192 ,6144 ,4096 ,3072 ,2048 ,1024 ,512 ,256 }; 6534for (const int64_t c :kAutoChunks ) { 6535// above 8192: only when asked for, and only when a prompt of the context can use it 6536if (c > 8192 && (c > o .prefill_auto_max || c > o .max_context ))continue ; 6537const int64_t k = slots_for (c ); 6538if (k + 128 <=xcache .slots ()&& k * 100 <=kAutoLendPct * xcache .slots ())return c ; 6539 } 6540return 0 ; 6541 }; 6542if (o .prefill_auto && !strata::prefill::Prefill ::ring_bytes_enabled ()) {// STRATA_RING_BYTES=0: 0.1.39's list 6543const int64_t c = old_rule (); 6544if (c > 0 ) {chunk = c ;return slots_for (c ); } 6545return 0 ; 6546 } 6547if (o .prefill_auto ) {// the default since 0.1.39b (#583) 6548// The chunk and the ring are one budget, and the ring is the better buy. Measured on this 4-way 6549// IQ3_S rig (2x RTX 3060 + 2x RTX 5060, CUDA3 lending at its 90% cap) on a 120K prompt: 8960 tokens 6550// with the 17-slot ring that leaves reads at 963 tok/s, 8192/130 at 1,008, 7168 with the ring full at 6551// its 199-slot byte budget at 1,000, and 5632/199 at 915. A ring slot is worth ~0.53 tok/s there and 6552// a chunk token ~0.05, so the 69 slots between a full ring and 8192's 130 are worth more than the 6553// 512 chunk tokens they cost - and once the ring IS full, shrinking the chunk further buys nothing. 6554// So: the largest chunk that still leaves the ring full. Only a rig where no chunk at all can afford 6555// one falls back to the old rule, which takes the largest chunk whose ring clears kRingMin (the 6556// value at or below which ring_slots() returns STAGE and streaming is off). 6557constexpr int64_t kRingMin = 16 ; 6558const int64_t small = old_rule ();// 0.1.39's chunk (and its ring for the prompts that fit it) 6559const int64_t ring_max = strata::prefill::Prefill ::ring_cap_for (small ); 6560const int64_t budget = std::min (xcache .slots ()- 128 ,kAutoLendPct * xcache .slots () /100 ); 6561// The room is a BYTE budget. A ring slot is max_blob bytes (`carve` lays out one whole blob each), 6562// while these cache slots hold their own layer's blob, which is smaller than max_blob unless the cache 6563// happens to hold the pack's biggest layer - on the 4-way IQ3_S rig that is 2.15 MiB a slot against a 6564// 2.54 MiB max_blob. Counting the room in slots priced the ring at 0.85x what it costs, `fits` then 6565// rejected the whole chunk instead of shrinking the ring, and the scan stopped a step short: measured 6566// against chunk 6144/ring 199, 8192 was refused where the same bytes afford a ~87-slot ring. 6567const int64_t blob = (int64_t ) strata::kernels::cpu::expert_layout ().max_blob ; 6568const uint64_t avail = bytes_from_slots (budget ); 6569auto room_of = [& ](int64_t t )-> int64_t { 6570const uint64_t nonring = strata::prefill::Prefill ::bytes_needed_no_ring (g ,ss ,t ); 6571return std::min ((int64_t ) ((avail - std::min (avail ,nonring )) / (uint64_t )blob ),ring_max ); 6572 }; 6573// `room_of` is capped at ring_max, so "the ring is full" is exactly room == ring_max, and both that 6574// test and the ones below it only get harder as t grows - the bisection stays valid. 6575auto scan = [& ](int64_t floor )-> int64_t { 6576return biggest_chunk (auto_ceiling , [& ](int64_t t )-> bool { 6577const int64_t room = room_of (t ); 6578if (room < floor )return false; 6579 strata::prefill::Prefill ::set_ring_budget ((int )room ,0 ); 6580// ring_slots() now returns `room` - unless STRATA_PREFILL_RING overrides it, in which case the 6581// chunk has to fit THAT ring, which is the pre-fix rule and the A/B arm 6582const int64_t k = slots_for (t ); 6583return k + 128 <=xcache .slots ()&& k * 100 <=kAutoLendPct * xcache .slots (); 6584 }); 6585 }; 6586int64_t c = scan (ring_max ); 6587if (c == 0 && ring_max < strata::prefill::Prefill ::ring_default_slots ())c = scan (kRingMin ); 6588// a prompt that fits 0.1.39's chunk keeps 0.1.39's ring (one chunk: the smaller ring only slowed it) 6589if (small >=c ) {// the scan bought nothing: 0.1.39's choice 6590 strata::prefill::Prefill ::set_ring_budget (0 ,0 ); 6591if (small > 0 ) {chunk = small ;return slots_for (small ); } 6592return 0 ; 6593 } 6594 strata::prefill::Prefill ::set_ring_budget ((int )room_of (c ),small ); 6595chunk = c ; 6596return slots_for (c ); 6597 } 6598for (int64_t c = chunk ;c >=256 ;c /=2 ) { 6599const int64_t k = slots_for (c ); 6600if (k + 128 <=xcache .slots ()) {chunk = c ;return k ; } 6601 } 6602return 0 ; 6603 }; 6604// ---- THE ELASTIC K/V (--kv-grow; vmm.hpp). Allocated for the whole --max-context up front, the K/V of a 262K 6605// context (3.35 GiB with the drafter's at int8) takes VRAM the expert cache could hold more experts in. Now the K/V pools hold physical memory only for the cells 6606// the requests reach. When a request needs more, slots just below the prompt path's loan give up their experts 6607// (the CPU computes those from RAM, like any miss) and their whole chunks are mapped into the K/V; a later short 6608// request hands them back and the slots are refilled with the profile's hottest experts. Neither side's 6609// addresses move, so every captured graph stays valid. The context is never smaller: --max-context cells always 6610// fit, the cache simply holds fewer experts while a long one is live. 6611struct KvGrow { 6612bool on = false; 6613int64_t top = 0 ,lo = 0 ;// slots [lo, top) hold no expert; their whole chunks may be with the K/V 6614int64_t floor = 128 ;// the cache keeps at least these slots 6615int64_t step = 8192 ;// the K/V grows in whole steps of cells 6616int64_t cells = 0 ;// what every K/V pool holds now 6617 std::vector < strata::core::VmmChunk > spare ;// out of the cache, not (yet) in the K/V 6618int64_t grows = 0 ,trims = 0 ,fresh = 0 ,evicted = 0 ,refilled = 0 ; 6619 }kvg ; 6620auto kvg_start = [& ](int64_t top ) { 6621kvg .on = strata::core::qsa_kv_elastic ()&& xcache .vmm_range ()!= nullptr && d_res != nullptr && 6622 !host_res .empty ()&& srcp != nullptr && top > kvg .floor ; 6623if (!kvg .on )return ; 6624kvg .top = kvg .lo = top ; 6625kvg .cells = strata::core::qsa_kv_elastic_cells (); 6626if (const char * v = std::getenv ("STRATA_KV_GROW_STEP" );v != nullptr && std::atoll (v )> 0 )kvg .step = std::atoll (v ); 6627// tests: the cache keeps this many slots (its size: the K/V grows into new VRAM only) 6628if (const char * v = std::getenv ("STRATA_KV_GROW_FLOOR" );v != nullptr && std::atoll (v )> 0 )kvg .floor = std::atoll (v ); 6629 std::fprintf (stderr ,"strata generate: elastic K/V: %lld of %lld cells in VRAM (%.2f of %.2f GiB); the expert " 6630"cache (%lld slots) gives the K/V room below slot %lld as the context grows\n" , 6631 (long long )kvg .cells , (long long )o .max_context , 6632 (double ) strata::core::qsa_kv_elastic_mapped_bytes () /1073741824.0 , 6633 (double ) strata::core::qsa_kv_elastic_full_bytes () /1073741824.0 , (long long )xcache .slots (), 6634 (long long )top ); 6635 }; 6636// Room for `cells` cells (rounded up to a step). `quiesce` must leave nothing running on the device and land 6637// the adaptive tier's swaps (a swap in flight could still be writing a slot given up here). 6638auto kvg_ensure = [& ](int64_t cells ,const std::function < void ()>& quiesce )-> bool { 6639if (!kvg .on || cells <=kvg .cells )return true; 6640const int64_t target = std::min < int64_t > (o .max_context , (cells + kvg .step - 1 ) /kvg .step * kvg .step ); 6641const int64_t need = strata::core::qsa_kv_elastic_need (target ); 6642if (need == 0 ) {kvg .cells = strata::core::qsa_kv_elastic_cells ();return true; } 6643quiesce (); 6644 strata::core::VmmRange & r = * xcache .vmm_range (); 6645const uint64_t G = strata::core::vmm_granularity (); 6646 std::vector < int32_t > owner ;// slot -> residency index 6647// The slots given up are the ones just below the prompt path's loan, and the loan is most of the cache: they 6648// hold experts of middling heat. So an expert there that is hotter than the coldest one in the loan region 6649// moves into that one's slot (a device copy), and the coldest is given up instead - the cache then holds what 6650// a smaller cache would. Heat: the adaptive tier's routing counts, then the profile's rank. 6651 std::vector < int32_t > rank ; 6652 std::vector < std::pair < float ,int32_t >> cold ;// the loan region's residents, hottest first 6653auto heat = [& ](int32_t i )-> float { 6654const float u = drive .d .usage .empty () ?0.0f :drive .d .usage [(size_t )i ]; 6655return u * 1048576.0f - (float )rank [(size_t )i ]; 6656 }; 6657const auto & lay = strata::kernels::cpu::expert_layout (); 6658int64_t gave = 0 ,moved = 0 ; 6659auto freeable = [& ]()-> int64_t {// mapped chunks wholly inside [lo, top): a chunk a live slot shares stays 6660const int64_t c0 = (int64_t ) ((xcache .slot_offset (kvg .lo )+ G - 1 ) /G ); 6661const int64_t c1 = (int64_t ) (xcache .slot_offset (kvg .top ) /G ); 6662int64_t k = 0 ; 6663for (int64_t c = c0 ;c < c1 ;++ c )k += r .mapped (c ) ?1 :0 ; 6664return k ; 6665 }; 6666while ((int64_t )kvg .spare .size ()+ freeable ()< need && kvg .lo > kvg .floor ) { 6667if (owner .empty ()) { 6668owner .assign ((size_t )xcache .slots (),-1 ); 6669for (size_t i = 0 ;i < host_res .size ();++ i ) 6670if (host_res [i ] >=0 && host_res [i ]< xcache .slots ())owner [(size_t )host_res [i ]]= (int32_t )i ; 6671rank .assign (host_res .size (), (int32_t )profile .size ()); 6672for (size_t r = 0 ;r < profile .size ();++ r ) 6673rank [(size_t )profile [r ].first * (size_t )g .n_expert + (size_t )profile [r ].second ]= (int32_t )r ; 6674for (size_t i = 0 ;i < host_res .size ();++ i ) 6675if (host_res [i ] >=kvg .top )cold .emplace_back (heat ((int32_t )i ), (int32_t )i ); 6676 std::sort (cold .begin (),cold .end (), [](const auto & a ,const auto & b ) {return a .first > b .first ; }); 6677 } 6678-- kvg .lo ; 6679++ gave ; 6680if (const int32_t oi = owner [(size_t )kvg .lo ];oi >=0 ) { 6681const int64_t layer = oi /g .n_expert ; 6682int32_t vi = -1 ; 6683if (!cold .empty ()&& cold .back ().first < heat (oi )) { 6684vi = cold .back ().second ; 6685const int32_t vs = host_res [(size_t )vi ]; 6686if (xcache .slot_offset (vs + 1 )- xcache .slot_offset (vs )< 6687lay .blob_bytes (layer )|| 6688DPCT_CHECK_ERROR (dpct::get_in_order_queue ().memcpy ( 6689xcache .device_slot (vs ), 6690xcache .device_slot ((int32_t )kvg .lo ), 6691 (size_t )lay .blob_bytes (layer )).wait ())!= 0 ) 6692vi = -1 ; 6693else { 6694cold .pop_back (); 6695host_res [(size_t )oi ]= vs ; 6696host_res [(size_t )vi ]= strata::core::kNotResident ; 6697++ moved ; 6698 } 6699 } 6700if (vi < 0 )host_res [(size_t )oi ]= strata::core::kNotResident ; 6701++ kvg .evicted ; 6702 } 6703 } 6704// a device-to-device cudaMemcpy does not wait for the copy: the moves still read the slots given up, and a 6705// chunk unmapped under a copy faults it (the error then sticks to whatever runs next) 6706if (gave > 0 && 6707DPCT_CHECK_ERROR ( 6708 dpct::get_current_device ().queues_wait_and_throw ())!= 0 ) { 6709/* 6710DPCT1009: SYCL reports errors using exceptions and does not use 6711error codes. Please replace the "get_error_string_dummy(...)" with a 6712real error-handling function. 6713*/ 6714/* 6715DPCT1010: SYCL uses exceptions to report errors and does not 6716use the error codes. The cudaGetLastError function call was replaced 6717with 0. You need to rewrite this code. 6718*/ 6719 std::fprintf (stderr , 6720"strata: moving experts for the K/V failed: %s\n" , 6721 dpct::get_error_string_dummy (0 )); 6722return false; 6723 } 6724 { 6725const int64_t c0 = (int64_t ) ((xcache .slot_offset (kvg .lo )+ G - 1 ) /G ); 6726const int64_t c1 = (int64_t ) (xcache .slot_offset (kvg .top ) /G ); 6727for (int64_t c = c0 ;c < c1 ;++ c ) 6728if (r .mapped (c )) 6729if (const strata::core::VmmChunk h = r .unmap (c ))kvg .spare .push_back (h ); 6730 } 6731if (gave > 0 && 6732/* 6733DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 6734assuming in the original code the source host memory is pageable 6735memory. If the memory is not pageable, call wait() on event return 6736by memcpy API to ensure synchronization behavior. 6737*/ 6738DPCT_CHECK_ERROR (dpct::get_in_order_queue ().memcpy ( 6739d_res ,host_res .data (),host_res .size ()* sizeof (int32_t )).wait ())!= 67400 ) { 6741/* 6742DPCT1009: SYCL reports errors using exceptions and does not use 6743error codes. Please replace the "get_error_string_dummy(...)" with a 6744real error-handling function. 6745*/ 6746/* 6747DPCT1010: SYCL uses exceptions to report errors and does not 6748use the error codes. The cudaGetLastError function call was replaced 6749with 0. You need to rewrite this code. 6750*/ 6751 std::fprintf (stderr , 6752"strata: the residency table upload failed: %s\n" , 6753 dpct::get_error_string_dummy (0 )); 6754return false; 6755 } 6756int64_t fresh = 0 ; 6757const bool ok = strata::core::qsa_kv_elastic_grow (target , [& ]()-> strata::core::VmmChunk { 6758if (kvg .spare .empty ()) {++ fresh ;return 0 ; }// the cache is at its floor: new memory 6759const strata::core::VmmChunk h = kvg .spare .back (); 6760kvg .spare .pop_back (); 6761return h ; 6762 }); 6763kvg .fresh += fresh ; 6764kvg .cells = strata::core::qsa_kv_elastic_cells (); 6765++ kvg .grows ; 6766 std::fprintf (stderr ,"strata: K/V grown to %lld cells (%.2f GiB); the expert cache gave %lld slots for it, " 6767"%lld hotter experts moved to colder ones' slots (%lld of %lld slots hold experts)%s\n" , 6768 (long long )kvg .cells , (double ) strata::core::qsa_kv_elastic_mapped_bytes () /1073741824.0 , 6769 (long long )gave , (long long )moved , (long long ) (kvg .lo + (xcache .slots ()- kvg .top )), 6770 (long long )xcache .slots (), 6771fresh > 0 ?" - and new VRAM, the cache being at its floor" :"" ); 6772if (!ok ) 6773 std::fprintf ( 6774stderr ,"strata: the K/V could not grow to %lld cells (%s)\n" , 6775 (long long )target , 6776/* 6777DPCT1009: SYCL reports errors using exceptions and does not 6778use error codes. Please replace the 6779"get_error_string_dummy(...)" with a real error-handling 6780function. 6781*/ 6782/* 6783DPCT1010: SYCL uses exceptions to report errors and does 6784not use the error codes. The cudaGetLastError function call was 6785replaced with 0. You need to rewrite this code. 6786*/ 6787 dpct::get_error_string_dummy (0 )); 6788return ok ; 6789 }; 6790// A request that needs far fewer cells than the K/V holds gives the rest back: the slots refill with the 6791// profile's hottest experts the GPU does not hold. Run on a quiet device (as kvg_ensure's `quiesce`). 6792auto kvg_trim = [& ](int64_t cells )-> bool { 6793if (!kvg .on )return true; 6794const int64_t target = std::max < int64_t > (kvg .step , (cells + kvg .step - 1 ) /kvg .step * kvg .step ); 6795if (kvg .cells < target + 2 * kvg .step || kvg .lo >=kvg .top )return true; 6796 strata::core::qsa_kv_elastic_shrink (target , [& ](strata::core::VmmChunk h ) {kvg .spare .push_back (h ); }); 6797kvg .cells = strata::core::qsa_kv_elastic_cells (); 6798 strata::core::VmmRange & r = * xcache .vmm_range (); 6799const uint64_t G = strata::core::vmm_granularity (); 6800const int64_t c1 = (int64_t ) (xcache .slot_offset (kvg .top ) /G ); 6801 {// one run from the lowest unmapped chunk, as long as the chunks handed back last (one access call) 6802const int64_t c0 = (int64_t ) (xcache .slot_offset (kvg .lo ) /G ); 6803int64_t cend = c0 ,need = (int64_t )kvg .spare .size (); 6804while (cend < c1 && need > 0 )need -= r .mapped (cend ++ ) ?0 :1 ; 6805if (!r .map_range (c0 ,cend , [& ]()-> strata::core::VmmChunk { 6806if (kvg .spare .empty ())return 0 ; 6807const strata::core::VmmChunk h = kvg .spare .back (); 6808kvg .spare .pop_back (); 6809return h ; 6810 })) 6811 std::fprintf (stderr ,"strata: the expert cache could not take its VRAM back from the K/V\n" ); 6812 } 6813const int64_t lo0 = kvg .lo ; 6814while (kvg .lo < kvg .top ) {// a slot whose chunks are all mapped again holds an expert again 6815const int64_t a = (int64_t ) (xcache .slot_offset (kvg .lo ) /G ); 6816const int64_t b = (int64_t ) ((xcache .slot_offset (kvg .lo + 1 )+ G - 1 ) /G ); 6817bool all = true; 6818for (int64_t c = a ;c < b && all ;++ c )all = r .mapped (c ); 6819if (!all )break ; 6820++ kvg .lo ; 6821 } 6822// the refills on one stream and one sync (a blocking copy each was a driver round trip per expert) 6823const auto & lay = strata::kernels::cpu::expert_layout (); 6824 std::vector < std::pair < size_t ,int32_t >> filled ;// (residency index, slot), resident once the copies landed 6825size_t pi = 0 ; 6826for (int64_t s = lo0 ;s < kvg .lo ;++ s ) { 6827const uint64_t room = xcache .slot_offset (s + 1 )- xcache .slot_offset (s ); 6828for (;pi < profile .size ();++ pi ) { 6829const int32_t l = profile [pi ].first ,e = profile [pi ].second ; 6830const size_t i = (size_t )l * (size_t )g .n_expert + (size_t )e ; 6831if (host_res [i ] >=0 || lay .blob_bytes (l )> room )continue ; 6832const uint8_t * b = srcp -> blob (l ,e ); 6833if (b == nullptr )continue ; 6834/* 6835DPCT1124: cudaMemcpyAsync is migrated to asynchronous 6836memcpy API. While the origin API might be synchronous, it 6837depends on the type of operand memory, so you may need to call 6838wait() on event return by memcpy API to ensure synchronization 6839behavior. 6840*/ 6841 dpct::get_in_order_queue ().memcpy ( 6842xcache .device_slot ((int32_t )s ),b , 6843 (size_t )lay .blob_bytes (l )).wait (); 6844filled .emplace_back (i , (int32_t )s ); 6845++ pi ; 6846break ; 6847 } 6848 } 6849if (DPCT_CHECK_ERROR ( 6850 dpct::get_current_device ().queues_wait_and_throw ())!= 0 ) { 6851/* 6852DPCT1009: SYCL reports errors using exceptions and does not use 6853error codes. Please replace the "get_error_string_dummy(...)" with a 6854real error-handling function. 6855*/ 6856/* 6857DPCT1010: SYCL uses exceptions to report errors and does not 6858use the error codes. The cudaGetLastError function call was replaced 6859with 0. You need to rewrite this code. 6860*/ 6861 std::fprintf (stderr , 6862"strata: refilling the expert cache failed: %s\n" , 6863 dpct::get_error_string_dummy (0 )); 6864return false; 6865 } 6866for (const auto & [i ,s ] :filled )host_res [i ]= s ; 6867kvg .refilled += (int64_t )filled .size (); 6868/* 6869DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 6870assuming in the original code the source host memory is pageable memory. 6871If the memory is not pageable, call wait() on event return by memcpy API 6872to ensure synchronization behavior. 6873*/ 6874if (DPCT_CHECK_ERROR (dpct::get_in_order_queue ().memcpy ( 6875d_res ,host_res .data (),host_res .size ()* sizeof (int32_t )).wait ())!= 68760 ) 6877return false; 6878for (const strata::core::VmmChunk h :kvg .spare ) strata::core::vmm_chunk_free (h );// new ones, if any 6879kvg .spare .clear (); 6880++ kvg .trims ; 6881 std::fprintf (stderr ,"strata: K/V trimmed to %lld cells; %lld slots back to the expert cache, refilled from " 6882"the profile\n" , (long long )kvg .cells , (long long ) (kvg .lo - lo0 )); 6883return true; 6884 }; 6885// ---- the resident RAM mode (--resident-experts / --resident-cpu-experts): the experts the GPU cache does not 6886// hold are copied from experts.bin into RAM once, so no decode or prompt step reads the file (the plain mmap 6887// mode reads them through the OS file cache, which a small-RAM PC keeps giving back to the SSD). Built here, 6888// after the prompt path's lend plan is known: the slots it may lend (the cache's last ones) have their experts 6889// streamed during a prompt and copied back after it, so those are kept in RAM too as far as RAM allows. The 6890// bytes are the file's bytes and the placement is the same, so the answers are the plain mmap mode's; the 6891// share-of-pinned figure above (which sizes the prompt path) is left as the mmap mode's for the same reason. 6892// --adapt-async (opt-in): where the asynchronous adaptive tier does not apply, the blocking tier runs, said once. 6893// It exchanges experts between the GPU caches and the resident RAM copy only (the copy is checked once it is 6894// built, below). Not beside the --batch slots (their windows run between a request's prompt chunks), a peer 6895// tier or the helper GPUs' tier, which pick their swaps from the same table. (A pipelined decode loop that 6896// adapts beside windows in flight needs the blocking tier too: such a mode belongs on this list.) 6897auto adapt_async_off = [& ](const char * why ) { 6898 std::fprintf (stderr ,"strata generate: --adapt-async 1 is off (%s): the blocking adaptive tier\n" ,why ); 6899o .adapt_async = 0 ; 6900 }; 6901if (o .adapt_async ) { 6902const char * why = !o .serve ?"it needs --serve" 6903 :o .adapt_every <=0 || o .adapt_swaps <=0 ?"the adaptive tier is off" 6904 : !o .resident_cpu_experts ?"it needs the resident RAM mode, --resident-experts" 6905 :o .batch > 0 ?"not with --batch slots" 6906 :o .pipeline_windows > 0 ?"not with --pipeline-windows (its windows are in flight while the tier adapts)" 6907 :peer .valid () ?"not with --peer-device" 6908 :remote_opt ?"not with --remote-expert-opt" 6909 :nullptr ; 6910if (why != nullptr )adapt_async_off (why ); 6911 } 6912if (o .resident_cpu_experts ) { 6913int64_t lend_from = -1 ; 6914if (o .prefill_chunk > 0 && !o .no_prefill_borrow && d_res != nullptr && xcache .slots ()> 0 ) { 6915int64_t chunk = o .prefill_chunk ; 6916const int64_t k = plan_lend (chunk ); 6917if (k > 0 )lend_from = xcache .slots ()- k ; 6918 } 6919// a layer split: the experts every later stage's cache holds are left out of the RAM copy, as CUDA0's are 6920// (with them the copy keeps no lend region: pin_cache_complement turns the loan off) 6921 std::vector < std::pair < int32_t ,int32_t >> stage_pairs ; 6922for (auto & st :stages ) 6923for (int64_t l = st -> lb ;l < st -> le ;++ l ) 6924for (int64_t e = 0 ;e < g .n_expert ;++ e ) 6925if (st -> cache .slot_of (l ,e ) >=0 )stage_pairs .emplace_back ((int32_t )l , (int32_t )e ); 6926const std::vector < std::pair < int32_t ,int32_t >>& rank_all = profile_all .empty () ?profile :profile_all ; 6927bool resident_ok = src .pin_cache_complement (xcache ,err ,o .resident_pin ,stage_pairs ,lend_from , 6928o .resident_headroom ,o .resident_budget ,& rank_all ); 6929 std::string whole_err ; 6930if (!resident_ok && o .resident_soft ) { 6931// #467: the whole complement does not fit - keep what does, the hottest by the profile, through the #403 6932// budget path (sized by available memory) instead of none: the misses outside it read the same file bytes 6933// the mmap fallback reads, so the answers are unchanged. Nothing pinned: the old fallback below. 6934whole_err = err ; 6935resident_ok = src .pin_cache_complement (xcache ,err ,o .resident_pin ,stage_pairs ,-1 ,o .resident_headroom , 6936 strata::core::FileExpertSource ::kResidentWhatFits ,& rank_all ); 6937if (resident_ok ) 6938 std::fprintf (stderr ,"strata generate: WARNING: the whole resident RAM mode does not fit (%s); %.2f " 6939"GiB of the experts the GPU does not hold, the hottest by the expert profile, are " 6940"kept in RAM and the rest are read from the model folder through the OS file " 6941"cache\n" , 6942whole_err .c_str (), (double )src .resident_bytes () /1073741824.0 ); 6943else 6944err = whole_err + "; " + err ; 6945 } 6946if (resident_ok ) { 6947// --adapt-async: twice the exchange buffers - the second half bounces the copies in whose source is not 6948// page-locked (an asynchronous copy instead of the driver's staged, synchronous one) 6949if (o .adapt_async && !src .reserve_exchanges (2 * std::min < int64_t > (o .adapt_swaps ,96 ),err )) 6950adapt_async_off (err .c_str ()); 6951// pageable buffers would make every copy of a round synchronous (the driver stages them): that is the 6952// blocking tier's cost, so the asynchronous tier is not worth running - said, and the blocking tier stays 6953if (o .adapt_async && !src .exchange_pinned ()) 6954adapt_async_off ("the exchange buffers could not be page-locked" ); 6955if (o .adapt_every > 0 && o .adapt_swaps > 0 && 6956 !src .reserve_exchanges (std::min < int64_t > (o .adapt_swaps ,96 ),err )) { 6957 std::fprintf (stderr ,"strata generate: CPU expert residency: %s\n" ,err .c_str ()); 6958return 1 ; 6959 } 6960 std::fprintf (stderr ,"strata generate: resident RAM mode: %.2f GiB of experts in RAM (%s), %lld in the GPU " 6961"cache; adaptive swaps %s\n" , 6962 (double )src .resident_bytes () /1073741824.0 , 6963src .complement_pinned () ?"page-locked" :src .locked_bytes ()> 0 ?"locked" :"pageable" , 6964 (long long )xcache .resident (), 6965o .adapt_every > 0 && o .adapt_swaps > 0 ?"exchange them with the GPU cache (no file reads)" 6966 :"off" ); 6967 }else if (o .resident_soft ) { 6968 std::fprintf (stderr ,"strata generate: WARNING: the resident RAM mode does not fit (%s); the experts the " 6969"GPU does not hold are read from the model folder through the OS file cache " 6970"(--mmap-experts), which is slower when the RAM cannot keep them\n" ,err .c_str ()); 6971 }else if (o .resident_budget > 0 ) { 6972// #403: a RAM budget that cannot be kept is not a reason to stop - the experts it would have held are 6973// read from the files like the ones outside it (pin_cache_complement leaves nothing half-built) 6974 std::fprintf (stderr ,"strata generate: WARNING: the RAM budget (--resident-budget-gib) cannot be kept (%s); " 6975"every expert the GPU does not hold is read from the model files %s " 6976"(--mmap-experts), which is slower\n" ,err .c_str (), 6977src .unbuffered () ?"with unbuffered I/O" :"through the OS file cache" ); 6978 }else { 6979 std::fprintf (stderr ,"strata generate: CPU expert residency: %s\n" ,err .c_str ()); 6980return 1 ; 6981 } 6982// #577: the unbuffered choice above was made before the RAM copy existed, from the budget asked for; now the 6983// copy is built, decide again from the RAM it really holds and the expert bytes outside it (on a 96 GB PC 6984// the file cache keeps those, and every refill after a prompt read the drive instead). Windows and Linux: the 6985// unbuffered reads exist there 6986#if defined(_WIN32 )|| defined(__linux__ ) 6987if (o .mmap_experts && o .resident_budget > 0 ) { 6988 std::string why ; 6989const bool was = src .unbuffered (); 6990const bool ub = src .recheck_unbuffered (why ); 6991 std::fprintf (stderr ,"strata generate: the file tier reads %s%s (%s)\n" , 6992ub ?"unbuffered" :"through the file cache" ,ub == was ?"" :" (changed)" ,why .c_str ()); 6993 } 6994#endif 6995 } 6996if (o .adapt_async && !src .complement_ready ())adapt_async_off ("the resident RAM mode is not running" ); 6997if (o .serve ) { 6998if (o .spec < 2 || o .prefill_chunk <=0 || 6999 (graph_hits && (thits .d_res == nullptr || host_res .empty ()))) { 7000 std::fprintf (stderr ,"strata serve: needs --spec T and --prefill CHUNK (and a fillable " 7001"--expert-cache; the graphed hit path additionally needs --expert-profile P)\n" ); 7002return 2 ; 7003 } 7004// STRATA_VOLTA_BUILD backport (see docs/ and ninfer-flash-next-v100-backport): --mtp is optional here, 7005// mirroring the plain `generate` command's own use_mtp handling below. Without it, drafting falls back 7006// to the suffix/prompt-lookup drafter (DraftPolicy still picks Lookup vs plain per round) or, when 7007// neither fires, plain one-token-per-round decoding - slower, never wrong: the verify window still 7008// confirms every emitted token against the real model regardless of where the draft came from. 7009const bool use_mtp = !o .mtp .empty (); 7010 strata::prefill::Prefill sp ; 7011void * borrow = nullptr ; 7012uint64_t borrow_bytes = 0 ; 7013int32_t lend_first = -1 ;// the first slot the prompt path may borrow (its largest chunk) 7014// ---- WHO BORROWS, AND FROM WHOSE CACHE. One entry per prompt path: CUDA0's (layers [0, split_at[0]), 7015// which is the whole model without a split) borrowing the tail of CUDA0's cache, then one per stage 7016// borrowing the tail of ITS OWN cache. A loan is sized by the exact `Prefill::bytes_needed` for the 7017// chunk, is laid out by `Prefill::relayout`, and is refilled before any window reads - so outside the 7018// prompt the whole cache is expert cache. THIS IS THE POINT OF THE STRUCT: the loan used to exist only 7019// for CUDA0, and `no_prefill_borrow` made every stage instead withhold a chunk-sized reserve from its 7020// cache for the entire session, which is what cost the 4-way its context (see the note at the top of the 7021// layer-split block). A stage may only lend the rows for ITS OWN layers: `host_res` is one table whose 7022// slot values are indices into whichever cache owns the layer, so a loan that marked rows by slot number 7023// alone would hand CUDA0 a slot belonging to another stage's cache. 7024struct PfPart { 7025 strata::core::ExpertCache * cache = nullptr ; 7026const strata::core::SessionState * ses = nullptr ; 7027 strata::prefill::Prefill * sp = nullptr ; 7028int dev = -1 ;// -1: leave the device alone (CUDA0) 7029int64_t lb = 0 ,le = 0 ;// the layers whose rows this cache holds - the only rows it may lend 7030int32_t first = -1 ;// the first slot it may lend, for the chunk that was chosen 7031int32_t first_now = -1 ;// where its buffers are laid out now 7032int64_t lent_chunk = 0 ; 7033 std::vector < std::pair < int32_t ,int32_t >> lent ; 7034 }; 7035// bytes -> slots for one cache: exact when it knows its per-slot offsets (a native pack's blobs differ 7036// per layer), otherwise max_blob each. 7037auto cache_slots_for = [& ](const strata::core::ExpertCache & xc ,uint64_t need )-> int64_t { 7038if (xc .slot_offsets ()!= nullptr ) {// sized slots: from the end until they hold `need` 7039int64_t k = 0 ; 7040while (k < xc .slots ()&& 7041 (uint64_t ) (xc .bytes ()- (int64_t )xc .slot_offsets ()[xc .slots ()- k ])< need )++ k ; 7042return k ; 7043 } 7044const int64_t blob = (int64_t ) strata::kernels::cpu::expert_layout ().max_blob ; 7045return (int64_t ) ((need + (uint64_t )blob - 1 ) / (uint64_t )blob ); 7046 }; 7047auto part_slots = [& ](const PfPart & p ,int64_t c )-> int64_t { 7048return cache_slots_for (* p .cache , strata::prefill::Prefill ::bytes_needed (g ,* p .ses ,c )); 7049 }; 7050auto part_bytes = [& ](const PfPart & p ,int32_t first )-> uint64_t { 7051 strata::core::ExpertCache & xc = * p .cache ; 7052return xc .slot_offsets () ? (uint64_t ) (xc .bytes ()- (int64_t )xc .slot_offsets ()[first ]) 7053 : (uint64_t ) (xc .slots ()- first )* 7054 (uint64_t ) strata::kernels::cpu::expert_layout ().max_blob ; 7055 }; 7056// #340: a layer split whose caches already hold most experts streams few of them through the prompt path, so 7057// the 384-slot ring (sized for a card that streams nearly every expert of a chunk) only makes every stage's 7058// loan bigger: 96 slots (0.1.30's ring here) when >= 75% of the (layer, expert) pairs are resident. One GPU 7059// keeps the pinned-share rule. STRATA_SPLIT_RING=N: N slots on a split; 0: the pinned-share rule. 7060if (multi_gpu && !host_res .empty ()) { 7061int64_t res_n = 0 ; 7062for (const int32_t r :host_res )res_n += r >=0 ; 7063const double res_share = (double )res_n / (double )host_res .size (); 7064const char * v = std::getenv ("STRATA_SPLIT_RING" ); 7065const int ring = v ? std::atoi (v ) : (res_share >=0.75 ?96 :0 ); 7066if (ring > 0 ) { 7067 strata::prefill::Prefill ::set_ring_override (ring ); 7068 std::fprintf (stderr ,"strata serve: layer split: %.0f%% of the experts resident, the prompt path's " 7069"streamed ring %d slots\n" ,100.0 * res_share ,ring ); 7070 } 7071 } 7072 std::vector < PfPart > pf_parts ; 7073// a cache too small to lend the prompt path its buffers would make it allocate them on top - on a card 7074// whose cache already filled its reserve, that is the over-subscription the auto sizing avoids - so the 7075// chunk is the largest one EVERY participant can lend (a smaller chunk only reads slower) 7076if (pf_borrow && d_res != nullptr ) { 7077pf_parts .push_back ({& xcache ,& ss ,& sp ,-1 ,0 ,multi_gpu ?split_at [0 ] :g .n_layers ,-1 ,-1 ,0 , {}}); 7078for (auto & st :stages ) 7079pf_parts .push_back ({& st -> cache ,& st -> ss ,& st -> sp ,st -> dev ,st -> lb ,st -> le ,-1 ,-1 ,0 , {}}); 7080// The two tests plan_lend makes for CUDA0 alone, one participant at a time: a loan must leave the 7081// 128-slot floor. The percentage cap is an AUTO-chunk rule and only the auto scan applies it - an 7082// explicit --prefill is the operator's number, and a loan of it only has to fit. With one participant 7083// (no split) this reduces to plan_lend exactly, so the single-GPU loan is unchanged from main. 7084auto fits_one = [& ](const PfPart & p ,int64_t c ,bool cap )-> bool { 7085const int64_t k = part_slots (p ,c ); 7086if (k <=0 || k + 128 > p .cache -> slots ())return false; 7087return !(cap && k * 100 > kAutoLendPct * p .cache -> slots ()); 7088 }; 7089// `only`: CUDA0's cache alone (#448: what one GPU would choose, for the log below); null: every one 7090auto fits = [& ](int64_t c ,bool cap ,const PfPart * only = nullptr )-> bool { 7091if (only != nullptr )return fits_one (* only ,c ,cap ); 7092for (const PfPart & p :pf_parts ) 7093if (!fits_one (p ,c ,cap ))return false; 7094return true; 7095 }; 7096// The chunk and the ring are one budget. The ring used to be a fixed 384 slots taken off the top 7097// before the chunk was considered: 506 MiB on a Q2_0 pack, where it was tuned, but 1,912 MiB on 7098// Q8_0, more than half an 8 GB card's cache - which is what kept that card at a 1024-token chunk. 7099// Size the chunk first and hand the ring what the smallest participant leaves over, up to the ring's 7100// byte budget - but hand it ALL of it, as in plan_lend: the ring is the better buy per byte (the 7101// measurements are there), so the chunk to take is the largest one that still leaves the ring full, 7102// not the largest one that leaves it anything at all. kRingMin is the fallback floor for a rig where 7103// no chunk can afford a full ring; ring_slots() returns STAGE at or below it, which turns streaming 7104// off. 7105constexpr int64_t kRingMin = 16 ; 7106// The room is a BYTE budget, as in plan_lend: a ring slot is max_blob bytes, but a cache slot holds 7107// its own layer's blob, which on this rig averages 0.85 of it. In slots the ring looked 18% cheaper 7108// than it is, and a chunk whose ring only fitted after that discount was refused outright - the scan 7109// stopped one step short while the chunk it did take had room to spare for the cap-sized ring. 7110const int64_t kBlob = (int64_t ) strata::kernels::cpu::expert_layout ().max_blob ; 7111auto ring_room = [& ](int64_t c ,const PfPart * only ,int64_t cap )-> int64_t { 7112int64_t room = cap ; 7113for (const PfPart & p :pf_parts ) { 7114if (only != nullptr && & p != only )continue ; 7115// clamped at 0: a cache under 128 slots has a negative lend budget, and `slots - budget` is 7116// then `slots`, which is off_[slots] - the end of the prefix sum, so that cache lends 0 bytes 7117// rather than reading one entry past its offsets 7118const int64_t budget = std::max < int64_t > (0 , std::min (p .cache -> slots ()- 128 , 7119kAutoLendPct * p .cache -> slots () /100 )); 7120const uint64_t avail = part_bytes (p , (int32_t ) (p .cache -> slots ()- budget )); 7121const uint64_t nonring = strata::prefill::Prefill ::bytes_needed_no_ring (g ,* p .ses ,c ); 7122room = std::min (room , (int64_t ) ((avail - std::min (avail ,nonring )) / (uint64_t )kBlob )); 7123 } 7124return room ; 7125 }; 7126// The largest chunk on the 256-token grid that `only` - or, with null, every stage - can lend with the 7127// ring still at its full byte budget (ring_room is capped at ring_max, so that is room == ring_max), 7128// under the operator's ceiling (auto_ceiling keeps a bare `auto` at 8192, #282). Failing that, the 7129// largest chunk whose ring clears kRingMin. 7130// 0.1.39's list with its ring: the chunk it would pick, and the size up to which a prompt keeps that ring 7131auto old_pick = [& ](const PfPart * only )-> int64_t { 7132 strata::prefill::Prefill ::set_ring_budget (0 ,0 ); 7133static constexpr int64_t kAutoChunks []= {32768 ,16384 ,8192 ,6144 ,4096 ,3072 ,2048 ,1024 ,512 ,256 }; 7134for (const int64_t c :kAutoChunks ) { 7135if (c > 8192 && (c > o .prefill_auto_max || c > o .max_context ))continue ;// #282, as plan_lend 7136if (fits (c , true,only ))return c ; 7137 } 7138return 0 ; 7139 }; 7140auto scan = [& ](const PfPart * only )-> int64_t { 7141if (!o .prefill_auto ) {// an explicit --prefill is the operator's number, and a loan of it only has to fit 7142for (int64_t c = o .prefill_chunk ;c >=256 ;c /=2 ) 7143if (fits (c , false,only ))return c ; 7144return 0 ; 7145 } 7146if (!strata::prefill::Prefill ::ring_bytes_enabled ())return old_pick (only );// STRATA_RING_BYTES=0 7147const int64_t small = old_pick (only ); 7148const int64_t cap = strata::prefill::Prefill ::ring_cap_for (small ); 7149auto probe = [& ](int64_t floor )-> int64_t { 7150return biggest_chunk (auto_ceiling , [& ](int64_t t )-> bool { 7151const int64_t room = ring_room (t ,only ,cap ); 7152if (room < floor )return false; 7153 strata::prefill::Prefill ::set_ring_budget ((int )room ,0 ); 7154// ring_slots() now returns `room` - unless STRATA_PREFILL_RING overrides it, in which 7155// case the chunk has to fit THAT ring, which is the pre-fix rule and the A/B arm 7156return fits (t , true,only ); 7157 }); 7158 }; 7159int64_t c = probe (cap ); 7160if (c == 0 && cap < strata::prefill::Prefill ::ring_default_slots ())c = probe (kRingMin ); 7161return std::max (c ,small );// never a smaller chunk than 0.1.39's 7162 }; 7163const int64_t chunk = scan (nullptr ); 7164// #448: a small card in a layer split caps every stage's chunk (an RTX 3080's 512-slot cache held a 7165// 32 GB card's split to 512 tokens: prompts 6.2x slower, decode the same). Named when it bites, so the 7166// regression is one log line: each stage that cannot fund the chunk CUDA0 alone would read in. 7167const int64_t alone = pf_parts .size ()> 1 ?scan (& pf_parts [0 ]) :chunk ; 7168// both scans left the ring override on their own last trial: put it back on the chunk that won, which 7169// is what `init` lays out and what the INFO line reports 7170if (chunk > 0 && o .prefill_auto && strata::prefill::Prefill ::ring_bytes_enabled ()) { 7171// a prompt that fits 0.1.39's chunk keeps 0.1.39's ring (one chunk: the smaller ring only slowed 7172// it); the byte-budget ring is for the chunks past it 7173const int64_t small = old_pick (nullptr ); 7174 strata::prefill::Prefill ::set_ring_budget ( 7175small >=chunk ?0 : (int )ring_room (chunk ,nullptr , strata::prefill::Prefill ::ring_cap_for (small )), 7176small ); 7177 } 7178if (chunk > 0 && alone > chunk ) { 7179for (size_t i = 1 ;i < pf_parts .size ();++ i ) { 7180const PfPart & p = pf_parts [i ]; 7181if (fits_one (p ,alone ,o .prefill_auto ))continue ; 7182const int dev = p .dev < 0 ?0 :p .dev ; 7183 dpct::device_info prop {}; 7184if (DPCT_CHECK_ERROR ( 7185 dpct::get_device (dev ).get_device_info (prop ))!= 0 ) { 7186/* 7187DPCT1010: SYCL uses exceptions to report errors and 7188does not use the error codes. The cudaGetLastError 7189function call was replaced with 0. You need to rewrite 7190this code. 7191*/ 7192 (void )0 ; 7193prop .get_name ()[0 ]= 0 ; 7194 } 7195const std::string pct = 7196o .prefill_auto ?", and lend at most " + std::to_string (kAutoLendPct )+ "%" :"" ; 7197 std::fprintf (stderr , 7198"strata serve: WARNING: prompt chunk %lld " 7199"tokens, not %lld: CUDA%d (%s) " 7200"has %lld expert-cache slots, and a " 7201"%lld-token chunk borrows %lld of them " 7202"(it must keep 128%s) - prompts read slower " 7203"than on CUDA0 alone (#448)\n" , 7204 (long long )chunk , (long long )alone ,dev , 7205prop .get_name (), (long long )p .cache -> slots (), 7206 (long long )alone , 7207 (long long )part_slots (p ,alone ),pct .c_str ()); 7208// the helper tiers start at CUDA1 without a split (and are enabled in order) 7209 std::fprintf (stderr ,"strata serve: a card this small can serve as a helper expert cache " 7210"instead of a split stage: without --layer-split, with %s " 7211"(docs/SECOND_GPU.md)\n" , 7212dev == 1 ?"--expert-cache-device1 N" :"--expert-cache-device1..3 N, in order" ); 7213 } 7214 } 7215if (chunk > 0 ) { 7216if (o .prefill_auto ) 7217// the RESOLVED ring, not the room offered: ring_slots() clamps to [16, RING_MAX] and a chunk 7218// under stream_all_min() gets STAGE, and STRATA_PREFILL_RING overrides both. This is what 7219// `init` lays out, and what the INFO line reports to the Monitor tab. 7220 std::fprintf (stderr ,"strata serve: prompt chunk auto: %lld tokens, a %lld-slot ring\n" , 7221 (long long )chunk , 7222 (long long ) strata::prefill::Prefill ::ring_slots_for (chunk )); 7223else if (chunk != o .prefill_chunk ) 7224 std::fprintf (stderr ,"strata serve: prompt chunk %lld -> %lld tokens so its buffers fit in " 7225"every expert cache\n" , (long long )o .prefill_chunk , (long long )chunk ); 7226o .prefill_chunk = chunk ; 7227for (PfPart & p :pf_parts ) { 7228p .first = (int32_t ) (p .cache -> slots ()- part_slots (p ,chunk )); 7229p .first_now = p .first ; 7230 } 7231// #340: a split stage whose card still has room for the chunk's buffers (its cache already holds 7232// every expert of its layers, so auto stopped short of its VRAM) keeps them as its own instead of 7233// borrowing cache slots: nothing of it is lent, streamed during the prompt or refilled after it. 7234// Room = the buffers + 1.5 GiB (the verify windows, the draft head, hipBLAS/cuBLAS workspaces made 7235// after this). Layer splits only - one GPU keeps its loan exactly as before. 7236// STRATA_SPLIT_OWN_BUFFERS=0: every stage borrows (0.1.30/0.1.31). 7237static const bool own_ok = [] { 7238const char * v = std::getenv ("STRATA_SPLIT_OWN_BUFFERS" ); 7239return v == nullptr || v [0 ]!= '0' ; 7240 }(); 7241if (pf_parts .size ()> 1 && own_ok ) { 7242for (PfPart & p :pf_parts ) { 7243const strata::core::OnDevice on (p .dev ); 7244size_t fb = 0 ,tb = 0 ; 7245/* 7246DPCT1010: SYCL uses exceptions to report errors and 7247does not use the error codes. The cudaGetLastError 7248function call was replaced with 0. You need to rewrite 7249this code. 7250*/ 7251/* 7252DPCT1106: 'cudaMemGetInfo' was migrated with the 7253Intel extensions for device information which may not be 7254supported by all compilers or runtimes. You may need to 7255adjust the code. 7256*/ 7257if (DPCT_CHECK_ERROR ( 7258 dpct::get_current_device ().get_memory_info ( 7259fb ,tb ))!= 0 ) { 7260 (void )0 ;continue ; 7261 } 7262const uint64_t need = strata::prefill::Prefill ::bytes_needed (g ,* p .ses ,chunk ); 7263if ((uint64_t )fb >=need + (3ull <<29 )) { 7264 std::fprintf (stderr ,"strata serve: CUDA%d keeps its own prompt buffers (%.2f GiB of " 7265"%.2f GiB free): no loan\n" ,p .dev < 0 ?0 :p .dev , 7266 (double )need /1073741824.0 , (double )fb /1073741824.0 ); 7267p .first = -1 ; 7268p .first_now = -1 ; 7269 } 7270 } 7271 } 7272lend_first = pf_parts [0 ].first ; 7273borrow = lend_first >=0 ?xcache .device_slot (lend_first ) :nullptr ; 7274borrow_bytes = lend_first >=0 ?part_bytes (pf_parts [0 ],lend_first ) :0 ; 7275 }else if (o .prefill_auto ) { 7276o .prefill_chunk = 1024 ;// nothing lendable: small buffers of its own 7277 }else if (pf_parts .size ()> 1 ) { 7278// An explicit chunk no stage can lend in full. main falls back to the prompt path's own buffers 7279// here and so do we, rather than refusing to start - but say what every stage has, because a split 7280// stage that has to allocate these on top of a cache that already filled its VRAM will not fit, 7281// and `init` would otherwise report only that the buffers do not fit. 7282 std::fprintf (stderr ,"strata serve: no stage can lend the prompt path its %lld-token buffers, so " 7283"each stage allocates its own:\n" , (long long )o .prefill_chunk ); 7284for (const PfPart & p :pf_parts ) 7285 std::fprintf (stderr ,"strata serve: CUDA%d has %lld slots, and a %lld-token chunk needs " 7286"the last %lld of them\n" ,p .dev < 0 ?0 :p .dev , 7287 (long long )p .cache -> slots (), (long long )o .prefill_chunk , 7288 (long long )part_slots (p ,o .prefill_chunk )); 7289 } 7290 }else if (o .prefill_auto && d_res == nullptr ) { 7291o .prefill_chunk = 1024 ;// #85: no expert cache at all (a full 8 GB card): small buffers of its own 7292 } 7293bool any_loan = borrow != nullptr ; 7294for (size_t i = 1 ;i < pf_parts .size ();++ i )any_loan = any_loan || pf_parts [i ].first >=0 ; 7295if (any_loan ) { 7296if (borrow != nullptr ) 7297 std::fprintf (stderr ,"strata serve: the prompt path borrows %lld CUDA0 cache slots (%.2f GiB)\n" , 7298 (long long ) (xcache .slots ()- lend_first ), (double )borrow_bytes /1073741824.0 ); 7299for (size_t i = 1 ;i < pf_parts .size ();++ i )// one loan per stage, from that stage's own cache 7300if (pf_parts [i ].first >=0 ) std::fprintf (stderr ,"strata serve: CUDA%d prompt path borrows %lld of its %lld slots (%.2f GiB)\n" , 7301pf_parts [i ].dev , (long long ) (pf_parts [i ].cache -> slots ()- pf_parts [i ].first ), 7302 (long long )pf_parts [i ].cache -> slots (), 7303 (double )part_bytes (pf_parts [i ],pf_parts [i ].first ) /1073741824.0 ); 7304 }else { 7305 std::fprintf (stderr ,"strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)\n" ); 7306 } 7307rss_probe ("the prompt path set up" ); 7308// layer split across GPUs: a prompt path per stage, each handing its chunk's rows to the next. 7309// THE CHUNK STEPS DOWN INSTEAD OF EXITING. A split's stage caches are sized after the arena is registered, and 7310// the prompt path's own buffers (no loan) are not priced into them: with the whole arena pinned (#253) a 7311// `--prefill auto` split could stop at start with "device buffers for a chunk of 2048 tokens do not fit". A 7312// chunk that does not fit is tried again one size smaller, down to 512 tokens (a smaller chunk only reads slower). 7313auto init_prompt_paths = [& ]()-> int {// 0: ready; 1: failed (err set); 2: failed with "do not fit" 7314for (size_t i = 0 ;i < stages .size ();++ i ) { 7315GpuStage & st = * stages [i ]; 7316st .sp .set_stage (st .lb ,i + 1 < stages .size () ?st .le :-1 ,i + 1 < stages .size () ?& stages [i + 1 ]-> sp :nullptr ); 7317const strata::core::OnDevice on (st .dev ); 7318void * sb = nullptr ;// this stage's own loan, out of its own cache 7319uint64_t sbb = 0 ; 7320// `first < 0`: no loan was taken (nothing was lendable), so this stage allocates its own buffers 7321if (i + 1 < pf_parts .size ()&& pf_parts [i + 1 ].first >=0 ) { 7322sb = st .cache .device_slot (pf_parts [i + 1 ].first ); 7323sbb = part_bytes (pf_parts [i + 1 ],pf_parts [i + 1 ].first ); 7324 } 7325if (!st .sp .init (st .wt ,g ,st .ss ,srcp ,& st .cache ,host_res .data (),o .prefill_chunk , (void * )st .stream , 7326err ,sb ,sbb )) { 7327err = "layer split, CUDA" + std::to_string (st .dev )+ " prompt path: " + err ; 7328return err .find ("do not fit" )!= std::string::npos ?2 :1 ; 7329 } 7330 } 7331if (multi_gpu )sp .set_stage (0 ,split_at [0 ],& stages [0 ]-> sp ); 7332if (!sp .init (wt ,g ,ss ,srcp ,& xcache ,host_res .data (),o .prefill_chunk ,main_cs ,err ,borrow ,borrow_bytes )) 7333return err .find ("do not fit" )!= std::string::npos ?2 :1 ; 7334return 0 ; 7335 }; 7336static constexpr int64_t kStepChunks []= {6144 ,4096 ,3072 ,2048 ,1536 ,1024 ,512 }; 7337 { 7338// First by arithmetic: a prompt path without a loan allocates its buffers, so the chunk must leave 7339// headroom on that device (a chunk that fits to the last MiB left hipBLAS nothing: its GEMMs then 7340// failed to launch on gfx1201 and the prompt hung). `bytes_needed` is the same count `init` makes. 7341const int64_t kHeadroom = 512ll <<20 ; 7342auto own_fits = [& ](int64_t c ,int & dev_out ,int64_t & need_out , 7343int64_t & free_out )-> bool { 7344try { 7345for (size_t i = 0 ;i <=stages .size ();++ i ) { 7346const bool loan = i == 0 ?borrow != nullptr : (i < pf_parts .size ()&& pf_parts [i ].first >= 0 ); 7347if (loan )continue ; 7348const int dev = i == 0 ?-1 :stages [i - 1 ]-> dev ; 7349const strata::core::OnDevice on (dev ); 7350size_t fb = 0 ,tb = 0 ; 7351/* 7352DPCT1106: 'cudaMemGetInfo' was migrated with the Intel 7353extensions for device information which may not be supported 7354by all compilers or runtimes. You may need to adjust the 7355code. 7356*/ 7357 dpct::get_current_device ().get_memory_info (fb ,tb ); 7358const int64_t need = (int64_t ) strata::prefill::Prefill ::bytes_needed (g ,i == 0 ?ss :stages [i - 1 ]-> ss ,c ); 7359if (need + kHeadroom > (int64_t )fb ) { 7360dev_out = dev < 0 ?0 :dev ;need_out = need ;free_out = (int64_t )fb ; 7361return false; 7362 } 7363 } 7364return true; 7365 } 7366catch (sycl::exception const & exc ) { 7367 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 7368 <<", line:" <<__LINE__ << std::endl ; 7369 std::exit (1 ); 7370 } 7371 }; 7372int dev = 0 ; 7373int64_t need = 0 ,fb = 0 ; 7374if (!own_fits (o .prefill_chunk ,dev ,need ,fb )) { 7375int64_t c = 0 ; 7376for (const int64_t s :kStepChunks ) { 7377int d2 = 0 ; 7378int64_t n2 = 0 ,f2 = 0 ; 7379if (s < o .prefill_chunk && own_fits (s ,d2 ,n2 ,f2 )) {c = s ;break ; } 7380 } 7381if (c > 0 ) { 7382 std::fprintf (stderr ,"strata serve: a %lld-token chunk's prompt buffers need %lld MiB on CUDA%d, " 7383"%lld MiB free: %lld-token chunks\n" , (long long )o .prefill_chunk , 7384 (long long ) (need >>20 ),dev , (long long ) (fb >>20 ), (long long )c ); 7385o .prefill_chunk = c ; 7386 } 7387 } 7388 } 7389for (;;) { 7390const int r = init_prompt_paths (); 7391if (r == 0 )break ; 7392int64_t next = 0 ; 7393for (const int64_t c :kStepChunks ) 7394if (c < o .prefill_chunk ) {next = c ;break ; } 7395if (r == 2 && next > 0 ) { 7396 std::fprintf (stderr ,"strata serve: %s: trying a %lld-token chunk\n" ,err .c_str (), (long long )next ); 7397// start the prompt paths over (a failed init may hold buffers), and consume the failed allocation's 7398// error: it is sticky, and the next launch check would report "out of memory" for a kernel 7399for (auto & stp :stages ) { 7400const strata::core::OnDevice on (stp -> dev ); 7401stp -> sp .reset (); 7402/* 7403DPCT1010: SYCL uses exceptions to report errors and 7404does not use the error codes. The cudaGetLastError function 7405call was replaced with 0. You need to rewrite this code. 7406*/ 7407 (void )0 ; 7408 } 7409sp .reset (); 7410/* 7411DPCT1010: SYCL uses exceptions to report errors and does 7412not use the error codes. The cudaGetLastError function call was 7413replaced with 0. You need to rewrite this code. 7414*/ 7415 (void )0 ; 7416o .prefill_chunk = next ; 7417if (any_loan ) {// smaller loans for the smaller chunk 7418for (PfPart & p :pf_parts ) 7419if (p .first >=0 ) { 7420p .first = (int32_t ) (p .cache -> slots ()- part_slots (p ,next )); 7421p .first_now = p .first ; 7422 } 7423lend_first = pf_parts [0 ].first ; 7424borrow = lend_first >=0 ?xcache .device_slot (lend_first ) :nullptr ; 7425borrow_bytes = lend_first >=0 ?part_bytes (pf_parts [0 ],lend_first ) :0 ; 7426 } 7427err .clear (); 7428continue ; 7429 } 7430 std::fprintf (stderr ,"strata serve: %s\n" ,err .c_str ()); 7431if (err .find ("fit" )!= std::string::npos )// #85: say what frees VRAM 7432 std::fprintf (stderr ,"strata serve: the GPU has too little free VRAM for the prompt path: turn images " 7433"off (setup: --vision no), close other programs using the GPU, use a shorter " 7434"context, or read prompts in smaller chunks (--prefill 512)\n" ); 7435return 1 ; 7436 } 7437if (peer .valid ()&& o .peer_prefill_rows != 0 ) { 7438const int64_t rows = o .peer_prefill_rows > 0 ?o .peer_prefill_rows :o .prefill_chunk * K /2 ; 7439if (!sp .set_peer (& peer ,rows ,err )) { 7440 std::fprintf (stderr ,"strata serve: %s - the prompt path stays on the primary GPU\n" ,err .c_str ()); 7441err .clear (); 7442 } 7443 } 7444// a layer split: a one-chunk prompt runs the stages one after the other, so each stage's prompt path gets the 7445// next stage's GPU (the last one the first's) to stream and compute a share of its experts meanwhile 7446if (multi_gpu && !stages .empty ()) { 7447 std::vector < std::pair < strata::prefill::Prefill * ,int >> paths {{& sp ,0 }}; 7448for (const auto & st :stages )paths .emplace_back (& st -> sp ,st -> dev ); 7449for (size_t i = 0 ;i < paths .size ();++ i ) { 7450const strata::core::OnDevice on (paths [i ].second ); 7451if (!paths [i ].first -> set_stage_helper (paths [(i + 1 ) %paths .size ()].first ,err )) { 7452 std::fprintf (stderr ,"strata serve: %s - stage %zu reads its prompts alone\n" ,err .c_str (),i ); 7453err .clear (); 7454 } 7455 } 7456 } 7457mem_mark ("the head and the prompt path" ); 7458// #340: STRATA_SPLIT_SMALL_OWN=S (tokens): on a layer split, every stage that borrows keeps the slots for an 7459// S-token chunk's buffers for the whole session (0.1.29's own buffers, carved from the tail of its cache): 7460// a request of at most S prompt tokens then lends, streams and refills nothing, a longer one lends (and 7461// refills) only the slots above them. Their experts stay non-resident (the CPU / PCIe path computes them). 7462// STRATA_SPLIT_SMALL_MAX=M: a request of at most M prompt tokens reads in S-token chunks on those stages 7463// (several chunks, still nothing lent) instead of borrowing for a bigger one. 7464int64_t split_small = 0 ,split_small_max = 0 ; 7465if (multi_gpu && !pf_parts .empty ()&& !host_res .empty ()) { 7466const char * v = std::getenv ("STRATA_SPLIT_SMALL_OWN" ); 7467const int64_t S = v ?request_chunk (std::atoll (v ),o .prefill_chunk ) :0 ; 7468const char * vm = std::getenv ("STRATA_SPLIT_SMALL_MAX" ); 7469split_small = S ; 7470split_small_max = S > 0 ? std::max < int64_t > (S ,vm ? std::atoll (vm ) :S ) :0 ; 7471int64_t evicted = 0 ; 7472for (PfPart & p :pf_parts ) { 7473if (S <=0 || p .first < 0 )continue ; 7474const int32_t first_s = std::max < int32_t > (p .first , (int32_t ) (p .cache -> slots ()- part_slots (p ,S ))); 7475int64_t n = 0 ; 7476for (int64_t l = p .lb ;l < p .le ;++ l ) 7477for (int64_t ex = 0 ;ex < g .n_expert ;++ ex ) { 7478int32_t & r = host_res [(size_t ) (l * g .n_expert + ex )]; 7479if (r >=first_s ) {r = strata::core::kNotResident ;++ n ; } 7480 } 7481evicted += n ; 7482 std::fprintf (stderr ,"strata serve: CUDA%d keeps %lld slots for %lld-token prompts (%lld experts " 7483"no longer resident)\n" ,p .dev < 0 ?0 :p .dev , 7484 (long long ) (p .cache -> slots ()- first_s ), (long long )S , (long long )n ); 7485 } 7486if (evicted > 0 ) { 7487if (d_res != nullptr ) 7488res_put (d_res ); 7489for (auto & st :stages ) { 7490const strata::core::OnDevice on (st -> dev ); 7491res_put (st -> d_res ); 7492 } 7493 } 7494 } 7495kvg_start (borrow != nullptr ? (int64_t )lend_first :xcache .slots ()); 7496// the penalty-history buffer: one row per verify-window row (`penalty_rows`), each the last 7497// `penalty_last_n` tokens that row's pick follows, -1 padded in front. Allocated once at the cap for 7498// the widest window; a request without penalties gets a null buffer and takes the byte-for-byte 7499// neutral path (no upload, no buffer handed to the sampler). 7500constexpr int kPenaltyWindowCap = 4096 ; 7501constexpr size_t kHistSlots = (size_t )kPenaltyWindowCap * (size_t ) strata::kernels::kVerifyMaxT ; 7502int32_t * d_hist = nullptr ; 7503 std::vector < int32_t > hist_stage (kHistSlots ,-1 ); 7504const int hist_dev = last_st ?last_st -> dev :-1 ;// with the head: the last stage's device 7505if (const strata::core::OnDevice on_h (hist_dev ); 7506DPCT_CHECK_ERROR (d_hist = sycl::malloc_device < int32_t > ( 7507kHistSlots , dpct::get_in_order_queue ()))!= 75080 ) { 7509 std::fprintf (stderr ,"strata serve: the penalty-history allocation failed\n" ); 7510return 1 ; 7511 } 7512 strata::core::Verifier ver ; 7513 strata::core::VerifyHits vh ; 7514int32_t * usage_dev_srv = nullptr ; 7515vh .d_res = thits .d_res ; 7516// 0.1.44 --expert-profile-save under STRATA_VERIFY_NO_HOST (no adaptive tier, so no host-side counts): the device 7517// plan counts every routed expert of the verify windows and the saved profile is ranked from those counts. 7518if (mirror_table_d && !o .expert_profile_save .empty ()) { 7519usage_dev_srv = sycl::malloc_device < int32_t > ((size_t ) (g .n_layers * g .n_expert ), dpct::get_in_order_queue ()); 7520 dpct::get_in_order_queue ().memset (usage_dev_srv ,0 , (size_t ) (g .n_layers * g .n_expert )* 4 ).wait (); 7521 } 7522if (mirror_table_d ) strata::kernels::resident_plan_set_mirror (thits .d_res ,mirror_table_d ,usage_dev_srv , (long long ) (g .n_layers * g .n_expert )); 7523vh .h_res = host_res .empty () ?nullptr :host_res .data (); 7524vh .cache_base = thits .cache_base ; 7525vh .blob = thits .blob ; 7526vh .slot_off = xcache .slot_offsets ();// E-6: the device plan's pointers 7527vh .n_slots = xcache .slots (); 7528// Layer split: `ver` runs layers [0, K1) and hands its residual to the next stage's verifier, and so on; the 7529// last runs the head. The hand-offs are mapped pinned memory, portable: a stage on another GPU reads it. 7530// (--split-device 0: the second stage on this GPU, sharing its weights, session and cache - the A/B.) 7531 strata::core::Verifier ver_same ; 7532SplitDrive split_drive ; 7533auto stage_ver = [& ](int st )-> strata::core::Verifier & { 7534return st == 0 ?ver :split_same ?ver_same :stages [(size_t )st - 1 ]-> ver ; 7535 }; 7536auto pcie_num_of = [](double f ) {return std::max (0 , std::min (256 , (int ) (f * 256.0 + 0.5 ))); }; 7537const int n_stages = split_devs .empty () ?1 : (int )split_at .size ()+ 1 ; 7538// --pipeline-windows (decided where the split was): two verifiers per stage, one for the even windows and one 7539// for the odd ones, sharing one stream of their card, and a hand-off per parity - so stage 0 can run window 7540// K+1 while stage 1 still reads window K's hand-off 7541const bool pipe = o .pipeline_windows > 0 && n_stages == 2 && !split_same && stages .size ()== 1 ; 7542 strata::core::Verifier ver_b ; 7543SplitDrive split_drive_b ; 7544 dpct::queue_ptr pl_stream [2 ]= {& dpct::get_in_order_queue (), 7545& dpct::get_in_order_queue ()}; 7546if (pipe ) { 7547/* 7548DPCT1025: The SYCL queue is created ignoring the flag and 7549priority options. 7550*/ 7551bool ok_p = 7552DPCT_CHECK_ERROR ( 7553pl_stream [0 ]= 7554 dpct::get_current_device ().create_queue (true))== 0 ; 7555 { 7556const strata::core::OnDevice on (stages [0 ]-> dev ); 7557/* 7558DPCT1025: The SYCL queue is created ignoring the flag and 7559priority options. 7560*/ 7561ok_p = 7562ok_p && 7563DPCT_CHECK_ERROR ( 7564pl_stream [1 ]= 7565 dpct::get_current_device ().create_queue (true))== 0 ; 7566 } 7567if (!ok_p ) { std::fprintf (stderr ,"strata serve: --pipeline-windows: stream creation failed\n" );return 1 ; } 7568for (strata::core::Verifier * v : {& ver ,& ver_b }) { 7569v -> set_stream (pl_stream [0 ]); 7570v -> set_always_publish (true); 7571v -> set_self_commit_off (true);// a pipelined window may run speculatively: never let it 7572// advance the state itself, the commit graph always does 7573 } 7574for (strata::core::Verifier * v : {& stages [0 ]-> ver ,& stages [0 ]-> ver_b }) { 7575v -> set_stream (pl_stream [1 ]); 7576v -> set_always_publish (true); 7577v -> set_self_commit_off (true);// a pipelined window may run speculatively: never let it 7578// advance the state itself, the commit graph always does 7579 } 7580 } 7581if (n_stages > 1 ) { 7582const size_t hb = (size_t ) strata::kernels::kVerifyMaxT * 7583 (size_t ) strata::core::Verifier ::handoff_floats (g )* sizeof (float ); 7584 std::vector < float *> hand ((size_t )n_stages - 1 ,nullptr ); 7585for (float *& h :hand ) { 7586float * hh = nullptr ; 7587/* 7588DPCT1048: The original value cudaHostAllocMapped is not 7589meaningful in the migrated code and was removed or replaced with 75900. You may need to check the migrated code. 7591*/ 7592/* 7593DPCT1048: The original value cudaHostAllocPortable is not 7594meaningful in the migrated code and was removed or replaced with 75950. You may need to check the migrated code. 7596*/ 7597if (DPCT_CHECK_ERROR (hh = (float * )sycl::malloc_host ( 7598hb , dpct::get_in_order_queue ()))!= 75990 || 7600DPCT_CHECK_ERROR (* (void ** )& h = (float * )hh )!= 0 ) { 7601 std::fprintf (stderr ,"strata serve: the layer-split hand-off allocation failed\n" ); 7602return 1 ; 7603 } 7604 std::memset (hh ,0 ,hb ); 7605 } 7606split_drive .base = & drive ; 7607split_drive .n = n_stages ; 7608for (int st = 0 ;st < n_stages ;++ st ) { 7609stage_ver (st ).set_stage (st == 0 ?0 :split_at [(size_t )st - 1 ],st + 1 < n_stages ?split_at [(size_t )st ] :-1 , 7610st == 0 ?nullptr :hand [(size_t )st - 1 ],st + 1 < n_stages ?hand [(size_t )st ] :nullptr ); 7611split_drive .end [st ]= st + 1 < n_stages ?split_at [(size_t )st ] :g .n_layers ; 7612split_drive .cache_base [st ]= drive .d .cache_base ; 7613split_drive .cache_slot_off [st ]= drive .d .cache_slot_off ; 7614split_drive .pcie_num [st ]= pcie_num_of (o .pcie_frac ); 7615 } 7616for (int st = 1 ;st < n_stages ;++ st ) { 7617bool ok_s = false; 7618if (split_same ) { 7619ok_s = ver_same .init (wt ,g ,ss ,vh ,native_head .loaded () ?& native_head :nullptr , std::max (o .spec ,o .batch ),err ); 7620 }else { 7621GpuStage & gs = * stages [(size_t )st - 1 ]; 7622const strata::core::OnDevice on (gs .dev ); 7623 strata::core::VerifyHits vs ; 7624vs .d_res = gs .d_res ; 7625vs .h_res = host_res .empty () ?nullptr :host_res .data (); 7626vs .cache_base = gs .cache .device_slot (0 ); 7627vs .blob = thits .blob ; 7628vs .slot_off = gs .cache .slot_offsets (); 7629vs .n_slots = gs .cache .slots (); 7630gs .ver .set_remote_expert_opt (remote_opt .get ()); 7631ok_s = gs .ver .init (gs .wt ,g ,gs .ss ,vs ,gs .head .loaded () ?& gs .head :nullptr , std::max (o .spec ,o .batch ),err ); 7632split_drive .cache_base [st ]= gs .cache .device_slot (0 ); 7633split_drive .cache_slot_off [st ]= gs .cache .slot_offsets (); 7634split_drive .pcie_num [st ]= pcie_num_of (gs .pcie_frac ); 7635 } 7636if (!ok_s ) { 7637 std::fprintf (stderr ,"strata serve: layer split, stage %d: %s\n" ,st + 1 ,err .c_str ()); 7638return 1 ; 7639 } 7640 } 7641for (int st = 0 ;st + 1 < n_stages ;++ st )stage_ver (st ).set_next (& stage_ver (st + 1 ),& split_drive ); 7642 std::string plan_s = "0-" + std::to_string (split_at [0 ]- 1 )+ " (CUDA0)" ; 7643for (int st = 1 ;st < n_stages ;++ st ) 7644plan_s += ", " + std::to_string (split_at [(size_t )st - 1 ])+ "-" + std::to_string (split_drive .end [st ]- 1 )+ 7645" (CUDA" + std::to_string (split_same ?0 :stages [(size_t )st - 1 ]-> dev )+ ")" ; 7646 std::fprintf (stderr ,"strata serve: layer split: layers %s, one hand-off per window\n" ,plan_s .c_str ()); 7647 } 7648// --pipeline-windows: the odd windows' verifiers and their hand-off (initialized before `ver`, which stays the 7649// watchdog's verifier), and the drafter's own row buffer, which either parity's rows are copied into 7650float * pl_mtp_R = nullptr ; 7651if (pipe ) { 7652const size_t hb = (size_t ) strata::kernels::kVerifyMaxT * 7653 (size_t ) strata::core::Verifier ::handoff_floats (g )* sizeof (float ); 7654float * hh = nullptr ,* hand_b = nullptr ; 7655/* 7656DPCT1048: The original value cudaHostAllocMapped is not 7657meaningful in the migrated code and was removed or replaced with 0. 7658You may need to check the migrated code. 7659*/ 7660/* 7661DPCT1048: The original value cudaHostAllocPortable is not 7662meaningful in the migrated code and was removed or replaced with 0. 7663You may need to check the migrated code. 7664*/ 7665if (DPCT_CHECK_ERROR (hh = (float * )sycl::malloc_host ( 7666hb , dpct::get_in_order_queue ()))!= 0 || 7667DPCT_CHECK_ERROR (* (void ** )& hand_b = (float * )hh )!= 0 ) { 7668 std::fprintf (stderr ,"strata serve: --pipeline-windows: the second hand-off allocation failed\n" ); 7669return 1 ; 7670 } 7671 std::memset (hh ,0 ,hb ); 7672GpuStage & gs = * stages [0 ]; 7673ver_b .set_stage (0 ,split_at [0 ],nullptr ,hand_b ); 7674gs .ver_b .set_stage (split_at [0 ],-1 ,hand_b ,nullptr ); 7675 { 7676const strata::core::OnDevice on (gs .dev ); 7677 strata::core::VerifyHits vs ; 7678vs .d_res = gs .d_res ; 7679vs .h_res = host_res .empty () ?nullptr :host_res .data (); 7680vs .cache_base = gs .cache .device_slot (0 ); 7681vs .blob = thits .blob ; 7682vs .slot_off = gs .cache .slot_offsets (); 7683vs .n_slots = gs .cache .slots (); 7684if (!gs .ver_b .init (gs .wt ,g ,gs .ss ,vs ,gs .head .loaded () ?& gs .head :nullptr ,o .spec ,err )) { 7685 std::fprintf (stderr ,"strata serve: --pipeline-windows: the second verifier on CUDA%d (the later " 7686"card): %s (raise --vram-reserve-mib by ~200, or --pipeline-windows 0)\n" , 7687gs .dev ,err .c_str ()); 7688return 1 ; 7689 } 7690if (DPCT_CHECK_ERROR (pl_mtp_R = sycl::malloc_device < float > ( 7691 (size_t )strata::kernels::kVerifyMaxT * 7692 (size_t )(g .hc * g .n_embd ), 7693 dpct::get_in_order_queue ()))!= 0 ) { 7694 std::fprintf (stderr ,"strata serve: --pipeline-windows: the drafter's row buffer does not fit\n" ); 7695return 1 ; 7696 } 7697 } 7698 { 7699// Verifier::init takes the CURRENT device, so the first card's second verifier is made while card 0 7700// (stage 0 always runs on the default device in this port) is current: the block above ended its scope. 7701const strata::core::OnDevice on_first (0 ); 7702if (!ver_b .init (wt ,g ,ss ,vh ,native_head .loaded () ?& native_head :nullptr ,o .spec ,err )) { 7703 std::fprintf (stderr ,"strata serve: --pipeline-windows: the second verifier on CUDA0 (the first card): " 7704"%s (raise --vram-reserve-mib by ~200, or --pipeline-windows 0)\n" ,err .c_str ()); 7705return 1 ; 7706 } 7707 } 7708ver_b .set_next (& gs .ver_b ,& split_drive_b );// the setters reach it; the pipeline never chains run/commit 7709 } 7710ver .set_remote_expert_opt (remote_opt .get ()); 7711if (use_df2 )ver .set_taps (df2 .tap_layers ()); 7712if (batch_mtp )ver .set_batch_graph_limit (64 );// --batch-mtp only: slot rotation makes many layouts (LRU); 0.1.39 keeps all 7713if (!ver .init (wt ,g ,ss ,vh ,native_head .loaded () ?& native_head :nullptr , 7714batch_mtp ? strata::kernels::kVerifyMaxT : std::max (o .spec ,o .batch ),err )|| 7715 (use_mtp && !mtp .bind (last_st ?last_st -> wt :wt ,last_st ?& last_st -> head :& native_head , 7716pipe ?pl_mtp_R :ver .final_R_all (),err ))) { 7717print_start_refusal ("strata serve" ,err ); 7718return 1 ; 7719 } 7720if (pipe )mtp .set_source_R (ver .final_R_all ());// the serial decode's rows (the last stage's even verifier) 7721if (use_df2 ) {// DFlash2 in the serve loop: one card, one request at a time; no MTP to draft instead, so anything it cannot do ends the start 7722 std::string why_not ; 7723df2 .set_max_drafts ((o .mtp_max_t > 0 ? std::min (o .mtp_max_t ,o .spec ) :o .spec )- 1 );// the widest window - 1: the head and the walk run for that many rows 7724if (!ver .tapping ())why_not = "the verifier keeps no taps here" ; 7725else if (!df2 .bind (wt ,& native_head ,df2_vocab_file ,why_not )|| !df2 .prepare (ver .tap_dev (),why_not )|| 7726 !sp .reserve_taps (df2 .tap_layers (),2048 ,g .n_embd ,why_not )) { 7727if (why_not .empty ())why_not = "the drafter could not be set up" ; 7728 } 7729if (!why_not .empty ()) { 7730 std::fprintf (stderr ,"strata serve: --draft dflash2: %s. It needs about 1.2 GiB of VRAM in all (the pack 0.5 GiB, buffers and K/V ring 0.2 GiB, " 7731"a draft head 0.3 GiB, 0.1 GiB of prompt staging); --vram-reserve-mib keeps it. No MTP is loaded, so the start ends here\n" ,why_not .c_str ()); 7732return 1 ; 7733 } 7734// STRATA_DF2_TIMING=1: the time the prompt's context updates take per request (printed when the prompt is read); STRATA_DF2_NO_PROMPT_CTX=1 (measurement only): 7735// the prompt's rows are not given to the drafter (its first drafts are poor), which attributes the drafter's share of the prompt read time 7736sp .on_taps = [& ](const float * taps ,int64_t rows ,int64_t pos0 , std::string & e )-> bool { 7737static const bool skip = std::getenv ("STRATA_DF2_NO_PROMPT_CTX" )!= nullptr ; 7738static const bool timing = std::getenv ("STRATA_DF2_TIMING" )!= nullptr ; 7739if (skip )return true; 7740const Clock ::time_point t = Clock ::now (); 7741const bool ok = df2 .context (taps ,rows ,pos0 ,e ); 7742if (timing ) std::fprintf (stderr ,"strata serve: DFlash2: prompt context update, %lld rows at %lld, %.1f ms\n" , (long long )rows , (long long )pos0 , std::chrono::duration < double , std::milli > (Clock ::now ()- t ).count ()); 7743return ok ; 7744 }; 7745 std::fprintf (stderr ,"strata serve: DFlash2 drafter on (%s, graphs captured in %.0f ms); windows up to %d tokens; no MTP layer is loaded\n" , 7746o .draft_model .c_str (),df2 .ms_capture ,o .spec ); 7747 } 7748const bool draft_on = use_mtp || use_df2 ;// some drafter proposes 7749auto free_slot_mtp_rows = [](float * p ) { 7750try { 7751if (p != nullptr ) (void )DPCT_CHECK_ERROR (sycl::free (p , dpct::get_in_order_queue ())); } 7752catch (sycl::exception const & exc ) { 7753 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 7754 <<", line:" <<__LINE__ << std::endl ; 7755 std::exit (1 ); 7756 } 7757 }; 7758 std::vector < std::unique_ptr < float , decltype(free_slot_mtp_rows )>> slot_mtp_rows ; 7759if (batch_mtp ) { 7760for (int b = 0 ;b < o .batch ;++ b ) { 7761float * r = nullptr ; 7762const size_t bytes = (size_t )o .spec * (size_t )g .hc * (size_t )g .n_embd * sizeof (float ); 7763if (DPCT_CHECK_ERROR (r = (float * )sycl::malloc_device ( 7764bytes , dpct::get_in_order_queue ()))!= 77650 ) { 7766 std::fprintf (stderr ,"strata serve: batch MTP slot %d residual buffer does not fit%s\n" , 7767b ,vram_free_note ().c_str ()); 7768return 1 ; 7769 } 7770slot_mtp_rows .emplace_back (r ,free_slot_mtp_rows ); 7771if (!slot_mtp [(size_t )b ]-> bind (wt ,& native_head ,r ,err ,& mtp )) { 7772 std::fprintf (stderr ,"strata serve: batch MTP slot %d: %s%s\n" ,b ,err .c_str (), 7773vram_free_note ().c_str ()); 7774return 1 ; 7775 } 7776 } 7777 } 7778// each stage's verifier gets its stage's slot sessions 7779if (o .batch > 0 ) { 7780for (size_t k = 0 ;k < bslot_ss .size ();++ k ) { 7781 std::vector < strata::core::SessionState *> ptrs ; 7782for (auto & u :bslot_ss [k ])ptrs .push_back (u .get ()); 7783 strata::core::Verifier & vk = k == 0 ?ver :stages [k - 1 ]-> ver ; 7784const strata::core::OnDevice on_k (k == 0 ?0 :stages [k - 1 ]-> dev ); 7785if (!vk .init_slots (ptrs ,err )) { 7786 std::fprintf (stderr ,"strata serve: --batch, stage %zu: %s\n" ,k + 1 ,err .c_str ()); 7787return 1 ; 7788 } 7789 } 7790 } 7791for (int st = 0 ;st < n_stages && n_stages > 1 ;++ st ) { 7792split_drive .plan [st ]= stage_ver (st ).plan_sink (); 7793if (st > 0 ) { 7794stage_ver (st ).set_split (o .spec_split ); 7795stage_ver (st ).set_pcie_mode (o .pcie_mode == "dma" ?0 :o .pcie_mode == "direct" ?1 :2 ); 7796 } 7797 } 7798if (pipe ) {// the odd windows' pool routing: the same as the even ones', with their plans 7799split_drive_b = split_drive ; 7800split_drive_b .plan [0 ]= ver_b .plan_sink (); 7801split_drive_b .plan [1 ]= stages [0 ]-> ver_b .plan_sink (); 7802stages [0 ]-> ver_b .set_split (o .spec_split ); 7803stages [0 ]-> ver_b .set_pcie_mode (o .pcie_mode == "dma" ?0 :o .pcie_mode == "direct" ?1 :2 ); 7804ver_b .set_split (o .spec_split ); 7805ver_b .set_pcie_mode (o .pcie_mode == "dma" ?0 :o .pcie_mode == "direct" ?1 :2 ); 7806 } 7807// the pool the verify windows call: with a layer split, the wrapper that routes each layer to its stage 7808const strata::core::PoolMultiFn win_pool_fn = n_stages > 1 ?& drive_pool_split :& drive_pool_multi ; 7809void * const win_pool_user = n_stages > 1 ? (void * )& split_drive : (void * )& drive ; 7810mem_mark ("the verifier and the drafter's binding" ); 7811ver .set_split (o .spec_split ); 7812// auto: the copy kernel for every pack. DMA (the native packs' default until 0.1.13) has the host call 7813// cudaMemcpyAsync + cudaLaunchHostFunc inside a verify window while the GPU spins on the flag they raise; 7814// issue #31's thread dumps show the host stuck in that cudaMemcpyAsync on a driver lock for good. The copy 7815// kernel needs no host CUDA call there, and costs ~1-3% decode on IQ3_S (45.3 -> 44.8 tok/s, 8 requests). 7816ver .set_pcie_mode (o .pcie_mode == "dma" ?0 :o .pcie_mode == "direct" ?1 :2 ); 7817// --pipeline-windows 2: stage 0's GDN state before a speculative commit, restored when the guess was wrong. 7818// Window W reads the state its snapshot must hold and no window writes it (only commits do), so it is copied 7819// on a side stream while W runs, into the buffer of W's parity, and only W's speculative commit waits for it 7820// (STRATA_PIPELINE_SNAP_OVERLAP=0: one buffer, copied on the critical path). 7821const size_t pl_snap_bytes = pipe ?gdn_snapshot_bytes (ss ) :0 ; 7822float * pl_snap2 [2 ]= {nullptr ,nullptr }; 7823 dpct::queue_ptr pl_snap_stream = & dpct::get_in_order_queue (); 7824 dpct::event_ptr pl_snap_pre [2 ]= {nullptr ,nullptr }, 7825pl_snap_ev [2 ]= {nullptr ,nullptr }; 7826bool pl_snap_overlap = false; 7827if (pipe && o .pipeline_windows >=2 ) { 7828if (DPCT_CHECK_ERROR ( 7829pl_snap2 [0 ]= (float * )sycl::malloc_device ( 7830pl_snap_bytes , dpct::get_in_order_queue ()))!= 0 ) { 7831 std::fprintf (stderr ,"strata serve: --pipeline-windows 2: the GDN snapshot (%.1f MiB) does not fit; the " 7832"decode stays serial\n" , (double )pl_snap_bytes /1048576.0 ); 7833/* 7834DPCT1026: The call to cudaGetLastError was removed because 7835this functionality is redundant in SYCL. 7836*/ 7837pl_snap2 [0 ]= nullptr ; 7838 }else if ([] {const char * v = pipe_dbg_env ("STRATA_PIPELINE_SNAP_OVERLAP" );return v == nullptr || std::atoi (v )!= 0 ; }()) { 7839pl_snap_overlap = 7840DPCT_CHECK_ERROR ( 7841pl_snap2 [1 ]= (float * )sycl::malloc_device ( 7842pl_snap_bytes , dpct::get_in_order_queue ()))== 0 && 7843/* 7844DPCT1025: The SYCL queue is created ignoring the flag 7845and priority options. 7846*/ 7847DPCT_CHECK_ERROR ( 7848pl_snap_stream = 7849 dpct::get_current_device ().create_queue (true))== 0 ; 7850for (int i = 0 ;i < 2 && pl_snap_overlap ;++ i ) 7851pl_snap_overlap = 7852DPCT_CHECK_ERROR (pl_snap_pre [i ]= new sycl::event ())== 78530 && 7854DPCT_CHECK_ERROR (pl_snap_ev [i ]= new sycl::event ())== 78550 ; 7856/* 7857DPCT1010: SYCL uses exceptions to report errors and does 7858not use the error codes. The cudaGetLastError function call was 7859replaced with 0. You need to rewrite this code. 7860*/ 7861if (!pl_snap_overlap )0 ; 7862 } 7863 } 7864if (pipe ) 7865 std::fprintf (stderr ,"strata serve: --pipeline-windows %d: two verifiers per stage, the stages overlap across " 7866"windows%s\n" ,o .pipeline_windows , 7867pl_snap2 [0 ]== nullptr ?"" :pl_snap_overlap ?" (decode too; the GDN snapshots beside the window)" 7868 :" (decode too; the GDN snapshot on the critical path)" ); 7869// the verifiers by [stage][parity], their pool routing, and the drafter's events (in a pipelined prompt read, a 7870// stage-1 window waits until the drafter has read the rows of the same parity's previous window) 7871 strata::core::Verifier * PV [2 ][2 ]= {{& ver ,& ver_b }, {pipe ?& stages [0 ]-> ver :nullptr ,pipe ?& stages [0 ]-> ver_b :nullptr }}; 7872SplitDrive * PSD [2 ]= {& split_drive ,& split_drive_b }; 7873 dpct::event_ptr pl_mtp_ev [2 ]= {nullptr ,nullptr }; 7874bool pl_mtp_live [2 ]= {false, false}; 7875bool pl_prepared = false; 7876if (strata::kernels::b60_layout_requested ()&& strata::kernels::b60_single_actor_requested ()){ 7877b60_layouts .bind_single (xcache ,host_res ,strata::kernels::cpu::expert_layout ()); 7878b60_layouts .packed (true); 7879 }else if (strata::kernels::b60_layout_requested ()){ 7880if (!native_pack || !pipe || n_stages != 2 || !o .no_prefill_borrow || o .batch > 0 || o .prompt_cache != 0 || o .spec > 6 || g .n_layers != 48 || g .n_expert != 512 || g .n_embd != 2560 || g .n_ff != 640 || g .hc != 4 || g .hc_lr != 320 ) 7881throw std::invalid_argument ("B60 layout candidate requires the fixed all-resident two-stage decode scene" ); 7882const char * pvr = std::getenv ("STRATA_PRIVATE_PACKED_REGISTER" ); 7883if (!pvr || pvr [0 ]!= '1' )throw std::invalid_argument ("B60 packed weights require the packed register reader" ); 7884const auto & layout = strata::kernels::cpu::expert_layout (); 7885b60_layouts .add_device (0 ,0 ,split_at [0 ],wt ,xcache ,host_res ,layout ); 7886for (auto & st :stages )b60_layouts .add_device (st -> dev ,st -> lb ,st -> le ,st -> wt ,st -> cache ,host_res ,layout ,& st -> head ); 7887b60_layouts .packed (true); 7888 } 7889// every graph captured and the drafter's prompt path sized while nothing is in flight (a capture syncs its stream) 7890auto pl_prepare = [& ](std::string & e )-> bool { 7891try { 7892if (pl_prepared )return true; 7893for (int st = 0 ;st < 2 ;++ st ) 7894for (int par = 0 ;par < 2 ;++ par ) { 7895const strata::core::OnDevice on (PV [st ][par ]-> device ()); 7896if (!PV [st ][par ]-> capture_all (e ))return false; 7897 } 7898if (!mtp .prepare_prefill (e ))return false; 7899if (o .pipeline_windows >=2 && pl_snap2 [0 ]!= nullptr && !mtp .prepare_chain (e ))return false; 7900const strata::core::OnDevice on (mtp .device ()); 7901for (dpct::event_ptr & ev :pl_mtp_ev ) 7902if (ev == nullptr && 7903DPCT_CHECK_ERROR (ev = new sycl::event ())!= 0 ) { 7904e = "pipeline: event creation failed" ; 7905return false; 7906 } 7907pl_prepared = true; 7908return true; 7909 } 7910catch (sycl::exception const & exc ) { 7911 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 7912 <<", line:" <<__LINE__ << std::endl ; 7913 std::exit (1 ); 7914 } 7915 }; 7916// INVARIANT: nothing pipelined is in flight outside read_windows_pl and the pipelined decode loop - both end 7917// here (a checkpoint, a park, the next request and the serial paths all find both stages and the drafter idle). 7918// Every window in flight is served to its end (its picks discarded), then both stages and the drafter idle. 7919auto pl_drain = [& ]() { 7920try { 7921 std::string e2 ; 7922for (int round = 0 ;round < 10000000 ;++ round ) { 7923bool any = false; 7924for (int st = 0 ;st < 2 ;++ st ) 7925for (int par = 0 ;par < 2 ;++ par ) { 7926 strata::core::Verifier & v = * PV [st ][par ]; 7927if (!v .in_flight ())continue ; 7928any = true; 7929if (v .service (& drive_pool_split ,PSD [par ],e2 )< 0 )return ; 7930if (v .done (e2 ))v .pl_finish (nullptr ,e2 ); 7931else if (!e2 .empty ())return ; 7932 } 7933if (!any )break ; 7934 } 7935for (int st = 0 ;st < 2 ;++ st ) { 7936const strata::core::OnDevice on (PV [st ][0 ]-> device ()); 7937PV [st ][0 ]-> stream ()-> wait (); 7938 } 7939const strata::core::OnDevice on (mtp .device ()); 7940mtp .stream ()-> wait (); 7941 } 7942catch (sycl::exception const & exc ) { 7943 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 7944 <<", line:" <<__LINE__ << std::endl ; 7945 std::exit (1 ); 7946 } 7947 }; 7948 std::vector < int64_t > cur ; 7949// ---- the conversation cache (see ConvCheckpoint). `live` is what the session holds right now: the tokens 7950// it has consumed, so a request that starts with exactly them continues without any copy. `checks` are the 7951// saved points; every one of them is a prefix of `live` (the loop drops the rest), so they form a chain - 7952// the radix cache's tree collapsed onto the one branch of history whose cells the session holds. The 7953// chain's root is the deepest point every request so far shared (the end of the system prompt, in 7954// practice); the retention policy pins it and rotates the rest LRU (conv_cache.hpp), so a NEW chat that 7955// shares that prefix mounts through it instead of reading it again. 7956 std::vector < int32_t > live ; 7957 std::vector < ImgKey > live_imgs ,req_imgs ; 7958bool live_ok = false; 7959 std::vector < ConvCheckpoint > checks ; 7960uint64_t check_clock = 0 ;// the checkpoints' LRU clock; creation and every use advance it 7961int64_t tail_ckpt_len = -1 ;// --prompt-cache-tail: the length of the one tail checkpoint alive (-1 = none) 7962bool cvec_cached = true;// the control vector's state the live session and the checkpoints were read with 7963// without --mtp the conversation cache stays on: a parked image carries the draft layer's K/V only when there is one 7964// (the snapshots accept a null draft) 7965 strata::core::ConversationCache conversations ( 7966o .prompt_cache > 0 ? (size_t )o .conversation_cache_mib * 1024 * 1024 :0 , 7967 (size_t )o .conversation_cache_slots ); 7968// Disk sessions: what a session file is bound to. The model fingerprint samples every model input this 7969// engine loaded, by role (conversation_file.hpp), once; the config fingerprint covers the RESOLVED settings 7970// that change what the saved bytes mean - the rope (K is cached post-RoPE), the loaded control vector, the 7971// K/V format and the arithmetic switches. Sampling, seeds, draft tuning and the expert tier are not in it. 7972 std::optional < uint64_t > model_fp ,config_fp ; 7973auto session_identity = [& ](strata::core::SessionFileIdentity & id , std::string & e , 7974const std::function < void ()>& next_file )-> bool { 7975if (!model_fp ) { 7976// what the loaders actually resolved: the CLI inputs, the pack's files and - from the expert source 7977// itself - every file its experts were read from (native_experts.txt can name GGUFs per layer/role) 7978 strata::core::SessionInputs in ; 7979in .native_shards = o .native_shards ; 7980in .native_dense = o .native_dense_gguf ; 7981in .native_head = o .native_head_shards ; 7982in .embedding = o .embd_gguf ; 7983in .ple = o .ple_gguf ; 7984in .pack = o .pack ; 7985in .mtp = o .mtp .empty () ? std::string () :o .mtp + "/dense.bin" ; 7986if (srcp != nullptr )in .experts = srcp -> model_inputs (); 7987 std::vector < strata::core::SessionModelFile > files = strata::core::session_model_inputs (in ); 7988// the pack's other files the loader reads (weights.cpp, expert_layout.cpp) 7989if (!o .pack .empty ()) { 7990for (const char * n : {"index.txt" ,"dense.bin" })files .push_back ({std::string ("pack " )+ n ,o .pack + "/" + n }); 7991for (const char * n : {"embd.bin" ,"extra.bin" ,"manifest.json" }) 7992files .push_back ({std::string ("pack " )+ n ,o .pack + "/" + n , true}); 7993if (srcp == nullptr )files .push_back ({"pack experts.bin" ,o .pack + "/experts.bin" , true}); 7994 } 7995if (!o .mtp .empty ()) { 7996for (const char * n : {"dense.txt" ,"experts.bin" })files .push_back ({std::string ("mtp " )+ n ,o .mtp + "/" + n }); 7997files .push_back ({"mtp draft_vocab.bin" ,o .mtp + "/draft_vocab.bin" , true}); 7998 } 7999uint64_t fp = 0 ; 8000// each file is one blocking read of at most 2 MiB (head and tail): announced before it starts 8001if (next_file )next_file (); 8002if (!strata::core::session_model_fingerprint (files ,fp ,e ,next_file )) 8003return false; 8004model_fp = fp ; 8005 } 8006if (!config_fp ) { 8007 strata::core::SessionConfig c ; 8008c .engine_version = STRATA_VERSION ; 8009#if defined(STRATA_USE_HIP ) 8010c .backend = "hip" ; 8011#else 8012c .backend = "cuda" ; 8013#endif 8014c .kv = o .kv ; 8015c .max_context = o .max_context ; 8016c .kv_resident = o .kv_resident ; 8017c .mtp_window = o .mtp .empty () ?-1 :o .mtp_window ; 8018const char * rot = std::getenv ("STRATA_KV_ROT" ); 8019c .kv_rot = rot != nullptr && rot [0 ]== '1' ; 8020c .rope = {(int64_t )rope_cfg .type ,rope_cfg .freq_base ,rope_cfg .factor ,rope_cfg .freq_scale (), 8021rope_cfg .orig_ctx ,rope_cfg .ext_factor ,rope_cfg .attn_factor ,rope_cfg .beta_fast , 8022rope_cfg .beta_slow }; 8023c .cvec = cvec_digest ; 8024c .switches = { 8025 {"no_ple" ,o .no_ple }, {"native_bf16" ,o .native_bf16 }, {"native_bf16_extra" ,o .native_bf16_extra }, 8026 {"native_ple_key" ,o .native_ple_key }, {"native_moe_combine" ,o .native_moe_combine }, 8027 {"native_gdn" ,o .native_gdn }, {"native_flash_attn_short" ,o .native_flash_attn_short }, 8028 {"native_qsa_indexer" ,o .native_qsa_indexer }, {"native_qsa" ,o .native_qsa }, 8029 {"native_rope" ,o .native_rope }, {"native_ple_postops" ,o .native_ple_postops }, 8030 {"native_router" ,o .native_router }, {"cpu_oracle_q8_0" ,o .cpu_oracle_q8_0 }, 8031 {"gr_fp32_activations" ,o .gr_fp32_activations }, {"gr_native_mmvf" ,o .gr_native_mmvf }, 8032 {"native_preset" , !o .native_preset .empty ()}, {"shared_late" ,o .shared_late }, 8033 {"keep_canonical" ,o .keep_canonical }, {"no_fused_gr" ,o .no_fused_gr }, 8034 {"no_fast_attn" ,o .no_fast_attn }, {"no_fused_gdn" ,o .no_fused_gdn }, 8035 {"no_fast_select" ,o .no_fast_select }, {"vision" ,o .vision }}; 8036config_fp = strata::core::session_config_fingerprint (c ); 8037 } 8038id .model = * model_fp ; 8039id .config = * config_fp ; 8040return true; 8041 }; 8042// What a park captures: the main session's conversation (park_current) or an idle batch slot's (park_slot: 8043// the reply it decoded, before an admission overwrites it). One budget / admission / snapshot path for both. 8044struct ParkSource { 8045const std::vector < int32_t >& ids ; 8046const std::vector < ImgKey >& imgs ; 8047 std::vector < ConvCheckpoint >& checks ;///< moved apart into stage parts for the capture, put back after 8048bool cvec ; 8049 strata::core::SessionState & session ;///< stage 0's 8050 std::vector < strata::core::SessionState *> stage_sessions ;///< the later stages', in stage order (stages[k]->dev) 8051const strata::core::QsaState * draft0 ;///< the draft layer's K/V saved with stage 0's image (or none) 8052const strata::core::QsaState * draft_last ;///< ... with the last stage's image (a split: the drafter's GPU) 8053bool with_reuse ;///< the retained K/V describes this source (the main session's) 8054 std::string what ;///< the log's words after the token count ("", " from slot 1") 8055 }; 8056// Save only on a switch/rewind, not on each continuing request. No graph 8057// addresses change: all parked images live in ordinary host vectors. 8058auto park_source = [& ](const ParkSource & src ,size_t held )-> bool { 8059// #342: before make_room evicts oldest-first, the copies of this conversation a turn back go (they hold 8060// nothing the outgoing chain does not, apart from the tail this conversation rewrote) 8061if (const size_t dropped = conversations .drop_superseded (src .ids ,src .imgs ,src .checks ,src .cvec )) 8062 std::fprintf (stderr ,"strata serve: conversation cache: dropped %zu superseded cop%s of this " 8063"conversation; parked=%zu\n" ,dropped ,dropped == 1 ?"y" :"ies" ,conversations .size ()); 8064// A layer split parks one image per stage: the first stage's (with the draft layer's K/V) and one per 8065// later stage (without it - the draft ring is saved once). The checkpoints are MOVED apart into their 8066// stage parts for the capture and put back together whichever way this ends (no running state copied). 8067const size_t n_st = stages .size (); 8068// the draft layer's K/V lives on the last stage's GPU (the drafter is loaded there): with a split it is 8069// saved with that stage's image, under its device; stage 0's image holds none 8070const strata::core::QsaState * draft0 = src .draft0 ;// no --mtp: no draft K/V (snapshots accept null) 8071auto draft_of = [& ](size_t k )-> const strata::core::QsaState * {return k + 1 == n_st ?src .draft_last :nullptr ; }; 8072 std::vector < ConvCheckpoint >& checks = src .checks ; 8073 strata::core::ConversationCheckpointSplit cs ; 8074if (n_st > 0 )cs = strata::core::conversation_checkpoints_split (std::move (checks ),n_st );// #752: two-phase; a bad_alloc leaves `checks` whole 8075struct MergeBack { 8076 strata::core::ConversationCheckpointSplit & cs ; std::vector < ConvCheckpoint >& checks ;bool on ; 8077 ~MergeBack () {if (on && !strata::core::conversation_checkpoints_merge (std::move (cs ),checks ))checks .clear (); } 8078 }merge_back {cs ,checks ,n_st > 0 }; 8079const strata::core::ConversationView view {src .ids ,src .imgs ,n_st > 0 ?cs .stage0 :checks ,src .cvec }; 8080const int64_t retained_n = src .with_reuse ?conversations .retained_tokens () :0 ; 8081// a batch slot's image carries no retained K/V (it describes the main session's conversation), and the 8082// main session's stays retained for its own park 8083auto reuse = src .with_reuse ?conversations .take_reuse_for (src .ids )// never another conversation's K/V 8084 : strata::core::ConversationKvReuse {}; 8085if (retained_n > 0 && reuse .unchanged_tokens < retained_n ) 8086 std::fprintf (stderr ,"strata serve: conversation cache: retained K/V reused for %lld of its %lld tokens " 8087"(the rest is not this conversation's)\n" , (long long )reuse .unchanged_tokens , 8088 (long long )retained_n ); 8089 std::vector < strata::core::ConversationKvReuse > stage_reuse = std::move (reuse .stages ); 8090stage_reuse .resize (n_st ); 8091reuse .stages .clear (); 8092// the later stages' estimates, each with its own retained K/V when it still fits 8093size_t stage_estimate = 0 ,stage_retained = 0 ; 8094for (size_t k = 0 ;k < n_st ;++ k ) { 8095auto & st = stages [k ]; 8096const strata::core::OnDevice on (st -> dev ); 8097const strata::core::ConversationView view_k {src .ids ,src .imgs ,cs .parts [k ],src .cvec }; 8098size_t b = 0 ; 8099if (!strata::core::conversation_snapshot_bytes (view_k ,* src .stage_sessions [k ],g ,draft_of (k ),b ,err )) { 8100 std::fprintf (stderr ,"strata serve: conversation cache: skip parking (stage CUDA%d: %s)\n" , 8101st -> dev ,err .c_str ()); 8102err .clear (); 8103return true; 8104 } 8105if (!stage_reuse [k ].kv .empty ()) { 8106size_t r = 0 ; 8107if (strata::core::conversation_snapshot_capture_bytes (stage_reuse [k ],view_k ,* src .stage_sessions [k ],g , 8108draft_of (k ),r ,err )) { 8109b = r ; 8110stage_retained += stage_reuse [k ].bytes (); 8111 }else { 8112stage_reuse [k ]= {}; 8113err .clear (); 8114 } 8115 } 8116stage_estimate += b ; 8117 } 8118size_t estimate = 0 ; 8119if (!strata::core::conversation_snapshot_bytes (view ,src .session ,g ,draft0 ,estimate ,err )) { 8120 std::fprintf (stderr ,"strata serve: conversation cache: skip parking (%s)\n" ,err .c_str ()); 8121err .clear ();// A recoverable miss must not poison the batched draft prefill's error channel. 8122return true; 8123 } 8124const size_t fresh_estimate = estimate ; 8125if (!reuse .kv .empty ()&& !strata::core::conversation_snapshot_capture_bytes ( 8126reuse ,view ,src .session ,g ,draft0 ,estimate ,err )) { 8127reuse = {}; 8128estimate = fresh_estimate ; 8129err .clear (); 8130 } 8131estimate += stage_estimate ; 8132// A park carrying its own retained K/V replaces memory the cache 8133// already held, so capacity is make_room's call - it runs next either 8134// way, and put()'s accounting still bounds the budget. The with-reuse 8135// estimate must stay uncapped: it counts the retained buffers' 8136// capacity and directories, and put() charges that same true size - 8137// a capped figure would under-evict and overfill the budget. 8138if (!conversations .make_room (estimate ,held )) { 8139 std::fprintf (stderr ,"strata serve: conversation cache: skip parking (snapshot %zu MiB exceeds available budget)\n" , 8140estimate >>20 ); 8141return true; 8142 } 8143const auto t0 = Clock ::now (); 8144try { 8145const uint64_t floor = (uint64_t )o .conversation_cache_min_free_mib * 1024 * 1024 ; 8146const size_t retained = reuse .bytes ()+ stage_retained ; 8147const size_t additional = estimate > retained ?estimate - retained :0 ; 8148if (!strata::core::conversation_memory_admit (strata::core::available_host_bytes (), 8149additional ,floor )) { 8150 std::fprintf (stderr ,"strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor, or telemetry unavailable)\n" , 8151additional >>20 , (long long )o .conversation_cache_min_free_mib ); 8152return true; 8153 } 8154 strata::core::SavedConversation image ; 8155size_t reused_bytes = 0 ; 8156if (!strata::core::conversation_snapshot_save (image ,view ,src .session ,g ,draft0 ,err , 8157 std::move (reuse ),& reused_bytes ))return false; 8158for (size_t k = 0 ;k < n_st ;++ k ) {// the later stages (the last one with the draft layer's K/V) 8159auto & st = stages [k ]; 8160const strata::core::OnDevice on (st -> dev ); 8161if (DPCT_CHECK_ERROR (dpct::get_current_device () 8162 .queues_wait_and_throw ())!= 0 ) { 8163err = "stage sync failed" ;return false; 8164 } 8165const strata::core::ConversationView view_k {src .ids ,src .imgs ,cs .parts [k ],src .cvec }; 8166 strata::core::SavedConversation part ; 8167if (!strata::core::conversation_snapshot_save (part ,view_k ,* src .stage_sessions [k ],g ,draft_of (k ),err , 8168 std::move (stage_reuse [k ]),& reused_bytes )) 8169return false; 8170image .stage_images .push_back (std::move (part )); 8171 } 8172if (!strata::core::conversation_memory_admit (strata::core::available_host_bytes (),0 ,floor )) { 8173 std::fprintf (stderr ,"strata serve: conversation cache: skip parking (physical RAM floor after capture, or telemetry unavailable)\n" ); 8174return true; 8175 } 8176const size_t snapshot_bytes = image .bytes (); 8177const bool stored = conversations .put (std::move (image ),held ); 8178 std::fprintf (stderr ,"strata serve: conversation cache: %s %zu tokens%s in %.1f ms; parked=%zu bytes=%zu evictions=%zu snapshot_bytes=%zu reused_kv_bytes=%zu\n" , 8179stored ?"parked" :"skipped" ,src .ids .size (),src .what .c_str (), 8180 std::chrono::duration < double , std::milli > (Clock ::now ()- t0 ).count (), 8181conversations .size (),conversations .bytes (),conversations .evictions (),snapshot_bytes ,reused_bytes ); 8182 }catch (const std::bad_alloc & ) { 8183// The active state has not been touched. Continue with normal 8184// prompt processing rather than killing a serving process. 8185 std::fprintf (stderr ,"strata serve: conversation cache: allocation failed; skip parking\n" ); 8186 } 8187return true; 8188 }; 8189auto park_current_body = [& ](size_t held )-> bool { 8190if (!conversations .enabled ()|| !live_ok || live .empty ())return true; 8191const size_t n_st = stages .size (); 8192ParkSource src {live ,live_imgs ,checks ,cvec_cached ,ss , {}, 8193n_st > 0 || !use_mtp ?nullptr :& mtp .kv_state (), 8194use_mtp && n_st > 0 ?& mtp .kv_state () :nullptr , true,"" }; 8195for (auto & st :stages )src .stage_sessions .push_back (& st -> ss ); 8196return park_source (src ,held ); 8197 }; 8198// #752: the whole park (the checkpoint split included) is under one try, so a host OOM skips parking instead of 8199// ending the server 8200auto park_current = [& ](size_t held )-> bool { 8201try {return park_current_body (held ); } 8202catch (const std::bad_alloc & ) { 8203 std::fprintf (stderr ,"strata serve: conversation cache: allocation failed; skip parking\n" ); 8204return true; 8205 } 8206 }; 8207int64_t pp_total = 0 ,pp_from = 0 ,pp_next_check = 0 ; 8208bool pp_tail_saved = false; 8209// #471: the position the prompt pass has read up to (a chunk's or a window's end): what a request cancelled 8210// mid-read reports as read, instead of the whole prompt 8211int64_t pp_reached = 0 ; 8212Clock ::time_point pp_t0 = Clock ::now (); 8213auto imgs_below = [& ](const std::vector < ImgKey >& all ,int64_t L ) { 8214 std::vector < ImgKey > v ; 8215for (const ImgKey & k :all )if (k .start < L )v .push_back (k ); 8216return v ; 8217 }; 8218// a checkpoint of the state after `cur[0, L)`; false only when the copy itself failed 8219// A layer split's mid-prompt checkpoints: when the last stage reports a chunk, the earlier ones already read 8220// the next, so each stage saves its own part when IT reaches a checkpoint position (the same rule as below: 8221// every `prompt_cache_every` tokens from where the request resumed), and the last stage puts them together. 8222 std::mutex part_mu ; 8223 std::map < int64_t , std::vector < ConvCheckpoint >> part_at ;// position -> one part per stage 8224 std::vector < int64_t > part_next (stages .size ()+ 1 ,INT64_MAX ); 8225// a checkpoint of the state after `cur[0, L)`; false only when the copy itself failed. `parts`: the stages' 8226// states saved at L (a split's mid-prompt checkpoint); without, they are read now (everything is at L) 8227// #613: why the last checkpoint_at failed - a failed device sync is the GPU itself (a hang Windows then resets), 8228// not the checkpoint, and the error says so 8229 std::string ckpt_why ; 8230auto gpu_sync_ok = [& ]()-> bool { 8231try { 8232const dpct::err0 e = DPCT_CHECK_ERROR ( 8233 dpct::get_current_device ().queues_wait_and_throw ()); 8234if (e == 0 )return true; 8235/* 8236DPCT1009: SYCL reports errors using exceptions and does not use 8237error codes. Please replace the "get_error_string_dummy(...)" with a 8238real error-handling function. 8239*/ 8240ckpt_why = std::string (": the GPU stopped responding before it (" )+ 8241 dpct::get_error_string_dummy (e )+ 8242") - a GPU hang; on Windows the driver is then reset" ; 8243return false; 8244 } 8245catch (sycl::exception const & exc ) { 8246 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 8247 <<", line:" <<__LINE__ << std::endl ; 8248 std::exit (1 ); 8249 } 8250 }; 8251auto checkpoint_at = [& ](int64_t L , std::vector < ConvCheckpoint >* parts = nullptr ,bool as_tail = false)-> bool { 8252ckpt_why .clear (); 8253if (o .prompt_cache <=0 || L < 1 )return true; 8254for (ConvCheckpoint & c :checks ) 8255if ((int64_t )c .ids .size ()== L ) { 8256c .used = ++ check_clock ; 8257if (!as_tail && L == tail_ckpt_len )tail_ckpt_len = -1 ;// a periodic one lands here: a normal item now 8258return true; 8259 } 8260ConvCheckpoint c ; 8261c .ids .assign (cur .begin (),cur .begin ()+ L ); 8262c .imgs = imgs_below (req_imgs ,L ); 8263if (parts != nullptr ) { 8264if (parts -> size ()!= stages .size ()+ 1 )return false; 8265c .gdn = std::move ((* parts )[0 ].gdn ); 8266c .ple = std::move ((* parts )[0 ].ple ); 8267c .tails = std::move ((* parts )[0 ].tails ); 8268c .dead = std::move ((* parts )[0 ].dead ); 8269c .block_pos = std::move ((* parts )[0 ].block_pos ); 8270for (size_t i = 1 ;i < parts -> size ();++ i )c .stage_parts .push_back (std::move ((* parts )[i ])); 8271 }else { 8272if (!gpu_sync_ok ()|| !checkpoint_save (c ,ss ,g ))return false; 8273for (auto & st :stages ) {// a layer split's later stages: their sessions' part 8274const strata::core::OnDevice on (st -> dev ); 8275ConvCheckpoint part ; 8276part .ids = c .ids ; 8277if (!gpu_sync_ok ()|| !checkpoint_save (part ,st -> ss ,g ))return false; 8278c .stage_parts .push_back (std::move (part )); 8279 } 8280 } 8281c .used = ++ check_clock ; 8282if (as_tail ) {// only one tail checkpoint stays alive: the previous request's goes 8283const int64_t old_tail = tail_ckpt_len ; 8284checks .erase (std::remove_if (checks .begin (),checks .end (), [& ](const ConvCheckpoint & k ) { 8285return old_tail >=0 && (int64_t )k .ids .size ()== old_tail ; 8286 }),checks .end ()); 8287tail_ckpt_len = L ; 8288 }else if (L == tail_ckpt_len ) { 8289tail_ckpt_len = -1 ;// the flagged tail was dropped and a normal checkpoint takes its length 8290 } 8291checks .push_back (std::move (c )); 8292while ((int )checks .size ()> o .prompt_cache ) { 8293 std::vector < uint64_t > stamps ; 8294 std::vector < char > is_tail ; 8295stamps .reserve (checks .size ()); 8296for (const ConvCheckpoint & k :checks ) { 8297stamps .push_back (k .used ); 8298is_tail .push_back (tail_ckpt_len >=0 && (int64_t )k .ids .size ()== tail_ckpt_len ); 8299 } 8300// the tail checkpoint serves only a branch of the last request: it leaves before a periodic one 8301 std::unique_ptr < bool []> tail_flags (new bool [is_tail .size ()]); 8302for (size_t i = 0 ;i < is_tail .size ();++ i )tail_flags [i ]= is_tail [i ]!= 0 ; 8303const size_t victim = strata::program::conv_cache::eviction_victim ( 8304stamps .data (),stamps .size (),o .prompt_cache ,tail_flags .get ()); 8305checks .erase (checks .begin ()+ (std::ptrdiff_t )victim ); 8306 } 8307return true; 8308 }; 8309sp .on_chunk = [& ](const float * R_rows ,int64_t T ,int64_t p0 , std::string & e )-> bool { 8310 std::vector < int32_t > nxt ((size_t )T ); 8311for (int64_t t = 0 ;t < T ;++ t )nxt [(size_t )t ]= (int32_t )cur [(size_t ) (p0 + t + 1 )]; 8312// E-9: batched through the prompt path when it can (one GPU: a layer split's drafter is on the last stage) 8313const bool batched = use_mtp && !multi_gpu && sp .draft_kv (mtp ,R_rows ,nxt .data (),T ,p0 ,e ); 8314if (!e .empty ()|| (use_mtp && !batched && !mtp .prefill (R_rows ,nxt .data (),T ,p0 ,e )))return false; 8315if (use_df2 ) {// the drafter's token history covers the batched prompt rows too (its begin_request compares it with the next prompt) 8316 std::vector < int32_t > tk ((size_t )T ); 8317for (int64_t t = 0 ;t < T ;++ t )tk [(size_t )t ]= (int32_t )cur [(size_t ) (p0 + t )]; 8318df2 .note_rows (tk .data (),T ,p0 ); 8319 } 8320if (use_mtp && std::getenv ("STRATA_SNAPSHOT_VERIFY" )!= nullptr ) 8321 std::fprintf (stderr ,"strata serve: DRAFT_PREFILL path=%s mode=%d cells=%lld\n" , 8322batched ?"batched" :"token" ,mtp .kv_state ().kv_mode , (long long )T ); 8323// progress for the server window: PP <position reached> <prompt tokens> <ms> <fresh tokens/s> 8324const int64_t done = p0 + T ; 8325pp_reached = done ; 8326const double ms = std::chrono::duration < double , std::milli > (Clock ::now ()- pp_t0 ).count (); 8327 std::printf ("PP %lld %lld %.0f %.1f\n" , (long long )done , (long long )pp_total ,ms , 8328ms > 0.0 ?1000.0 * (double ) (done - pp_from ) /ms :0.0 ); 8329 strata::core::progress_at ("reading the prompt (batched), done up to token" ,done ); 8330 strata::core::progress_beat (); 8331 std::fflush (stdout ); 8332const bool periodic_checkpoint = o .prompt_cache_every > 0 && done >=pp_next_check ; 8333// Keep the prefill's existing chunk geometry. One extra near-tail checkpoint 8334// can serve a branch whose shared prefix ends before the final cached state. 8335const bool tail_checkpoint = o .prompt_cache_tail && o .prompt_cache > 0 && o .prompt_cache_every > 0 && 8336 !multi_gpu && !pp_tail_saved && pp_total - done > std::max < int64_t > (1 ,o .short_read )&& 8337pp_total - done <=T ;// this chunk's real size (--prefill auto chunks differ from o.prefill_chunk) 8338if (periodic_checkpoint || tail_checkpoint ) { 8339bool saved = false; 8340if (multi_gpu ) {// the stages' parts, saved when each of them read this chunk 8341 std::vector < ConvCheckpoint > parts ; 8342 { 8343 std::lock_guard < std::mutex > lk (part_mu ); 8344auto it = part_at .find (done ); 8345if (it != part_at .end ())parts = std::move (it -> second ); 8346part_at .erase (part_at .begin (),part_at .upper_bound (done )); 8347 } 8348bool complete = parts .size ()== stages .size ()+ 1 ; 8349for (const ConvCheckpoint & k :parts )complete = complete && !k .gdn .empty (); 8350saved = !complete || checkpoint_at (done ,& parts );// an incomplete set: no checkpoint here 8351 }else { 8352saved = checkpoint_at (done ,nullptr ,tail_checkpoint && !periodic_checkpoint ); 8353 } 8354if (!saved ) { 8355// #3350: only a GPU that is unwell ends the request; a copy that ran out of memory skips this checkpoint 8356if (!ckpt_why .empty ()|| !checkpoint_failure_is_survivable ()) { 8357e = "saving a conversation checkpoint failed" + ckpt_why ; 8358return false; 8359 } 8360 std::fprintf (stderr ,"strata serve: checkpoint at %lld skipped: its state could not be copied out (see " 8361"above); the request goes on without it\n" , (long long )done ); 8362 } 8363if (periodic_checkpoint )pp_next_check = done + o .prompt_cache_every ; 8364if (tail_checkpoint )pp_tail_saved = true; 8365 } 8366return true; 8367 }; 8368if (multi_gpu ) {// the batched prompt is reported by its last stage (the drafter's rows are there) 8369stages .back ()-> sp .on_chunk = std::move (sp .on_chunk ); 8370sp .on_chunk = nullptr ; 8371for (size_t i = 0 ;i <=stages .size ();++ i ) { 8372 strata::prefill::Prefill & stage_sp = i == 0 ?sp :stages [i - 1 ]-> sp ; 8373 strata::core::SessionState & stage_ss = i == 0 ?ss :stages [i - 1 ]-> ss ; 8374stage_sp .on_stage_chunk = [& ,i ](int64_t done , std::string & e )-> bool { 8375if (o .prompt_cache <=0 || o .prompt_cache_every <=0 || done < part_next [i ])return true; 8376part_next [i ]= done + o .prompt_cache_every ; 8377ConvCheckpoint part ;// this stage's state at `done` (its stream is synchronized) 8378part .ids .assign (cur .begin (),cur .begin ()+ done ); 8379if (!checkpoint_save (part ,stage_ss ,g )) { 8380// #3350: the copy ran out of memory (not the GPU): leave this part out. The set at `done` is then 8381// incomplete and the checkpoint is skipped below, as for a part that was never made 8382if (!checkpoint_failure_is_survivable ()) {e = "saving a checkpoint part failed" ;return false; } 8383 std::fprintf (stderr ,"strata serve: checkpoint at %lld skipped: stage %zu's state could not be copied " 8384"out (see above); the request goes on without it\n" , (long long )done ,i ); 8385 std::lock_guard < std::mutex > lk (part_mu ); 8386part_at [done ].resize (stages .size ()+ 1 );// (marks the set as seen; its empty parts make it incomplete) 8387return true; 8388 } 8389 std::lock_guard < std::mutex > lk (part_mu ); 8390auto & v = part_at [done ]; 8391v .resize (stages .size ()+ 1 ); 8392v [i ]= std::move (part ); 8393return true; 8394 }; 8395 } 8396 } 8397drive .d .plan = ver .plan_sink (); 8398drive .d .pcie_num = std::max (0 , std::min (256 , (int ) (o .pcie_frac * 256.0 + 0.5 ))); 8399const bool all_experts_resident = !host_res .empty ()&& 8400 std::all_of (host_res .begin (),host_res .end (), [](int32_t r ) {return r >=0 ; }); 8401if (o .adapt_every > 0 && o .adapt_swaps > 0 && !all_experts_resident ) 8402drive .d .usage .assign ((size_t ) (g .n_layers * g .n_expert ),0.0f ); 8403PcieAuto pcie_auto ; 8404if (o .pcie_frac_auto && !all_experts_resident && o .batch == 0 && n_stages == 1 ) { 8405const auto & pl = strata::kernels::cpu::expert_layout (); 8406double sum = 0.0 ; 8407for (int64_t l = 0 ;l < g .n_layers ;++ l )sum += (double )pl .blob_bytes (l ); 8408pcie_auto .on = true; 8409pcie_auto .link_gbps = o .pcie_probe_gbps ; 8410pcie_auto .blob_bytes = g .n_layers > 0 ?sum / (double )g .n_layers :0.0 ; 8411 } 8412auto pcie_auto_step = [& ](double & req_pcie_frac ) { 8413if (!pcie_auto .on )return ; 8414double tc_us = 0.0 ,rate = 0.0 ; 8415const double nf = req_pcie_frac == o .pcie_frac 8416 ?pcie_auto .window (drive .d .ms_run ,drive .d .multi_misses ,o .pcie_frac ,& tc_us ,& rate ) 8417 : (pcie_auto .mark (drive .d .ms_run ,drive .d .multi_misses ),-1.0 ); 8418if (nf < 0.0 )return ; 8419 std::fprintf (stderr ,"strata serve: PCIe share: the CPU pool takes %.0f us per missed expert (%.1f GB/s of expert bytes), " 8420"the link %.1f GB/s -> pcie_frac %.2f (was %.2f; --pcie-frac N fixes it)\n" , 8421tc_us ,rate ,pcie_auto .link_gbps ,nf ,o .pcie_frac ); 8422o .pcie_frac = nf ; 8423req_pcie_frac = nf ; 8424drive .d .pcie_num = std::max (0 , std::min (256 , (int ) (nf * 256.0 + 0.5 ))); 8425 }; 8426if (sycl_mirror_adapt ())ver .set_expert_usage_counter (& drive .d .usage ); 8427// #477 --expert-profile-save: what the adaptive tier learned, kept across restarts (opt-in; off: `heat` stays 8428// empty and nothing below runs). It needs the adaptive tier's counts and the residency table. 8429 std::vector < double > heat ; 8430if (!o .expert_profile_save .empty ()&& !all_experts_resident ) { 8431if (usage_dev_srv != nullptr ) { 8432// the device plan's routing counts (STRATA_VERIFY_NO_HOST): read when the profile is written 8433 }else if (drive .d .usage .empty ()|| host_res .empty ()) 8434 std::fprintf (stderr ,"strata serve: --expert-profile-save needs the adaptive tier (--adapt-every and " 8435"--adapt-swaps above 0) and --expert-profile: nothing will be saved\n" ); 8436else 8437heat .assign (drive .d .usage .size (),0.0 ); 8438 } 8439Clock ::time_point profile_saved_at = Clock ::now (); 8440 dpct::queue_ptr adapt_stream = & dpct::get_in_order_queue (); 8441/* 8442DPCT1025: The SYCL queue is created ignoring the flag and priority 8443options. 8444*/ 8445if (DPCT_CHECK_ERROR ( 8446adapt_stream = dpct::get_current_device ().create_queue (true))!= 84470 ) { 8448 std::fprintf (stderr ,"strata serve: cannot create the refill stream\n" ); 8449return 1 ; 8450 } 8451// plan v0.3 P6: swaps in flight - (residency index, slot) admitted when adapt_ev has completed 8452 std::vector < std::pair < int32_t ,int32_t >> pending ; 8453int pending_age = 0 ;// the windows the pending swaps have waited (adapt_lag) 8454 std::vector < void *> pin_live ;// the swaps' locked arena pages (pin_blob), unlocked once they have landed 8455 dpct::event_ptr adapt_ev = nullptr ; 8456adapt_ev = new sycl::event (); 8457// a layer split's later stages keep a copy of the residency table on their devices, and swap on their own 8458auto res_upload = [& ]() { 8459try { 8460if (d_res != nullptr ) 8461res_put (d_res ); 8462for (auto & st :stages ) { 8463const strata::core::OnDevice on (st -> dev ); 8464res_put (st -> d_res ); 8465 } 8466 } 8467catch (sycl::exception const & exc ) { 8468 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 8469 <<", line:" <<__LINE__ << std::endl ; 8470 std::exit (1 ); 8471 } 8472 }; 8473auto apply_pending = [& ](bool wait ) { 8474try { 8475if (peer .valid ())peer .apply_pending (wait ); 8476if (pending .empty ())return ; 8477if (wait )adapt_ev -> wait_and_throw (); 8478else if (adapt_ev -> get_info < 8479 sycl::info::event::command_execution_status > ()!= 8480 sycl::info::event_command_status::complete )return ; 8481for (auto & st :stages ) 8482if (st -> adapt_live ) { 8483if (wait )st -> adapt_ev -> wait_and_throw (); 8484else if ((st -> adapt_ev ) 8485-> get_info < sycl::info::event:: 8486command_execution_status > ()!= 8487 sycl::info::event_command_status::complete )return ; 8488 } 8489for (auto & st :stages )st -> adapt_live = false; 8490unpin_blobs (pin_live ); 8491src .commit_exchanges ();// the resident RAM mode: the evicted experts take their places in RAM 8492for (const auto & [i ,slot ] :pending ) { 8493host_res [(size_t )i ]= slot ; 8494srcp -> release ((int64_t )i /g .n_expert , (int64_t )i %g .n_expert );// in VRAM now: RAM not needed 8495 } 8496pending .clear (); 8497pending_age = 0 ; 8498res_upload (); 8499 } 8500catch (sycl::exception const & exc ) { 8501 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 8502 <<", line:" <<__LINE__ << std::endl ; 8503 std::exit (1 ); 8504 } 8505 }; 8506// --pipeline-windows: set while the tier adapts beside windows in flight (see its use in adapt) 8507 std::function < void ()> adapt_fence ; 8508// the VRAM tier follows the conversation (the same rule as the speculative loop below) 8509auto adapt = [& ]()-> bool { 8510if (!pending .empty ())return true;// the previous swaps are still in flight 8511if (remote_opt && !remote_opt -> adapt (drive .d .usage ,host_res ,pending ,o .adapt_swaps ,* srcp ))return false; 8512struct Swap {float gain ;int32_t layer ,in ,out ; }; 8513 std::vector < Swap > swaps ; 8514 std::vector < std::pair < float ,int32_t >> cand ,vict ; 8515for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 8516cand .clear (); 8517vict .clear (); 8518const float * u = drive .d .usage .data ()+ l * g .n_expert ; 8519const int32_t * r = host_res .data ()+ l * g .n_expert ; 8520for (int32_t e = 0 ;e < (int32_t )g .n_expert ;++ e ) { 8521if (r [e ]< 0 ) {if (u [e ] >=2.0f && !(peer .valid ()&& peer .has (l ,e ))&& !(remote_opt && remote_opt -> owns (l ,e ))&& !helper_holds (l ,e ))cand .emplace_back (u [e ],e ); } 8522else vict .emplace_back (u [e ],e ); 8523 } 8524if (cand .empty ()|| vict .empty ())continue ; 8525 std::sort (cand .begin (),cand .end (), [](auto & a ,auto & b ) {if (sycl_mirror_adapt ()&& a .first == b .first )return a .second < b .second ;return a .first > b .first ; }); 8526const size_t nc = std::min (cand .size (),vict .size ()); 8527 std::partial_sort (vict .begin (),vict .begin ()+ (ptrdiff_t )nc ,vict .end (), 8528 [](auto & a ,auto & b ) {if (sycl_mirror_adapt ()&& a .first == b .first )return a .second < b .second ;return a .first < b .first ; }); 8529for (size_t i = 0 ;i < nc ;++ i ) { 8530if (cand [i ].first < vict [i ].first + 1.5f )break ; 8531swaps .push_back ({cand [i ].first - vict [i ].first , (int32_t )l ,cand [i ].second ,vict [i ].second }); 8532 } 8533 } 8534 std::sort (swaps .begin (),swaps .end (), [](const Swap & a ,const Swap & b ) {if (sycl_mirror_adapt ()&& a .gain == b .gain )return a .layer == b .layer ?a .in < b .in :a .layer < b .layer ;return a .gain > b .gain ; }); 8535if ((int )swaps .size ()> o .adapt_swaps )swaps .resize ((size_t )o .adapt_swaps ); 8536if (sycl_mirror_adapt ()) { 8537 std::string error ; 8538for (const Swap & s :swaps ) { 8539const size_t in = (size_t )s .layer * g .n_expert + s .in ; 8540const size_t out = (size_t )s .layer * g .n_expert + s .out ; 8541const int32_t slot = host_res [out ]; 8542if (host_res [in ] >=0 || slot < 0 || xcache .slot_of (s .layer ,s .out )!= slot || 8543 !gguf_src .exchange_cached_expert (s .layer ,s .in ,s .out ,xcache .device_slot (slot ),adapt_stream ,error )) { 8544 std::fprintf (stderr ,"SYCL mirror adaptive exchange failed: %s\n" ,error .c_str ());return false; 8545 } 8546xcache .replace (s .layer ,s .out ,s .in ); 8547host_res [out ]= strata::core::kNotResident ; 8548host_res [in ]= slot ; 8549 } 8550if (!swaps .empty ()) { 8551 std::vector < unsigned long long > tab (host_res .size (),0ull ); 8552for (int64_t l = 0 ;l < g .n_layers ;++ l )for (int64_t e = 0 ;e < g .n_expert ;++ e ) { 8553const size_t at = (size_t )(l * g .n_expert + e ); 8554if (host_res [at ]< 0 ) { 8555if (!gguf_src .pinned (l ,e )) { std::fprintf (stderr ,"SYCL mirror adaptive mirror complement missing\n" );return false; } 8556tab [at ]= (unsigned long long )gguf_src .device_alias (l ,e ); 8557 }else if (gguf_src .pinned (l ,e )) { 8558 std::fprintf (stderr ,"SYCL mirror adaptive mirror/cache overlap\n" );return false; 8559 } 8560 } 8561 dpct::get_in_order_queue ().memcpy (mirror_table_d ,tab .data (),tab .size ()* 8 ).wait_and_throw (); 8562res_upload (); 8563 } 8564for (float & value :drive .d .usage )value *=o .adapt_decay ; 8565return true; 8566 } 8567// the copies back read the cache of the card that owns each layer (see resident_stage_swaps) 8568auto home_of = [& ](int64_t layer )-> SwapHome { 8569const int stn = multi_gpu ?stage_of (layer ) :0 ; 8570if (stn > 0 ) { 8571GpuStage * gs = stages [(size_t )stn - 1 ].get (); 8572return {& gs -> cache ,gs -> adapt_stream ,gs -> dev }; 8573 } 8574return {& xcache ,adapt_stream ,-1 }; 8575 }; 8576if (!resident_stage_swaps (src ,host_res ,g .n_expert ,swaps ,home_of ))return false; 8577if (pin_blobs_on ()) {// lock the batch's source pages (a file-backed arena on AMD; see pin_blobs) 8578 std::vector < std::pair < uintptr_t ,uintptr_t >> spans ; 8579for (const Swap & s :swaps ) 8580if (const uint8_t * b = srcp -> blob (s .layer ,s .in )) 8581spans .emplace_back ((uintptr_t )b , 8582 (uintptr_t )b + strata::kernels::cpu::expert_layout ().blob_bytes (s .layer )); 8583pin_blobs (std::move (spans ),pin_live ); 8584 } 8585// --pipeline-windows: windows are in flight while the tier adapts. The evicted experts stop being planned 8586// for the GPU first (the pool computes them on the CPU from the rows every layer publishes, see 8587// Verifier::set_always_publish); then every copy into their slots waits until all the work the stages' 8588// streams hold now has completed: any window that may still read those slots was launched before this. 8589 std::vector < int32_t > fenced_slots ; 8590if (adapt_fence && !swaps .empty ()) { 8591for (const Swap & s :swaps ) { 8592const size_t out = (size_t )s .layer * g .n_expert + s .out ; 8593fenced_slots .push_back (host_res [out ]); 8594host_res [out ]= strata::core::kNotResident ; 8595 } 8596 std::atomic_thread_fence (std::memory_order_seq_cst ); 8597adapt_fence (); 8598 } 8599bool main_live = false; 8600// STRATA_DMA_BATCH (F12): the main device's copies as one cudaMemcpyBatchAsync (mode 0: one each) 8601const int dma_mode = multi_gpu ?0 : strata::core::dma_batch_mode (); 8602 std::vector < void *> cp_dst ; 8603 std::vector < const void *> cp_src ; 8604 std::vector < size_t > cp_bytes ; 8605for (size_t si = 0 ;si < swaps .size ();++ si ) { 8606const Swap & s = swaps [si ]; 8607const size_t in = (size_t )s .layer * g .n_expert + s .in ,out = (size_t )s .layer * g .n_expert + s .out ; 8608const int32_t slot = fenced_slots .empty () ?host_res [out ] :fenced_slots [si ]; 8609const uint8_t * b = srcp -> blob (s .layer ,s .in ); 8610const int stn = multi_gpu ?stage_of (s .layer ) :0 ;// the swap stays in the layer's own cache 8611GpuStage * gs = stn > 0 ?stages [(size_t )stn - 1 ].get () :nullptr ; 8612const strata::core::OnDevice on (gs ?gs -> dev :-1 ); 8613if (dma_mode != 0 && slot >=0 && b != nullptr ) { 8614cp_dst .push_back (xcache .device_slot (slot )); 8615cp_src .push_back (b ); 8616cp_bytes .push_back ((size_t ) strata::kernels::cpu::expert_layout ().blob_bytes (s .layer )); 8617main_live = true; 8618host_res [out ]= strata::core::kNotResident ; 8619srcp -> prefetch (s .layer ,s .out ); 8620pending .emplace_back ((int32_t )in ,slot ); 8621continue ; 8622 } 8623if (slot < 0 || b == nullptr || 8624adapt_copy_h2d (gs ?gs -> cache .device_slot (slot ) 8625 :xcache .device_slot (slot ), 8626b , 8627 (size_t )strata::kernels::cpu::expert_layout () 8628 .blob_bytes (s .layer ), 8629gs ?gs -> adapt_stream :adapt_stream )!= 0 ) { 8630 std::fprintf (stderr , 8631"strata serve: adaptive swap copy failed " 8632"(layer %d, slot %d, pinned %d): %s\n" , 8633/* 8634DPCT1009: SYCL reports errors using 8635exceptions and does not use error codes. Please 8636replace the "get_error_string_dummy(...)" with 8637a real error-handling function. 8638*/ 8639/* 8640DPCT1010: SYCL uses exceptions to report 8641errors and does not use the error codes. The 8642cudaGetLastError function call was replaced 8643with 0. You need to rewrite this code. 8644*/ 8645 (int )s .layer , (int )slot , 8646pin_live .empty () ?0 :1 , 8647 dpct::get_error_string_dummy (0 )); 8648return false; 8649 } 8650if (gs )gs -> adapt_live = true; 8651else main_live = true; 8652host_res [out ]= strata::core::kNotResident ;// evicted now: the CPU computes it meanwhile 8653srcp -> prefetch (s .layer ,s .out );// a file-backed arena released its pages: read them back ahead 8654pending .emplace_back ((int32_t )in ,slot );// resident once the copy has landed 8655 } 8656if (!cp_dst .empty ()&& 8657 strata::core::copy_blobs (cp_dst .data (),cp_src .data (), 8658cp_bytes .data (),cp_dst .size (), 8659adapt_stream ,dma_mode )!= 0 ) { 8660 std::fprintf ( 8661stderr , 8662"strata serve: adaptive swap copy failed (batched): %s\n" , 8663/* 8664DPCT1009: SYCL reports errors using exceptions and does 8665not use error codes. Please replace the 8666"get_error_string_dummy(...)" with a real error-handling 8667function. 8668*/ 8669/* 8670DPCT1010: SYCL uses exceptions to report errors and 8671does not use the error codes. The cudaGetLastError function 8672call was replaced with 0. You need to rewrite this code. 8673*/ 8674 dpct::get_error_string_dummy (0 )); 8675return false; 8676 } 8677if (!swaps .empty ()) dpct::sync_barrier (adapt_ev ,adapt_stream ); 8678 (void )main_live ; 8679for (auto & st :stages ) 8680if (st -> adapt_live ) { 8681const strata::core::OnDevice on (st -> dev ); 8682 dpct::sync_barrier (st -> adapt_ev ,st -> adapt_stream ); 8683 } 8684// #477: the routing counted since the start (each count adds up to 1 / (1 - --adapt-decay) over its 8685// decays: the sum is proportional to the routing itself) - only with --expert-profile-save, else `heat` 8686// is empty 8687for (size_t i = 0 ;i < heat .size ();++ i )heat [i ]+= (double )drive .d .usage [i ]; 8688if (peer .valid ()) {// multi-GPU: the peer takes the next most-routed CPU misses 8689 std::vector < int32_t > r0 = host_res ; 8690for (const auto & [i ,slot ] :pending )r0 [(size_t )i ]= slot ;// swapped into the primary already 8691 std::string perr ; 8692if (!peer .adapt (drive .d .usage .data (),r0 .data (), 8693o .peer_adapt_swaps >=0 ?o .peer_adapt_swaps :o .adapt_swaps ,perr )) { 8694 std::fprintf (stderr ,"strata serve: %s\n" ,perr .c_str ()); 8695return false; 8696 } 8697 } 8698for (float & v :drive .d .usage )v *=o .adapt_decay ; 8699return true; 8700 }; 8701// ---- --adapt-async 1: the asynchronous adaptive tier (opt-in; the resident RAM mode, see the checks where 8702// the RAM copy is built). adapt() runs a whole round - choose, copy the evicted slots back with a stream sync, 8703// copy the new experts in from the RAM copy - on a thread the decode loop joins after the draft: ~24 ms every 8704// 4th window with ~90 swaps. Here a round moves through four steps, each started by `adapt_tick` between 8705// windows once the previous step's copies (events) and host work (the job thread) are done: 8706// 1. job: choose (adapt()'s rule, over snapshots of the routing counts and the residency) and copy the 8707// evicted slots back into exchange buffers (D2H), each from the cache of the card that owns its layer; 8708// 2. stage the exchanges and mark the evicted experts non-resident (the CPU reads them from the exchange 8709// buffers from the next window on); job: copy the new experts in (straight from a page-locked RAM copy, 8710// else through a pinned bounce buffer), on the owning card's refill stream; 8711// 3. mark the new experts resident; job: move the evicted blobs into the RAM places the new ones left; 8712// 4. flip the copy's offsets. 8713// A slot is overwritten only after its old expert stopped being planned for the GPU (step 2, between windows, 8714// with the device copies of the residency table uploaded as apply_pending does), and a RAM place only once its 8715// expert is resident (step 3), so no window computes from memory that is changing. A request starts with the 8716// round drained (adapt_tick(true)), before its prompt lends any slot. Not bit-exact run to run: which window 8717// first computes a swapped-in expert on the GPU (which rounds differently from the CPU) depends on when its 8718// copy lands. `j`: the swap's exchange buffer (its copy back) and bounce buffer (a_cap + j). 8719struct ASwap {int32_t layer ,in ,out ,slot ;int home ;int64_t j ;bool exchange ; }; 8720struct AHome { 8721 strata::core::ExpertCache * cache ; dpct::queue_ptr stream ; 8722 dpct::event_ptr ev ; 8723int dev ; 8724bool used ; 8725 }; 8726enum class AState {Idle ,CopyBack ,SwapIn ,Commit }; 8727AState astate = AState ::Idle ; 8728 std::vector < ASwap > aswaps ; 8729 std::vector < float > a_usage ; 8730 std::vector < int32_t > a_res ; 8731int64_t a_win = 0 ,a_last = 0 ,a_rounds = 0 ,a_swapped = 0 ; 8732double a_ms = 0 ;// wall time from a round's start to its flip, summed (the "ms/round" stat) 8733Clock ::time_point a_t0 ; 8734 std::atomic < bool > a_err {false}; 8735 std::vector < AHome > ahomes ;// [0] = CUDA0's cache, [k] = layer split stage k's 8736 std::unique_ptr < JobThread > ajob ; 8737const int64_t a_cap = std::min < int64_t > (o .adapt_swaps ,96 );// as the blocking tier's exchange buffers 8738if (o .adapt_async && !drive .d .usage .empty ()&& src .complement_ready ()&& src .exchange_capacity () >=2 * a_cap ) { 8739ahomes .push_back ({& xcache ,adapt_stream ,adapt_ev ,0 , false}); 8740for (auto & st :stages )ahomes .push_back ({& st -> cache ,st -> adapt_stream ,st -> adapt_ev ,st -> dev , false}); 8741ajob = std::make_unique < JobThread > (); 8742 std::fprintf (stderr ,"strata serve: adaptive tier asynchronous (--adapt-async 1): up to %lld swaps per round, " 8743"a round every %d windows\n" , (long long )a_cap ,o .adapt_every ); 8744 } 8745auto a_flush = [& ]() {// the job's copies: an event after them on every 8746// stream used, submitted now (WDDM) 8747try { 8748for (AHome & h :ahomes ) 8749if (h .used ) { 8750const strata::core::OnDevice on (h .dev ); 8751/* 8752DPCT1024: The original code returned the error code 8753that was further consumed by the program logic. This 8754original code was replaced with 0. You may need to rewrite 8755the program logic consuming the error code. 8756*/ 8757if (DPCT_CHECK_ERROR (dpct::sync_barrier (h .ev ,h .stream ))!= 87580 )a_err = true; 8759 (void )DPCT_CHECK_ERROR (((h .stream )-> ext_oneapi_empty ())); 8760 } 8761 } 8762catch (sycl::exception const & exc ) { 8763 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 8764 <<", line:" <<__LINE__ << std::endl ; 8765 std::exit (1 ); 8766 } 8767 }; 8768auto a_choose = [& ]() {// step 1, on the job thread 8769try { 8770struct C {float gain ;int32_t layer ,in ,out ; }; 8771 std::vector < C > all ; 8772 std::vector < std::pair < float ,int32_t >> cand ,vict ; 8773for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 8774cand .clear (); 8775vict .clear (); 8776const float * u = a_usage .data ()+ l * g .n_expert ; 8777const int32_t * r = a_res .data ()+ l * g .n_expert ; 8778for (int32_t e = 0 ;e < (int32_t )g .n_expert ;++ e ) { 8779if (r [e ]< 0 ) {if (u [e ] >=2.0f && !helper_holds (l ,e ))cand .emplace_back (u [e ],e ); } 8780else vict .emplace_back (u [e ],e ); 8781 } 8782if (cand .empty ()|| vict .empty ())continue ; 8783 std::sort (cand .begin (),cand .end (), [](auto & a ,auto & b ) {return a .first > b .first ; }); 8784const size_t nc = std::min (cand .size (),vict .size ()); 8785 std::partial_sort (vict .begin (),vict .begin ()+ (ptrdiff_t )nc ,vict .end (), 8786 [](auto & a ,auto & b ) {return a .first < b .first ; }); 8787for (size_t i = 0 ;i < nc ;++ i ) { 8788if (cand [i ].first < vict [i ].first + 1.5f )break ; 8789all .push_back ({cand [i ].first - vict [i ].first , (int32_t )l ,cand [i ].second ,vict [i ].second }); 8790 } 8791 } 8792 std::sort (all .begin (),all .end (), [](const C & a ,const C & b ) {return a .gain > b .gain ; }); 8793aswaps .clear (); 8794for (const C & c :all ) { 8795if ((int64_t )aswaps .size () >=a_cap )break ; 8796const int32_t slot = a_res [(size_t )c .layer * g .n_expert + c .out ]; 8797if (slot < 0 )continue ; 8798// an exchange (as resident_stage_swaps): `in` from the RAM copy, `out` held by its slot alone takes its 8799// place there; otherwise `out` is in the copy already (the lend region) or `in` is not (a RAM budget) 8800const bool x = src .has_resident (c .layer ,c .in )&& !src .has_resident (c .layer ,c .out ); 8801aswaps .push_back ({c .layer ,c .in ,c .out ,slot ,multi_gpu ?stage_of (c .layer ) :0 , (int64_t )aswaps .size (),x }); 8802 } 8803for (AHome & h :ahomes )h .used = false; 8804for (const ASwap & w :aswaps ) { 8805if (!w .exchange )continue ; 8806AHome & h = ahomes [(size_t )w .home ]; 8807const strata::core::OnDevice on (h .dev ); 8808/* 8809DPCT1000: Error handling if-stmt was detected but could not 8810be rewritten. 8811*/ 8812/* 8813DPCT1124: cudaMemcpyAsync is migrated to asynchronous 8814memcpy API. While the origin API might be synchronous, it 8815depends on the type of operand memory, so you may need to call 8816wait() on event return by memcpy API to ensure synchronization 8817behavior. 8818*/ 8819if (const dpct::err0 e = DPCT_CHECK_ERROR (h .stream -> memcpy ( 8820src .exchange_buffer (w .j ),h .cache -> device_slot (w .slot ), 8821 (size_t )strata::kernels::cpu::expert_layout () 8822 .blob_bytes (w .layer ))); 8823e != 0 ) { 8824 std::fprintf (stderr , 8825"strata serve: adaptive tier: copy back of " 8826"layer %d slot %d (CUDA%d) failed: %s\n" , 8827/* 8828DPCT1009: SYCL reports errors using 8829exceptions and does not use error codes. Please 8830replace the "get_error_string_dummy(...)" with 8831a real error-handling function. 8832*/ 8833 (int )w .layer , (int )w .slot ,h .dev , 8834 dpct::get_error_string_dummy (e )); 8835/* 8836DPCT1001: The statement could not be removed. 8837*/ 8838a_err = true; 8839 } 8840h .used = true; 8841 } 8842a_flush (); 8843 } 8844catch (sycl::exception const & exc ) { 8845 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 8846 <<", line:" <<__LINE__ << std::endl ; 8847 std::exit (1 ); 8848 } 8849 }; 8850auto a_copy_in = [& ]() {// step 2, on the job thread 8851try { 8852for (AHome & h :ahomes )h .used = false; 8853for (const ASwap & w :aswaps ) { 8854AHome & h = ahomes [(size_t )w .home ]; 8855const size_t nb = (size_t ) strata::kernels::cpu::expert_layout ().blob_bytes (w .layer ); 8856const uint8_t * b = src .pinned (w .layer ,w .in ) ?src .resident_blob (w .layer ,w .in ) :nullptr ; 8857if (b == nullptr ) {// pageable, or not in the RAM copy: through a bounce buffer (an async copy) 8858uint8_t * bb = src .exchange_buffer (a_cap + w .j ); 8859if (bb == nullptr || !src .copy_blob (w .layer ,w .in ,bb )) { 8860 std::fprintf (stderr ,"strata serve: adaptive tier: layer %d expert %d could not be read\n" , 8861 (int )w .layer , (int )w .in ); 8862a_err = true; 8863continue ; 8864 } 8865b = bb ; 8866 } 8867const strata::core::OnDevice on (h .dev ); 8868/* 8869DPCT1000: Error handling if-stmt was detected but could not 8870be rewritten. 8871*/ 8872/* 8873DPCT1124: cudaMemcpyAsync is migrated to asynchronous 8874memcpy API. While the origin API might be synchronous, it 8875depends on the type of operand memory, so you may need to call 8876wait() on event return by memcpy API to ensure synchronization 8877behavior. 8878*/ 8879if (const dpct::err0 e = DPCT_CHECK_ERROR ( 8880h .stream -> memcpy (h .cache -> device_slot (w .slot ),b ,nb )); 8881e != 0 ) { 8882 std::fprintf (stderr , 8883"strata serve: adaptive tier: copy of layer " 8884"%d into slot %d (CUDA%d) failed: %s\n" , 8885/* 8886DPCT1009: SYCL reports errors using 8887exceptions and does not use error codes. Please 8888replace the "get_error_string_dummy(...)" with 8889a real error-handling function. 8890*/ 8891 (int )w .layer , (int )w .slot ,h .dev , 8892 dpct::get_error_string_dummy (e )); 8893/* 8894DPCT1001: The statement could not be removed. 8895*/ 8896a_err = true; 8897 } 8898h .used = true; 8899 } 8900a_flush (); 8901 } 8902catch (sycl::exception const & exc ) { 8903 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 8904 <<", line:" <<__LINE__ << std::endl ; 8905 std::exit (1 ); 8906 } 8907 }; 8908auto a_ready = 8909 [& ](bool wait )-> bool {// the job and its copies are done 8910try { 8911if (wait )ajob -> wait (); 8912else if (!ajob -> idle ())return false; 8913for (AHome & h :ahomes ) 8914if (h .used ) { 8915const strata::core::OnDevice on (h .dev ); 8916if (wait ) { 8917if (DPCT_CHECK_ERROR (h .ev -> wait_and_throw ())!= 0 ) 8918a_err = true; 8919 }else if (const dpct::err0 q = 8920 dpct::sycl_event_query (h .ev ); 8921q == 1 )return false; 8922/* 8923DPCT1001: The statement could not be removed. 8924*/ 8925/* 8926DPCT1000: Error handling if-stmt was detected but could 8927not be rewritten. 8928*/ 8929else if (q != 0 )a_err = true; 8930 } 8931return true; 8932 } 8933catch (sycl::exception const & exc ) { 8934 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 8935 <<", line:" <<__LINE__ << std::endl ; 8936 std::exit (1 ); 8937 } 8938 }; 8939// between windows: `drain` finishes the round in flight and starts none. False when a copy failed. 8940auto adapt_tick = [& ](bool drain )-> bool { 8941if (!ajob )return true; 8942if (!drain )++ a_win ;// one tick per window 8943for (;;) { 8944if (a_err .load ())return false; 8945switch (astate ) { 8946case AState ::Idle : 8947if (drain || a_win - a_last < (int64_t )o .adapt_every )return true; 8948a_last = a_win ; 8949++ a_rounds ; 8950a_t0 = Clock ::now (); 8951a_usage = drive .d .usage ; 8952a_res = host_res ; 8953// #477: the routing counted, as adapt() counts it (--expert-profile-save; else `heat` is empty) 8954for (size_t i = 0 ;i < heat .size ();++ i )heat [i ]+= (double )drive .d .usage [i ]; 8955for (float & v :drive .d .usage )v *=o .adapt_decay ; 8956ajob -> post (a_choose ); 8957astate = AState ::CopyBack ; 8958return true; 8959case AState ::CopyBack : {// step 2: the evicted experts leave the GPU's plan 8960if (!a_ready (drain ))return true; 8961if (a_err .load ())return false; 8962size_t k = 0 ; 8963for (size_t i = 0 ;i < aswaps .size ();++ i ) { 8964const ASwap w = aswaps [i ]; 8965const size_t out = (size_t )w .layer * g .n_expert + w .out ; 8966if (host_res [out ]!= w .slot )continue ;// the table moved since the snapshot: not this one 8967if (w .exchange && !src .stage_exchange (w .layer ,w .in ,w .out ,w .j )) { 8968 std::fprintf (stderr ,"strata serve: adaptive tier: stage_exchange refused layer %d in %d out %d\n" , 8969 (int )w .layer , (int )w .in , (int )w .out ); 8970return false; 8971 } 8972host_res [out ]= strata::core::kNotResident ;// the CPU computes it from the next window on 8973srcp -> prefetch (w .layer ,w .out ); 8974aswaps [k ++ ]= w ; 8975 } 8976aswaps .resize (k ); 8977res_upload (); 8978ajob -> post (a_copy_in ); 8979astate = AState ::SwapIn ; 8980if (!drain )return true; 8981continue ; 8982 } 8983case AState ::SwapIn :// step 3: the new experts are in their slots 8984if (!a_ready (drain ))return true; 8985if (a_err .load ())return false; 8986for (const ASwap & w :aswaps ) { 8987host_res [(size_t )w .layer * g .n_expert + w .in ]= w .slot ; 8988srcp -> release (w .layer ,w .in ); 8989 } 8990res_upload (); 8991a_swapped += (int64_t )aswaps .size (); 8992ajob -> post ([& ] {src .commit_copies (); }); 8993astate = AState ::Commit ; 8994if (!drain )return true; 8995continue ; 8996case AState ::Commit :// step 4 8997if (!a_ready (drain ))return true; 8998if (a_err .load ())return false; 8999src .commit_flip (); 9000a_ms += std::chrono::duration < double , std::milli > (Clock ::now ()- a_t0 ).count (); 9001aswaps .clear (); 9002astate = AState ::Idle ; 9003continue ;// a round due now starts at this same boundary 9004 } 9005 } 9006 }; 9007// #477: write the learned profile (between requests and at QUIT: a prompt's lent slots are back by then). 9008// A swap still in flight counts as done - its expert is resident once the copy lands. `why`: for the log. 9009auto save_profile = [& ](const char * why ) { 9010if (usage_dev_srv != nullptr ) { 9011// The cache and the mirror are fixed (no swaps under NO_HOST), so every pair is ranked by its device 9012// count mixed with the start's ranking (a short conversation must not wipe the prior). 9013const size_t n = (size_t ) (g .n_layers * g .n_expert ); 9014 std::vector < int32_t > uh (n ); 9015 dpct::get_in_order_queue ().memcpy (uh .data (),usage_dev_srv ,n * 4 ).wait (); 9016double total = 0 ; 9017for (int32_t c :uh )total += (double )c ; 9018// prior mass by rank: exponential with lambda 2 (the shipped ranking holds ~70% of the routing in its 9019// first 47% of pairs, section 8 of notes-143-intel), worth `prior_entries` routed entries (800k: about one 150-token x 8 prompt session; 60k lost 36% on a different kind of text, 800k lost 18% and kept +13..19% on the trained kind) 9020const double lam = 2.0 ; 9021double prior_entries = 800000.0 ; 9022if (const char * pe = std::getenv ("STRATA_PROFILE_PRIOR_ENTRIES" ))prior_entries = std::max (0.0 , std::atof (pe )); 9023 std::vector < double > hv (n ,0.0 ); 9024for (size_t i = 0 ;i < n ;++ i )hv [i ]= (double )uh [i ]; 9025for (size_t r = 0 ;r < profile_loaded .size ();++ r ) { 9026const auto [l ,e ]= profile_loaded [r ]; 9027if (l < 0 || l >=g .n_layers || e < 0 || e >=g .n_expert )continue ; 9028const double x = (double )r / (double )n ; 9029hv [(size_t ) (l * g .n_expert + e )]+= prior_entries * lam * std::exp (- lam * x ) / (1.0 - std::exp (- lam )) / (double )n ; 9030 } 9031 std::vector < uint8_t > none (n ,0 ); 9032 std::string e ; 9033const auto ranked = strata::core::rank_learned_profile (g .n_layers ,g .n_expert ,none ,hv ,profile_loaded ); 9034if (strata::core::write_expert_profile (o .expert_profile_save ,g .n_layers ,g .n_expert ,ranked ,e )) 9035 std::fprintf (stderr ,"strata serve: expert profile saved to %s (%s, %.0f routed entries counted on the device)\n" , 9036o .expert_profile_save .c_str (),why ,total ); 9037else 9038 std::fprintf (stderr ,"strata serve: the expert profile was not saved: %s\n" ,e .c_str ()); 9039profile_saved_at = Clock ::now (); 9040return ; 9041 } 9042if (heat .empty ())return ; 9043 std::vector < uint8_t > resident (host_res .size (),0 ); 9044for (size_t i = 0 ;i < host_res .size ();++ i )resident [i ]= host_res [i ] >=0 ; 9045for (const auto & p :pending )resident [(size_t )p .first ]= 1 ; 9046if (astate == AState ::SwapIn )// --adapt-async: the same for a round past its step 2 9047for (const ASwap & w :aswaps )resident [(size_t )w .layer * g .n_expert + w .in ]= 1 ; 9048 std::string e ; 9049const auto ranked = strata::core::rank_learned_profile (g .n_layers ,g .n_expert ,resident ,heat , 9050profile_loaded ); 9051if (strata::core::write_expert_profile (o .expert_profile_save ,g .n_layers ,g .n_expert ,ranked ,e )) 9052 std::fprintf (stderr ,"strata serve: expert profile saved to %s (%s)\n" ,o .expert_profile_save .c_str (), 9053why ); 9054else 9055 std::fprintf (stderr ,"strata serve: the expert profile was not saved: %s\n" ,e .c_str ()); 9056profile_saved_at = Clock ::now (); 9057 }; 9058// stdin is read on its own thread, so a STOP line reaches a request that is still running (the client went 9059// away, or pressed Esc): the flag is checked between prompt chunks and between verify windows. 9060// 0.1.44: the reader is detached and may sit in read(2) past QUIT (the server writes more, or closes stdin, while 9061// main returns and the process exits), so what it touches is shared with it, never main's locals: a line or 9062// EOF after QUIT used to lock a destroyed mutex (undefined behaviour; an abort on macOS). 9063struct StdinShared { 9064 std::atomic < bool > stop_req {false}; 9065 std::mutex mu ; 9066 std::condition_variable cv ; 9067 std::deque < std::string > lines ; 9068bool eof = false; 9069 }; 9070const auto in_shared = std::make_shared < StdinShared > (); 9071 std::atomic < bool >& stop_req = in_shared -> stop_req ; 9072 std::mutex & in_mu = in_shared -> mu ; 9073 std::condition_variable & in_cv = in_shared -> cv ; 9074 std::deque < std::string >& in_lines = in_shared -> lines ; 9075bool & in_eof = in_shared -> eof ; 9076 std::thread ([st = in_shared ] { 9077// read(2) on the descriptor, not std::cin: glibc's exit() flushes every stdio stream and waits for 9078// stdin's lock, which getline holds while it waits for input - an engine ending on an error (every 9079// std::exit) would hang in exit() on Linux, and the server would wait for it forever 9080 std::string l ,buf ; 9081char chunk [4096 ]; 9082auto getline_fd = [& ](std::string & out )-> bool { 9083for (;;) { 9084const size_t nlpos = buf .find ('\n' ); 9085if (nlpos != std::string::npos ) { 9086out .assign (buf ,0 ,nlpos ); 9087buf .erase (0 ,nlpos + 1 ); 9088return true; 9089 } 9090#if defined(_WIN32 ) 9091const int n = _read (0 ,chunk , (unsigned )sizeof chunk ); 9092#else 9093const ssize_t n = ::read (0 ,chunk ,sizeof chunk ); 9094if (n < 0 && errno == EINTR )continue ; 9095#endif 9096if (n <=0 ) { 9097if (buf .empty ())return false; 9098out .swap (buf ); 9099buf .clear (); 9100return true; 9101 } 9102buf .append (chunk , (size_t )n ); 9103 } 9104 }; 9105while (getline_fd (l )) { 9106if (!l .empty ()&& l .back ()== '\r' )l .pop_back (); 9107if (l == "STOP" ) {st -> stop_req .store (true);continue ; } 9108 std::lock_guard < std::mutex > lk (st -> mu ); 9109st -> lines .push_back (l ); 9110st -> cv .notify_one (); 9111 } 9112 std::lock_guard < std::mutex > lk (st -> mu ); 9113st -> eof = true; 9114st -> cv .notify_one (); 9115 }).detach (); 9116auto next_line = [& ](std::string & out )-> bool { 9117 std::unique_lock < std::mutex > lk (in_mu ); 9118in_cv .wait (lk , [& ] {return !in_lines .empty ()|| in_eof ; }); 9119if (in_lines .empty ())return false; 9120out = std::move (in_lines .front ()); 9121in_lines .pop_front (); 9122return true; 9123 }; 9124sp .should_stop = [& ] {return stop_req .load (); }; 9125// STRATA_TRACE=1: one stderr line per step of a request (the log shows where a request stops) 9126const bool trace = std::getenv ("STRATA_TRACE" )!= nullptr ; 9127auto tr = [& ](const char * what ,long long a = -1 ,long long b = -1 ) { 9128if (!trace )return ; 9129 std::fprintf (stderr ,"strata trace: %s %lld %lld\n" ,what ,a ,b ); 9130 std::fflush (stderr ); 9131 }; 9132 { 9133// what is left once everything is allocated: under WDDM a GPU filled to the brim does not fail, it pages - 9134// and a page-in while the verify graph spins on a host flag stalls the request for good 9135size_t free_b = 0 ,total_b = 0 ; 9136/* 9137DPCT1106: 'cudaMemGetInfo' was migrated with the Intel 9138extensions for device information which may not be supported by all 9139compilers or runtimes. You may need to adjust the code. 9140*/ 9141 dpct::get_current_device ().get_memory_info (free_b ,total_b ); 9142// below ~256 MiB a later allocation (a first-used window's buffers, the desktop, another program) can make 9143// the driver page GPU memory, and a verify graph spinning on a host flag then never finishes 9144const int64_t free_mib = (int64_t ) (free_b >>20 ); 9145if (free_mib >=256 ) { 9146 std::fprintf (stderr ,"strata serve: %lld MiB of VRAM free with everything loaded\n" , (long long )free_mib ); 9147rss_probe ("serving" ); 9148 }else if (reserve_adapted ) { 9149// #496: the reserve was already lowered to make the cache fit - a bigger one would leave it no room 9150 std::fprintf (stderr ,"strata serve: WARNING: %lld MiB of VRAM free with everything loaded - this card " 9151"only just fits the model (the VRAM reserve was lowered to %d MiB so the expert " 9152"cache fits): requests may stall. Close other programs that use the GPU, or lower " 9153"--max-context\n" , (long long )free_mib ,o .vram_reserve_mib ); 9154 }else { 9155 std::fprintf (stderr ,"strata serve: %lld MiB of VRAM free with everything loaded - LOW: requests may stall;" 9156" add --vram-reserve-mib %lld to the config's args (or lower --max-context)\n" , 9157 (long long )free_mib , (long long ) (o .vram_reserve_mib + 512 - free_mib )); 9158 } 9159 } 9160// what the server's Monitor tab shows (servers before 0.1.8 skip unknown lines until READY) 9161 { 9162size_t free_b = 0 ,total_b = 0 ; 9163/* 9164DPCT1106: 'cudaMemGetInfo' was migrated with the Intel 9165extensions for device information which may not be supported by all 9166compilers or runtimes. You may need to adjust the code. 9167*/ 9168 dpct::get_current_device ().get_memory_info (free_b ,total_b ); 9169// "Experts in VRAM" is every tier, not one card's. This used to report `xcache` alone, so a layer split 9170// showed CUDA0's cache as if it were the whole GPU's: a 4-GPU 256K run read 3327 experts when the four 9171// cards held 13320, and the Monitor tab was wrong by 4x for every multi-GPU config. The tiers are 9172// disjoint by construction (remote_experts.cpp skips any pair a stage already claimed), so they add. 9173const int64_t slots_primary = (int64_t )xcache .slots (); 9174const int64_t mib_primary = (int64_t ) (xcache .bytes () >>20 ); 9175int64_t slots_all = slots_primary ,mib_all = mib_primary ; 9176for (const auto & st :stages ) { 9177slots_all += (int64_t )st -> cache .slots (); 9178mib_all += (int64_t ) (st -> cache .bytes () >>20 ); 9179 } 9180for (int r = 0 ;r < 3 ;++ r ) 9181if (o .expert_cache_remote [(size_t )r ]> 0 ) { 9182slots_all += remote_experts [(size_t )r ].resident (); 9183mib_all += (int64_t ) (remote_experts [(size_t )r ].gib ()* 1024.0 ); 9184 } 9185 std::printf ("INFO context=%lld kv=%s kv_resident=%lld expert_slots=%lld expert_cache_mib=%lld " 9186"expert_slots_primary=%lld expert_cache_primary_mib=%lld spec=%d " 9187"mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s arena_mib=%lld pool_workers=%d pcie_frac=%.2f " 9188"spec_min_p=%.2f conversation_cache_mib=%lld conversation_cache_slots=%d " 9189"conversation_cache_min_free_mib=%lld tail_role_token=%lld vram_elastic=%d%s engine=" STRATA_VERSION "\n" , 9190 (long long )o .max_context ,o .kv .c_str (), 9191 (long long ) (g .n_qsa_layers ()> 0 && ss .qsa_states [ss .qsa_primary ()].kv_mode == 1 9192 ?ss .qsa_states [ss .qsa_primary ()].n_slots * 4 :0 ), 9193 (long long )slots_all , (long long )mib_all , 9194 (long long )slots_primary , (long long )mib_primary , 9195o .spec ,o .mtp_max_t , 9196o .suffix_draft , (long long ) (free_b >>20 ),cvec_summary .c_str (), 9197 (long long ) ((o .mmap_experts ?src .resident_bytes () : strata::kernels::cpu::expert_layout ().total ) >>20 ), 9198pool .workers (),o .pcie_frac , 9199o .spec_min_p , (long long )o .conversation_cache_mib ,o .conversation_cache_slots , 9200 (long long )o .conversation_cache_min_free_mib , (long long )o .tail_role_token ,xcache .segmented () ?1 :0 , 9201o .batch > 0 ? (" batch_slots=" + std::to_string (o .batch )+ 9202" batch_groups=" + std::to_string (o .batch_groups > 0 ?o .batch_groups :1 )+ 9203" slot_cache=" + std::to_string (o .prompt_cache > 0 ?1 :0 )).c_str () :"" ); 9204 } 9205// issue #29: a request whose heartbeat (tokens, prompt chunks, verify windows) stops for this long is stuck on 9206// a flag nobody will raise - end the engine with where it was, so the server starts it again instead of the 9207// GPU spinning forever. STRATA_WATCHDOG_S=0 turns it off. Issue #31: before it does, it reports what every 9208// part was doing (stall_report), so one occurrence says where the wait is. 9209 { 9210const char * ws = std::getenv ("STRATA_WATCHDOG_S" ); 9211const int limit = ws ? std::atoi (ws ) :60 ;// one step (a prompt layer, a verify window) takes seconds 9212if (limit > 0 ) 9213 std::thread ([limit ] { 9214 strata::core::Progress & p = strata::core::progress (); 9215uint64_t last = p .beats .load (),ticks_at = p .ticks .load (); 9216auto since = std::chrono::steady_clock::now (); 9217for (;;) { 9218 std::this_thread::sleep_for (std::chrono::seconds (1 )); 9219const auto now = std::chrono::steady_clock::now (); 9220const uint64_t b = p .beats .load (); 9221if (!p .busy .load ()|| b != last ) {last = b ;ticks_at = p .ticks .load ();since = now ;continue ; } 9222if (now - since < std::chrono::seconds (limit ))continue ; 9223// a blocking step's explicit allowance (session files): still within it, not yet stuck 9224if (strata::core::progress_now_ms ()< p .allow_until_ms .load ())continue ; 9225 std::fprintf (stderr ,"strata serve: no progress for %d s during a request (%s) - stopping " 9226"the engine so the server starts it again (issue #29)\n" , 9227limit ,stage_text ().c_str ()); 9228stall_report (stderr ,p .ticks .load ()- ticks_at ); 9229 strata::core::release_gpu_waits (stderr );// #267: no spin kernel outlives the process 9230 std::fflush (stderr ); 9231 std::abort (); 9232 } 9233 }).detach (); 9234 } 9235 strata::uc_probe ("ready" ); 9236 std::printf ("READY %lld stop\n" , (long long )o .max_context );// "stop": this engine honours STOP 9237 std::fflush (stdout ); 9238 std::string line ; 9239int64_t rounds = 0 ; 9240const int S = o .spec ; 9241const int S_mtp = o .mtp_max_t > 0 ? std::min (o .mtp_max_t ,S ) :S ;// the MTP's windows; suffixes go up to S 9242if (use_mtp && S_mtp < S )mtp .set_max_drafts (S_mtp - 1 ); 9243// --pipeline-windows 2 loads the drafter with 8 rows: the serial loop's chain keeps its own length 9244else if (use_mtp && mtp .max_t ()> S_mtp )mtp .set_max_drafts (S_mtp - 1 ); 9245 strata::spec::SuffixDrafter sfx (std::max (1 ,o .suffix_draft ),64 , (size_t )o .max_context + 4096 ); 9246 strata::spec::DraftPolicy policy (S );// MTP or lookup window, learned over the whole process 9247// The vision path (--vision): GENI <max_new> <embeddings file> <id,id,...> carries images. The file is one 9248// or more strata-vision records (int32 'SVE1', n, nx, ny, n_embd, then n x n_embd floats) in prompt order; 9249// each image's rows go to its run of <|image_pad|> tokens, whose M-RoPE positions are mtmd's: t = p, 9250// h = p + y, w = p + x, and the text after the image continues at p + max(nx, ny). 9251constexpr int64_t kImagePad = 248056 ;// qwen4exp.ple.image_token_id: the PLE hash reads it for image cells 9252bool mrope_identity = true; 9253 std::vector < float > img_rows ; 9254 std::vector < const float *> row_ptr ; 9255// ---- #533: VRAM <reserve_mib>, between requests, only with --vram-elastic. It shrinks the expert cache 9256// until that much VRAM is free for other programs (a game, a CAD session), or grows it back towards its full 9257// size when more than that is free. Never on its own: only this command (the server's POST /v1/vram) moves 9258// it. A shrink gives back the cache's LAST segments: the experts in their slots become CPU misses, as any 9259// expert outside the cache is (no output changes beyond what a smaller cache decodes), the prompt path's 9260// loan moves down to the end of what is left (a smaller chunk when it no longer fits). A grow maps them 9261// again and puts each slot's expert back (or, when the adaptive tier already brought that one back, the 9262// most-routed missing expert of the same layer); the adaptive tier carries on from there. 9263 std::vector < std::pair < int32_t ,int32_t >> vram_evicted ;// (residency index, slot) the shrinks took 9264const int64_t chunk_full = o .prefill_chunk ;// the loan's chunk with the whole cache 9265auto relend = [& ]() {// the prompt path's loan: the end of the slots left, its chunk as large as fits 9266if (pf_parts .empty ()|| pf_parts [0 ].first < 0 )return ; 9267PfPart & p = pf_parts [0 ]; 9268const int64_t live = xcache .slots (); 9269auto fits = [& ](int64_t c ) { 9270const int64_t k = part_slots (p ,c ); 9271return k > 0 && k + 128 <=live && !(o .prefill_auto && k * 100 > kAutoLendPct * live ); 9272 }; 9273int64_t c = chunk_full ; 9274while (c > 256 && !fits (c ))c = std::max < int64_t > (256 ,c /2 /256 * 256 ); 9275o .prefill_chunk = c ; 9276p .first = (int32_t ) std::max < int64_t > (0 ,live - part_slots (p ,c )); 9277p .first_now = -1 ;// laid out again at the next loan 9278 }; 9279auto vram_command = [& ](const std::string & cmd , 9280 std::string & e )-> bool { 9281// `VRAM` alone: the reserve the engine started with (--vram-reserve-mib) 9282try { 9283char * end = nullptr ; 9284const bool bare = cmd .find_first_not_of (' ' ,4 )== std::string::npos ; 9285const long long reserve = bare ? (long long )o .vram_reserve_mib : std::strtoll (cmd .c_str ()+ 4 ,& end ,10 ); 9286if (!bare && (end == cmd .c_str ()+ 4 || reserve < 0 )) {e = "expected: VRAM [reserve_mib]" ;return false; } 9287if (!xcache .segmented ()) { 9288e = "VRAM needs an engine started with --vram-elastic (one NVIDIA GPU, --serve)" ; 9289return false; 9290 } 9291if (src .complement_ready ()) { 9292e = "VRAM: not with the resident low-RAM mode (the cache holds experts RAM does not)" ; 9293return false; 9294 } 9295if (peer .valid ()) {e = "VRAM: not with --peer-device" ;return false; } 9296for (const PfPart & p :pf_parts ) 9297if (!p .lent .empty ()) {e = "VRAM: a prompt's loan is still out" ;return false; } 9298if (!ver .wait_commit (e ))return false; 9299apply_pending (true);// the adaptive tier's swaps in flight land first 9300if (DPCT_CHECK_ERROR ( 9301 dpct::get_current_device ().queues_wait_and_throw ())!= 0 ) { 9302/* 9303DPCT1009: SYCL reports errors using exceptions and does not 9304use error codes. Please replace the 9305"get_error_string_dummy(...)" with a real error-handling 9306function. 9307*/ 9308/* 9309DPCT1010: SYCL uses exceptions to report errors and does 9310not use the error codes. The cudaGetLastError function call was 9311replaced with 0. You need to rewrite this code. 9312*/ 9313e = std::string ("VRAM: " )+ dpct::get_error_string_dummy (0 ); 9314return false; 9315 } 9316const auto t0 = Clock ::now (); 9317size_t free_b = 0 ,total_b = 0 ; 9318/* 9319DPCT1106: 'cudaMemGetInfo' was migrated with the Intel 9320extensions for device information which may not be supported by all 9321compilers or runtimes. You may need to adjust the code. 9322*/ 9323 dpct::get_current_device ().get_memory_info (free_b ,total_b ); 9324const int64_t want_free = (int64_t )reserve <<20 ,mapped = xcache .mapped_bytes (); 9325const int64_t before = xcache .slots (); 9326// what stays at least: the prompt path's smallest loan (256 tokens) and the 128 slots it must leave 9327const int64_t floor_slots = std::min < int64_t > (xcache .full_slots (), 9328128 + (pf_parts .empty ()|| pf_parts [0 ].first < 0 ?0 :part_slots (pf_parts [0 ],256 ))); 9329 std::string note ; 9330if ((int64_t )free_b < want_free ) { 9331const int64_t floor_b = xcache .bytes_of (floor_slots ); 9332int64_t keep = mapped - (want_free - (int64_t )free_b ); 9333if (keep < floor_b ) { 9334keep = floor_b ; 9335note = " (the cache keeps its smallest size: the prompt path's buffers)" ; 9336 } 9337if (!xcache .shrink (keep ,e ))return false; 9338const int64_t live = xcache .slots (); 9339for (size_t i = 0 ;i < host_res .size ();++ i ) 9340if (host_res [i ] >=live ) { 9341vram_evicted .emplace_back ((int32_t )i ,host_res [i ]); 9342host_res [i ]= strata::core::kNotResident ; 9343 } 9344res_upload (); 9345 }else if (mapped < xcache .full_bytes ()) { 9346 std::string gerr ; 9347if (!xcache .grow (mapped + ((int64_t )free_b - want_free ),gerr ))note = " (" + gerr + ")" ; 9348const int64_t live = xcache .slots (); 9349 std::string ferr ; 9350 std::vector < std::pair < int32_t ,int32_t >> keep_out ; 9351for (const auto & [i ,slot ] :vram_evicted ) { 9352if (slot >=live ) {keep_out .emplace_back (i ,slot );continue ; } 9353const int64_t layer = i /g .n_expert ; 9354int64_t pick = i ; 9355if (host_res [(size_t )i ] >=0 ) {// back already (the adaptive tier): the layer's most-routed miss 9356pick = -1 ; 9357float best = -1.0f ; 9358for (int64_t ex = 0 ;ex < g .n_expert ;++ ex ) { 9359const size_t j = (size_t ) (layer * g .n_expert + ex ); 9360if (host_res [j ] >=0 )continue ; 9361const float u = drive .d .usage .empty () ?0.0f :drive .d .usage [j ]; 9362if (u > best ) {best = u ;pick = (int64_t )j ; } 9363 } 9364 } 9365if (pick < 0 )continue ; 9366const uint8_t * b = srcp -> blob (layer ,pick %g .n_expert ); 9367if (b == nullptr || !xcache .fill_slot_queued (slot ,b ,ferr , 9368 (int64_t ) strata::kernels::cpu::expert_layout ().blob_bytes (layer ))) { 9369e = "VRAM: refilling the cache failed: " + ferr ; 9370return false; 9371 } 9372host_res [(size_t )pick ]= slot ; 9373 } 9374vram_evicted .swap (keep_out ); 9375if (!xcache .sync_queued (ferr )) {e = "VRAM: " + ferr ;return false; } 9376res_upload (); 9377 } 9378relend (); 9379/* 9380DPCT1106: 'cudaMemGetInfo' was migrated with the Intel 9381extensions for device information which may not be supported by all 9382compilers or runtimes. You may need to adjust the code. 9383*/ 9384 dpct::get_current_device ().get_memory_info (free_b ,total_b ); 9385 std::fprintf (stderr ,"strata serve: VRAM %lld MiB kept free: the expert cache %lld -> %lld of %lld slots " 9386"(%.2f of %.2f GiB), %lld MiB free now, prompt chunk %lld, in %.0f ms%s\n" , 9387reserve , (long long )before , (long long )xcache .slots (), (long long )xcache .full_slots (), 9388 (double )xcache .mapped_bytes () /1073741824.0 , (double )xcache .full_bytes () /1073741824.0 , 9389 (long long ) (free_b >>20 ), (long long )o .prefill_chunk , 9390 std::chrono::duration < double , std::milli > (Clock ::now ()- t0 ).count (),note .c_str ()); 9391 std::printf ("VRAM reserve_mib=%lld expert_slots=%lld expert_slots_full=%lld expert_cache_mib=%lld " 9392"expert_cache_full_mib=%lld vram_free_mib=%lld prompt_chunk=%lld\n" ,reserve , 9393 (long long )xcache .slots (), (long long )xcache .full_slots (), 9394 (long long ) (xcache .mapped_bytes () >>20 ), (long long ) (xcache .full_bytes () >>20 ), 9395 (long long ) (free_b >>20 ), (long long )o .prefill_chunk ); 9396return true; 9397 } 9398catch (sycl::exception const & exc ) { 9399 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 9400 <<", line:" <<__LINE__ << std::endl ; 9401 std::exit (1 ); 9402 } 9403 }; 9404// ---- --batch: the slots of the batch windows 9405struct BSlot { 9406bool active = false,stop = false; 9407int32_t x = 0 ;///< the token the next window feeds (not yet in the slot's state) 9408 std::array < int32_t , strata::kernels::kVerifyMaxT > draft {};///< the slot's next MTP proposal 9409bool draft_ready = false; 9410int64_t p = 0 ;///< its position 9411int64_t produced = 0 ,max_new = 0 ; 9412Clock ::time_point t0 ; 9413// the slot's own conversation cache: the tokens its sessions hold (the prompt, then every token a window 9414// fed). Kept when the request ends (`cached`), so the next turn of that conversation continues from it 9415// instead of reading its history again (see `slot_source` in the request path). 9416 std::vector < int32_t > ids ; 9417int64_t reply0 = 0 ;///< the index in `ids` where its penalty window starts (the last prompt token; 0 with STRATA_PENALTY_PROMPT=1) 9418int pen_n = 0 ;///< its request's penalty window (penalty_last_n) when it has a repeat / frequency / presence penalty, else 0 9419bool cached = false;///< idle, and its sessions still hold `ids` 9420bool cvec = true;///< the control vector setting `ids` were read with 9421bool img = false;///< the conversation has pictures (never reused from the slot) 9422// the checkpoint its prompt read took at the last turn boundary (the history before the new turn's 9423// header): a client's next turn renders the history again WITHOUT this reply's thinking, so it matches 9424// the slot's tokens only up to there - the slot's K/V up to it plus this state continue from it 9425 std::vector < ConvCheckpoint > checks ; 9426// a prompt read that gave way to a waiting request (BYIELD): `ids` is the part read so far, and the same 9427// request continues from it (the read goes on with the same chunks; `from0`: it had started at token 0) 9428bool partial = false,partial_from0 = false; 9429 }; 9430 std::vector < BSlot > bs ((size_t ) std::max (o .batch ,0 )); 9431// timing of the batch windows since the slots were last all idle (one stderr line then) 9432double bt_run = 0 ,bt_commit = 0 ,bt_emit = 0 ; 9433double bt_wait0 = 0 ,bt_pool0 = 0 ; 9434int64_t bt_miss0 = 0 ,bt_hits0 = 0 ,bt_pcie0 = 0 ; 9435int64_t bt_windows = 0 ,bt_rows = 0 ,bt_tokens = 0 ; 9436Clock ::time_point bt_start = Clock ::now (); 9437int admit_slot = -1 ;///< the slot the request being read will continue in (BGEN) 9438long long admit_max_new = 0 ; 9439auto batch_on = [& ] {for (const BSlot & b :bs )if (b .active )return true;return false; }; 9440auto try_next_line = [& ](std::string & out )-> bool { 9441 std::lock_guard < std::mutex > lk (in_mu ); 9442if (in_lines .empty ())return false; 9443out = std::move (in_lines .front ()); 9444in_lines .pop_front (); 9445return true; 9446 }; 9447// the session a request just left behind (its prompt) -> slot b's sessions, on every stage 9448auto copy_to_slot = [& ](int b ,const std::vector < int32_t > & ids , 9449 std::string & e )-> bool { 9450try { 9451const int64_t upto = (int64_t )ids .size (); 9452for (size_t k = 0 ;k < bslot_ss .size ();++ k ) { 9453 strata::core::SessionState & from = k == 0 ?ss :stages [k - 1 ]-> ss ; 9454 strata::core::SessionState & to = * bslot_ss [k ][(size_t )b ]; 9455const strata::core::OnDevice on_k (k == 0 ?0 :stages [k - 1 ]-> dev ); 9456if (DPCT_CHECK_ERROR ( 9457 dpct::get_current_device ().queues_wait_and_throw ())!= 94580 ) { 9459e = "batch admission: device sync failed" ;return false; 9460 } 9461 strata::core::ConversationCheckpoint ck ; 9462ck .ids = ids ; 9463if (!strata::core::conversation_checkpoint_save (ck ,from ,g ,e )|| 9464 !strata::core::conversation_checkpoint_restore (ck ,to ,g ,e )) 9465return false; 9466for (int64_t j = 0 ;j < from .qsa_alloc ;++ j ) { 9467 strata::core::ConversationKv img ; 9468if (!strata::core::conversation_kv_save (img ,from .qsa_states [from .qsa_ord0 + j ],g ,upto , true,e )) 9469return false; 9470if (DPCT_CHECK_ERROR (dpct::get_current_device () 9471 .queues_wait_and_throw ())!= 0 ) { 9472e = "batch admission: device sync failed" ;return false; 9473 } 9474if (!strata::core::conversation_kv_restore (img ,to .qsa_states [to .qsa_ord0 + j ],g ,upto , true,e )) 9475return false; 9476 } 9477if (DPCT_CHECK_ERROR ( 9478 dpct::get_current_device ().queues_wait_and_throw ())!= 94790 ) { 9480e = "batch admission: device sync failed" ;return false; 9481 } 9482 } 9483if (batch_mtp ) { 9484// Admission first builds the solo draft KV; copy it into the slot before drafting. 9485 strata::core::ConversationKv image ; 9486if (!mtp .idle (e )|| !slot_mtp [(size_t )b ]-> idle (e )|| 9487 !strata::core::conversation_kv_save (image ,mtp .kv_state (), 9488draft_geometry ,upto , 9489 false,e )|| 9490 !strata::core::conversation_kv_restore ( 9491image ,slot_mtp [(size_t )b ]-> kv_state (),draft_geometry , 9492upto , false,e )|| 9493DPCT_CHECK_ERROR ( 9494 dpct::get_current_device ().queues_wait_and_throw ())!= 94950 ) 9496return false; 9497slot_mtp [(size_t )b ]-> set_prompt_len (upto ); 9498 } 9499return true; 9500 } 9501catch (sycl::exception const & exc ) { 9502 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 9503 <<", line:" <<__LINE__ << std::endl ; 9504 std::exit (1 ); 9505 } 9506 }; 9507// slot b's sessions -> the main ones (the reverse of copy_to_slot): a request that continues the 9508// conversation an idle slot holds reads on from there. Every stage, the same calls. 9509// `at`: one of the slot's checkpoints - only the K/V up to it is copied and its state restored instead 9510auto copy_from_slot = [& ](int b ,const ConvCheckpoint * at , 9511 std::string & e )-> bool { 9512// the main session's K/V is replaced by the slot's: K/V retained from a restore described the old one 9513conversations .take_reuse (); 9514try { 9515const int64_t upto = at != nullptr ? (int64_t )at -> ids .size () 9516 : (int64_t )bs [(size_t )b ].ids .size (); 9517if (at != nullptr && at -> stage_parts .size ()!= stages .size ()) {e = "a checkpoint without its stage parts" ;return false; } 9518for (size_t k = 0 ;k < bslot_ss .size ();++ k ) { 9519 strata::core::SessionState & from = * bslot_ss [k ][(size_t )b ]; 9520 strata::core::SessionState & to = k == 0 ?ss :stages [k - 1 ]-> ss ; 9521const strata::core::OnDevice on_k (k == 0 ?0 :stages [k - 1 ]-> dev ); 9522if (DPCT_CHECK_ERROR ( 9523 dpct::get_current_device ().queues_wait_and_throw ())!= 95240 ) { 9525e = "batch slot restore: device sync failed" ;return false; 9526 } 9527if (at != nullptr ) { 9528if (!strata::core::conversation_checkpoint_restore (k == 0 ?* at :at -> stage_parts [k - 1 ],to ,g ,e )) 9529return false; 9530 }else { 9531 strata::core::ConversationCheckpoint ck ; 9532ck .ids = bs [(size_t )b ].ids ; 9533if (!strata::core::conversation_checkpoint_save (ck ,from ,g ,e )|| 9534 !strata::core::conversation_checkpoint_restore (ck ,to ,g ,e )) 9535return false; 9536 } 9537for (int64_t j = 0 ;j < from .qsa_alloc ;++ j ) { 9538 strata::core::ConversationKv img ; 9539if (!strata::core::conversation_kv_save (img ,from .qsa_states [from .qsa_ord0 + j ],g ,upto , true,e )) 9540return false; 9541if (DPCT_CHECK_ERROR (dpct::get_current_device () 9542 .queues_wait_and_throw ())!= 0 ) { 9543e = "batch slot restore: device sync failed" ; 9544return false; 9545 } 9546if (!strata::core::conversation_kv_restore (img ,to .qsa_states [to .qsa_ord0 + j ],g ,upto , true,e )) 9547return false; 9548 } 9549if (DPCT_CHECK_ERROR ( 9550 dpct::get_current_device ().queues_wait_and_throw ())!= 95510 ) { 9552e = "batch slot restore: device sync failed" ;return false; 9553 } 9554 } 9555if (batch_mtp ) { 9556// A returning solo request resumes from its slot's draft KV. 9557 strata::core::ConversationKv image ; 9558if (!slot_mtp [(size_t )b ]-> idle (e )|| !mtp .idle (e )|| 9559 !strata::core::conversation_kv_save ( 9560image ,slot_mtp [(size_t )b ]-> kv_state (),draft_geometry , 9561upto , false,e )|| 9562 !strata::core::conversation_kv_restore ( 9563image ,mtp .kv_state (),draft_geometry ,upto , false, 9564e )|| 9565DPCT_CHECK_ERROR ( 9566 dpct::get_current_device ().queues_wait_and_throw ())!= 95670 ) 9568return false; 9569mtp .set_prompt_len (upto ); 9570 } 9571return true; 9572 } 9573catch (sycl::exception const & exc ) { 9574 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 9575 <<", line:" <<__LINE__ << std::endl ; 9576 std::exit (1 ); 9577 } 9578 }; 9579// What an idle slot holds (the conversation it decoded last: its sessions, its draft K/V and its checkpoints) 9580// goes to the parked conversations before an admission overwrites it. The main session was parked with that 9581// conversation's prompt only (the admission's copy), so the reply the slot decoded lives nowhere else: without 9582// this, the conversation's next turn finds its prompt-read state and reads the whole reply again (measured on 9583// four 200K chats over two slots: 255 of a 256-token reply re-read, and a chat whose copies the cache had 9584// evicted meanwhile read from token 0). Nothing to do when the live main session or a parked conversation 9585// already holds that state (or a continuation of it). 9586// Parking is an optimization like a checkpoint (#3350): a skip and a failed snapshot (a host or device 9587// allocation that ran out) are logged and the slot is overwritten as before. Nothing here ends the request 9588// or the engine. 9589auto park_slot = [& ](int b ) { 9590BSlot & sl = bs [(size_t )b ]; 9591if (!conversations .enabled ()|| sl .active || !sl .cached || sl .img || sl .ids .empty ())return ; 9592auto prefix_of = [& ](const std::vector < int32_t >& whole ) { 9593return whole .size () >=sl .ids .size ()&& std::equal (sl .ids .begin (),sl .ids .end (),whole .begin ()); 9594 }; 9595const bool in_main = live_ok && cvec_cached == sl .cvec && prefix_of (live )&& 9596imgs_below (live_imgs , (int64_t )sl .ids .size ()).empty (); 9597if (in_main || conversations .holds (sl .ids , {},sl .cvec ))return ; 9598if (use_mtp && !batch_mtp ) {// no draft K/V of its own: an image without it would not restore beside the drafter 9599 std::fprintf (stderr ,"strata serve: conversation cache: slot %d not parked before its overwrite (its %zu tokens " 9600"have no per-slot draft K/V without --batch-mtp)\n" ,b ,sl .ids .size ()); 9601return ; 9602 } 9603try { 9604if (DPCT_CHECK_ERROR (dpct::get_current_device ().queues_wait_and_throw ())!= 0 ) { 9605 std::fprintf (stderr ,"strata serve: conversation cache: slot %d not parked before its overwrite (device " 9606"sync failed)\n" ,b ); 9607return ; 9608 } 9609 }catch (sycl::exception const & exc ) { 9610 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ <<", line:" <<__LINE__ << std::endl ; 9611 std::exit (1 ); 9612 } 9613 std::string why ; 9614if (batch_mtp && !slot_mtp [(size_t )b ]-> idle (why )) { 9615 std::fprintf (stderr ,"strata serve: conversation cache: slot %d not parked before its overwrite (%s)\n" , 9616b ,why .c_str ()); 9617return ; 9618 } 9619const size_t n_st = stages .size (); 9620static const std::vector < ImgKey > no_imgs ; 9621ParkSource src {sl .ids ,no_imgs ,sl .checks ,sl .cvec ,* bslot_ss [0 ][(size_t )b ], {}, 9622n_st > 0 || !batch_mtp ?nullptr :& slot_mtp [(size_t )b ]-> kv_state (), 9623batch_mtp && n_st > 0 ?& slot_mtp [(size_t )b ]-> kv_state () :nullptr , false, 9624" from slot " + std::to_string (b )}; 9625for (size_t k = 1 ;k < bslot_ss .size ();++ k )src .stage_sessions .push_back (bslot_ss [k ][(size_t )b ].get ()); 9626try { 9627if (park_source (src ,0 ))return ; 9628// the snapshot failed (the copy's own memory, as in #3350): the slot is not touched, so go on without 9629// the image 9630 std::fprintf (stderr ,"strata serve: conversation cache: slot %d not parked before its overwrite (%s)\n" , 9631b ,err .empty () ?"the snapshot failed" :err .c_str ()); 9632err .clear (); 9633 (void )checkpoint_failure_is_survivable (); 9634 }catch (const std::bad_alloc & ) { 9635 std::fprintf (stderr ,"strata serve: conversation cache: allocation failed; skip parking slot %d\n" ,b ); 9636 } 9637 }; 9638// one batch window over the active slots only (row t is the t-th active slot): an idle slot is not touched, 9639// so it keeps the conversation it holds 9640auto batch_step = [& ]()-> bool { 9641int S = 0 ; 9642int rows [strata::kernels::kVerifyMaxT ]= {}; 9643int32_t tok [strata::kernels::kVerifyMaxT ]= {},outb [strata::kernels::kVerifyMaxT ]= {}; 9644int64_t pos [strata::kernels::kVerifyMaxT ]= {}; 9645int first [strata::kernels::kVerifyMaxT ]= {},active [strata::kernels::kVerifyMaxT ]= {}; 9646static size_t next_slot = 0 ; 9647// Each MTP slot uses two rows; rotate slots when more than four are active. 9648int A = 0 ; 9649for (size_t offset = 0 ;offset < bs .size ()&& S + (batch_mtp ?2 :1 ) <= strata::kernels::kVerifyMaxT ;++ offset ) { 9650const int b = (int ) ((next_slot + offset ) %bs .size ()); 9651if (bs [(size_t )b ].active ) { 9652first [A ]= S ; 9653active [A ++ ]= b ; 9654rows [S ]= b ; 9655tok [S ]= bs [(size_t )b ].x ; 9656pos [S ]= bs [(size_t )b ].p ; 9657++ S ; 9658if (batch_mtp ) { 9659rows [S ]= b ; 9660if (!bs [(size_t )b ].draft_ready ) { 9661err = "batch MTP: a live slot has no draft" ; 9662return false; 9663 } 9664tok [S ]= bs [(size_t )b ].draft [0 ]; 9665pos [S ]= bs [(size_t )b ].p + 1 ; 9666++ S ; 9667 } 9668 } 9669 } 9670if (batch_mtp && A > 0 )next_slot = ((size_t )active [A - 1 ]+ 1 ) %bs .size (); 9671if (S == 0 )return true; 9672const bool was_busy = strata::core::progress ().busy .load (); 9673 strata::core::progress ().busy .store (true); 9674drive .d .layers = 0 ; 9675drive .d .experts = 0 ; 9676drive .d .failed = false; 9677apply_pending (false); 9678if (bt_windows == 0 ) { 9679bt_start = Clock ::now (); 9680bt_wait0 = ver .ms_wait ;bt_pool0 = ver .ms_pool ; 9681bt_miss0 = drive .d .multi_misses ;bt_hits0 = drive .d .cache_hits ;bt_pcie0 = drive .d .pcie_experts ; 9682 } 9683for (int t = 0 ;t < S ;++ t ) {// each penalised slot's reply tail for its penalty window (the verifier builds the rows from it and this window's tokens) 9684const BSlot & ps = bs [(size_t )rows [t ]]; 9685if (ps .pen_n <=0 || (t > 0 && rows [t - 1 ]== rows [t ]))continue ; 9686const int64_t from = std::max < int64_t > (ps .reply0 , (int64_t )ps .ids .size ()- ps .pen_n ); 9687ver .set_slot_history (rows [t ],ps .ids .data ()+ from , (int64_t )ps .ids .size ()- from ); 9688 } 9689const Clock ::time_point w0 = Clock ::now (); 9690if (!ver .run_slot_rows (rows ,S ,tok ,pos ,win_pool_fn ,win_pool_user ,outb ,err )|| drive .d .failed ) { 9691 std::printf ("ERR %s\n" ,drive .d .failed && drive .d .fail ?drive .d .fail :err .c_str ()); 9692return false; 9693 } 9694const Clock ::time_point w1 = Clock ::now (); 9695// Accept the proposal only when the target picked it and there is room to emit both tokens. 9696 std::vector < int > keep (bs .size (),0 ); 9697for (int a = 0 ;a < A ;++ a ) { 9698const int b = active [a ],i = first [a ]; 9699const BSlot & sl = bs [(size_t )b ]; 9700const bool eos = std::find (o .eos_ids .begin (),o .eos_ids .end (), (int64_t )outb [i ])!= o .eos_ids .end (); 9701keep [b ]= batch_mtp && outb [i ]== tok [i + 1 ]&& !eos && !sl .stop && 9702sl .produced + 2 <=sl .max_new && sl .p + 3 <=o .max_context ?2 :1 ; 9703 } 9704if (!(batch_mtp ?ver .commit_slot_prefixes (keep .data (),err ) :ver .commit_slots (err ))) { 9705 std::printf ("ERR %s\n" ,err .c_str ()); 9706return false; 9707 } 9708const Clock ::time_point w2 = Clock ::now (); 9709auto msd = [](Clock ::time_point a0 ,Clock ::time_point b0 ) {return std::chrono::duration < double , std::milli > (b0 - a0 ).count (); }; 9710bt_run += msd (w0 ,w1 ); 9711bt_commit += msd (w1 ,w2 ); 9712++ bt_windows ; 9713for (int a = 0 ;a < A ;++ a )bt_rows += keep [active [a ]]; 9714for (int t = 0 ;t < A ;++ t ) { 9715const int b = active [t ]; 9716BSlot & sl = bs [(size_t )b ]; 9717for (int j = 0 ;j < keep [b ];++ j ) { 9718const int32_t y = outb [first [t ]+ j ]; 9719sl .ids .push_back (tok [first [t ]+ j ]); 9720 std::printf ("BT %d %d\n" ,b , (int )y ); 9721++ sl .produced ; 9722const bool eos = std::find (o .eos_ids .begin (),o .eos_ids .end (), (int64_t )y )!= o .eos_ids .end (); 9723const char * fin = eos ?"stop" :sl .stop ?"cancel" :sl .produced >=sl .max_new ?"length" 9724 :sl .p + 2 > o .max_context ?"length" :nullptr ; 9725if (fin != nullptr ) { 9726const double ms = std::chrono::duration < double , std::milli > (Clock ::now ()- sl .t0 ).count (); 9727 std::printf ("BDONE %d %lld %s %.1f\n" ,b , (long long )sl .produced ,fin ,ms ); 9728sl .active = false; 9729sl .cached = o .prompt_cache > 0 && !sl .img ; 9730break ; 9731 } 9732sl .x = y ; 9733sl .p += 1 ; 9734 } 9735if (batch_mtp && sl .active ) { 9736const size_t stride = (size_t )g .hc * (size_t )g .n_embd ; 9737if (DPCT_CHECK_ERROR (dpct::get_in_order_queue ().memcpy ( 9738slot_mtp_rows [(size_t )b ].get (), 9739ver .final_R_all ()+ (size_t )first [t ]* stride , 97402 * stride * sizeof (float )).wait ())!= 0 || 9741 !slot_mtp [(size_t )b ]-> draft (2 ,outb + first [t ], 9742pos [first [t ]],keep [b ]- 1 , 9743sl .draft .data (),err )) { 9744 std::printf ("ERR batch MTP slot %d: %s\n" ,b ,err .c_str ()); 9745return false; 9746 } 9747sl .draft_ready = true; 9748 } 9749 } 9750 std::fflush (stdout ); 9751bt_emit += msd (w2 ,Clock ::now ()); 9752 strata::core::progress ().busy .store (was_busy ); 9753if (!batch_on ()&& bt_windows > 0 ) { 9754const double w = (double )bt_windows ,wall = msd (bt_start ,Clock ::now ()); 9755const double L = (double )g .n_layers ; 9756 std::fprintf (stderr ,"strata batch: %lld windows, avg %.2f rows, %.2f ms/window = run %.2f (CUDA0 GPU-reach " 9757"wait %.2f + CPU experts %.2f) + commit %.2f + emit %.2f; per layer-window: CPU experts " 9758"%.2f, VRAM hits %.2f, PCIe %.2f; %.1f rows/s over %.0f ms of wall time (admissions " 9759"included)\n" , 9760 (long long )bt_windows ,bt_rows /w , (bt_run + bt_commit + bt_emit ) /w ,bt_run /w , 9761 (ver .ms_wait - bt_wait0 ) /w , (ver .ms_pool - bt_pool0 ) /w ,bt_commit /w ,bt_emit /w , 9762 (drive .d .multi_misses - bt_miss0 ) / (w * L ), (drive .d .cache_hits - bt_hits0 ) / (w * L ), 9763 (drive .d .pcie_experts - bt_pcie0 ) / (w * L ),1000.0 * bt_rows / std::max (wall ,1e-9 ),wall ); 9764for (size_t k = 0 ;k <=stages .size ();++ k ) { 9765const std::string pr = (k == 0 ?ver :stages [k - 1 ]-> ver ).profile_report (); 9766if (!pr .empty ()) std::fprintf (stderr ,"strata batch GPU stages, stage %zu (ms/window):%s\n" ,k + 1 ,pr .c_str ()); 9767 } 9768bt_run = bt_commit = bt_emit = 0 ; 9769bt_windows = bt_rows = bt_tokens = 0 ; 9770 } 9771return true; 9772 }; 9773// ---- --batch-groups: the slot groups pipelined through the stages (--batch-groups G > 1 with a layer split) 9774const int n_pipe = (int )stages .size ()+ 1 ; 9775const bool piped = o .batch > 0 && o .batch_groups > 1 && n_pipe > 1 ; 9776const int GS = piped ?o .batch /o .batch_groups :o .batch ; 9777struct PGroup { 9778bool inflight = false; 9779int stage = 0 ;///< the stage it runs on or waits for 9780int32_t tok [strata::kernels::kVerifyMaxT ]= {}; 9781int64_t pos [strata::kernels::kVerifyMaxT ]= {}; 9782int64_t since = 0 ;///< tick it started waiting (fairness) 9783 }; 9784 std::vector < PGroup > pg ((size_t ) (piped ?o .batch_groups :0 )); 9785 std::vector < int > stage_group ((size_t )n_pipe ,-1 ); 9786int64_t pipe_tick = 0 ,rr = 0 ; 9787auto stage_verifier = [& ](int k )-> strata::core::Verifier & {return k == 0 ?ver :stages [(size_t )k - 1 ]-> ver ; }; 9788auto pipe_inflight = [& ] {for (const PGroup & x :pg )if (x .inflight )return true;return false; }; 9789auto group_active = [& ](int gi ) { 9790for (int t = 0 ;t < GS ;++ t )if (bs [(size_t ) (gi * GS + t )].active )return true; 9791return false; 9792 }; 9793// one turn: serve every running stage, hand finished groups on, start what can start 9794auto pump = [& ](bool may_start )-> bool { 9795++ pipe_tick ; 9796if (bt_windows == 0 && !pipe_inflight ()) { 9797bt_start = Clock ::now (); 9798bt_wait0 = ver .ms_wait ;bt_pool0 = ver .ms_pool ; 9799bt_miss0 = drive .d .multi_misses ;bt_hits0 = drive .d .cache_hits ;bt_pcie0 = drive .d .pcie_experts ; 9800 } 9801for (int k = 0 ;k < n_pipe ;++ k ) { 9802const int gi = stage_group [(size_t )k ]; 9803if (gi < 0 )continue ; 9804 strata::core::Verifier & vk = stage_verifier (k ); 9805const int r = vk .batch_poll (win_pool_fn ,win_pool_user ,err ); 9806if (r < 0 ) { std::printf ("ERR %s\n" ,err .c_str ());return false; } 9807if (r == 0 )continue ; 9808stage_group [(size_t )k ]= -1 ; 9809PGroup & G = pg [(size_t )gi ]; 9810if (k + 1 < n_pipe ) {G .stage = k + 1 ;G .since = pipe_tick ;continue ; } 9811// the last stage: the group's picks 9812const int32_t * outb = vk .batch_out (); 9813for (int t = 0 ;t < GS ;++ t ) { 9814BSlot & sl = bs [(size_t ) (gi * GS + t )]; 9815if (!sl .active )continue ; 9816const int32_t y = outb [t ]; 9817 std::printf ("BT %d %d\n" ,gi * GS + t , (int )y ); 9818++ sl .produced ; 9819++ bt_rows ; 9820const bool eos = std::find (o .eos_ids .begin (),o .eos_ids .end (), (int64_t )y )!= o .eos_ids .end (); 9821const char * fin = eos ?"stop" :sl .stop ?"cancel" :sl .produced >=sl .max_new ?"length" 9822 :sl .p + 2 > o .max_context ?"length" :nullptr ; 9823sl .ids .push_back (sl .x ); 9824if (fin != nullptr ) { 9825const double ms = std::chrono::duration < double , std::milli > (Clock ::now ()- sl .t0 ).count (); 9826 std::printf ("BDONE %d %lld %s %.1f\n" ,gi * GS + t , (long long )sl .produced ,fin ,ms ); 9827sl .active = false; 9828sl .cached = false;// the pipeline's pad rows: a pipelined slot is not reused as a cache 9829 }else { 9830sl .x = y ; 9831sl .p += 1 ; 9832 } 9833 } 9834 std::fflush (stdout ); 9835++ bt_windows ; 9836G .inflight = false; 9837 } 9838// start waiting groups on free stages, the longest waiting first; a new step on stage 0 round-robin 9839for (int k = n_pipe - 1 ;k >=0 ;-- k ) { 9840if (stage_group [(size_t )k ] >=0 )continue ; 9841int pick = -1 ; 9842if (k > 0 ) { 9843for (int gi = 0 ;gi < (int )pg .size ();++ gi ) 9844if (pg [(size_t )gi ].inflight && pg [(size_t )gi ].stage == k && 9845 (pick < 0 || pg [(size_t )gi ].since < pg [(size_t )pick ].since )) 9846pick = gi ; 9847if (pick < 0 )continue ; 9848 }else { 9849if (!may_start )continue ; 9850for (int j = 0 ;j < (int )pg .size ()&& pick < 0 ;++ j ) { 9851const int gi = (int ) ((rr + j ) % (int64_t )pg .size ()); 9852if (!pg [(size_t )gi ].inflight && group_active (gi ))pick = gi ; 9853 } 9854if (pick < 0 )continue ; 9855rr = pick + 1 ; 9856PGroup & G = pg [(size_t )pick ]; 9857for (int t = 0 ;t < GS ;++ t ) { 9858BSlot & sl = bs [(size_t ) (pick * GS + t )]; 9859G .tok [t ]= sl .active ?sl .x :0 ; 9860G .pos [t ]= sl .active ?sl .p :0 ; 9861if (!sl .active )sl .cached = false;// its pad row writes its state 9862 } 9863G .inflight = true; 9864G .stage = 0 ; 9865drive .d .failed = false; 9866apply_pending (false); 9867 } 9868PGroup & G = pg [(size_t )pick ]; 9869 strata::core::progress ().busy .store (true); 9870if (k == 0 ) {// the penalised slots' reply tails for the group's rows (the last stage draws them) 9871for (int t = 0 ;t < GS && t < (int ) strata::kernels::kVerifyMaxT ;++ t ) { 9872const BSlot & ps = bs [(size_t ) (pick * GS + t )]; 9873if (ps .pen_n <=0 )continue ; 9874const int64_t from = std::max < int64_t > (ps .reply0 , (int64_t )ps .ids .size ()- ps .pen_n ); 9875ver .set_slot_history (pick * GS + t ,ps .ids .data ()+ from , (int64_t )ps .ids .size ()- from ); 9876 } 9877 } 9878if (!stage_verifier (k ).batch_launch (pick * GS ,GS ,G .tok ,G .pos ,err )) { 9879 std::printf ("ERR %s\n" ,err .c_str ()); 9880return false; 9881 } 9882stage_group [(size_t )k ]= pick ; 9883 } 9884if (drive .d .failed ) { std::printf ("ERR %s\n" ,drive .d .fail ?drive .d .fail :"the expert pool failed" );return false; } 9885if (!pipe_inflight ()&& !batch_on ()&& bt_windows > 0 ) {// all idle: the timing line, as batch_step 9886const double w = (double )bt_windows ,wall = std::chrono::duration < double , std::milli > (Clock ::now ()- bt_start ).count (); 9887 std::fprintf (stderr ,"strata batch (pipelined, %d groups of %d): %lld group-steps, %lld rows in %.0f ms = " 9888"%.1f rows/s (admissions included)\n" ,o .batch_groups ,GS , (long long )bt_windows , 9889 (long long )bt_rows ,wall ,1000.0 * bt_rows / std::max (wall ,1e-9 )); 9890for (int k = 0 ;k < n_pipe ;++ k ) { 9891const std::string pr = stage_verifier (k ).profile_report (); 9892if (!pr .empty ()) std::fprintf (stderr ,"strata batch GPU stages, stage %d (ms/window):%s\n" ,k + 1 ,pr .c_str ()); 9893 } 9894bt_windows = bt_rows = 0 ; 9895 strata::core::progress ().busy .store (false); 9896 } 9897return true; 9898 }; 9899auto pipe_drain = [& ]()-> bool { 9900while (pipe_inflight ()) 9901if (!pump (false))return false; 9902return true; 9903 }; 9904for (;;) { 9905if (batch_on ()|| (piped && pipe_inflight ())) { 9906if (!try_next_line (line )) { 9907if (!(piped ?pump (true) :batch_step ()))return 1 ; 9908continue ; 9909 } 9910// a request reads its prompt through every stage: the groups in flight finish first 9911if (piped && line .rfind ("BSTOP " ,0 )!= 0 && !pipe_drain ())return 1 ; 9912 }else if (!next_line (line )) { 9913break ; 9914 } 9915// --batch: BSTOP <slot> ends that slot at its next batch window; BGEN <slot> <max_new> ... reads the 9916// request's prompt and first token as a GEN 1, then continues it in that slot 9917if (line .rfind ("BSTOP " ,0 )== 0 ) { 9918const int b = std::atoi (line .c_str ()+ 6 ); 9919if (b >=0 && b < (int )bs .size ())bs [(size_t )b ].stop = true; 9920continue ; 9921 } 9922if (line .rfind ("BYIELD" ,0 )== 0 )continue ;// for a prompt read that has ended meanwhile 9923if (line .rfind ("VRAM" ,0 )== 0 ) {// #533 (above): between requests, not a request 9924 std::string verr ; 9925if (batch_on ())verr = "VRAM: not while batch slots are decoding" ; 9926else vram_command (line ,verr ); 9927if (!verr .empty ()) std::printf ("ERR %s\n" ,verr .c_str ()); 9928 std::fflush (stdout ); 9929continue ; 9930 } 9931admit_slot = -1 ; 9932if (line .rfind ("BGEN " ,0 )== 0 || line .rfind ("BGENI " ,0 )== 0 ) { 9933const bool bimg = line .rfind ("BGENI " ,0 )== 0 ; 9934char * e1 = nullptr ; 9935const long b = std::strtol (line .c_str ()+ (bimg ?6 :5 ),& e1 ,10 ); 9936char * e2 = nullptr ; 9937const long long mn = std::strtoll (e1 ,& e2 ,10 ); 9938if (bs .empty ()|| b < 0 || b >= (long )bs .size ()|| bs [(size_t )b ].active || mn < 1 || e2 == e1 ) { 9939 std::printf ("ERR BGEN: no such free slot (--batch %d) or a bad max_new\n" ,o .batch ); 9940 std::fflush (stdout ); 9941continue ; 9942 } 9943admit_slot = (int )b ; 9944admit_max_new = mn ; 9945line = std::string (bimg ?"GENI 1" :"GEN 1" )+ e2 ; 9946 } 9947// #477: every --expert-profile-save-every minutes, before the next request (at QUIT: after the loop) 9948if ((!heat .empty ()|| usage_dev_srv != nullptr )&& line != "QUIT" && o .expert_profile_save_min > 0 && 9949Clock ::now ()- profile_saved_at >= std::chrono::duration < double > (o .expert_profile_save_min * 60.0 )) 9950save_profile ("periodic" ); 9951if (line == "QUIT" )break ; 9952// the watchdog watches a request from here until this iteration ends, whichever way it ends 9953struct BusyScope { 9954BusyScope () { 9955 strata::core::progress ().allow_until_ms .store (0 ); 9956 strata::core::progress ().busy .store (true); 9957 strata::core::progress_at ("request" ); 9958 } 9959 ~BusyScope () { 9960 strata::core::progress ().busy .store (false); 9961 strata::core::progress ().allow_until_ms .store (0 ); 9962 strata::core::progress_at ("idle" ); 9963 } 9964 }busy_scope ; 9965stop_req .store (false);// a STOP that arrived between requests is stale 9966err .clear (); 9967// Disk sessions: SAVE <path> | RESTORE <path>, between requests (the path runs to the end of the line, 9968// UTF-8). The file holds what a parked conversation holds (conversation_file.hpp). Answers: SAVED / 9969// RESTORED <tokens> <bytes> <ms>; SERR <invalid|storage|memory|io> <published 0|1> <reason> for a refusal 9970// or failure that leaves the engine in step (the live session as it was, unless published=1 says the new 9971// file already replaced the old one); FATAL <reason> (and the engine exits) for a restore transfer that 9972// failed after the device state was touched. On the way: SESSION <done> <total> after every block of 9973// the file moved (at most 16 MiB), and SWAIT <phase> <seconds> before a step that blocks in one call 9974// (fingerprint file, state capture, file flush, rename + folder flush, validation, device transfer): 9975// that step is allowed <seconds> (session_phase_limit_s) by the watchdog and by the server, no more. 9976// (A verifier commit that fails before the command still answers ERR and exits, as for a request.) 9977if (line .rfind ("SAVE " ,0 )== 0 || line .rfind ("RESTORE " ,0 )== 0 ) { 9978const bool save = line [0 ]== 'S' ; 9979const std::string path = line .substr (save ?5 :8 ); 9980const auto t0 = Clock ::now (); 9981auto ms = [& ] {return std::chrono::duration < double , std::milli > (Clock ::now ()- t0 ).count (); }; 9982auto refuse = [& ](const std::string & why , strata::core::SessionError kind = strata::core::SessionError ::invalid , 9983bool published = false) { 9984 std::fprintf (stderr ,"strata serve: session %s %s: %s\n" ,save ?"save" :"restore" ,path .c_str (), 9985why .c_str ()); 9986 std::string one = why ;// one protocol line 9987for (char & c :one )if (c == '\n' || c == '\r' )c = ' ' ; 9988 std::printf ("SERR %s %d %s\n" , strata::core::session_error_name (kind ),published ?1 :0 ,one .c_str ()); 9989 std::fflush (stdout ); 9990err .clear (); 9991 }; 9992auto moving = [& ](uint64_t done ,uint64_t total ) { 9993 strata::core::progress_at (save ?"writing a session file, MiB" :"reading a session file, MiB" , 9994 (int64_t ) (done >>20 )); 9995 strata::core::progress_allow (0 );// a block moved: the ordinary watchdog limit again, and a beat 9996 std::printf ("SESSION %llu %llu\n" , (unsigned long long )done , (unsigned long long )total ); 9997 std::fflush (stdout ); 9998 }; 9999// a step that blocks in one call: its explicit allowance, on both sides, announced before it starts 10000auto blocking = [& ](const char * phase ,uint64_t bytes ) { 10001const int64_t s = strata::core::session_phase_limit_s (bytes ); 10002 strata::core::progress_at (phase ); 10003 strata::core::progress_allow (s ); 10004 std::printf ("SWAIT %s %lld\n" ,phase , (long long )s ); 10005 std::fflush (stdout ); 10006 }; 10007 strata::core::progress_at (save ?"saving a session" :"restoring a session" ); 10008if (path .empty ()) {refuse ("missing path" );continue ; } 10009if (!stages .empty ()|| multi_gpu ) {refuse ("session files do not support --layer-split" );continue ; } 10010if (o .peer_device >=1 ) {refuse ("session files do not support --peer-device" );continue ; } 10011if (o .batch > 0 ) {refuse ("session files do not support --batch (parallel requests)" );continue ; } 10012if (o .prompt_cache <=0 ) {refuse ("session files need --prompt-cache > 0" );continue ; } 10013if (!ver .wait_commit (err )) { 10014 std::printf ("ERR %s\n" ,err .c_str ()); 10015return 1 ; 10016 } 10017 strata::core::SessionFileIdentity id ; 10018try { 10019if (!session_identity (id ,err , [& ] {blocking ("fingerprint" ,2u <<20 ); })) { 10020refuse (err , strata::core::SessionError ::io ); 10021continue ; 10022 } 10023 }catch (const std::bad_alloc & ) { 10024refuse ("session identity: out of memory" , strata::core::SessionError ::memory ); 10025continue ; 10026 }catch (const std::exception & e ) { 10027refuse (std::string ("session identity: " )+ e .what (), strata::core::SessionError ::io ); 10028continue ; 10029 } 10030if (save ) { 10031if (!live_ok || live .empty ()) {refuse ("no complete session to save" );continue ; } 10032size_t bytes = 0 ,kept = 0 ; 10033double capture_ms = 0 ; 10034try { 10035// RAM PREFLIGHT for the save (not a reservation), BEFORE anything is copied: the deepest 10036// checkpoint is chosen by reference, and the copies it will take (the list below and the one 10037// in `meta`), the copied live running state with its tokens and images, the K/V source 10038// directory and the 16 MiB write buffer are asked for above the parking floor. Only the 10039// deepest checkpoint goes to disk (the next turn's resume point); the K/V is streamed from 10040// the authoritative pools straight into the file, without a full host capture. 10041 strata::core::SessionSaveLive sl ; 10042 { 10043 strata::core::ConversationStateSizes z ; 10044 std::string why ; 10045uint64_t state = UINT64_MAX ;// unknown sizes: the preflight refuses rather than guesses 10046if (strata::core::conversation_session_sizes (g ,ss ,z ,why )) { 10047const uint64_t q = (uint64_t ) std::max < int64_t > (ss .qsa_alloc ,0 ); 10048const uint64_t per = (uint64_t )z .tail + z .dead + z .block_pos ; 10049if (q == 0 || per <= (UINT64_MAX - z .gdn - z .ple ) /q )state = z .gdn + z .ple + q * per ; 10050 } 10051sl .state_bytes = state ; 10052sl .tokens = live .size (); 10053sl .images = live_imgs .size (); 10054sl .kv_layers = (uint64_t ) std::max < int64_t > (ss .qsa_alloc ,0 )+ 1 ; 10055 } 10056const uint64_t floor = (uint64_t )o .conversation_cache_min_free_mib <<20 ; 10057auto admit = [& ](uint64_t need , std::string & why ) { 10058const auto avail = strata::core::available_host_bytes (); 10059if (strata::core::conversation_memory_admit (avail ,need ,floor ))return true; 10060why = "not enough RAM to save the session (" + 10061 (need == UINT64_MAX ? std::string ("unknown" ) : std::to_string (need >>20 ))+ 10062" MiB plus a floor of " + std::to_string ((long long )o .conversation_cache_min_free_mib )+ 10063" MiB needed, " + (avail ? std::to_string (* avail >>20 )+ " MiB available)" 10064 :"RAM telemetry unavailable)" ); 10065return false; 10066 }; 10067 std::vector < ConvCheckpoint > disk_checks ; 10068 std::string why ; 10069if (!strata::core::session_save_checkpoints (checks ,sl ,admit ,disk_checks ,why )) { 10070refuse (why , strata::core::SessionError ::memory ); 10071continue ; 10072 } 10073kept = disk_checks .size (); 10074const strata::core::ConversationView view {live ,live_imgs ,disk_checks ,cvec_cached }; 10075 strata::core::SavedConversation meta ; 10076 std::vector < strata::core::SessionKvSource > sources ; 10077// the live running state comes off the device in one synchronous copy 10078blocking ("capture" ,sl .state_bytes == UINT64_MAX ?0 :sl .state_bytes ); 10079if (!strata::core::conversation_snapshot_sources (meta ,sources ,view ,ss ,g ,mtp .kv_state (), 10080err )) { 10081refuse (err , strata::core::SessionError ::io ); 10082continue ; 10083 } 10084capture_ms = ms (); 10085 strata::core::SessionWriteOptions wo ; 10086wo .min_free_bytes = (uint64_t )o .session_min_free_mib <<20 ; 10087wo .progress = moving ; 10088wo .phase = blocking ; 10089 strata::core::SessionStatus st ; 10090if (!strata::core::session_file_write (path ,meta ,sources ,id ,bytes ,err ,wo ,& st )) { 10091refuse (err ,st .error ,st .published ); 10092continue ; 10093 } 10094if (st .dir_flush_unsupported ) 10095 std::fprintf (stderr ,"strata serve: session saved to %s; this filesystem cannot flush a " 10096"folder, so the new name is not flushed\n" ,path .c_str ()); 10097 }catch (const std::bad_alloc & ) { 10098refuse ("not enough RAM to save the session" , strata::core::SessionError ::memory ); 10099continue ; 10100 } 10101 std::fprintf (stderr ,"strata serve: session saved %zu tokens, %zu of %zu checkpoints, %zu bytes to %s " 10102"in %.1f ms (state %.1f ms)\n" ,live .size (),kept ,checks .size (),bytes , 10103path .c_str (),ms (),capture_ms ); 10104 std::printf ("SAVED %zu %zu %.1f\n" ,live .size (),bytes ,ms ()); 10105 }else { 10106 strata::core::SavedConversation image ; 10107size_t bytes = 0 ; 10108try { 10109// bounds this session can ever restore (geometry, layer range, tokens, checkpoints, every 10110// state and K/V part), checked as the file is parsed and before each array is allocated; the 10111// file size follows from them. The RAM the parse needs at its peak is asked first. 10112 strata::core::SessionReadLimits limits ; 10113limits .progress = moving ; 10114const uint64_t floor = (uint64_t )o .conversation_cache_min_free_mib <<20 ; 10115limits .admit = [floor ,& o ](uint64_t need , std::string & why ) { 10116const auto avail = strata::core::available_host_bytes (); 10117if (strata::core::conversation_memory_admit (avail ,need ,floor ))return true; 10118why = "not enough RAM to read it (" + std::to_string (need >>20 )+ " MiB plus a floor of " + 10119 std::to_string ((long long )o .conversation_cache_min_free_mib )+ " MiB needed, " + 10120 (avail ? std::to_string (* avail >>20 )+ " MiB available)" :"RAM telemetry unavailable)" ); 10121return false; 10122 }; 10123if (!strata::core::conversation_session_read_limits ( 10124limits ,ss ,g ,mtp .kv_state (), (uint64_t )o .max_context , 10125 (uint64_t ) std::max (o .prompt_cache ,1 ),err )) { 10126refuse (err , strata::core::SessionError ::io ); 10127continue ; 10128 } 10129 strata::core::SessionStatus st ; 10130if (!strata::core::session_file_read (path ,id ,image ,bytes ,err ,limits ,& st )) { 10131refuse (err ,st .error ); 10132continue ; 10133 } 10134 }catch (const std::bad_alloc & ) { 10135refuse ("not enough RAM to read the session" , strata::core::SessionError ::memory ); 10136continue ; 10137 } 10138const double read_ms = ms (); 10139// the whole image against this engine, still without any device write 10140blocking ("validate" ,bytes ); 10141if (!strata::core::conversation_snapshot_validate (image ,ss ,g ,mtp .kv_state (),err )) { 10142refuse (err ); 10143continue ; 10144 } 10145// the elastic K/V (--kv-grow) maps only the cells it has grown to: make room for the file's cells 10146if (!kvg_ensure ((int64_t )image .live .ids .size ()+ 256 , [& ] { 10147 dpct::get_current_device () 10148 .queues_wait_and_throw (); 10149apply_pending ( 10150 true); })) { 10151refuse ("the K/V cannot grow to the saved conversation: no VRAM is left" , strata::core::SessionError ::memory ); 10152continue ; 10153 } 10154conversations .take_reuse ();// retained K/V described the outgoing session 10155live_ok = false; 10156// host -> device in synchronous copies of the whole state: one bounded allowance 10157blocking ("transfer" ,bytes ); 10158if (strata::core::conversation_snapshot_restore (image ,ss ,g ,mtp .kv_state (),err )!= 10159 strata::core::ConversationRestore ::restored ) { 10160// validated above: a failure here is a transfer failure, after device writes began - never 10161// decode from a partial state; the server starts the engine again 10162 std::fprintf (stderr ,"strata serve: session restore %s: transfer failed: %s\n" ,path .c_str (), 10163err .c_str ()); 10164 std::printf ("FATAL restoring the session file failed after the device state was changed: %s\n" , 10165err .c_str ()); 10166 std::fflush (stdout ); 10167return 1 ; 10168 } 10169live = std::move (image .live .ids ); 10170live_imgs = std::move (image .live .imgs ); 10171checks = std::move (image .checkpoints ); 10172for (const ConvCheckpoint & c :checks )check_clock = std::max (check_clock ,c .used ); 10173cvec_cached = image .cvec ; 10174live_ok = true; 10175 std::fprintf (stderr ,"strata serve: session restored %zu tokens, %zu checkpoints, %zu bytes from %s " 10176"in %.1f ms (read+check %.1f ms)\n" ,live .size (),checks .size (),bytes ,path .c_str (), 10177ms (),read_ms ); 10178 std::printf ("RESTORED %zu %zu %.1f\n" ,live .size (),bytes ,ms ()); 10179 } 10180 std::fflush (stdout ); 10181continue ; 10182 } 10183const bool geni = line .rfind ("GENI " ,0 )== 0 ; 10184if (!geni && line .rfind ("GEN " ,0 )!= 0 ) { 10185 std::printf ("ERR expected: GEN <max_new> <id,id,...> or GENI <max_new> <file> <id,id,...>\n" ); 10186continue ; 10187 } 10188char * endp = nullptr ; 10189const long long max_new = std::strtoll (line .c_str ()+ (geni ?5 :4 ),& endp ,10 ); 10190// optional sampling keys between max_new and the ids: temperature=F, top_p=F, top_k=N, min_p=F, 10191// penalty_last_n=N, penalty_repeat=F, penalty_freq=F, penalty_present=F, seed=N (text requests 10192// only). Absent keys keep today's behavior: greedy, no penalties. 10193float req_temperature = 0.0f ,req_top_p = 1.0f ; 10194int req_top_k = 20 ;// the sampler's own default; the sampled path REQUIRES top_k in 1..64 10195unsigned long long req_seed = 0 ; 10196float req_min_p = 0.0f ,req_penalty_repeat = 1.0f ,req_penalty_freq = 0.0f ,req_penalty_present = 0.0f ; 10197int req_penalty_last_n = 0 ; 10198long long req_pen_from = -1 ;// pen_from=N: this request continues one that began at token N (the last token of the original prompt): the penalty window starts there 10199int req_cvec = 1 ;// cvec=0|1: a loaded control vector for this request (on when absent) 10200// SYCL port: logprobs=K (0..20) - after each "T id" an "LP logprob id:logprob ..." line with the token's 10201// log-probability and the K most likely tokens', from the verify window's head logits (before sampling, 10202// penalties and temperature). -1 (absent): no LP lines; a server that does not ask never sees one. 10203int req_logprobs = -1 ; 10204// allowed=a,b,c: with logprobs, print only these token ids (the server renormalises over them; the same key 10205// the CUDA engine reads). Absent: the K most likely tokens, as before. 10206 std::vector < int32_t > req_allowed ; 10207// ckpt=0: a one-shot call whose turn no later request extends. No checkpoint at its last turn boundary 10208// (so no split there) nor every --prompt-cache-every tokens, and its session is neither continued nor 10209// parked after it. It still resumes from a checkpoint it matches, and still saves the system-prompt root 10210// when that reaches --prompt-cache-root. Absent = checkpointed as before. 10211int req_ckpt = 1 ; 10212// tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of 10213// the missed experts and the draft-probability floor, for this request only 10214// #2228: img_keys=<hex>,<hex>,... (GENI): each picture's key from the server (its normalized bytes' hash), in 10215// prompt order; the conversation cache matches a picture by it and its grid instead of its embedding floats 10216 std::vector < uint64_t > req_img_keys ; 10217double req_pcie_frac = o .pcie_frac ,req_spec_min_p = o .spec_min_p ; 10218if (endp != nullptr ) {// GENI takes the same keys (#75: image requests were always greedy); its 10219// embedding file path is the first token without an = 10220for (;;) { 10221while (* endp == ' ' )++ endp ; 10222const char * start = endp ; 10223while (* endp != '\0' && * endp != ' ' )++ endp ; 10224if (endp == start )break ; 10225const std::string tok (start , (size_t ) (endp - start )); 10226const size_t eq = tok .find ('=' ); 10227if (eq == std::string::npos ) {endp = const_cast < char *> (start );break ; } 10228const std::string key = tok .substr (0 ,eq ); 10229const float fv = std::strtof (tok .c_str ()+ eq + 1 ,nullptr ); 10230if (key == "cvec" )req_cvec = std::atoi (tok .c_str ()+ eq + 1 ); 10231else if (key == "ckpt" )req_ckpt = std::atoi (tok .c_str ()+ eq + 1 )!= 0 ; 10232else if (key == "temperature" )req_temperature = fv ; 10233else if (key == "top_p" )req_top_p = fv ; 10234else if (key == "top_k" )req_top_k = std::atoi (tok .c_str ()+ eq + 1 ); 10235else if (key == "min_p" )req_min_p = fv ; 10236else if (key == "penalty_last_n" )req_penalty_last_n = std::atoi (tok .c_str ()+ eq + 1 ); 10237else if (key == "pen_from" )req_pen_from = std::atoll (tok .c_str ()+ eq + 1 ); 10238else if (key == "penalty_repeat" )req_penalty_repeat = fv ; 10239else if (key == "penalty_freq" )req_penalty_freq = fv ; 10240else if (key == "penalty_present" )req_penalty_present = fv ; 10241else if (key == "seed" )req_seed = std::strtoull (tok .c_str ()+ eq + 1 ,nullptr ,10 ); 10242else if (key == "logprobs" )req_logprobs = std::clamp (std::atoi (tok .c_str ()+ eq + 1 ),-1 ,20 ); 10243else if (key == "allowed" ) { 10244const std::string csv = tok .substr (eq + 1 ); 10245size_t p = 0 ; 10246while (p < csv .size ()) { 10247const size_t c = csv .find ("," ,p ); 10248const std::string one = csv .substr (p ,c == std::string::npos ? std::string::npos :c - p ); 10249if (!one .empty ())req_allowed .push_back ((int32_t ) std::atoi (one .c_str ())); 10250if (c == std::string::npos )break ; 10251p = c + 1 ; 10252 } 10253 } 10254else if (key == "pcie_frac" )req_pcie_frac = std::clamp ((double )fv ,0.0 ,1.0 ); 10255else if (key == "spec_min_p" )req_spec_min_p = std::clamp ((double )fv ,0.0 ,1.0 ); 10256else if (key == "img_keys" ) { 10257req_img_keys .clear (); 10258const char * q = tok .c_str ()+ eq + 1 ; 10259while (* q != '\0' ) { 10260char * qe = nullptr ; 10261const unsigned long long v = std::strtoull (q ,& qe ,16 ); 10262if (qe == q ) {req_img_keys .clear ();break ; } 10263req_img_keys .push_back ((uint64_t )v ); 10264q = * qe == ',' ?qe + 1 :qe ; 10265if (* qe != ',' && * qe != '\0' ) {req_img_keys .clear ();break ; } 10266 } 10267 } 10268// unknown keys are skipped: the ids start at the first token without '=' 10269 } 10270 } 10271 std::string emb_path ; 10272if (geni && endp != nullptr ) { 10273while (* endp == ' ' )++ endp ; 10274char * gap = std::strchr (endp ,' ' ); 10275if (gap != nullptr ) {emb_path .assign (endp , (size_t ) (gap - endp ));endp = gap ; } 10276 } 10277 std::vector < int64_t > ids ; 10278 std::string pe ; 10279if (max_new < 1 || endp == nullptr || (geni && emb_path .empty ())|| !parse_i64_list (endp ,ids ,pe )) { 10280 std::printf ("ERR bad request: %s\n" ,pe .empty () ?"max_new" :pe .c_str ()); 10281continue ; 10282 } 10283const int64_t n = (int64_t )ids .size (); 10284req_imgs .clear (); 10285if (geni && !o .vision ) { std::printf ("ERR this engine was started without --vision\n" );continue ; } 10286if (geni || !mrope_identity ) { 10287// positions for every cell this request can reach; the identity again for a text request 10288 std::string ve ; 10289row_ptr .assign ((size_t )n ,nullptr ); 10290const int64_t cells = (int64_t )mrope_host .size () /3 ; 10291auto put = [& ](int64_t c ,int64_t t ,int64_t h ,int64_t w ) { 10292mrope_host [(size_t )c * 3 ]= (int32_t )t ; 10293mrope_host [(size_t )c * 3 + 1 ]= (int32_t )h ; 10294mrope_host [(size_t )c * 3 + 2 ]= (int32_t )w ; 10295 }; 10296if (!geni ) { 10297for (int64_t c = 0 ;c < cells ;++ c )put (c ,c ,c ,c ); 10298 }else { 10299struct Img {int64_t n ,nx ,ny ;size_t off ; }; 10300 std::vector < Img > imgs ; 10301img_rows .clear (); 10302 std::FILE * f = std::fopen (emb_path .c_str (),"rb" ); 10303if (!f )ve = "cannot open " + emb_path ; 10304while (f && ve .empty ()) { 10305int32_t hdr [5 ]; 10306const size_t got = std::fread (hdr ,sizeof (int32_t ),5 ,f ); 10307if (got == 0 )break ; 10308if (got != 5 || hdr [0 ]!= 0x31455653 || hdr [1 ]< 1 || hdr [2 ]< 1 || hdr [3 ]< 1 || 10309 (int64_t )hdr [2 ]* hdr [3 ]!= hdr [1 ]|| hdr [4 ]!= (int32_t )g .n_embd ) { 10310ve = "bad embeddings file (expected strata-vision records of width " + 10311 std::to_string ((long long )g .n_embd )+ ")" ; 10312break ; 10313 } 10314const size_t off = img_rows .size (),cnt = (size_t )hdr [1 ]* (size_t )hdr [4 ]; 10315img_rows .resize (off + cnt ); 10316if (std::fread (img_rows .data ()+ off ,sizeof (float ),cnt ,f )!= cnt ) {ve = "short embeddings file" ;break ; } 10317imgs .push_back ({hdr [1 ],hdr [2 ],hdr [3 ],off }); 10318 } 10319if (f ) std::fclose (f ); 10320int64_t p = 0 ,i = 0 ; 10321size_t k = 0 ; 10322while (ve .empty ()&& i < n ) { 10323if (ids [(size_t )i ]!= kImagePad ) {put (i ,p ,p ,p );++ p ;++ i ;continue ; } 10324if (k >=imgs .size ()) {ve = "the prompt has more images than the embeddings file" ;break ; } 10325const Img & im = imgs [k ++ ]; 10326 {// what the conversation cache compares: a picture is its grid and its embeddings 10327const int64_t grid [3 ]= {im .n ,im .nx ,im .ny }; 10328uint64_t h = fnv1a (grid ,sizeof grid ); 10329if (req_img_keys .size ()== imgs .size ())// #2228: the server's key for picture k 10330h = fnv1a (& req_img_keys [k - 1 ],sizeof (uint64_t ),h ); 10331else 10332h = fnv1a (img_rows .data ()+ im .off , (size_t )im .n * (size_t )g .n_embd * sizeof (float ),h ); 10333req_imgs .push_back ({i ,h }); 10334 } 10335for (int64_t j = 0 ;j < im .n && ve .empty ();++ j ) 10336if (i + j >=n || ids [(size_t ) (i + j )]!= kImagePad ) 10337ve = "image " + std::to_string (k )+ " has " + std::to_string ((long long )im .n )+ 10338" rows but fewer <|image_pad|> tokens" ; 10339for (int64_t j = 0 ;j < im .n && ve .empty ();++ j ) { 10340const int64_t y = j /im .nx ,x = j %im .nx ; 10341put (i + j ,p ,p + y ,p + x ); 10342row_ptr [(size_t ) (i + j )]= img_rows .data ()+ im .off + (size_t )j * (size_t )g .n_embd ; 10343 } 10344i += im .n ; 10345p += std::max (im .nx ,im .ny ); 10346 } 10347if (ve .empty ()&& k != imgs .size ())ve = "the embeddings file has more images than the prompt" ; 10348if (ve .empty ()&& n > 0 && ids [(size_t ) (n - 1 )]== kImagePad )ve = "the prompt cannot end in an image" ; 10349for (int64_t c = n ;ve .empty ()&& c < cells ;++ c )put (c ,p + (c - n ),p + (c - n ),p + (c - n )); 10350 } 10351tr ("positions built" , (long long )img_rows .size ()); 10352 dpct::get_current_device ().queues_wait_and_throw (); 10353tr ("device idle" ); 10354// CUDA0's table and, with a layer split, every later stage's (each device reads its own) 10355auto upload_mrope = [& ]()-> bool { 10356try { 10357bool ok = DPCT_CHECK_ERROR ( 10358 dpct::get_in_order_queue () 10359 .memcpy (d_mrope ,mrope_host .data (), 10360mrope_host .size ()* sizeof (int32_t )) 10361 .wait ())== 0 ; 10362for (auto & st :stages ) { 10363const strata::core::OnDevice on (st -> dev ); 10364 dpct::get_current_device ().queues_wait_and_throw (); 10365ok = 10366ok && 10367DPCT_CHECK_ERROR ( 10368 dpct::get_in_order_queue () 10369 .memcpy (st -> mrope ,mrope_host .data (), 10370mrope_host .size ()* sizeof (int32_t )) 10371 .wait ())== 0 ; 10372 } 10373return ok ; 10374 } 10375catch (sycl::exception const & exc ) { 10376 std::cerr <<exc .what () 10377 <<"Exception caught at file:" <<__FILE__ 10378 <<", line:" <<__LINE__ << std::endl ; 10379 std::exit (1 ); 10380 } 10381 }; 10382if (ve .empty ()&& !upload_mrope ())ve = "the image position upload failed" ; 10383if (!ve .empty ()) { 10384// leave the table as the identity so the next text request is untouched 10385for (int64_t c = 0 ;c < cells ;++ c )put (c ,c ,c ,c ); 10386upload_mrope (); 10387mrope_identity = true; 10388 std::printf ("ERR %s\n" ,ve .c_str ()); 10389 std::fflush (stdout ); 10390continue ; 10391 } 10392mrope_identity = !geni ; 10393 } 10394sp .embd_rows = geni ?row_ptr .data () :nullptr ; 10395if (n + max_new + 8 > o .max_context ) { 10396 std::printf ("ERR prompt (%lld tokens) + max_new (%lld) exceeds the context (%lld)\n" , (long long )n , 10397 (long long )max_new , (long long )o .max_context ); 10398continue ; 10399 } 10400bool bad = false; 10401for (int64_t t :ids )bad = bad || t < 0 || t >=n_vocab ; 10402if (bad ) { std::printf ("ERR a token id is outside the vocabulary\n" );continue ; } 10403 std::array < int64_t ,3 > remote_before {}; 10404 std::array < int64_t ,3 > launches_before {}; 10405 std::array < uint64_t ,3 > compact_before {},full_before {}; 10406// ms_begin/ms_wait are cumulative since boot; the log line used to print them next to per-request deltas, 10407// so the host time read as if it belonged to this request. Take deltas here like every other column. 10408 std::array < double ,3 > begin_before {},wait_before {}; 10409for (int r = 0 ;r < 3 ;++ r )if (o .expert_cache_remote [(size_t )r ]> 0 ) 10410 { 10411remote_before [(size_t )r ]= remote_experts [(size_t )r ].computed (); 10412launches_before [(size_t )r ]= remote_experts [(size_t )r ].launched_layers (); 10413compact_before [(size_t )r ]= remote_experts [(size_t )r ].returned_bytes (); 10414full_before [(size_t )r ]= remote_experts [(size_t )r ].full_row_bytes (); 10415begin_before [(size_t )r ]= remote_experts [(size_t )r ].ms_begin (); 10416wait_before [(size_t )r ]= remote_experts [(size_t )r ].ms_wait (); 10417 } 10418cur = ids ; 10419const Clock ::time_point r0 = Clock ::now (); 10420// ---- where this request starts reading: the live session, or a checkpoint, whose tokens AND pictures are 10421// exactly the start of this prompt - at most n - 1 of them, the last token is always the first window 10422auto starts_with = [& ](const std::vector < int32_t >& pre ,const std::vector < ImgKey >& pre_imgs )-> bool { 10423const int64_t L = (int64_t )pre .size (); 10424if (L < 1 || L > n - 1 )return false; 10425for (int64_t i = 0 ;i < L ;++ i ) 10426if ((int32_t )ids [(size_t )i ]!= pre [(size_t )i ])return false; 10427return imgs_below (req_imgs ,L )== pre_imgs ; 10428 }; 10429const bool want_cvec = strata::kernels::cvec ().loaded () ?req_cvec != 0 : true; 10430// the last request's final commit may still be running on the verifier's stream (set_commit_async): 10431// everything below reads, restores or zeroes the session from other streams and the host (the end of the 10432// last request waited already; this covers a request that ended on an error path) 10433if (!ver .wait_commit (err )) { 10434 std::printf ("ERR %s\n" ,err .c_str ()); 10435return 1 ; 10436 } 10437auto kv_quiesce = [& ] { 10438try { 10439 dpct::get_current_device ().queues_wait_and_throw ();apply_pending (true); } 10440catch (sycl::exception const & exc ) { 10441 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 10442 <<", line:" <<__LINE__ << std::endl ; 10443 std::exit (1 ); 10444 } 10445 }; 10446if (kvg .on ) {// the elastic K/V: this prompt's cells (it gives back what it does not need below) 10447// a failed growth may leave the tier half-changed: the engine stops (as for any CUDA failure) 10448if (!kvg_ensure (n + 256 ,kv_quiesce )) { 10449 std::printf ("ERR the K/V cannot grow to this prompt: no VRAM is left\n" ); 10450 std::fflush (stdout ); 10451return 1 ; 10452 } 10453 } 10454int64_t resume = 0 ; 10455bool from_live = false; 10456if (o .prompt_cache > 0 && want_cvec == cvec_cached ) { 10457if (live_ok && starts_with (live ,live_imgs )) {resume = (int64_t )live .size ();from_live = true; } 10458for (const ConvCheckpoint & c :checks ) 10459if ((int64_t )c .ids .size ()> resume && starts_with (c .ids ,c .imgs )) { 10460resume = (int64_t )c .ids .size (); 10461from_live = false; 10462 } 10463 } 10464// --batch: an idle slot that holds the start of this prompt (the conversation it served last) is a 10465// source too - its sessions are copied back below, so only the new part is read 10466int slot_source = -1 ; 10467int64_t slot_tokens = 0 ; 10468bool resumed_from0 = false;// a prompt read parked in a slot (BYIELD) that had started at token 0 10469const ConvCheckpoint * slot_ck = nullptr ;// the slot's checkpoint the prompt continues from (else its end) 10470if (o .prompt_cache > 0 && req_imgs .empty ()) 10471for (int b = 0 ;b < (int )bs .size ();++ b ) { 10472const BSlot & sl = bs [(size_t )b ]; 10473if (sl .active || !sl .cached || sl .cvec != want_cvec )continue ; 10474if ((int64_t )sl .ids .size ()> std::max (resume ,slot_tokens )&& starts_with (sl .ids , {})) { 10475slot_source = b ; 10476slot_tokens = (int64_t )sl .ids .size (); 10477slot_ck = nullptr ; 10478 } 10479for (const ConvCheckpoint & c :sl .checks ) 10480if ((int64_t )c .ids .size ()> std::max (resume ,slot_tokens )&& starts_with (c .ids ,c .imgs )) { 10481slot_source = b ; 10482slot_tokens = (int64_t )c .ids .size (); 10483slot_ck = & c ; 10484 } 10485 } 10486const auto parked = conversations .best (ids ,req_imgs ,want_cvec ); 10487 std::optional < strata::core::SavedConversation > incoming ; 10488if (parked .tokens > std::max (resume ,slot_tokens ))incoming .emplace (conversations .take (parked .index )); 10489if (incoming )slot_source = -1 ; 10490// Reject the entire image before parking/overwriting the outgoing 10491// state. Invalid entries can safely fall back to its existing prefix. 10492if (incoming && incoming -> stage_images .size ()!= stages .size ()) { 10493 std::fprintf (stderr ,"strata serve: conversation cache: discard snapshot (stage count)\n" ); 10494incoming .reset (); 10495 } 10496if (incoming )for (size_t i = 0 ;i < stages .size ();++ i ) { 10497const strata::core::OnDevice on (stages [i ]-> dev ); 10498if (!strata::core::conversation_snapshot_validate (incoming -> stage_images [i ],stages [i ]-> ss ,g , 10499use_mtp && i + 1 == stages .size () ?& mtp .kv_state () :nullptr ,err )) {// the draft: the last stage's 10500 std::fprintf (stderr ,"strata serve: conversation cache: discard invalid stage snapshot (%s)\n" , 10501err .c_str ()); 10502incoming .reset (); 10503err .clear (); 10504break ; 10505 } 10506 } 10507if (incoming && !strata::core::conversation_snapshot_validate (* incoming ,ss ,g , 10508use_mtp && stages .empty () ?& mtp .kv_state () :nullptr ,err )) { 10509 std::fprintf (stderr ,"strata serve: conversation cache: discard invalid snapshot (%s)\n" ,err .c_str ()); 10510incoming .reset (); 10511err .clear (); 10512 } 10513// Preserve the outgoing branch before any checkpoint rewind, reset, 10514// or incoming restore overwrites the positional state it requires. 10515if ((!from_live || incoming || slot_source >=0 )&& !park_current (incoming ?incoming -> bytes () :0 )) { 10516 std::printf ("ERR %s\n" ,err .c_str ()); 10517return 1 ; 10518 } 10519if (slot_source >=0 ) { 10520const auto t0 = Clock ::now (); 10521if (!copy_from_slot (slot_source ,slot_ck ,err )) { 10522// the main session may be half written: read this prompt from the start 10523 std::fprintf (stderr ,"strata batch: restoring slot %d failed (%s); reading the prompt\n" , 10524slot_source ,err .c_str ()); 10525err .clear (); 10526live .clear (); 10527live_imgs .clear (); 10528checks .clear (); 10529resume = 0 ; 10530from_live = false; 10531 }else { 10532checks .clear ();// the main session's checkpoints were of the conversation it held before 10533// a read that gave way, the same request again (into its own slot): on with it - its segments and 10534// checkpoints as if it had not stopped 10535if (slot_ck == nullptr && bs [(size_t )slot_source ].partial && admit_slot == slot_source ) { 10536resumed_from0 = bs [(size_t )slot_source ].partial_from0 ; 10537bs [(size_t )slot_source ].partial = false; 10538 } 10539// the slot's checkpoints come along (the one continued from, and any shorter one: prefixes of what 10540// was copied back, their K/V cells with it), so the chain keeps its branch points and the parked 10541// copies of this conversation a turn back - whose deepest checkpoint the chain holds again - go 10542// as superseded (#342) instead of taking a parked entry each until the cache evicts another chat 10543try {// an optimization: a host allocation that fails skips the rest 10544// (a shorter checkpoint only when it is a prefix of the tokens copied back, text only) 10545const std::vector < int32_t >& copied_back = slot_ck != nullptr ?slot_ck -> ids :bs [(size_t )slot_source ].ids ; 10546for (const ConvCheckpoint & c :bs [(size_t )slot_source ].checks ) 10547if ((int64_t )c .ids .size () <=slot_tokens && c .imgs .empty ()&& c .ids .size () <=copied_back .size ()&& 10548 std::equal (c .ids .begin (),c .ids .end (),copied_back .begin ())) 10549checks .push_back (c ); 10550 }catch (const std::bad_alloc & ) { 10551 std::fprintf (stderr ,"strata batch: slot %d: its checkpoints were not all copied (out of memory); the rest are skipped\n" ,slot_source ); 10552 } 10553if (slot_ck != nullptr ) { 10554live = slot_ck -> ids ; 10555for (ConvCheckpoint & c :checks )// the main session's chain has it now 10556if (c .ids .size ()== slot_ck -> ids .size ())c .used = ++ check_clock ; 10557 }else { 10558live = bs [(size_t )slot_source ].ids ; 10559 } 10560live_imgs .clear (); 10561resume = slot_tokens ; 10562from_live = true; 10563 std::fprintf (stderr ,"strata batch: slot %d gave back %lld tokens of this conversation (%s) in " 10564"%.1f ms\n" ,slot_source , (long long )slot_tokens , 10565slot_ck != nullptr ?"its turn checkpoint" :"all it holds" , 10566 std::chrono::duration < double , std::milli > (Clock ::now ()- t0 ).count ()); 10567 } 10568 } 10569// the elastic K/V: a parked conversation is restored whole, and it may be longer than this prompt 10570if (incoming && !kvg_ensure ((int64_t )incoming -> live .ids .size ()+ 256 ,kv_quiesce )) { 10571 std::printf ("ERR the K/V cannot grow to the parked conversation: no VRAM is left\n" ); 10572return 1 ; 10573 } 10574if (incoming ) { 10575const auto t0 = Clock ::now (); 10576if (strata::core::conversation_snapshot_restore (* incoming ,ss ,g , 10577use_mtp && stages .empty () ?& mtp .kv_state () :nullptr ,err )!= 10578 strata::core::ConversationRestore ::restored ) { 10579// Already prevalidated above: a failure here is fatal, never 10580// permission to decode from a partially restored session. 10581 std::printf ("ERR restoring parked conversation: %s\n" ,err .c_str ()); 10582return 1 ; 10583 } 10584for (size_t i = 0 ;i < stages .size ();++ i ) {// the later stages' parts 10585const strata::core::OnDevice on (stages [i ]-> dev ); 10586if (strata::core::conversation_snapshot_restore (incoming -> stage_images [i ],stages [i ]-> ss ,g , 10587use_mtp && i + 1 == stages .size () ?& mtp .kv_state () :nullptr ,err )!= 10588 strata::core::ConversationRestore ::restored ) { 10589 std::printf ("ERR restoring parked conversation (stage CUDA%d): %s\n" ,stages [i ]-> dev , 10590err .c_str ()); 10591return 1 ; 10592 } 10593if (DPCT_CHECK_ERROR (dpct::get_current_device () 10594 .queues_wait_and_throw ())!= 0 ) { 10595 std::printf ("ERR stage sync\n" );return 1 ; 10596 } 10597 } 10598if (use_mtp && std::getenv ("STRATA_SNAPSHOT_VERIFY" )!= nullptr ) { 10599uint64_t draft_hash = 0 ; 10600const auto & draft_kv = stages .empty () ?incoming -> kv .back () :incoming -> stage_images .back ().kv .back (); 10601const strata::core::OnDevice on_d (stages .empty () ?0 :stages .back ()-> dev ); 10602if (!strata::core::conversation_kv_verify (draft_kv ,mtp .kv_state (),g , 10603int64_t (incoming -> live .ids .size ()), false,draft_hash ,err )) { 10604 std::printf ("ERR verifying restored draft KV: %s\n" ,err .c_str ()); 10605return 1 ; 10606 } 10607 std::fprintf (stderr ,"strata serve: SNAPSHOT_VERIFY draft=%016llx cells=%lld mode=%d source=%s resident=%lld\n" , 10608 (unsigned long long )draft_hash , (long long )draft_kv .cells , 10609mtp .kv_state ().kv_mode ,"ram" , 10610 (long long ) (mtp .kv_state ().n_slots * strata::kernels::qsa_real_shapes ().page_size )); 10611 } 10612live = std::move (incoming -> live .ids ); 10613live_imgs = std::move (incoming -> live .imgs ); 10614if (stages .empty ()) { 10615checks = std::move (incoming -> checkpoints ); 10616 }else {// give each checkpoint back its stage parts (moved, not copied); none if they do not line up 10617 strata::core::ConversationCheckpointSplit cs ; 10618cs .stage0 = std::move (incoming -> checkpoints ); 10619for (auto & si :incoming -> stage_images )cs .parts .push_back (std::move (si .checkpoints )); 10620if (!strata::core::conversation_checkpoints_merge (std::move (cs ),checks ))checks .clear (); 10621 } 10622cvec_cached = incoming -> cvec ; 10623resume = parked .tokens ; 10624from_live = parked .live ; 10625if (std::getenv ("STRATA_SNAPSHOT_FULL_CAPTURE" )== nullptr ) { 10626 std::vector < std::vector < strata::core::ConversationKv >> stage_kv ;// every stage's, for its next park 10627for (auto & si :incoming -> stage_images )stage_kv .push_back (std::move (si .kv )); 10628conversations .retain (std::move (incoming -> kv ),int64_t (live .size ()), std::move (stage_kv ),live ); 10629 } 10630incoming .reset ();// Running-state/checkpoint copies are no longer needed. 10631 std::fprintf (stderr ,"strata serve: conversation cache: restored %lld tokens (%s) in %.1f ms; parked=%zu bytes=%zu\n" , 10632 (long long )resume ,from_live ?"live" :"checkpoint" , 10633 std::chrono::duration < double , std::milli > (Clock ::now ()- t0 ).count (), 10634conversations .size (),conversations .bytes ()); 10635 } 10636if (want_cvec != cvec_cached ) { 10637live_ok = false; 10638checks .clear (); 10639cvec_cached = want_cvec ; 10640 } 10641if (strata::kernels::cvec ().loaded ()) strata::kernels::cvec_set_enabled (want_cvec ); 10642// this request rewrites every cell from `resume` on, so a checkpoint past it (or not on this prompt's 10643// path) no longer has its cells; the ones kept are prefixes of both the old tokens and the new 10644checks .erase (std::remove_if (checks .begin (),checks .end (), [& ](const ConvCheckpoint & c ) { 10645return (int64_t )c .ids .size ()> resume || !starts_with (c .ids ,c .imgs ); 10646 }),checks .end ()); 10647live_ok = false;// until this request has finished, the session is in between 10648// the elastic K/V: the outgoing session is parked and this request rewrites every cell from `resume` on, 10649// so cells past this prompt's are no longer anyone's - far more than it needs go back to the cache 10650if (kvg .on ) { 10651kv_quiesce (); 10652if (!kvg_trim (n + 256 )) { 10653 std::printf ("ERR the K/V could not give its VRAM back to the expert cache\n" ); 10654 std::fflush (stdout ); 10655return 1 ; 10656 } 10657 } 10658int64_t reread_to = -1 ;// STRATA_CKPT_REREAD only: read [0, reread_to) again instead of restoring 10659if (resume == 0 ) { 10660 strata::core::session_zero (ss ,g ,nullptr ,main_cs ); 10661main_stream -> wait (); 10662for (auto & st :stages ) { 10663const strata::core::OnDevice on (st -> dev ); 10664 strata::core::session_zero (st -> ss ,g ,nullptr , (void * )st -> stream ); 10665st -> stream -> wait (); 10666 } 10667checks .clear (); 10668 }else if (!from_live ) { 10669ConvCheckpoint * c = nullptr ; 10670for (ConvCheckpoint & k :checks )if ((int64_t )k .ids .size ()== resume )c = & k ; 10671if (c != nullptr )c -> used = ++ check_clock ;// mounting through it is the use LRU counts 10672static const bool reread = std::getenv ("STRATA_CKPT_REREAD" )!= nullptr ; 10673if (reread && c != nullptr ) { 10674// THE CHECK OF THE CHECKPOINT: instead of restoring it, read its tokens again from position 0 in 10675// one run (below, with the prompt path's slots lent like any read) - the same chunks the request 10676// that saved it read them in, when that request started at 0. With the VRAM expert set fixed 10677// (--adapt-swaps 0) the answer must match the restored one token for token; anything the 10678// checkpoint missed shows up as a difference. 10679 strata::core::session_zero (ss ,g ,nullptr ,main_cs ); 10680main_stream -> wait (); 10681for (auto & st :stages ) { 10682const strata::core::OnDevice on (st -> dev ); 10683 strata::core::session_zero (st -> ss ,g ,nullptr , (void * )st -> stream ); 10684st -> stream -> wait (); 10685 } 10686reread_to = resume ; 10687 std::fprintf (stderr ,"strata serve: STRATA_CKPT_REREAD: reading %lld tokens again instead of " 10688"restoring\n" , (long long )resume ); 10689 }else if (c == nullptr || !checkpoint_restore (* c ,ss ,g )|| c -> stage_parts .size ()!= stages .size ()|| 10690 [& ] { 10691for (size_t i = 0 ;i < stages .size ();++ i ) { 10692const strata::core::OnDevice on (stages [i ]-> dev ); 10693if (!checkpoint_restore (c -> stage_parts [i ],stages [i ]-> ss ,g ))return true; 10694 } 10695return false; 10696 }()) { 10697 std::printf ("ERR restoring a conversation checkpoint failed\n" ); 10698return 1 ; 10699 } 10700 } 10701// KV streaming: the drafter's ring may hold cells past `resume` from a longer turn; the main layers' 10702// host copies and slots are always current (every writer writes both), so they need nothing 10703if (use_mtp && resume > 0 && reread_to <=0 )mtp .kv_restore (resume ); 10704tr ("request" ,n ,geni ?1 :0 ); 10705 strata::workload_trace::set_context (0 ,n ,-1 ); 10706 strata::workload_trace::Scope request_trace ("request" ,nullptr ,n ); 10707if (use_mtp )mtp .set_prompt_len (n ); 10708if (use_df2 ) {// the drafter's ring goes on from the live conversation, or starts over (a parked or edited one) 10709 std::vector < int32_t > idv (ids .begin (),ids .end ()); 10710bool cold = false; 10711df2 .begin_request (idv .data (), (int64_t )idv .size (),reread_to > 0 ?0 :resume ,& cold ); 10712if (df2 .last_rebuilt > 0 ) 10713 std::fprintf (stderr ,"strata serve: DFlash2: %s%lld context rows of the window rebuilt from the drafter's log in %.1f ms%s\n" , 10714df2 .last_swapped ?"a parked conversation came back: " :"" , (long long )df2 .last_rebuilt ,df2 .last_ms , 10715df2 .last_missing >=64 ?" (the rest were never logged)" :"" ); 10716if (cold && df2 .last_missing >=64 )// (a few rows missing are not worth a line: they are counted in the ring stats) 10717 std::fprintf (stderr ,"strata serve: DFlash2: %lld context rows of the window are not the drafter's to give (a conversation it has no log of: edited, " 10718"from a session file, or its log was evicted): it drafts poorly for the first rounds (the answers are the same)\n" , 10719 (long long ) std::max < int64_t > (df2 .last_missing ,1 )); 10720sp .set_taps (df2 .tap_layers (), std::max < int64_t > (0 ,n - 2047 ),2048 ); 10721 } 10722const int64_t read_from = reread_to > 0 ?0 :resume ; 10723conversations .limit_reuse (read_from ); 10724pp_total = n ; 10725pp_from = read_from ; 10726pp_reached = read_from ; 10727pp_t0 = r0 ; 10728pp_next_check = reread_to > 0 || !req_ckpt ?INT64_MAX :resume + o .prompt_cache_every ;// ckpt=0: none 10729pp_tail_saved = reread_to > 0 || !req_ckpt ;// ckpt=0 (#861): no tail checkpoint either 10730 { 10731 std::lock_guard < std::mutex > lk (part_mu ); 10732part_at .clear (); 10733 std::fill (part_next .begin (),part_next .end (),pp_next_check ); 10734 } 10735 std::printf ("RESUME %lld\n" , (long long )resume );// before reading: this many prompt tokens are reused 10736 strata::core::progress_at ("reading the prompt, from token" ,read_from ); 10737 std::fflush (stdout ); 10738// A SHORT PART OF THE PROMPT - the new message of a chat that continues from a checkpoint, the assistant 10739// header - goes through the verify windows, S tokens at a time, as decode reads them. The batched path 10740// costs ~300 ms per run however few tokens it has (it streams every expert the chunk routes to that is 10741// not in VRAM over PCIe), and it borrows slots it must refill after (~180 ms); a window costs ~16 ms a 10742// token, with the misses on the CPU. Each part below is decided on its own, so a long first message is 10743// read batched and its header still goes through the windows. Picture rows need the batched path. 10744// STRATA_CKPT_REREAD compares a restored checkpoint with a batched re-read, so it keeps every read batched. 10745static const bool no_short = std::getenv ("STRATA_CKPT_REREAD" )!= nullptr ; 10746int64_t req_short_read = o .short_read ;// STRATA_PIPELINE_SWITCH may set it per request (short_read=) 10747auto windows_ok = [& ](int64_t a ,int64_t b )-> bool { 10748if (no_short || b - a > req_short_read )return false; 10749if (sp .embd_rows != nullptr ) 10750for (int64_t i = a ;i < b ;++ i ) 10751if (sp .embd_rows [i ]!= nullptr )return false; 10752return true; 10753 }; 10754// --pipeline-windows, testing: STRATA_PIPELINE_SWITCH=<file> is read at every request, "pw=<0|1|2> 10755// theta=<f> force_miss=<k> short_read=<n>" - an A/B of the pipelined and the serial loops (and forced 10756// rollbacks) on one server, with the same expert placement 10757int pl_pw = pipe ?o .pipeline_windows :0 ; 10758float pl_theta = [] {// a speculative window is launched only when its estimated chance is at least this 10759const char * v = pipe_dbg_env ("STRATA_PIPELINE_THETA" ); 10760return v ? (float ) std::atof (v ) :0.2f ; 10761 }(); 10762int pl_force_miss = [] {// exactness test: every k-th speculative window gets a wrong first token 10763const char * v = pipe_dbg_env ("STRATA_PIPELINE_FORCE_MISS" ); 10764return v ? std::max (0 , std::atoi (v )) :0 ; 10765 }(); 10766if (static const char * sw = pipe_dbg_env ("STRATA_PIPELINE_SWITCH" );sw != nullptr && pipe ) { 10767if (std::FILE * f = std::fopen (sw ,"r" )) { 10768char buf [256 ]= {}; 10769const size_t nr = std::fread (buf ,1 ,sizeof buf - 1 ,f ); 10770 std::fclose (f ); 10771buf [nr ]= 0 ; 10772if (const char * q = std::strstr (buf ,"pw=" ))pl_pw = std::max (0 , std::min (2 , std::atoi (q + 3 ))); 10773if (const char * q = std::strstr (buf ,"theta=" ))pl_theta = (float ) std::atof (q + 6 ); 10774if (const char * q = std::strstr (buf ,"force_miss=" ))pl_force_miss = std::max (0 , std::atoi (q + 11 )); 10775if (const char * q = std::strstr (buf ,"short_read=" ))req_short_read = std::max (0LL , std::atoll (q + 11 )); 10776 std::fprintf (stderr ,"strata pipeline switch: pw=%d theta=%.3f force_miss=%d short_read=%lld\n" ,pl_pw , 10777pl_theta ,pl_force_miss , (long long )req_short_read ); 10778 } 10779 } 10780// --pipeline-windows: tokens [a, b) through the windows with the stages overlapped. The tokens are known, 10781// so every window commits whole: stage 0 queues window K, its commit and window K+1 back to back (each 10782// parity's verifier keeps its own window), and stage 1 runs window K once stage 0 is done with it. Every 10783// stage runs the same windows in the same order as read_windows below, so the session ends the same. 10784auto read_windows_pl = [& ](int64_t a ,int64_t b , std::string & e )-> bool { 10785 strata::core::progress_at ("reading the prompt (pipelined verify windows), from token" ,a ); 10786if (!pl_prepare (e ))return false; 10787for (int par = 0 ;par < 2 ;++ par )PV [0 ][par ]-> set_head_sampling (false);// reaches stage 1 (set_next) 10788struct Restore { 10789 strata::core::Verifier * v [2 ]; 10790 ~Restore () {v [0 ]-> set_head_sampling (true);v [1 ]-> set_head_sampling (true); } 10791 }restore {{PV [0 ][0 ],PV [0 ][1 ]}}; 10792struct Win {int T ;int64_t q ; }; 10793 std::vector < Win > wins ; 10794for (int64_t q = a ;q < b ;) { 10795const int T = (int ) std::min < int64_t > (S ,b - q ); 10796wins .push_back ({T ,q }); 10797q += T ; 10798 } 10799const size_t N = wins .size (); 10800 std::vector < int32_t > w0 ((size_t )S ),w1 ((size_t )S ),nx ((size_t )S ); 10801size_t l0 = 0 ,f0 = 0 ,l1 = 0 ,f1 = 0 ;// stage 0 launched / finished, stage 1 launched / finished 10802drive .d .layers = 0 ; 10803drive .d .experts = 0 ; 10804drive .d .failed = false; 10805auto fail = [& ](std::string why )-> bool { 10806pl_drain (); 10807e = why .empty () ? std::string ("a pipelined prompt window failed" ) :why ; 10808return false; 10809 }; 10810while (f1 < N ) { 10811if (stop_req .load ())return fail ("cancelled" ); 10812// stage 0: up to two windows queued; window K+2 (K's parity) only once stage 1 has finished window 10813// K, whose hand-off K+2 overwrites 10814while (l0 < N && l0 < f0 + 2 && l0 < f1 + 2 ) { 10815const Win & w = wins [l0 ]; 10816for (int t = 0 ;t < w .T ;++ t )w0 [(size_t )t ]= (int32_t )cur [(size_t ) (w .q + t )]; 10817 strata::core::Verifier & v = * PV [0 ][l0 & 1 ]; 10818if (!v .pl_launch (w .T ,w0 .data (),w .q ,e )|| !v .pl_commit_async (w .T ,e ))return fail (e ); 10819++ l0 ; 10820 } 10821if (f0 < l0 ) { 10822 strata::core::Verifier & v = * PV [0 ][f0 & 1 ]; 10823if (v .service (win_pool_fn ,PSD [f0 & 1 ],e )< 0 )return fail (e ); 10824if (v .done (e )) { 10825if (!v .pl_finish (nullptr ,e ))return fail (e ); 10826++ f0 ; 10827 }else if (!e .empty ())return fail (e ); 10828 } 10829if (l1 < f0 && l1 == f1 ) {// stage 1: the next window, its stage 0 done 10830const Win & w = wins [l1 ]; 10831for (int t = 0 ;t < w .T ;++ t )w1 [(size_t )t ]= (int32_t )cur [(size_t ) (w .q + t )]; 10832 strata::core::Verifier & v = * PV [1 ][l1 & 1 ]; 10833if (pl_mtp_live [l1 & 1 ]) {// the drafter has read this parity's previous rows first 10834// SYCL keeps an event in its context, so another card's queue cannot take it as a 10835// dependency ("Cannot submit to a queue with a dependency from a graph that is 10836// associated with a different context", the first pipelined window on a split). The 10837// drafter's rows must be in memory before stage 1 reads them, so on two cards the 10838// host waits for the drafter here and the window is launched without the barrier. 10839if (mtp .device ()== v .device ()) { 10840const strata::core::OnDevice on (mtp .device ()); 10841 (v .stream ()) 10842-> ext_oneapi_submit_barrier ( 10843 {* pl_mtp_ev [l1 & 1 ]}); 10844 }else if (DPCT_CHECK_ERROR (pl_mtp_ev [l1 & 1 ]-> wait ())!= 0 ) { 10845return fail ("the drafter's rows did not land before the window" ); 10846 } 10847 } 10848if (!v .pl_launch (w .T ,w1 .data (),w .q ,e )|| !v .pl_commit_async (w .T ,e ))return fail (e ); 10849++ l1 ; 10850 } 10851if (f1 < l1 ) { 10852 strata::core::Verifier & v = * PV [1 ][f1 & 1 ]; 10853if (v .service (win_pool_fn ,PSD [f1 & 1 ],e )< 0 )return fail (e ); 10854if (v .done (e )) { 10855if (!v .pl_finish (nullptr ,e ))return fail (e ); 10856const Win & w = wins [f1 ]; 10857for (int t = 0 ;t < w .T ;++ t )nx [(size_t )t ]= (int32_t )cur [(size_t ) (w .q + t + 1 )]; 10858if (!mtp .prefill (v .final_R (0 ),nx .data (),w .T ,w .q ,e , false))return fail (e ); 10859 { 10860const strata::core::OnDevice on (mtp .device ()); 10861 dpct::sync_barrier (pl_mtp_ev [f1 & 1 ], 10862mtp .stream ()); 10863 } 10864pl_mtp_live [f1 & 1 ]= true; 10865pp_reached = w .q + w .T ;// #471 10866++ f1 ; 10867 }else if (!e .empty ())return fail (e ); 10868 } 10869if (drive .d .failed )return fail (drive .d .fail ?drive .d .fail :"the expert pool failed" ); 10870 } 10871pl_drain ();// nothing in flight: both stages' commits and the drafter's rows have landed 10872pl_mtp_live [0 ]= pl_mtp_live [1 ]= false; 10873const double ms = std::chrono::duration < double , std::milli > (Clock ::now ()- pp_t0 ).count (); 10874 std::printf ("PP %lld %lld %.0f %.1f\n" , (long long )b , (long long )pp_total ,ms , 10875ms > 0.0 ?1000.0 * (double ) (b - pp_from ) /ms :0.0 ); 10876 strata::core::progress_beat (); 10877 std::fflush (stdout ); 10878return true; 10879 }; 10880// tokens [a, b) through the windows: commit all of them, then give the draft layer their residuals 10881auto read_windows = [& ](int64_t a ,int64_t b , std::string & e )-> bool { 10882// (STRATA_LOGPOS reads every window's logits: the serial loop) 10883if (pipe && pl_pw >=1 && std::getenv ("STRATA_LOGPOS" )== nullptr )return read_windows_pl (a ,b ,e ); 10884 strata::core::progress_at ("reading the prompt (verify windows), from token" ,a );// #217: not "batched" 10885// every token is committed and the picks are discarded: no head sampling (see set_head_sampling) 10886struct NoHeadSampling { 10887 strata::core::Verifier & v ; 10888explicit NoHeadSampling (strata::core::Verifier & x ) :v (x ) {v .set_head_sampling (false); } 10889 ~NoHeadSampling () {v .set_head_sampling (true); } 10890 }no_head_sampling (ver ); 10891 std::vector < int32_t > win ((size_t )S ),outw ((size_t )S ),nxt ((size_t )S ); 10892for (int64_t q = a ;q < b ;) { 10893if (stop_req .load ()) {e = "cancelled" ;return false; } 10894const int T = (int ) std::min < int64_t > (S ,b - q ); 10895for (int t = 0 ;t < T ;++ t ) { 10896win [(size_t )t ]= (int32_t )cur [(size_t ) (q + t )]; 10897nxt [(size_t )t ]= (int32_t )cur [(size_t ) (q + t + 1 )]; 10898 } 10899drive .d .layers = 0 ; 10900drive .d .experts = 0 ; 10901drive .d .failed = false; 10902if (!ver .run (T ,win .data (),q ,win_pool_fn ,win_pool_user ,outw .data (),e )|| drive .d .failed ) { 10903if (drive .d .failed && drive .d .fail )e = drive .d .fail ; 10904return false; 10905 } 10906// STRATA_LOGPOS=<path>: the teacher-forced log-probability of every token read here (every 10907// token is committed and nxt[t] is the prompt's own next token), appended to <path>; the last 10908// column is the log-probability of STRATA_LOGPOS_EXTRA (default 248046, <|im_end|>), so the 10909// end-of-turn mass a chat model puts on raw text can be taken out of the measurement 10910static std::FILE * logpos = [] { 10911const char * p = std::getenv ("STRATA_LOGPOS" ); 10912return p != nullptr ? std::fopen (p ,"ab" ) :nullptr ; 10913 }(); 10914static const int32_t logpos_extra = [] { 10915const char * p = std::getenv ("STRATA_LOGPOS_EXTRA" ); 10916return p != nullptr ? (int32_t ) std::atoi (p ) : (int32_t )248046 ; 10917 }(); 10918if (logpos != nullptr && !ver .window_logprobs (nxt .data (),T ,q ,logpos_extra ,logpos ,e )) 10919return false; 10920if (!ver .commit (T ,e )|| (use_mtp && !mtp .prefill (ver .final_R_all (),nxt .data (),T ,q ,e )))return false; 10921if (use_df2 ) { 10922if (!df2 .context (ver .tap_dev (),T ,q ,e ))return false; 10923df2 .note_rows (win .data (),T ,q ); 10924 } 10925q += T ; 10926pp_reached = q ;// #471 10927 } 10928// the batched prompt path (other streams), checkpoints and snapshots may follow: the last commit first 10929if (!ver .wait_commit (e ))return false; 10930const double ms = std::chrono::duration < double , std::milli > (Clock ::now ()- pp_t0 ).count (); 10931 std::printf ("PP %lld %lld %.0f %.1f\n" , (long long )b , (long long )pp_total ,ms , 10932ms > 0.0 ?1000.0 * (double ) (b - pp_from ) /ms :0.0 ); 10933 strata::core::progress_beat (); 10934 std::fflush (stdout ); 10935return true; 10936 }; 10937// the batched path's slots are lent just before its first run and given back (refilled) before a window 10938// reads - so the windows always see the whole expert cache - or once the prompt is read 10939// Every participant gives its loan back here: the rows it lent are refilled into the SAME slots from 10940// the arena, the residency table is restored, and one upload puts it on every device. A stage refills 10941// through its own cache and its own device - a slot refilled into the wrong cache would leave that 10942// stage's cache holding an expert it does not own, which is silent and produces plausible tokens. 10943// (split in two halves so a layer split can queue every stage's copies before it waits for any: #340) 10944auto refill_issue = [& ](PfPart & p , std::string & e )-> bool { 10945tr ("refill start" , (long long )p .lent .size ()); 10946const strata::core::OnDevice on (p .dev ); 10947size_t queued = 0 ; 10948for (const auto & [i ,slot ] :p .lent ) {// D-4: queued, one wait (STRATA_REFILL_BLOCKING=1: each) 10949const uint8_t * b = srcp -> blob (i /g .n_expert ,i %g .n_expert ); 10950const int64_t nb = (int64_t ) strata::kernels::cpu::expert_layout ().blob_bytes (i /g .n_expert ); 10951if (b == nullptr || !(refill_blocking () ?p .cache -> fill_slot_blocking (slot ,b ,e ,nb ) 10952 :p .cache -> fill_slot_queued (slot ,b ,e ,nb ))) 10953return false; 10954host_res [(size_t )i ]= slot ; 10955// SYCL port: drain before GgufExpertSource's 512-buffer blob ring can wrap onto a queued copy 10956if (!refill_blocking ()&& ++ queued %256 == 0 && !p .cache -> sync_queued (e ))return false; 10957 } 10958return true; 10959 }; 10960auto refill_wait = [& ](PfPart & p , std::string & e )-> bool { 10961const strata::core::OnDevice on (p .dev ); 10962if (!p .cache -> sync_queued (e ))return false; 10963#if defined(_WIN32 ) 10964// The copies have landed: the file pages touched by the loan need not stay in the working set. 10965for (const auto & [i ,slot ] :p .lent ) 10966srcp -> release (i /g .n_expert ,i %g .n_expert ); 10967#endif 10968p .lent .clear (); 10969p .lent_chunk = 0 ; 10970return true; 10971 }; 10972auto refill_one = [& ](PfPart & p , std::string & e )-> bool { 10973if (p .lent .empty ())return true; 10974return refill_issue (p ,e )&& refill_wait (p ,e ); 10975 }; 10976// #340: with several stages every stage's copies go out first (each card on its own link), then each is 10977// waited for - the same copies into the same slots, so the same cache; one stage: refill_one exactly. 10978// STRATA_REFILL_SERIAL=1: stage after stage, as 0.1.30/0.1.31. 10979static const bool refill_serial = std::getenv ("STRATA_REFILL_SERIAL" )!= nullptr ; 10980auto refill = [& ](std::string & e )-> bool { 10981const auto t_rf = Clock ::now (); 10982int64_t n_lent = 0 ,n_parts = 0 ; 10983for (PfPart & p :pf_parts ) 10984if (!p .lent .empty ()) {n_lent += (int64_t )p .lent .size ();++ n_parts ; } 10985if (n_parts > 1 && !refill_serial ) { 10986for (PfPart & p :pf_parts ) 10987if (!p .lent .empty ()&& !refill_issue (p ,e ))return false; 10988for (PfPart & p :pf_parts ) 10989if (!p .lent .empty ()&& !refill_wait (p ,e ))return false; 10990 }else { 10991for (PfPart & p :pf_parts ) 10992if (!p .lent .empty ()&& !refill_one (p ,e ))return false; 10993 } 10994if (n_parts > 0 )res_upload (); 10995if (trace && n_parts > 0 ) { 10996 std::fprintf (stderr ,"strata trace: refilled %lld slots on %lld stage(s) in %.1f ms\n" , 10997 (long long )n_lent , (long long )n_parts , 10998 std::chrono::duration < double , std::milli > (Clock ::now ()- t_rf ).count ()); 10999 std::fflush (stderr ); 11000 } 11001return true; 11002 }; 11003// lend the slots `tokens` batched prompt tokens need: the prompt path's buffers for min(chunk, tokens 11004// rounded up to 256), laid out in the last of the slots it may borrow - per participant, out of that 11005// participant's own cache, and marking only that participant's own layers 11006auto lend = [& ](int64_t tokens , std::string & e )-> bool { 11007if (pf_parts .empty ())return true;// its own buffers: nothing to lend 11008const auto t_ln = Clock ::now (); 11009// what this segment needs, capped by the configured chunk: a request lends only what its own 11010// prompt needs, so a large chunk costs a short prompt nothing 11011const int64_t want_full = equal_chunk (tokens ,o .prefill_chunk ); 11012// #340: a short enough request reads in the stages' own S-token chunks (nothing lent) 11013const int64_t want = split_small > 0 && tokens <=split_small_max ? std::min (want_full ,split_small ) 11014 :want_full ; 11015if (want <=0 ) { 11016e = "prefill: cannot lend buffers for an empty request segment" ; 11017return false; 11018 } 11019bool any = false; 11020for (PfPart & p :pf_parts ) { 11021if (p .first < 0 )continue ; 11022if (!p .lent .empty ()) { 11023if (want <=p .lent_chunk )continue ;// its current loan already covers this 11024// ONLY this participant's loan goes back: `refill` would return the other participants' 11025// loans too, and their buffers are still laid out in their caches - marking those slots 11026// resident again would hand the next window a prompt buffer in place of an expert 11027if (!refill_one (p ,e ))return false; 11028 } 11029const strata::core::OnDevice on (p .dev ); 11030const int32_t first = std::max < int32_t > (p .first , (int32_t ) (p .cache -> slots ()- part_slots (p ,want ))); 11031if (want != p .sp -> chunk ()|| first != p .first_now ) { 11032if (!p .sp -> relayout (want ,p .cache -> device_slot (first ),part_bytes (p ,first ),e ))return false; 11033p .first_now = first ; 11034 } 11035for (int64_t l = p .lb ;l < p .le ;++ l )// THIS participant's layers only 11036for (int64_t ex = 0 ;ex < g .n_expert ;++ ex ) { 11037const size_t i = (size_t ) (l * g .n_expert + ex ); 11038if (host_res [i ] >=first ) { 11039p .lent .emplace_back ((int32_t )i ,host_res [i ]); 11040host_res [i ]= strata::core::kNotResident ; 11041any = true; 11042 } 11043 } 11044p .lent_chunk = want ; 11045 } 11046if (any )res_upload (); 11047if (trace ) { 11048int64_t n_lent = 0 ; 11049for (const PfPart & p :pf_parts )n_lent += (int64_t )p .lent .size (); 11050 std::fprintf (stderr ,"strata trace: lent %lld slots for %lld tokens in %.1f ms\n" , (long long )n_lent , 11051 (long long )want , std::chrono::duration < double , std::milli > (Clock ::now ()- t_ln ).count ()); 11052 std::fflush (stderr ); 11053 } 11054return true; 11055 }; 11056// --batch: a prompt read while slots are decoding goes one prompt chunk at a time (the same chunks as one 11057// run: each run starts where the last ended, at a multiple of the chunk), and between two chunks the slots 11058// decode for a share of the time the chunk took (STRATA_BATCH_DECODE_SHARE, default 0.5), so a long 11059// prompt does not stop the others. The slots' windows then see the cache without the slots this prompt 11060// borrowed (marked missing: those experts run on the CPU), never a prompt buffer. 11061static const double decode_share = [] { 11062const char * v = std::getenv ("STRATA_BATCH_DECODE_SHARE" ); 11063return v != nullptr ? std::max (0.0 , std::atof (v )) :0.5 ; 11064 }(); 11065bool batch_fatal = false; 11066int64_t il_parts = 0 ;// the slots' windows run between this prompt's chunks 11067double il_ms = 0 ; 11068int64_t yielded_at = -1 ;// BYIELD: the read stopped here and its slot holds it 11069int yielded_slot = -1 ; 11070// `BYIELD <slot>` (the server: a shorter request is waiting): at the next chunk boundary the part read so 11071// far is copied into <slot> (this admission's own, or a free one the server reserved for a solo request), 11072// the request ends with `YIELDED <slot> <tokens>` + DONE cancel, and the server sends it again later: it 11073// continues from the slot with the same chunks. #656's cooperative preemption, with a slot as the park. 11074auto read_part = [& ](int64_t a0 ,int64_t b0 , std::string & e )-> bool { 11075// (a layer split reads its stages as a pipeline over one run's chunks: in pieces only beside slots) 11076if (o .batch <=0 || piped || (!stages .empty ()&& !batch_on ())) { 11077b60_layouts .packed (false); 11078const bool ok = sp .run (ids .data ()+ a0 ,b0 - a0 ,a0 ,e ); 11079b60_layouts .packed (true); 11080return ok ; 11081 } 11082const int64_t C = std::max < int64_t > (sp .chunk (),1 ); 11083for (int64_t q = a0 ;q < b0 ;) { 11084const int64_t r = std::min (b0 ,q + C ); 11085const auto tq = Clock ::now (); 11086if (!sp .run (ids .data ()+ q ,r - q ,q ,e ))return false; 11087q = r ; 11088if (q >=b0 )continue ; 11089int ys = -1 ; 11090 {// a BSTOP that came meanwhile ends its slot at its next window; a BYIELD is for this read 11091 std::lock_guard < std::mutex > lk (in_mu ); 11092for (auto it = in_lines .begin ();it != in_lines .end ();) { 11093if (it -> rfind ("BSTOP " ,0 )== 0 ) { 11094const int b = std::atoi (it -> c_str ()+ 6 ); 11095if (b >=0 && b < (int )bs .size ())bs [(size_t )b ].stop = true; 11096it = in_lines .erase (it ); 11097 }else if (it -> rfind ("BYIELD " ,0 )== 0 ) { 11098ys = std::atoi (it -> c_str ()+ 7 ); 11099it = in_lines .erase (it ); 11100 }else { 11101++ it ; 11102 } 11103 } 11104 } 11105if (ys >=0 ) { 11106// only where the rest is read the same way after it (more than a chunk and more than a short 11107// read left), text only, and into a slot that is not decoding 11108const bool can = ys < (int )bs .size ()&& !bs [(size_t )ys ].active && 11109 (admit_slot < 0 || ys == admit_slot )&& req_imgs .empty ()&& o .prompt_cache > 0 && 11110b0 - q > std::max < int64_t > (C ,o .short_read ); 11111 std::string ye ; 11112const auto ty = Clock ::now (); 11113 std::vector < int32_t > pre (ids .begin (),ids .begin ()+ q ); 11114if (can )park_slot (ys );// the conversation the slot holds, before this read overwrites it 11115if (can && copy_to_slot (ys ,pre ,ye )) { 11116BSlot & sl = bs [(size_t )ys ]; 11117sl = BSlot {}; 11118sl .ids = std::move (pre ); 11119sl .cached = true; 11120sl .partial = true; 11121sl .partial_from0 = read_from == 0 || resumed_from0 ; 11122sl .cvec = cvec_cached ; 11123for (const ConvCheckpoint & c :checks )// the root / periodic checkpoints of this read 11124if ((int64_t )c .ids .size () <=q && std::equal (c .ids .begin (),c .ids .end (),ids .begin (), 11125 [](int32_t x ,int64_t y ) {return (int64_t )x == y ; })) 11126sl .checks .push_back (c ); 11127yielded_at = q ; 11128yielded_slot = ys ; 11129 std::fprintf (stderr ,"strata batch: the prompt read gives way at %lld of %lld tokens; slot %d " 11130"holds it (copied in %.1f ms)\n" , (long long )q , (long long )n ,ys , 11131 std::chrono::duration < double , std::milli > (Clock ::now ()- ty ).count ()); 11132e = "yield" ; 11133return false; 11134 } 11135if (can )bs [(size_t )ys ].cached = false;// half written 11136 std::fprintf (stderr ,"strata batch: BYIELD %d not taken at %lld of %lld%s%s\n" ,ys , (long long )q , 11137 (long long )n ,ye .empty () ?"" :": " ,ye .c_str ()); 11138 } 11139if (decode_share <=0.0 || !batch_on ())continue ; 11140const double budget = decode_share * std::chrono::duration < double , std::milli > (Clock ::now ()- tq ).count (); 11141const auto td = Clock ::now (); 11142do { 11143if (!batch_step ()) {batch_fatal = true;e = "a batch window failed" ;return false; } 11144 }while (batch_on ()&& std::chrono::duration < double , std::milli > (Clock ::now ()- td ).count ()< budget ); 11145++ il_parts ; 11146il_ms += std::chrono::duration < double , std::milli > (Clock ::now ()- td ).count (); 11147if (trace ) { 11148 std::fprintf (stderr ,"strata trace: prompt chunk to %lld, then the slots decoded %.0f ms\n" , 11149 (long long )q , std::chrono::duration < double , std::milli > (Clock ::now ()- td ).count ()); 11150 std::fflush (stderr ); 11151 } 11152 } 11153return true; 11154 }; 11155apply_pending (true); 11156if (!adapt_tick (true)) {// --adapt-async: the round in flight lands before the prompt lends any slot 11157 std::printf ("ERR an adaptive refill failed\n" ); 11158return 1 ; 11159 } 11160// per-request sampling for the verify window's head (greedy when temperature is absent) 11161 strata::kernels::SamplerParams req_sp ; 11162req_sp .greedy = req_temperature <=0.0f ; 11163req_sp .temperature = req_temperature ; 11164req_sp .top_p = req_top_p ; 11165req_sp .top_k = req_top_k ; 11166req_sp .seed = req_seed ?req_seed 11167 : (unsigned long long ) std::chrono::steady_clock::now ().time_since_epoch ().count (); 11168req_sp .min_p = std::clamp (req_min_p ,0.0f ,1.0f ); 11169req_sp .penalty_last_n = std::max (req_penalty_last_n ,0 ); 11170req_sp .penalty_repeat = req_penalty_repeat ; 11171req_sp .penalty_freq = req_penalty_freq ; 11172req_sp .penalty_present = req_penalty_present ; 11173req_sp .counter = 0 ; 11174ver .set_sampling (req_sp ); 11175if (pipe )ver_b .set_sampling (req_sp );// (reaches the later stage's odd verifier) 11176if (use_mtp )mtp .set_draft_sampling (req_sp );// STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise) 11177drive .d .pcie_num = std::max (0 , std::min (256 , (int ) (req_pcie_frac * 256.0 + 0.5 ))); 11178// a layer split: CUDA0's share as asked; a later GPU keeps its own (its link) unless the request sets one 11179for (int st = 0 ;st < split_drive .n ;++ st ) 11180split_drive .pcie_num [st ]= (st == 0 || split_same || req_pcie_frac != o .pcie_frac ) 11181 ?drive .d .pcie_num :pcie_num_of (stages [(size_t )st - 1 ]-> pcie_frac ); 11182if (pipe )for (int st = 0 ;st < split_drive .n ;++ st )split_drive_b .pcie_num [st ]= split_drive .pcie_num [st ]; 11183const int hist_n = std::min (req_sp .penalty_last_n ,kPenaltyWindowCap ); 11184// #4590: the repeat / frequency / presence penalties count the tokens this reply has written, not the prompt's last 11185// tokens (same as src/program/generate.cpp). Earlier assistant turns inside the prompt are not counted either. 11186// STRATA_PENALTY_PROMPT=1 brings the old window back (the last penalty_last_n tokens of prompt + reply). The history 11187// is rebuilt from the request's prompt ids every time, so a restored conversation seeds it like a cold read. 11188static const bool pen_prompt = strata::kernels::penalty_counts_prompt (std::getenv ("STRATA_PENALTY_PROMPT" )); 11189ver .set_history (hist_n > 0 ?d_hist :nullptr ,hist_n ); 11190if (pipe )ver_b .set_history (hist_n > 0 ?d_hist :nullptr ,hist_n ); 11191bool cancelled = false; 11192tr ("prompt start" ,n - 1 ); 11193 strata::workload_trace::Scope prompt_trace ("request.prefill" ,nullptr ,n - 1 ); 11194// The prompt is read in two parts when it has a turn boundary past `resume`: up to the last <|im_start|> 11195// (the conversation so far), a checkpoint there, then the new turn's header. The next request of the same 11196// chat renders the same history - but not always the same header or the thinking of this reply - so that 11197// checkpoint is the one it reuses. 11198int64_t turn_at = -1 ; 11199if (o .prompt_cache > 0 && o .turn_token >=0 ) 11200for (int64_t i = n - 1 ;i > resume ;-- i ) 11201if (ids [(size_t )i ]== o .turn_token ) {turn_at = i ;break ; } 11202// #458 (opt-in): a short turn of --tail-role-token's role right before the new assistant turn (the 11203// server's trailing reasoning-effort turn) stays out of the checkpoint, so the next request - another 11204// effort, or the next turn of the chat - finds the conversation without it 11205if (turn_at > 0 && o .tail_role_token >=0 ) 11206for (int64_t i = turn_at - 1 ;i > resume ;-- i ) 11207if (ids [(size_t )i ]== o .turn_token ) { 11208if (ids [(size_t )i + 1 ]== o .tail_role_token )turn_at = i ; 11209break ; 11210 } 11211// A prompt read from token 0 also stops at its FIRST turn boundary: the end of the system prompt (with 11212// the tools), which every new chat of the same client shares. That checkpoint becomes the chain's root, 11213// which the retention policy pins (conv_cache.hpp), so the next new chat reads only what comes after it. 11214// (PR #65, code-martin.) Only for a system prompt of --prompt-cache-root tokens or more: a small one 11215// is cheaper to read again than the extra part costs (~0.3 s). 11216const int64_t last_turn = turn_at ;// ckpt=0 drops the split there, the root is still looked for before it 11217if (!req_ckpt )turn_at = -1 ; 11218int64_t root_at = -1 ; 11219if (o .prompt_cache > 0 && o .turn_token >=0 && o .prompt_cache_root > 0 && (read_from == 0 || resumed_from0 )) 11220for (int64_t i = 1 ;i < last_turn ;++ i ) 11221if (ids [(size_t )i ]== o .turn_token ) { 11222if (i >=o .prompt_cache_root )root_at = i ; 11223break ; 11224 } 11225static const bool message_checkpoint = [] { 11226const char * e = std::getenv ("STRATA_CACHE_MESSAGE_BOUNDARY" ); 11227return e != nullptr && std::atoi (e )!= 0 ; 11228 }(); 11229// Only add a snapshot; the existing token and image checks still decide reuse. 11230const int64_t message_at = message_checkpoint && !multi_gpu && o .prompt_cache > 0 11231 ? strata::program::message_checkpoint_boundary (ids ,resume ,turn_at ,o .turn_token ) :-1 ; 11232int64_t at = read_from ; 11233for (const int64_t to : {reread_to ,root_at ,message_at ,turn_at ,n - 1 }) { 11234if (to <=at )continue ; 11235err .clear (); 11236const bool win = windows_ok (at ,to ); 11237if (win && !refill (err )) { 11238 std::printf ("ERR refilling a lent slot failed: %s\n" ,err .c_str ()); 11239return 1 ; 11240 } 11241if (!win && !lend (to - at ,err )) { 11242 std::printf ("ERR lending the prompt path its slots failed: %s\n" ,err .c_str ()); 11243return 1 ; 11244 } 11245const auto tsp = Clock ::now (); 11246const bool sp_ok = win ?read_windows (at ,to ,err ) :read_part (at ,to ,err ); 11247if (trace ) { 11248 std::fprintf (stderr ,"strata trace: read %lld tokens (%s) in %.1f ms\n" , (long long ) (to - at ), 11249win ?"windows" :"batched" , 11250 std::chrono::duration < double , std::milli > (Clock ::now ()- tsp ).count ()); 11251 std::fflush (stderr ); 11252 } 11253if (!sp_ok ) { 11254if (yielded_at < 0 && (batch_fatal || !stop_req .load ())) { 11255 std::fprintf (stderr ,"strata serve: %s\n" ,err .c_str ()); 11256 std::printf ("ERR %s\n" ,err .c_str ()); 11257// #224: a CUDA fault (an illegal address) poisons the context for the whole process, and 11258// unwinding the destructors on it could hang until the 60 s watchdog: leave at once 11259/* 11260DPCT1010: SYCL uses exceptions to report errors and 11261does not use the error codes. The cudaPeekAtLastError 11262function call was replaced with 0. You need to rewrite 11263this code. 11264*/ 11265if (0 != 0 ) { 11266 std::fflush (stdout ); 11267 std::fflush (stderr ); 11268 std::_Exit (1 ); 11269 } 11270return 1 ; 11271 } 11272cancelled = true;// stopped while reading the prompt: refill the lent slots below, then DONE cancel 11273break ; 11274 } 11275at = to ; 11276if ((to == turn_at || to == root_at || to == message_at )&& 11277 !checkpoint_at (to ,nullptr ,to == message_at && to != turn_at && to != root_at )) {// the tail kind leaves first 11278if (!ckpt_why .empty ()|| !checkpoint_failure_is_survivable ()) {// #3350: only an unwell GPU ends the request 11279 std::printf ("ERR saving a conversation checkpoint failed%s\n" ,ckpt_why .c_str ()); 11280return 1 ; 11281 } 11282 std::fprintf (stderr ,"strata serve: checkpoint at %lld skipped: its state could not be copied out (see " 11283"above); the request goes on without it\n" , (long long )to ); 11284 } 11285if (trace && to == message_at ) 11286 std::fprintf (stderr ,"strata serve: message boundary checkpoint: %lld tokens, %lld tail\n" , 11287 (long long )message_at , (long long ) (turn_at - message_at )); 11288 } 11289if (!refill (err )) { 11290 std::printf ("ERR refilling a lent slot failed: %s\n" ,err .c_str ()); 11291return 1 ; 11292 } 11293tr ("prompt done (slots refilled)" ); 11294if (il_parts > 0 ) 11295 std::fprintf (stderr ,"strata batch: the prompt was read in %lld parts, the slots decoding %.0f ms between " 11296"them\n" , (long long )il_parts + 1 ,il_ms ); 11297prompt_trace .finish (); 11298const double prompt_ms = std::chrono::duration < double , std::milli > (Clock ::now ()- r0 ).count (); 11299 std::printf ("REUSED %lld\n" , (long long )resume );// the prompt is read; the first window comes next 11300 std::fflush (stdout ); 11301// the verify windows: the first holds the last prompt token alone 11302int64_t p = n - 1 ; 11303int32_t x = (int32_t )ids [(size_t ) (n - 1 )]; 11304// (the drafter writes max_t - 1 drafts: 8 rows with --pipeline-windows 2) 11305const size_t DS = (size_t ) std::max (S ,use_mtp ?mtp .max_t () :0 ); 11306 std::vector < int32_t > drafts (DS ,0 ),window ((size_t )S ),outv ((size_t )S ); 11307 std::vector < float > dprob (DS ,0.0f ); 11308 std::vector < int32_t > sbuf ((size_t )S ,0 ); 11309const bool sfx_on = o .suffix_draft > 0 || o .lookup_chain > 0 ; 11310if (sfx_on ) { 11311sfx .reset (); 11312for (int64_t t :ids )sfx .append ((int32_t )t ); 11313 } 11314if (o .lookup_chain > 0 ) { 11315extra_sources_reset (); 11316for (int64_t t :ids ) {const int32_t t32 = (int32_t )t ;extra_sources_append (& t32 ,1 ); } 11317 } 11318bool first_window = true; 11319int64_t produced_n = 0 ,sfx_windows = 0 ,sfx_drafts = 0 ,sfx_ok = 0 ; 11320int64_t chain_windows = 0 ,chain_drafts = 0 ,chain_ok = 0 ;// --lookup-chain's own counts 11321int64_t t2_rej [8 ]= {},t2_hit [8 ]= {};// STRATA_MTP_TOP2: rejections inside the MTP drafts by depth, runner-up hits 11322 std::vector < int32_t > cbuf ((size_t )S ,0 ),ctail ; 11323 strata::spec::PromptLookupSource lookup_src (sfx ); 11324static const bool chain_fixed = std::getenv ("STRATA_LOOKUP_CHAIN_FIXED" )!= nullptr ;// no policy gate 11325int64_t draft_offered = 0 ,draft_accepted = 0 ; 11326// what the session holds once this request is done: the prompt read so far, then every committed token 11327 std::vector < int32_t > consumed ; 11328consumed .reserve ((size_t ) (n + max_new + S )); 11329for (int64_t i = 0 ;i < n - 1 ;++ i )consumed .push_back ((int32_t )ids [(size_t )i ]); 11330// #4590: where the penalty window may start in `consumed` (see pen_prompt above): the end of the prompt without its 11331// last token, which joins the window as the fed-back head `x`. 11332size_t pen_gen0 = strata::kernels::penalty_window_from (consumed .size (),pen_prompt ); 11333if (req_pen_from >=0 && !pen_prompt )pen_gen0 = std::min < size_t > (pen_gen0 , (size_t )req_pen_from );// a continued request: its reply began earlier 11334const char * finish = "length" ; 11335const Clock ::time_point d0 = Clock ::now (); 11336 strata::workload_trace::set_context (n - 1 ,0 ,-1 ); 11337 strata::workload_trace::Scope decode_trace ("request.decode" ); 11338// STRATA_DECODE_TIMING=1: where a request's decode time goes (one line per request) 11339static const bool dec_timing = std::getenv ("STRATA_DECODE_TIMING" )!= nullptr ; 11340struct DecSnap { 11341double wait ,pool ,host ,plan ,actq ,jobs ,run ; 11342int64_t misses ,entries ,hits ,pcie ; 11343 }; 11344auto dec_snap = [& ]() { 11345return DecSnap {ver .ms_wait ,ver .ms_pool ,ver .ms_host ,drive .d .ms_plan ,drive .d .ms_actq ,drive .d .ms_jobs , 11346drive .d .ms_run ,drive .d .multi_misses ,drive .d .multi_entries ,drive .d .cache_hits , 11347drive .d .pcie_experts }; 11348 }; 11349const DecSnap ds0 = dec_snap (); 11350double dt_run = 0 ,dt_commit = 0 ,dt_draft = 0 ; 11351int64_t dec_windows = 0 ,dec_T = 0 ; 11352// STRATA_FOLLOW=<file> (test path, off by default): this request decodes the token ids in <file> (whitespace 11353// separated, read and deleted at the request's start) instead of the argmax, through the real verify windows 11354// with the MTP drafts; STRATA_FOLLOW_LOGPOS=<path> appends, for every valid window row, the teacher-forced 11355// log-probability of the forced token and the top STRATA_LOGPOS_TOPK log-probabilities 11356 std::vector < int32_t > fol ; 11357if (const char * fp = std::getenv ("STRATA_FOLLOW" )) { 11358if (std::FILE * ff = std::fopen (fp ,"r" )) { 11359long long v ; 11360while (std::fscanf (ff ,"%lld" ,& v )== 1 )fol .push_back ((int32_t )v ); 11361 std::fclose (ff ); 11362 std::remove (fp ); 11363 } 11364 } 11365static std::FILE * fol_lp = [] { 11366const char * p = std::getenv ("STRATA_FOLLOW_LOGPOS" ); 11367return p != nullptr ? std::fopen (p ,"ab" ) :nullptr ; 11368 }(); 11369const int64_t decode_hits0 = drive .d .cache_hits ; 11370pcie_auto .mark (drive .d .ms_run ,drive .d .multi_misses );// the prompt's windows are not the decode's 11371// CS-T: the RAM and file tiers of this request (the mmap source; 0 with the arena) 11372const int64_t ram0 = src .ram_reads (),files0 = src .file_reads (); 11373const uint64_t file_bytes0 = src .file_read_bytes (); 11374const int64_t decode_look0 = drive .d .cache_hits + drive .d .cache_admitted + drive .d .cache_refused ; 11375const int64_t offload0 = drive .d .offload_entries ;// #588 11376if (cancelled )finish = "cancel" ; 11377// ======== --pipeline-windows 2: the decode windows with the two cards overlapped ======== 11378// Stage 0 (the first card) runs window K+1 while stage 1 verifies window K, on the guess that K is accepted 11379// whole and that its bonus token is the drafter's. The drafter, teacher-forced through K+1's drafts, 11380// guesses K+1's bonus and drafts K+2 while stage 1 runs K+1. A wrong guess costs the speculative window: 11381// stage 0's GDN state comes back from a snapshot and K's commit is replayed with its real count (the 11382// window's own commit inputs are intact in its parity's verifier). Stage 1 never runs a speculative window 11383// and a window row computes what it would in any other window, so every emitted token is the serial loop's 11384// (with STRATA_IQ_MT_MIN=1 bit for bit; sampled requests with the same Philox draw per position). 11385bool pl_ran = false; 11386const bool pl_want = pipe && pl_pw >=2 && pl_snap2 [0 ]!= nullptr ; 11387const char * pl_serial = !pl_want ?nullptr 11388 :hist_n > 0 ?"repetition penalties (penalty_last_n)" 11389 :mtp .coupled () ?"coupled draft sampling" :nullptr ; 11390if (pl_serial != nullptr ) {// said once per reason 11391static std::set < std::string > said ; 11392if (said .insert (pl_serial ).second ) 11393 std::fprintf (stderr ,"strata serve: --pipeline-windows: a request with %s decodes serially\n" , 11394pl_serial ); 11395 } 11396if (pl_want && pl_serial == nullptr && !cancelled && produced_n < max_new ) { 11397pl_ran = true; 11398if (!pl_prepare (err )) { 11399 std::printf ("ERR %s\n" ,err .c_str ()); 11400return 1 ; 11401 } 11402struct PW { 11403int T = 0 ,seq = 0 ; 11404int64_t p = 0 ; 11405int32_t tok [8 ]= {}; 11406float prob [8 ]= {};// prob[i]: the drafter's probability of tok[i + 1] 11407float p_on = 0.0f ;// the chain's estimate that the window before is accepted whole, tok[0] its bonus 11408bool ready = false,launched = false,finished = false,committed = false,s1 = false,s1_done = false; 11409bool spec = false;// launched speculatively (behind the window before, ahead of its verdict) 11410bool made = false;// made from a chain (its outcome can be scored even when the gate held it) 11411bool sfx = false;// a lookup window (the suffix drafter's drafts) 11412int sfx_match = 0 ; 11413 }; 11414auto V0 = [& ](const PW & w )-> strata::core::Verifier & {return * PV [0 ][w .seq & 1 ]; }; 11415auto V1 = [& ](const PW & w )-> strata::core::Verifier & {return * PV [1 ][w .seq & 1 ]; }; 11416auto SDf = [& ](const PW & w ) {return (void * )PSD [w .seq & 1 ]; }; 11417const float theta = pl_theta ; 11418const int force_miss = pl_force_miss ; 11419static const bool pl_log = pipe_dbg_env ("STRATA_PIPELINE_LOG" )!= nullptr ; 11420const int dev0 = PV [0 ][0 ]-> device (); 11421 dpct::queue_ptr s0 = PV [0 ][0 ]-> stream (); 11422// the snapshot of the GDN state window `seq` reads (overlapped: before its launch, on the side stream) 11423auto snap_take = [& ](int seq )-> bool { 11424try { 11425if (!pl_snap_overlap )return true; 11426const strata::core::OnDevice on (dev0 ); 11427const int q = seq & 1 ; 11428/* 11429DPCT1024: The original code returned the error code 11430that was further consumed by the program logic. This 11431original code was replaced with 0. You may need to rewrite 11432the program logic consuming the error code. 11433*/ 11434return DPCT_CHECK_ERROR ( 11435 dpct::sync_barrier (pl_snap_pre [q ],s0 ))== 0 && 11436DPCT_CHECK_ERROR ( 11437pl_snap_stream -> ext_oneapi_submit_barrier ( 11438 {* pl_snap_pre [q ]}))== 0 && 11439/* 11440DPCT1124: cudaMemcpyAsync is migrated to 11441asynchronous memcpy API. While the origin API might 11442be synchronous, it depends on the type of operand 11443memory, so you may need to call wait() on event 11444return by memcpy API to ensure synchronization 11445behavior. 11446*/ 11447DPCT_CHECK_ERROR (pl_snap_stream -> memcpy ( 11448pl_snap2 [q ],ss .gdn_state ,pl_snap_bytes ))== 114490 && 11450/* 11451DPCT1024: The original code returned the error 11452code that was further consumed by the program logic. 11453This original code was replaced with 0. You may need 11454to rewrite the program logic consuming the error 11455code. 11456*/ 11457DPCT_CHECK_ERROR (dpct::sync_barrier ( 11458pl_snap_ev [q ],pl_snap_stream ))== 0 && 11459 (DPCT_CHECK_ERROR ( 11460 (pl_snap_stream -> ext_oneapi_empty ())), 11461 true); 11462 } 11463catch (sycl::exception const & exc ) { 11464 std::cerr <<exc .what () 11465 <<"Exception caught at file:" <<__FILE__ 11466 <<", line:" <<__LINE__ << std::endl ; 11467 std::exit (1 ); 11468 } 11469 }; 11470PW A ,B ,D ;// A: the oldest window not verified; B: the next; D: a wrong speculative window 11471bool doomed = false;// D still runs: when it finishes, stage 0 goes back to undo_w's real commit 11472PW undo_w ; 11473int undo_keep = 0 ; 11474int32_t undo_ple [2 ]= {-1 ,-1 }; 11475int chain_kind = 0 ;// 1: after an on-path verdict (A's drafts forced); 2: fresh (A's drafts from it) 11476bool early_used = false; 11477bool b_done = false;// B has been made from the chain in flight 11478int chain_n = 0 ; 11479int64_t pl_spec = 0 ,pl_on = 0 ,pl_undo = 0 ,pl_gate = 0 ,pl_fm = 0 ; 11480 std::vector < int32_t > outp (8 ,0 ); 11481bool ending = false; 11482A .T = 1 ; 11483A .p = p ; 11484A .tok [0 ]= x ; 11485A .ready = true; 11486drive .d .layers = 0 ; 11487drive .d .experts = 0 ; 11488drive .d .failed = false; 11489// the adaptive tier beside the pipeline: the serial loop's rule and adapt() on a thread of its own (its 11490// copies wait for the windows in flight, which this loop keeps serving meanwhile) 11491 std::thread pl_adapt_thr ; 11492 std::atomic < bool > pl_adapt_done {true}; 11493bool pl_adapt_ok = true; 11494// an error ends the engine, as the serial loop's do: every GPU wait is released first (#267), so no 11495// window in flight keeps spinning on a flag nobody raises, and the tier's thread can finish 11496auto die = [& ](const std::string & m )-> int { 11497 std::fprintf (stderr ,"strata serve: pipelined decode: %s\n" ,m .c_str ()); 11498 strata::core::diag_pipeline_fn ().store (nullptr ); 11499 strata::core::release_gpu_waits (stderr ); 11500if (pl_adapt_thr .joinable ())pl_adapt_thr .join (); 11501 std::printf ("ERR %s\n" ,m .c_str ()); 11502 std::fflush (stdout ); 11503return 1 ; 11504 }; 11505// STRATA_PIPELINE_TRACE=<file>: every event of the loop with its time (appended per request) 11506static const char * pl_trace_path = pipe_dbg_env ("STRATA_PIPELINE_TRACE" ); 11507 std::string pl_trace ; 11508const Clock ::time_point pl_tr0 = Clock ::now (); 11509auto tre = [& ](const char * ev ,int seq ,int x0 = 0 ,int x1 = 0 ) { 11510if (pl_trace_path == nullptr )return ; 11511char b [96 ]; 11512 std::snprintf (b ,sizeof b ,"%.3f %s %d %d %d\n" , 11513 std::chrono::duration < double , std::milli > (Clock ::now ()- pl_tr0 ).count (),ev ,seq ,x0 ,x1 ); 11514pl_trace += b ; 11515 }; 11516auto pump0 = [& ](PW & w )-> bool { 11517if (!w .launched || w .finished )return true; 11518 strata::core::Verifier & v = V0 (w ); 11519// a doomed window (its guess was wrong) gets empty plans: no expert work on the CPU or the GPU for 11520// its remaining layers, so it frees stage 0 and the pool sooner (its rows are discarded and the 11521// undo restores everything it wrote). STRATA_PIPELINE_DOOM_SKIP=0: served in full. 11522static const bool doom_skip = [] {const char * e = pipe_dbg_env ("STRATA_PIPELINE_DOOM_SKIP" );return e == nullptr || std::atoi (e )!= 0 ; }(); 11523const bool skip = doom_skip && doomed && & w == & D ; 11524if (v .service (skip ?nullptr :& drive_pool_split ,SDf (w ),err )< 0 )return false; 11525if (v .done (err )) { 11526if (!v .pl_finish (nullptr ,err ))return false; 11527w .finished = true; 11528tre ("F0" ,w .seq ,w .T ,w .spec ); 11529 } 11530return err .empty (); 11531 }; 11532// the serial loop's window size over the chain's outputs from index `from` (`avail` of them) 11533auto t_rule = [& ](const float * pr ,int from ,int avail ) { 11534int T = S_mtp ; 11535if (req_spec_min_p > 0.0 ) { 11536T = 1 ; 11537while (T < S_mtp && from + T - 1 < avail && pr [from + T - 1 ] >= (float )req_spec_min_p )++ T ; 11538 } 11539return std::max (1 , std::min (T ,1 + avail - from )); 11540 }; 11541// B from the chain's outputs: its row 0 is the guess at index `base`, its drafts follow 11542auto make_b = [& ](const int32_t * oc ,const float * op ,int base ,int avail ,float pa ) { 11543B = PW {}; 11544if (base >=avail )return ; 11545B .seq = A .seq + 1 ; 11546B .p = A .p + A .T ; 11547B .tok [0 ]= oc [base ]; 11548B .T = t_rule (op ,base + 1 ,avail ); 11549for (int i = 1 ;i < B .T ;++ i ) { 11550B .tok [i ]= oc [base + i ]; 11551B .prob [i - 1 ]= op [base + i ]; 11552 } 11553B .p_on = pa * op [base ]; 11554if (force_miss > 0 && ++ pl_fm %force_miss == 0 )B .tok [0 ]= B .tok [0 ]== 0 ?1 :0 ; 11555B .ready = true; 11556B .made = true; 11557 }; 11558// events after all the work both stages' streams hold now, and whether they have passed 11559 dpct::event_ptr fence_ev [2 ]= {nullptr ,nullptr }, 11560exch_ev [2 ]= {nullptr ,nullptr }; 11561 { 11562const strata::core::OnDevice on0 (dev0 ); 11563fence_ev [0 ]= new sycl::event (); 11564exch_ev [0 ]= new sycl::event (); 11565 } 11566 { 11567const strata::core::OnDevice on1 (stages [0 ]-> dev ); 11568fence_ev [1 ]= new sycl::event (); 11569exch_ev [1 ]= new sycl::event (); 11570 } 11571auto stage_record = [& ](dpct::event_ptr * ev ) { 11572try { 11573 { 11574const strata::core::OnDevice on (dev0 ); 11575 dpct::sync_barrier (ev [0 ],s0 ); 11576 (void )DPCT_CHECK_ERROR ((s0 -> ext_oneapi_empty ())); 11577 } 11578const strata::core::OnDevice on (stages [0 ]-> dev ); 11579 dpct::sync_barrier (ev [1 ],PV [1 ][0 ]-> stream ()); 11580 (void )DPCT_CHECK_ERROR ( 11581 ((PV [1 ][0 ]-> stream ())-> ext_oneapi_empty ())); 11582 } 11583catch (sycl::exception const & exc ) { 11584 std::cerr <<exc .what () 11585 <<"Exception caught at file:" <<__FILE__ 11586 <<", line:" <<__LINE__ << std::endl ; 11587 std::exit (1 ); 11588 } 11589 }; 11590auto stage_passed = [& ](dpct::event_ptr * ev ) { 11591try { 11592return dpct::sycl_event_query (ev [0 ])!= 1 && 11593 dpct::sycl_event_query (ev [1 ])!= 1 ; 11594 } 11595catch (sycl::exception const & exc ) { 11596 std::cerr <<exc .what () 11597 <<"Exception caught at file:" <<__FILE__ 11598 <<", line:" <<__LINE__ << std::endl ; 11599 std::exit (1 ); 11600 } 11601 }; 11602// adapt()'s fence, on the tier's thread: it waits on the HOST. A device-side wait (the refill streams 11603// waiting for the stages' events) would queue copies behind windows that need this loop, beside it. 11604adapt_fence = [& ]() { 11605stage_record (fence_ev ); 11606while (!stage_passed (fence_ev )) std::this_thread::yield (); 11607 }; 11608src .prepare_overrides (); 11609// The swaps land in two steps. Once their copies are done, the incoming experts are resident (the plans 11610// from then on use their slots). What gives their RAM back - the resident RAM mode's exchange, the 11611// released or unpinned pages - waits until every window that may still pull them over PCIe (a plan 11612// published before that point) has completed: both stages' streams are fenced there. 11613bool exch_wait = false; 11614 std::vector < int32_t > pl_landed ; 11615auto pl_release = [& ]() { 11616unpin_blobs (pin_live ); 11617src .commit_exchanges (); 11618for (const int32_t i :pl_landed )srcp -> release ((int64_t )i /g .n_expert , (int64_t )i %g .n_expert ); 11619pl_landed .clear (); 11620exch_wait = false; 11621 }; 11622auto pl_apply = [& ]() { 11623try { 11624if (exch_wait ) { 11625if (stage_passed (exch_ev ))pl_release (); 11626return ; 11627 } 11628if (pending .empty ()|| 11629adapt_ev -> get_info < 11630 sycl::info::event::command_execution_status > ()!= 11631 sycl::info::event_command_status::complete )return ; 11632for (auto & st :stages ) 11633if (st -> adapt_live && 11634 (st -> adapt_ev ) 11635-> get_info < 11636 sycl::info::event:: 11637command_execution_status > ()!= 11638 sycl::info::event_command_status:: 11639complete )return ; 11640for (auto & st :stages )st -> adapt_live = false; 11641for (const auto & [i ,slot ] :pending ) { 11642host_res [(size_t )i ]= slot ; 11643pl_landed .push_back (i ); 11644 } 11645pending .clear (); 11646pending_age = 0 ; 11647res_upload (); 11648stage_record (exch_ev ); 11649exch_wait = true; 11650 } 11651catch (sycl::exception const & exc ) { 11652 std::cerr <<exc .what () 11653 <<"Exception caught at file:" <<__FILE__ 11654 <<", line:" <<__LINE__ << std::endl ; 11655 std::exit (1 ); 11656 } 11657 }; 11658auto pl_adapt = [& ]()-> bool { 11659if (pl_adapt_thr .joinable ()&& pl_adapt_done .load ()) { 11660pl_adapt_thr .join (); 11661if (!pl_adapt_ok )return false; 11662 } 11663if (pl_adapt_thr .joinable ())return true;// still adapting 11664pl_apply (); 11665if (!drive .d .usage .empty ()&& o .adapt_every > 0 && (rounds %o .adapt_every )== 0 && pending .empty ()&& 11666 !exch_wait ) { 11667pl_adapt_done = false; 11668pl_adapt_thr = std::thread ([& ] {pl_adapt_ok = adapt ();pl_adapt_done = true; }); 11669 } 11670return true; 11671 }; 11672// the serial loop's prompt lookup for a fresh window: where the text repeats an earlier stretch and the 11673// drafter's own first guess agrees, the policy may take the lookup's continuation (up to S rows) 11674 std::vector < int32_t > pl_sbuf ((size_t ) (2 * S ),0 ); 11675// a lookup window's continuation goes on past it: the next window (B) is taken from the same lookup and 11676// speculated behind it (a copied stretch is mostly accepted whole). STRATA_PIPELINE_LOOKUP_PON: B's 11677// estimate (default 0.75; 0 = no lookup B) 11678static const float pl_lookup_pon = [] { 11679const char * v = pipe_dbg_env ("STRATA_PIPELINE_LOOKUP_PON" ); 11680return v ? (float ) std::atof (v ) :0.75f ; 11681 }(); 11682auto pick_lookup = [& ](PW & w ,const int32_t * chain0 ) { 11683if (o .suffix_draft <=0 || w .seq == 0 )return ; 11684const int k = sfx .propose (2 * S - 1 ,pl_sbuf .data ()); 11685const int match = sfx .last_match (); 11686if (k <=0 || pl_sbuf [0 ]!= chain0 [0 ])return ; 11687const strata::spec::DraftPolicy ::Pick pk = policy .choose (w .T , std::min (k ,S - 1 ),match ); 11688if (!pk .lookup )return ; 11689w .T = pk .t ; 11690for (int i = 1 ;i < w .T ;++ i ) { 11691w .tok [i ]= pl_sbuf [(size_t )i - 1 ]; 11692w .prob [i - 1 ]= 1.0f ; 11693 } 11694w .sfx = true; 11695w .sfx_match = match ; 11696const int rest = k - (w .T - 1 );// lookup tokens past w: B's row 0 (w's bonus guess) and its drafts 11697if (& w == & A && rest >=1 && pl_lookup_pon > 0.0f && !b_done ) { 11698B = PW {}; 11699B .seq = A .seq + 1 ; 11700B .p = A .p + A .T ; 11701B .T = std::min (S ,rest ); 11702for (int i = 0 ;i < B .T ;++ i )B .tok [i ]= pl_sbuf [(size_t ) (A .T - 1 + i )]; 11703for (int i = 1 ;i < B .T ;++ i )B .prob [i - 1 ]= 1.0f ; 11704B .p_on = pl_lookup_pon ; 11705B .ready = true; 11706B .made = true; 11707b_done = true;// the chain in flight makes no B for this A 11708tre ("CD" ,A .seq + 1 ,3 , (int ) (1000.0f * B .p_on )); 11709 } 11710 }; 11711const Clock ::time_point pl_t0 = Clock ::now (); 11712for (int st = 0 ;st < 2 ;++ st ) 11713for (int par = 0 ;par < 2 ;++ par )g_pl_diag .v [st ][par ]= PV [st ][par ]; 11714 strata::core::diag_pipeline_fn ().store (& pl_diag_print ); 11715auto pw_bits = [](const PW & w ) { 11716return (w .ready ?1 :0 ) | (w .launched ?2 :0 ) | (w .finished ?4 :0 ) | (w .committed ?8 :0 ) | 11717 (w .s1 ?16 :0 ) | (w .s1_done ?32 :0 ); 11718 }; 11719// per window class (0: fresh, 1: run speculatively ahead of its predecessor's verdict): the time from 11720// the previous verdict, the tokens it emitted, how many 11721double cls_ms [2 ]= {0 ,0 },cls_tok [2 ]= {0 ,0 },cls_n [2 ]= {0 ,0 }; 11722int64_t cal_n [10 ]= {},cal_on [10 ]= {};// per p_on decile: windows scored, on the path 11723double last_verdict = 0.0 ; 11724int64_t pl_disagree = 0 ,pl_late = 0 ; 11725static const bool pl_prestage = [] {// STRATA_PIPELINE_PRESTAGE=0: B staged at its launch 11726const char * v = pipe_dbg_env ("STRATA_PIPELINE_PRESTAGE" ); 11727return v == nullptr || std::atoi (v )!= 0 ; 11728 }(); 11729static const bool pl_agree = [] {// STRATA_PIPELINE_AGREE=0: only the old chain's probabilities 11730const char * v = pipe_dbg_env ("STRATA_PIPELINE_AGREE" ); 11731return v == nullptr || std::atoi (v )!= 0 ; 11732 }(); 11733// Private opt-in; unusual debug disagreement/forced-miss modes 11734// keep the complete normal path. No public setting changes. 11735const char * demand_env = std::getenv ("STRATA_PRIVATE_MTP_DEMAND" ); 11736 strata::private_demand::begin (& mtp ,demand_env && demand_env [0 ]== '1' && pl_agree && force_miss == 0 ); 11737auto ms_now = [& ]() {return std::chrono::duration < double , std::milli > (Clock ::now ()- pl_t0 ).count (); }; 11738while (true) { 11739g_pl_diag .iters .fetch_add (1 , std::memory_order_relaxed ); 11740g_pl_diag .a_seq .store (A .seq , std::memory_order_relaxed ); 11741g_pl_diag .a_bits .store (pw_bits (A ), std::memory_order_relaxed ); 11742g_pl_diag .b_bits .store (pw_bits (B ), std::memory_order_relaxed ); 11743g_pl_diag .d_bits .store (pw_bits (D ), std::memory_order_relaxed ); 11744g_pl_diag .chain_kind .store (chain_kind , std::memory_order_relaxed ); 11745g_pl_diag .chain_live .store (mtp .chain_live () ?1 :0 , std::memory_order_relaxed ); 11746g_pl_diag .doomed .store (doomed ?1 :0 , std::memory_order_relaxed ); 11747g_pl_diag .ending .store (ending ?1 :0 , std::memory_order_relaxed ); 11748// ---- every window in flight served 11749if ((doomed && !pump0 (D ))|| !pump0 (A )|| !pump0 (B ))return die (err ); 11750if (A .s1 && !A .s1_done ) { 11751 strata::core::Verifier & v = V1 (A ); 11752if (v .service (& drive_pool_split ,SDf (A ),err )< 0 )return die (err ); 11753if (v .done (err )) { 11754if (!v .pl_finish (outp .data (),err ))return die (err ); 11755A .s1_done = true; 11756tre ("F1" ,A .seq ,A .T ); 11757 }else if (!err .empty ())return die (err ); 11758 } 11759if (drive .d .failed )return die (drive .d .fail ?drive .d .fail :"the expert pool failed" ); 11760// ---- a wrong speculative window has finished: stage 0 back to the verified window's real commit 11761if (doomed && D .finished ) { 11762 { 11763const strata::core::OnDevice on (dev0 ); 11764/* 11765DPCT1124: cudaMemcpyAsync is migrated to 11766asynchronous memcpy API. While the origin API might 11767be synchronous, it depends on the type of operand 11768memory, so you may need to call wait() on event 11769return by memcpy API to ensure synchronization 11770behavior. 11771*/ 11772if (DPCT_CHECK_ERROR (s0 -> memcpy ( 11773ss .gdn_state , 11774pl_snap2 [pl_snap_overlap ? (undo_w .seq & 1 ) 11775 :0 ], 11776pl_snap_bytes ))!= 0 ) 11777return die ("restoring the GDN snapshot failed" ); 11778 } 11779ss .ple_prev [0 ]= undo_ple [0 ]; 11780ss .ple_prev [1 ]= undo_ple [1 ]; 11781if (!V0 (undo_w ).pl_commit_async (undo_keep ,err ))return die (err ); 11782doomed = false; 11783++ pl_undo ; 11784tre ("U" ,undo_w .seq ,undo_keep ); 11785 } 11786if (ending ) { 11787if (!doomed )break ; 11788continue ; 11789 } 11790// ---- the drafter's chain, read as its outputs land (an event after each): a fresh A once its size 11791// is decided, then B once ITS size is decided - its bonus guess and a draft below spec_min_p (or 11792// S_mtp - 1 drafts) - so stage 0 need not wait for the whole chain 11793if (chain_kind != 0 ) { 11794const int k_ready = mtp .chain_outputs_ready (err ); 11795if (k_ready < 0 )return die (err ); 11796if (chain_kind == 2 && !early_used ) { 11797// A's size is decided by its first outputs: a draft below spec_min_p ends it (the serial 11798// loop's rule), so A goes to stage 0 as soon as that is known, not after all S_mtp - 1 11799const int k = k_ready ; 11800bool decided = k >=S_mtp - 1 ; 11801if (!decided && req_spec_min_p > 0.0 ) 11802for (int j = 0 ;j < k ;++ j ) 11803if (mtp .chain_prob ()[j ]< (float )req_spec_min_p ) {decided = true;break ; } 11804if (decided ) { 11805A .T = t_rule (mtp .chain_prob (),0 , std::min (k ,S_mtp - 1 )); 11806for (int i = 1 ;i < A .T ;++ i ) { 11807A .tok [i ]= mtp .chain_tok ()[i - 1 ]; 11808A .prob [i - 1 ]= mtp .chain_prob ()[i - 1 ]; 11809 } 11810pick_lookup (A ,mtp .chain_tok ()); 11811A .ready = true; 11812early_used = true; 11813tre ("CE" ,A .seq ,A .T ); 11814 } 11815 } 11816 11817// A's first low probability (or S-1 outputs) is read 11818// above before stopping a fresh chain. Lookup A keeps 11819// the original complete chain. Products use the same 11820// float order; future probabilities can only lower pa. 11821if (auto * ds = strata::private_demand::get (& mtp )) { 11822const int k = k_ready ; 11823bool final = k >=ds -> limit ,dead_b = false; 11824if (k > 0 && (chain_kind == 1 || early_used )&& !A .sfx ) { 11825const int base = A .T - 1 ; 11826const float * op = mtp .chain_prob (); 11827const int32_t * oc = mtp .chain_tok (); 11828float pa = 1.0f ; 11829bool finite = true,agree = true; 11830if (chain_kind == 1 ) { 11831for (int j = 0 ;j < std::min (k ,base );++ j ) { 11832finite = finite && std::isfinite (op [j ])&& op [j ] >=0.0f && op [j ] <=1.0f ; 11833agree = agree && oc [j ]== A .tok [j + 1 ]; 11834pa *=op [j ]; 11835 } 11836 }else { 11837for (int j = 0 ;j < base ;++ j ) { 11838finite = finite && std::isfinite (A .prob [j ])&& A .prob [j ] >=0.0f && A .prob [j ] <=1.0f ; 11839pa *=A .prob [j ]; 11840 } 11841 } 11842if (finite && (!agree || pa < theta ))dead_b = true; 11843if (finite && k > base && std::isfinite (op [base ])&& op [base ] >=0.0f && op [base ] <=1.0f && pa * op [base ]< theta ) 11844dead_b = true; 11845bool size_known = k >=base + S_mtp ; 11846if (!size_known && k > base + 1 && req_spec_min_p > 0.0 ) 11847for (int j = base + 1 ;j < k ;++ j ) 11848if (op [j ]< (float )req_spec_min_p ) {size_known = true;break ; } 11849final = final || dead_b || size_known ; 11850 } 11851if (dead_b && !b_done ) { 11852// Do not fabricate an uncomputed bonus or B 11853// calibration record. Such a B cannot launch. 11854B = PW {};b_done = true;++ ds -> dead ; 11855 } 11856ds -> final = final ; 11857ds -> target = final ?ds -> submitted : std::min (ds -> limit ,k + 1 ); 11858 } 11859 11860const int r = mtp .chain_poll (err ); 11861if (r < 0 )return die (err ); 11862const auto * demand_state = strata::private_demand::get (& mtp ); 11863const int completed_n = demand_state ?demand_state -> submitted :chain_n ; 11864const int k = r == 1 ?completed_n :k_ready ; 11865// Optional functional evidence, excluded from timing. 11866static const bool demand_detail = std::getenv ("STRATA_PRIVATE_MTP_DEMAND_LOG" )!= nullptr ; 11867if (demand_detail && demand_state && r == 1 ) { 11868 std::fprintf (stderr ,"STRATA_DEMAND_DETAIL {\"chain\":%lld,\"seq\":%d,\"kind\":%d,\"n_out\":%d,\"k\":%d,\"A_T\":%d,\"A_pos\":%lld,\"A_sfx\":%s,\"A_tok\":[" , 11869demand_state -> chains ,A .seq ,chain_kind ,chain_n ,k ,A .T , (long long )A .p ,A .sfx ?"true" :"false" ); 11870for (int j = 0 ;j < A .T ;++ j ) std::fprintf (stderr ,"%s%d" ,j ?"," :"" ,A .tok [j ]); 11871 std::fprintf (stderr ,"],\"tok\":[" ); 11872for (int j = 0 ;j < k ;++ j ) std::fprintf (stderr ,"%s%d" ,j ?"," :"" ,mtp .chain_tok ()[j ]); 11873 std::fprintf (stderr ,"],\"prob\":[" ); 11874for (int j = 0 ;j < k ;++ j ) std::fprintf (stderr ,"%s%.9g" ,j ?"," :"" ,double (mtp .chain_prob ()[j ])); 11875 std::fprintf (stderr ,"]}\n" ); 11876 } 11877 11878const int32_t * oc = mtp .chain_tok (); 11879const float * op = mtp .chain_prob (); 11880if (r == 1 && chain_kind == 2 && !early_used ) { 11881A .T = t_rule (op ,0 , std::min (chain_n ,S_mtp - 1 )); 11882for (int i = 1 ;i < A .T ;++ i ) { 11883A .tok [i ]= oc [i - 1 ]; 11884A .prob [i - 1 ]= op [i - 1 ]; 11885 } 11886pick_lookup (A ,oc ); 11887A .ready = true; 11888early_used = true; 11889 } 11890if (!b_done && (chain_kind == 1 || early_used )) { 11891const int base = A .T - 1 ;// B's row 0: the guess of A's bonus 11892bool decided = r == 1 || k >=base + S_mtp ; 11893if (!decided && k > base + 1 && req_spec_min_p > 0.0 ) 11894for (int j = base + 1 ;j < k ;++ j ) 11895if (op [j ]< (float )req_spec_min_p ) {decided = true;break ; } 11896if (decided ) { 11897float pa = 1.0f ; 11898if (chain_kind == 1 ) { 11899// forced through A's drafts: its outputs there are the drafter's own picks from 11900// A's verified predecessor, a better estimate of A's acceptance than the chain that 11901// drafted A; a disagreement means A is unlikely to be accepted whole 11902bool agree = true; 11903for (int i = 0 ;i + 1 < A .T ;++ i ) { 11904if (oc [i ]!= A .tok [i + 1 ])agree = false; 11905pa *=pl_agree ?op [i ] :A .prob [i ]; 11906 } 11907if (pl_agree && !agree ) {pa = 0.0f ;++ pl_disagree ; } 11908 }else { 11909for (int i = 0 ;i + 1 < A .T ;++ i )pa *=A .prob [i ]; 11910 } 11911if (!A .sfx )make_b (oc ,op ,base ,k ,pa );// a lookup window's bonus is not the chain's 11912// stage B now (its PLE rows from the tokens before it as they will be once A is 11913// committed whole), so its launch behind A is only the graph launch (never while a 11914// rollback is pending: B's verifier is the one the undo commit reads) 11915if (B .ready && B .p_on >=theta && pl_prestage && !V0 (B ).in_flight ()&& !doomed ) { 11916int32_t prev [2 ]= {ss .ple_prev [0 ],ss .ple_prev [1 ]}; 11917for (int i = 0 ;i < A .T ;++ i ) {prev [0 ]= prev [1 ];prev [1 ]= A .tok [i ]; } 11918if (!V0 (B ).prestage (B .T ,B .tok ,B .p ,prev ,err ))return die (err ); 11919 } 11920b_done = true; 11921tre ("CD" ,A .seq ,chain_kind , (int ) (1000.0f * B .p_on )); 11922if (pl_log ) 11923 std::fprintf (stderr ,"strata pipeline: chain %d for p=%lld T=%d: B T=%d p_on %.3f (%d " 11924"outputs)\n" ,chain_kind , (long long )A .p ,A .T ,B .T ,B .p_on ,k ); 11925 } 11926 } 11927if (r == 1 )chain_kind = 0 ; 11928 } 11929// ---- stage 0: A (never while a wrong window still holds stage 0's state) 11930if (A .ready && !A .launched && !doomed ) { 11931if (A .p + A .T > o .max_context ) {ending = true;continue ; } 11932if (!snap_take (A .seq ))return die ("the GDN snapshot failed" ); 11933if (!V0 (A ).pl_launch (A .T ,A .tok ,A .p ,err ))return die (err ); 11934A .launched = true; 11935tre ("L0" ,A .seq ,A .T ,0 ); 11936 } 11937// ---- stage 0: B, speculatively, right behind A 11938if (B .ready && !B .launched && A .finished && !A .committed && !doomed ) { 11939if (B .p_on >=theta && B .p + B .T <=o .max_context ) { 11940 { 11941const strata::core::OnDevice on (dev0 ); 11942if (pl_snap_overlap 11943 ?DPCT_CHECK_ERROR ( 11944s0 -> ext_oneapi_submit_barrier ( 11945 {* pl_snap_ev [A .seq & 1 ]}))!= 119460 11947/* 11948DPCT1124: cudaMemcpyAsync is 11949migrated to asynchronous memcpy API. 11950While the origin API might be 11951synchronous, it depends on the type of 11952operand memory, so you may need to call 11953wait() on event return by memcpy API to 11954ensure synchronization behavior. 11955*/ 11956 :DPCT_CHECK_ERROR (s0 -> memcpy ( 11957pl_snap2 [0 ],ss .gdn_state , 11958pl_snap_bytes ))!= 0 ) 11959return die ("the GDN snapshot failed" ); 11960 } 11961undo_ple [0 ]= ss .ple_prev [0 ]; 11962undo_ple [1 ]= ss .ple_prev [1 ]; 11963if (!V0 (A ).pl_commit_async (A .T ,err )|| !snap_take (B .seq )|| 11964 !V0 (B ).pl_launch (B .T ,B .tok ,B .p ,err )) 11965return die (err .empty () ? std::string ("the GDN snapshot failed" ) :err ); 11966A .committed = true; 11967B .launched = true; 11968B .spec = true; 11969tre ("L0" ,B .seq ,B .T ,1 ); 11970++ pl_spec ; 11971 }else { 11972B .ready = false;// not worth it: A's verdict decides the next window 11973++ pl_gate ; 11974 } 11975 } 11976// ---- stage 1: A, once its stage 0 is done 11977if (A .finished && !A .s1 && strata::private_demand::can_enqueue_s1 (& mtp )) { 11978if (chain_kind == 1 && !B .ready )++ pl_late ;// stage 0 idles until the chain has B 11979if (!V1 (A ).pl_launch (A .T ,A .tok ,A .p ,err ))return die (err ); 11980A .s1 = true; 11981tre ("L1" ,A .seq ,A .T ); 11982 } 11983// ---- A's verdict 11984if (!A .s1_done )continue ; 11985// the drafter must be idle before the next chain. The chain needs nothing from the host, so this 11986// wait is bounded even with B (made from its first outputs) in flight on stage 0; in practice the 11987// chain ended long before a verdict that needs a whole stage-1 window. 11988while (chain_kind != 0 && mtp .chain_live ()) 11989if (mtp .chain_poll (err )< 0 )return die (err ); 11990if (chain_kind != 0 && !B .launched && !B .made )B = PW {}; 11991chain_kind = 0 ; 11992int a = 0 ; 11993while (a < A .T - 1 && A .tok [a + 1 ]== outp [(size_t )a ])++ a ; 11994if (!V1 (A ).pl_commit_async (a + 1 ,err ))return die (err ); 11995for (int i = 0 ;i <=a ;++ i )consumed .push_back (A .tok [i ]); 11996draft_offered += A .T - 1 ; 11997draft_accepted += a ; 11998++ rounds ; 11999++ dec_windows ; 12000dec_T += A .T ; 12001bool eos = false; 12002for (int i = 0 ;i <=a && produced_n < max_new && !eos ;++ i ) { 12003 std::printf ("T %d\n" , (int )outp [(size_t )i ]); 12004 strata::core::progress_beat (); 12005++ produced_n ; 12006if (o .suffix_draft > 0 )sfx .append (outp [(size_t )i ]); 12007eos = std::find (o .eos_ids .begin (),o .eos_ids .end (), (int64_t )outp [(size_t )i ])!= o .eos_ids .end (); 12008 } 12009 std::fflush (stdout ); 12010if (eos )finish = "stop" ; 12011else if (stop_req .load ())finish = "cancel" ; 12012const bool last = eos || produced_n >=max_new || stop_req .load (); 12013const bool on = B .launched && a == A .T - 1 && B .tok [0 ]== outp [(size_t )A .T - 1 ]; 12014if (B .made ) {// the gate's calibration: would B have been on the path, by its estimate p_on 12015const bool would = a == A .T - 1 && B .tok [0 ]== outp [(size_t )A .T - 1 ]; 12016const int bin = std::min (9 , std::max (0 , (int ) (B .p_on * 10.0f ))); 12017cal_n [bin ]+= 1 ; 12018cal_on [bin ]+= would ?1 :0 ; 12019 } 12020tre ("V" ,A .seq ,a ,on ?1 : (B .launched ?-1 :0 )); 12021 { 12022const double now = ms_now (); 12023const int c = A .spec ?1 :0 ; 12024if (A .sfx ) {++ sfx_windows ;sfx_drafts += A .T - 1 ;sfx_ok += a ; } 12025if (A .seq > 0 && !last )policy .observe (A .sfx ,A .T ,a ,A .sfx_match ,now - last_verdict ); 12026cls_ms [c ]+= now - last_verdict ; 12027cls_tok [c ]+= a + 1 ; 12028cls_n [c ]+= 1 ; 12029last_verdict = now ; 12030 } 12031if (pl_log ) 12032 std::fprintf (stderr ,"strata pipeline: verdict p=%lld T=%d a=%d B %s%s\n" , (long long )A .p ,A .T ,a , 12033B .launched ?"launched" :B .ready ?"ready" :"none" ,on ?" ON" :"" ); 12034x = outp [(size_t )a ]; 12035p = A .p + a + 1 ; 12036// STRATA_PIPELINE_DUMP=<file>: after every window, append a hash and the sum of the first stage's 12037// sequence state (its GDN rows: the recurrence state plus the conv history). Two arms that ran 12038// the same tokens must agree here; the first position where they do not is the state that 12039// escapes. Debug only: it waits for the stage's stream, so it distorts the timing. 12040static const char * pl_dump = std::getenv ("STRATA_PIPELINE_DUMP" );// read once 12041if (pl_dump != nullptr ) { 12042const int64_t gdn_floats = g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size + 12043g .ssm_conv_channels * (g .ssm_d_conv - 1 ); 12044const size_t n = (size_t )ss .gdn_alloc * (size_t )gdn_floats ; 12045 std::vector < float > h (n ); 12046 (void )DPCT_CHECK_ERROR (s0 -> memcpy (h .data (),ss .gdn_state ,n * sizeof (float )).wait ()); 12047// the recurrence state and the conv history hashed apart: a wrong row shows which half it is 12048const size_t n_rec = (size_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size ; 12049const size_t n_cnv = (size_t )g .ssm_conv_channels * (g .ssm_d_conv - 1 ); 12050double rec_sum = 0.0 ,cnv_sum = 0.0 ; 12051uint64_t rec_hash = 1469598103934665603ull ,cnv_hash = 1469598103934665603ull ; 12052for (int64_t l = 0 ;l < ss .gdn_alloc ;++ l ) { 12053const size_t base = (size_t )l * (size_t )gdn_floats ; 12054uint64_t rh = 1469598103934665603ull ,ch = 1469598103934665603ull ; 12055for (size_t i = 0 ;i < n_rec ;++ i ) { 12056uint64_t b = 0 ; 12057 std::memcpy (& b ,& h [base + i ],sizeof (float )); 12058rh = (rh ^b )* 1099511628211ull ; 12059rec_sum += (double )h [base + i ]; 12060 } 12061for (size_t i = 0 ;i < n_cnv ;++ i ) { 12062uint64_t b = 0 ; 12063 std::memcpy (& b ,& h [base + n_rec + i ],sizeof (float )); 12064ch = (ch ^b )* 1099511628211ull ; 12065cnv_sum += (double )h [base + n_rec + i ]; 12066 } 12067rec_hash = (rec_hash ^rh )* 1099511628211ull ; 12068cnv_hash = (cnv_hash ^ch )* 1099511628211ull ; 12069 } 12070if (std::FILE * df = std::fopen (pl_dump ,"a" )) { 12071 std::fprintf (df ,"pos %lld windows %lld rec %.9g %016llx cnv %.9g %016llx\n" , (long long )p , 12072 (long long )dec_windows ,rec_sum , (unsigned long long )rec_hash ,cnv_sum , 12073 (unsigned long long )cnv_hash ); 12074 std::fclose (df ); 12075 } 12076 } 12077if (!last && !pl_adapt ())return die ("an adaptive refill failed" ); 12078if (on && !last ) { 12079++ pl_on ; 12080// the chain over A, forced through B's drafts: B's bonus guess and the next window's drafts 12081mtp .set_source_R (V1 (A ).final_R (0 )); 12082chain_n = std::min (strata::kernels::kVerifyMaxT - 1 ,B .T + S_mtp - 1 ); 12083if (!mtp .chain_launch (A .T ,outp .data (),A .p ,a ,B .tok + 1 ,B .T - 1 ,chain_n ,chain_n ,err )) 12084return die (err ); 12085chain_kind = 1 ; 12086tre ("CL" ,A .seq ,1 ); 12087early_used = false; 12088b_done = false; 12089A = B ; 12090B = PW {}; 12091 }else { 12092if (B .launched ) {// a wrong guess (or the end): undo once it has finished 12093doomed = true; 12094D = B ; 12095undo_w = A ; 12096undo_keep = a + 1 ; 12097 }else if (!A .committed ) { 12098if (!V0 (A ).pl_commit_async (a + 1 ,err ))return die (err ); 12099 } 12100// B is D now (or dropped): never pump it twice (whichever copy saw the window complete first 12101// would finish it, and the other would wait for it forever) 12102B = PW {}; 12103if (!last ) { 12104mtp .set_source_R (V1 (A ).final_R (0 )); 12105chain_n = strata::kernels::kVerifyMaxT - 1 ; 12106if (!mtp .chain_launch (A .T ,outp .data (),A .p ,a ,nullptr ,0 ,chain_n ,chain_n ,err )) 12107return die (err ); 12108chain_kind = 2 ; 12109tre ("CL" ,A .seq ,2 ); 12110early_used = false; 12111b_done = false; 12112PW nA ; 12113nA .seq = A .seq + 1 ; 12114nA .p = A .p + a + 1 ; 12115nA .tok [0 ]= outp [(size_t )a ]; 12116A = nA ; 12117 } 12118 } 12119if (last )ending = true; 12120 } 12121// Context/cancel exits can precede the frontier. Submit and 12122// retire the remainder before the old drain/reuse boundary. 12123 strata::private_demand::drain (& mtp ); 12124if (mtp .chain_live ()&& mtp .chain_outputs_ready (err )< 0 )return die (err ); 12125pl_drain ();// nothing in flight: both stages' commits and the drafter have landed 12126 strata::core::diag_pipeline_fn ().store (nullptr ); 12127if (pl_adapt_thr .joinable ())pl_adapt_thr .join ();// its copies waited only for finished work 12128adapt_fence = nullptr ; 12129if (exch_wait )pl_release ();// every window has completed (drained) 12130for (dpct::event_ptr ev :fence_ev )if (ev ) 12131 dpct::destroy_event (ev ); 12132for (dpct::event_ptr ev :exch_ev )if (ev ) 12133 dpct::destroy_event (ev ); 12134if (pl_trace_path != nullptr && !pl_trace .empty ()) { 12135if (std::FILE * f = std::fopen (pl_trace_path ,"a" )) { 12136 std::fprintf (f ,"# request p0=%lld\n" , (long long ) (n - 1 )); 12137 std::fwrite (pl_trace .data (),1 ,pl_trace .size (),f ); 12138 std::fclose (f ); 12139 } 12140 } 12141// the odd windows' counters and GPU profiles into the verifiers that report them 12142PV [0 ][0 ]-> absorb_stats (* PV [0 ][1 ]); 12143PV [1 ][0 ]-> absorb_stats (* PV [1 ][1 ]); 12144if (!pl_adapt_ok ) { 12145 std::printf ("ERR an adaptive refill failed\n" ); 12146return 1 ; 12147 } 12148while (mtp .chain_live ()&& mtp .chain_poll (err )== 0 ) {} 12149 12150// The request and all verifier work have drained. Replay the 12151// actual last chain's staging and source R (still bound) with 12152// the same causal KV prefix. No model or device allocation. 12153const char * demand_micro = std::getenv ("STRATA_PRIVATE_MTP_DEMAND_MICRO" ); 12154if (auto * ds = strata::private_demand::get (& mtp ); 12155ds && demand_micro && ds -> ordinal == std::atoi (demand_micro )) { 12156const auto saved = * ds ; 12157const double old_ms = mtp .ms_draft ; 12158const int64_t old_rounds = mtp .rounds ; 12159const int outputs = saved .limit ; 12160int32_t ref_tok [8 ]= {};float ref_prob [8 ]= {}; 12161auto run_chain = [& ](bool segmented ,int take ,bool set_reference ) { 12162ds -> enabled = segmented ; 12163if (!mtp .chain_launch (saved .T ,saved .tokens ,saved .p ,saved .a , 12164saved .force ,saved .n_force ,outputs ,outputs ,err ))return false; 12165if (segmented ) { 12166while (mtp .chain_live ()) { 12167const int ready = mtp .chain_outputs_ready (err ); 12168if (ready < 0 )return false; 12169ds -> final = ready >=take ; 12170ds -> target = ds -> final ?ds -> submitted : std::min (take ,ready + 1 ); 12171const int rc = mtp .chain_poll (err ); 12172if (rc < 0 )return false; 12173 } 12174 }else { 12175int rc ; 12176do {rc = mtp .chain_poll (err ); }while (rc == 0 ); 12177if (rc < 0 )return false; 12178 } 12179if (set_reference ) { 12180 std::memcpy (ref_tok ,mtp .chain_tok (),sizeof (ref_tok )); 12181 std::memcpy (ref_prob ,mtp .chain_prob (),sizeof (ref_prob )); 12182 }else if (std::memcmp (ref_tok ,mtp .chain_tok (),take * sizeof (int32_t ))|| 12183 std::memcmp (ref_prob ,mtp .chain_prob (),take * sizeof (float ))) { 12184err = "private demand micro: token/probability prefix differs" ;return false; 12185 } 12186 strata::core::progress_beat ();// a real, retired benchmark chain 12187return true; 12188 }; 12189if (!run_chain (false,outputs , true))return die (err ); 12190// Partial chains followed by fresh complete chains test 12191// retirement and reuse, as well as every output prefix. 12192for (int k = 1 ;k <=outputs ;++ k ) 12193if (!run_chain (true,k , false)|| !run_chain (false,outputs , false))return die (err ); 12194 std::fprintf (stderr ,"STRATA_DEMAND_MICRO_FIXTURE {\"T\":%d,\"p\":%lld,\"a\":%d,\"n_force\":%d,\"n_out\":%d,\"all_prefixes_equal\":true,\"next_chain_equal\":true}\n" , 12195saved .T ,saved .p ,saved .a ,saved .n_force ,outputs ); 12196// Same complete GPU work in each arm. Difference measures 12197// the cost of host-driven continuation, not tail savings. 12198for (int arm = 0 ;arm < 3 ;++ arm ) { 12199const bool segmented = arm == 1 ; 12200for (int sample = 0 ;sample < 3 ;++ sample ) { 12201int warm_n = 0 ;auto start = Clock ::now (); 12202do { 12203if (!run_chain (segmented ,outputs , false))return die (err ); 12204++ warm_n ; 12205 }while (warm_n < 1000 || std::chrono::duration < double > (Clock ::now ()- start ).count ()< 2.0 ); 12206int measured_n = 0 ;start = Clock ::now (); 12207do { 12208if (!run_chain (segmented ,outputs , false))return die (err ); 12209++ measured_n ; 12210 }while (measured_n < 2000 || std::chrono::duration < double > (Clock ::now ()- start ).count ()< 3.0 ); 12211const double us = std::chrono::duration < double , std::micro > (Clock ::now ()- start ).count () /measured_n ; 12212 std::fprintf (stderr ,"STRATA_DEMAND_MICRO_SAMPLE {\"arm\":%d,\"sample\":%d,\"warm_iterations\":%d,\"iterations\":%d,\"mean_us\":%.12g}\n" , 12213arm ,sample ,warm_n ,measured_n ,us ); 12214 std::fflush (stderr ); 12215 } 12216 } 12217* ds = saved ;mtp .ms_draft = old_ms ; 12218mtp .rounds = old_rounds ; 12219 } 12220if (auto * ds = strata::private_demand::get (& mtp )) 12221 std::fprintf (stderr ,"STRATA_MTP_DEMAND chains=%lld requested=%lld actual=%lld continuations=%lld dead_B=%lld reaction_ns=%lld submit_ns=%lld max_reaction_ns=%lld\n" , 12222ds -> chains ,ds -> requested ,ds -> actual ,ds -> continuations ,ds -> dead , 12223ds -> reaction_ns ,ds -> submit_ns ,ds -> max_reaction_ns ); 12224 strata::private_demand::begin (& mtp , false); 12225mtp .set_source_R (ver .final_R_all ());// the serial loop's rows again 12226const double pl_ms = std::chrono::duration < double , std::milli > (Clock ::now ()- pl_t0 ).count (); 12227dt_run += pl_ms ; 12228if (dec_timing ) { 12229auto avg = [](double s_ ,double n_ ) {return n_ > 0 ?s_ /n_ :0.0 ; }; 12230 std::fprintf (stderr ,"strata pipeline: %lld windows in %.0f ms (%.2f ms/window): %lld speculative, %lld on " 12231"the path, %lld rolled back, %lld below the gate (theta %.2f)\n" , 12232 (long long )dec_windows ,pl_ms ,avg (pl_ms , (double )dec_windows ), (long long )pl_spec , 12233 (long long )pl_on , (long long )pl_undo , (long long )pl_gate ,theta ); 12234 std::fprintf (stderr ,"strata pipeline classes: fresh %.0f windows %.2f ms %.2f tok | speculative %.0f " 12235"windows %.2f ms %.2f tok | forced-chain disagreements %lld, chain late %lld\n" , 12236cls_n [0 ],avg (cls_ms [0 ],cls_n [0 ]),avg (cls_tok [0 ],cls_n [0 ]),cls_n [1 ], 12237avg (cls_ms [1 ],cls_n [1 ]),avg (cls_tok [1 ],cls_n [1 ]), (long long )pl_disagree , 12238 (long long )pl_late ); 12239 std::string cal ; 12240char b [48 ]; 12241for (int i = 0 ;i < 10 ;++ i ) 12242if (cal_n [i ]> 0 ) { 12243 std::snprintf (b ,sizeof b ," %.1f:%lld/%lld" ,i /10.0 , (long long )cal_on [i ], (long long )cal_n [i ]); 12244cal += b ; 12245 } 12246 std::fprintf (stderr ,"strata pipeline calibration (p_on decile: on/scored):%s\n" ,cal .c_str ()); 12247 } 12248 } 12249// DFlash2 with a long suffix match: the next round's draft is deferred to that round's start (spec/window_rule.hpp skip_draft_for_lookup, 12250// STRATA_DF2_LOOKUP_SKIP=N, default 0 = off until measured on this card) 12251const int df2_skip_min = strata::spec::df2_lookup_skip_min (0 ); 12252bool df2_deferred = false; 12253int dfr_n = 0 ; 12254int64_t dfr_pos = 0 ; 12255int32_t dfr_anchor = 0 ; 12256auto defer_df2 = [& ](int a_ )-> bool { 12257if (!use_df2 || o .suffix_draft <=0 || df2_skip_min <=0 )return false; 12258const int ks = sfx .propose (S - 1 ,sbuf .data ()); 12259if (!strata::spec::skip_draft_for_lookup (true,df2_skip_min ,ks ,sfx .last_match ()))return false; 12260df2_deferred = true;dfr_n = a_ + 1 ;dfr_pos = p ;dfr_anchor = outv [(size_t )a_ ]; 12261return true; 12262 }; 12263// the next round's drafts after a commit: the DFlash2 block from the committed rows' taps (the window's first a + 1 rows) 12264auto draft_df2 = [& ](int a_ )-> bool { 12265int32_t dd [strata::core::Dflash2Drafter ::kDrafts ]; 12266float pp [strata::core::Dflash2Drafter ::kDrafts ]; 12267if (!df2 .draft (ver .tap_dev (),a_ + 1 ,p ,outv [(size_t )a_ ],dd ,pp ,err ))return false; 12268for (size_t i = 0 ;i < drafts .size ()&& i < (size_t ) strata::core::Dflash2Drafter ::kDrafts ;++ i ) {drafts [i ]= dd [i ];dprob [i ]= pp [i ]; } 12269return true; 12270 }; 12271while (!pl_ran && !cancelled && produced_n < max_new ) { 12272bool dfr_lookup = false; 12273int dfr_T = 0 ,dfr_match = 0 ; 12274if (df2_deferred ) {// the draft skipped for a long lookup match: the lookup if the policy takes it, else the draft now (same taps and rows) 12275df2_deferred = false; 12276const int kd = sfx .propose (S - 1 ,sbuf .data ()); 12277const int md = sfx .last_match (); 12278const strata::spec::DraftPolicy ::Pick pkd = kd > 0 ?policy .choose (S_mtp ,kd ,md ) : strata::spec::DraftPolicy ::Pick {}; 12279if (kd > 0 && pkd .lookup ) { 12280dfr_lookup = true;dfr_T = pkd .t ;dfr_match = md ; 12281if (!df2 .context (ver .tap_dev (),dfr_n ,dfr_pos ,err )) { std::printf ("ERR %s\n" ,err .c_str ());return 1 ; } 12282 }else { 12283int32_t dd [strata::core::Dflash2Drafter ::kDrafts ]; 12284float pp [strata::core::Dflash2Drafter ::kDrafts ]; 12285if (!df2 .draft (ver .tap_dev (),dfr_n ,dfr_pos ,dfr_anchor ,dd ,pp ,err )) { std::printf ("ERR %s\n" ,err .c_str ());return 1 ; } 12286for (size_t i = 0 ;i < drafts .size ()&& i < (size_t ) strata::core::Dflash2Drafter ::kDrafts ;++ i ) {drafts [i ]= dd [i ];dprob [i ]= pp [i ]; } 12287 } 12288 } 12289int T = draft_on ?S_mtp :1 ;// no drafter: one token a round unless a lookup draft fires 12290 {// the window rule of this request's ACTIVE source (spec/window_rule.hpp) 12291 strata::spec::WindowRuleIn wr ; 12292wr .use_mtp = draft_on ;wr .draft_on = draft_on ;wr .df2_active = use_df2 ;wr .spec_cost = false;wr .first_window = first_window ; 12293wr .chain_rows = 1 ;wr .cap = S_mtp ;wr .start = T ;wr .spec_min_p = req_spec_min_p ; 12294wr .draft_conf = o .draft_conf ;wr .dprob = dprob .data (); 12295T = strata::spec::choose_window (wr ); 12296 } 12297if (first_window )T = 1 ; 12298// a repeat of earlier context (prompt lookup) where the MTP's own first guess agrees: the policy takes it 12299// when its expected tokens per ms, from the measured acceptance and window costs, beat the MTP window's 12300bool from_sfx = false; 12301int sfx_match = 0 ; 12302if (o .suffix_draft > 0 && !first_window ) { 12303const int k = sfx .propose (S - 1 ,sbuf .data ()); 12304sfx_match = sfx .last_match (); 12305if (k > 0 && (!draft_on || sbuf [0 ]== drafts [0 ])) { 12306const strata::spec::DraftPolicy ::Pick pk = policy .choose (T ,k ,sfx_match ); 12307if (pk .lookup ) {T = pk .t ;from_sfx = true; } 12308 } 12309 } 12310if (dfr_lookup ) {// the lookup window chosen before the draft (the draft was skipped) 12311sfx .propose (S - 1 ,sbuf .data ()); 12312T = dfr_T ;from_sfx = true;sfx_match = dfr_match ; 12313 } 12314// --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them 12315int chain_n = 0 ,cm = 0 ; 12316if (o .lookup_chain > 0 && !first_window && !from_sfx && T < S ) { 12317int csrc = -1 ; 12318const int nt = chain_tail (sfx ,drafts .data (),T - 1 ,ctail ); 12319chain_n = strata::spec::propose_from_sources (lookup_src ,ctail .data (),nt ,T - 1 , 12320 std::min (o .lookup_chain ,S - T ),o .lookup_chain_min , 12321cbuf .data (),& cm ,& csrc ); 12322// the policy keeps the chained tokens that pay at this machine's measured window costs 12323if (chain_n > 0 && !chain_fixed ) { 12324double p_mtp = 1.0 ; 12325for (int i = 0 ;i < T - 1 ;++ i )p_mtp *=dprob [(size_t )i ]; 12326chain_n = policy .chain (T ,p_mtp ,chain_n ,cm ); 12327 } 12328 } 12329const int T_mtp = T ; 12330T += chain_n ; 12331const bool timed_round = !first_window ; 12332const Clock ::time_point round0 = Clock ::now (); 12333if (p + T > o .max_context )break ; 12334window [0 ]= x ; 12335for (int i = 1 ;i < T_mtp ;++ i )window [(size_t )i ]= from_sfx ?sbuf [(size_t )i - 1 ] :drafts [(size_t )i - 1 ]; 12336for (int i = 0 ;i < chain_n ;++ i )window [(size_t ) (T_mtp + i )]= cbuf [(size_t )i ]; 12337drive .d .layers = 0 ; 12338drive .d .experts = 0 ; 12339drive .d .failed = false; 12340// #463: the previous adapt round's copies land first - with a non-blocking query, whether a swapped-in 12341// expert ran on the GPU or the CPU (they round differently) depended on the copy's timing 12342// (STRATA_ADAPT_NOWAIT=1: 0.1.37's non-blocking query, the A/B) 12343if (adapt_nowait ())apply_pending (false); 12344else if (pending .empty ()|| ++ pending_age >=adapt_lag ())apply_pending (true); 12345if (!adapt_tick (false)) {// --adapt-async: the round in flight moves on a step when it can 12346 std::printf ("ERR an adaptive refill failed\n" ); 12347return 1 ; 12348 } 12349if (hist_n > 0 ) { 12350// the tails the penalties count over, ONE PER ROW: the tokens the state has consumed, the 12351// fed-back head `x` (it joins `consumed` only after this window commits), then the drafts 12352// before that row - what plain decode would have counted there. (Until 0.1.19 only row 0 12353// was staged, and the drafted rows read unwritten slots.) 12354 strata::kernels::penalty_rows (consumed .data ()+ pen_gen0 , (int64_t ) (consumed .size ()- pen_gen0 ),window .data (),T , 12355hist_n ,hist_stage .data ()); 12356const strata::core::OnDevice on_h (hist_dev ); 12357 dpct::get_in_order_queue () 12358 .memcpy (d_hist ,hist_stage .data (), 12359 (size_t )T * (size_t )hist_n * sizeof (int32_t )) 12360 .wait (); 12361 } 12362// the elastic K/V: the window's cells and the drafter's beyond them 12363if (kvg .on && p + T + 64 > kvg .cells && 12364 !kvg_ensure (p + T + 64 , [& ] { 12365 dpct::get_current_device () 12366 .queues_wait_and_throw (); 12367apply_pending (true); })) { 12368 std::printf ("ERR the K/V cannot grow: no VRAM is left\n" ); 12369return 1 ; 12370 } 12371tr ("window" ,p ,T ); 12372 strata::workload_trace::set_context (p ,T ,-1 ); 12373 strata::workload_trace::Scope verify_trace ("decode.verify" ,nullptr ,T ); 12374const Clock ::time_point tw0 = Clock ::now (); 12375if (!ver .run (T ,window .data (),p ,win_pool_fn ,win_pool_user ,outv .data (),err )|| drive .d .failed ) { 12376 std::printf ("ERR %s\n" ,drive .d .failed && drive .d .fail ?drive .d .fail :err .c_str ()); 12377return 1 ; 12378 } 12379int32_t fol_tgt [16 ]; 12380if (!fol .empty ()) {// STRATA_FOLLOW: the forced continuation stands in for the argmax 12381for (int i = 0 ;i < T && i < 16 ;++ i ) { 12382const size_t k = (size_t )produced_n + (size_t )i ; 12383fol_tgt [i ]= k < fol .size () ?fol [k ] :-1 ; 12384if (fol_tgt [i ] >=0 )outv [(size_t )i ]= fol_tgt [i ]; 12385 } 12386 } 12387int a = 0 ; 12388while (a < T - 1 && window [(size_t )a + 1 ]== outv [(size_t )a ])++ a ; 12389if (!fol .empty ()&& fol_lp != nullptr && !ver .window_logprobs (fol_tgt ,a + 1 ,produced_n ,-1 ,fol_lp ,err )) { 12390 std::printf ("ERR %s\n" ,err .c_str ()); 12391return 1 ; 12392 } 12393if (from_sfx ) {++ sfx_windows ;sfx_drafts += T - 1 ;sfx_ok += a ; } 12394if (chain_n > 0 ) {++ chain_windows ;chain_drafts += chain_n ;chain_ok += std::max (0 ,a - (T_mtp - 1 )); } 12395if (strata::core::MtpDrafter ::top2_env ()&& !from_sfx && !first_window && a < T_mtp - 1 && a < 8 ) { 12396++ t2_rej [a ]; 12397if (mtp .top2 (a )== outv [(size_t )a ])++ t2_hit [a ]; 12398 } 12399const Clock ::time_point tw1 = Clock ::now (); 12400verify_trace .finish (); 12401 strata::workload_trace::Scope commit_trace ("decode.commit_emit" ,nullptr ,T ); 12402 std::thread adapt_thr ;// the adaptive tier beside the commit and the draft (as in generate) 12403bool adapt_ok = true; 12404if (!drive .d .usage .empty ()&& !ajob && ((rounds + 1 ) %o .adapt_every )== 0 ) { 12405if (sycl_mirror_adapt ())adapt_ok = adapt (); 12406else adapt_thr = std::thread ([& ] {adapt_ok = adapt (); }); 12407 } 12408if (sycl_mirror_adapt ()&& !adapt_ok ) { std::printf ("ERR SYCL mirror adaptive exchange failed\n" );return 1 ; } 12409if (!ver .commit (a + 1 ,err )) { 12410if (adapt_thr .joinable ())adapt_thr .join (); 12411 std::printf ("ERR %s\n" ,err .c_str ()); 12412return 1 ; 12413 } 12414// the window's first a + 1 tokens are in the session now (the last output is not: it is next x) 12415// STRATA_PIPELINE_DUMP=<file>: the serial half of the pipelined window's state diff (see the same block 12416// in the pipelined loop): the first stage's GDN state after every committed window. 12417 { 12418static const char * sd = std::getenv ("STRATA_PIPELINE_DUMP" ); 12419if (sd != nullptr ) { 12420const int64_t gf = g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size + 12421g .ssm_conv_channels * (g .ssm_d_conv - 1 ); 12422const size_t n = (size_t )ss .gdn_alloc * (size_t )gf ; 12423 std::vector < float > h (n ); 12424 (void )DPCT_CHECK_ERROR (ver .stream ()-> memcpy (h .data (),ss .gdn_state ,n * sizeof (float )).wait ()); 12425const size_t n_rec = (size_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size ; 12426const size_t n_cnv = (size_t )g .ssm_conv_channels * (g .ssm_d_conv - 1 ); 12427double rec_sum = 0.0 ,cnv_sum = 0.0 ; 12428uint64_t rec_hash = 1469598103934665603ull ,cnv_hash = 1469598103934665603ull ; 12429for (int64_t l = 0 ;l < ss .gdn_alloc ;++ l ) { 12430const size_t base = (size_t )l * (size_t )gf ; 12431uint64_t rh = 1469598103934665603ull ,ch = 1469598103934665603ull ; 12432for (size_t i = 0 ;i < n_rec ;++ i ) { 12433uint64_t bb = 0 ; 12434 std::memcpy (& bb ,& h [base + i ],sizeof (float )); 12435rh = (rh ^bb )* 1099511628211ull ; 12436rec_sum += (double )h [base + i ]; 12437 } 12438for (size_t i = 0 ;i < n_cnv ;++ i ) { 12439uint64_t bb = 0 ; 12440 std::memcpy (& bb ,& h [base + n_rec + i ],sizeof (float )); 12441ch = (ch ^bb )* 1099511628211ull ; 12442cnv_sum += (double )h [base + n_rec + i ]; 12443 } 12444rec_hash = (rec_hash ^rh )* 1099511628211ull ; 12445cnv_hash = (cnv_hash ^ch )* 1099511628211ull ; 12446 } 12447if (std::FILE * df = std::fopen (sd ,"a" )) { 12448 std::fprintf (df ,"pos %lld serial rec %.9g %016llx cnv %.9g %016llx\n" , (long long ) (p + a + 1 ), 12449rec_sum , (unsigned long long )rec_hash ,cnv_sum , 12450 (unsigned long long )cnv_hash ); 12451 std::fclose (df ); 12452 } 12453 } 12454 } 12455for (int i = 0 ;i <=a ;++ i )consumed .push_back (window [(size_t )i ]); 12456if (use_df2 )df2 .note_rows (window .data (),a + 1 ,p ); 12457draft_offered += T - 1 ; 12458draft_accepted += a ; 12459first_window = false; 12460bool eos = false; 12461for (int i = 0 ;i <=a && produced_n < max_new && !eos ;++ i ) { 12462 std::printf ("T %d\n" , (int )outv [(size_t )i ]); 12463if (req_logprobs >=0 ) {// row i of this window's head logits is the distribution token i came from 12464static std::vector < float > lrow ; 12465static std::vector < int32_t > lord ; 12466lrow .resize ((size_t )ver .vocab ()); 12467if (!ver .copy_logits (i ,lrow .data ())) { 12468 std::printf ("LP nan\n" ); 12469 }else { 12470float mx = - INFINITY ; 12471for (const float v :lrow )mx = std::max (mx ,v ); 12472double se = 0.0 ; 12473for (const float v :lrow )se += std::exp ((double )v - mx ); 12474const double lse = (double )mx + std::log (se ); 12475 std::printf ("LP %.6f" , (double )lrow [(size_t )outv [(size_t )i ]]- lse ); 12476if (!req_allowed .empty ()) { 12477// only the ids the caller named (never the chosen one, which the head carries, and never an id 12478// past the engine's own vocabulary); the server renormalises over them 12479for (const int32_t id :req_allowed ) { 12480if (id == outv [(size_t )i ]|| id < 0 || (size_t )id >=lrow .size ())continue ; 12481 std::printf (" %d:%.6f" , (int )id , (double )lrow [(size_t )id ]- lse ); 12482 } 12483 }else if (req_logprobs > 0 ) { 12484lord .resize (lrow .size ()); 12485for (size_t v = 0 ;v < lrow .size ();++ v )lord [v ]= (int32_t )v ; 12486 std::partial_sort (lord .begin (),lord .begin ()+ req_logprobs ,lord .end (), 12487 [& ](int32_t x1 ,int32_t x2 ) {return lrow [(size_t )x1 ]> lrow [(size_t )x2 ]; }); 12488for (int j = 0 ;j < req_logprobs ;++ j ) 12489 std::printf (" %d:%.6f" ,lord [(size_t )j ], (double )lrow [(size_t )lord [(size_t )j ]]- lse ); 12490 } 12491 std::printf ("\n" ); 12492 } 12493 } 12494 strata::core::progress_beat (); 12495++ produced_n ; 12496if (sfx_on )sfx .append (outv [(size_t )i ]); 12497if (o .lookup_chain > 0 )extra_sources_append (& outv [(size_t )i ],1 ); 12498eos = std::find (o .eos_ids .begin (),o .eos_ids .end (), (int64_t )outv [(size_t )i ])!= o .eos_ids .end (); 12499 } 12500 std::fflush (stdout ); 12501++ rounds ; 12502const Clock ::time_point tw2 = Clock ::now (); 12503commit_trace .finish (); 12504 strata::workload_trace::Scope draft_trace ("decode.draft" ,nullptr ,T ); 12505// coupled drafts with penalties: the next window's row-0 history (`consumed` holds this window's 12506// commit, outv[a] is its row 0) - the drafts extend it on the device as the verify rows will 12507if (use_mtp && hist_n > 0 && mtp .coupled ()&& !eos && produced_n < max_new ) 12508mtp .set_draft_history (consumed .data ()+ pen_gen0 , (int64_t ) (consumed .size ()- pen_gen0 ),outv [(size_t )a ]); 12509// The request ends here, so no draft follows and the window's committed rows would never reach the drafter's ring or its log: every turn would 12510// leave a hole of a + 1 positions behind it, which a later turn that resumes after this one finds blank (and cannot rebuild). Update them now. 12511if (use_df2 && (eos || produced_n >=max_new )) { 12512const Clock ::time_point tctx = Clock ::now (); 12513if (!df2 .context (ver .tap_dev (),a + 1 ,p ,err )) {if (adapt_thr .joinable ())adapt_thr .join (); std::printf ("ERR %s\n" ,err .c_str ());return 1 ; } 12514static const bool ctx_timing = std::getenv ("STRATA_DF2_TIMING" )!= nullptr ; 12515if (ctx_timing ) std::fprintf (stderr ,"strata serve: DFlash2: the request-end context update (%d rows) took %.1f ms\n" ,a + 1 , std::chrono::duration < double , std::milli > (Clock ::now ()- tctx ).count ()); 12516 } 12517const bool drafted = !draft_on || eos || produced_n >=max_new || 12518 (use_df2 ? (defer_df2 (a )|| draft_df2 (a )) :mtp .draft (T ,outv .data (),p ,a ,drafts .data (),err ,dprob .data (), (float )req_spec_min_p )); 12519draft_trace .finish (); 12520 { 12521const Clock ::time_point tw3 = Clock ::now (); 12522auto msd = [](Clock ::time_point a0 ,Clock ::time_point b0 ) {return std::chrono::duration < double , std::milli > (b0 - a0 ).count (); }; 12523dt_run += msd (tw0 ,tw1 );dt_commit += msd (tw1 ,tw2 );dt_draft += msd (tw2 ,tw3 ); 12524++ dec_windows ;dec_T += T ; 12525 } 12526pcie_auto_step (req_pcie_frac );// PcieAuto (opt-in): the share refined from the CPU pool's speed 12527if (adapt_thr .joinable ())adapt_thr .join (); 12528if (!adapt_ok ) { 12529 std::printf ("ERR an adaptive refill failed\n" ); 12530return 1 ; 12531 } 12532if (!drafted ) { 12533 std::printf ("ERR %s\n" ,err .c_str ()); 12534return 1 ; 12535 } 12536if (timed_round && !eos && chain_n == 0 ) 12537policy .observe (from_sfx ,T ,a ,sfx_match , 12538 std::chrono::duration < double , std::milli > (Clock ::now ()- round0 ).count ()); 12539else if (timed_round && !eos )// a chained window: its MTP part, its chain, its cost 12540policy .observe_chain (T_mtp ,chain_n ,a ,cm , 12541 std::chrono::duration < double , std::milli > (Clock ::now ()- round0 ).count ()); 12542if (eos ) {finish = "stop" ;break ; } 12543if (stop_req .load ()) {finish = "cancel" ;break ; } 12544x = outv [(size_t )a ]; 12545p += a + 1 ; 12546 } 12547const double decode_ms = std::chrono::duration < double , std::milli > (Clock ::now ()- d0 ).count (); 12548decode_trace .finish (); 12549// the last commit (set_commit_async): the session is complete before anything reads or copies it 12550if (!ver .wait_commit (err )) { 12551 std::printf ("ERR %s\n" ,err .c_str ()); 12552return 1 ; 12553 } 12554if (dec_timing && dec_windows > 0 ) { 12555const DecSnap d1 = dec_snap (); 12556const double w = (double )dec_windows ,L = (double )g .n_layers ; 12557 std::fprintf (stderr ,"strata decode timing: %lld windows, avg T %.2f, %.2f tokens/window, %.2f ms/window = " 12558"verify %.2f (GPU-reach wait %.2f + per-layer host %.2f [plan %.2f actq %.2f jobs %.2f " 12559"CPU %.2f] + stage %.2f) + commit/emit %.2f + draft %.2f; per layer-window: CPU experts " 12560"%.2f (%.2f entries), VRAM hits %.2f, PCIe %.2f\n" , 12561 (long long )dec_windows ,dec_T /w ,produced_n /w ,decode_ms /w ,dt_run /w , 12562 (d1 .wait - ds0 .wait ) /w , (d1 .pool - ds0 .pool ) /w , (d1 .plan - ds0 .plan ) /w , 12563 (d1 .actq - ds0 .actq ) /w , (d1 .jobs - ds0 .jobs ) /w , (d1 .run - ds0 .run ) /w , 12564 (d1 .host - ds0 .host ) /w ,dt_commit /w ,dt_draft /w , (d1 .misses - ds0 .misses ) / (w * L ), 12565 (d1 .entries - ds0 .entries ) / (w * L ), (d1 .hits - ds0 .hits ) / (w * L ), (d1 .pcie - ds0 .pcie ) / (w * L )); 12566for (int st = 0 ;st < n_stages ;++ st ) {// every stage's GPU profile, not only the first card's 12567const std::string pr = stage_ver (st ).profile_report (); 12568if (pr .empty ())continue ; 12569if (st == 0 ) std::fprintf (stderr ,"strata decode GPU stages (ms/window):%s\n" ,pr .c_str ());// text as before 12570else std::fprintf (stderr ,"strata decode GPU stages, stage %d (ms/window):%s\n" ,st ,pr .c_str ()); 12571 } 12572 } 12573if (!cancelled ) { 12574// a prompt stopped halfway leaves the session somewhere between two chunks: nothing to continue from 12575// (the checkpoints taken while reading it are still good) 12576live .swap (consumed ); 12577live_imgs = imgs_below (req_imgs , (int64_t )live .size ()); 12578live_ok = o .prompt_cache > 0 && req_ckpt ;// ckpt=0: nothing to continue or park (#830) 12579 } 12580static const bool state_hash = std::getenv ("STRATA_STATE_HASH" )!= nullptr ; 12581if (state_hash && !cancelled && o .prompt_cache > 0 ) {// every finished request, ckpt=0 too (parity gates) 12582// DEBUG: a fingerprint of every part of the session over the positions it holds ([0, L)), and 12583// separately of what lies past them in the last KV page (stale cells, fine unless something reads them) 12584if (DPCT_CHECK_ERROR ( 12585 dpct::get_current_device ().queues_wait_and_throw ())!= 125860 ) { 12587 std::printf ("ERR synchronizing state fingerprint\n" ); 12588return 1 ; 12589 } 12590const int64_t L = (int64_t )live .size (); 12591const strata::kernels::QsaShapes qs = strata::core::qsa_shapes (g ); 12592bool hash_ok = true; 12593 std::array < uint8_t ,65536 > hash_buffer ; 12594auto hash_dev = [& ](const void * p ,size_t bytes ,uint64_t h ) { 12595try { 12596for (size_t offset = 0 ;hash_ok && offset < bytes ;) { 12597const size_t n = std::min (hash_buffer .size (),bytes - offset ); 12598// VRAM or a streamed host copy, with fixed diagnostic workspace. 12599if (DPCT_CHECK_ERROR ( 12600 dpct::get_in_order_queue () 12601 .memcpy (hash_buffer .data (), 12602static_cast < const uint8_t *> (p )+ 12603offset , 12604n ) 12605 .wait ())!= 0 ) { 12606hash_ok = false; 12607break ; 12608 } 12609h = fnv1a (hash_buffer .data (),n ,h ); 12610offset += n ; 12611 } 12612return h ; 12613 } 12614catch (sycl::exception const & exc ) { 12615 std::cerr <<exc .what () 12616 <<"Exception caught at file:" <<__FILE__ 12617 <<", line:" <<__LINE__ << std::endl ; 12618 std::exit (1 ); 12619 } 12620 }; 12621// the cells [c0, c1) of one int8 K or V pool ([page][kv_head][page_size][head_dim]), bytes per value `w` 12622auto hash_cells = [& ](const void * pool ,int64_t per_cell ,int64_t c0 ,int64_t c1 ,uint64_t h ) { 12623const int64_t ps = qs .page_size ; 12624for (int64_t pg = c0 /ps ;pg * ps < c1 ;++ pg ) 12625for (int64_t hd = 0 ;hd < qs .n_head_kv ;++ hd ) { 12626const int64_t a = std::max (c0 ,pg * ps )- pg * ps ,e = std::min (c1 , (pg + 1 )* ps )- pg * ps ; 12627const size_t off = (size_t ) (((pg * qs .n_head_kv + hd )* ps + a )* per_cell ); 12628h = hash_dev ((const uint8_t * )pool + off , (size_t ) ((e - a )* per_cell ),h ); 12629 } 12630return h ; 12631 }; 12632const ConvStateSizes z = conv_state_sizes (g ,ss ); 12633uint64_t h_gdn = hash_dev (ss .gdn_state ,z .gdn ,1469598103934665603ull ); 12634if (std::getenv ("STRATA_STATE_HASH_GDN" )!= nullptr && ss .gdn_alloc > 0 ) {// per GDN layer: which one differs first 12635const size_t per = z .gdn / (size_t )ss .gdn_alloc ; 12636 std::string s ; 12637char b [8 ]; 12638for (int64_t i = 0 ;i < ss .gdn_alloc ;++ i ) { 12639 std::snprintf (b ,sizeof (b ),"%04llx " , (unsigned long long ) (hash_dev ((const uint8_t * )ss .gdn_state + i * per ,per ,1469598103934665603ull )& 0xffff )); 12640s += b ; 12641 } 12642 std::fprintf (stderr ,"strata serve: STATE_HASH_GDN %s\n" ,s .c_str ()); 12643 } 12644uint64_t h_ple = hash_dev (ss .ple_hist ,ss .ple_hist ?z .ple :0 ,1469598103934665603ull ); 12645uint64_t h_tail = 1469598103934665603ull ,h_pool = h_tail ,h_kv = h_tail ,h_stale = h_tail ; 12646// pooled= keeps its 0.1.29 meaning: the completed rows [0, L / idx_block) only. pooled_full= adds the 12647// spare row at L / idx_block (the `dead` key the next block completion overwrites), which a 12648// conversation restore writes back; dead= is the spare key itself 12649uint64_t h_dead = h_tail ,h_pool_full = h_tail ; 12650const int64_t kvb = qs .head_dim ,scb = (qs .head_dim /64 )* 2 ; 12651// a state's K/V arrays and their bytes per (cell, head) row: the host copy when it has one 12652auto kv_arrays = [& ](const strata::core::QsaState & st ) { 12653const bool h = st .kv_mode != 0 ; 12654 std::vector < std::pair < const void * ,int64_t >> a ; 12655if (st .kv_q4 ) { 12656const int64_t q4b = (int64_t ) strata::kernels::kv_q4_bytes_per_head ((int )qs .head_dim ); 12657a = {{h ?st .host .k_q4 :st .k_q4 ,q4b }, {h ?st .host .v_q4 :st .v_q4 ,q4b }}; 12658 }else if (st .kv_hybrid ) { 12659const int64_t q4b = (int64_t ) strata::kernels::kv_q4_bytes_per_head ((int )qs .head_dim ); 12660a = {{h ?st .host .k_q :st .k_q ,kvb }, {h ?st .host .v_q4 :st .v_q4 ,q4b }, 12661 {h ?st .host .k_scale :st .k_scale ,scb }}; 12662 }else if (st .kv_int8 ) { 12663a = {{h ?st .host .k_q :st .k_q ,kvb }, {h ?st .host .v_q :st .v_q ,kvb }, 12664 {h ?st .host .k_scale :st .k_scale ,scb }, {h ?st .host .v_scale :st .v_scale ,scb }}; 12665 }else { 12666a = {{h ?st .host .k_pool :st .k_pool ,qs .head_dim * 2 }, 12667 {h ?st .host .v_pool :st .v_pool ,qs .head_dim * 2 }}; 12668 } 12669return a ; 12670 }; 12671const int64_t end_cell = std::min < int64_t > (((L + qs .page_size - 1 ) /qs .page_size )* qs .page_size , 12672ss .max_cells );// = the primary state's max_cells 12673for (int64_t j = 0 ;j < ss .qsa_alloc ;++ j ) {// this session's owned QSA ordinals only 12674const strata::core::QsaState & st = ss .qsa_states [ss .qsa_ord0 + j ]; 12675h_tail = hash_dev (st .idx_tail ,z .tail ,h_tail ); 12676h_dead = hash_dev (st .idx_dead ,z .dead ,h_dead ); 12677h_pool = hash_dev (st .idx_pooled , (size_t ) (L /qs .idx_block )* qs .idx_dim * 4 ,h_pool ); 12678h_pool_full = hash_dev (st .idx_pooled , (size_t ) (L > 0 ?L /qs .idx_block + 1 :0 )* qs .idx_dim * 4 , 12679h_pool_full ); 12680// KV streaming: the host copy is the identity layout and holds every cell 12681for (const auto & [pool ,w ] :kv_arrays (st )) { 12682h_kv = hash_cells (pool ,w ,0 ,L ,h_kv ); 12683h_stale = hash_cells (pool ,w ,L ,end_cell ,h_stale ); 12684 } 12685 } 12686uint64_t h_mtp = 1469598103934665603ull ; 12687if (use_mtp ) { 12688const strata::core::QsaState & ms = mtp .kv_state (); 12689const int64_t mL = std::min < int64_t > (L ,ms .max_cells ); 12690for (const auto & [pool ,w ] :kv_arrays (ms )) 12691if (pool != nullptr )h_mtp = hash_cells (pool ,w ,0 ,mL ,h_mtp ); 12692 } 12693if (!hash_ok ) { 12694 std::printf ("ERR reading state fingerprint\n" ); 12695return 1 ; 12696 } 12697 std::fprintf (stderr ,"strata serve: STATE_HASH L=%lld gdn=%016llx ple=%016llx tail=%016llx pooled=%016llx " 12698"kv=%016llx mtp=%016llx stale=%016llx dead=%016llx pooled_full=%016llx ple_prev=%d,%d\n" , (long long )L , 12699 (unsigned long long )h_gdn , (unsigned long long )h_ple , (unsigned long long )h_tail , 12700 (unsigned long long )h_pool , (unsigned long long )h_kv , (unsigned long long )h_mtp , 12701 (unsigned long long )h_stale , (unsigned long long )h_dead , 12702 (unsigned long long )h_pool_full ,ss .ple_prev [0 ],ss .ple_prev [1 ]); 12703 } 12704const int64_t req_hits = drive .d .cache_hits - decode_hits0 ; 12705const int64_t req_look = (drive .d .cache_hits + drive .d .cache_admitted + drive .d .cache_refused )- decode_look0 ; 12706const int64_t req_offload = drive .d .offload_entries - offload0 ; 12707// #471: the prompt tokens this request read - all the fresh ones, or as far as the prompt pass got when a 12708// cancel stopped it part-way (a cancelled request used to be logged and counted as having read them all) 12709const int64_t fresh = n - resume ; 12710const int64_t read_n = cancelled ? std::clamp < int64_t > (pp_reached - resume ,0 ,fresh ) :fresh ; 12711// DONE <generated> <prompt> <prompt ms> <decode ms> <finish> <drafts accepted> <drafts offered> <reused> [hits] [lookups] 12712// [RAM blobs] [file blobs] [file MB] (CS-T tiers; appended, so an older server reads the rest) 12713// [prompt tokens read] (#471: fewer than <prompt> - <reused> when a cancel stopped the read) 12714// [offloaded] (#588: the decode's routed experts the GPU read over PCIe or another GPU computed; 12715// not in [lookups]) 12716// [lookup-chain accepted] [lookup-chain offered] [suffix accepted] [suffix offered] [windows] 12717// (only with --lookup-chain) 12718char chain_txt [128 ]= "" ; 12719if (o .lookup_chain > 0 ) 12720 std::snprintf (chain_txt ,sizeof (chain_txt )," %lld %lld %lld %lld %lld" , (long long )chain_ok , 12721 (long long )chain_drafts , (long long )sfx_ok , (long long )sfx_drafts , (long long )dec_windows ); 12722if (yielded_at >=0 ) std::printf ("YIELDED %d %lld\n" ,yielded_slot , (long long )yielded_at ); 12723 std::printf ("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f %lld %lld%s\n" , 12724 (long long )produced_n , 12725 (long long )n ,prompt_ms ,decode_ms ,finish , (long long )draft_accepted , (long long )draft_offered , 12726 (long long )resume , (long long )req_hits , (long long )req_look , 12727 (long long ) (src .ram_reads ()- ram0 ), (long long ) (src .file_reads ()- files0 ), 12728 (double ) (src .file_read_bytes ()- file_bytes0 ) /1e6 , (long long )read_n , 12729 (long long )req_offload ,chain_txt ); 12730 std::fflush (stdout ); 12731 strata::uc_probe ("after-request" ); 12732if (admit_slot >=0 ) {// --batch: BADM <slot> <1 = continues in the batch windows | 0 = done> 12733bool cont = !cancelled && produced_n == 1 && admit_max_new > 1 && std::strcmp (finish ,"length" )== 0 && 12734 (int64_t )live .size ()== p ; 12735const auto tc0 = Clock ::now (); 12736if (cont )park_slot (admit_slot );// the conversation the slot holds, before this one overwrites it 12737if (cont && !copy_to_slot (admit_slot ,live ,err )) { 12738 std::fprintf (stderr ,"strata serve: batch admission failed: %s\n" ,err .c_str ()); 12739bs [(size_t )admit_slot ].cached = false;// its sessions may be half written 12740cont = false; 12741 } 12742if (cont ) { 12743ver .set_slot_sampling (admit_slot ,req_sp );// the request's own sampling, row by row 12744BSlot & sl = bs [(size_t )admit_slot ]; 12745sl = BSlot {}; 12746sl .active = true; 12747sl .x = x ; 12748sl .p = p ; 12749sl .produced = 1 ; 12750sl .max_new = admit_max_new ; 12751sl .t0 = Clock ::now (); 12752sl .ids = live ; 12753 {// the penalty window of the slot's decode: the reply, from the last prompt token (the first window fed it), as the solo loop counts it 12754const bool slot_pen = req_sp .penalty_last_n > 0 && (req_sp .penalty_repeat != 1.0f || req_sp .penalty_freq != 0.0f || req_sp .penalty_present != 0.0f ); 12755sl .pen_n = slot_pen ? std::min (req_sp .penalty_last_n ,kPenaltyWindowCap ) :0 ; 12756sl .reply0 = (int64_t ) strata::kernels::penalty_window_from (live .size ()> 0 ?live .size ()- 1 :0 ,pen_prompt ); 12757if (req_pen_from >=0 && !pen_prompt )sl .reply0 = std::min < int64_t > (sl .reply0 ,req_pen_from );// a continued request (prompt + what it generated): the reply began earlier 12758 } 12759if (batch_mtp ) { 12760if (!slot_mtp [(size_t )admit_slot ]-> draft_first (1 ,ver .final_R_all (),sl .x , 12761sl .p - 1 ,sl .draft .data (),err )) { 12762 std::fprintf (stderr ,"strata batch: MTP admission for slot %d failed: %s\n" , 12763admit_slot ,err .c_str ()); 12764return 1 ; 12765 } 12766sl .draft_ready = true; 12767 } 12768sl .cvec = cvec_cached ; 12769sl .img = !live_imgs .empty ();// pictures: not matched again by tokens alone, so not cached 12770const ConvCheckpoint * best = nullptr ; 12771for (const ConvCheckpoint & c :checks ) 12772if (c .ids .size ()< live .size ()&& (best == nullptr || c .ids .size ()> best -> ids .size ())&& 12773 std::equal (c .ids .begin (),c .ids .end (),live .begin ())) 12774best = & c ; 12775if (best != nullptr && !sl .img )sl .checks .push_back (* best ); 12776 std::fprintf (stderr ,"strata batch: slot %d takes %lld tokens (copied in %.1f ms)\n" ,admit_slot , 12777 (long long )live .size (), std::chrono::duration < double , std::milli > (Clock ::now ()- tc0 ).count ()); 12778 } 12779 std::printf ("BADM %d %d\n" ,admit_slot ,cont ?1 :0 ); 12780 std::fflush (stdout ); 12781admit_slot = -1 ; 12782 } 12783if (drive .routing != nullptr ) std::fflush (drive .routing );// the routing trace survives a crash and is watchable mid-session 12784request_trace .finish (); 12785 strata::workload_trace::flush (); 12786// "12288 of 98179" when cancelled mid-read (#471), the rate from what was read 12787char read_txt [64 ]; 12788if (cancelled ) 12789 std::snprintf (read_txt ,sizeof (read_txt ),"%lld of %lld" , (long long )read_n , (long long )fresh ); 12790else 12791 std::snprintf (read_txt ,sizeof (read_txt ),"%lld" , (long long )fresh ); 12792 std::fprintf (stderr ,"strata serve: prompt %lld tokens = %lld reused + %s read in %.0f ms (%.1f tok/s), " 12793"%lld generated in %.0f ms (%.1f tok/s), drafts accepted %lld of %lld, %zu checkpoints%s\n" , 12794 (long long )n , (long long )resume ,read_txt ,prompt_ms , 12795prompt_ms > 0 ?1000.0 * read_n /prompt_ms :0.0 , (long long )produced_n ,decode_ms , 12796decode_ms > 0 ?1000.0 * produced_n /decode_ms :0.0 , (long long )draft_accepted , 12797 (long long )draft_offered ,checks .size (),cancelled ?" (cancelled)" :"" ); 12798// the VRAM share of the experts the pool looked up while decoding; experts it sent over PCIe for the GPU 12799// to read (--pcie-frac) are in neither count - #588: so that share is said beside it (raising --pcie-frac 12800// raises the hit rate while the PCIe reads may make the decode slower) 12801if (req_look > 0 ) { 12802char off [160 ]= "" ; 12803if (req_offload > 0 ) 12804 std::snprintf (off ,sizeof off ,"; %lld more read by the GPU over PCIe or from another GPU (%.1f%% of " 12805"all %lld routed)" , (long long )req_offload , 12806100.0 * (double )req_offload / (double ) (req_look + req_offload ), 12807 (long long ) (req_look + req_offload )); 12808 std::fprintf (stderr ,"strata serve: decode expert cache hit rate: %.1f%% (%lld hits / %lld lookups)%s\n" , 12809100.0 * (double )req_hits / (double )req_look , 12810 (long long )req_hits , (long long )req_look ,off ); 12811 } 12812// the resident RAM mode, cumulative: experts read from experts.bin since the copy was made (what the plain 12813// mmap mode reads through the OS file cache, from the SSD when the RAM could not keep it) 12814if (src .complement_ready ()) 12815 std::fprintf (stderr ,"strata serve: resident RAM: %.2f GiB of experts in RAM, %lld exchanged with the " 12816"VRAM tier, %lld blob reads from the file\n" , 12817 (double )src .resident_bytes () /1073741824.0 , (long long )src .exchanges (), 12818 (long long )src .file_reads ()); 12819if (ajob )// --adapt-async, cumulative (a round may still be in flight: it lands before the next request) 12820 std::fprintf (stderr ,"strata serve: asynchronous adaptive tier: %lld rounds, %lld experts swapped in, " 12821"%.1f ms per round (start to flip, between windows)\n" , 12822 (long long )a_rounds , (long long )a_swapped ,a_rounds > 0 ?a_ms / (double )a_rounds :0.0 ); 12823if (src .exchange_rotation ()) 12824 std::fprintf (stderr ,"strata serve: exchange rotation: %llu blocks, %llu host memcpy bytes avoided (cumulative payload)\n" , 12825 (unsigned long long )src .rotated_exchanges (), 12826 (unsigned long long )src .avoided_exchange_copy_bytes ()); 12827// CS-T: the tiers, cumulative - GPU cache hits (the decode lookups above), RAM copy, files (SSD / OS cache) 12828if (srcp == & src ) 12829 std::fprintf (stderr ,"strata serve: expert tiers: GPU %lld hits this request; since the start RAM %lld blobs, files %lld blobs " 12830"%.1f MB read%s\n" , (long long )req_hits , (long long )src .ram_reads (), 12831 (long long )src .file_reads (), (double )src .file_read_bytes () /1e6 , 12832src .gguf_mode () ?" (the GGUF in place)" :"" ); 12833// STRATA_SPLIT_TIMING: where each verify stage's host time went, cumulative per window since the start 12834// (waiting for its GPU to ring a layer, the CPU pool and plan per layer, staging the window) 12835if (static const bool st_timing = std::getenv ("STRATA_SPLIT_TIMING" )!= nullptr ;st_timing ) 12836for (int st = 0 ;st < n_stages ;++ st ) { 12837const strata::core::Verifier & v = stage_ver (st ); 12838const double w = v .windows > 0 ? (double )v .windows :1.0 ; 12839 std::fprintf (stderr ,"strata serve: stage %d: %lld windows; per window: wait for the GPU %.3f ms, " 12840"pool + plan %.3f ms, host staging %.3f ms, commit %.3f ms\n" ,st , 12841 (long long )v .windows ,v .ms_wait /w ,v .ms_pool /w ,v .ms_host /w ,v .ms_commit /w ); 12842 } 12843if (g .n_qsa_layers ()> 0 && ss .qsa_states [ss .qsa_primary ()].kv_mode == 1 ) { 12844// KV streaming, cumulative over the process: blocks the selections named vs blocks read from RAM 12845// (this device's owned ordinals; a split's other stages hold theirs) 12846uint64_t miss = 0 ,look = 0 ; 12847bool over = false; 12848for (int64_t j = 0 ;j < ss .qsa_alloc ;++ j ) { 12849const strata::kernels::KvStreamCounters c = 12850 strata::kernels::kv_stream_counters (ss .qsa_states [ss .qsa_ord0 + j ].map ); 12851miss += c .misses ;look += c .lookups ;over = over || c .overflow ; 12852 } 12853 std::fprintf (stderr ,"strata serve: KV streaming: %.2f%% of %llu block reads hit VRAM, %.1f MiB read " 12854"from RAM%s\n" ,look ?100.0 * (double ) (look - miss ) / (double )look :100.0 , 12855 (unsigned long long )look , (double )miss * 4224.0 /1048576.0 , 12856over ?" - OVERFLOW (too few resident cells)" :"" ); 12857 } 12858if (sfx_windows > 0 ) 12859 std::fprintf (stderr ,"strata serve: suffix drafts: %lld windows, %lld of %lld drafts accepted\n" , 12860 (long long )sfx_windows , (long long )sfx_ok , (long long )sfx_drafts ); 12861if (o .lookup_chain > 0 ) 12862 std::fprintf (stderr ,"strata serve: lookup chain: %lld of %lld windows, %lld of %lld chained drafts accepted\n" , 12863 (long long )chain_windows , (long long )dec_windows , (long long )chain_ok , (long long )chain_drafts ); 12864if (strata::core::MtpDrafter ::top2_env ()) 12865 std::fprintf (stderr ,"strata serve: mtp top2: rejected/runner-up by depth %lld/%lld %lld/%lld %lld/%lld %lld/%lld " 12866"of %lld windows\n" , (long long )t2_rej [0 ], (long long )t2_hit [0 ], (long long )t2_rej [1 ], 12867 (long long )t2_hit [1 ], (long long )t2_rej [2 ], (long long )t2_hit [2 ], (long long )t2_rej [3 ], 12868 (long long )t2_hit [3 ], (long long )dec_windows ); 12869for (int r = 0 ;r < 3 ;++ r )if (o .expert_cache_remote [(size_t )r ]> 0 ) 12870 std::fprintf (stderr ,"strata serve: CUDA%d: %lld expert entries, %lld active layer launches, %.1f MiB returned " 12871"(%.1f MiB with full rows) in this request; host %.0f ms staging+launching, %.0f ms " 12872"waiting for it in this request\n" ,r + 1 , 12873 (long long ) (remote_experts [(size_t )r ].computed ()- remote_before [(size_t )r ]), 12874 (long long ) (remote_experts [(size_t )r ].launched_layers ()- launches_before [(size_t )r ]), 12875 (double ) (remote_experts [(size_t )r ].returned_bytes ()- compact_before [(size_t )r ]) /1048576.0 , 12876 (double ) (remote_experts [(size_t )r ].full_row_bytes ()- full_before [(size_t )r ]) /1048576.0 , 12877remote_experts [(size_t )r ].ms_begin ()- begin_before [(size_t )r ], 12878remote_experts [(size_t )r ].ms_wait ()- wait_before [(size_t )r ]); 12879 } 12880save_profile ("exit" );// #477: QUIT, or the server closed stdin 12881// SYCL port: the requests are done and their output written; leave without unwinding the GPU objects (the OS 12882// reclaims them). Their destructors ran against a runtime already shutting down and aborted (exit 139). 12883try { 12884 dpct::get_current_device ().queues_wait_and_throw (); 12885// Release the direct-access USM host mirror before process teardown. 12886gguf_src .close (); 12887 }catch (const std::exception & e ) { 12888 std::fprintf (stderr ,"strata shutdown: mirror release failed: %s\n" ,e .what ()); 12889 std::fflush (stderr ); 12890 std::_Exit (1 ); 12891 } 12892 std::fflush (stdout ); 12893 std::fflush (stderr ); 12894 std::_Exit (0 ); 12895 } 12896 12897// ---- plan v0.3 P5: the prompt's conditioning positions [0, n_prompt - 1) in batched chunks. The token loop 12898// then starts at the last prompt position, whose prediction is the first generated token. 12899int64_t pos_start = 0 ; 12900int64_t spec_pos = 0 ;// plan v0.3 P6: where the speculative loop starts (0 = not used) 12901 strata::uc_probe ("before-prefill" ); 12902 strata::prefill::Prefill prefill ; 12903bool kvg_started = false;// the elastic K/V took this run's cells 12904double prefill_batched_ms = 0 ; 12905 std::FILE * final_r = o .dump_final_r .empty () ?nullptr : std::fopen (o .dump_final_r .c_str (),"wb" ); 12906 std::vector < float > final_r_host (final_r ? (size_t ) (g .hc * g .n_embd ) :0 ); 12907 std::vector < std::pair < int32_t ,int32_t >> lent ;// (residency index, slot) lent to the prompt path 12908const int64_t n_batched = (o .prefill_until > 0 && o .prefill_until < n_prompt - 1 ) ?o .prefill_until :n_prompt - 1 ; 12909if (o .prefill_chunk > 0 && n_prompt > 1 ) { 12910void * borrow = nullptr ; 12911uint64_t borrow_bytes = 0 ; 12912if (!o .no_prefill_borrow && !host_res .empty ()&& d_res != nullptr ) { 12913int64_t chunk = o .prefill_chunk ; 12914int64_t k = plan_lend (chunk );// auto: the largest chunk that fits; fixed: halved to fit 12915const int64_t request_sized = equal_chunk (n_batched ,chunk ); 12916if (k > 0 && request_sized < chunk ) {// no bigger than this prompt segment needs 12917chunk = request_sized ; 12918k = lend_slots (chunk ); 12919if (k + 128 > xcache .slots ())k = 0 ; 12920if (!o .prefill_auto )o .prefill_chunk = chunk ; 12921 } 12922if (o .prefill_auto ) { 12923o .prefill_chunk = k > 0 ?chunk :request_chunk (n_batched ,1024 ); 12924 std::fprintf (stderr ,"strata generate: prompt chunk auto: %lld tokens\n" , (long long )o .prefill_chunk ); 12925 }else if (chunk != o .prefill_chunk ) { 12926k = 0 ;// a fixed chunk that does not fit: its own buffers, as before 12927 } 12928const int64_t blob = (int64_t ) strata::kernels::cpu::expert_layout ().max_blob ; 12929if (k > 0 ) {// the lent slots are refilled after the prompt 12930const int32_t first = (int32_t ) (xcache .slots ()- k ); 12931// the elastic K/V first: its hot experts move into slots of the loan, which are refilled after it 12932kvg_started = true; 12933kvg_start (first ); 12934if (!kvg_ensure (n_prompt + o .max_new + 64 , [] { 12935 dpct::get_current_device ().queues_wait_and_throw (); }))return 1 ; 12936for (size_t i = 0 ;i < host_res .size ();++ i ) 12937if (host_res [i ] >=first ) { 12938lent .emplace_back ((int32_t )i ,host_res [i ]); 12939host_res [i ]= strata::core::kNotResident ; 12940 } 12941res_put (d_res ); 12942borrow = xcache .device_slot (first ); 12943borrow_bytes = xcache .slot_offsets () ? (uint64_t ) (xcache .bytes ()- (int64_t )xcache .slot_offsets ()[first ]) 12944 : (uint64_t )k * (uint64_t )blob ; 12945 std::fprintf (stderr ,"strata generate: prompt path borrows %lld cache slots (%.2f GiB)\n" , (long long )k , 12946 (double )borrow_bytes /1073741824.0 ); 12947 } 12948 } 12949if (borrow == nullptr ) 12950 std::fprintf (stderr ,"strata generate: prompt path allocates its own buffers (no cache slots to borrow)\n" ); 12951if (!prefill .init (wt ,g ,ss ,srcp ,o .expert_cache > 0 ?& xcache :nullptr , 12952host_res .empty () ?nullptr :host_res .data (),o .prefill_chunk ,main_cs ,err ,borrow , 12953borrow_bytes )) { 12954 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 12955return 1 ; 12956 } 12957if (!o .mtp .empty ()) { 12958if (!mtp .bind (wt ,& native_head ,nullptr ,err )) { 12959 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 12960return 1 ; 12961 } 12962prefill .on_chunk = [& ](const float * R_rows ,int64_t T ,int64_t p0 , std::string & e )-> bool { 12963// cell i pairs R_i with the token at i + 1 (every such token is in the prompt) 12964 std::vector < int32_t > nxt ((size_t )T ); 12965for (int64_t t = 0 ;t < T ;++ t )nxt [(size_t )t ]= (int32_t )o .tokens [(size_t ) (p0 + t + 1 )]; 12966if (prefill .draft_kv (mtp ,R_rows ,nxt .data (),T ,p0 ,e ))return true;// E-9 12967return e .empty ()&& mtp .prefill (R_rows ,nxt .data (),T ,p0 ,e ); 12968 }; 12969 } 12970if (use_df2 ) {// the drafter's context: the last 2047 prompt rows' taps 12971df2 .reset (); 12972prefill .set_taps (df2 .tap_layers (), std::max < int64_t > (0 ,n_prompt - 2047 ),2048 ); 12973prefill .on_taps = [& ](const float * taps ,int64_t rows ,int64_t pos0 , std::string & e )-> bool {return df2 .context (taps ,rows ,pos0 ,e ); }; 12974 } 12975if (!kvg_started ) {// the elastic K/V: every cell this run can reach (no loan) 12976kvg_started = true; 12977kvg_start (xcache .slots ()); 12978if (!kvg_ensure (n_prompt + o .max_new + 64 , [] { 12979 dpct::get_current_device ().queues_wait_and_throw (); }))return 1 ; 12980 } 12981const Clock ::time_point tp0 = Clock ::now (); 12982if (!prefill .run (o .tokens .data (),n_batched ,0 ,err )) { 12983 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 12984return 1 ; 12985 } 12986prefill .clear_taps (); 12987// refill the lent slots from the arena and give them back to the decode tier 12988if (!lent .empty ()) { 12989const Clock ::time_point tr = Clock ::now (); 12990size_t queued = 0 ; 12991for (const auto & [i ,slot ] :lent ) {// D-4: queued, one wait (STRATA_REFILL_BLOCKING=1: each) 12992const uint8_t * b = srcp -> blob (i /g .n_expert ,i %g .n_expert ); 12993const int64_t nb = (int64_t ) strata::kernels::cpu::expert_layout ().blob_bytes (i /g .n_expert ); 12994if (b == nullptr || !(refill_blocking () ?xcache .fill_slot_blocking (slot ,b ,err ,nb ) 12995 :xcache .fill_slot_queued (slot ,b ,err ,nb ))) { 12996 std::fprintf (stderr ,"strata generate: refilling a lent slot failed: %s\n" ,err .c_str ()); 12997return 1 ; 12998 } 12999host_res [(size_t )i ]= slot ; 13000// SYCL port: GgufExpertSource::blob() hands out a ring of 512 buffers, valid until the next blob() 13001// call; a queued copy reads its buffer later, so drain before the ring can wrap onto one (938 lent 13002// slots refilled through 512 buffers gave ~426 slots another expert's bytes) 13003if (!refill_blocking ()&& ++ queued %256 == 0 && !xcache .sync_queued (err )) { 13004 std::fprintf (stderr ,"strata generate: refilling the lent slots failed: %s\n" ,err .c_str ()); 13005return 1 ; 13006 } 13007 } 13008if (!xcache .sync_queued (err )) { 13009 std::fprintf (stderr ,"strata generate: refilling the lent slots failed: %s\n" ,err .c_str ()); 13010return 1 ; 13011 } 13012#if defined(_WIN32 ) 13013for (const auto & [i ,slot ] :lent ) 13014srcp -> release (i /g .n_expert ,i %g .n_expert ); 13015#endif 13016res_put (d_res ); 13017 std::fprintf (stderr ,"strata generate: %zu lent slots refilled in %.1f ms\n" ,lent .size (), 13018 std::chrono::duration < double , std::milli > (Clock ::now ()- tr ).count ()); 13019 } 13020prefill_batched_ms = std::chrono::duration < double , std::milli > (Clock ::now ()- tp0 ).count (); 13021prefill_ms += prefill_batched_ms ; 13022 strata::uc_probe ("after-prefill" ); 13023pos_start = n_batched ; 13024tok = o .tokens [(size_t )pos_start ]; 13025// the PLE window of the token path: the two tokens before `pos_start` 13026ss .ple_prev [0 ]= pos_start >=2 ? (int32_t )o .tokens [(size_t ) (pos_start - 2 )] :-1 ; 13027ss .ple_prev [1 ]= pos_start >=1 ? (int32_t )o .tokens [(size_t ) (pos_start - 1 )] :-1 ; 13028const strata::prefill::PrefillStats & ps = prefill .stats (); 13029 std::fprintf (stderr ,"strata generate: prefill %lld tokens in %lld chunks, %.1f ms (%.1f tok/s); experts " 13030"streamed %lld (%lld by DMA, host %.1f ms), resident %lld; PLE %.1f ms\n" , 13031 (long long )ps .tokens , (long long )ps .chunks ,ps .ms_total , 13032ps .ms_total > 0 ?1000.0 * (double )ps .tokens /ps .ms_total :0.0 , (long long )ps .experts_streamed , 13033 (long long )ps .experts_dma ,ps .ms_experts_host , (long long )ps .experts_resident ,ps .ms_ple ); 13034 } 13035 13036if (!kvg_started ) {// the elastic K/V of a prompt that was not read in batches 13037kvg_started = true; 13038kvg_start (xcache .slots ()); 13039if (!kvg_ensure (n_prompt + o .max_new + 64 , [] { 13040 dpct::get_current_device ().queues_wait_and_throw (); }))return 1 ; 13041 } 13042for (int64_t pos = pos_start ;;++ pos ) { 13043// plan v0.3 P6: a native pack's last prompt token is the first verify window (T = 1) 13044if (native_pack ) {spec_pos = pos ;break ; } 13045if (pos >=o .max_context ) { 13046 std::fprintf (stderr ,"strata generate: ran out of context at position %lld\n" , (long long )pos ); 13047return 2 ; 13048 } 13049// **THE TOKEN TIMER STARTS HERE, BEFORE ANY OF THE TOKEN'S WORK (A7).** It used to start after 13050// `put_input`/`embed_row`, which excluded the embedding and the PLE window advance from the reported 13051// rate, and it stopped before the NaN scan, the logits dump and the sampler. The published tok/s 13052// figure is a WALL-CLOCK rate: everything one token costs, PLE advance to sampled id. A rate that 13053// excludes real per-token work is not a rate anyone can plan against. 13054const Clock ::time_point t0 = Clock ::now (); 13055// **THE PLE'S TOKEN WINDOW ADVANCES HERE, ONCE PER TOKEN, AND `ple_stage_token` RUNS OUTSIDE THE 13056// CAPTURE.** Both are the driver's job: `ngram_rows` is a host hash over the last three tokens and the 13057// table gather is a host read, so either one inside a captured graph would run once at capture time and 13058// replay forever. `ple_prev` is OLDEST FIRST and `-1` means "no predecessor", which `ngram_rows` 13059// treats as the EOS cut - a sequence boundary. 13060ss .ple_token = (int32_t )tok ; 13061Clock ::time_point tp = Clock ::now (); 13062// Plan v0.3 P2: the 16 SSD reads start here and complete while the embedding is staged; `ms_ple` is 13063// the issue plus the time still spent WAITING afterwards, i.e. the part the embedding did not hide. 13064if (ss .ple .ready ()&& !strata::core::ple_issue_token (ss .ple ,err )) { 13065 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 13066return 1 ; 13067 } 13068 { 13069const Clock ::time_point n = Clock ::now (); 13070ms_ple += std::chrono::duration < double , std::milli > (n - tp ).count (); 13071tp = n ; 13072 } 13073if (!put_input (tok ,pos ))return 1 ; 13074 { 13075const Clock ::time_point n = Clock ::now (); 13076ms_embed += std::chrono::duration < double , std::milli > (n - tp ).count (); 13077tp = n ; 13078 } 13079if (ss .ple .ready ()&& !strata::core::ple_finish_token (ss .ple ,token_stream ,err )) { 13080 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 13081return 1 ; 13082 } 13083 { 13084const Clock ::time_point n = Clock ::now (); 13085ms_ple += std::chrono::duration < double , std::milli > (n - tp ).count (); 13086tp = n ; 13087 } 13088 13089if (pos %256 == 0 || pos + 1 >=n_prompt - 1 ) 13090 std::fprintf (stderr ,"strata generate: position %lld, token %lld%s\n" , (long long )pos , (long long )tok , 13091pos < n_prompt ?" (prompt)" :"" ); 13092// **`d.layers` IS THE BLOB'S LAYER AXIS, NOT A COUNTER.** The adapter uses it to index 13093// `experts.bin` as `layer * n_expert + expert`, so it MUST restart at 0 for every token. Leaving it 13094// running across tokens asks for layer 48 of a 48-layer file on the second token - which 13095// `FileExpertSource` REFUSES rather than wrapping into layer 0's experts, and that refusal is the only 13096// reason this was a clean error instead of a silently wrong second token. 13097drive .d .layers = 0 ; 13098drive .d .experts = 0 ; 13099drive .d .failed = false; 13100err .clear (); 13101if (o .no_capture ) { 13102if (!strata::core::session_token (wt ,g ,pos ,/*pos_base=*/ 0 ,ss ,d_parts ,main_cs , 13103o .sync_every_layer ,err )) { 13104 std::fprintf (stderr ,"strata generate: session_token: %s\n" ,err .c_str ()); 13105return 1 ; 13106 } 13107 }else { 13108 strata::core::doorbell_reset (db ); 13109if (tgraph .captured ) { 13110if (!strata::core::session_run_token (g ,pos ,/*pos_base=*/ 0 ,ss ,tgraph ,pool_fn ,pool_user , 13111loop_scratch .y_miss ,main_cs ,err )) { 13112 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 13113return 1 ; 13114 } 13115 }else if (!strata::core::session_loop (g ,pos ,/*pos_base=*/ 0 ,ss ,gr ,pool_fn ,hit_fn ,pool_user ,/*overlap=*/ true,main_cs , 13116err ,layer_stage ,& loop_scratch )) { 13117 std::fprintf (stderr ,"strata generate: session_loop: %s\n" ,err .c_str ()); 13118return 1 ; 13119 } 13120 } 13121if (final_r != nullptr ) { 13122 dpct::get_in_order_queue () 13123 .memcpy (final_r_host .data (),ss .R , 13124final_r_host .size ()* sizeof (float )) 13125 .wait (); 13126const int64_t posrec [2 ]= {pos ,tok }; 13127 std::fwrite (posrec ,sizeof posrec ,1 ,final_r ); 13128 std::fwrite (final_r_host .data (),sizeof (float ),final_r_host .size (),final_r ); 13129 } 13130if (drive .d .failed ) { 13131 std::fprintf (stderr ,"strata generate: the expert pool failed at layer %lld expert %lld: %s\n" , 13132 (long long )drive .d .fail_layer , (long long )drive .d .fail_expert , 13133drive .d .fail ?drive .d .fail :"(no message)" ); 13134return 1 ; 13135 } 13136 { 13137// **THE LAYER LOOP ITSELF, WHICH IS WHAT `--gpu-only-full` HAS TO BE COMPARED AGAINST.** 13138const Clock ::time_point n = Clock ::now (); 13139ms_layers += std::chrono::duration < double , std::milli > (n - tp ).count (); 13140tp = n ; 13141 } 13142// ---- the ladder for THIS position, in the order `session_loop` filled it: layer 0 first. 13143if (layer_dump != nullptr ) std::fwrite (layer_stage ,sizeof (float ),layer_floats ,layer_dump ); 13144if (half_dump != nullptr ) { 13145 std::fwrite (half_stage ,sizeof (float ), (size_t )g .n_layers * (size_t )half_stride ,half_dump ); 13146 } 13147if (!run_head (token_stream )) { 13148 std::fprintf (stderr ,"strata generate: lm_head: %s\n" ,err .c_str ()); 13149return 1 ; 13150 } 13151// **A CHECKPOINT AFTER THE HEAD, BECAUSE AN ASYNC FAULT IS STICKY AND LIES ABOUT WHERE IT HAPPENED.** 13152// Measured, and it cost an hour: without this, `embed_row`'s D2H on the NEXT token reported "an illegal 13153// memory access" at a plane offset that has nothing to do with the fault, and the layer that actually 13154// faulted had completed its own error checks successfully - because its kernels had not run yet. A 13155// sticky error surfaces at the next SYNCHRONISING call, which is whatever happens to come next. 13156if (!o .stream_token && 13157DPCT_CHECK_ERROR ( 13158 dpct::get_current_device ().queues_wait_and_throw ())!= 0 ) { 13159 std::fprintf ( 13160stderr , 13161"strata generate: the device faulted in lm_head at position " 13162"%lld: %s\n" , 13163/* 13164DPCT1009: SYCL reports errors using exceptions and does not 13165use error codes. Please replace the 13166"get_error_string_dummy(...)" with a real error-handling 13167function. 13168*/ 13169/* 13170DPCT1010: SYCL uses exceptions to report errors and does 13171not use the error codes. The cudaGetLastError function call was 13172replaced with 0. You need to rewrite this code. 13173*/ 13174 (long long )pos , dpct::get_error_string_dummy (0 )); 13175return 1 ; 13176 } 13177 { 13178const Clock ::time_point n = Clock ::now (); 13179ms_head += std::chrono::duration < double , std::milli > (n - tp ).count (); 13180tp = n ; 13181 } 13182const bool emit_logits = dump != nullptr && 13183 strata::program::logits_selection::selected (pos ,dump_positions ,o .logits_stride ); 13184const bool read_logits = !o .stream_token || o .check_logits || emit_logits ; 13185/* 13186DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. 13187While the origin API might be synchronous, it depends on the type of 13188operand memory, so you may need to call wait() on event return by memcpy 13189API to ensure synchronization behavior. 13190*/ 13191if (read_logits && 13192 (DPCT_CHECK_ERROR (strata::q_of (token_stream )-> memcpy ( 13193logits .data (),d_logits , (size_t )n_vocab * 4 ))!= 0 || 13194DPCT_CHECK_ERROR (strata::q_of (token_stream )-> wait ())!= 0 )) { 13195 std::fprintf (stderr ,"strata generate: reading the logits back failed\n" ); 13196return 1 ; 13197 } 13198int bad = 0 ; 13199if (read_logits )for (float v :logits )if (!std::isfinite (v ))++ bad ; 13200if (bad != 0 ) { 13201 std::fprintf (stderr ,"strata generate: %d of %lld logits are not finite at position %lld\n" ,bad , 13202 (long long )n_vocab , (long long )pos ); 13203return 1 ; 13204 } 13205// the header with the first row (see `hdr`): a run that dumps nothing leaves an empty file 13206if (emit_logits && !hdr_written && std::fwrite (hdr ,sizeof hdr ,1 ,dump )!= 1 ) { 13207 std::fprintf (stderr ,"strata generate: cannot write logits header\n" ); 13208 std::fclose (dump ); 13209return 1 ; 13210 } 13211if (emit_logits )hdr_written = true; 13212if (emit_logits && std::fwrite (logits .data (),sizeof (float ), (size_t )n_vocab ,dump )!= (size_t )n_vocab ) { 13213 std::fprintf (stderr ,"strata generate: cannot write logits at position %lld\n" , (long long )pos ); 13214 std::fclose (dump ); 13215return 1 ; 13216 } 13217 { 13218// **993 KB OF SYNCHRONOUS D2H AND A 248,320-FLOAT HOST SCAN, EVERY TOKEN.** (The review's notes 13219// say 151,936 floats; the artifact's `output.weight` is 248,320 rows, so the real figure is 1.6x 13220// that - a number nobody had checked because nothing measured this term.) R2.6 asks for the dump 13221// and the scan to be behind flags; round 36 did exactly that and measured it SLOWER, because on 13222// this driver a large blocking readback is also what flushes the pipeline for the sampler that 13223// follows. Timed so the claim can be re-checked rather than remembered. 13224const Clock ::time_point n = Clock ::now (); 13225ms_readback += std::chrono::duration < double , std::milli > (n - tp ).count (); 13226tp = n ; 13227 } 13228 13229int next = 0 ; 13230// The draw is Philox(seed, position), as in a verify window (row t at pos0 draws pos0 + t): a seed gives 13231// the same text whether a token comes from this path or from the speculative loop below. 13232sp .counter = (uint64_t )pos ; 13233 strata::kernels::sample_tokens (d_logits ,1 , (int )n_vocab ,nullptr ,0 ,sp ,d_next ,token_stream ); 13234/* 13235DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. 13236While the origin API might be synchronous, it depends on the type of 13237operand memory, so you may need to call wait() on event return by memcpy 13238API to ensure synchronization behavior. 13239*/ 13240if (DPCT_CHECK_ERROR (strata::q_of (token_stream )-> memcpy ( 13241& next ,d_next ,sizeof (int )))!= 0 || 13242DPCT_CHECK_ERROR (strata::q_of (token_stream )-> wait ())!= 0 ) { 13243 std::fprintf ( 13244stderr , 13245"strata generate: reading the sampled token back failed: %s\n" , 13246/* 13247DPCT1009: SYCL reports errors using exceptions and does not 13248use error codes. Please replace the 13249"get_error_string_dummy(...)" with a real error-handling 13250function. 13251*/ 13252/* 13253DPCT1010: SYCL uses exceptions to report errors and does 13254not use the error codes. The cudaGetLastError function call was 13255replaced with 0. You need to rewrite this code. 13256*/ 13257 dpct::get_error_string_dummy (0 )); 13258return 1 ; 13259 } 13260// The sampled-token synchronization also completes every captured QSA 13261// status readback. Retain one status per layer so a later layer cannot 13262// hide an earlier failure; no extra synchronization or token allocation. 13263if (o .native_flash_attn_short )for (int64_t j = 0 ;j < ss .qsa_alloc ;++ j ) { 13264const int64_t i = ss .qsa_ord0 + j ;// the global ordinal, as the session's carve names it 13265const int32_t status = ss .qsa_states [i ].host_step [strata::kernels::kStepCount ]; 13266if (status != 0 ) { 13267 std::fprintf (stderr ,"strata generate: native attention status %d at QSA layer %lld, position %lld\n" , 13268status , (long long )i , (long long )pos ); 13269return 1 ; 13270 } 13271 } 13272if (next < 0 || next >=n_vocab ) { 13273 std::fprintf (stderr ,"strata generate: the sampler returned %d, outside 0..%lld\n" ,next , 13274 (long long ) (n_vocab - 1 )); 13275return 1 ; 13276 } 13277 { 13278// **TWO DEVICE-WIDE SYNCS FOR FOUR BYTES.** `sample_tokens(nullptr)` ends in 13279// `cudaDeviceSynchronize()` (`sampler.cu:245`) and the blocking 4-byte read below is the second. 13280const Clock ::time_point n = Clock ::now (); 13281ms_sample += std::chrono::duration < double , std::milli > (n - tp ).count (); 13282++ phase_tokens ; 13283 } 13284// CHARGED HERE, AFTER THE SAMPLER, so the wall-clock rate covers the whole token including the embedding, 13285// the NaN scan, the logits readback and the sample (A7). Only DECODE positions count; prefill is 13286// measured separately. 13287if (pos >=n_prompt - 1 )total_ms += std::chrono::duration < double , std::milli > (Clock ::now ()- t0 ).count (); 13288else prefill_ms += std::chrono::duration < double , std::milli > (Clock ::now ()- t0 ).count (); 13289if (pos == n_prompt - 1 )ttft_ms = std::chrono::duration < double , std::milli > (Clock ::now ()- t_start ).count (); 13290// **THE PREDICTION AT THE LAST PROMPT POSITION *IS* THE FIRST GENERATED TOKEN.** Sampling on every 13291// position and recording only from `n_prompt - 1` onward is what keeps the two cases from needing 13292// separate handling - and the version that "obviously" only samples after the prompt loses exactly one 13293// token's worth of conditioning. 13294if (pos >=n_prompt - 1 )produced .push_back (next ); 13295if ((int64_t )produced .size () >=o .max_new )break ; 13296if (o .stop_eos && pos >=n_prompt - 1 && 13297 std::find (o .eos_ids .begin (),o .eos_ids .end (), (int64_t )next )!= o .eos_ids .end ())break ; 13298// TEACHER FORCING while the prompt lasts: the next input is the prompt's own next token, not the 13299// model's guess. Feeding the guess would make the run depend on the model's own errors from position 13300// 1, which is a different (and worse) measurement of the same prompt. 13301// and the window advances: the token just decoded becomes the newest predecessor. 13302ss .ple_prev [0 ]= ss .ple_prev [1 ]; 13303ss .ple_prev [1 ]= (int32_t )tok ; 13304tok = (pos + 1 < n_prompt ) ?o .tokens [(size_t ) (pos + 1 )] :next ; 13305// Plan v0.3 P6: from the first generated token on, the speculative loop below takes over. 13306if (o .spec > 0 && pos >=n_prompt - 1 ) {spec_pos = pos + 1 ;break ; } 13307 } 13308 13309// ================================ plan v0.3 P6: SPECULATIVE DECODING ================================ 13310// 13311// Each round verifies [the last emitted token, drafts...] in one window; the window's argmax after token t 13312// is exactly what greedy decode would emit there, so the first draft that differs ends the round and the 13313// round emits (accepted drafts + 1) tokens. `commit` keeps the state of the tokens that were emitted. 13314const bool ended = o .stop_eos && !produced .empty ()&& 13315 std::find (o .eos_ids .begin (),o .eos_ids .end (), (int64_t )produced .back ())!= o .eos_ids .end (); 13316if (spec_pos > 0 && (int64_t )produced .size ()< o .max_new && !ended ) { 13317auto read_ids = [](const std::string & path , std::vector < int64_t >& ids ) { 13318 std::ifstream in (path ); 13319 std::string text ((std::istreambuf_iterator < char > (in )), std::istreambuf_iterator < char > ()); 13320 std::string e ; 13321return (bool )in && parse_i64_list (text .c_str (),ids ,e ); 13322 }; 13323 std::vector < int64_t > oracle ,follow ; 13324if (!o .spec_oracle .empty ()&& !read_ids (o .spec_oracle ,oracle )) { 13325 std::fprintf (stderr ,"strata generate: cannot read --spec-oracle %s\n" ,o .spec_oracle .c_str ()); 13326return 2 ; 13327 } 13328if (!o .spec_follow .empty ()&& !read_ids (o .spec_follow ,follow )) { 13329 std::fprintf (stderr ,"strata generate: cannot read --spec-follow %s\n" ,o .spec_follow .c_str ()); 13330return 2 ; 13331 } 13332// --spec-follow: the run ends with the continuation 13333const int64_t max_new = follow .empty () ?o .max_new : std::min < int64_t > (o .max_new , (int64_t )follow .size ()); 13334int64_t follow_differ = 0 ,follow_emitted = 0 ; 13335if (thits .d_res == nullptr ) { 13336 std::fprintf (stderr ,"strata generate: --spec needs the device residency table (--expert-profile, " 13337"--expert-cache and the token graph)\n" ); 13338return 2 ; 13339 } 13340mem_mark ("the head and the prompt path" ); 13341 strata::core::Verifier ver ; 13342 strata::core::VerifyHits vh ; 13343vh .d_res = thits .d_res ; 13344int32_t * usage_dev = nullptr ;// STRATA_USAGE_DUMP=PATH: the device plan counts every routed expert (measurement) 13345const char * usage_dump = std::getenv ("STRATA_USAGE_DUMP" ); 13346if (mirror_table_d && usage_dump && * usage_dump ) { 13347usage_dev = sycl::malloc_device < int32_t > ((size_t ) (g .n_layers * g .n_expert ), dpct::get_in_order_queue ()); 13348 dpct::get_in_order_queue ().memset (usage_dev ,0 , (size_t ) (g .n_layers * g .n_expert )* 4 ).wait (); 13349 } 13350if (mirror_table_d ) strata::kernels::resident_plan_set_mirror (thits .d_res ,mirror_table_d ,usage_dev , (long long ) (g .n_layers * g .n_expert )); 13351vh .h_res = host_res .empty () ?nullptr :host_res .data (); 13352vh .cache_base = thits .cache_base ; 13353vh .blob = thits .blob ; 13354vh .slot_off = xcache .slot_offsets ();// E-6: the device plan's pointers 13355vh .n_slots = xcache .slots (); 13356if (use_df2 )ver .set_taps (df2 .tap_layers ()); 13357if (!ver .init (wt ,g ,ss ,vh ,native_head .loaded () ?& native_head :nullptr ,o .spec ,err )) { 13358print_start_refusal ("strata generate" ,err ); 13359return 1 ; 13360 } 13361const bool use_mtp = !o .mtp .empty (); 13362if (use_mtp && !mtp .bind (wt ,& native_head ,ver .final_R_all (),err )) { 13363 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 13364return 1 ; 13365 } 13366if (use_df2 ) {// no MTP to draft instead: anything DFlash2 cannot do ends the run 13367if (!ver .tapping ()) { 13368 std::fprintf (stderr ,"strata generate: --draft dflash2: the verifier keeps no taps here, so the run ends here\n" ); 13369return 1 ; 13370 } 13371df2 .set_max_drafts ((o .mtp_max_t > 0 ? std::min (o .mtp_max_t ,o .spec ) :o .spec )- 1 );// the widest window - 1: the head and the walk run for that many rows 13372if (!df2 .bind (wt ,& native_head ,df2_vocab_file ,err )|| !df2 .prepare (ver .tap_dev (),err )) { 13373 std::fprintf (stderr ,"strata generate: --draft dflash2: %s. It needs about 1.2 GiB of VRAM in all (--vram-reserve-mib keeps it); there is no MTP to draft instead, so the run ends here\n" ,err .c_str ()); 13374return 1 ; 13375 } 13376 std::fprintf (stderr ,"strata generate: DFlash2 drafter on (%s, graphs captured in %.0f ms), no MTP layer is loaded\n" ,o .draft_model .c_str (),df2 .ms_capture ); 13377 } 13378const bool draft_on = use_mtp || use_df2 ;// some drafter proposes 13379mem_mark ("the verifier and the drafter's binding" ); 13380ver .set_sampling (sp );// the CLI's own sampling (until 0.1.19 this loop was always greedy); no penalties here 13381if (use_mtp )mtp .set_draft_sampling (sp );// STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise) 13382ver .set_split (o .spec_split ); 13383// auto: the copy kernel for every pack. DMA (the native packs' default until 0.1.13) has the host call 13384// cudaMemcpyAsync + cudaLaunchHostFunc inside a verify window while the GPU spins on the flag they raise; 13385// issue #31's thread dumps show the host stuck in that cudaMemcpyAsync on a driver lock for good. The copy 13386// kernel needs no host CUDA call there, and costs ~1-3% decode on IQ3_S (45.3 -> 44.8 tok/s, 8 requests). 13387ver .set_pcie_mode (o .pcie_mode == "dma" ?0 :o .pcie_mode == "direct" ?1 :2 ); 13388drive .d .plan = ver .plan_sink (); 13389drive .d .pcie_num = (int ) (o .pcie_frac * 256.0 + 0.5 ); 13390if (drive .d .pcie_num < 0 )drive .d .pcie_num = 0 ; 13391if (drive .d .pcie_num > 256 )drive .d .pcie_num = 256 ; 13392const int64_t pcie0 = drive .d .pcie_experts ; 13393// CS-T: the file tier since the decode began (the prompt path's copies are before this) 13394const int64_t files0 = src .file_reads (),ram0 = src .ram_reads (); 13395const uint64_t fbytes0 = src .file_blob_bytes (),fall0 = src .file_read_bytes (); 13396const double fms0 = src .file_ms (); 13397if (o .adapt_every > 0 && o .adapt_swaps > 0 )drive .d .usage .assign ((size_t ) (g .n_layers * g .n_expert ),0.0f ); 13398int64_t swaps_total = 0 ; 13399double ms_adapt = 0 ; 13400 dpct::queue_ptr adapt_stream = & dpct::get_in_order_queue (); 13401/* 13402DPCT1025: The SYCL queue is created ignoring the flag and priority 13403options. 13404*/ 13405if (!drive .d .usage .empty ()&& 13406DPCT_CHECK_ERROR ( 13407adapt_stream = dpct::get_current_device ().create_queue (true))!= 134080 ) { 13409 std::fprintf (stderr ,"strata generate: cannot create the refill stream\n" ); 13410return 1 ; 13411 } 13412// plan v0.3 P6: swaps in flight - (residency index, slot) admitted when adapt_ev has completed 13413 std::vector < std::pair < int32_t ,int32_t >> pending ; 13414int pending_age = 0 ;// the windows the pending swaps have waited (adapt_lag) 13415 std::vector < void *> pin_live ;// the swaps' locked arena pages (pin_blob), unlocked once they have landed 13416 dpct::event_ptr adapt_ev = nullptr ; 13417adapt_ev = new sycl::event (); 13418int64_t adapt_rounds = 0 ;// counted here: `rounds` is declared below the adapt lambda 13419auto apply_pending = [& ](bool wait ) { 13420try { 13421if (pending .empty ())return ; 13422// STRATA_TRACE_ADAPT=1: whether a round's copies had landed when the next window read the table 13423static const bool trace_pending = std::getenv ("STRATA_TRACE_ADAPT" )!= nullptr ; 13424if (wait )adapt_ev -> wait_and_throw (); 13425else if (adapt_ev -> get_info < 13426 sycl::info::event::command_execution_status > ()!= 13427 sycl::info::event_command_status::complete ) { 13428if (trace_pending ) 13429 std::fprintf (stderr ,"strata: PENDING not landed, %zu stay non-resident this window\n" , 13430pending .size ()); 13431return ; 13432 } 13433if (trace_pending ) 13434 std::fprintf (stderr ,"strata: PENDING landed, %zu experts become resident\n" ,pending .size ()); 13435unpin_blobs (pin_live ); 13436src .commit_exchanges ();// the resident RAM mode: the evicted experts take their places in RAM 13437for (const auto & [i ,slot ] :pending ) { 13438host_res [(size_t )i ]= slot ; 13439srcp -> release ((int64_t )i /g .n_expert , (int64_t )i %g .n_expert );// in VRAM now: RAM not needed 13440 } 13441pending .clear (); 13442pending_age = 0 ; 13443if (d_res != nullptr ) 13444res_put (d_res ); 13445 } 13446catch (sycl::exception const & exc ) { 13447 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 13448 <<", line:" <<__LINE__ << std::endl ; 13449 std::exit (1 ); 13450 } 13451 }; 13452// Plan v0.3 P6: the VRAM tier follows the conversation. Candidates are missing experts routed at least 13453// twice (decayed); each is paired with its layer's least-routed resident expert and swapped when it was 13454// routed clearly more often. Copies run between rounds, when the GPU is idle. 13455auto adapt = [& ]()-> bool { 13456const Clock ::time_point ta = Clock ::now (); 13457++ adapt_rounds ; 13458// STRATA_TRACE_ADAPT: why an adapt round did or did not swap. Default off, one getenv, and it 13459// reports the only thing that can make an adapt round a coin flip: whether the PREVIOUS round's 13460// asynchronous expert copies had landed by the time this round started. 13461static const bool trace_adapt = std::getenv ("STRATA_TRACE_ADAPT" )!= nullptr ; 13462if (!pending .empty ()) { 13463if (trace_adapt ) 13464 std::fprintf (stderr ,"strata: ADAPT round=%lld SKIPPED, %zu swaps still in flight\n" , 13465 (long long )adapt_rounds ,pending .size ()); 13466return true;// the previous swaps are still in flight 13467 } 13468if (trace_adapt ) std::fprintf (stderr ,"strata: ADAPT round=%lld considering\n" , (long long )adapt_rounds ); 13469struct Swap {float gain ;int32_t layer ,in ,out ; }; 13470 std::vector < Swap > swaps ; 13471 std::vector < std::pair < float ,int32_t >> cand ,vict ; 13472for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 13473cand .clear (); 13474vict .clear (); 13475const float * u = drive .d .usage .data ()+ l * g .n_expert ; 13476const int32_t * r = host_res .data ()+ l * g .n_expert ; 13477for (int32_t e = 0 ;e < (int32_t )g .n_expert ;++ e ) { 13478if (r [e ]< 0 ) {if (u [e ] >=2.0f && !helper_holds (l ,e ))cand .emplace_back (u [e ],e ); } 13479else vict .emplace_back (u [e ],e ); 13480 } 13481if (cand .empty ()|| vict .empty ())continue ; 13482 std::sort (cand .begin (),cand .end (), [](auto & a ,auto & b ) {return a .first > b .first ; }); 13483const size_t nc = std::min (cand .size (),vict .size ()); 13484 std::partial_sort (vict .begin (),vict .begin ()+ (ptrdiff_t )nc ,vict .end (), 13485 [](auto & a ,auto & b ) {return a .first < b .first ; }); 13486for (size_t i = 0 ;i < nc ;++ i ) { 13487if (cand [i ].first < vict [i ].first + 1.5f )break ; 13488swaps .push_back ({cand [i ].first - vict [i ].first , (int32_t )l ,cand [i ].second ,vict [i ].second }); 13489 } 13490 } 13491 std::sort (swaps .begin (),swaps .end (), [](const Swap & a ,const Swap & b ) {return a .gain > b .gain ; }); 13492if ((int )swaps .size ()> o .adapt_swaps )swaps .resize ((size_t )o .adapt_swaps ); 13493// this (non-serve) path refills CUDA0's cache only, so its copies back read CUDA0's cache too 13494if (!resident_stage_swaps (src ,host_res ,g .n_expert ,swaps , 13495 [& ](int64_t )-> SwapHome {return {& xcache ,adapt_stream ,-1 }; })) { 13496 std::fprintf (stderr ,"strata generate: an adaptive refill failed (copying evicted experts back)\n" ); 13497return false; 13498 } 13499if (pin_blobs_on ()) {// lock the batch's source pages (a file-backed arena on AMD; see pin_blobs) 13500 std::vector < std::pair < uintptr_t ,uintptr_t >> spans ; 13501for (const Swap & s :swaps ) 13502if (const uint8_t * b = srcp -> blob (s .layer ,s .in )) 13503spans .emplace_back ((uintptr_t )b , 13504 (uintptr_t )b + strata::kernels::cpu::expert_layout ().blob_bytes (s .layer )); 13505pin_blobs (std::move (spans ),pin_live ); 13506 } 13507// STRATA_DMA_BATCH (F12): the round's copies as one cudaMemcpyBatchAsync; mode 0 is the loop of one copy each 13508const int dma_mode = strata::core::dma_batch_mode (); 13509 std::vector < void *> cp_dst ; 13510 std::vector < const void *> cp_src ; 13511 std::vector < size_t > cp_bytes ; 13512for (const Swap & s :swaps ) { 13513const size_t in = (size_t )s .layer * g .n_expert + s .in ,out = (size_t )s .layer * g .n_expert + s .out ; 13514const int32_t slot = host_res [out ]; 13515const uint8_t * b = srcp -> blob (s .layer ,s .in ); 13516const size_t blob_n = (size_t ) strata::kernels::cpu::expert_layout ().blob_bytes (s .layer ); 13517// asynchronous: the copies run while the MTP drafts; the next window waits for them 13518if (slot < 0 || b == nullptr ) { 13519 std::fprintf (stderr ,"strata generate: an adaptive refill failed\n" ); 13520return false; 13521 } 13522if (dma_mode != 0 ) { 13523cp_dst .push_back (xcache .device_slot (slot )); 13524cp_src .push_back (b ); 13525cp_bytes .push_back (blob_n ); 13526 }else if (adapt_copy_h2d (xcache .device_slot (slot ),b ,blob_n , 13527adapt_stream )!= 0 ) { 13528 std::fprintf (stderr ,"strata generate: an adaptive refill failed\n" ); 13529return false; 13530 } 13531host_res [out ]= strata::core::kNotResident ;// evicted now: the CPU computes it meanwhile 13532srcp -> prefetch (s .layer ,s .out );// a file-backed arena released its pages: read them back ahead 13533pending .emplace_back ((int32_t )in ,slot );// resident once the copy has landed 13534 } 13535if (!cp_dst .empty ()&& 13536 strata::core::copy_blobs (cp_dst .data (),cp_src .data (), 13537cp_bytes .data (),cp_dst .size (), 13538adapt_stream ,dma_mode )!= 0 ) { 13539 std::fprintf (stderr ,"strata generate: an adaptive refill failed\n" ); 13540return false; 13541 } 13542if (!swaps .empty ()) dpct::sync_barrier (adapt_ev ,adapt_stream ); 13543if (trace_adapt ) 13544 std::fprintf (stderr ,"strata: ADAPT round=%lld swapped %zu of %d slots, usage decayed\n" , 13545 (long long )adapt_rounds ,swaps .size (),o .adapt_swaps ); 13546for (float & v :drive .d .usage )v *=o .adapt_decay ; 13547swaps_total += (int64_t )swaps .size (); 13548ms_adapt += std::chrono::duration < double , std::milli > (Clock ::now ()- ta ).count (); 13549return true; 13550 }; 13551int64_t p = spec_pos ; 13552int32_t x = (int32_t )tok ; 13553 std::vector < int32_t > drafts ((size_t )o .spec ,0 ); 13554 std::vector < float > dprob ((size_t )o .spec ,1.0f ); 13555 std::vector < int64_t > window_hist ((size_t )o .spec + 1 ,0 ); 13556// plan v0.3 P6: with a native pack the first window is the last prompt token alone (it produces the first 13557// generated token and the MTP's first cell); otherwise the token loop already did that. 13558bool first_window = native_pack ; 13559// SYCL port: every window graph and the drafter's graphs are captured here, once, instead of on first use in 13560// the loop below (STRATA_WARM_GRAPHS=0: as before). A server pays this once per process, not per request. 13561 { 13562static const bool warm_on = [] {const char * v = std::getenv ("STRATA_WARM_GRAPHS" );return !(v && v [0 ]== '0' ); }(); 13563if (warm_on ) { 13564const Clock ::time_point tw = Clock ::now (); 13565if (!ver .warm (err )|| (use_mtp && !mtp .warm (err ))) { 13566 std::fprintf (stderr ,"strata generate: warm-up capture: %s\n" ,err .c_str ()); 13567return 1 ; 13568 } 13569 std::fprintf (stderr ,"strata generate: window and draft graphs captured in %.0f ms\n" , 13570 std::chrono::duration < double , std::milli > (Clock ::now ()- tw ).count ()); 13571 strata::uc_probe ("captured" ); 13572 } 13573 } 13574if (use_mtp && !first_window && 13575 !mtp .draft_first (o .spec ,ss .R ,x ,p - 1 ,drafts .data (),err ,dprob .data (), (float )o .spec_min_p )) { 13576 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 13577return 1 ; 13578 } 13579 std::vector < int32_t > window ((size_t )o .spec ),outv ((size_t )o .spec ); 13580 std::vector < uint8_t > fdiff ((size_t )o .spec ,0 ); 13581 std::FILE * hashes = o .window_hashes .empty () ?nullptr : std::fopen (o .window_hashes .c_str (),"w" ); 13582if (!o .window_hashes .empty ()&& hashes == nullptr ) { 13583 std::fprintf (stderr ,"strata generate: cannot write %s\n" ,o .window_hashes .c_str ()); 13584return 1 ; 13585 } 13586 std::vector < float > hash_rows ; 13587 std::vector < int64_t > accepted_hist ((size_t )o .spec ,0 ); 13588int64_t rounds = 0 ,drafts_total = 0 ,drafts_ok = 0 ,corrupt_counter = 0 ; 13589const int S_mtp = o .mtp_max_t > 0 ? std::min (o .mtp_max_t ,o .spec ) :o .spec ; 13590if (use_mtp && S_mtp < o .spec )mtp .set_max_drafts (S_mtp - 1 ); 13591 strata::spec::SuffixDrafter sfx (std::max (1 ,o .suffix_draft ),64 , (size_t )o .max_context + 4096 ); 13592 strata::spec::DraftPolicy policy (o .spec );// MTP or lookup window (see draft_policy.hpp) 13593 std::vector < int32_t > sbuf ((size_t )o .spec ,0 ); 13594int64_t sfx_windows = 0 ,sfx_drafts = 0 ,sfx_ok = 0 ; 13595int64_t chain_windows = 0 ,chain_drafts = 0 ,chain_ok = 0 ;// --lookup-chain's own counts 13596 std::vector < int32_t > cbuf ((size_t )o .spec ,0 ),ctail ; 13597 strata::spec::PromptLookupSource lookup_src (sfx ); 13598const bool sfx_on = o .suffix_draft > 0 || o .lookup_chain > 0 ; 13599if (sfx_on ) { 13600for (int64_t t :o .tokens )sfx .append ((int32_t )t ); 13601for (int64_t t :produced )sfx .append ((int32_t )t ); 13602 } 13603if (o .lookup_chain > 0 ) { 13604extra_sources_reset (); 13605for (int64_t t :o .tokens ) {const int32_t t32 = (int32_t )t ;extra_sources_append (& t32 ,1 ); } 13606for (int64_t t :produced ) {const int32_t t32 = (int32_t )t ;extra_sources_append (& t32 ,1 ); } 13607 } 13608const double pool_ms0 = drive .cpu_ms ; 13609const int64_t misses0 = drive .d .multi_misses ,entries0 = drive .d .multi_entries ; 13610// DFlash2 with a long suffix match: the next round's draft is deferred to that round's start (spec/window_rule.hpp skip_draft_for_lookup) 13611const int df2_skip_min = strata::spec::df2_lookup_skip_min (0 ); 13612bool df2_deferred = false; 13613int dfr_n = 0 ; 13614int64_t dfr_pos = 0 ; 13615int32_t dfr_anchor = 0 ; 13616auto defer_df2 = [& ](int a_ )-> bool { 13617if (!use_df2 || o .suffix_draft <=0 || df2_skip_min <=0 )return false; 13618const int ks = sfx .propose (o .spec - 1 ,sbuf .data ()); 13619if (!strata::spec::skip_draft_for_lookup (true,df2_skip_min ,ks ,sfx .last_match ()))return false; 13620df2_deferred = true;dfr_n = a_ + 1 ;dfr_pos = p ;dfr_anchor = outv [(size_t )a_ ]; 13621return true; 13622 }; 13623// the next round's drafts after a commit: the DFlash2 block from the committed rows' taps (the window's first a + 1 rows) 13624auto draft_df2 = [& ](int a_ )-> bool { 13625int32_t dd [strata::core::Dflash2Drafter ::kDrafts ]; 13626float pp [strata::core::Dflash2Drafter ::kDrafts ]; 13627if (!df2 .draft (ver .tap_dev (),a_ + 1 ,p ,outv [(size_t )a_ ],dd ,pp ,err ))return false; 13628for (size_t i = 0 ;i < drafts .size ()&& i < (size_t ) strata::core::Dflash2Drafter ::kDrafts ;++ i ) {drafts [i ]= dd [i ];dprob [i ]= pp [i ]; } 13629return true; 13630 }; 13631while ((int64_t )produced .size ()< max_new ) { 13632const Clock ::time_point t0 = Clock ::now (); 13633bool dfr_lookup = false; 13634int dfr_T = 0 ,dfr_match = 0 ; 13635if (df2_deferred ) {// the draft skipped for a long lookup match: the lookup if the policy takes it, else the draft now (same taps and rows) 13636df2_deferred = false; 13637const int kd = sfx .propose (o .spec - 1 ,sbuf .data ()); 13638const int md = sfx .last_match (); 13639const strata::spec::DraftPolicy ::Pick pkd = kd > 0 ?policy .choose (S_mtp ,kd ,md ) : strata::spec::DraftPolicy ::Pick {}; 13640if (kd > 0 && pkd .lookup ) { 13641dfr_lookup = true;dfr_T = pkd .t ;dfr_match = md ; 13642if (!df2 .context (ver .tap_dev (),dfr_n ,dfr_pos ,err )) { std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ());return 1 ; } 13643 }else { 13644int32_t dd [strata::core::Dflash2Drafter ::kDrafts ]; 13645float pp [strata::core::Dflash2Drafter ::kDrafts ]; 13646if (!df2 .draft (ver .tap_dev (),dfr_n ,dfr_pos ,dfr_anchor ,dd ,pp ,err )) { std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ());return 1 ; } 13647for (size_t i = 0 ;i < drafts .size ()&& i < (size_t ) strata::core::Dflash2Drafter ::kDrafts ;++ i ) {drafts [i ]= dd [i ];dprob [i ]= pp [i ]; } 13648 } 13649 } 13650int T = S_mtp ; 13651 {// the window rule of the round's ACTIVE source (spec/window_rule.hpp) 13652 strata::spec::WindowRuleIn wr ; 13653wr .use_mtp = draft_on ;wr .draft_on = draft_on ;wr .df2_active = use_df2 ;wr .spec_cost = false;wr .first_window = first_window ; 13654wr .chain_rows = 1 ;wr .cap = S_mtp ;wr .start = T ;wr .spec_min_p = o .spec_min_p ; 13655wr .draft_conf = o .draft_conf ;wr .dprob = dprob .data (); 13656T = strata::spec::choose_window (wr ); 13657 } 13658if (first_window )T = 1 ; 13659bool from_sfx = false; 13660int sfx_match = 0 ; 13661if (o .suffix_draft > 0 && !first_window ) { 13662const int k = sfx .propose (o .spec - 1 ,sbuf .data ()); 13663sfx_match = sfx .last_match (); 13664if (k > 0 && (!draft_on || sbuf [0 ]== drafts [0 ])) { 13665const strata::spec::DraftPolicy ::Pick pk = policy .choose (T ,k ,sfx_match ); 13666if (pk .lookup ) {T = pk .t ;from_sfx = true; } 13667 } 13668 } 13669if (dfr_lookup ) {// the lookup window chosen before the draft (the draft was skipped) 13670sfx .propose (o .spec - 1 ,sbuf .data ()); 13671T = dfr_T ;from_sfx = true;sfx_match = dfr_match ; 13672 } 13673// --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them 13674int chain_n = 0 ,cm = 0 ; 13675if (o .lookup_chain > 0 && use_mtp && !first_window && !from_sfx && T < o .spec ) { 13676int csrc = -1 ; 13677const int nt = chain_tail (sfx ,drafts .data (),T - 1 ,ctail ); 13678chain_n = strata::spec::propose_from_sources (lookup_src ,ctail .data (),nt ,T - 1 , 13679 std::min (o .lookup_chain ,o .spec - T ),o .lookup_chain_min , 13680cbuf .data (),& cm ,& csrc ); 13681if (chain_n > 0 && std::getenv ("STRATA_LOOKUP_CHAIN_FIXED" )== nullptr ) { 13682double p_mtp = 1.0 ; 13683for (int i = 0 ;i < T - 1 ;++ i )p_mtp *=dprob [(size_t )i ]; 13684chain_n = policy .chain (T ,p_mtp ,chain_n ,cm ); 13685 } 13686 } 13687const int T_mtp = T ; 13688T += chain_n ; 13689const bool timed_round = !first_window ; 13690++ window_hist [(size_t )T ]; 13691if (p + T > o .max_context ) { 13692 std::fprintf (stderr ,"strata generate: ran out of context at position %lld\n" , (long long )p ); 13693return 2 ; 13694 } 13695window [0 ]= x ; 13696for (int i = 1 ;i < T ;++ i ) { 13697const size_t at = produced .size ()- 1 + (size_t )i ; 13698int32_t d = from_sfx ?sbuf [(size_t )i - 1 ] :draft_on ?drafts [(size_t )i - 1 ] 13699 :at < oracle .size () ? (int32_t )oracle [at ] :0 ; 13700if (i >=T_mtp )d = cbuf [(size_t ) (i - T_mtp )]; 13701if (o .spec_corrupt > 0 && (++ corrupt_counter %o .spec_corrupt )== 0 )d = (d + 1 ) % (int32_t )n_vocab ; 13702window [(size_t )i ]= d ; 13703 } 13704drive .d .layers = 0 ; 13705drive .d .experts = 0 ; 13706drive .d .failed = false; 13707// #463: the previous adapt round's copies land first - with a non-blocking query, whether a swapped-in 13708// expert ran on the GPU or the CPU (they round differently) depended on the copy's timing 13709// (STRATA_ADAPT_NOWAIT=1: 0.1.37's non-blocking query, the A/B) 13710if (adapt_nowait ())apply_pending (false); 13711else if (pending .empty ()|| ++ pending_age >=adapt_lag ())apply_pending (true); 13712if (!ver .run (T ,window .data (),p ,& drive_pool_multi ,& drive ,outv .data (),err )) { 13713 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 13714return 1 ; 13715 } 13716if (drive .d .failed ) { 13717 std::fprintf (stderr ,"strata generate: the expert pool failed at layer %lld expert %lld: %s\n" , 13718 (long long )drive .d .fail_layer , (long long )drive .d .fail_expert , 13719drive .d .fail ?drive .d .fail :"(no message)" ); 13720return 1 ; 13721 } 13722if (const char * wl = std::getenv ("STRATA_DUMP_WINDOW_TOP2" )) {// debug: per window row, the top-2 ids and logits (text lines "pos T row id1 l1 id2 l2") 13723static std::FILE * wlf = std::fopen (wl ,"w" ); 13724 std::vector < float > lrow ((size_t )ver .vocab ()); 13725for (int t = 0 ;wlf != nullptr && t < T ;++ t ) { 13726if (!ver .copy_logits (t ,lrow .data ()))break ; 13727int i1 = 0 ,i2 = -1 ; 13728for (int v = 1 ;v < (int )lrow .size ();++ v ) { 13729if (lrow [(size_t )v ]> lrow [(size_t )i1 ]) {i2 = i1 ;i1 = v ; } 13730else if (i2 < 0 || lrow [(size_t )v ]> lrow [(size_t )i2 ])i2 = v ; 13731 } 13732 std::fprintf (wlf ,"%lld %d %d %d %.5f %d %.5f\n" , (long long ) (p + t ),T ,t ,i1 , (double )lrow [(size_t )i1 ],i2 , (double )lrow [(size_t )i2 ]); 13733 } 13734if (wlf ) std::fflush (wlf ); 13735 } 13736if (hashes != nullptr ) {// FNV-1a over the window's final residual rows (a test path: a plain copy) 13737const size_t n_floats = (size_t )T * (size_t ) (g .hc * g .n_embd ); 13738hash_rows .resize (n_floats ); 13739 dpct::get_in_order_queue () 13740 .memcpy (hash_rows .data (),ver .final_R_all (), 13741n_floats * sizeof (float )) 13742 .wait (); 13743uint64_t h = 1469598103934665603ull ; 13744const auto * bytes = (const uint8_t * )hash_rows .data (); 13745for (size_t i = 0 ;i < n_floats * sizeof (float );++ i )h = (h ^bytes [i ])* 1099511628211ull ; 13746 std::fprintf (hashes ,"%lld %lld %d %016llx" , (long long )rounds , (long long )p ,T , (unsigned long long )h ); 13747for (int i = 0 ;i < T ;++ i ) std::fprintf (hashes ," %d" , (int )outv [(size_t )i ]); 13748 std::fprintf (hashes ,"\n" ); 13749 } 13750if (!follow .empty ()) {// the continuation stands in for the argmax 13751const size_t k0 = produced .size (); 13752for (int i = 0 ;i < T && k0 + (size_t )i < follow .size ();++ i ) { 13753fdiff [(size_t )i ]= outv [(size_t )i ]!= (int32_t )follow [k0 + (size_t )i ]; 13754outv [(size_t )i ]= (int32_t )follow [k0 + (size_t )i ]; 13755 } 13756 } 13757int a = 0 ; 13758while (a < T - 1 && window [(size_t )a + 1 ]== outv [(size_t )a ])++ a ; 13759if (std::getenv ("STRATA_DBG_DRAFT" )!= nullptr ) {// the window the drafter built and what the target said 13760 std::fprintf (stderr ,"draftdbg: window" );for (int i = 0 ;i < T ;++ i ) std::fprintf (stderr ," %d" , (int )window [(size_t )i ]); 13761 std::fprintf (stderr ," | target" );for (int i = 0 ;i < T ;++ i ) std::fprintf (stderr ," %d" , (int )outv [(size_t )i ]); 13762 std::fprintf (stderr ," | accepted %d\n" ,a ); 13763 } 13764if (first_window ) { 13765first_window = false; 13766ttft_ms = std::chrono::duration < double , std::milli > (Clock ::now ()- t_start ).count (); 13767// Diagnostics: the first window runs the prompt's last token over the state the prompt path left 13768// (keys, values, recurrent state), so its logits carry whatever that path did. A native pack never 13769// runs the per-token loop --dump-logits reads; this is where prompt paths can be compared by output. 13770if (const char * fl = std::getenv ("STRATA_DUMP_FIRST_LOGITS" )) { 13771 std::vector < float > row ((size_t )ver .vocab ()); 13772 std::FILE * f = ver .copy_logits (0 ,row .data ()) ? std::fopen (fl ,"wb" ) :nullptr ; 13773if (f == nullptr || std::fwrite (row .data (),sizeof (float ),row .size (),f )!= row .size ()) 13774 std::fprintf (stderr ,"strata generate: STRATA_DUMP_FIRST_LOGITS: cannot write %s\n" ,fl ); 13775if (f ) std::fclose (f ); 13776 } 13777 } 13778// plan v0.3 P6: the adaptive tier's host work (ranking, copy submission) runs on its own thread while the 13779// GPU commits and drafts; it touches only the residency tables, which nothing reads until the next window 13780 std::thread adapt_thr ; 13781bool adapt_ok = true; 13782if (!drive .d .usage .empty ()&& ((rounds + 1 ) %o .adapt_every )== 0 ) 13783adapt_thr = std::thread ([& ] {adapt_ok = adapt (); }); 13784if (!ver .commit (a + 1 ,err )) { 13785if (adapt_thr .joinable ())adapt_thr .join (); 13786 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 13787return 1 ; 13788 } 13789++ rounds ; 13790drafts_total += T - 1 ; 13791drafts_ok += a ; 13792++ accepted_hist [(size_t )a ]; 13793if (from_sfx ) {++ sfx_windows ;sfx_drafts += T - 1 ;sfx_ok += a ; } 13794if (chain_n > 0 ) {++ chain_windows ;chain_drafts += chain_n ;chain_ok += std::max (0 ,a - (T_mtp - 1 )); } 13795bool eos = false; 13796for (int i = 0 ;i <=a && (int64_t )produced .size ()< max_new && !eos ;++ i ) { 13797produced .push_back (outv [(size_t )i ]); 13798if (sfx_on )sfx .append (outv [(size_t )i ]); 13799if (o .lookup_chain > 0 )extra_sources_append (& outv [(size_t )i ],1 ); 13800eos = o .stop_eos && std::find (o .eos_ids .begin (),o .eos_ids .end (), (int64_t )outv [(size_t )i ])!= o .eos_ids .end (); 13801if (!follow .empty ()) {follow_differ += fdiff [(size_t )i ];++ follow_emitted ; } 13802 } 13803if (eos ) { 13804if (adapt_thr .joinable ())adapt_thr .join (); 13805if (!ver .wait_commit (err )) { std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ());return 1 ; } 13806total_ms += std::chrono::duration < double , std::milli > (Clock ::now ()- t0 ).count (); 13807break ; 13808 } 13809const bool drafted = !draft_on || (int64_t )produced .size () >=max_new || 13810 (use_df2 ? (defer_df2 (a )|| draft_df2 (a )) :mtp .draft (T ,outv .data (),p ,a ,drafts .data (),err ,dprob .data (), (float )o .spec_min_p )); 13811if (adapt_thr .joinable ())adapt_thr .join (); 13812if (!adapt_ok )return 1 ; 13813if (!drafted ) { 13814 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 13815return 1 ; 13816 } 13817x = outv [(size_t )a ]; 13818p += a + 1 ; 13819const double round_ms = std::chrono::duration < double , std::milli > (Clock ::now ()- t0 ).count (); 13820total_ms += round_ms ; 13821if (timed_round && chain_n == 0 )policy .observe (from_sfx ,T ,a ,sfx_match ,round_ms ); 13822else if (timed_round )policy .observe_chain (T_mtp ,chain_n ,a ,cm ,round_ms ); 13823if (rounds %64 == 0 ) 13824 std::fprintf (stderr ,"strata generate: position %lld, %lld tokens, %lld rounds\n" , (long long )p , 13825 (long long )produced .size (), (long long )rounds ); 13826 } 13827// the last commit (set_commit_async) before anything reads the session again 13828if (!ver .wait_commit (err )) { 13829 std::fprintf (stderr ,"strata generate: %s\n" ,err .c_str ()); 13830return 1 ; 13831 } 13832if (hashes != nullptr ) std::fclose (hashes ); 13833 std::printf ("%-24s %lld rounds of %d, drafts accepted %lld of %lld (%.3f), %.2f tokens per round\n" , 13834"speculation" , (long long )rounds ,o .spec , (long long )drafts_ok , (long long )drafts_total , 13835drafts_total > 0 ? (double )drafts_ok / (double )drafts_total :0.0 , 13836rounds > 0 ? (double ) (drafts_ok + rounds ) / (double )rounds :0.0 ); 13837if (!follow .empty ()) 13838 std::printf ("%-24s %lld of %lld emitted tokens differ from the argmax\n" ,"follow" , 13839 (long long )follow_differ , (long long )follow_emitted ); 13840if (o .spec_min_p > 0.0 || o .draft_conf > 0.0 ) { 13841 std::printf ("%-24s" ,"window sizes" ); 13842for (size_t i = 1 ;i < window_hist .size ();++ i ) std::printf (" T%zu:%lld" ,i , (long long )window_hist [i ]); 13843 std::printf (" (min draft probability %.2f)\n" ,o .spec_min_p ); 13844 } 13845if (o .suffix_draft > 0 ) 13846 std::printf ("%-24s %lld windows, drafts accepted %lld of %lld\n" ,"suffix drafts" , (long long )sfx_windows , 13847 (long long )sfx_ok , (long long )sfx_drafts ); 13848if (o .lookup_chain > 0 ) 13849 std::printf ("%-24s %lld windows, chained drafts accepted %lld of %lld\n" ,"lookup chain" , 13850 (long long )chain_windows , (long long )chain_ok , (long long )chain_drafts ); 13851 std::printf ("%-24s" ,"accepted per round" ); 13852for (size_t i = 0 ;i < accepted_hist .size ();++ i ) std::printf (" %zu:%lld" ,i , (long long )accepted_hist [i ]); 13853 std::printf ("\n" ); 13854if (rounds > 0 ) 13855 std::printf ("%-24s wait for rings %.3f pool %.3f host %.3f commit %.3f ms/round; CPU experts %.2f " 13856"distinct / %.2f routed per layer\n" , 13857"verify window" ,ver .ms_wait /rounds ,ver .ms_pool /rounds ,ver .ms_host /rounds , 13858ver .ms_commit /rounds , 13859 (double ) (drive .d .multi_misses - misses0 ) / (double ) (rounds * g .n_layers ), 13860 (double ) (drive .d .multi_entries - entries0 ) / (double ) (rounds * g .n_layers )); 13861if (rounds > 0 ) 13862 std::printf ("%-24s gate/up %.3f quantize %.3f down %.3f ms/round; %.1f GB/s over the rows phases; " 13863"CPU pool call %.3f ms/round\n" ,"pool multi" ,pool .ms_multi_gu /rounds , 13864pool .ms_multi_q /rounds ,pool .ms_multi_down /rounds , 13865 (double )pool .multi_bytes /1e6 / std::max (1e-9 ,pool .ms_multi_gu + pool .ms_multi_down ), 13866 (drive .cpu_ms - pool_ms0 ) /rounds ); 13867if (rounds > 0 ) 13868 std::printf ("%-24s plan %.3f activation quantize %.3f jobs %.3f run %.3f ms/round\n" ,"dispatch" , 13869drive .d .ms_plan /rounds ,drive .d .ms_actq /rounds ,drive .d .ms_jobs /rounds , 13870drive .d .ms_run /rounds ); 13871if (usage_dev != nullptr ) {// STRATA_USAGE_DUMP: the window's routing as make_profile.py reads it (layer, k=1, id, weight) 13872 std::vector < int32_t > uh ((size_t ) (g .n_layers * g .n_expert )); 13873 dpct::get_in_order_queue ().memcpy (uh .data (),usage_dev ,uh .size ()* 4 ).wait (); 13874if (FILE * uf = std::fopen (usage_dump ,"wb" )) { 13875int64_t total = 0 ; 13876for (int64_t l = 0 ;l < g .n_layers ;++ l ) 13877for (int64_t e = 0 ;e < g .n_expert ;++ e ) 13878for (int32_t c = 0 ;c < uh [(size_t ) (l * g .n_expert + e )];++ c ,++ total ) { 13879const int32_t hdr [3 ]= {(int32_t )l ,1 , (int32_t )e }; 13880const float wgt [2 ]= {0.0f ,0.0f }; 13881 std::fwrite (hdr ,4 ,3 ,uf ); 13882 std::fwrite (wgt ,4 ,1 ,uf );// (layer, k) + k ids + k weights: 8 + 8 bytes 13883 } 13884 std::fclose (uf ); 13885 std::printf ("%-24s %s (%lld routed entries counted on the device)\n" ,"usage dumped" ,usage_dump , 13886 (long long )total ); 13887 } 13888 } 13889if (rounds > 0 && !drive .d .usage .empty ()) 13890 std::printf ("%-24s %lld experts swapped into the VRAM tier (every %d rounds, %.3f ms/round)\n" ,"adaptive tier" , 13891 (long long )swaps_total ,o .adapt_every ,ms_adapt /rounds ); 13892if (src .complement_ready ()) 13893 std::printf ("%-24s %.2f GiB of experts in RAM, %lld exchanged with the VRAM tier, %lld blob reads from " 13894"the file\n" ,"resident RAM" , (double )src .resident_bytes () /1073741824.0 , 13895 (long long )src .exchanges (), (long long )src .file_reads ()); 13896// STRATA_CHECK_SWAPS=1 (a test aid): after the run every expert must be held (the GPU cache or the RAM copy), 13897// and every RAM-copy blob must equal the model file's bytes (nothing lost, nothing stale after the swaps) 13898if (src .complement_ready ()) 13899if (const char * chk = std::getenv ("STRATA_CHECK_SWAPS" );chk != nullptr && chk [0 ]!= '\0' && chk [0 ]!= '0' ) { 13900int64_t held_ram = 0 ,held_gpu = 0 ,lost = 0 ,stale = 0 ; 13901 std::vector < uint8_t > ref ; 13902for (int64_t l = 0 ;l < g .n_layers ;++ l ) 13903for (int64_t e = 0 ;e < g .n_expert ;++ e ) { 13904const bool ram = src .has_resident (l ,e ); 13905const bool gpu = host_res [(size_t )l * (size_t )g .n_expert + (size_t )e ] >=0 ; 13906held_ram += ram ; 13907held_gpu += gpu ; 13908if (!ram && !gpu ) {++ lost ;continue ; } 13909if (!ram )continue ; 13910ref .resize ((size_t ) strata::kernels::cpu::expert_layout ().blob_bytes (l )); 13911if (!src .copy_blob_from_file (l ,e ,ref .data ())|| 13912 std::memcmp (ref .data (),src .resident_blob (l ,e ),ref .size ())!= 0 ) { 13913if (stale ++ < 8 ) 13914 std::fprintf (stderr ,"strata: STRATA_CHECK_SWAPS: layer %d expert %d: the RAM copy differs from the file\n" , 13915 (int )l , (int )e ); 13916 } 13917 } 13918 std::printf ("%-24s audit: %lld experts in RAM, %lld in the GPU cache, %lld held by neither, %lld RAM blobs differ from the file\n" , 13919"STRATA_CHECK_SWAPS" , (long long )held_ram , (long long )held_gpu , (long long )lost , (long long )stale ); 13920 } 13921if (srcp == & src ) {// CS-T: the RAM and file tiers (the GPU cache's share is the hit rate above) 13922const double fms = src .file_ms ()- fms0 ,fmb = (double ) (src .file_blob_bytes ()- fbytes0 ) /1e6 ; 13923 std::printf ("%-24s decode: RAM %lld blobs, files %lld blobs, %.1f MB read from the files (%.2f MB/round, " 13924"%.1f ms/round of reading, %.2f GB/s per reading thread)%s; prompt copies %.1f MB\n" , 13925"expert tiers" , (long long ) (src .ram_reads ()- ram0 ), (long long ) (src .file_reads ()- files0 ), 13926fmb ,rounds > 0 ?fmb /rounds :0.0 ,rounds > 0 ?fms /rounds :0.0 , 13927fms > 0 ?fmb /fms :0.0 ,src .gguf_mode () ?" (the GGUF in place)" :"" , 13928 (double ) (fall0 - fbytes0 ) /1e6 ); 13929if (drive .d .lookahead != nullptr ) 13930 std::printf ("%-24s %lld experts warmed, %lld of the file tier's %lld blob reads had been warmed (%.1f%%); " 13931"predictor %.1f ms/round on its thread, %lld layers skipped (still busy)\n" ,"routing prefetch" , 13932 (long long )src .warmed (), (long long )src .warmed_hits (), 13933 (long long ) (src .file_reads ()- files0 ), 13934src .file_reads ()> files0 ?100.0 * (double )src .warmed_hits () / (double ) (src .file_reads ()- files0 ) :0.0 , 13935rounds > 0 ?drive .d .lookahead -> busy_ms () /rounds :0.0 , (long long )drive .d .lookahead -> skipped ()); 13936 } 13937if (rounds > 0 && drive .d .pcie_num > 0 ) 13938 std::printf ("%-24s %.2f distinct experts per layer read over PCIe (share %d/256 of the misses)\n" , 13939"pcie experts" , (double ) (drive .d .pcie_experts - pcie0 ) / (double ) (rounds * g .n_layers ), 13940drive .d .pcie_num ); 13941 (void )pool_ms0 ; 13942if (use_df2 && df2 .rounds > 0 ) 13943 std::printf ("%-24s %.3f ms/round drafting (%lld rounds), %.0f MiB of VRAM\n" ,"dflash2" ,df2 .ms_draft / (double )df2 .rounds , 13944 (long long )df2 .rounds , (double )df2 .vram_bytes () /1048576.0 ); 13945if (use_mtp && rounds > 0 ) 13946 std::printf ("%-24s %.3f ms/round drafting (%lld rounds), MTP prompt %.1f ms, %.0f MiB of VRAM\n" ,"mtp" , 13947mtp .ms_draft / (double )mtp .rounds , (long long )mtp .rounds ,mtp .ms_prefill , 13948 (double )mtp .vram_bytes () /1048576.0 ); 13949 } 13950 13951if (dump != nullptr && std::fclose (dump )!= 0 ) { 13952 std::fprintf (stderr ,"strata generate: cannot finish logits dump\n" ); 13953return 1 ; 13954 } 13955if (layer_dump != nullptr ) { 13956 std::fclose (layer_dump ); 13957 sycl::free (layer_stage , dpct::get_in_order_queue ()); 13958 std::printf ("%-24s %s (%lld layers + the input x %d streams x %lld per position)\n" ,"layers dumped" , 13959o .dump_layers .c_str (), (long long )g .n_layers , (int )g .hc , (long long )g .n_embd ); 13960 } 13961if (half_dump != nullptr ) { 13962 std::fclose (half_dump ); 13963 sycl::free (half_stage , dpct::get_in_order_queue ()); 13964 std::printf ("%-24s %s (%lld layers x %llu per position)\n" ,"halves dumped" ,o .dump_halves .c_str (), 13965 (long long )g .n_layers , (unsigned long long )half_stride ); 13966 } 13967if (routing != nullptr ) { 13968 std::fclose (routing ); 13969drive .routing = nullptr ; 13970 std::printf ("%-24s %s (%lld records of layer, k, ids, weights)\n" ,"routing dumped" , 13971o .dump_routing .c_str (), (long long )drive .calls ); 13972 } 13973if (o .stage_timing ) strata::core::stage_timing_report (g .n_layers ); 13974 13975const int64_t decoded = (int64_t )produced .size (); 13976 std::printf ("prompt :" ); 13977for (int64_t t :o .tokens ) std::printf (" %lld" , (long long )t ); 13978 std::printf ("\noutput :" ); 13979for (int64_t t :produced ) std::printf (" %lld" , (long long )t ); 13980 std::printf ("\n" ); 13981const double decode_ms = decoded > 0 ?total_ms / (double )decoded :0.0 ; 13982 strata::uc_probe ("end-cli" ); 13983 std::printf ("%-24s %lld tokens in %.1f ms -> %.2f tok/s\n" ,"decode" , (long long )decoded ,total_ms , 13984decode_ms > 0.0 ?1000.0 /decode_ms :0.0 ); 13985if (n_prompt > 1 ) 13986 std::printf ("%-24s %lld tokens in %.1f ms -> %.2f tok/s (time to first token %.1f ms)\n" ,"prefill" , 13987 (long long ) (n_prompt - 1 ),prefill_ms , 13988prefill_ms > 0 ?1000.0 * (double ) (n_prompt - 1 ) /prefill_ms :0.0 ,ttft_ms ); 13989if (!o .dump_mixed .empty ()) { 13990 std::vector < float > mx ((size_t )g .n_embd ); 13991if (DPCT_CHECK_ERROR (dpct::get_in_order_queue () 13992 .memcpy (mx .data (),ss .block .mixed , 13993mx .size ()* sizeof (float )) 13994 .wait ())!= 0 ) { 13995 std::fprintf (stderr ,"strata generate: reading mixed back failed\n" ); 13996return 1 ; 13997 } 13998 std::FILE * mf = std::fopen (o .dump_mixed .c_str (),"wb" ); 13999if (mf == nullptr ) { 14000 std::fprintf (stderr ,"strata generate: cannot write %s\n" ,o .dump_mixed .c_str ()); 14001return 1 ; 14002 } 14003 std::fwrite (mx .data (),sizeof (float ),mx .size (),mf ); 14004 std::fclose (mf ); 14005double s2 = 0 ,mag = 0 ; 14006for (float v :mx ) {s2 += (double )v * (double )v ;mag += std::fabs ((double )v ); } 14007 std::printf ("%-24s %s (n_embd %lld, rms %.5g, mean|.| %.5g)\n" ,"mixed dumped" ,o .dump_mixed .c_str (), 14008 (long long )g .n_embd , std::sqrt (s2 / (double )mx .size ()),mag / (double )mx .size ()); 14009 } 14010 14011// ---- the residual, for bisecting the head against the layers (see `dump_residual`'s note) 14012if (!o .dump_residual .empty ()) { 14013 std::vector < float > R ((size_t )g .hc * g .n_embd ); 14014if (DPCT_CHECK_ERROR ( 14015 dpct::get_in_order_queue () 14016 .memcpy (R .data (),ss .R ,R .size ()* sizeof (float )) 14017 .wait ())!= 0 ) { 14018 std::fprintf (stderr ,"strata generate: reading R back failed\n" ); 14019return 1 ; 14020 } 14021 std::FILE * rf = std::fopen (o .dump_residual .c_str (),"wb" ); 14022if (rf == nullptr ) { 14023 std::fprintf (stderr ,"strata generate: cannot write %s\n" ,o .dump_residual .c_str ()); 14024return 1 ; 14025 } 14026const int32_t hdr [2 ]= {(int32_t )g .hc , (int32_t )g .n_embd }; 14027 std::fwrite (hdr ,sizeof hdr ,1 ,rf ); 14028 std::fwrite (R .data (),sizeof (float ),R .size (),rf ); 14029 std::fclose (rf ); 14030double mag = 0 ,mx = 0 ; 14031int bad = 0 ; 14032for (float v :R ) { 14033if (!std::isfinite (v ))++ bad ; 14034else {mag += std::fabs ((double )v );mx = std::max (mx , (double ) std::fabs ((double )v )); } 14035 } 14036 std::printf ("%-24s %s (%d x %lld, nonfinite %d, mean|.| %.4g, max|.| %.4g)\n" ,"residual dumped" , 14037o .dump_residual .c_str (), (int )g .hc , (long long )g .n_embd ,bad ,mag / (double )R .size (),mx ); 14038 } 14039 14040if (o .stats ) { 14041 std::printf ("%-24s %.3f ms/token (WALL CLOCK: embed, layers, head, sample)\n" ," per token" ,decode_ms ); 14042// **THE PER-TOKEN HOST TERM, WHICH `--gpu-only-full` CANNOT SEE.** That measurement never enters the 14043// token loop, so it excludes all six of these. On the 78-token fixture + 200 generated tokens the six 14044// sum to ~9 ms of non-layer work against ~1.5 ms of actual head GPU work - 16% of the token, and it is 14045// not the pool. 14046if (phase_tokens > 0 ) { 14047const double pt = (double )phase_tokens ; 14048 std::printf ("%-24s PLE %.3f embed %.3f LAYERS %.3f head %.3f readback %.3f sample %.3f " 14049"(sum %.3f of %.3f ms)\n" , 14050" token host phases" ,ms_ple /pt ,ms_embed /pt ,ms_layers /pt ,ms_head /pt , 14051ms_readback /pt ,ms_sample /pt , 14052 (ms_ple + ms_embed + ms_layers + ms_head + ms_readback + ms_sample ) /pt ,decode_ms ); 14053 } 14054if (const std::string io = ple_table .io_report (); !io .empty ()) std::printf (" %s\n" ,io .c_str ()); 14055// **THE DENOMINATOR IS THE POSITIONS THE POOL ACTUALLY RAN ON, NOT THE DECODED TOKENS (A6).** 14056// `drive_pool` is called once per layer per position and PREFILL runs the loop too, so accumulating 14057// `cpu_ms` over prefill and then dividing by `decoded` inflates this figure. `drive.calls / n_layers` 14058// is the number of positions - the same correction the ring counters below already received, which is 14059// why they print "of 192" rather than "240 of 192". 14060const double pool_positions = g .n_layers > 0 ? (double )drive .calls / (double )g .n_layers :0.0 ; 14061 std::printf ("%-24s %.3f ms/token over %lld layers (%.0f positions, %lld dispatches)\n" , 14062" the CPU expert pool" ,pool_positions > 0.0 ?drive .cpu_ms /pool_positions :0.0 , 14063 (long long )g .n_layers ,pool_positions , (long long )drive .calls ); 14064// **AND WHERE INSIDE `run()` IT WENT.** Three phases per layer and they were one number, which cannot 14065// tell a pool that is slow at the WORK from one that is slow at the SYNCHRONISATION - opposite fixes. 14066// Wait-for-park is expected to be ~0 (the workers re-parked at the end of the previous layer); the 14067// question is whether the time is in the drain or in the re-park barrier. 14068if (pool_positions > 0.0 ) { 14069double wp = 0 ,dr = 0 ,rp = 0 ; 14070pool .phase_ms (wp ,dr ,rp ); 14071const double per = pool_positions ; 14072 std::printf ("%-24s wait-park %.3f drain %.3f re-park %.3f ms/token\n" , 14073" pool phases" ,wp /per ,dr /per ,rp /per ); 14074 } 14075 std::printf ("%-24s %lld blobs read\n" ," expert blobs" , (long long )srcp -> reads ()); 14076for (int r = 0 ;r < 3 ;++ r )if (o .expert_cache_remote [(size_t )r ]> 0 ) 14077 std::printf (" CUDA%d experts %lld routed entries computed\n" , 14078r + 1 , (long long )remote_experts [(size_t )r ].computed ()); 14079// ---- **R4's DISPATCH MEASUREMENT: h, ON THE ENGINE'S OWN ROUTING.** No offline trace, no corpus 14080// question, no k-fold - these are the ids the router actually produced on this run. Reported as 14081// hits/lookups so it can be read directly as the h the cache would deliver, and alongside `refused` 14082// so a full cache is visible rather than silently capping the rate. 14083if (o .expert_cache > 0 ) { 14084const int64_t look = drive .d .cache_hits + drive .d .cache_admitted + drive .d .cache_refused ; 14085const int64_t hl = drive .d .hit_ready + drive .d .hit_late ; 14086 std::printf ("%-24s %lld of %lld layers the hit work was DONE when the pool returned\n" , 14087" R4 overlap" , (long long )drive .d .hit_ready , (long long )hl ); 14088 std::printf ("%-24s %lld of %lld = %.4f (%lld admitted, %lld refused, cache %.4f%% full)\n" , 14089" R4 expert-cache hits" , (long long )drive .d .cache_hits , (long long )look , 14090look > 0 ? (double )drive .d .cache_hits / (double )look :0.0 , 14091 (long long )drive .d .cache_admitted , (long long )drive .d .cache_refused , 14092100.0 * (double ) (drive .d .cache_admitted + drive .d .cache_hits > 0 14093 ? (double )xcache .resident () / (double )xcache .slots () 14094 :0.0 )); 14095 } 14096if (kvg .on ) 14097 std::printf ("%-24s %lld cells in VRAM, %lld grows, %lld trims, %lld experts given up, %lld refilled\n" , 14098" elastic K/V" , (long long )kvg .cells , (long long )kvg .grows , (long long )kvg .trims , 14099 (long long )kvg .evicted , (long long )kvg .refilled ); 14100if (tgraph .captured && tgraph .calls > 0 ) { 14101const double per = (double )tgraph .calls ; 14102 std::printf ("%-24s wait for rings %.3f pool %.3f ms/token (%lld flushes over %lld positions)\n" , 14103" token graph" ,tgraph .ms_wait /per ,tgraph .ms_pool /per , (long long )tgraph .flushes , 14104 (long long )tgraph .calls ); 14105 } 14106if (gr .captured && gr .calls_total > 0 ) { 14107// The counters are CUMULATIVE over every `session_loop` call, and PREFILL runs the loop too - so 14108// the denominator is the number of positions, not the number of generated tokens. Dividing by 14109// `n_layers * decoded` printed "240 of 192", which is a reporting bug that looks like a ring 14110// firing more often than it should. 14111const int64_t positions = gr .calls_total ; 14112 std::printf ("%-24s %lld of %lld over %lld positions\n" ," rings seen MID-GRAPH" , 14113 (long long )gr .rings_mid_graph , (long long ) (g .n_layers * positions ), 14114 (long long )positions ); 14115 std::printf ("%-24s %.3f ms of a %.3f ms layer\n" ," ring latency" , 14116gr .ms_to_ring / (double ) (g .n_layers * positions ),decode_ms / (double )g .n_layers ); 14117// **THE ROUND TRIP, SPLIT AT THE RING.** `ring latency` is the first half and stops when the ring 14118// is seen; this is the second half - the driver calls after it, during which the GPU is IDLE 14119// because `post[l]` has not been launched yet. `--no-pool` is the arm that isolates it: 38.73 14120// ms/token against a 26.32 ms pure-GPU floor is 12.4 ms of round trip with no expert work at all. 14121// 14122// Same denominator as the pool line above (the positions the loop actually ran on), so the two can 14123// be added without one of them being inflated by prefill. 14124const double perlap = (double ) (g .n_layers * positions ); 14125 std::printf ("%-24s %.3f ms/token over %.0f positions (%.3f ms/layer, after the ring)\n" , 14126" host after ring" ,pool_positions > 0.0 ?gr .ms_host /pool_positions :0.0 , 14127pool_positions ,gr .ms_host /perlap ); 14128 } 14129 } 14130 14131if (dump != nullptr ) std::printf ("%-24s %s\n" ,"logits dumped" ,o .dump_logits .c_str ()); 14132 14133 strata::core::session_graphs_free (gr ); 14134 strata::core::doorbell_free (db ); 14135 sycl::free (d_next , dpct::get_in_order_queue ()); 14136 sycl::free (d_logits , dpct::get_in_order_queue ()); 14137 sycl::free (d_emb , dpct::get_in_order_queue ()); 14138 sycl::free (d_parts , dpct::get_in_order_queue ()); 14139 sycl::free (sbuf , dpct::get_in_order_queue ()); 14140 sycl::free (arena , dpct::get_in_order_queue ()); 14141return 0 ; 14142} 14143catch (sycl::exception const & exc ) { 14144const std::string what = exc .what (); 14145if (exc .code ()== sycl::errc::memory_allocation || what .find ("OUT_OF_DEVICE_MEMORY" )!= std::string::npos ) { 14146// the one plain refusal for a start no sizing could fit (the sizing above already shrank the prompt chunk, the reserve and the resident K/V window) 14147 std::cerr <<"strata: this card does not have the memory for this start: the GPU ran out of memory while the engine was loading (" <<what <<"). Lower the number of " 14148"requests at once (--batch / parallel), use --kv q4_0 (a smaller K/V), turn off the draft layer, or close other programs that use the GPU" << std::endl ; 14149 std::exit (1 ); 14150 } 14151 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 14152 <<", line:" <<__LINE__ << std::endl ; 14153 std::exit (1 ); 14154}