okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-sycl-prs e106b4c86 into the batch 16 candidate (SYCL pull requests 4185 and 3153)a8a51b280

main
901.0 KiB14154 linesraw
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() {
142    static const bool enabled = [] {
143        const char* v = std::getenv("STRATA_SYCL_MIRROR_ADAPT");
144        return v && v[0] == '1';
145    }();
146    return 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
154    return true;
155#else
156    static const bool dxg = std::filesystem::exists("/dev/dxg");
157    return 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    /*
164    DPCT1010: SYCL uses exceptions to report errors and does not use the
165    error codes. The cudaGetLastError function call was replaced with 0. You
166    need to rewrite this code.
167    */
168    (void)0;
169    size_t free_b = 0, total_b = 0;
170    /*
171    DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions for
172    device information which may not be supported by all compilers or runtimes.
173    You may need to adjust the code.
174    */
175    if (DPCT_CHECK_ERROR(
176            dpct::get_current_device().get_memory_info(free_b, total_b)) != 0) {
177        /*
178        DPCT1010: SYCL uses exceptions to report errors and does not use
179        the error codes. The cudaGetLastError function call was replaced with 0.
180        You need to rewrite this code.
181        */
182        (void)0;
183        return {};
184    }
185    char 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));
188    return 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)
208    static const bool on = std::getenv("STRATA_ARENA_MMAP") && std::getenv("STRATA_ARENA_MMAP")[0] == '1';
209    return on;
210#else
211    return 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)
222    static const bool kernel = [] {
223        const char* e = std::getenv("STRATA_HIP_ADAPT_KERNEL_COPY");
224        const bool on = e != nullptr && e[0] == '1';
225        if (on) std::fprintf(stderr, "strata: STRATA_HIP_ADAPT_KERNEL_COPY=1: adaptive swaps copy with a kernel, not SDMA (#884)\n");
226        return on;
227    }();
228    if (kernel && bytes % 16 == 0 && ((uintptr_t) src & 15) == 0 && ((uintptr_t) dst & 15) == 0) {
229        void* dsrc = nullptr;
230        if (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);
232            return cudaGetLastError();
233        }
234        (void) cudaGetLastError();   // not registered / not mapped: the ordinary copy
235    }
236#endif
237    /*
238    DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While
239    the origin API might be synchronous, it depends on the type of operand
240    memory, so you may need to call wait() on event return by memcpy API to
241    ensure synchronization behavior.
242    */
243    return 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) {
251    int 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)
253    if (!pin_blobs_on() || r.empty()) return 0;
254    for (auto& [a, e] : r) { a &= ~(uintptr_t) 4095; e = (e + 4095) & ~(uintptr_t) 4095; }
255    std::sort(r.begin(), r.end());
256    size_t k = 0;
257    for (size_t i = 1; i < r.size(); ++i) {
258        if (r[i].first <= r[k].second) r[k].second = std::max(r[k].second, r[i].second);
259        else r[++k] = r[i];
260    }
261    r.resize(k + 1);
262    for (const auto& [a, e] : r) {
263        if (cudaHostRegister((void*) a, (size_t) (e - a), cudaHostRegisterReadOnly | cudaHostRegisterPortable) ==
264            cudaSuccess)
265            live.push_back((void*) a);
266        else {
267            (void) cudaGetLastError();
268            ++failed;
269        }
270    }
271#else
272    (void) r; (void) live;
273#endif
274    return failed;
275}
276void unpin_blobs(std::vector<void*>& v) {
277    /*
278    DPCT1027: The call to cudaHostUnregister was replaced with 0 because
279    SYCL currently does not support registering of existing host memory for use
280    by device. Use USM to allocate memory for use by host and device.
281    */
282    for (void *p : v)(void) 0;
283    /*
284    DPCT1010: SYCL uses exceptions to report errors and does not use the
285    error codes. The cudaGetLastError function call was replaced with 0. You
286    need to rewrite this code.
287    */
288    (void)0;
289    v.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) {
294    static const bool on = std::getenv("STRATA_RSS_TRACE") != nullptr;
295    if (!on) return;
296    FILE* f = std::fopen("/proc/self/status", "r");
297    if (!f) return;
298    char line[256];
299    long long kb = -1;
300    while (std::fgets(line, sizeof line, f))
301        if (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() {
308    static const bool v = std::getenv("STRATA_REFILL_BLOCKING") != nullptr;
309    return 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) {
320    if (!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());
322    else
323        std::fprintf(stderr, "%s: %s\n", who, err.c_str());
324}
325
326static const char* pipe_dbg_env(const char* name) {
327    static const bool on = [] { const char* v = std::getenv("STRATA_PIPELINE_DEBUG"); return v != nullptr && v[0] != 0 && v[0] != '0'; }();
328    return 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;
346    int dev;
347};
348template <class Swap, class Locate>
349bool resident_stage_swaps(strata::core::FileExpertSource &src,
350                          const std::vector<int32_t> &host_res,
351                          int64_t n_expert, std::vector<Swap> &swaps,
352                          Locate locate) try {
353    if (!src.complement_ready() || swaps.empty()) return true;
354    struct Staged { int32_t layer, in, out; int64_t q; };
355    std::vector<Staged> staged;
356    std::vector<SwapHome> used;
357    std::vector<Swap> kept;
358    kept.reserve(swaps.size());
359    for (const Swap& s : swaps) {
360        if (!src.has_resident(s.layer, s.in) || src.has_resident(s.layer, s.out)) { kept.push_back(s); continue; }
361        const int64_t q = (int64_t) staged.size();
362        if (q >= src.exchange_capacity()) continue;
363        const int32_t slot = host_res[(size_t) s.layer * (size_t) n_expert + (size_t) s.out];
364        if (slot < 0) continue;
365        const SwapHome home = locate(s.layer);
366        const 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)
369        try {
370            home.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());
375            return false;
376        }
377        bool seen = false;
378        for (const SwapHome& u : used) seen = seen || u.stream == home.stream;
379        if (!seen) used.push_back(home);
380        staged.push_back({s.layer, s.in, s.out, q});
381        kept.push_back(s);
382    }
383    if (!staged.empty()) {
384        for (const SwapHome& u : used) {
385            const strata::core::OnDevice on(u.dev);
386            try {
387                u.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());
390                return false;
391            }
392        }
393        // STRATA_CHECK_SWAPS=1 (a test aid): each evicted expert's exchange buffer must hold the model file's bytes
394        if (const char* chk = std::getenv("STRATA_CHECK_SWAPS"); chk != nullptr && chk[0] != '\0' && chk[0] != '0') {
395            static std::atomic<int64_t> n_ok{0}, n_bad{0};
396            std::vector<uint8_t> ref;
397            int64_t bad = 0;
398            for (const Staged& x : staged) {
399                ref.resize((size_t) strata::kernels::cpu::expert_layout().blob_bytes(x.layer));
400                if (!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            }
409            n_bad += bad;
410            std::fprintf(stderr, "strata: STRATA_CHECK_SWAPS: %zu staged, %lld differ (total %lld ok, %lld differ)\n",
411                         staged.size(), (long long) bad, (long long) n_ok.load(), (long long) n_bad.load());
412        }
413        for (const Staged& x : staged)
414            if (!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);
417                return false;
418            }
419    }
420    swaps.swap(kept);
421    return 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
432    int64_t max_new = 16;
433    int64_t max_context = 4096;
434    bool greedy = true;
435    uint64_t seed = 0;
436    int top_k = 20;
437    float top_p = 0.95f;
438    float temperature = 1.0f;
439    std::string dump_logits;          // one line of logits per generated position
440    int64_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
448    bool no_ple = false;              // explicit diagnostic ablation; never a normal inference default
449    bool stream_token = false;        // R2.6 experiment: ordered work on the session stream
450    bool check_logits = false;        // optional full-vocabulary finite scan
451    bool gr_fp32_activations = false;  // pinned CUDA single-token BF16 activation contract
452    bool gr_native_mmvf = false;       // pinned projection reduction tree as well as FP32 inputs
453    bool native_bf16 = false;          // SSM gates, router and indexer projections only
454    bool native_bf16_extra = false;    // PLE value and shared expert scalar gate
455    bool native_ple_key = false;       // unchanged Q2_0 key and CUDA Q8_1 activations
456    bool native_moe_combine = false;   // pinned fused CUDA weighted reduction
457    bool native_gdn = false;          // pinned CUDA recurrence and preprocessing
458    bool native_flash_attn_short = false; // diagnostic pinned attention, context <=256
459    bool native_qsa_indexer = false;  // pinned F16 key cache and F32 pooling
460    bool 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
467    double rope_scale = 0;              ///< --rope-scale F: the extension factor; 0 = the flag is absent (the model file's, else 1 = off)
468    double rope_freq_base = 0;          ///< --rope-freq-base N: 0 = the model's (1e7)
469    double rope_freq_scale = 0;         ///< --rope-freq-scale F: the raw ggml knob; 0 = 1/--rope-scale
470    double yarn_orig_ctx = 0;           ///< --yarn-orig-ctx N: 0 = the model's, else 262144
471    double yarn_ext_factor = -1.0;      ///< --yarn-ext-factor F: <0 = auto (1 for yarn, 0 otherwise)
472    double yarn_attn_factor = 1.0;      ///< --yarn-attn-factor F
473    double yarn_beta_fast = 32.0;       ///< --yarn-beta-fast F
474    double yarn_beta_slow = 1.0;        ///< --yarn-beta-slow F
475    bool native_rope = false;         // pinned text-only CUDA rotary arithmetic
476    bool native_ple_postops = false;  // pinned PLE postprojection arithmetic
477    bool native_router = false;       // pinned fused 512-expert top-10 router
478    bool 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";
492    bool ple_io_explicit = false;      ///< --ple-io was given: the engine only warns when direct measures slow
493    int64_t ple_row_cache = 1 << 20;   ///< bounded row cache (rows of 90 B); 0 disables
494    int ple_inflight = 256;   // the prompt path reads a chunk's rows at once: 64 left the SSD half idle (32K: 303 -> 189 ms)
495    double ple_delay_us = 0;           ///< fault injection: every row read completes no earlier than this
496    bool 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)
498    int64_t kv_resident = 0;           ///< KV streaming: resident cells per QSA layer (0: all in VRAM)
499    bool 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;
518    bool no_capture = false;          // run the layers directly instead of replaying graphs
519    bool no_pool = false;             // skip the CPU expert pool: the GPU-only floor
520    bool 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.
523    bool 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.
527    bool graph_only = false;
528    bool gpu_only_full = false;   ///< R0.3: pre + post + head, the true per-token GPU floor
529    int 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.
539    bool no_host_worker = false;
540    bool coupled_draft = strata::core::coupled_draft_env(); ///< Coupled draft sampling for MTP drafter under sampling
541    bool 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
543    bool resident_cpu_experts = false; ///< mmap-backed static-cache misses copied into ordinary RAM
544    bool 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.
548    bool resident_pin = false;
549    uint64_t resident_headroom = 8ull << 30;
550    bool resident_soft = false;
551    bool 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).
555    uint64_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`.
564    int 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{};
567    bool 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
569    bool 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.
575    bool 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).
579    int peer_device = -1;
580    int peer_reserve_mib = 600;
581    int64_t peer_slots = 0;
582    int 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
585    int64_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`.
588    bool 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;
598    double 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`.
602    bool 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.
605    bool gpu_stages = false;
606    bool stats = false;
607    bool shared_late = false;          ///< plan v0.3 P3 A/B: shared expert inside post[l] (old order)
608    bool keep_canonical = false;       ///< plan v0.3 P1 A/B: load canonical copies of natively served tensors
609    bool no_token_graph = false;       ///< plan v0.3 P3 A/B: two graphs per layer instead of one per token
610    bool no_fused_gr = false;          ///< plan v0.3 P3 A/B: the six-kernel native gr_read + separate gr_write
611    bool no_fast_attn = false;         ///< plan v0.3 P3 A/B: gather + one-block-per-head QSA attention
612    bool no_publish_kernel = false;    ///< plan v0.3 P3 A/B: memcpy nodes for the doorbell and QSA step
613    bool no_fused_gdn = false;         ///< plan v0.3 P3 A/B: llama.cpp-layout GDN step + separate out norm
614    bool 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.
617    int vram_reserve_mib = 700;
618    bool 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.
621    bool vram_elastic = false;
622    int64_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.
625    int vram_reserve_later_mib = -1;
626    /// Plan v0.3 P5: batched prompt processing in chunks of this many tokens (0 = the token path).
627    int64_t prefill_chunk = 0;
628    /// `--prefill N` (a number, not auto): the person's chunk, which the cache sizing leaves alone.
629    bool 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).
632    bool 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
635    int64_t prefill_auto_max = 8192;
636    bool 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.
639    bool 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.
643    int64_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.
650    int 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> ...`).
654    int 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)
657    bool 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.
662    int batch_groups = 0;
663    bool batch_mtp = false;      ///< --batch-mtp / STRATA_BATCH_MTP=1 (opt-in): one MTP proposal per batch slot
664    std::string spec_oracle;
665    int 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;
674    int64_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).
677    double pcie_frac = -1.0;   ///< < 0: the model's default (0.2 direct for the Q2_0 pack, 0.55 DMA for native packs)
678    bool pcie_frac_auto = false;     ///< STRATA_PCIE_FRAC_DEFAULT=auto, single card, no --pcie-frac: the share is refined in the first decode windows (PcieAuto)
679    double 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.
683    int adapt_every = 4;
684    float 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.
688    int 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.
691    double spec_min_p = 0.0;
692    /// Stop when the model emits an end-of-turn token (<|endoftext|> 248044, <|im_end|> 248046, or --eos-ids).
693    bool stop_eos = false;
694    std::vector<int64_t> eos_ids = {248044, 248046};
695    bool 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)
705    bool split_skip_if_fits = false;
706    /// Plan v0.3 P8: stay resident and take requests on stdin (see the --serve block in main).
707    bool serve = false;
708    /// The vision path: keep a per-cell (t, h, w) rotary position table so --serve can take GENI requests.
709    bool vision = false;
710    int 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.
714    int prompt_cache = 6;
715    int64_t conversation_cache_mib = 0; // opt-in host RAM for independent conversations
716    int conversation_cache_slots = 4;
717    int64_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)
719    int64_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)
721    int64_t prompt_cache_every = 16384;
722    bool 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)
725    int64_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.
728    int64_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).
733    int64_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)
737    int64_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.
743    int 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.
748    int 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.
750    int 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.
754    int lookup_chain = 0;
755    int 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).
758    bool 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";
767    double 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
768    int 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;
773    int cvec_first = -1, cvec_last = -1;   ///< llama.cpp's defaults: 1 .. the last layer
774    int cvec_mode = 1;                     ///< 0 = project, 1 = add (llama.cpp's default)
775    int 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) {
1009    const std::vector<int32_t>& h = sfx.history();
1010    const int keep = std::max(0, std::min((int) h.size(), 64 - n_pending));
1011    tail.assign(h.end() - keep, h.end());
1012    tail.insert(tail.end(), pending, pending + n_pending);
1013    return (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() {
1018    for (auto& src : strata::spec::extra_draft_sources()) src->reset();
1019}
1020void extra_sources_append(const int32_t* t, size_t n) {
1021    for (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) {
1025    out.clear();
1026    std::string text(s);
1027    for (char& c : text) if (c == ',') c = ' ';
1028    std::istringstream input(text);
1029    std::string token;
1030    while (input >> token) {
1031        int32_t id = 0;
1032        const auto parsed = std::from_chars(token.data(), token.data() + token.size(), id);
1033        if (parsed.ec != std::errc{} || parsed.ptr != token.data() + token.size() || id < 0) {
1034            err = "invalid token id: expected an integer in [0, 2147483647]";
1035            out.clear();
1036            return false;
1037        }
1038        out.push_back(id);
1039    }
1040    if (out.empty()) { err = "token list was empty"; return false; }
1041    return 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;
1047    double cpu_ms = 0;
1048    int64_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,
1057                float* out) {
1058    Drive* t = (Drive*) user;
1059    const Clock::time_point a = Clock::now();
1060    strata::core::expert_pool_dispatch(&t->d, x_f, ids, weights, n_embd, k, out);
1061    t->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.
1066    if (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.
1073        const int32_t layer_idx = (int32_t) (t->d.layers - 1);
1074        if (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);
1076            return;
1077        }
1078        const 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,
1087                      int64_t layer) {
1088    Drive* t = (Drive*) user;
1089    t->d.layers = layer;
1090    const Clock::time_point a = Clock::now();
1091    strata::core::expert_pool_dispatch_multi(t->d, x_f, ids, n_tok, k, out);
1092    t->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.
1098    if (t->routing != nullptr && layer >= 0 && layer < strata::core::kCompiledGeometry.n_layers) {
1099        for (int64_t tok = 0; tok < n_tok; ++tok) {
1100            const 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);
1103            static 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 {
1112    static constexpr int kMax = 8;
1113    Drive* base = nullptr;
1114    int n = 0;                                    ///< stages
1115    int64_t end[kMax] = {};                       ///< stage i runs the layers from end[i - 1] (0) below end[i]
1116    strata::core::GpuPlanSink* plan[kMax] = {};
1117    const uint8_t* cache_base[kMax] = {};
1118    const uint64_t* cache_slot_off[kMax] = {};
1119    int 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,
1122                      int64_t layer) {
1123    SplitDrive* s = (SplitDrive*) user;
1124    int st = 0;
1125    while (st + 1 < s->n && layer >= s->end[st]) ++st;
1126    Drive& d = *s->base;
1127    d.d.plan = s->plan[st];
1128    d.d.cache_base = s->cache_base[st];
1129    d.d.cache_slot_off = s->cache_slot_off[st];
1130    d.d.pcie_num = s->pcie_num[st];
1131    drive_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 {
1138    int dev = 0;
1139    int64_t lb = 0, le = 0;
1140    double 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
1148    int32_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;
1154    bool adapt_live = false;                             ///< swaps of this request are in flight on it
1155    int32_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 {
1160    unsigned long long faults = 0, rss_mib = 0, avail_mib = 0, commit_mib = 0;   // faults: hard (Linux) / all (Windows)
1161};
1162MemSample mem_sample() {
1163    MemSample m;
1164#if defined(_WIN32)
1165    PROCESS_MEMORY_COUNTERS pmc{};
1166    if (K32GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc)) {
1167        m.faults = pmc.PageFaultCount;
1168        m.rss_mib = pmc.WorkingSetSize >> 20;
1169        m.commit_mib = pmc.PagefileUsage >> 20;
1170    }
1171    MEMORYSTATUSEX ms{};
1172    ms.dwLength = sizeof ms;
1173    if (GlobalMemoryStatusEx(&ms)) m.avail_mib = ms.ullAvailPhys >> 20;
1174#else
1175    if (std::FILE* f = std::fopen("/proc/self/stat", "r")) {
1176        char buf[4096];
1177        const size_t n = std::fread(buf, 1, sizeof buf - 1, f);
1178        buf[n] = 0;
1179        std::fclose(f);
1180        const char* s = std::strrchr(buf, ')');   // fields after the command name: 3 state ... 12 majflt
1181        for (int field = 2; s && field < 12; ++field) s = std::strchr(s + 1, ' ');
1182        if (s) m.faults = std::strtoull(s + 1, nullptr, 10);
1183    }
1184    auto kb = [](const char* path, const char* key) -> unsigned long long {
1185        unsigned long long v = 0;
1186        if (std::FILE* f = std::fopen(path, "r")) {
1187            char line[256];
1188            const size_t kl = std::strlen(key);
1189            while (std::fgets(line, sizeof line, f))
1190                if (std::strncmp(line, key, kl) == 0) { v = std::strtoull(line + kl, nullptr, 10); break; }
1191            std::fclose(f);
1192        }
1193        return v;
1194    };
1195    m.rss_mib = kb("/proc/self/status", "VmRSS:") >> 10;
1196    m.commit_mib = kb("/proc/self/status", "VmSwap:") >> 10;
1197    m.avail_mib = kb("/proc/meminfo", "MemAvailable:") >> 10;
1198#endif
1199    return 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() {
1204    const strata::core::Progress& p = strata::core::progress();
1205    std::string s = std::string(p.where.load()) + " " + std::to_string((long long) p.detail.load());
1206    if (const int64_t c = p.chunk.load(); c >= 0) s += " of the prompt chunk from token " + std::to_string((long long) c);
1207    return 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) {
1213    struct stat st{};
1214    if (::stat(path.c_str(), &st) != 0) return -1;
1215    char 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);
1219    for (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");
1221        int r = -1;
1222        if (q >> r) {
1223            dev = p.filename().string();
1224            return r;
1225        }
1226    }
1227    return -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;
1234    int waiting = 0, threads = 0;
1235    std::error_code ec;
1236    for (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);
1241        const size_t rp = line.rfind(')');
1242        if (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    }
1249    if (threads == 0) return;
1250    std::string list;
1251    for (const auto& [name, n] : where) list += (list.empty() ? " (" : ", ") + name + " x" + std::to_string(n);
1252    if (!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(),
1254                 waiting > 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) {
1267    PlDiag& d = g_pl_diag;
1268    auto 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' : '-',
1270                      b & 16 ? 'S' : '-', b & 32 ? 'V' : '-');
1271        return (const char*) o;
1272    };
1273    char 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(),
1276                 bits(d.a_bits.load(), ba), bits(d.b_bits.load(), bb), bits(d.d_bits.load(), bd), d.chain_kind.load(),
1277                 d.chain_live.load(), d.doomed.load(), d.ending.load());
1278    const char* names[2][2] = {{"stage 0 even", "stage 0 odd"}, {"stage 1 even", "stage 1 odd"}};
1279    for (int st = 0; st < 2; ++st)
1280        for (int par = 0; par < 2; ++par)
1281            if (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);
1290    for (int pass = 0; pass < 2; ++pass) {
1291        if (pass == 1) {
1292            std::this_thread::sleep_for(std::chrono::seconds(2));
1293            std::fprintf(f, "  2 s later:\n");
1294        }
1295        if (auto fn = strata::core::diag_pool_fn().load()) fn(f);
1296        if (auto fn = strata::core::diag_verify_fn().load()) fn(f);
1297        if (auto fn = strata::core::diag_pipeline_fn().load()) fn(f);
1298#if !defined(_WIN32)
1299        disk_wait_threads(f);
1300#endif
1301        const 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,
1303                     m.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
1314    if (HMODULE dbg = LoadLibraryA("dbghelp.dll")) {
1315        using Fn = BOOL(WINAPI*)(HANDLE, DWORD, HANDLE, int, void*, void*, void*);
1316        if (auto write = (Fn) GetProcAddress(dbg, "MiniDumpWriteDump")) {
1317            char path[64];
1318            std::snprintf(path, sizeof path, "strata-stall-%lu.dmp", (unsigned long) GetCurrentProcessId());
1319            HANDLE h = CreateFileA(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
1320            if (h != INVALID_HANDLE_VALUE) {
1321                const int kThreadInfo = 0x1000;   // MiniDumpWithThreadInfo; MiniDumpNormal = 0
1322                const BOOL ok = write(GetCurrentProcess(), GetCurrentProcessId(), h, kThreadInfo, nullptr, nullptr, nullptr);
1323                CloseHandle(h);
1324                char full[MAX_PATH];
1325                if (!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",
1327                             full);
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) {
1336    static const bool on = std::getenv("STRATA_TRACE") != nullptr;
1337    if (!on) return;
1338    size_t free_b = 0, total_b = 0;
1339    /*
1340    DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions for
1341    device information which may not be supported by all compilers or runtimes.
1342    You 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() {
1350    static const bool v = [] { const char* e = std::getenv("STRATA_ADAPT_NOWAIT"); return e && e[0] == '1'; }();
1351    return 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() {
1360    static const int v = [] { const char* e = std::getenv("STRATA_ADAPT_LAG"); return e ? std::max(1, std::atoi(e)) : 1; }();
1361    return 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:
1368    JobThread() : th_([this] { loop(); }) {}
1369    ~JobThread() {
1370        { std::lock_guard<std::mutex> lk(mu_); quit_ = true; }
1371        cv_.notify_one();
1372        th_.join();
1373    }
1374    JobThread(const JobThread&) = delete;
1375    JobThread& operator=(const JobThread&) = delete;
1376    void post(std::function<void()> f) {
1377        {
1378            std::lock_guard<std::mutex> lk(mu_);
1379            job_ = std::move(f);
1380            has_ = true;
1381            done_.store(false, std::memory_order_release);
1382        }
1383        cv_.notify_one();
1384    }
1385    bool idle() const { return done_.load(std::memory_order_acquire); }
1386    void 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.
1390    static int smt_spare_cpu() {
1391#if defined(_WIN32)
1392        DWORD len = 0;
1393        GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &len);
1394        if (len == 0) return -1;
1395        std::vector<char> buf(len);
1396        if (!GetLogicalProcessorInformationEx(RelationProcessorCore, (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) buf.data(),
1397                                              &len))
1398            return -1;
1399        int best = -1, core = 0;
1400        for (const char* p = buf.data(); p < buf.data() + len;
1401             p += ((const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) p)->Size, ++core) {
1402            const auto* e = (const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) p;
1403            const GROUP_AFFINITY& ga = e->Processor.GroupMask[0];
1404            int seen = 0;
1405            for (int bit = 0; bit < 64; ++bit)
1406                if ((ga.Mask & (1ull << bit)) && ++seen == 2 && core > 0) best = ga.Group * 64 + bit;
1407        }
1408        return best;
1409#else
1410        return -1;
1411#endif
1412    }
1413    void 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
1416        const char* c = std::getenv("STRATA_ADAPT_JOB_CPU");
1417        const int cpu = c != nullptr ? std::atoi(c) : smt_spare_cpu();
1418        if (cpu >= 0) (void) strata::kernels::cpu::pin_current_thread(cpu);
1419        for (;;) {
1420            std::function<void()> f;
1421            {
1422                std::unique_lock<std::mutex> lk(mu_);
1423                cv_.wait(lk, [&] { return has_ || quit_; });
1424                if (!has_) return;
1425                f = std::move(job_);
1426                has_ = false;
1427            }
1428            f();
1429            done_.store(true, std::memory_order_release);
1430        }
1431    }
1432    std::mutex mu_;
1433    std::condition_variable cv_;
1434    std::function<void()> job_;
1435    bool 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) {
1456    const uint8_t* p = (const uint8_t*) data;
1457    for (size_t i = 0; i < n; ++i) { h ^= p[i]; h *= 1099511628211ull; }
1458    return h;
1459}
1460
1461using ConvStateSizes = strata::core::ConversationStateSizes;
1462
1463ConvStateSizes conv_state_sizes(const strata::core::ModelGeometry& g, const strata::core::SessionState& ss) {
1464    ConvStateSizes 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);
1469    return 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;
1475    if (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
1477    return 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)
1486    try {
1487        dpct::get_current_device().queues_wait_and_throw();
1488        return true;
1489    } catch (...) {
1490        return 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;
1497    if (strata::core::conversation_checkpoint_restore(c, ss, g, error)) return true;
1498    std::fprintf(stderr, "strata serve: checkpoint restore: %s\n", error.c_str());
1499    return 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,
1507                          uint64_t& digest, std::string& err) {
1508    const 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);
1511    for (const auto& [path, scale] : o.cvec_files) {
1512        try {
1513            strata::GgufFile f(path);
1514            const strata::MetaValue* arch = f.get("general.architecture");
1515            if (arch == nullptr || arch->s != "controlvector") {
1516                err = path + ": not a control vector GGUF (general.architecture is not 'controlvector')";
1517                return false;
1518            }
1519            const strata::MetaValue* hint = f.get("controlvector.model_hint");
1520            if (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());
1522            int found = 0;
1523            for (const strata::TensorInfo& t : f.tensors()) {
1524                if (t.name.rfind("direction.", 0) != 0) continue;
1525                const long l = std::strtol(t.name.c_str() + 10, nullptr, 10);
1526                if (l < 1 || l >= L) continue;   // layer 0 has no vector; past the model is ignored, as in llama.cpp
1527                if (t.type != 0 || t.elements() != (uint64_t) N) {
1528                    err = path + ": " + t.name + " must be " + std::to_string((long long) N) + " f32";
1529                    return false;
1530                }
1531                const float* src = reinterpret_cast<const float*>(f.tensor_data(t));
1532                for (int64_t j = 0; j < N; ++j) data[(size_t) (l * N + j)] += scale * src[j];
1533                have[(size_t) l] = true;
1534                ++found;
1535            }
1536            if (found == 0) { err = path + ": no direction.<layer> tensors"; return false; }
1537        } catch (const std::exception& e) {
1538            err = e.what();
1539            return false;
1540        }
1541    }
1542    const int first = o.cvec_first <= 0 ? 1 : o.cvec_first;
1543    const int last = (o.cvec_last <= 0 || o.cvec_last >= L) ? (int) L - 1 : o.cvec_last;
1544    const int single = o.cvec_mode == 0 ? o.cvec_single : -1;
1545    if (single >= 0 && (single >= L || !have[(size_t) single])) {
1546        err = "--cvec-dir single:" + std::to_string(single) + ": the vector has no direction for that layer";
1547        return false;
1548    }
1549    std::vector<float> dir((size_t) (L * N), 0.0f), s((size_t) L, 0.0f);
1550    int steered = 0;
1551    for (int64_t l = first; l <= last; ++l) {
1552        const int64_t src = single >= 0 ? single : l;
1553        if (!have[(size_t) src]) continue;
1554        const float* d = data.data() + (size_t) (src * N);
1555        if (o.cvec_mode == 0) {
1556            double nrm = 0.0;
1557            for (int64_t j = 0; j < N; ++j) nrm += (double) d[j] * d[j];
1558            nrm = std::sqrt(nrm);
1559            if (nrm <= 0.0) continue;
1560            s[(size_t) l] = (float) nrm;
1561            for (int64_t j = 0; j < N; ++j) dir[(size_t) (l * N + j)] = (float) (d[j] / nrm);
1562        } else {
1563            s[(size_t) l] = 1.0f;
1564            std::copy(d, d + N, dir.begin() + (size_t) (l * N));
1565        }
1566        ++steered;
1567    }
1568    if (steered == 0) { err = "the control vector has no direction in layers " + std::to_string(first) + ".." + std::to_string(last); return false; }
1569    if (!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"
1572        b.i64("mode", o.cvec_mode);
1573        b.i64("first", first);
1574        b.i64("last", last);
1575        b.i64("single", single);
1576        b.bytes("dir", dir.data(), dir.size() * sizeof(float));
1577        b.bytes("scale", s.data(), s.size() * sizeof(float));
1578        digest = b.digest();
1579        if (digest == 0) digest = 1;   // 0 means "none loaded"
1580    }
1581    summary = 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",
1585                 o.cvec_mode == 0 ? "project" : "add", single >= 0 ? "single" : "per-layer", first, last, steered);
1586    return 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 {
1601    constexpr size_t kBytes = 256ull << 20;
1602    constexpr int kBursts = 4;
1603    void* h = nullptr;
1604    void* 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).
1607    if (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;
1608    if (DPCT_CHECK_ERROR(d = (void *)sycl::malloc_device(
1609                             kBytes, dpct::get_in_order_queue())) != 0) {
1610        if (pin_source) sycl::free(h, dpct::get_in_order_queue()); else free(h);
1611        return -1.0;
1612    }
1613    std::memset(h, 0, kBytes);   // fault the pages in before timing
1614    dpct::get_in_order_queue().memcpy(
1615        d, h, kBytes).wait(); // warmup: context up, copy engine primed
1616    float 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
1621    bool ok = cudaDeviceSynchronize() == cudaSuccess;
1622    for (int b = 0; b < kBursts && ok; ++b) {
1623        const Clock::time_point t0 = Clock::now();
1624        cudaMemcpyAsync(d, h, kBytes, cudaMemcpyHostToDevice);
1625        ok = cudaDeviceSynchronize() == cudaSuccess;
1626        ms[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];
1631    int n_ev = 0;
1632    while (n_ev <= kBursts &&
1633           DPCT_CHECK_ERROR(ev[n_ev] = new sycl::event()) == 0)++ n_ev;
1634    bool ok = n_ev == kBursts + 1;
1635    if (ok) {
1636        dpct::sync_barrier(ev[0]);
1637        for (int b = 0; b < kBursts; ++b) {
1638            /*
1639            DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
1640            API. While the origin API might be synchronous, it depends on the
1641            type of operand memory, so you may need to call wait() on event
1642            return 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        }
1647        ok = DPCT_CHECK_ERROR(ev[kBursts]->wait_and_throw()) == 0;
1648        for (int b = 0; b < kBursts && ok; ++b) ok =
1649            DPCT_CHECK_ERROR(
1650                ms[b] =
1651                    (ev[b + 1]
1652                         ->get_profiling_info<
1653                             sycl::info::event_profiling::command_end>() -
1654                     ev[b]
1655                         ->get_profiling_info<
1656                             sycl::info::event_profiling::command_start>()) /
1657                    1000000.0f) == 0;
1658    }
1659    for (int i = 0; i < n_ev; ++i) dpct::destroy_event(ev[i]);
1660#endif
1661    double bw = -1.0;
1662    if (samples != nullptr) samples->clear();
1663    for (int b = 0; b < kBursts && ok; ++b) {
1664        const double s = ms[b] > 0.01f ? (double) kBytes / (ms[b] * 1e-3) / 1e9 : -1.0;
1665        bw = std::max(bw, s);
1666        if (samples != nullptr) {
1667            char buf[32];
1668            std::snprintf(buf, sizeof(buf), "%s%.1f", b == 0 ? "" : " ", s);
1669            *samples += buf;
1670        }
1671    }
1672    /*
1673    DPCT1010: SYCL uses exceptions to report errors and does not use the
1674    error codes. The cudaGetLastError function call was replaced with 0. You
1675    need to rewrite this code.
1676    */
1677    if (!ok)(void) 0;
1678    sycl::free(d, dpct::get_in_order_queue());
1679    if (pin_source) sycl::free(h, dpct::get_in_order_queue()); else free(h);
1680    return 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) {
1694    return 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 {
1702    static constexpr double kPoolFactor = 1.85;
1703    bool on = false;
1704    double link_gbps = 0.0, blob_bytes = 0.0;
1705    double mark_ms = 0.0;
1706    int64_t mark_jobs = 0;
1707    double acc_ms = 0.0;
1708    int64_t acc_jobs = 0;
1709    int acc_win = 0, updates = 0;
1710    void 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.
1712    double window(double ms_run, int64_t jobs, double cur, double* tc_us, double* rate) {
1713        if (!on) return -1.0;
1714        acc_ms += ms_run - mark_ms;
1715        acc_jobs += jobs - mark_jobs;
1716        mark(ms_run, jobs);
1717        ++acc_win;
1718        if (acc_win < (updates == 0 ? 48 : 96)) return -1.0;
1719        if (acc_jobs < 300) {          // too few missed experts to read the pool's speed (everything hits): look again
1720            if (acc_win >= 2000) on = false;
1721            return -1.0;
1722        }
1723        const double tc = acc_ms * 1000.0 / (double) acc_jobs;
1724        acc_ms = 0.0;
1725        acc_jobs = 0;
1726        acc_win = 0;
1727        if (++updates >= 3) on = false;
1728        if (!(tc > 1.0) || !(blob_bytes > 0.0) || !(link_gbps > 0.0)) return -1.0;
1729        const double r = blob_bytes / (tc * 1e-6) / 1e9;
1730        const 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;
1733        return 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) {
1744    const uint64_t n = t.rows();
1745    if (n < 4096) return -1.0;
1746    constexpr 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);
1749    uint64_t x = 0x9E3779B97F4A7C15ull ^ n;
1750    const auto t0 = std::chrono::steady_clock::now();
1751    uint64_t done = 0;
1752    double el = 0;
1753    for (int b = 0; b < 64; ++b) {
1754        for (auto& r : rows) { x ^= x << 13; x ^= x >> 7; x ^= x << 17; r = (uint32_t) (x % n); }
1755        std::string e;
1756        if (!t.gather_batch(rows.data(), kTok, out.data(), e)) return -1.0;
1757        done += rows.size();
1758        el = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
1759        if (el > 0.6) break;
1760    }
1761    return 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);
1771    try {
1772        for (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.
1787    for (int i = 1; i < argc && i < 3; ++i) {
1788        if (std::strcmp(argv[i], "--version") == 0 || std::strcmp(argv[i], "-V") == 0) {
1789            std::printf("strata %s\n", STRATA_VERSION);
1790            return 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.
1794        if (std::strcmp(argv[i], "--families") == 0) {
1795            std::printf("qwen4exp\n");
1796            return 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)
1800        if (std::strcmp(argv[i], "--geometry") == 0) {
1801            std::printf("%s\n", strata::core::kGeometryName);
1802            return 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).
1811    if (std::getenv("STRATA_ARENA_MMAP") && std::getenv("STRATA_ARENA_MMAP")[0] == '1')
1812        setenv("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.
1817    if (std::getenv("CUDA_MODULE_LOADING") == nullptr) {
1818#if defined(_WIN32)
1819        _putenv_s("CUDA_MODULE_LOADING", "EAGER");
1820#else
1821        setenv("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)
1825    Options o;
1826    bool borrow_explicit = false;   // SYCL port: --prefill-borrow / --no-prefill-borrow given (else chosen by context)
1827    bool have_tokens = false;
1828    bool have_logits_stride = false;
1829    for (int i = 1; i < argc; ++i) {
1830        const std::string a = argv[i];
1831        auto next = [&](const char* what) -> const char* {
1832            if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", what); std::exit(2); }
1833            return argv[++i];
1834        };
1835        bool parsed = true;
1836        if (a == "--help" || a == "-h") { usage(); return 0; }
1837        else if (a == "--pack") o.pack = next("--pack");
1838        else if (a == "--tokens") {
1839            if (have_tokens) { std::fprintf(stderr, "supply one token input only\n"); return 2; }
1840            std::string e;
1841            if (!parse_i64_list(next("--tokens"), o.tokens, e)) { std::fprintf(stderr, "%s\n", e.c_str()); return 2; }
1842            have_tokens = true;
1843        }
1844        else if (a == "--tokens-file") {
1845            if (have_tokens) { std::fprintf(stderr, "supply one token input only\n"); return 2; }
1846            std::ifstream input(next("--tokens-file"));
1847            if (!input) { std::fprintf(stderr, "cannot open token file\n"); return 2; }
1848            std::string text((std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>());
1849            if (input.bad()) { std::fprintf(stderr, "cannot read token file\n"); return 2; }
1850            std::string error;
1851            if (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            }
1854            have_tokens = true;
1855        }
1856        else if (a == "--max-new") o.max_new = std::atoll(next("--max-new"));
1857        else if (a == "--max-context") o.max_context = std::atoll(next("--max-context"));
1858        else if (a == "--rope-scaling") o.rope_scaling = next("--rope-scaling");
1859        else if (a == "--rope-scale") o.rope_scale = std::atof(next("--rope-scale"));
1860        else if (a == "--rope-freq-base") o.rope_freq_base = std::atof(next("--rope-freq-base"));
1861        else if (a == "--rope-freq-scale") o.rope_freq_scale = std::atof(next("--rope-freq-scale"));
1862        else if (a == "--yarn-orig-ctx") o.yarn_orig_ctx = std::atof(next("--yarn-orig-ctx"));
1863        else if (a == "--yarn-ext-factor") o.yarn_ext_factor = std::atof(next("--yarn-ext-factor"));
1864        else if (a == "--yarn-attn-factor") o.yarn_attn_factor = std::atof(next("--yarn-attn-factor"));
1865        else if (a == "--yarn-beta-fast") o.yarn_beta_fast = std::atof(next("--yarn-beta-fast"));
1866        else if (a == "--yarn-beta-slow") o.yarn_beta_slow = std::atof(next("--yarn-beta-slow"));
1867        else if (a == "--greedy") o.greedy = true;
1868        else if (a == "--seed") { o.seed = (uint64_t) std::atoll(next("--seed")); o.greedy = false; }
1869        else if (a == "--top-k") o.top_k = std::atoi(next("--top-k"));
1870        else if (a == "--top-p") o.top_p = (float) std::atof(next("--top-p"));
1871        else if (a == "--temperature") o.temperature = (float) std::atof(next("--temperature"));
1872        else if (a == "--dump-logits") o.dump_logits = next("--dump-logits");
1873        else if (a == "--logits-stride") {
1874            if (have_logits_stride) { std::fprintf(stderr, "--logits-stride must be supplied only once\n"); return 2; }
1875            if (!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            }
1878            have_logits_stride = true;
1879        }
1880        else if (a == "--dump-residual") o.dump_residual = next("--dump-residual");
1881        else if (a == "--dump-mixed") o.dump_mixed = next("--dump-mixed");
1882        else if (a == "--dump-layers") o.dump_layers = next("--dump-layers");
1883        else if (a == "--dump-halves") o.dump_halves = next("--dump-halves");
1884        else if (a == "--dump-routing") o.dump_routing = next("--dump-routing");
1885        else if (a == "--ple-gguf") o.ple_gguf = next("--ple-gguf");
1886        else if (a == "--no-ple") o.no_ple = true;
1887        else if (a == "--ple-io") { o.ple_io = next("--ple-io"); o.ple_io_explicit = true; }
1888        else if (a == "--ple-row-cache") o.ple_row_cache = std::atoll(next("--ple-row-cache"));
1889        else if (a == "--ple-inflight") o.ple_inflight = std::atoi(next("--ple-inflight"));
1890        else if (a == "--ple-delay-us") o.ple_delay_us = std::atof(next("--ple-delay-us"));
1891        else if (a == "--ple-sync-submit") o.ple_sync_submit = true;
1892        else if (a == "--kv") o.kv = next("--kv");
1893        else if (a == "--kv-resident") o.kv_resident = std::atoll(next("--kv-resident"));
1894        else if (a == "--kv-grow") o.kv_grow = true;
1895        else if (a == "--no-kv-grow") o.kv_grow = false;
1896        else if (a == "--stream-token") o.stream_token = true;
1897        else if (a == "--check-logits") o.check_logits = true;
1898        else if (a == "--gr-fp32-activations") o.gr_fp32_activations = true;
1899        else if (a == "--gr-native-mmvf") o.gr_native_mmvf = true;
1900        else if (a == "--native-bf16") o.native_bf16 = true;
1901        else if (a == "--native-bf16-extra") o.native_bf16_extra = true;
1902        else if (a == "--native-ple-key") o.native_ple_key = true;
1903        else if (a == "--native-moe-combine") o.native_moe_combine = true;
1904        else if (a == "--native-gdn") o.native_gdn = true;
1905        else if (a == "--native-flash-attn-short") o.native_flash_attn_short = true;
1906        else if (a == "--native-qsa-indexer") o.native_qsa_indexer = true;
1907        else if (a == "--native-qsa") o.native_qsa = true;
1908        else if (a == "--native-rope") o.native_rope = true;
1909        else if (a == "--native-ple-postops") o.native_ple_postops = true;
1910        else if (a == "--native-router") o.native_router = true;
1911        else if (a == "--cpu-oracle-q8-0") o.cpu_oracle_q8_0 = true;
1912        else if (a == "--native") o.native_preset = next("--native");
1913        else if (a == "--native-head-gguf") o.native_head_gguf = next("--native-head-gguf");
1914        else if (a == "--embd-gguf") o.embd_gguf = next("--embd-gguf");
1915        else if (a == "--native-dense-gguf") o.native_dense_gguf.push_back(next("--native-dense-gguf"));
1916        else if (a == "--no-capture") o.no_capture = true;
1917        else if (a == "--no-pool") o.no_pool = true;
1918        else if (a == "--sync-every-layer") o.sync_every_layer = true;
1919        else if (a == "--stage-timing") o.stage_timing = true;
1920        else if (a == "--graph-only") o.graph_only = true;
1921        else if (a == "--gpu-only-full") o.gpu_only_full = true;
1922        else if (a == "--pool-workers") o.pool_workers = std::atoi(next("--pool-workers"));
1923        else if (a == "--pool-cores") o.pool_cores = next("--pool-cores");
1924        else if (a == "--host-core") {
1925            o.host_core = next("--host-core");
1926            if (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());
1928                return 2;
1929            }
1930        }
1931        else if (a == "--pool-affinity") {
1932            const std::string v = next("--pool-affinity");
1933            if (v == "auto") o.pool_affinity = strata::kernels::cpu::PoolAffinity::Auto;
1934            else if (v == "p-cores" || v == "pcores") o.pool_affinity = strata::kernels::cpu::PoolAffinity::PCores;
1935            else if (v == "all") o.pool_affinity = strata::kernels::cpu::PoolAffinity::All;
1936            else {
1937                std::fprintf(stderr, "strata generate: unknown --pool-affinity value '%s' (expected auto, p-cores, or all)\n", v.c_str());
1938                return 2;
1939            }
1940        }
1941        else if (a == "--no-host-worker") o.no_host_worker = true;
1942        else if (a == "--no-ple-prefetch") o.no_ple_prefetch = true;
1943        else if (a == "--coupled-draft") o.coupled_draft = true;
1944        else if (a == "--no-coupled-draft") o.coupled_draft = false;
1945        else 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.
1948        if (!parsed) {
1949        if (a == "--expert-cache") {
1950            const std::string v = next("--expert-cache");
1951            o.expert_cache = (v == "auto") ? -1 : std::atoi(v.c_str());
1952        }
1953        else if (a == "--expert-cache-device1" || a == "--expert-cache-device2" || a == "--expert-cache-device3") {
1954            const size_t r = (size_t) (a.back() - '1');
1955            const std::string v = next(a.c_str());
1956            o.expert_cache_remote_auto[r] = v == "auto";
1957            o.expert_cache_remote[r] = v == "auto" ? std::numeric_limits<int>::max() : std::atoi(v.c_str());
1958        }
1959        else if (a == "--remote-expert-opt") o.remote_expert_opt = true;
1960        else if (a == "--expert-cache-remote-placement")
1961            o.expert_cache_remote_placement = next("--expert-cache-remote-placement");
1962        else if (a == "--vram-reserve-mib") { o.vram_reserve_mib = std::atoi(next("--vram-reserve-mib")); o.vram_reserve_given = true; }
1963        else if (a == "--vram-reserve-later-mib")
1964            o.vram_reserve_later_mib = std::atoi(next("--vram-reserve-later-mib"));
1965        else if (a == "--prefill") {
1966            const std::string v = next("--prefill");
1967            o.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
1969            const char* env_max = std::getenv("STRATA_PREFILL_AUTO_MAX");
1970            const 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);
1972            o.prefill_auto_max = want_max >= 32768 ? 32768 : want_max >= 16384 ? 16384 : 8192;
1973            o.prefill_chunk = o.prefill_auto ? o.prefill_auto_max : std::atoll(v.c_str());
1974            o.prefill_given = !o.prefill_auto && o.prefill_chunk > 0;
1975        }
1976        else if (a == "--no-split-rows") o.no_split_rows = true;
1977        else if (a == "--no-prefill-borrow") { o.no_prefill_borrow = true; borrow_explicit = true; }
1978        else if (a == "--prefill-borrow") { o.no_prefill_borrow = false; borrow_explicit = true; }
1979        else if (a == "--vram-elastic") o.vram_elastic = true;
1980        else if (a == "--vram-segment-mib") o.vram_segment_mib = std::atoll(next("--vram-segment-mib"));
1981        else if (a == "--prefill-until") o.prefill_until = std::atoll(next("--prefill-until"));
1982        else if (a == "--dump-final-r") o.dump_final_r = next("--dump-final-r");
1983        else if (a == "--spec") o.spec = std::atoi(next("--spec"));
1984        else if (a == "--batch") o.batch = std::atoi(next("--batch"));
1985        else if (a == "--slots") o.batch = std::atoi(next("--slots"));   // the same as --batch
1986        else if (a == "--trim-stage-weights") o.trim_stage_weights = true;
1987        else if (a == "--batch-groups") {
1988            const std::string bg = next("--batch-groups");
1989            o.batch_groups = bg == "auto" ? -1 : std::atoi(bg.c_str());
1990        }
1991        else if (a == "--batch-mtp") o.batch_mtp = true;
1992        else if (a == "--spec-oracle") o.spec_oracle = next("--spec-oracle");
1993        else if (a == "--spec-corrupt") o.spec_corrupt = std::atoi(next("--spec-corrupt"));
1994        else if (a == "--spec-follow") o.spec_follow = next("--spec-follow");
1995        else if (a == "--window-hashes") o.window_hashes = next("--window-hashes");
1996        else if (a == "--mtp") o.mtp = next("--mtp");
1997        else if (a == "--mtp-window") o.mtp_window = std::atoll(next("--mtp-window"));
1998        else if (a == "--pcie-frac") o.pcie_frac = std::atof(next("--pcie-frac"));
1999        else if (a == "--adapt-every") o.adapt_every = std::atoi(next("--adapt-every"));
2000        else if (a == "--adapt-decay") o.adapt_decay = strata::program::adapt_decay_checked(std::atof(next("--adapt-decay")));   // #1284: outside 0..1 -> 0.7, said
2001        else if (a == "--adapt-async") o.adapt_async = std::atoi(next("--adapt-async")) != 0 ? 1 : 0;
2002        else if (a == "--spec-min-p") o.spec_min_p = std::atof(next("--spec-min-p"));
2003        else if (a == "--stop-eos") o.stop_eos = true;
2004        else if (a == "--spec-split") o.spec_split = true;
2005        else if (a == "--layer-split") o.layer_split = next("--layer-split");
2006        else if (a == "--split-device") o.split_device = next("--split-device");
2007        else if (a == "--split-skip-if-fits") o.split_skip_if_fits = true;
2008        else if (a == "--pcie-mode") o.pcie_mode = next("--pcie-mode");
2009        else if (a == "--serve") o.serve = true;
2010        else if (a == "--vision") o.vision = true;
2011        else if (a == "--prompt-cache") o.prompt_cache = std::max(0, std::atoi(next("--prompt-cache")));
2012        else if (a == "--conversation-cache-mib" || a == "--conversation-cache-slots" ||
2013                 a == "--conversation-cache-min-free-mib" || a == "--session-min-free-mib") {
2014            const std::string value = next(a.c_str());
2015            int64_t number = 0;
2016            const auto result = std::from_chars(value.data(), value.data() + value.size(), number);
2017            const int64_t limit = a == "--conversation-cache-slots" ? INT32_MAX : INT64_MAX / (1024 * 1024);
2018            if (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());
2020                return 2;
2021            }
2022            if (a == "--conversation-cache-mib") o.conversation_cache_mib = number;
2023            else if (a == "--conversation-cache-min-free-mib") o.conversation_cache_min_free_mib = number;
2024            else if (a == "--session-min-free-mib") o.session_min_free_mib = number;
2025            else o.conversation_cache_slots = (int) number;
2026        }
2027        else if (a == "--prompt-cache-tail") o.prompt_cache_tail = true;
2028        else if (a == "--prompt-cache-every") o.prompt_cache_every = std::max(0LL, std::atoll(next("--prompt-cache-every")));
2029        else if (a == "--prompt-cache-root") o.prompt_cache_root = std::max(0LL, std::atoll(next("--prompt-cache-root")));
2030        else if (a == "--turn-token") o.turn_token = std::atoll(next("--turn-token"));
2031        else if (a == "--tail-role-token") o.tail_role_token = std::atoll(next("--tail-role-token"));
2032        else if (a == "--short-read") o.short_read = std::max(0LL, std::atoll(next("--short-read")));
2033        else if (a == "--pipeline-windows") o.pipeline_windows = std::max(0, std::min(2, std::atoi(next("--pipeline-windows"))));
2034        else if (a == "--suffix-draft") o.suffix_draft = std::max(0, std::atoi(next("--suffix-draft")));
2035        else if (a == "--mtp-max-t") o.mtp_max_t = std::max(0, std::atoi(next("--mtp-max-t")));
2036        else if (a == "--lookup-chain") o.lookup_chain = std::clamp(std::atoi(next("--lookup-chain")), 0, 7);
2037        else if (a == "--lookup-chain-min") o.lookup_chain_min = std::max(3, std::atoi(next("--lookup-chain-min")));
2038        else if (a == "--mtp-hnorm") {
2039            const std::string v = next("--mtp-hnorm");
2040            if (v != "pooled" && v != "stream") {
2041                std::fprintf(stderr, "strata generate: --mtp-hnorm takes pooled or stream\n");
2042                return 2;
2043            }
2044            o.mtp_hnorm_stream = v == "stream";
2045        }
2046        else if (a == "--mtp-q4") {
2047            o.mtp_q4 = next("--mtp-q4");
2048            if (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");
2050                return 2;
2051            }
2052        }
2053        else if (a == "--mtp-draft-vocab") o.mtp_draft_vocab = next("--mtp-draft-vocab");
2054        else if (a == "--draft") o.draft = next("--draft");
2055        else if (a == "--draft-model") o.draft_model = next("--draft-model");
2056        else if (a == "--draft-fallback") {
2057            o.draft_fallback = next("--draft-fallback");
2058            if (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        }
2063        else if (a == "--draft-conf") o.draft_conf = std::clamp(std::atof(next("--draft-conf")), 0.0, 1.0);
2064        else if (a == "--draft-cap") o.draft_cap = std::max(0, std::atoi(next("--draft-cap")));
2065        else if (a == "--control-vector") o.cvec_files.push_back({next("--control-vector"), 1.0f});
2066        else 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;
2070            while (std::getline(list, item, ',')) {
2071                const size_t colon = item.rfind(':');
2072                char* end = nullptr;
2073                const float sc = colon == std::string::npos ? 0.0f : std::strtof(item.c_str() + colon + 1, &end);
2074                if (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());
2076                    return 2;
2077                }
2078                o.cvec_files.push_back({item.substr(0, colon), sc});
2079            }
2080        }
2081        else if (a == "--control-vector-layer-range") {
2082            o.cvec_first = std::atoi(next("--control-vector-layer-range"));
2083            o.cvec_last = std::atoi(next("--control-vector-layer-range"));
2084        }
2085        else if (a == "--cvec-mode") {
2086            const std::string m = next("--cvec-mode");
2087            if (m == "project") o.cvec_mode = 0;
2088            else if (m == "add") o.cvec_mode = 1;
2089            else { std::fprintf(stderr, "--cvec-mode: add or project, got '%s'\n", m.c_str()); return 2; }
2090        }
2091        else if (a == "--cvec-dir") {
2092            const std::string d = next("--cvec-dir");
2093            if (d == "per-layer") o.cvec_single = -1;
2094            else if (d.rfind("single:", 0) == 0) o.cvec_single = std::atoi(d.c_str() + 7);
2095            else { std::fprintf(stderr, "--cvec-dir: per-layer or single:L, got '%s'\n", d.c_str()); return 2; }
2096        }
2097        else if (a == "--no-spec-split") o.spec_split = false;
2098        else if (a == "--eos-ids") {
2099            std::string e;
2100            if (!parse_i64_list(next("--eos-ids"), o.eos_ids, e)) { std::fprintf(stderr, "--eos-ids: %s\n", e.c_str()); return 2; }
2101            o.stop_eos = true;
2102        }
2103        else if (a == "--adapt-swaps") o.adapt_swaps = std::atoi(next("--adapt-swaps"));
2104        else if (a == "--expert-cache-cpu-order") o.expert_cache_cpu_order = true;
2105        else if (a == "--expert-cache-per-layer") o.expert_cache_per_layer = true;
2106        else if (a == "--peer-device") o.peer_device = std::atoi(next("--peer-device"));
2107        else if (a == "--peer-reserve-mib") o.peer_reserve_mib = std::atoi(next("--peer-reserve-mib"));
2108        else if (a == "--peer-slots") o.peer_slots = std::atoll(next("--peer-slots"));
2109        else if (a == "--peer-adapt-swaps") o.peer_adapt_swaps = std::atoi(next("--peer-adapt-swaps"));
2110        else if (a == "--peer-prefill-rows") o.peer_prefill_rows = std::atoll(next("--peer-prefill-rows"));
2111        else if (a == "--no-hit-poke") o.no_hit_poke = true;
2112        else if (a == "--expert-profile") o.expert_profile = next("--expert-profile");
2113        else if (a == "--expert-profile-save") o.expert_profile_save = next("--expert-profile-save");
2114        else if (a == "--expert-profile-save-every")
2115            o.expert_profile_save_min = std::atof(next("--expert-profile-save-every"));
2116        else if (a == "--gpu-stages") o.gpu_stages = true;
2117        else if (a == "--mmap-experts") o.mmap_experts = true;
2118        else if (a == "--shared-expert-arena") o.shared_expert_arena = next("--shared-expert-arena");
2119        else if (a == "--resident-cpu-experts") o.resident_cpu_experts = o.resident_cpu_explicit = true;
2120        else if (a == "--stream-experts") o.stream_experts = true;
2121        else if (a == "--resident-experts") {
2122            o.mmap_experts = o.resident_cpu_experts = o.resident_pin = o.resident_soft = true;
2123            o.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
2126            if (const char* v = std::getenv("STRATA_RESIDENT_PIN"); v != nullptr && std::string(v) == "0")
2127                o.resident_pin = false;
2128            if (const char* v = std::getenv("STRATA_RESIDENT_HEADROOM_GIB"); v != nullptr && std::atof(v) >= 0.0)
2129                o.resident_headroom = (uint64_t) (std::atof(v) * 1073741824.0);
2130        }
2131        else if (a == "--resident-budget-gib") {
2132            const double gib = std::atof(next("--resident-budget-gib"));
2133            if (!(gib > 0.0)) { std::fprintf(stderr, "strata generate: --resident-budget-gib needs N > 0\n"); return 2; }
2134            o.resident_budget = (uint64_t) (gib * 1073741824.0);
2135            o.mmap_experts = o.resident_cpu_experts = o.resident_pin = true;
2136            o.resident_headroom = 4ull << 30;
2137            if (const char* v = std::getenv("STRATA_RESIDENT_PIN"); v != nullptr && std::string(v) == "0")
2138                o.resident_pin = false;
2139            if (const char* v = std::getenv("STRATA_RESIDENT_HEADROOM_GIB"); v != nullptr && std::atof(v) >= 0.0)
2140                o.resident_headroom = (uint64_t) (std::atof(v) * 1073741824.0);
2141        }
2142        else if (a == "--stats") o.stats = true;
2143        else if (a == "--shared-late") o.shared_late = true;
2144        else if (a == "--keep-canonical") o.keep_canonical = true;
2145        else if (a == "--no-token-graph") o.no_token_graph = true;
2146        else if (a == "--no-fused-gr") o.no_fused_gr = true;
2147        else if (a == "--no-fast-attn") o.no_fast_attn = true;
2148        else if (a == "--no-publish-kernel") o.no_publish_kernel = true;
2149        else if (a == "--no-fused-gdn") o.no_fused_gdn = true;
2150        else if (a == "--no-fast-select") o.no_fast_select = true;
2151        else {
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());
2155            usage();
2156            return 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
2163        cudaDeviceProp ad{};
2164        if (cudaGetDeviceProperties(&ad, 0) == cudaSuccess) strata::core::apply_arch_defaults(ad.gcnArchName);
2165        else (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;
2171        if (hc.empty())
2172            if (const char* e = std::getenv("STRATA_HOST_CORE")) hc = e;
2173        if (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;
2178        if (pc.empty())
2179            if (const char* e = std::getenv("STRATA_POOL_CORES")) pc = e;
2180        if (!pc.empty()) {
2181            std::vector<int> cpus;
2182            std::string perr;
2183            if (strata::kernels::cpu::parse_pool_cores(pc, cpus, perr)) strata::kernels::cpu::set_pool_cores(cpus);
2184            else 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)
2188    if (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",
2190                     o.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)
2199    const bool pcie_given = o.pcie_frac >= 0.0;
2200    std::vector<int64_t> split_at;
2201    std::vector<int> split_devs;
2202    bool split_auto = false, split_same = false;
2203    if (!o.layer_split.empty()) {
2204        int n_dev = 1;
2205        if (DPCT_CHECK_ERROR(n_dev = dpct::device_count()) != 0 || n_dev < 1)
2206            n_dev = 1;
2207        /*
2208        DPCT1026: The call to cudaGetLastError was removed because this
2209        functionality is redundant in SYCL.
2210        */
2211        auto ints = [](const std::string &str, auto &out) -> bool {
2212            using V = typename std::decay_t<decltype(out)>::value_type;
2213            size_t a = 0;
2214            while (a < str.size()) {
2215                size_t b = str.find(',', a);
2216                if (b == std::string::npos) b = str.size();
2217                const std::string t = str.substr(a, b - a);
2218                if (t.empty() || t.find_first_not_of("0123456789") != std::string::npos) return false;
2219                out.push_back((V) std::atoll(t.c_str()));
2220                a = b + 1;
2221            }
2222            return !out.empty();
2223        };
2224        split_auto = o.layer_split == "auto";
2225        bool 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.
2231        const auto stage_dev = [](int d) -> bool {
2232            try {
2233                const sycl::device dev = dpct::get_device(d);
2234                return dev.is_gpu() && dev.get_backend() == dpct::get_device(0).get_backend();
2235            } catch (...) {
2236                return false;
2237            }
2238        };
2239        if (ok && !o.split_device.empty()) ok = ints(o.split_device, split_devs);
2240        else if (ok)
2241            for (int d = 1; d < n_dev && (split_auto || split_devs.size() < split_at.size()); ++d)
2242                if (!split_auto || stage_dev(d)) split_devs.push_back(d);
2243        if (ok && !split_auto && split_devs.empty() && split_at.size() == 1) split_devs.push_back(0);   // one GPU
2244        split_same = ok && split_devs.size() == 1 && split_devs[0] == 0 && !split_auto;
2245        if (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");
2248            return 2;
2249        }
2250        if (ok && split_auto && split_devs.empty()) {
2251            std::fprintf(stderr, "strata generate: --layer-split auto: one GPU visible, so no split\n");
2252            o.layer_split.clear();
2253            split_auto = false;
2254        } else if (ok) {
2255            ok = (split_auto || split_at.size() == split_devs.size()) && split_devs.size() < (size_t) SplitDrive::kMax;
2256            for (size_t i = 0; ok && i < split_at.size(); ++i) ok = split_at[i] >= 2 && (i == 0 || split_at[i] > split_at[i - 1]);
2257            for (size_t i = 0; ok && !split_same && i < split_devs.size(); ++i) {
2258                ok = split_devs[i] > 0 && split_devs[i] < n_dev;
2259                for (size_t j = 0; ok && j < i; ++j) ok = split_devs[i] != split_devs[j];
2260            }
2261        }
2262        if (!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());
2267            return 2;
2268        }
2269    }
2270    bool multi_gpu = !split_devs.empty() && !split_same;   // cleared by --split-skip-if-fits before any stage loads
2271    bool split_own_auto = false;   // #340: the split keeps own prompt buffers by its rule (not --no-prefill-borrow)
2272    if (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");
2274        return 2;
2275    }
2276    if (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");
2278        return 2;
2279    }
2280    const bool remote_caches = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 ||
2281                               o.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).
2284    if (o.resident_cpu_experts && remote_caches) {
2285        std::fprintf(stderr, "strata generate: --resident-cpu-experts does not support remote expert caches\n");
2286        return 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
2290    int remote_dev[3] = {1, 2, 3};
2291    if (multi_gpu) {
2292        if (o.expert_profile.empty()) {
2293            std::fprintf(stderr, "strata generate: a layer split across GPUs needs --expert-profile\n");
2294            return 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).
2317        const char* own_env = std::getenv("STRATA_SPLIT_OWN");
2318        if (!o.no_prefill_borrow && !o.split_skip_if_fits && own_env != nullptr && own_env[0] != '0') {
2319            const char* v = std::string(own_env) == "auto" ? nullptr : own_env;
2320            bool 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)
2322            const int64_t own_chunk = o.prefill_auto || o.prefill_chunk <= 0 ? 2048 : o.prefill_chunk;
2323            const int64_t reserve_mib = 160 + (own_chunk * 680) / 1024 + 96 * 4;
2324            std::string why;
2325            if (!v) {
2326                std::vector<int> devs = {0};
2327                for (const int d : split_devs) devs.push_back(d);
2328                for (const int d : devs) {
2329                    dpct::device_info prop{};
2330                    /*
2331                    DPCT1026: The call to cudaGetLastError was removed
2332                    because this functionality is redundant in SYCL.
2333                    */
2334                    if (DPCT_CHECK_ERROR(
2335                            dpct::get_device(d).get_device_info(prop)) != 0) {
2336                        ; own = false; break;
2337                    }
2338                    const int64_t total_mib =
2339                        (int64_t)(prop.get_global_mem_size() >> 20);
2340                    if (reserve_mib * 100 > 12 * total_mib) {
2341                        own = false;
2342                        why = "CUDA" + std::to_string(d) + " has " + std::to_string(total_mib) + " MiB";
2343                        break;
2344                    }
2345                }
2346            }
2347            if (own) {
2348                o.no_prefill_borrow = true;
2349                split_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,
2352                             v ? " (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",
2355                             why.c_str());
2356            }
2357        }
2358        int n_vis = 1;
2359        if (DPCT_CHECK_ERROR(n_vis = dpct::device_count()) != 0 || n_vis < 1)
2360            n_vis = 1;
2361        /*
2362        DPCT1026: The call to cudaGetLastError was removed because this
2363        functionality is redundant in SYCL.
2364        */
2365        int next_free = 1;
2366        for (int r = 0; r < 3; ++r) {
2367            if (o.expert_cache_remote[(size_t) r] <= 0) continue;
2368            while (next_free < n_vis &&
2369                   std::find(split_devs.begin(), split_devs.end(), next_free) != split_devs.end()) ++next_free;
2370            if (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);
2373                return 2;
2374            }
2375            remote_dev[r] = next_free++;
2376        }
2377        std::string devs;
2378        for (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",
2380                     split_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.
2399    if (!borrow_explicit) {
2400        static const bool alchemist = [] {
2401            try {
2402                // PCI device ids, the same table setup_intel.py uses: 56a0 A770, 56a1 A750, 56a2 A580, 56a5 A380,
2403                // 56a6 A310, 5690 A770M
2404                const 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)
2407                if (dpct::get_current_device().get_info<sycl::info::device::global_mem_size>() < (12ull << 30)) return false;
2408                switch (id & 0xffffu) {
2409                case 0x56a0: case 0x56a1: case 0x56a2: case 0x56a5: case 0x56a6: case 0x5690: return true;
2410                default: return false;
2411                }
2412            } catch (...) { return false; }
2413        }();
2414        if (!multi_gpu && alchemist) {
2415            o.no_prefill_borrow = true;
2416            if (o.prefill_auto && o.prefill_chunk > 2048) o.prefill_chunk = o.prefill_auto_max = 2048;
2417        } else {
2418            o.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};
2426        if (multi_gpu) used.insert(used.end(), split_devs.begin(), split_devs.end());
2427        for (int r = 0; r < 3; ++r)
2428            if (o.expert_cache_remote[(size_t) r] > 0) used.push_back(remote_dev[r]);
2429        for (const int d : used) {
2430            if (const std::string why = strata::core::gpu_arch_problem(d); !why.empty()) {
2431                std::fprintf(stderr, "strata generate: %s\n", why.c_str());
2432                return 1;
2433            }
2434        }
2435    }
2436#endif
2437    if (o.prefill_auto && (o.no_prefill_borrow || o.expert_profile.empty())) {
2438        o.prefill_auto = false;       // nothing to lend from: the buffers are reserved for the session, so keep them small
2439        o.prefill_chunk = 2048;
2440    }
2441    if (!have_tokens && o.serve) {   // plan v0.3 P8: requests bring their own tokens
2442        o.tokens = {248045};
2443        o.max_new = 1;
2444        have_tokens = true;
2445        o.stop_eos = true;
2446    }
2447    if (!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");
2450        usage();
2451        return 2;
2452    }
2453
2454    if ((o.ple_io != "direct" && o.ple_io != "mmap" && o.ple_io != "ram") || o.ple_row_cache < 0 || o.ple_inflight < 1 ||
2455        o.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");
2457        return 2;
2458    }
2459#if defined(_WIN32)
2460    if (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");
2462        return 2;
2463    }
2464#endif
2465    if (o.kv == "q4") o.kv = "q4_0";
2466    if (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");
2468        return 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)
2474    const char* kv_rot = std::getenv("STRATA_KV_ROT");
2475    strata::core::qsa_set_kv_int8_rotate(kv_rot != nullptr && kv_rot[0] == '1');
2476    if (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
2479    if (o.kv_resident < 0) {
2480        std::fprintf(stderr, "strata generate: --kv-resident must be >= 0\n");
2481        return 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.
2487    if (o.suffix_draft > 0 && o.spec >= 2 && o.mtp_max_t == 0) {
2488        o.mtp_max_t = o.spec;
2489        o.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
2492    if (o.lookup_chain > 0 && o.spec >= 2) {
2493        if (o.mtp_max_t == 0) o.mtp_max_t = o.spec;
2494        o.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);
2498    if (!o.native_preset.empty()) {
2499        try {
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.
2502            o.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            {
2506                const strata::GgufFile meta(o.native_shards.front());
2507                const std::string why = strata::model_family_not_supported(strata::model_family(meta));
2508                if (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());
2510                    return 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
2515            if (o.ple_gguf.empty() && !o.no_ple) {
2516                const strata::GgufModel model(o.native_shards);
2517                size_t at = 0;
2518                if (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());
2522            return 2;
2523        }
2524        if (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");
2527            return 2;
2528        }
2529        o.stream_token = true;
2530        o.gr_native_mmvf = true;
2531        o.native_bf16 = o.native_bf16_extra = true;
2532        o.native_ple_key = o.native_moe_combine = o.native_gdn = o.native_router = true;
2533        o.native_qsa = o.native_qsa_indexer = o.native_rope = o.native_ple_postops = true;
2534        if (o.native_head_gguf.empty()) o.native_head_gguf = o.native_preset;
2535        if (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)
2538            o.native_dense_gguf = o.native_shards;
2539            // a PLE-only table (tools/ple_fp8_pack.py: architecture strata-ple) holds no projections
2540            bool ple_only = false;
2541            try {
2542                strata::GgufFile pg(o.ple_gguf);
2543                if (const strata::MetaValue* v = pg.get("general.architecture")) ple_only = v->s == "strata-ple";
2544            } catch (const std::exception&) {}
2545            if (!ple_only &&
2546                std::find(o.native_dense_gguf.begin(), o.native_dense_gguf.end(), o.ple_gguf) == o.native_dense_gguf.end())
2547                o.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    }
2552    if (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");
2554        return 2;
2555    }
2556    if (o.no_ple && !o.ple_gguf.empty()) {
2557        std::fprintf(stderr, "strata generate: --no-ple and --ple-gguf are mutually exclusive\n");
2558        return 2;
2559    }
2560    if (o.native_ple_postops && o.no_ple) {
2561        std::fprintf(stderr, "strata generate: --native-ple-postops requires PLE enabled\n");
2562        return 2;
2563    }
2564    if (!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");
2566        return 2;
2567    }
2568    // P7 audit: positions, cells and pooled-block indices are cast to int32 on the device path.
2569    if (o.max_context > 2147483647LL - 8) {
2570        std::fprintf(stderr, "strata generate: --max-context must be below 2^31\n");
2571        return 2;
2572    }
2573    if (o.max_new <= 0 || o.max_context <= 0 || o.max_new > o.max_context ||
2574        o.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");
2576        return 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    {
2583        using 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
2586        if (o.rope_scaling == "none") rope_cfg.type = RST::None;
2587        else if (o.rope_scaling == "linear") rope_cfg.type = RST::Linear;
2588        else if (o.rope_scaling == "yarn") rope_cfg.type = RST::YaRN;
2589        else if (!o.rope_scaling.empty()) {
2590            std::fprintf(stderr, "strata generate: --rope-scaling must be none, linear or yarn (got '%s')\n",
2591                         o.rope_scaling.c_str());
2592            return 2;
2593        }
2594        // every knob FINITE first: `atof("nan")` is NaN, and a NaN passes every range comparison below
2595        for (const double v : {o.rope_scale, o.rope_freq_base, o.rope_freq_scale, o.yarn_orig_ctx, o.yarn_ext_factor,
2596                               o.yarn_attn_factor, o.yarn_beta_fast, o.yarn_beta_slow})
2597            if (!std::isfinite(v)) {
2598                std::fprintf(stderr, "strata generate: a rope scaling knob is not a finite number (%g)\n", v);
2599                return 2;
2600            }
2601        // 0 is the absent default; an explicit factor must extend, not shrink
2602        if (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",
2604                         o.rope_scale);
2605            return 2;
2606        }
2607        if (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");
2609            return 2;
2610        }
2611        if (o.rope_freq_scale < 0 || o.yarn_orig_ctx < 0 || o.yarn_ext_factor < -1.0 || o.yarn_attn_factor <= 0 ||
2612            o.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");
2615            return 2;
2616        }
2617    }
2618    if (!std::isfinite(o.temperature) || o.temperature < 0 || !std::isfinite(o.top_p) ||
2619        o.top_p <= 0 || o.top_p > 1 || o.top_k < 0 || o.expert_cache < -1 ||
2620        o.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");
2625        return 2;
2626    }
2627    if (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");
2629        return 2;
2630    }
2631    if (o.remote_expert_opt && !o.serve) {
2632        std::fprintf(stderr, "strata generate: --remote-expert-opt requires --serve\n");
2633        return 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
2637    if (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)");
2641        return 2;
2642    }
2643
2644    if (o.native_flash_attn_short && o.max_context > 256) {
2645        std::fprintf(stderr, "strata generate: --native-flash-attn-short requires --max-context <=256\n");
2646        return 2;
2647    }
2648    if (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");
2650        return 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.
2655    if (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");
2658        return 2;
2659    }
2660    if (!o.native_head_gguf.empty()) {
2661        try {
2662            o.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());
2666            return 2;
2667        }
2668    }
2669    if (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");
2671        return 2;
2672    }
2673    if (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");
2675        return 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).
2687    const char* isa_floor = strata::kernels::cpu::isa_floor_build();
2688    if (!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());
2694        return 2;
2695    }
2696    if (isa_floor[0] != '\0') {
2697        const bool avx_floor = std::strcmp(isa_floor, "avx") == 0;
2698        if (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(),
2702                         avx_floor ? "; compile it with STRATA_ISA_FLOOR=none" : "");
2703            return 2;
2704        }
2705        if (!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);
2708        else
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;
2714    if (!o.native_head_gguf.empty() && !o.stream_token) {
2715        std::fprintf(stderr, "--native-head-gguf requires --stream-token\n");
2716        return 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    {
2722        const strata::core::ModelGeometry& g0 = strata::core::kCompiledGeometry;
2723        if (!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());
2725            return 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.
2730        const auto& lay = strata::kernels::cpu::expert_layout();
2731        for (int64_t l = 0; lay.native && l < (int64_t) lay.fmt.size(); ++l) {
2732            const auto& f = lay.fmt[(size_t) l];
2733            if (!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),
2737                             f.gu_type, f.d_type);
2738                return 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).
2743        if (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    }
2747    const 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").
2751    const char* early_env = std::getenv("STRATA_EARLY_REMOTE_CONTEXTS");
2752    const bool early_remote = early_env && early_env[0] == '1';
2753    for (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.
2756        double free_gib = 0;
2757        if (!strata::core::RemoteExperts::preflight(remote_dev[r], free_gib, err)) {
2758            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
2759            return 1;
2760        }
2761        std::fprintf(stderr, "strata generate: CUDA%d context ready, %.2f GiB free before expert arena registration\n",
2762                     remote_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.
2769    const bool pcie_explicit = o.pcie_frac >= 0.0;
2770    if (o.pcie_frac < 0.0) {
2771        const double base = native_pack ? 0.55 : 0.2;
2772        std::string bursts;
2773        const double bw = native_pack ? probe_pcie_h2d_gbps(&bursts, multi_gpu) : -1.0;
2774        if (!native_pack) {
2775            o.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.
2781            bool trellis = false;
2782            {
2783                const auto& lay = strata::kernels::cpu::expert_layout();
2784                for (size_t l = 0; lay.native && l < lay.fmt.size(); ++l) trellis = trellis || lay.fmt[l].gu_type >= 144;
2785            }
2786            o.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
2790                const char* pfd = std::getenv("STRATA_PCIE_FRAC_DEFAULT");
2791                o.pcie_frac_auto = pfd != nullptr && std::strcmp(pfd, "auto") == 0 && o.layer_split.empty();
2792                o.pcie_probe_gbps = bw;
2793            }
2794        } else {
2795            o.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.
2804    if (strata::intel_gpu_driver() == "xe" && !o.stream_experts) {
2805        if (!pcie_explicit) {
2806            o.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
2818    if (!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.
2822        if (!strata::kernels::cpu::cpu_features().usable()) {
2823            std::error_code ec;
2824            const 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",
2829                         o.pack.c_str());
2830            if (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());
2832            else
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
2846    int64_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;
2857        double gguf_rope_base = 0, gguf_rope_factor = 0, gguf_rope_orig_ctx = 0;
2858        if (!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.
2862            try {
2863                strata::GgufFile model_gguf(o.native_shards.front());   // the metadata shard
2864                std::string gerr;
2865                if (!strata::core::geometry_from_gguf(model_gguf, g, K, gerr)) {
2866                    std::fprintf(stderr, "strata generate: %s\n", gerr.c_str());
2867                    return 1;
2868                }
2869                const std::string mismatch = strata::core::compiled_geometry_mismatch(g);
2870                if (!mismatch.empty()) {
2871                    std::fprintf(stderr, "strata generate: %s: %s\n", o.native_preset.c_str(), mismatch.c_str());
2872                    return 1;
2873                }
2874                const std::string p = std::string(strata::model_family_arch(g.family)) + ".";
2875                if (const strata::MetaValue* v = model_gguf.get(p + "rope.freq_base")) gguf_rope_base = v->num();
2876                if (const strata::MetaValue* v = model_gguf.get(p + "rope.scaling.type")) gguf_rope_type = v->s;
2877                if (const strata::MetaValue* v = model_gguf.get(p + "rope.scaling.factor")) gguf_rope_factor = v->num();
2878                if (const strata::MetaValue* v = model_gguf.get(p + "rope.scaling.original_context_length"))
2879                    gguf_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                {
2883                    auto arr = [&](const char* k, std::vector<uint64_t>& out) {
2884                        const strata::MetaValue* v = model_gguf.get(p + k);
2885                        if (v == nullptr || v->type != strata::MetaType::ARRAY) return false;
2886                        for (const strata::MetaValue& e : v->items) out.push_back(e.u);
2887                        return true;
2888                    };
2889                    std::vector<uint64_t> pm, pv, po;
2890                    const bool a1 = arr("ple.layer_multipliers", pm), a2 = arr("ple.head_vocab_sizes", pv), a3 = arr("ple.head_offsets", po);
2891                    if (a1 || a2 || a3) {
2892                        std::string perr;
2893                        if (!(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",
2895                                         o.native_preset.c_str(), (a1 && a2 && a3) ? perr.c_str() : "one of the three arrays is missing");
2896                            return 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",
2902                             o.native_preset.c_str(), e.what());
2903                return 1;
2904            }
2905        }
2906        using RST = strata::kernels::RopeScalingType;
2907        if (!o.rope_scaling.empty()) {
2908            // the early validation pinned the spelling; `none` here is the CLI opting OUT of the model file's keys
2909            if (o.rope_scaling == "linear") rope_cfg.type = RST::Linear;
2910            else if (o.rope_scaling == "yarn") rope_cfg.type = RST::YaRN;
2911            else rope_cfg.type = RST::None;
2912        } else if (!gguf_rope_type.empty()) {
2913            if (gguf_rope_type == "linear") rope_cfg.type = RST::Linear;
2914            else if (gguf_rope_type == "yarn") rope_cfg.type = RST::YaRN;
2915            else if (gguf_rope_type != "none") {
2916                std::fprintf(stderr, "strata generate: %s carries rope.scaling.type '%s' - none, linear or yarn only\n",
2917                             o.native_preset.c_str(), gguf_rope_type.c_str());
2918                return 2;
2919            }
2920        }
2921        if (o.rope_scale > 0) rope_cfg.factor = o.rope_scale;            // an explicit factor, 1 included
2922        else if (gguf_rope_factor > 1.0) rope_cfg.factor = gguf_rope_factor;
2923        if (o.rope_freq_base > 0) rope_cfg.freq_base = o.rope_freq_base;
2924        else if (gguf_rope_base > 1.0) rope_cfg.freq_base = gguf_rope_base;
2925        if (o.yarn_orig_ctx > 0) rope_cfg.orig_ctx = o.yarn_orig_ctx;
2926        else if (gguf_rope_orig_ctx >= 1) rope_cfg.orig_ctx = gguf_rope_orig_ctx;
2927        rope_cfg.freq_scale_in = o.rope_freq_scale;
2928        rope_cfg.ext_factor = o.yarn_ext_factor >= 0 ? o.yarn_ext_factor
2929                                                     : (rope_cfg.type == RST::YaRN ? 1.0 : 0.0);
2930        rope_cfg.attn_factor = o.yarn_attn_factor;
2931        rope_cfg.beta_fast = o.yarn_beta_fast;
2932        rope_cfg.beta_slow = o.yarn_beta_slow;
2933        if (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.
2937            const bool knobs = o.rope_scale > 1.0 || o.rope_freq_scale > 0 || o.yarn_ext_factor > 0 ||
2938                               o.yarn_attn_factor != 1.0;
2939            const double base = rope_cfg.freq_base;
2940            rope_cfg = strata::kernels::RopeScaling{};
2941            rope_cfg.freq_base = base;
2942            if (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.
2949        if (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",
2952                         why, rope_cfg.type == RST::YaRN ? "yarn" : rope_cfg.type == RST::Linear ? "linear" : "none",
2953                         rope_cfg.factor, rope_cfg.freq_scale(), rope_cfg.freq_base, rope_cfg.orig_ctx);
2954            return 2;
2955        }
2956        strata::kernels::rope_scaling_set(rope_cfg);
2957        if (rope_cfg.type != RST::None) {
2958            const 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",
2962                         tn, rope_cfg.factor, rope_cfg.freq_scale(), rope_cfg.freq_base, rope_cfg.mscale(),
2963                         (long long) o.max_context, rope_cfg.orig_ctx);
2964            if ((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",
2968                             rope_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
2971            if (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",
2975                             rope_cfg.type == RST::YaRN ? "YaRN" : "--yarn-attn-factor", rope_cfg.mscale());
2976        }
2977    }
2978    strata::core::NativeEmbed native_embed;
2979    if (native_pack) {
2980        if (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());
2984            return 2;
2985        }
2986        const auto embed_t0 = std::chrono::steady_clock::now();
2987        if (!native_embed.load(o.embd_gguf.empty() ? o.native_shards : std::vector<std::string>{o.embd_gguf}, g.n_embd,
2988                               g.n_vocab, err)) {
2989            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
2990            return 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",
2995                     o.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;
3002    if (!o.keep_canonical) {
3003        if (!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());
3006            return 1;
3007        }
3008        if (!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
3010        if (!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
3012        if (native_pack && !strata::core::NativeDense::keep_unquantized_ple_key(o.pack, skip, err)) {
3013            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
3014            return 1;
3015        }
3016        if (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.
3022    const std::set<std::string> skip_base = skip;
3023    // --trim-stage-weights (PR #559) is the same switch as STRATA_STAGE_TRIM=1 (PR #639)
3024    const bool trim_asked = o.trim_stage_weights || [] {
3025        const char* v = std::getenv("STRATA_STAGE_TRIM");
3026        return 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.
3034    const bool stage_trim = trim_asked && multi_gpu && !split_auto && !split_at.empty();
3035    if (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.
3040    const 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
3044    auto 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");
3046        if (!f) return;
3047        char line[1024], name[256];
3048        while (std::fgets(line, sizeof line, f)) {
3049            if (line[0] == '#' || std::sscanf(line, "%255s", name) != 1) continue;
3050            const std::string n = name;
3051            if (n.rfind("blk.", 0) != 0 || n.find("ple") != std::string::npos) continue;
3052            if (keep_routers && n.ends_with(".ffn_gate_inp.weight")) continue;
3053            const int64_t l = std::atoll(name + 4);
3054            if (l < lb || l >= le) out.insert(n);
3055        }
3056        std::fclose(f);
3057    };
3058    if (stage_trim) {
3059        add_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    }
3064    uint64_t pool_bytes = 0;
3065    if (!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());
3067        return 1;
3068    }
3069    void* arena = nullptr;
3070    /*
3071    DPCT1000: Error handling if-stmt was detected but could not be
3072    rewritten.
3073    */
3074    if (const dpct::err0 ce =
3075            DPCT_CHECK_ERROR(arena = (void *)strata::malloc_device_guarded(
3076                                 pool_bytes, dpct::get_in_order_queue()));
3077        ce != 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        /*
3081        DPCT1026: The call to cudaGetLastError was removed because this
3082        functionality is redundant in SYCL.
3083        */
3084        /*
3085        DPCT1001: The statement could not be removed.
3086        */
3087        size_t free_b = 0, total_b = 0;
3088        /*
3089        DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions
3090        for device information which may not be supported by all compilers or
3091        runtimes. You may need to adjust the code.
3092        */
3093        dpct::get_current_device().get_memory_info(free_b, total_b);
3094        std::fprintf(
3095            stderr,
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            /*
3104            DPCT1009: SYCL reports errors using exceptions and does not use
3105            error codes. Please replace the "get_error_string_dummy(...)" with a
3106            real 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));
3111        return 1;
3112    }
3113    auto load_t0 = std::chrono::steady_clock::now();
3114    auto load_s = [&] {
3115        const auto t = std::chrono::steady_clock::now();
3116        const double s = std::chrono::duration<double>(t - load_t0).count();
3117        load_t0 = t;
3118        return s;
3119    };
3120    strata::core::WeightTable wt;
3121    if (!wt.load(o.pack, arena, pool_bytes, err, skip.empty() ? nullptr : &skip)) {
3122        std::fprintf(stderr, "strata generate: %s\n", err.c_str());
3123        return 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;
3131    if (!o.native_dense_gguf.empty()) {
3132        if (!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());
3134            return 1;
3135        }
3136        std::fprintf(stderr, "strata generate: %zu native projection matrices, %.2f MiB of weights, in %.1f s\n",
3137                     native_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() &&
3150                                     o.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.
3163    int32_t* d_mrope = nullptr;
3164    std::vector<int32_t> mrope_host;
3165    if (o.vision) {
3166        const int64_t cells = o.max_context + 64;
3167        mrope_host.resize((size_t) cells * 3);
3168        for (int64_t c = 0; c < cells; ++c)
3169            mrope_host[(size_t) c * 3] = mrope_host[(size_t) c * 3 + 1] = mrope_host[(size_t) c * 3 + 2] = (int32_t) c;
3170        if (DPCT_CHECK_ERROR(
3171                d_mrope = sycl::malloc_device<int32_t>(
3172                    mrope_host.size(), dpct::get_in_order_queue())) != 0 ||
3173            /*
3174            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
3175            assuming in the original code the source host memory is pageable
3176            memory. If the memory is not pageable, call wait() on event return
3177            by memcpy API to ensure synchronization behavior.
3178            */
3179            DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
3180                d_mrope, mrope_host.data(),
3181                mrope_host.size() * sizeof(int32_t)).wait()) != 0) {
3182            std::fprintf(stderr, "strata generate: cannot allocate the image position table\n");
3183            return 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";
3190    uint64_t cvec_digest = 0;   // a session file is bound to the loaded vector (0: none)
3191    if (!o.cvec_files.empty()) {
3192        std::string ce;
3193        if (!load_control_vectors(o, g, cvec_summary, cvec_digest, ce)) {
3194            std::fprintf(stderr, "strata generate: control vector: %s\n", ce.c_str());
3195            return 2;
3196        }
3197    }
3198    if (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);
3201        return 2;
3202    }
3203
3204    strata::core::SessionState ss;
3205    void* 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    /*
3215    DPCT1025: The SYCL queue is created ignoring the flag and priority
3216    options.
3217    */
3218    if (DPCT_CHECK_ERROR(
3219            main_stream = dpct::get_current_device().create_queue(true)) != 0) {
3220        std::fprintf(stderr, "strata generate: cannot create the main stream\n");
3221        return 1;
3222    }
3223    void* 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.
3230    const 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;
3234    float* half_stage = nullptr;
3235    if (!o.dump_halves.empty()) {
3236        half_dump = std::fopen(o.dump_halves.c_str(), "wb");
3237        if (half_dump == nullptr) {
3238            std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_halves.c_str());
3239            return 1;
3240        }
3241        const size_t n = (size_t) g.n_layers * (size_t) half_stride;
3242        /*
3243        DPCT1048: The original value cudaHostAllocDefault is not meaningful
3244        in the migrated code and was removed or replaced with 0. You may need to
3245        check the migrated code.
3246        */
3247        if (DPCT_CHECK_ERROR(half_stage = sycl::malloc_host<float>(
3248                                 n, dpct::get_in_order_queue())) != 0) {
3249            std::fprintf(stderr, "strata generate: cannot pin the half-dump staging buffer\n");
3250            return 1;
3251        }
3252        ss.block.dump = half_stage;
3253    }
3254
3255    strata::core::Doorbell db;
3256    if (strata::core::doorbell_init(g, K, db) == 0) {
3257        std::fprintf(stderr, "strata generate: doorbell_init failed\n");
3258        return 1;
3259    }
3260    ss.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);
3270    float* ple_emb_dev = nullptr;
3271    float* ple_scratch = nullptr;
3272    if (!o.ple_gguf.empty()) {
3273        strata::kernels::PleIoOptions pio;
3274        pio.mode = o.ple_io == "mmap" || o.ple_io == "ram" ? strata::kernels::PleIo::Mmap : strata::kernels::PleIo::Direct;
3275        pio.lock = o.ple_io == "ram";
3276        const auto tpl = Clock::now();
3277        pio.max_inflight = (uint32_t) o.ple_inflight;
3278        pio.cache_rows = (uint64_t) o.ple_row_cache;
3279        pio.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        {
3285            const char* ka = std::getenv("STRATA_SSD_KEEPALIVE");
3286            const char* kw = std::getenv("STRATA_SSD_KEEPALIVE_WINDOW");
3287            pio.keepalive_ms = ka != nullptr && *ka ? std::clamp(std::atof(ka), 0.0, 10000.0) : 100.0;
3288            pio.keepalive_window_s = kw != nullptr && *kw ? std::clamp(std::atof(kw), 1.0, 86400.0) : 60.0;
3289            if (pio.mode != strata::kernels::PleIo::Direct || !pio.io_thread) pio.keepalive_ms = 0;
3290        }
3291        if (!ple_table.open(o.ple_gguf, err, pio)) {
3292            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
3293            return 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.
3297        if (pio.mode == strata::kernels::PleIo::Direct && std::getenv("STRATA_PLE_PROBE") == nullptr) {
3298            constexpr double kSlowRowsPerS = 15000.0;   // ~60 MB/s of 4 KiB pages; a healthy NVMe is >100k
3299            const double rps = ple_direct_rows_per_s(ple_table);
3300            if (rps >= kSlowRowsPerS)
3301                std::fprintf(stderr, "strata generate: PLE direct read probe: %.0f rows/s (fine)\n", rps);
3302            if (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.
3307                bool auto_mmap = !o.ple_io_explicit;
3308                if (const char* am = std::getenv("STRATA_PLE_AUTO_MMAP"); am == nullptr || std::atoi(am) == 0) auto_mmap = false;
3309                if (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",
3313                                 rps, rps * 4096.0 / 1e6);
3314                    ple_table.close();
3315                    pio.mode = strata::kernels::PleIo::Mmap;
3316                    pio.keepalive_ms = 0;
3317                    if (!ple_table.open(o.ple_gguf, err, pio)) {
3318                        std::fprintf(stderr, "strata generate: %s\n", err.c_str());
3319                        return 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,
3326                                 o.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)
3331        if (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;
3335            if (!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
3342        if (pio.lock)
3343            std::fprintf(stderr, "strata generate: PLE table %s (--ple-io ram) in %.1f s\n",
3344                         ple_table.locked() ? "locked in RAM" : "loaded (not locked)",
3345                         std::chrono::duration<double>(Clock::now() - tpl).count());
3346        if (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);
3350        else 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");
3352        const strata::core::WeightRef* wk = wt.find("blk.1.ple_key.weight");
3353        const strata::core::WeightRef* wv = wt.find("blk.1.ple_value.weight");
3354        const strata::core::WeightRef* wnk = wt.find("blk.1.ple_norm_key.weight");
3355        const strata::core::WeightRef* wnq = wt.find("blk.1.ple_norm_query.weight");
3356        const strata::core::WeightRef* wnc = wt.find("blk.1.ple_norm_conv.weight");
3357        const strata::core::WeightRef* wc = wt.find("blk.1.ple_conv1d.weight");
3358        if (!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");
3361            return 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.
3365        if (!wk->quantized()) {
3366            // plan v0.3 P6: the IQ model files' BF16 key (the pack's extra.bin, raw BF16)
3367            ss.ple.w.key_bf16 = (const uint16_t*) wk->data;
3368        } else if (wk->data != nullptr) {
3369            ss.ple.w.key_codes = (const uint8_t*) wk->data;
3370            ss.ple.w.key_scales = (const float*) ((const uint8_t*) wk->data + wk->codes_bytes);
3371        }
3372        if (o.native_ple_key && wk->quantized()) {
3373            if (!wk->native_data || (wk->native_type != 42 && wk->native_type != 18 && wk->native_type != 23 &&
3374                                     wk->native_type != 8) || !wk->native_q8_1) {
3375                std::fprintf(stderr, "strata generate: native PLE key is absent or incompatible\n");
3376                return 1;
3377            }
3378            ss.ple.w.key_native_data = wk->native_data;
3379            ss.ple.w.key_native_type = wk->native_type;
3380            ss.ple.w.key_native_q8_1 = wk->native_q8_1;
3381        }
3382        ss.ple.w.value_bf16 = (const uint16_t*) wv->data;
3383        ss.ple.w.norm_key = (const float*) wnk->data;
3384        ss.ple.w.norm_query = (const float*) wnq->data;
3385        ss.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.
3391        const bool f16 = wc->kind == strata::core::WeightKind::F16InF32 ||
3392                         (wc->kind == strata::core::WeightKind::Verbatim && wc->code_bits == 0);
3393        if (!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);
3398            return 1;
3399        }
3400        ss.ple.w.conv1d_f16 = (const uint16_t*) wc->data;
3401        ss.ple.consts = ple_consts_run;
3402        for (int h = 0; h < strata::kernels::PLE_N_HEADS; ++h) {   // the hash may only reach rows the table has
3403            if (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",
3405                             h, (unsigned long long) (ple_consts_run.offset[h] + ple_consts_run.vocab[h]), (unsigned long long) ple_table.rows());
3406                return 1;
3407            }
3408        }
3409        if (o.ple_delay_us > 0) ple_table.set_injected_delay_us(o.ple_delay_us);
3410        ss.ple.table = &ple_table;
3411        ss.ple.token = &ss.ple_token;
3412        ss.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
3415        ss.ple.emb_host = ple_emb_host.data();
3416        if (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 ||
3419            DPCT_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");
3423            return 1;
3424        }
3425        ss.ple.emb_dev = ple_emb_dev;
3426        ss.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
3433    float* d_parts = nullptr;
3434    if (DPCT_CHECK_ERROR(
3435            d_parts = (float *)sycl::malloc_device(
3436                (size_t)K * g.n_embd * 4, dpct::get_in_order_queue())) != 0 ||
3437        DPCT_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");
3441        return 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.
3448    if (multi_gpu && split_auto && o.split_skip_if_fits) {
3449        std::vector<std::pair<int32_t, int32_t>> prof;
3450        int64_t pslots = 0;
3451        std::string perr;
3452        const bool remote = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0;
3453        if (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",
3456                         remote ? "remote expert caches are in use" : perr.empty() ? "no expert profile" : perr.c_str());
3457        } else {
3458            const auto& lay = strata::kernels::cpu::expert_layout();
3459            int64_t pairs_bytes = 0;
3460            for (const auto& pr : prof)
3461                pairs_bytes += native_pack ? ((int64_t) lay.blob_bytes(pr.first) + 255) / 256 * 256 : (int64_t) lay.max_blob;
3462            size_t fb = 0, tb = 0;
3463            /*
3464            DPCT1106: 'cudaMemGetInfo' was migrated with the Intel
3465            extensions for device information which may not be supported by all
3466            compilers or runtimes. You may need to adjust the code.
3467            */
3468            dpct::get_current_device().get_memory_info(fb, tb);
3469            const int64_t session = (int64_t) strata::core::session_bytes(g, o.max_context, K, 0, g.n_layers);
3470            const int64_t held_back = session + (((int64_t) o.vram_reserve_mib + 1000 + 96) << 20);   // + drafter/head, windows
3471            const int64_t room = (int64_t) fb - held_back;
3472            dpct::device_info dp{};
3473            dpct::get_device(0).get_device_info(dp);
3474            if (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",
3482                             dp.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);
3488                multi_gpu = false;
3489                split_auto = false;
3490                split_devs.clear();
3491                split_at.clear();
3492                o.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",
3500                             dp.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.
3516    if (o.pipeline_windows < 0) {
3517        static const char* ae = std::getenv("STRATA_PIPELINE_AUTO");
3518        const auto battlemage = [](int d) -> bool {
3519            try {
3520                return strata::intel_gpu_gen(dpct::get_device(d)) == strata::IntelGpuGen::Battlemage;
3521            } catch (...) {
3522                return false;
3523            }
3524        };
3525        strata::PipelineAutoInputs in;
3526        in.serve = o.serve; in.multi_gpu = multi_gpu; in.split_same = split_same;
3527        in.later_stages = (unsigned) split_devs.size();
3528        in.auto_off = ae != nullptr && std::atoi(ae) == 0;
3529        in.has_mtp = !o.mtp.empty(); in.spec = o.spec; in.batch = o.batch;
3530        in.peer_device = o.peer_device >= 1;     // the same test as the validation below
3531        in.helper_caches = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0;
3532        if (split_devs.size() == 1) {            // the devices are looked at only for a split the pipeline could take
3533            in.first_is_battlemage = battlemage(0);
3534            in.later_is_battlemage = battlemage(split_devs[0]);
3535        }
3536        const bool on = strata::pipeline_auto_on(in);
3537        o.pipeline_windows = on ? 2 : 0;
3538        if (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    }
3542    if (o.pipeline_windows > 0) {
3543        const bool helpers = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0;
3544        const 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;
3553        if (off != nullptr) {
3554            std::fprintf(stderr, "strata generate: --pipeline-windows %d is off: %s\n", o.pipeline_windows, off);
3555            o.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).
3562    auto load_stage_weights = [&](GpuStage &st, int64_t lb, int64_t le,
3563                                  bool trim) -> bool {
3564        try {
3565    std::set<std::string> skip_s = skip_base;
3566        uint64_t pool_s = pool_bytes;
3567        if (trim) {
3568            add_foreign(lb, le, skip_s, false);
3569            strata::core::NativeDense::set_layer_range((int) lb, (int) le);
3570            if (!strata::core::WeightTable::pool_bytes(o.pack, pool_s, err, &skip_s)) {
3571                std::fprintf(stderr, "strata generate: %s\n", err.c_str());
3572                return false;
3573            }
3574            std::fprintf(stderr, "strata generate: layer split: CUDA%d loads the dense weights of layers %lld-%lld only\n",
3575                         st.dev, (long long) lb, (long long) le - 1);
3576        } else {
3577            skip_s = skip;
3578        }
3579        void* arena_s = nullptr;
3580        if (DPCT_CHECK_ERROR(arena_s = (void *)strata::malloc_device_guarded(
3581                                 pool_s, dpct::get_in_order_queue())) != 0 ||
3582            !st.wt.load(o.pack, arena_s, pool_s, err,
3583                        skip_s.empty() ? nullptr : &skip_s)) {
3584            /*
3585            DPCT1026: The call to cudaGetLastError was removed because this
3586            functionality is redundant in SYCL.
3587            */
3588            size_t free_b = 0, total_b = 0; // #486: what that card had free
3589            /*
3590            DPCT1106: 'cudaMemGetInfo' was migrated with the Intel
3591            extensions for device information which may not be supported by all
3592            compilers 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,
3597                         err.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));
3600            return false;
3601        }
3602        if (!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,
3604                         err.c_str());
3605            return false;
3606        }
3607        return true;
3608    }
3609    catch (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    };
3615    for (size_t i = 0; multi_gpu && i < split_devs.size(); ++i) {
3616        stages.push_back(std::make_unique<GpuStage>());
3617        GpuStage& st = *stages.back();
3618        st.dev = split_devs[i];
3619        double free_gib = 0;
3620        if (!strata::core::RemoteExperts::preflight(st.dev, free_gib, err)) {
3621            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
3622            return 1;
3623        }
3624        const 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.
3627        if (!late_weights) {
3628            const int64_t lb = stage_trim ? split_at[i] : 0;
3629            const int64_t le = stage_trim ? (i + 1 < split_at.size() ? split_at[i + 1] : g.n_layers) : 0;
3630            if (!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        /*
3636        DPCT1025: The SYCL queue is created ignoring the flag and priority
3637        options.
3638        */
3639        if (DPCT_CHECK_ERROR(
3640                st.stream = dpct::get_current_device().create_queue(true)) !=
3641                0 ||
3642            /*
3643            DPCT1025: The SYCL queue is created ignoring the flag and
3644            priority options.
3645            */
3646            DPCT_CHECK_ERROR(
3647                st.adapt_stream =
3648                    dpct::get_current_device().create_queue(true)) != 0 ||
3649            DPCT_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);
3651            return 1;
3652        }
3653        // a control vector (the speed projection): its tables on this device too - the stage's layers apply it here
3654        if (!strata::kernels::cvec_replicate(err)) {
3655            std::fprintf(stderr, "strata generate: layer split, CUDA%d: %s\n", st.dev, err.c_str());
3656            return 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
3660        if (o.vision) {
3661            if (DPCT_CHECK_ERROR(
3662                    st.mrope = sycl::malloc_device<int32_t>(
3663                        mrope_host.size(), dpct::get_in_order_queue())) != 0 ||
3664                /*
3665                DPCT1114: cudaMemcpy is migrated to asynchronization
3666                memcpy, assuming in the original code the source host memory is
3667                pageable memory. If the memory is not pageable, call wait() on
3668                event return by memcpy API to ensure synchronization behavior.
3669                */
3670                DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
3671                    st.mrope, mrope_host.data(),
3672                    mrope_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);
3674                return 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.
3680        st.pcie_frac = o.pcie_frac;
3681        if (!pcie_given && native_pack) {
3682            std::string bursts;
3683            const double bw = probe_pcie_h2d_gbps(&bursts, true);
3684            if (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        }
3688        if (!late_weights) {
3689            size_t fb = 0, tb = 0;
3690            /*
3691            DPCT1106: 'cudaMemGetInfo' was migrated with the Intel
3692            extensions for device information which may not be supported by all
3693            compilers 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    }
3700    GpuStage* const last_st = stages.empty() ? nullptr : stages.back().get();
3701
3702    std::vector<std::pair<int32_t, int32_t>> profile;
3703    if (!o.expert_profile.empty()) {
3704        int64_t pslots = 0;
3705        if (!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());
3707            return 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.
3712        if (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.
3718        if (o.peer_device >= 1) {   // default 0.45 (measured: 0.3-0.6 all better than 0; 0 = off, e.g. for the gate)
3719            const char* ph = std::getenv("STRATA_PEER_HOT");
3720            const double f = ph ? std::atof(ph) : 0.45;
3721            const char* pa = std::getenv("STRATA_PEER_HOT_AT");
3722            const size_t at = std::min(profile.size(), (size_t) (pa ? std::atoll(pa) : 8700));
3723            if (f > 0.0 && f < 1.0 && at > 0) {
3724                std::vector<std::pair<int32_t, int32_t>> keep, moved;
3725                for (size_t r = 0; r < at; ++r) {
3726                    const bool to_peer = (int64_t) ((double) (r + 1) * f) > (int64_t) ((double) r * f);
3727                    (to_peer ? moved : keep).push_back(profile[r]);
3728                }
3729                const 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;
3732                out.reserve(profile.size());
3733                out.insert(out.end(), keep.begin(), keep.end());
3734                const size_t fill = std::min(profile.size(), at + n_moved);   // what the primary still takes
3735                out.insert(out.end(), profile.begin() + (long) at, profile.begin() + (long) fill);
3736                out.insert(out.end(), moved.begin(), moved.end());
3737                out.insert(out.end(), profile.begin() + (long) fill, profile.end());
3738                profile.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",
3745                     o.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;
3750    if (!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.
3772    const 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)
3776    const 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;
3780    if (split_ring_mib > 0) strata::prefill::Prefill::set_ring_override(96);
3781    const 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.
3790    const int64_t kWindowMib = 96;       // the verify windows; 75 MiB measured, rounded up
3791    const 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.
3796    const int64_t kPipeWindowMib = o.pipeline_windows > 0 ? 160 : 0;
3797    const int64_t kPipeSnapMib = o.pipeline_windows >= 2 ? 96 : 0;   // ~3 MiB per GDN layer, twice, ~15 layers
3798    auto gdn_snapshot_bytes = [&](const strata::core::SessionState& s0) -> size_t {
3799        return (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);
3812    if (late_weights)
3813        for (size_t i = 1; i < stage_pool.size(); ++i) stage_pool[i] = pool_bytes;
3814    static const bool place_with_reserve = [] {
3815        const char* v = std::getenv("STRATA_SPLIT_OWN_PLACE");
3816        return v != nullptr && std::string(v) == "reserve";
3817    }();
3818    auto stage_room = [&](int dev, bool later, bool drafter,
3819                          bool search = false) -> int64_t {
3820        try {
3821    const strata::core::OnDevice on(dev);
3822        size_t fb = 0, tb = 0;
3823        dpct::get_current_device().get_memory_info(fb, tb);   // #423 (tmking01): dpct dropped cudaMemGetInfo here
3824        /*
3825        DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions
3826        for device information which may not be supported by all compilers or
3827        runtimes. You may need to adjust the code.
3828        */
3829
3830        const int64_t pf = search && split_own_auto && !place_with_reserve ? 0 : split_pf_mib;
3831        const int64_t base_reserve =
3832            later && o.vram_reserve_later_mib >= 0 ? o.vram_reserve_later_mib : o.vram_reserve_mib;
3833        const int64_t reserve = (base_reserve + pf + (later ? kWindowMib : kPipeSnapMib) +
3834                                 kPipeWindowMib + (drafter ? kDrafterMib : 0)) << 20;
3835        return std::max<int64_t>((int64_t) fb - reserve, 0);
3836    }
3837    catch (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    };
3843    if (multi_gpu && split_auto) {
3844        const auto& lay = strata::kernels::cpu::expert_layout();
3845        const 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);
3848        for (int i = 0; i < ns; ++i) {
3849            const int dev = i == 0 ? 0 : stages[(size_t) i - 1]->dev;
3850            cap[(size_t) i] = stage_room(i == 0 ? -1 : dev, i > 0, i + 1 == ns, true);
3851            if (late_weights) cap[(size_t) i] = std::max<int64_t>(cap[(size_t) i] - (int64_t) stage_pool[(size_t) i], 0);
3852            int sms = 0, khz = 0;
3853            sms = dpct::get_device(dev).get_max_compute_units();
3854            if (DPCT_CHECK_ERROR(
3855                    khz = dpct::get_device(dev).get_max_clock_frequency()) !=
3856                    0 ||
3857                khz <= 0) khz = 1800000;
3858            /*
3859            DPCT1026: The call to cudaGetLastError was removed because this
3860            functionality is redundant in SYCL.
3861            */
3862            const double speed =
3863                std::max(1.0, (double)sms * (double)khz / 1e6); // SMs x GHz
3864            layer_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        }
3869        const 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.
3894        const size_t n_ranked = profile.size();
3895        const 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);
3897        double 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.
3901        const bool coverage_curve = ns >= 4 || std::getenv("STRATA_SPLIT_COVER_B") != nullptr;
3902        for (size_t r = 0; r < n_ranked; ++r) {
3903            if (!coverage_curve) {
3904                total_mass += (mass[r] = std::pow((double) r + 1.0, -1.2));
3905                continue;
3906            }
3907            const double hi = std::pow(1.0 - (double) r / (double) n_ranked, cover_b);
3908            const double lo = std::pow(1.0 - (double) (r + 1) / (double) n_ranked, cover_b);
3909            total_mass += (mass[r] = hi - lo);
3910        }
3911        auto cost = [&](int64_t l) -> int64_t {
3912            return 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
3915        auto 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);
3920            for (int i = 0; i < ns; ++i) {
3921                const int64_t lb = i == 0 ? 0 : at[(size_t) i - 1];
3922                const int64_t le = i + 1 < ns ? at[(size_t) i] : g.n_layers;
3923                capr[(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);
3926            held_mass = 0;
3927            held = 0;
3928            std::vector<bool> full((size_t) ns, false);
3929            for (size_t r = 0; r < profile.size(); ++r) {
3930                const int64_t l = profile[r].first;
3931                int st = 0;
3932                while (st + 1 < ns && l >= at[(size_t) st]) ++st;
3933                if (full[(size_t) st]) continue;
3934                if (used[(size_t) st] + cost(l) > capr[(size_t) st]) { full[(size_t) st] = true; continue; }   // as the fill
3935                used[(size_t) st] += cost(l);
3936                held_mass += mass[r];
3937                ++held;
3938            }
3939            held_mass /= std::max(total_mass, 1e-9);
3940            double ms = miss_ms * (1.0 - held_mass);
3941            for (int i = 0; i < ns; ++i) {
3942                const int64_t lb = i == 0 ? 0 : at[(size_t) i - 1], le = i + 1 < ns ? at[(size_t) i] : g.n_layers;
3943                ms += (double) (le - lb) * layer_ms[(size_t) i];
3944            }
3945            return ms;
3946        };
3947        std::vector<int64_t> best, at((size_t) ns - 1);
3948        double best_ms = 1e30, best_mass = 0;
3949        int64_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.
3954        static const bool split_headroom = [] {
3955            const char* v = std::getenv("STRATA_SPLIT_HEADROOM");
3956            return v == nullptr || std::atoi(v) != 0;
3957        }();
3958        const 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);
3961        for (int64_t l = 0; l < g.n_layers; ++l)
3962            need_prefix[(size_t) l + 1] = need_prefix[(size_t) l] + (int64_t) g.n_expert * cost(l);
3963        auto range_session = [&](int64_t lb, int64_t le) -> int64_t {
3964            return (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;
3969        auto score = [&](const std::vector<int64_t>& cuts, double ms, double hm, int64_t held) {
3970            if (!split_headroom) return;
3971            scored.push_back({cuts, ms, strata::program::split_rules::min_spare(cuts, g.n_layers, cap, need_prefix,
3972                                                                                range_session)});
3973            scored_mass.push_back(hm);
3974            scored_held.push_back(held);
3975        };
3976        auto consider = [&]() {
3977            double hm = 0;
3978            int64_t held = 0;
3979            const double ms = predict(at, hm, held);
3980            ++tried;
3981            score(at, ms, hm, held);
3982            if (ms < best_ms) { best = at; best_ms = ms; best_mass = hm; best_held = held; }
3983        };
3984        const 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).
3987        auto proportional = [&]() {
3988            double total = 0;
3989            for (const double c : layer_ms) total += 1.0 / c;
3990            double acc = 0;
3991            for (int i = 0; i + 1 < ns; ++i) {
3992                acc += 1.0 / layer_ms[(size_t) i];
3993                at[(size_t) i] = std::clamp<int64_t>((int64_t) std::llround(acc / total * (double) L),
3994                                                     i == 0 ? 2 : at[(size_t) i - 1] + 1, L - (ns - 1 - i));
3995            }
3996            consider();
3997        };
3998        if (ns == 2) {
3999            for (int64_t k = 2; k < L; ++k) { at[0] = k; consider(); }
4000        } else if (ns == 3) {
4001            for (int64_t k1 = 2; k1 + 1 < L; ++k1)
4002                for (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.)
4023            const 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);
4026            auto range_hold = [&](int i, int64_t lb, int64_t le) -> size_t {
4027                const size_t key = ((size_t) i * (size_t) L + (size_t) lb) * stride + (size_t) le;
4028                if (held_mass_at[key] < 0.0) {
4029                    // one stage's own carve, exactly as `predict` prices it
4030                    const int64_t room = cap[(size_t) i] -
4031                        (int64_t) strata::core::session_bytes(g, o.max_context, K, lb, le);
4032                    double hm = 0;
4033                    int64_t used = 0, cnt = 0;
4034                    for (size_t r = 0; r < profile.size(); ++r) {
4035                        const int64_t l = profile[r].first;
4036                        if (l < lb || l >= le) continue;
4037                        if (used + cost(l) > room) break;   // the fill stops exactly where predict's does
4038                        used += cost(l);
4039                        hm += mass[r];
4040                        ++cnt;
4041                    }
4042                    held_mass_at[key] = hm;
4043                    held_at[key] = cnt;
4044                }
4045                return key;
4046            };
4047            const double denom = std::max(total_mass, 1e-9);
4048            for (int64_t k1 = 2; k1 + 2 < L; ++k1)
4049                for (int64_t k2 = k1 + 1; k2 + 1 < L; ++k2)
4050                    for (int64_t k3 = k2 + 1; k3 < L; ++k3) {
4051                        const size_t a = range_hold(0, 0, k1), b = range_hold(1, k1, k2);
4052                        const size_t c = range_hold(2, k2, k3), d = range_hold(3, k3, L);
4053                        const double hm = held_mass_at[a] + held_mass_at[b] + held_mass_at[c] + held_mass_at[d];
4054                        const 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;
4058                        score({k1, k2, k3}, ms, hm / denom, held_at[a] + held_at[b] + held_at[c] + held_at[d]);
4059                        if (ms < best_ms) {
4060                            best = {k1, k2, k3};
4061                            best_ms = ms;
4062                            best_mass = hm / denom;
4063                            best_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.
4068            if (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.
4072            proportional();
4073        }
4074        if (split_headroom && scored.size() > 1) {
4075            const size_t first = strata::program::split_rules::fastest(scored);
4076            const size_t pick = strata::program::split_rules::pick_with_headroom(scored, headroom_tol);
4077            if (pick != first && scored[first].cuts == best) {
4078                auto fmt_k = [](const std::vector<int64_t>& v) {
4079                    std::string s;
4080                    for (const int64_t k : v) s += (s.empty() ? "" : ",") + std::to_string(k);
4081                    return 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",
4086                             fmt_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());
4089                best = scored[pick].cuts;
4090                best_ms = scored[pick].ms;
4091                best_mass = scored_mass[pick];
4092                best_held = scored_held[pick];
4093            }
4094        }
4095        split_at = best;
4096        std::string ks;
4097        for (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",
4100                     ks.c_str(), best_ms, (long long) best_held, profile.size(), 100.0 * best_mass, (long long) tried);
4101    }
4102    for (size_t i = 0; i < split_at.size(); ++i)
4103        if (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));
4106            return 2;
4107        }
4108    // the stage that runs a layer (0: CUDA0's)
4109    auto stage_of = [&](int64_t l) -> int {
4110        int st = 0;
4111        while (st < (int) split_at.size() && l >= split_at[(size_t) st]) ++st;
4112        return 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;
4118    if (multi_gpu) {
4119        profile_all = profile;
4120        std::vector<std::pair<int32_t, int32_t>> mine;
4121        for (const auto& pr : profile) {
4122            const int st = stage_of(pr.first);
4123            (st == 0 ? mine : stages[(size_t) st - 1]->profile).push_back(pr);
4124        }
4125        profile.swap(mine);
4126        for (size_t i = 0; i < stages.size(); ++i) {
4127            stages[i]->lb = split_at[i];
4128            stages[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`).
4136    if (late_weights)
4137        for (size_t i = 0; i < stages.size(); ++i) {
4138            GpuStage& st = *stages[i];
4139            const strata::core::OnDevice on(st.dev);
4140            if (!load_stage_weights(st, st.lb, st.le, true)) return 1;
4141            size_t fb = 0, tb = 0;
4142            /*
4143            DPCT1106: 'cudaMemGetInfo' was migrated with the Intel
4144            extensions for device information which may not be supported by all
4145            compilers 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.
4160    if (o.kv_resident <= 0 && o.max_context > 20480 && !multi_gpu && !o.kv_grow && o.expert_cache != 0) {
4161        const 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
4162        const int64_t blob_b = (int64_t) strata::kernels::cpu::expert_layout().max_blob;
4163        const int64_t n_sess = 1 + std::max(o.batch, 0);
4164        const int64_t reserve_b = (int64_t) (o.vram_reserve_given ? o.vram_reserve_mib : std::min(o.vram_reserve_mib, 300)) << 20;
4165        const int64_t fixed_b = (kLateLoadMib << 20) + reserve_b + ((160 + (256 * 680) / 1024) << 20) + 128 * blob_b;
4166        size_t free_k = 0, total_k = 0;
4167        free_k = strata::core::device_free_bytes(); (void) total_k;
4168        auto need_at = [&](int64_t res) -> int64_t {
4169            strata::core::qsa_set_kv_resident(res);
4170            return n_sess * (int64_t) strata::core::session_bytes(g, o.max_context, K, 0, g.n_layers) + fixed_b;
4171        };
4172        int64_t pick = strata::core::pick_kv_resident(o.max_context, (int64_t) free_k, need_at);
4173        if (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
4175            int64_t host_avail = -1;
4176            if (std::FILE* mf = std::fopen("/proc/meminfo", "r")) {
4177                char line[256];
4178                while (std::fgets(line, sizeof(line), mf)) {
4179                    long long kb = 0;
4180                    if (std::sscanf(line, "MemAvailable: %lld kB", &kb) == 1) { host_avail = (int64_t) kb << 10; break; }
4181                }
4182                std::fclose(mf);
4183            }
4184            const int64_t host_need = n_sess * (int64_t) o.max_context * 13 * 1056 + (6ll << 30);
4185            if (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);
4188                pick = 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        }
4195        o.kv_resident = pick;
4196        strata::core::qsa_set_kv_resident(o.kv_resident);
4197    }
4198    {
4199        const strata::core::OnDevice on0(0);
4200        const 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        {
4204            const char* ev = std::getenv("STRATA_KV_GROW");
4205            bool remote = false;
4206            for (const int r : o.expert_cache_remote) remote = remote || r > 0;
4207            const bool asked = ev != nullptr && ev[0] != '\0' ? ev[0] != '0' : o.kv_grow;
4208            const 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
4212                            o.batch == 0 && !o.vram_elastic && o.peer_device < 0;
4213            if (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");
4216            const 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        }
4220        if (DPCT_CHECK_ERROR(
4221                sbuf = (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");
4225            return 1;
4226        }
4227        if (strata::core::session_init(g, o.max_context, K, sbuf, ss, 0, hi0) == 0) {
4228            std::fprintf(stderr, "strata generate: session_init failed\n");
4229            return 1;
4230        }
4231        if (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
4237        ss.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);
4241        if (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");
4244            return 1;
4245        }
4246        if (!o.ple_gguf.empty()) {
4247            if (!ss.ple.ready()) {
4248                std::fprintf(stderr, "strata generate: the PLE run is not ready after construction\n");
4249                return 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    }
4255    for (size_t i = 0; i < stages.size(); ++i) {
4256        GpuStage& st = *stages[i];
4257        const strata::core::OnDevice on(st.dev);
4258        void* sbuf_s = nullptr;
4259        if (DPCT_CHECK_ERROR(sbuf_s = (void *)sycl::malloc_device(
4260                                 strata::core::session_bytes(g, o.max_context,
4261                                                             K, 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,
4264                                       st.lb, st.le) == 0) {
4265            std::fprintf(stderr, "strata generate: layer split, CUDA%d: the session state failed\n", st.dev);
4266            return 1;
4267        }
4268        const bool last = i + 1 == stages.size();
4269        const strata::core::WeightRef* wo_s = st.wt.find("output.weight");
4270        if (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,
4273                         wo_s == nullptr ? "output.weight is missing" : err.c_str(),
4274                         wo_s == nullptr ? "" : vram_free_note().c_str());
4275            return 1;
4276        }
4277        size_t fb = 0, tb = 0;
4278        /*
4279        DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions
4280        for device information which may not be supported by all compilers or
4281        runtimes. 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,
4286                     last ? " 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.
4295    const char* batch_mtp_env = std::getenv("STRATA_BATCH_MTP");
4296    bool batch_mtp = o.batch_mtp || (batch_mtp_env != nullptr && batch_mtp_env[0] != '\0' && batch_mtp_env[0] != '0');
4297    if (batch_mtp) {
4298        const 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;
4301        if (why != nullptr) {
4302            std::fprintf(stderr, "strata generate: WARNING: --batch-mtp is off: %s\n", why);
4303            batch_mtp = false;
4304        }
4305    }
4306    std::vector<std::vector<std::unique_ptr<strata::core::SessionState>>> bslot_ss;
4307    if (o.batch != 0) {
4308        const int cap = strata::kernels::kVerifyMaxT;
4309        const 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;
4311        if (off != nullptr) {
4312            std::fprintf(stderr, "strata generate: WARNING: --batch %d is off: %s\n", o.batch, off);
4313            o.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);
4317            o.batch = cap;
4318        }
4319    }
4320    if (o.batch > 0 && o.batch_groups <= 0) {   // not given, or `auto`
4321        const bool given_auto = o.batch_groups < 0;
4322        int g = 1;
4323        if (!stages.empty()) {
4324            const auto battlemage = [](int d) -> bool {
4325                try { return strata::intel_gpu_gen(dpct::get_device(d)) == strata::IntelGpuGen::Battlemage; } catch (...) { return false; }
4326            };
4327            const bool two_b = stages.size() == 1 && battlemage(0) && battlemage(stages[0]->dev);
4328            static const char* ga = std::getenv("STRATA_BATCH_GROUPS_AUTO");
4329            const bool off = ga != nullptr && std::atoi(ga) == 0;
4330            if (two_b && o.batch >= 8 && o.batch % 2 == 0 && !off) {
4331                g = 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) {
4335                for (int d = 2; d <= (int) stages.size() + 1 && d <= o.batch; ++d)
4336                    if (o.batch % d == 0) g = d;
4337            }
4338        }
4339        o.batch_groups = g;
4340    }
4341    if (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);
4344        o.batch_groups = 1;
4345    }
4346    if (o.batch > 0) {
4347        bslot_ss.resize(1 + stages.size());
4348        int fit = o.batch;   // the slots every stage could carve
4349        uint64_t bytes0 = 0;
4350        for (size_t k = 0; k < bslot_ss.size(); ++k) {
4351            const int dev = k == 0 ? 0 : stages[k - 1]->dev;
4352            const int64_t lo = k == 0 ? 0 : stages[k - 1]->lb;
4353            const int64_t hi = k == 0 ? (multi_gpu ? split_at[0] : -1) : stages[k - 1]->le;
4354            const strata::core::OnDevice on_k(dev);
4355            const uint64_t bytes = strata::core::session_bytes(g, o.max_context, K, lo, hi);
4356            if (k == 0) bytes0 = bytes;
4357            for (int b = 0; b < fit; ++b) {
4358                auto u = std::make_unique<strata::core::SessionState>();
4359                void* buf = nullptr;
4360                if (DPCT_CHECK_ERROR(buf = (void *)sycl::malloc_device(
4361                                         bytes, dpct::get_in_order_queue())) !=
4362                        0 ||
4363                    strata::core::session_init(g, o.max_context, K, buf, *u, lo,
4364                                               hi) == 0) {
4365                    /*
4366                    DPCT1026: The call to cudaGetLastError was removed
4367                    because this functionality is redundant in SYCL.
4368                    */
4369                    if (buf != nullptr)
4370                        sycl::free(buf, dpct::get_in_order_queue());
4371                    size_t fb = 0, tb = 0;
4372                    /*
4373                    DPCT1106: 'cudaMemGetInfo' was migrated with the Intel
4374                    extensions for device information which may not be supported
4375                    by all compilers or runtimes. You may need to adjust the
4376                    code.
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");
4382                    fit = b;
4383                    break;
4384                }
4385                strata::core::session_zero(*u, g, nullptr, nullptr);
4386                bslot_ss[k].push_back(std::move(u));
4387            }
4388            dpct::get_current_device().queues_wait_and_throw();
4389            size_t fb = 0, tb = 0;
4390            /*
4391            DPCT1106: 'cudaMemGetInfo' was migrated with the Intel
4392            extensions for device information which may not be supported by all
4393            compilers 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        }
4399        for (auto& v : bslot_ss) if ((int) v.size() > fit) v.resize((size_t) fit);   // the same count on every stage
4400        if (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");
4403            bslot_ss.clear();
4404            o.batch = 0;
4405        } else {
4406            o.batch = fit;
4407            if (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;
4420    bool use_df2 = false;
4421    std::string df2_vocab_file;
4422    if (o.draft == "dflash2") {
4423        if ((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");
4425            return 2;
4426        }
4427        df2_vocab_file = o.mtp_draft_vocab.empty() ? o.mtp + "/draft_vocab.bin" : o.mtp_draft_vocab;
4428        o.mtp.clear();
4429        if (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);
4431            o.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");
4435        return 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
4440    static const strata::core::ModelGeometry draft_geometry = strata::core::kCompiledGeometry;
4441    std::vector<std::unique_ptr<strata::core::MtpDrafter>> slot_mtp;
4442    if (!o.mtp.empty()) {
4443        if (o.spec < 2) {
4444            std::fprintf(stderr, "strata generate: --mtp is ignored without --spec T (T >= 2)\n");
4445            o.mtp.clear();
4446        }
4447        if (!o.mtp.empty()) mtp.set_prompt_len((int64_t) o.tokens.size());
4448        mtp.set_hnorm_per_stream(o.mtp_hnorm_stream);   // --mtp-hnorm stream (opt-in), before any capture
4449        mtp.set_q4(o.mtp_q4 == "all" || o.mtp_q4 == "proj", o.mtp_q4 == "all" || o.mtp_q4 == "head");   // before load
4450        if (!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
4454        const 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
4457        const int mtp_t = o.pipeline_windows >= 2 ? strata::kernels::kVerifyMaxT : o.spec;
4458        if (o.pipeline_windows >= 2) mtp.set_force_capture(true);
4459        if (!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; }
4460        mtp.set_ple_session(&ss);
4461        if (batch_mtp) {
4462            for (int b = 0; b < o.batch; ++b) {
4463                auto d = std::make_unique<strata::core::MtpDrafter>();
4464                if (!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(),
4466                                 vram_free_note().c_str());
4467                    return 1;
4468                }
4469                d->set_max_drafts(1);   // the first candidate verifies one proposal per slot
4470                d->set_ple_session(bslot_ss[0][(size_t) b].get());
4471                slot_mtp.push_back(std::move(d));
4472            }
4473        }
4474    }
4475    if (o.draft == "dflash2") {
4476        if (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");
4478            return 2;
4479        }
4480        if (!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",
4482                         err.c_str(), vram_free_note().c_str());
4483            return 1;
4484        }
4485        use_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).
4493    const strata::core::WeightRef* wo = wt.find("output.weight");
4494    if (wo == nullptr) { std::fprintf(stderr, "strata generate: output.weight is missing\n"); return 1; }
4495    const int64_t n_vocab = wo->ne1;
4496    strata::core::NativeHead native_head;
4497    if (!o.native_head_gguf.empty() && !multi_gpu) {   // a layer split's head is on its last stage
4498        const auto head_t0 = std::chrono::steady_clock::now();
4499        if (!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());
4501            return 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);
4509    if(strata::kernels::b60_layout_requested()&&strata::kernels::b60_single_actor_requested()){
4510        const char* nh=std::getenv("STRATA_VERIFY_NO_HOST");
4511        const char* dp=std::getenv("STRATA_VERIFY_DEVICE_PLAN");
4512        const char* pr=std::getenv("STRATA_PRIVATE_PACKED_REGISTER");
4513        if(!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)
4514            throw std::invalid_argument("B60 single layout requires the fixed single-device no-host decode scene");
4515        b60_layouts.prepare_single(wt,native_head,strata::kernels::cpu::expert_layout());
4516    }
4517    std::vector<float> logits((size_t) n_vocab);
4518    float* d_logits = nullptr;
4519    if (DPCT_CHECK_ERROR(
4520            d_logits = (float *)sycl::malloc_device(
4521                (size_t)n_vocab * 4, dpct::get_in_order_queue())) != 0) {
4522        /*
4523        DPCT1010: SYCL uses exceptions to report errors and does not use
4524        the error codes. The cudaGetLastError function call was replaced with 0.
4525        You 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());
4529        return 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.
4533    for (int r = 1; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0 && !early_remote) {
4534        double free_gib = 0;
4535        if (!strata::core::RemoteExperts::preflight(remote_dev[r], free_gib, err)) {
4536            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
4537            return 1;
4538        }
4539        std::fprintf(stderr, "strata generate: CUDA%d context ready, %.2f GiB free before expert arena registration\n",
4540                     remote_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
4566        int dev = 0;
4567        dpct::device_info p{};
4568        const bool named =
4569            DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()) == 0 &&
4570            DPCT_CHECK_ERROR(dpct::get_device(dev).get_device_info(p)) == 0;
4571        /*
4572        DPCT1010: SYCL uses exceptions to report errors and does not use
4573        the error codes. The cudaGetLastError function call was replaced with 0.
4574        You need to rewrite this code.
4575        */
4576        if (!named) 0;
4577        const char *name =
4578            named && 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
4583        if (HMODULE h = GetModuleHandleA("amdhip64_7.dll")) {
4584            char path[MAX_PATH] = {};
4585            if (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(
4591            stderr, "strata generate: GPU %d: %s, compute capability %d.%d%s\n",
4592            dev, name,
4593            /*
4594            DPCT1005: The SYCL device version is different from CUDA
4595            Compute 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
4604        const std::string e = strata::core::device_code_error();
4605        if (!e.empty()) {
4606            std::fprintf(
4607                stderr,
4608                "strata generate: this engine has no code for %s (sm_%d%d): %s "
4609                "- rebuild it for this "
4610                /*
4611                DPCT1005: The SYCL device version is different from CUDA
4612                Compute Compatibility. You may need to rewrite this code.
4613                */
4614                "card (setup does: START-HERE.bat --setup)\n",
4615                name, p.get_major_version(), p.get_minor_version(), e.c_str());
4616            return 1;
4617        }
4618    }
4619    strata::core::ArenaExpertSource arena_src;
4620    strata::core::GgufExpertSource gguf_src;
4621    strata::core::ExpertSource* srcp = nullptr;
4622    if (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).
4626        if (!native_pack || o.native_preset.empty()) {
4627            std::fprintf(stderr, "strata generate: --stream-experts needs a native (IQ) pack and --native SHARD1\n");
4628            return 2;
4629        }
4630        if (!gguf_src.open(o.native_preset, g.n_layers, g.n_expert, err)) {
4631            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
4632            return 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");
4636        srcp = &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
4644        src.set_gguf(o.native_preset);
4645        if (const char* v = std::getenv("STRATA_FETCH_THREADS"); v != nullptr && std::atoi(v) > 0)
4646            src.set_fetch_threads(std::atoi(v));
4647        if (!src.open(o.pack, g.n_layers, g.n_expert, err)) {
4648            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
4649            return 1;
4650        }
4651        std::fprintf(stderr, "strata generate: experts via mmap (--mmap-experts; %s)\n",
4652                     src.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
4659        if (o.resident_budget > 0) {
4660            std::string why;
4661            const bool ub = src.set_unbuffered(o.resident_budget, why);
4662            std::fprintf(stderr, "strata generate: the file tier reads %s (%s)\n",
4663                         ub ? "unbuffered" : "through the file cache", why.c_str());
4664        } else if (const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); env != nullptr && env[0] != '\0' &&
4665                   env[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        }
4669        srcp = &src;
4670    } else {
4671        arena_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.
4677        const int pin_env = strata::core::arena_pin_cap_gib();   // -1 unset, -2 "auto" (#243, Windows sliced pin)
4678        const bool pin_wddm_cap = pin_env < 0 && (o.expert_cache_remote[0] > 0 || multi_gpu) && under_wddm();
4679        const uint64_t pin_limit = pin_env >= 0 ? (uint64_t) pin_env << 30 : pin_wddm_cap ? (8ull << 30) : 0;
4680        if (pin_env >= 0)
4681            std::fprintf(stderr, "strata generate: STRATA_ARENA_PIN_GIB=%d: %s\n", pin_env,
4682                         pin_env == 0 ? "the whole expert arena is pinned" : "the expert arena's pinning is capped");
4683        else 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");
4686        if (!arena_src.open(o.pack, g.n_layers, g.n_expert, /*threads=*/6, err, pin_limit,
4687                            o.shared_expert_arena)) {
4688            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
4689            return 1;
4690        }
4691        if (!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),
4696                     arena_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
4703        if (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
4712        srcp = &arena_src;
4713    }
4714    strata::kernels::cpu::ExpertPool pool(o.pool_workers, /*pin=*/true, /*host_works=*/!o.no_host_worker, o.pool_affinity);
4715    if (pool.is_hybrid() && pool.affinity() != strata::kernels::cpu::PoolAffinity::All) {
4716        const char* aff_str = pool.affinity() == strata::kernels::cpu::PoolAffinity::PCores ? "p-cores" :
4717                              pool.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",
4719                     pool.p_cores(), pool.p_threads(), pool.e_cores(), pool.workers(), aff_str);
4720    }
4721    {   // where the threads run (--host-core)
4722        const strata::kernels::cpu::CpuTopology ht = strata::kernels::cpu::detect_cpu_topology(true, o.pool_affinity);
4723        std::string on;
4724        for (int i = 0; i < pool.workers() && i < (int) ht.worker_cores.size(); ++i)
4725            on += (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,
4728                     pool.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    }
4733    if (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.
4737    mem_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)
4740    const bool auto_cache = o.expert_cache < 0;
4741    bool 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)
4743    const int64_t pipe_first = o.pipeline_windows <= 0 ? 0
4744        : (kPipeWindowMib << 20) + (o.pipeline_windows >= 2 ? 2 * (int64_t) gdn_snapshot_bytes(ss) : 0);
4745    if (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),
4748                     o.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.
4753    auto owned_prefill_mib = [&]() -> int64_t {
4754        if (!(o.prefill_chunk > 0 && !pf_borrow)) return 0;
4755        static const bool exact = [] { const char* v = std::getenv("STRATA_OWNED_PRICE"); return v != nullptr && std::string(v) == "exact"; }();
4756        if (!exact) return 160 + (o.prefill_chunk * 680) / 1024;
4757        const 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));
4760        return mib + 64;   // a margin for the allocator
4761    };
4762    if (o.expert_cache < 0) {
4763        size_t free_b = 0, total_b = 0;
4764        free_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)
4769        int64_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)
4772        int64_t mtp_bind = (!o.mtp.empty() && native_head.loaded())
4773                               ? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : 0;
4774        for (const auto& d : slot_mtp)
4775            mtp_bind += (int64_t) d->bind_bytes(native_head.row_bytes(), n_vocab);
4776        if (use_df2 && native_head.loaded()) {   // DFlash2's draft head rows and ids (from the vocabulary file), its logits, 48 MiB of margin
4777            int64_t bytes = (int64_t) std::min(o.spec, (int) strata::kernels::kVerifyMaxT) * n_vocab * (int64_t) sizeof(float);
4778            if (FILE* vf = std::fopen(df2_vocab_file.c_str(), "rb")) {
4779                std::fseek(vf, 0, SEEK_END);
4780                const long size = std::ftell(vf);
4781                std::fclose(vf);
4782                if (size >= 4 && size % 4 == 0) bytes += (int64_t) (size / 4) * (int64_t) native_head.row_bytes() + (int64_t) size;
4783            }
4784            mtp_bind += bytes + (48 << 20);
4785        }
4786        const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind + pipe_first;
4787        const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;
4788        int64_t slots = ((int64_t) free_b - reserve) / blob;
4789        if (!profile.empty()) slots = std::min<int64_t>(slots, (int64_t) profile.size());
4790        o.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.
4804        constexpr int kSmallReserveMib = 300;
4805        const 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;
4807        if (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
4809            const int64_t fit_mib = ((int64_t) free_b - mtp_bind - pipe_first - min_slots * blob) / (1 << 20) - prefill_mib;
4810            if (fit_mib >= kSmallReserveMib) {
4811                const int r = (int) std::min<int64_t>(fit_mib, o.vram_reserve_mib);
4812                int64_t s2 = ((int64_t) free_b - ((((int64_t) r + prefill_mib) << 20) + mtp_bind + pipe_first)) / blob;
4813                if (!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",
4816                             o.vram_reserve_mib, (long long) min_slots, r, (long long) s2);
4817                o.vram_reserve_mib = r;
4818                o.expert_cache = (int) s2;
4819                reserve_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.
4826        constexpr 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)
4827        constexpr 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)
4830        if (o.expert_cache < min_slots && o.prefill_chunk > 0) {
4831            const strata::core::ShortCache sc = strata::core::size_short_cache(
4832                (int64_t) free_b, o.vram_reserve_mib, o.vram_reserve_given, kSmallReserveMib,
4833                pf_borrow ? std::min<int64_t>(o.prefill_chunk, 1024) : o.prefill_chunk,   // (what the loan-less path takes when nothing can be lent)
4834                o.prefill_given, kMinChunk, kWorkCacheSlots, mtp_bind, pipe_first, blob, (int64_t) profile.size());
4835            const int64_t chunk = sc.chunk, reserve_mib = sc.reserve_mib, n = sc.slots;
4836            if (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",
4838                             chunk != o.prefill_chunk ? ("prompt chunk " + std::to_string(o.prefill_chunk) + " -> " + std::to_string(chunk) + " tokens").c_str() : "",
4839                             chunk != o.prefill_chunk && reserve_mib != o.vram_reserve_mib ? ", " : "",
4840                             reserve_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);
4842                if (reserve_mib != o.vram_reserve_mib) reserve_adapted = true;
4843                if (pf_borrow) o.prefill_auto = false;   // the chunk is the person's-sized now: its own buffers, no loan to size it from
4844                o.prefill_chunk = chunk;
4845                o.vram_reserve_mib = (int) reserve_mib;
4846                o.expert_cache = (int) n;
4847                prefill_mib = owned_prefill_mib();
4848            } else if (pf_borrow && n == 0) {
4849                o.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        }
4852        if (o.expert_cache == 0) {
4853            // what is short, and what makes room: the numbers a small card picks from
4854            const int64_t at_reserve = o.vram_reserve_given ? o.vram_reserve_mib
4855                                                            : std::min(o.vram_reserve_mib, kSmallReserveMib);
4856            const int64_t need_b = (((int64_t) at_reserve + prefill_mib) << 20) + mtp_bind + pipe_first + min_slots * blob;
4857            const int64_t short_mib = std::max<int64_t>(1, (need_b - (int64_t) free_b + (1 << 20) - 1) >> 20);
4858            const int64_t session_mib =
4859                (int64_t) (strata::core::session_bytes(g, o.max_context, K, 0, g.n_layers) >> 20);
4860            const std::string reserve_tip =
4861                o.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),
4872                         reserve_tip.c_str());
4873            g_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)
4884        size_t free_b = 0, total_b = 0;
4885        free_b = strata::core::device_free_bytes(); (void) total_b;
4886        const int64_t prefill_mib = owned_prefill_mib();
4887        const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + pipe_first;
4888        const int64_t fit = std::max<int64_t>(((int64_t) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob, 0);
4889        if (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);
4895            o.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;
4905    uint64_t per_layer_bytes = 0;
4906    if (native_pack && o.expert_cache > 0 && o.expert_cache_per_layer) {
4907        size_t free_b = 0, total_b = 0;
4908        /*
4909        DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions
4910        for device information which may not be supported by all compilers or
4911        runtimes. You may need to adjust the code.
4912        */
4913        dpct::get_current_device().get_memory_info(free_b, total_b);
4914        const auto& lay = strata::kernels::cpu::expert_layout();
4915        const int asked = o.expert_cache;
4916        const uint64_t budget = (uint64_t) asked * lay.max_blob;
4917        size_t free_room = free_b > ((size_t) o.vram_reserve_mib << 20) ? free_b - ((size_t) o.vram_reserve_mib << 20) : 0;
4918        const uint64_t cap = std::min<uint64_t>(budget, (uint64_t) free_room);
4919        uint64_t sum = 0;
4920        for (int64_t l = 0; l < g.n_layers; ++l)
4921            sum += (lay.blob_bytes(l) + 255) / 256 * 256;
4922        int64_t q = sum > 0 ? (int64_t) (cap / sum) : 0;
4923        if (q > g.n_expert) q = g.n_expert;
4924        if (q > 0) {
4925            per_layer_bytes = sum;
4926            sized_slots.reserve((size_t) q * (size_t) g.n_layers);
4927            for (int64_t l = 0; l < g.n_layers; ++l) {
4928                const int64_t b = (int64_t) lay.blob_bytes(l);
4929                for (int64_t s = 0; s < q; ++s) sized_slots.push_back(b);
4930            }
4931            o.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",
4934                         asked, (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()) {
4938        size_t free_b = 0, total_b = 0;
4939        free_b = strata::core::device_free_bytes(); (void) total_b;
4940        const auto& lay = strata::kernels::cpu::expert_layout();
4941        const uint64_t budget = (uint64_t) o.expert_cache * lay.max_blob;   // what the uniform sizing granted
4942        uint64_t used = 0;
4943        const size_t keep_free = ((size_t) o.vram_reserve_mib << 20) + (size_t) pipe_first;
4944        size_t free_room = free_b > keep_free ? free_b - keep_free : 0;
4945        const uint64_t cap = std::min<uint64_t>(budget, (uint64_t) free_room);
4946        for (const auto& pr : profile) {
4947            const uint64_t b = (lay.blob_bytes(pr.first) + 255) / 256 * 256;
4948            if (used + b > cap) break;
4949            used += b;
4950            sized_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).
4954        if (!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,
4958                         profile.size(), o.expert_profile.c_str(), profile.size());
4959        o.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.
4963    if (o.vram_elastic) {
4964        const 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)
4970        if (why == nullptr) why = "it is NVIDIA-only for now";
4971#endif
4972        if (why != nullptr) {
4973            std::fprintf(stderr, "strata generate: --vram-elastic is off: %s\n", why);
4974            o.vram_elastic = false;
4975        } else {
4976            xcache.set_segment_bytes(o.vram_segment_mib << 20);
4977        }
4978    }
4979    if (o.expert_cache > 0) {
4980        // keep the first `keep_bytes` of the cache (the profile's hottest experts first); false when nothing is left
4981        auto shrink_to = [&](int64_t keep_bytes) -> bool {
4982            if (keep_bytes <= 0) { o.expert_cache = 0; sized_slots.clear(); return false; }
4983            if (per_layer_bytes > 0) {
4984                // Cutting the list short would put one layer's blob in the next layer's range.
4985                const auto& lay = strata::kernels::cpu::expert_layout();
4986                int64_t q = keep_bytes / (int64_t) per_layer_bytes;
4987                if (q > g.n_expert) q = g.n_expert;
4988                sized_slots.clear();
4989                if (q <= 0) { o.expert_cache = 0; return false; }
4990                for (int64_t l = 0; l < g.n_layers; ++l) {
4991                    const int64_t b = (int64_t) lay.blob_bytes(l);
4992                    for (int64_t s = 0; s < q; ++s) sized_slots.push_back(b);
4993                }
4994                o.expert_cache = (int) sized_slots.size();
4995                return true;
4996            }
4997            if (!sized_slots.empty()) {
4998                int64_t used = 0;
4999                size_t keep = 0;
5000                while (keep < sized_slots.size() && used + (sized_slots[keep] + 255) / 256 * 256 <= keep_bytes)
5001                    used += (sized_slots[keep++] + 255) / 256 * 256;
5002                sized_slots.resize(keep);
5003                o.expert_cache = (int) keep;
5004            } else {
5005                o.expert_cache = (int) (keep_bytes / (int64_t) strata::kernels::cpu::expert_layout().max_blob);
5006            }
5007            if (o.expert_cache <= 0) { o.expert_cache = 0; sized_slots.clear(); return false; }
5008            return true;
5009        };
5010        auto cache_bytes = [&]() -> int64_t {
5011            if (sized_slots.empty()) return (int64_t) o.expert_cache * (int64_t) strata::kernels::cpu::expert_layout().max_blob;
5012            int64_t b = 0;
5013            for (const int64_t s : sized_slots) b += (s + 255) / 256 * 256;
5014            return 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)
5022        int fake_fails = std::getenv("STRATA_TEST_CACHE_FAIL") ? std::atoi(std::getenv("STRATA_TEST_CACHE_FAIL")) : 0;
5023        int failed = 0;
5024        int zero_reads = 0;
5025        for (int attempt = 0;; ++attempt) {
5026            bool ok = false;
5027            if (fake_fails > 0) {
5028                --fake_fails;
5029                err = "ExpertCache: cudaMalloc failed: out of memory (STRATA_TEST_CACHE_FAIL)";
5030            } else {
5031                ok = 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            }
5035            if (!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.
5039                char commit[96] = "";
5040#if defined(_WIN32)
5041                MEMORYSTATUSEX ms{};
5042                ms.dwLength = sizeof ms;
5043                if (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
5047                if (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(),
5050                                 commit, o.expert_cache);
5051                    continue;
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
5059                return 1;
5060            }
5061            if (!auto_cache || attempt - failed >= 6) break;
5062            if (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();
5064            size_t free_b = 0, total_b = 0;
5065            free_b = strata::core::device_free_bytes(); (void) total_b;
5066            const int64_t want = ((int64_t) o.vram_reserve_mib << 20) + pipe_first;
5067            if ((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
5070            int64_t give = want - (int64_t) free_b + (64ll << 20);
5071            if (free_b < ((size_t) 16 << 20))
5072                give = std::max<int64_t>(give, ++zero_reads <= 2 ? 1ll << 30 : xcache.bytes() / 4);
5073            const 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);
5076            xcache.close();
5077            if (!shrink_to(keep_bytes)) break;
5078        }
5079        if (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",
5082                         o.expert_cache, (double) xcache.bytes() / 1073741824.0, failed);
5083    }
5084    if (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());
5087        mem_mark("opening the expert cache");
5088        xcache.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");
5099        if (o.expert_cache_per_layer) {
5100            int64_t lo = 0, hi = 0;
5101            xcache.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.
5114    int64_t prefilled = 0;
5115    std::function<void(const char*)> verify_all_slots;   // STRATA_VERIFY_ALL_SLOTS (debug), set by the pipelined fill
5116    if (!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)
5119        const bool per_layer = xcache.per_layer_admission();
5120        const int64_t want = per_layer ? (int64_t) profile.size()
5121                                       : std::min<int64_t>((int64_t) profile.size(), xcache.slots());
5122        const auto tfill = std::chrono::steady_clock::now();
5123        uint64_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.
5129        const bool piped = srcp == &gguf_src && !per_layer && std::getenv("STRATA_FILL_SERIAL") == nullptr;
5130        if (piped) {
5131            struct Fill { int32_t slot; int32_t l, e; };
5132            std::vector<Fill> fills;
5133            fills.reserve((size_t) want);
5134            for (int64_t i = 0; i < want; ++i) {
5135                const int32_t slot = xcache.admit(profile[(size_t) i].first, profile[(size_t) i].second);
5136                if (slot == strata::core::kNotResident) break;
5137                fills.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) {
5140                return a.l != b.l ? a.l < b.l : a.e < b.e;   // file order: each tensor read front to back
5141            });
5142            const auto& lay = strata::kernels::cpu::expert_layout();
5143            constexpr size_t kBatch = 64;
5144            const size_t blob_cap = (size_t) lay.max_blob;
5145            sycl::queue& q = dpct::get_in_order_queue();
5146            uint8_t* pin = sycl::malloc_host<uint8_t>(2 * kBatch * blob_cap, q);
5147            if (pin == nullptr) {
5148                std::fprintf(stderr, "strata generate: the profile fill could not pin %zu MiB\n",
5149                             (2 * kBatch * blob_cap) >> 20);
5150                return 1;
5151            }
5152            const int nthreads = std::max(2, std::min(8, (int) std::thread::hardware_concurrency()));
5153            sycl::event done[2];
5154            bool read_ok = true;
5155            for (size_t b0 = 0, k = 0; b0 < fills.size() && read_ok; b0 += kBatch, ++k) {
5156                const size_t n = std::min(kBatch, fills.size() - b0);
5157                uint8_t* set = pin + (k % 2) * kBatch * blob_cap;
5158                done[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;
5162                for (int t = 0; t < nthreads; ++t)
5163                    ts.emplace_back([&] {
5164                        for (size_t j; (j = next.fetch_add(1)) < n;) {
5165                            const Fill& f = fills[b0 + j];
5166                            if (!gguf_src.read_into(f.l, f.e, set + j * blob_cap, blob_cap)) ok = false;
5167                        }
5168                    });
5169                for (auto& t : ts) t.join();
5170                if (!ok) { read_ok = false; break; }
5171                for (size_t j = 0; j < n; ++j) {
5172                    const Fill& f = fills[b0 + j];
5173                    const size_t nb = (size_t) lay.blob_bytes(f.l);
5174                    done[k % 2] = q.memcpy(xcache.device_slot(f.slot), set + j * blob_cap, nb);
5175                    fill_bytes += nb;
5176                }
5177            }
5178            q.wait();
5179            sycl::free(pin, q);
5180            if (!read_ok) {
5181                std::fprintf(stderr, "strata generate: the profile fill could not read an expert from the GGUF\n");
5182                return 1;
5183            }
5184            prefilled = (int64_t) fills.size();
5185            if (std::getenv("STRATA_VERIFY_ALL_SLOTS") != nullptr) {   // debug: every filled slot read back and compared with the GGUF
5186                auto fl = std::make_shared<std::vector<Fill>>(fills);
5187                verify_all_slots = [&, fl, blob_cap](const char* when) {
5188                    sycl::queue& vq = dpct::get_in_order_queue();
5189                    vq.wait();
5190                    std::vector<uint8_t> want_b(blob_cap), got_b(blob_cap);
5191                    int64_t bad = 0, first_bad = -1;
5192                    for (size_t i = 0; i < fl->size(); ++i) {
5193                        const Fill& f = (*fl)[i];
5194                        const size_t nb = (size_t) lay.blob_bytes(f.l);
5195                        if (!gguf_src.read_into(f.l, f.e, want_b.data(), blob_cap)) { ++bad; continue; }
5196                        vq.memcpy(got_b.data(), xcache.device_slot(f.slot), nb).wait();
5197                        if (std::memcmp(want_b.data(), got_b.data(), nb) != 0) {
5198                            if (first_bad < 0) first_bad = (int64_t) i;
5199                            ++bad;
5200                            size_t nd = 0, fd = nb, ld = 0;
5201                            for (size_t x = 0; x < nb; ++x)
5202                                if (want_b[x] != got_b[x]) { ++nd; if (fd == nb) fd = x; ld = x; }
5203                            if (std::getenv("STRATA_VERIFY_FIND") != nullptr && bad <= 2 && fd + 4160 < nb) {   // whose blob is the wrong data?
5204                                const uint8_t* probe = got_b.data() + fd + 4096;
5205                                std::vector<uint8_t> other(blob_cap);
5206                                for (size_t j = 0; j < fl->size(); ++j) {
5207                                    const Fill& g2 = (*fl)[j];
5208                                    if (!gguf_src.read_into(g2.l, g2.e, other.data(), blob_cap)) continue;
5209                                    const size_t nb2 = (size_t) lay.blob_bytes(g2.l);
5210                                    const void* hit = memmem(other.data(), nb2, probe, 64);
5211                                    if (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",
5213                                                     fd + 4096, (int) g2.l, (int) g2.e, (int) g2.slot, j, (size_t) ((const uint8_t*) hit - other.data()));
5214                                }
5215                            }
5216                            if (const char* dd = std::getenv("STRATA_VERIFY_DUMP"); dd != nullptr && bad == 1) {
5217                                const std::string base = std::string(dd) + "/slot" + std::to_string(f.slot);
5218                                if (FILE* fo = std::fopen((base + ".got").c_str(), "wb")) { std::fwrite(got_b.data(), 1, nb, fo); std::fclose(fo); }
5219                                if (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",
5222                                         when, 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",
5226                                 when, (long long) bad, fl->size(), (long long) first_bad);
5227                };
5228                verify_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;
5233        auto 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
5235        int64_t fill_ahead = 0;
5236        if (!piped && !per_layer && srcp == &src && !src.unbuffered()) {
5237            const char* v = std::getenv("STRATA_FILL_AHEAD");
5238            fill_ahead = v == nullptr ? 256 : std::max(0, std::atoi(v));
5239            if (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        }
5243        for (int64_t i = 0; i < want && !piped; ++i) {
5244            if (!per_layer && srcp == &src && src.unbuffered() && i % 64 == 0) {
5245                if (ahead.valid()) ahead.get();
5246                else read_batch(i);
5247                if (i + 64 < want) ahead = std::async(std::launch::async, read_batch, i + 64);
5248            }
5249            if (fill_ahead > 0 && i + fill_ahead < want) (void) src.advise_pairs(profile.data() + i + fill_ahead, 1);
5250            const int32_t slot = xcache.admit(profile[(size_t) i].first, profile[(size_t) i].second);
5251            if (slot == strata::core::kNotResident) {
5252                if (per_layer) continue;
5253                break;
5254            }
5255            const uint8_t* b = srcp->blob(profile[(size_t) i].first, profile[(size_t) i].second);
5256            if (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());
5260                return 1;
5261            }
5262            ++prefilled;
5263            fill_bytes += (uint64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[(size_t) i].first);
5264        }
5265        const 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,
5268                     piped ? "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.
5272        if (prefilled > 0 && !xcache.verify_slot(xcache.slot_of(profile[0].first, profile[0].second),
5273                                srcp->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());
5276            return 1;
5277        }
5278        strata::uc_probe("after-fill");
5279        mem_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,
5283                     fill_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.
5288    unsigned long long* mirror_table_d = nullptr;   // [n_layers][n_expert] device-readable mirror addresses (0 = none)
5289    int64_t unmirrored_misses = 0;
5290    if (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).
5294        const 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;
5296        size_t n_true_miss = 0;   // the experts no slot holds; what follows them in `miss` are the lend candidates (below)
5297        for (const auto& pr : profile)   // the profile's order: the most-routed misses first, if the cap is reached
5298            if (pr.first < mirror_end && xcache.slot_of(pr.first, pr.second) == strata::core::kNotResident)
5299                miss.push_back({pr.first, pr.second});
5300        for (int64_t l = 0; l < mirror_end; ++l)                     // pairs the profile does not list at all
5301            for (int64_t e = 0; e < g.n_expert; ++e)
5302                if (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())
5304                    miss.push_back({l, e});
5305        n_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).
5312        if (!o.no_prefill_borrow && o.prefill_chunk > 0 && !multi_gpu) {
5313            const char* lm = std::getenv("STRATA_LEND_MIRROR");
5314            const int64_t want_tail = lm ? std::atoll(lm) : std::min<int64_t>(xcache.slots() / 10, 1200);
5315            if (want_tail > 0) {
5316                const int64_t first_tail = xcache.slots() - std::min<int64_t>(want_tail, xcache.slots());
5317                for (int64_t l = 0; l < mirror_end; ++l)
5318                    for (int64_t e = 0; e < g.n_expert; ++e)
5319                        if (const int64_t sl = xcache.slot_of(l, e); sl != strata::core::kNotResident && sl >= first_tail)
5320                            miss.push_back({l, e});
5321            }
5322        }
5323        uint64_t avail = 0;
5324        if (FILE* f = std::fopen("/proc/meminfo", "r")) {
5325            char key[64]; unsigned long long kb = 0;
5326            while (std::fscanf(f, "%63s %llu kB", key, &kb) == 2)
5327                if (std::strcmp(key, "MemAvailable:") == 0) { avail = kb << 10; break; }
5328            std::fclose(f);
5329        }
5330        const char* mv = std::getenv("STRATA_MIRROR_MIB");
5331        const uint64_t cap = mv ? (uint64_t) std::atoll(mv) << 20 : (avail > (4ull << 30) ? avail - (4ull << 30) : 0);
5332        if (!miss.empty() && cap > 0) {
5333            const auto tm = Clock::now();
5334            const int64_t got = gguf_src.mirror(miss, cap, 8, err);
5335            if (got < 0) {
5336                std::fprintf(stderr, "strata generate: mirroring the experts missing from VRAM: %s (they stay on the SSD)\n",
5337                             err.c_str());
5338                err.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);
5346                for (int64_t l = 0; l < g.n_layers; ++l)
5347                    for (int64_t e = 0; e < g.n_expert; ++e)
5348                        if (gguf_src.pinned(l, e))
5349                            tab[(size_t) (l * g.n_expert + e)] = (unsigned long long) gguf_src.device_alias(l, e);
5350                mirror_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        }
5354        unmirrored_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);
5356        const bool no_host = [] { const char* v = std::getenv("STRATA_VERIFY_NO_HOST"); return v && *v && std::strcmp(v, "0") != 0; }();
5357        if (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);
5361            refuse_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).
5366        if (!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");
5369            o.adapt_every = 0;
5370        }
5371    }
5372
5373    if (sycl_mirror_adapt()) {
5374        if (!o.serve || !o.stream_experts || srcp != &gguf_src || !stages.empty() ||
5375            o.peer_device >= 0 || remote_caches ||
5376            !o.no_prefill_borrow || o.vram_elastic || !mirror_table_d || unmirrored_misses ||
5377            o.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");
5380            return 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
5386    for (auto& stp : stages) {
5387        GpuStage& st = *stp;
5388        const 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.
5391        const int64_t room = stage_room(st.dev, true, false);
5392        const strata::core::OnDevice on(st.dev);
5393        {
5394            size_t fb = 0, tb = 0;
5395            /*
5396            DPCT1106: 'cudaMemGetInfo' was migrated with the Intel
5397            extensions for device information which may not be supported by all
5398            compilers 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",
5402                         st.dev, (double) fb / 1073741824.0, (double) tb / 1073741824.0, (double) room / 1073741824.0);
5403        }
5404        std::vector<int64_t> sized;
5405        int64_t used = 0;
5406        for (const auto& pr : st.profile) {
5407            const int64_t b = native_pack ? ((int64_t) lay.blob_bytes(pr.first) + 255) / 256 * 256 : (int64_t) lay.max_blob;
5408            if (used + b > room) break;
5409            used += b;
5410            sized.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.
5415        bool stage_open = false;
5416        for (int attempt = 0; !sized.empty(); ++attempt) {
5417            stage_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);
5419            if (stage_open || attempt >= 3) break;
5420            /*
5421            DPCT1010: SYCL uses exceptions to report errors and does not
5422            use the error codes. The cudaGetLastError function call was replaced
5423            with 0. You need to rewrite this code.
5424            */
5425            (void)0;
5426            const 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);
5429            if (keep == 0) break;
5430            st.cache.close();
5431            sized.resize(keep);
5432        }
5433        if (!stage_open) {
5434            std::fprintf(stderr, "strata generate: layer split, CUDA%d expert cache: %s\n", st.dev,
5435                         sized.empty() ? "no room" : err.c_str());
5436            return 1;
5437        }
5438        int64_t filled = 0;
5439        for (const auto& pr : st.profile) {
5440            if (filled >= st.cache.slots()) break;
5441            const int32_t slot = st.cache.admit(pr.first, pr.second);
5442            if (slot == strata::core::kNotResident) break;
5443            const uint8_t* b = srcp->blob(pr.first, pr.second);
5444            if (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",
5446                             st.dev, (long long) filled, err.c_str());
5447                return 1;
5448            }
5449            ++filled;
5450        }
5451        if (filled == 0 || !st.cache.verify_slot(st.cache.slot_of(st.profile[0].first, st.profile[0].second),
5452                                                 srcp->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,
5455                         filled == 0 ? "nothing filled" : err.c_str());
5456            return 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",
5460                     st.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    }
5463    if (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.
5469    if (multi_gpu) {
5470        const bool no_host_split = [] { const char* v = std::getenv("STRATA_VERIFY_NO_HOST"); return v && *v && std::strcmp(v, "0") != 0; }();
5471        int64_t later_misses = 0;
5472        for (auto& stp : stages) {
5473            const GpuStage& st = *stp;
5474            later_misses += std::max<int64_t>(0, (st.le - st.lb) * g.n_expert - (int64_t) st.cache.slots());
5475        }
5476        if (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);
5482            refuse_exit(2);
5483        }
5484        if (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;
5491    if (o.remote_expert_opt && o.expert_cache_remote[0] > 0) remote_opt = std::make_unique<strata::core::RemoteExpertOpt>();
5492    const bool multi_remote = o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0;
5493    if (o.expert_cache_remote[0] > 0) {
5494        if (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");
5497            return 2;
5498        }
5499        std::vector<std::pair<int32_t, int32_t>> ranked = profile;
5500        if (!stages.empty()) {   // a layer split: CUDA0's share of the profile, then the later stages' pairs no cache holds
5501            for (auto& st : stages)
5502                for (const auto& pr : st->profile)
5503                    if (st->cache.slot_of(pr.first, pr.second) < 0) ranked.push_back(pr);
5504        }
5505        if (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);
5511            for (const auto& pair : ranked)
5512                if (pair.first >= 0 && pair.first < g.n_layers && pair.second >= 0 && pair.second < g.n_expert)
5513                    seen[(size_t) pair.first * (size_t) g.n_expert + (size_t) pair.second] = 1;
5514            for (int64_t e = 0; e < g.n_expert; ++e)
5515                for (int64_t l = 0; l < g.n_layers; ++l)
5516                    if (!seen[(size_t) l * (size_t) g.n_expert + (size_t) e])
5517                        ranked.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;
5522        if (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);
5526            const int devices = 1 + (o.expert_cache_remote[1] > 0) + (o.expert_cache_remote[2] > 0);
5527            int next = 0;
5528            for (const auto& pair : ranked) {
5529                if (pair.first < 0 || pair.first >= g.n_layers || pair.second < 0 || pair.second >= g.n_expert ||
5530                    xcache.slot_of(pair.first, pair.second) >= 0) continue;
5531                const size_t index = (size_t) pair.first * (size_t) g.n_expert + (size_t) pair.second;
5532                if (assigned[index]) continue;
5533                int target = -1;
5534                if (o.expert_cache_remote_placement == "layer") {
5535                    target = pair.first % devices;
5536                    // Other layers' owners may still have room: keep scanning ranks.
5537                    if (by_device[(size_t) target].size() >=
5538                        (size_t) o.expert_cache_remote[(size_t) target]) continue;
5539                } else {
5540                    for (int i = 0; i < devices; ++i) {
5541                        const int r = (next + i) % devices;
5542                        if (by_device[(size_t) r].size() < (size_t) o.expert_cache_remote[(size_t) r]) {
5543                            target = r;
5544                            break;
5545                        }
5546                    }
5547                    if (target < 0) break;
5548                }
5549                assigned[index] = 1;
5550                by_device[(size_t) target].push_back(pair);
5551                next = (target + 1) % devices;
5552            }
5553            std::fprintf(stderr, "strata generate: remote ranks %s across %d CUDA devices\n",
5554                         o.expert_cache_remote_placement == "layer" ? "grouped by layer" : "striped", devices);
5555        } else {
5556            by_device[0] = std::move(ranked);
5557        }
5558        std::vector<uint8_t> claimed((size_t) g.n_layers * (size_t) g.n_expert, 0);
5559        for (auto& st : stages)   // a layer split: what a stage's cache holds is no helper's
5560            for (const auto& pr : st->profile)
5561                if (st->cache.slot_of(pr.first, pr.second) >= 0)
5562                    claimed[(size_t) pr.first * (size_t) g.n_expert + (size_t) pr.second] = 1;
5563        for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) {
5564            if (remote_opt) remote_opt->attach(remote_experts[(size_t) r]);
5565            if (!remote_experts[(size_t) r].open(remote_dev[r], o.expert_cache_remote[(size_t) r],
5566                     g.n_layers, g.n_expert, by_device[(size_t) r], xcache, *srcp, claimed, err,
5567                     o.expert_cache_remote_auto[(size_t) r])) {
5568                std::fprintf(stderr, "strata generate: %s\n", err.c_str());
5569                return 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;
5579    if (o.peer_device >= 1) {
5580        if (profile.empty() || srcp == nullptr || o.expert_cache <= 0) {
5581            std::fprintf(stderr, "strata generate: --peer-device needs --expert-profile and the expert cache\n");
5582            return 1;
5583        }
5584        const auto tp0 = Clock::now();
5585        if (!peer.open(o.peer_device, profile, xcache, *srcp, g.n_layers, g.n_expert, o.peer_reserve_mib, o.peer_slots,
5586                       err)) {
5587            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
5588            return 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
5596    if (remote_opt && !remote_opt->init(err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; }
5597    Drive 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.
5601    const bool disjoint_adapt = [] { const char* v = std::getenv("STRATA_DISJOINT_ADAPT"); return v != nullptr && std::atoi(v) != 0; }();
5602    auto helper_holds = [&](int64_t l, int32_t e) -> bool {
5603        if (!disjoint_adapt) return false;
5604        for (int r = 0; r < drive.d.remote_count; ++r)
5605            if (drive.d.remote[r]->holds(l, e)) return true;
5606        return false;
5607    };
5608    for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0)
5609        drive.d.remote[drive.d.remote_count++] = &remote_experts[(size_t) r];
5610    drive.d.peer = peer.valid() ? &peer : nullptr;
5611    drive.d.hit_cpu_order = o.expert_cache_cpu_order;
5612    drive.d.split_rows = !o.no_split_rows;
5613    drive.d.pool = &pool;
5614    drive.d.src = srcp;
5615    drive.d.n_expert = g.n_expert;
5616    drive.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;
5621    if (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);
5623        bool ok = true;
5624        for (int64_t l = 0; l < g.n_layers && ok; ++l) {
5625            const strata::core::WeightRef* w = wt.find("blk." + std::to_string(l) + ".ffn_gate_inp.weight");
5626            ok = w != nullptr && w->kind == strata::core::WeightKind::Bf16InF32 &&
5627                 w->bytes == (uint64_t) (g.n_expert * g.n_embd) * 2;
5628            if (!ok) break;
5629            routers[(size_t) l].resize((size_t) (g.n_expert * g.n_embd));
5630            ok = DPCT_CHECK_ERROR(dpct::get_in_order_queue()
5631                                      .memcpy(routers[(size_t)l].data(),
5632                                              w->data, (size_t)w->bytes)
5633                                      .wait()) == 0;
5634        }
5635        const char* kv = std::getenv("STRATA_LOOKAHEAD_K");
5636        if (ok && lookahead.start(std::move(routers), g.n_embd, g.n_expert, kv ? std::atoi(kv) : 10, &src, err)) {
5637            drive.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            /*
5641            DPCT1010: SYCL uses exceptions to report errors and does not
5642            use the error codes. The cudaGetLastError function call was replaced
5643            with 0. You need to rewrite this code.
5644            */
5645            (void)0;
5646            std::fprintf(stderr, "strata generate: routing-aware prefetch off (%s)\n",
5647                         ok ? err.c_str() : "the routers are not BF16 in the arena");
5648            err.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.
5654    void* hit_scratch = nullptr;
5655    int32_t* d_hit_slot = nullptr;
5656    int32_t* d_hit_dst = nullptr;
5657    uint8_t* d_hit_q8 = nullptr;
5658    float* d_hit_q8_scale = nullptr;   ///< R4.2h: the fp32 activation scales the CPU path also uses
5659    float* d_hit_out = nullptr;
5660    if (o.expert_cache > 0 && !o.no_pool) {
5661        const uint64_t sb = strata::kernels::moe_hit_grouped_scratch_bytes(K, g.n_embd, strata::kernels::cpu::FF);
5662        if (DPCT_CHECK_ERROR(hit_scratch = (void *)sycl::malloc_device(
5663                                 (size_t)sb, dpct::get_in_order_queue())) !=
5664                0 ||
5665            DPCT_CHECK_ERROR(d_hit_slot = sycl::malloc_device<int32_t>(
5666                                 (size_t)K, dpct::get_in_order_queue())) != 0 ||
5667            DPCT_CHECK_ERROR(d_hit_dst = sycl::malloc_device<int32_t>(
5668                                 (size_t)K, dpct::get_in_order_queue())) != 0 ||
5669            DPCT_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.
5677            DPCT_CHECK_ERROR(d_hit_q8_scale = sycl::malloc_device<float>(
5678                                 (size_t)(g.n_embd / 32),
5679                                 dpct::get_in_order_queue())) != 0 ||
5680            DPCT_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");
5684            return 1;
5685        }
5686        drive.d.cache = &xcache;
5687        drive.d.cache_stream = main_cs;
5688        drive.d.cache_base = (const uint8_t*) xcache.device_slot(0);
5689        drive.d.cache_blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;
5690        drive.d.cache_slot_off = xcache.slot_offsets();
5691        drive.d.hit_scratch = hit_scratch;
5692        drive.d.parts_out = d_parts;
5693        drive.d.hit_out = d_hit_out;
5694        drive.d.parts_elems = K * g.n_embd;
5695        drive.d.mixed = ss.block.mixed;
5696        drive.d.x_q8_0_hit = d_hit_q8;
5697        drive.d.x_q8_0_hit_scale = d_hit_q8_scale;
5698        drive.d.d_slot = d_hit_slot;
5699        drive.d.d_dst = d_hit_dst;
5700        drive.d.h_slot.resize((size_t) K);
5701        dpct::event_ptr hit_done = nullptr;
5702        if (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");
5704            return 1;
5705        }
5706        drive.d.hit_done = (void*) hit_done;
5707        drive.d.hit_poke = !o.no_hit_poke;
5708        drive.d.h_dst.resize((size_t) K);
5709        mem_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.
5718    if (o.stage_timing) {
5719        if (!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");
5723            return 2;
5724        }
5725        if (!strata::core::stage_timing_enable()) {
5726            std::fprintf(stderr, "strata generate: stage_timing_enable failed\n");
5727            return 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;
5749    if (!o.dump_routing.empty()) {
5750        if (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");
5753            return 2;
5754        }
5755        routing = std::fopen(o.dump_routing.c_str(), "wb");
5756        if (routing == nullptr) {
5757            std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_routing.c_str());
5758            return 1;
5759        }
5760        drive.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;
5767    void* pool_user = o.no_pool ? nullptr : (void*) &drive;
5768    std::fprintf(stderr, "strata generate: %d expert-pool workers%s%s\n", pool.workers(),
5769                 pool.host_works() ? " + the host thread" : "",
5770                 o.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;
5788    if (!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
5792        if (!strata::core::session_capture(wt, g, ss, d_parts, gr, err, /*split=*/o.gpu_stages, 0,
5793                                           multi_gpu ? split_at[0] : -1)) {
5794            std::fprintf(stderr, "strata generate: session_capture: %s\n", err.c_str());
5795            return 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".
5808    if (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");
5813        return 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.
5818    if (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");
5822        return 2;
5823    }
5824    if (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");
5828        return 2;
5829    }
5830
5831    strata::uc_probe("cache-done");
5832    mem_mark("the expert cache and the graphs");
5833    std::fprintf(stderr, "strata generate: session is up (engine %s)\n", STRATA_VERSION);
5834    if (verify_all_slots) verify_all_slots("session up");
5835    auto run_head = [&](void* stream) -> bool {
5836        if (!native_head.loaded())
5837            return strata::core::lm_head(wt, g, ss.block, d_logits, stream, err);
5838        return strata::core::lm_head_mix(wt, g, ss.block, stream, err) &&
5839               native_head.run(ss.block.mixed, d_logits, stream, err);
5840    };
5841    float* d_emb = nullptr;
5842    if (DPCT_CHECK_ERROR(
5843            d_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");
5846        return 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.
5852    int* d_next = nullptr;
5853    if (DPCT_CHECK_ERROR(d_next = sycl::malloc_device<int>(
5854                             1, dpct::get_in_order_queue())) != 0) {
5855        std::fprintf(stderr, "strata generate: the sampler output buffer failed\n");
5856        return 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.
5863    void* token_stream = o.stream_token ? main_cs : nullptr;
5864    auto put_input = [&](int64_t tok, int64_t pos) -> bool {
5865        try {
5866    if (!strata::core::embed_row(wt, g, tok, d_emb, token_stream, err)) {
5867            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
5868            return false;
5869        }
5870        if (pos == 0) {
5871            strata::core::session_zero(ss, g, d_emb, token_stream);
5872        } else {
5873            for (int64_t c = 0; c < g.hc; ++c)
5874                /*
5875                DPCT1124: cudaMemcpyAsync is migrated to asynchronous
5876                memcpy API. While the origin API might be synchronous, it
5877                depends on the type of operand memory, so you may need to call
5878                wait() on event return by memcpy API to ensure synchronization
5879                behavior.
5880                */
5881                if (DPCT_CHECK_ERROR(strata::q_of(token_stream)->memcpy(
5882                        ss.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");
5885                    return false;
5886                }
5887        }
5888        return o.stream_token ||
5889               DPCT_CHECK_ERROR(
5890                   dpct::get_current_device().queues_wait_and_throw()) == 0;
5891    }
5892    catch (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;
5900    sp.greedy = o.greedy;
5901    sp.seed = o.seed;
5902    sp.top_k = o.top_k;
5903    sp.top_p = o.top_p;
5904    sp.temperature = o.temperature;
5905    // what this run actually samples with (the speculative loop below gets the same parameters); serve samples
5906    // per request instead
5907    if (!o.serve) {
5908        if (sp.greedy || sp.temperature <= 0.0f)
5909            std::fprintf(stderr, "strata generate: sampling greedy\n");
5910        else
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.
5919    int32_t hdr[2] = {0, 0};
5920    bool hdr_written = false;
5921    const int64_t dump_positions = (int64_t) o.tokens.size() - 1 + o.max_new;
5922    if (!o.dump_logits.empty()) {
5923        if (dump_positions > INT32_MAX || n_vocab > INT32_MAX) {
5924            std::fprintf(stderr, "strata generate: logits dump dimensions exceed int32\n");
5925            return 2;
5926        }
5927        dump = std::fopen(o.dump_logits.c_str(), "wb");
5928        if (dump == nullptr) {
5929            std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_logits.c_str());
5930            return 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.
5939        const int32_t n_rows = (int32_t) strata::program::logits_selection::row_count(dump_positions, o.logits_stride);
5940        hdr[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;
5948    float* layer_stage = nullptr;
5949    const size_t layer_floats = (size_t) (g.n_layers + 1) * (size_t) g.hc * (size_t) g.n_embd;
5950    if (!o.dump_layers.empty()) {
5951        layer_dump = std::fopen(o.dump_layers.c_str(), "wb");
5952        if (layer_dump == nullptr) {
5953            std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_layers.c_str());
5954            return 1;
5955        }
5956        /*
5957        DPCT1048: The original value cudaHostAllocDefault is not meaningful
5958        in the migrated code and was removed or replaced with 0. You may need to
5959        check the migrated code.
5960        */
5961        if (DPCT_CHECK_ERROR(layer_stage = sycl::malloc_host<float>(
5962                                 layer_floats, dpct::get_in_order_queue())) !=
5963            0) {
5964            std::fprintf(stderr, "strata generate: cannot pin the layer-dump staging buffer\n");
5965            return 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;
5980    double total_ms = 0;
5981    double prefill_ms = 0;   // positions 0 .. n_prompt-2: prompt tokens that only condition
5982    const Clock::time_point t_start = Clock::now();
5983    double ttft_ms = 0;
5984    const int64_t n_prompt = (int64_t) o.tokens.size();
5985    int64_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.
5999    if (o.gpu_stages) {
6000        strata::core::doorbell_reset(db);
6001        double mix = 0, ffn = 0, post = 0;
6002        if (!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(),
6005                         native_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\")" : "");
6009            return 1;
6010        }
6011        const int reps = 20;
6012        double t_mix = 0, t_ffn = 0, t_post = 0;
6013        for (int r = 0; r < reps; ++r) {
6014            if (!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());
6016                return 1;
6017            }
6018            t_mix += mix;
6019            t_ffn += ffn;
6020            t_post += post;
6021        }
6022        const 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)",
6026                    t_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",
6028                    t_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)",
6030                    t_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;
6043            double f2 = 0, p2 = 0;
6044            for (int r = 0; r < reps; ++r) {
6045                if (!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());
6047                    return 1;
6048                }
6049                for (int64_t l = 0; l < g.n_layers; ++l) acc[(size_t) l] += per[(size_t) l];
6050            }
6051            double gdn = 0, qsa = 0, worst = 0;
6052            int64_t ng = 0, nq = 0, worst_l = 0;
6053            for (int64_t l = 0; l < g.n_layers; ++l) {
6054                const double v = acc[(size_t) l] / reps;
6055                if (strata::core::is_qsa_layer(g, l)) { qsa += v; ++nq; }
6056                else { gdn += v; ++ng; }
6057                if (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",
6061                        gdn, 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",
6063                        qsa, 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;
6076            for (int r = 0; r < reps; ++r) {
6077                if (!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());
6079                    return 1;
6080                }
6081                for (int k = 0; k < 5; ++k) acc5[(size_t) k] += s5[(size_t) k];
6082            }
6083            static const char* sn[5] = {"0 gr_read (attn)", "1 attention", "2 gr_write (attn)",
6084                                        "3 gr_read (ffn)", "4 moe_route (router)"};
6085            const char* kind[5] = {"GR", "ATTN", "GR", "GR", "ROUTER"};
6086            double 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");
6089            for (int k = 0; k < 5; ++k) {
6090                const double v = acc5[(size_t) k] / reps;
6091                tot5 += v;
6092                if (k != 1 && k != 4) gr_ms += v;
6093                std::printf("  %-24s %-8s %10.3f %10.4f %7.1f%%\n", sn[k], kind[k], v,
6094                            v / (double) g.n_layers, 0.0);
6095            }
6096            for (int k = 0; k < 5; ++k) {
6097                const 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",
6104                        tot / 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            {
6114                double sweep[6] = {0, 0, 0, 0, 0, 0};
6115                for (int k = 1; k <= 5; ++k) {
6116                    double acc = 0, one = 0;
6117                    for (int r = 0; r < reps; ++r) {
6118                        if (!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());
6120                            return 1;
6121                        }
6122                        acc += one;
6123                    }
6124                    sweep[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");
6128                static const char* sn2[5] = {"0 gr_read (attn)", "1 attention", "2 gr_write (attn)",
6129                                             "3 gr_read (ffn)", "4 moe_route (router)"};
6130                for (int k = 0; k < 5; ++k) {
6131                    const double sw = sweep[k + 1] - sweep[k];
6132                    const double df = acc5[(size_t) k] / reps;
6133                    std::printf("  %-24s %10.3f %10.3f %11.1f%%\n", sn2[k], sw, df,
6134                                sw != 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());
6144        return 0;
6145    }
6146
6147    if (o.graph_only) {
6148        strata::core::doorbell_reset(db);
6149        // one warm pass so the first launch does not pay for page mapping
6150        if (!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());
6152            return 1;
6153        }
6154        if (DPCT_CHECK_ERROR(
6155                dpct::get_current_device().queues_wait_and_throw()) != 0) {
6156            std::fprintf(stderr, "strata generate: session_replay warm faulted\n");
6157            return 1;
6158        }
6159        const int reps = 20;
6160        const Clock::time_point t0 = Clock::now();
6161        for (int r = 0; r < reps; ++r) {
6162            if (!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());
6164                return 1;
6165            }
6166        }
6167        if (DPCT_CHECK_ERROR(
6168                dpct::get_current_device().queues_wait_and_throw()) != 0) {
6169            /*
6170            DPCT1009: SYCL reports errors using exceptions and does not use
6171            error codes. Please replace the "get_error_string_dummy(...)" with a
6172            real error-handling function.
6173            */
6174            /*
6175            DPCT1010: SYCL uses exceptions to report errors and does not
6176            use the error codes. The cudaGetLastError function call was replaced
6177            with 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));
6182            return 1;
6183        }
6184        const 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);
6188        return 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.
6201    if (o.gpu_only_full) {
6202        strata::core::doorbell_reset(db);
6203        const int reps = 20;
6204        double ms_layers = 0, ms_head = 0;
6205        for (int r = -1; r < reps; ++r) {          // r == -1 is the warm pass, not counted
6206            const Clock::time_point t0 = Clock::now();
6207            if (!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());
6209                return 1;
6210            }
6211            // The sync is INSIDE the interval on purpose: it is the wait for the GPU, so t1 - t0 is GPU time.
6212            if (DPCT_CHECK_ERROR(strata::q_of(main_cs)->wait()) != 0) {
6213                std::fprintf(
6214                    stderr,
6215                    "strata generate: gpu-only-full layers faulted: %s\n",
6216                    /*
6217                    DPCT1009: SYCL reports errors using exceptions and does
6218                    not use error codes. Please replace the
6219                    "get_error_string_dummy(...)" with a real error-handling
6220                    function.
6221                    */
6222                    /*
6223                    DPCT1010: SYCL uses exceptions to report errors and
6224                    does not use the error codes. The cudaGetLastError function
6225                    call was replaced with 0. You need to rewrite this code.
6226                    */
6227                    dpct::get_error_string_dummy(0));
6228                return 1;
6229            }
6230            const Clock::time_point t1 = Clock::now();
6231            if (!run_head(main_cs)) {
6232                std::fprintf(stderr, "strata generate: gpu-only-full lm_head: %s\n", err.c_str());
6233                return 1;
6234            }
6235            if (DPCT_CHECK_ERROR(strata::q_of(main_cs)->wait()) != 0) {
6236                std::fprintf(
6237                    stderr, "strata generate: gpu-only-full head faulted: %s\n",
6238                    /*
6239                    DPCT1009: SYCL reports errors using exceptions and does
6240                    not use error codes. Please replace the
6241                    "get_error_string_dummy(...)" with a real error-handling
6242                    function.
6243                    */
6244                    /*
6245                    DPCT1010: SYCL uses exceptions to report errors and
6246                    does not use the error codes. The cudaGetLastError function
6247                    call was replaced with 0. You need to rewrite this code.
6248                    */
6249                    dpct::get_error_string_dummy(0));
6250                return 1;
6251            }
6252            const Clock::time_point t2 = Clock::now();
6253            if (r < 0) continue;
6254            ms_layers += std::chrono::duration<double, std::milli>(t1 - t0).count();
6255            ms_head += std::chrono::duration<double, std::milli>(t2 - t1).count();
6256        }
6257        ms_layers /= (double) reps;
6258        ms_head /= (double) reps;
6259        const 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,
6261                    ms > 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);
6265        return 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;
6275    struct 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.
6282    if (!loop_scratch.init((size_t) K * g.n_embd * 4, err)) {
6283        std::fprintf(stderr, "strata generate: %s\n", err.c_str());
6284        return 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;
6289    struct 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).
6299    auto 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
6301        try {
6302            dpct::get_in_order_queue().memcpy(dst, host_res.data(), host_res.size() * sizeof(int32_t)).wait();
6303            return 0;
6304        } catch (sycl::exception const& exc) {
6305            std::cerr << exc.what() << " (res_put)" << std::endl;
6306            return 1;
6307        }
6308    };
6309    int32_t* d_res = nullptr;
6310    int32_t* d_hit_count = nullptr;
6311    strata::core::TokenHits thits;
6312    const bool graph_hits = hit_fn != nullptr && !profile.empty() && !o.no_pool;
6313    if (graph_hits && !o.no_capture && !o.no_token_graph && layer_dump == nullptr && half_dump == nullptr) {
6314        host_res.assign((size_t) (g.n_layers * g.n_expert), strata::core::kNotResident);
6315        int64_t resident = 0;
6316        for (int64_t l = 0; l < g.n_layers; ++l)
6317            for (int64_t e = 0; e < g.n_expert; ++e) {
6318                const int st = multi_gpu ? stage_of(l) : 0;
6319                const int32_t slot = st > 0 ? stages[(size_t) st - 1]->cache.slot_of(l, e) : xcache.slot_of(l, e);
6320                host_res[(size_t) (l * g.n_expert + e)] = slot;
6321                if (slot != strata::core::kNotResident) ++resident;
6322            }
6323        if (DPCT_CHECK_ERROR(
6324                d_res = sycl::malloc_device<int32_t>(
6325                    host_res.size(), dpct::get_in_order_queue())) != 0 ||
6326            DPCT_CHECK_ERROR(d_hit_count = sycl::malloc_device<int32_t>(
6327                                 1, dpct::get_in_order_queue())) != 0 ||
6328            res_put(d_res) != 0) {
6329            std::fprintf(stderr, "strata generate: the device residency table could not be staged\n");
6330            return 1;
6331        }
6332        thits.d_res = d_res;
6333        thits.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        {
6339            static const bool keep = std::getenv("STRATA_ARENA_RELEASE") && std::getenv("STRATA_ARENA_RELEASE")[0] == '0';
6340            rss_probe("before the release");
6341            uint64_t released = 0;
6342            if (!keep)
6343                for (size_t i = 0; i < host_res.size(); ++i)
6344                    if (host_res[i] != strata::core::kNotResident)
6345                        released += srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert);
6346            if (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));
6349            rss_probe("after the release");
6350            int64_t pf = 0;
6351            for (size_t i = 0; i < host_res.size(); ++i)
6352                if (host_res[i] == strata::core::kNotResident) {
6353                    srcp->prefetch((int64_t) i / g.n_expert, (int64_t) i % g.n_expert);
6354                    ++pf;
6355                }
6356            (void) pf;
6357            rss_probe("after the prefetch hints");
6358        }
6359        for (auto& st : stages) {   // layer split across GPUs: the same table on every device
6360            const strata::core::OnDevice on(st->dev);
6361            if (DPCT_CHECK_ERROR(
6362                    st->d_res = sycl::malloc_device<int32_t>(
6363                        host_res.size(), dpct::get_in_order_queue())) != 0 ||
6364                res_put(st->d_res) != 0) {
6365                std::fprintf(stderr, "strata generate: layer split: CUDA%d residency table failed\n", st->dev);
6366                return 1;
6367            }
6368        }
6369        thits.cache_base = drive.d.cache_base;
6370        thits.blob = drive.d.cache_blob;
6371        thits.d_slot = drive.d.d_slot;
6372        thits.d_dst = drive.d.d_dst;
6373        thits.d_count = d_hit_count;
6374        thits.x_q8 = drive.d.x_q8_0_hit;
6375        thits.x_scale = drive.d.x_q8_0_hit_scale;
6376        thits.scratch = drive.d.hit_scratch;
6377        thits.hit_out = drive.d.hit_out;
6378        drive.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    }
6382    if (!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
6384        if (!strata::core::session_capture_token(wt, g, ss, d_parts, loop_scratch.y_miss, loop_scratch.parts_bytes,
6385                                                 tgraph, err, thits.on() ? &thits : nullptr)) {
6386            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
6387            return 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.
6405    double ms_ple = 0, ms_embed = 0, ms_layers = 0, ms_head = 0, ms_readback = 0, ms_sample = 0;
6406    int64_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)
6428    if (srcp != nullptr && o.prefill_chunk > 0) {
6429        uint64_t pinned = 0, total = 0;
6430        const auto& lay = strata::kernels::cpu::expert_layout();
6431        for (int64_t l = 0; l < g.n_layers; ++l)
6432            for (int64_t e = 0; e < g.n_expert; ++e) {
6433                const uint64_t b = lay.blob_bytes(l);
6434                total += b;
6435                if (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)
6439        int64_t nonres = 0;
6440        for (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.
6445    auto slots_from_bytes = [&](uint64_t need) -> int64_t {
6446        const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;
6447        int64_t k = (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob);
6448        if (xcache.slot_offsets() != nullptr) {   // sized slots: take slots from the end until they hold `need`
6449            k = 0;
6450            while (k < xcache.slots() &&
6451                   (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[xcache.slots() - k]) < need) ++k;
6452        }
6453        return 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.
6458    auto bytes_from_slots = [&](int64_t k) -> uint64_t {
6459        if (k <= 0) return 0;
6460        if (xcache.slot_offsets() != nullptr)
6461            return (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[xcache.slots() - k]);
6462        return (uint64_t) k * (uint64_t) strata::kernels::cpu::expert_layout().max_blob;
6463    };
6464    auto lend_slots = [&](int64_t c) -> int64_t {
6465        return 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.
6469    auto request_chunk = [](int64_t tokens, int64_t max_chunk) -> int64_t {
6470        if (tokens <= 0 || max_chunk <= 0) return 0;
6471        const int64_t rounded = tokens > std::numeric_limits<int64_t>::max() - 255
6472                                    ? tokens
6473                                    : ((tokens + 255) / 256) * 256;
6474        return 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.
6483    static const bool equal_chunks = [] { const char* e = std::getenv("STRATA_PREFILL_EQUAL"); return e != nullptr && e[0] == '1'; }();
6484    auto equal_chunk = [&](int64_t tokens, int64_t max_chunk) -> int64_t {
6485        const int64_t plain = request_chunk(tokens, max_chunk);
6486        if (!equal_chunks || tokens <= 0 || max_chunk <= 0) return plain;
6487        const int64_t n = tokens / max_chunk + (tokens % max_chunk != 0);
6488        const int64_t last = tokens - (n - 1) * max_chunk;
6489        if (n <= 1 || last < strata::prefill::Prefill::stream_all_min_tokens()) return plain;
6490        const int64_t per = tokens / n + (tokens % n != 0);
6491        const int64_t rounded = per > std::numeric_limits<int64_t>::max() - 255 ? per : ((per + 255) / 256) * 256;
6492        return 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.
6503    const int64_t kAutoLendPct = [] {
6504        const char* v = std::getenv("STRATA_PREFILL_LEND_PCT");
6505        return 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).
6512    const 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.
6519    auto biggest_chunk = [](int64_t ceiling, auto&& ok) -> int64_t {
6520        if (ceiling < 256) return 0;
6521        int64_t lo = 1, hi = ceiling / 256, best = 0;   // n = T / 256, and ok() is monotone in n
6522        while (lo <= hi) {
6523            const int64_t mid = lo + (hi - lo) / 2;
6524            if (ok(mid * 256)) { best = mid * 256; lo = mid + 1; } else hi = mid - 1;
6525        }
6526        return best;
6527    };
6528    auto plan_lend = [&](int64_t& chunk) -> int64_t {
6529        auto 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)
6531        auto old_rule = [&]() -> int64_t {
6532            strata::prefill::Prefill::set_ring_budget(0, 0);
6533            static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256};
6534            for (const int64_t c : kAutoChunks) {
6535                // above 8192: only when asked for, and only when a prompt of the context can use it
6536                if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue;
6537                const int64_t k = slots_for(c);
6538                if (k + 128 <= xcache.slots() && k * 100 <= kAutoLendPct * xcache.slots()) return c;
6539            }
6540            return 0;
6541        };
6542        if (o.prefill_auto && !strata::prefill::Prefill::ring_bytes_enabled()) {   // STRATA_RING_BYTES=0: 0.1.39's list
6543            const int64_t c = old_rule();
6544            if (c > 0) { chunk = c; return slots_for(c); }
6545            return 0;
6546        }
6547        if (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).
6557            constexpr int64_t kRingMin = 16;
6558            const int64_t small = old_rule();   // 0.1.39's chunk (and its ring for the prompts that fit it)
6559            const int64_t ring_max = strata::prefill::Prefill::ring_cap_for(small);
6560            const 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.
6567            const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;
6568            const uint64_t avail = bytes_from_slots(budget);
6569            auto room_of = [&](int64_t t) -> int64_t {
6570                const uint64_t nonring = strata::prefill::Prefill::bytes_needed_no_ring(g, ss, t);
6571                return 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.
6575            auto scan = [&](int64_t floor) -> int64_t {
6576                return biggest_chunk(auto_ceiling, [&](int64_t t) -> bool {
6577                    const int64_t room = room_of(t);
6578                    if (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
6582                    const int64_t k = slots_for(t);
6583                    return k + 128 <= xcache.slots() && k * 100 <= kAutoLendPct * xcache.slots();
6584                });
6585            };
6586            int64_t c = scan(ring_max);
6587            if (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)
6589            if (small >= c) {   // the scan bought nothing: 0.1.39's choice
6590                strata::prefill::Prefill::set_ring_budget(0, 0);
6591                if (small > 0) { chunk = small; return slots_for(small); }
6592                return 0;
6593            }
6594            strata::prefill::Prefill::set_ring_budget((int) room_of(c), small);
6595            chunk = c;
6596            return slots_for(c);
6597        }
6598        for (int64_t c = chunk; c >= 256; c /= 2) {
6599            const int64_t k = slots_for(c);
6600            if (k + 128 <= xcache.slots()) { chunk = c; return k; }
6601        }
6602        return 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.
6611    struct KvGrow {
6612        bool on = false;
6613        int64_t top = 0, lo = 0;          // slots [lo, top) hold no expert; their whole chunks may be with the K/V
6614        int64_t floor = 128;              // the cache keeps at least these slots
6615        int64_t step = 8192;              // the K/V grows in whole steps of cells
6616        int64_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
6618        int64_t grows = 0, trims = 0, fresh = 0, evicted = 0, refilled = 0;
6619    } kvg;
6620    auto kvg_start = [&](int64_t top) {
6621        kvg.on = strata::core::qsa_kv_elastic() && xcache.vmm_range() != nullptr && d_res != nullptr &&
6622                 !host_res.empty() && srcp != nullptr && top > kvg.floor;
6623        if (!kvg.on) return;
6624        kvg.top = kvg.lo = top;
6625        kvg.cells = strata::core::qsa_kv_elastic_cells();
6626        if (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)
6628        if (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).
6638    auto kvg_ensure = [&](int64_t cells, const std::function<void()>& quiesce) -> bool {
6639        if (!kvg.on || cells <= kvg.cells) return true;
6640        const int64_t target = std::min<int64_t>(o.max_context, (cells + kvg.step - 1) / kvg.step * kvg.step);
6641        const int64_t need = strata::core::qsa_kv_elastic_need(target);
6642        if (need == 0) { kvg.cells = strata::core::qsa_kv_elastic_cells(); return true; }
6643        quiesce();
6644        strata::core::VmmRange& r = *xcache.vmm_range();
6645        const 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
6653        auto heat = [&](int32_t i) -> float {
6654            const float u = drive.d.usage.empty() ? 0.0f : drive.d.usage[(size_t) i];
6655            return u * 1048576.0f - (float) rank[(size_t) i];
6656        };
6657        const auto& lay = strata::kernels::cpu::expert_layout();
6658        int64_t gave = 0, moved = 0;
6659        auto freeable = [&]() -> int64_t {   // mapped chunks wholly inside [lo, top): a chunk a live slot shares stays
6660            const int64_t c0 = (int64_t) ((xcache.slot_offset(kvg.lo) + G - 1) / G);
6661            const int64_t c1 = (int64_t) (xcache.slot_offset(kvg.top) / G);
6662            int64_t k = 0;
6663            for (int64_t c = c0; c < c1; ++c) k += r.mapped(c) ? 1 : 0;
6664            return k;
6665        };
6666        while ((int64_t) kvg.spare.size() + freeable() < need && kvg.lo > kvg.floor) {
6667            if (owner.empty()) {
6668                owner.assign((size_t) xcache.slots(), -1);
6669                for (size_t i = 0; i < host_res.size(); ++i)
6670                    if (host_res[i] >= 0 && host_res[i] < xcache.slots()) owner[(size_t) host_res[i]] = (int32_t) i;
6671                rank.assign(host_res.size(), (int32_t) profile.size());
6672                for (size_t r = 0; r < profile.size(); ++r)
6673                    rank[(size_t) profile[r].first * (size_t) g.n_expert + (size_t) profile[r].second] = (int32_t) r;
6674                for (size_t i = 0; i < host_res.size(); ++i)
6675                    if (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;
6680            if (const int32_t oi = owner[(size_t) kvg.lo]; oi >= 0) {
6681                const int64_t layer = oi / g.n_expert;
6682                int32_t vi = -1;
6683                if (!cold.empty() && cold.back().first < heat(oi)) {
6684                    vi = cold.back().second;
6685                    const int32_t vs = host_res[(size_t) vi];
6686                    if (xcache.slot_offset(vs + 1) - xcache.slot_offset(vs) <
6687                            lay.blob_bytes(layer) ||
6688                        DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
6689                            xcache.device_slot(vs),
6690                            xcache.device_slot((int32_t)kvg.lo),
6691                            (size_t)lay.blob_bytes(layer)).wait()) != 0)
6692                        vi = -1;
6693                    else {
6694                        cold.pop_back();
6695                        host_res[(size_t) oi] = vs;
6696                        host_res[(size_t) vi] = strata::core::kNotResident;
6697                        ++moved;
6698                    }
6699                }
6700                if (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)
6706        if (gave > 0 &&
6707            DPCT_CHECK_ERROR(
6708                dpct::get_current_device().queues_wait_and_throw()) != 0) {
6709            /*
6710            DPCT1009: SYCL reports errors using exceptions and does not use
6711            error codes. Please replace the "get_error_string_dummy(...)" with a
6712            real error-handling function.
6713            */
6714            /*
6715            DPCT1010: SYCL uses exceptions to report errors and does not
6716            use the error codes. The cudaGetLastError function call was replaced
6717            with 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));
6722            return false;
6723        }
6724        {
6725            const int64_t c0 = (int64_t) ((xcache.slot_offset(kvg.lo) + G - 1) / G);
6726            const int64_t c1 = (int64_t) (xcache.slot_offset(kvg.top) / G);
6727            for (int64_t c = c0; c < c1; ++c)
6728                if (r.mapped(c))
6729                    if (const strata::core::VmmChunk h = r.unmap(c)) kvg.spare.push_back(h);
6730        }
6731        if (gave > 0 &&
6732            /*
6733            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
6734            assuming in the original code the source host memory is pageable
6735            memory. If the memory is not pageable, call wait() on event return
6736            by memcpy API to ensure synchronization behavior.
6737            */
6738            DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
6739                d_res, host_res.data(), host_res.size() * sizeof(int32_t)).wait()) !=
6740                0) {
6741            /*
6742            DPCT1009: SYCL reports errors using exceptions and does not use
6743            error codes. Please replace the "get_error_string_dummy(...)" with a
6744            real error-handling function.
6745            */
6746            /*
6747            DPCT1010: SYCL uses exceptions to report errors and does not
6748            use the error codes. The cudaGetLastError function call was replaced
6749            with 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));
6754            return false;
6755        }
6756        int64_t fresh = 0;
6757        const bool ok = strata::core::qsa_kv_elastic_grow(target, [&]() -> strata::core::VmmChunk {
6758            if (kvg.spare.empty()) { ++fresh; return 0; }   // the cache is at its floor: new memory
6759            const strata::core::VmmChunk h = kvg.spare.back();
6760            kvg.spare.pop_back();
6761            return h;
6762        });
6763        kvg.fresh += fresh;
6764        kvg.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(),
6771                     fresh > 0 ? " - and new VRAM, the cache being at its floor" : "");
6772        if (!ok)
6773            std::fprintf(
6774                stderr, "strata: the K/V could not grow to %lld cells (%s)\n",
6775                (long long)target,
6776                /*
6777                DPCT1009: SYCL reports errors using exceptions and does not
6778                use error codes. Please replace the
6779                "get_error_string_dummy(...)" with a real error-handling
6780                function.
6781                */
6782                /*
6783                DPCT1010: SYCL uses exceptions to report errors and does
6784                not use the error codes. The cudaGetLastError function call was
6785                replaced with 0. You need to rewrite this code.
6786                */
6787                dpct::get_error_string_dummy(0));
6788        return 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`).
6792    auto kvg_trim = [&](int64_t cells) -> bool {
6793        if (!kvg.on) return true;
6794        const int64_t target = std::max<int64_t>(kvg.step, (cells + kvg.step - 1) / kvg.step * kvg.step);
6795        if (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); });
6797        kvg.cells = strata::core::qsa_kv_elastic_cells();
6798        strata::core::VmmRange& r = *xcache.vmm_range();
6799        const uint64_t G = strata::core::vmm_granularity();
6800        const 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)
6802            const int64_t c0 = (int64_t) (xcache.slot_offset(kvg.lo) / G);
6803            int64_t cend = c0, need = (int64_t) kvg.spare.size();
6804            while (cend < c1 && need > 0) need -= r.mapped(cend++) ? 0 : 1;
6805            if (!r.map_range(c0, cend, [&]() -> strata::core::VmmChunk {
6806                    if (kvg.spare.empty()) return 0;
6807                    const strata::core::VmmChunk h = kvg.spare.back();
6808                    kvg.spare.pop_back();
6809                    return h;
6810                }))
6811                std::fprintf(stderr, "strata: the expert cache could not take its VRAM back from the K/V\n");
6812        }
6813        const int64_t lo0 = kvg.lo;
6814        while (kvg.lo < kvg.top) {   // a slot whose chunks are all mapped again holds an expert again
6815            const int64_t a = (int64_t) (xcache.slot_offset(kvg.lo) / G);
6816            const int64_t b = (int64_t) ((xcache.slot_offset(kvg.lo + 1) + G - 1) / G);
6817            bool all = true;
6818            for (int64_t c = a; c < b && all; ++c) all = r.mapped(c);
6819            if (!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)
6823        const 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
6825        size_t pi = 0;
6826        for (int64_t s = lo0; s < kvg.lo; ++s) {
6827            const uint64_t room = xcache.slot_offset(s + 1) - xcache.slot_offset(s);
6828            for (; pi < profile.size(); ++pi) {
6829                const int32_t l = profile[pi].first, e = profile[pi].second;
6830                const size_t i = (size_t) l * (size_t) g.n_expert + (size_t) e;
6831                if (host_res[i] >= 0 || lay.blob_bytes(l) > room) continue;
6832                const uint8_t* b = srcp->blob(l, e);
6833                if (b == nullptr) continue;
6834                /*
6835                DPCT1124: cudaMemcpyAsync is migrated to asynchronous
6836                memcpy API. While the origin API might be synchronous, it
6837                depends on the type of operand memory, so you may need to call
6838                wait() on event return by memcpy API to ensure synchronization
6839                behavior.
6840                */
6841                dpct::get_in_order_queue().memcpy(
6842                    xcache.device_slot((int32_t)s), b,
6843                    (size_t)lay.blob_bytes(l)).wait();
6844                filled.emplace_back(i, (int32_t) s);
6845                ++pi;
6846                break;
6847            }
6848        }
6849        if (DPCT_CHECK_ERROR(
6850                dpct::get_current_device().queues_wait_and_throw()) != 0) {
6851            /*
6852            DPCT1009: SYCL reports errors using exceptions and does not use
6853            error codes. Please replace the "get_error_string_dummy(...)" with a
6854            real error-handling function.
6855            */
6856            /*
6857            DPCT1010: SYCL uses exceptions to report errors and does not
6858            use the error codes. The cudaGetLastError function call was replaced
6859            with 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));
6864            return false;
6865        }
6866        for (const auto& [i, s] : filled) host_res[i] = s;
6867        kvg.refilled += (int64_t) filled.size();
6868        /*
6869        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
6870        assuming in the original code the source host memory is pageable memory.
6871        If the memory is not pageable, call wait() on event return by memcpy API
6872        to ensure synchronization behavior.
6873        */
6874        if (DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
6875                d_res, host_res.data(), host_res.size() * sizeof(int32_t)).wait()) !=
6876            0)
6877            return false;
6878        for (const strata::core::VmmChunk h : kvg.spare) strata::core::vmm_chunk_free(h);   // new ones, if any
6879        kvg.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));
6883        return 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.)
6897    auto adapt_async_off = [&](const char* why) {
6898        std::fprintf(stderr, "strata generate: --adapt-async 1 is off (%s): the blocking adaptive tier\n", why);
6899        o.adapt_async = 0;
6900    };
6901    if (o.adapt_async) {
6902        const 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;
6910        if (why != nullptr) adapt_async_off(why);
6911    }
6912    if (o.resident_cpu_experts) {
6913        int64_t lend_from = -1;
6914        if (o.prefill_chunk > 0 && !o.no_prefill_borrow && d_res != nullptr && xcache.slots() > 0) {
6915            int64_t chunk = o.prefill_chunk;
6916            const int64_t k = plan_lend(chunk);
6917            if (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;
6922        for (auto& st : stages)
6923            for (int64_t l = st->lb; l < st->le; ++l)
6924                for (int64_t e = 0; e < g.n_expert; ++e)
6925                    if (st->cache.slot_of(l, e) >= 0) stage_pairs.emplace_back((int32_t) l, (int32_t) e);
6926        const std::vector<std::pair<int32_t, int32_t>>& rank_all = profile_all.empty() ? profile : profile_all;
6927        bool resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, stage_pairs, lend_from,
6928                                                    o.resident_headroom, o.resident_budget, &rank_all);
6929        std::string whole_err;
6930        if (!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.
6934            whole_err = err;
6935            resident_ok = src.pin_cache_complement(xcache, err, o.resident_pin, stage_pairs, -1, o.resident_headroom,
6936                                                   strata::core::FileExpertSource::kResidentWhatFits, &rank_all);
6937            if (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",
6942                             whole_err.c_str(), (double) src.resident_bytes() / 1073741824.0);
6943            else
6944                err = whole_err + "; " + err;
6945        }
6946        if (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)
6949            if (o.adapt_async && !src.reserve_exchanges(2 * std::min<int64_t>(o.adapt_swaps, 96), err))
6950                adapt_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
6953            if (o.adapt_async && !src.exchange_pinned())
6954                adapt_async_off("the exchange buffers could not be page-locked");
6955            if (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());
6958                return 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,
6963                         src.complement_pinned() ? "page-locked" : src.locked_bytes() > 0 ? "locked" : "pageable",
6964                         (long long) xcache.resident(),
6965                         o.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(),
6977                         src.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());
6980            return 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__)
6987        if (o.mmap_experts && o.resident_budget > 0) {
6988            std::string why;
6989            const bool was = src.unbuffered();
6990            const bool ub = src.recheck_unbuffered(why);
6991            std::fprintf(stderr, "strata generate: the file tier reads %s%s (%s)\n",
6992                         ub ? "unbuffered" : "through the file cache", ub == was ? "" : " (changed)", why.c_str());
6993        }
6994#endif
6995    }
6996    if (o.adapt_async && !src.complement_ready()) adapt_async_off("the resident RAM mode is not running");
6997    if (o.serve) {
6998        if (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");
7002            return 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.
7009        const bool use_mtp = !o.mtp.empty();
7010        strata::prefill::Prefill sp;
7011        void* borrow = nullptr;
7012        uint64_t borrow_bytes = 0;
7013        int32_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.
7024        struct PfPart {
7025            strata::core::ExpertCache* cache = nullptr;
7026            const strata::core::SessionState* ses = nullptr;
7027            strata::prefill::Prefill* sp = nullptr;
7028            int dev = -1;                  // -1: leave the device alone (CUDA0)
7029            int64_t lb = 0, le = 0;        // the layers whose rows this cache holds - the only rows it may lend
7030            int32_t first = -1;            // the first slot it may lend, for the chunk that was chosen
7031            int32_t first_now = -1;        // where its buffers are laid out now
7032            int64_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.
7037        auto cache_slots_for = [&](const strata::core::ExpertCache& xc, uint64_t need) -> int64_t {
7038            if (xc.slot_offsets() != nullptr) {   // sized slots: from the end until they hold `need`
7039                int64_t k = 0;
7040                while (k < xc.slots() &&
7041                       (uint64_t) (xc.bytes() - (int64_t) xc.slot_offsets()[xc.slots() - k]) < need) ++k;
7042                return k;
7043            }
7044            const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;
7045            return (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob);
7046        };
7047        auto part_slots = [&](const PfPart& p, int64_t c) -> int64_t {
7048            return cache_slots_for(*p.cache, strata::prefill::Prefill::bytes_needed(g, *p.ses, c));
7049        };
7050        auto part_bytes = [&](const PfPart& p, int32_t first) -> uint64_t {
7051            strata::core::ExpertCache& xc = *p.cache;
7052            return 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.
7060        if (multi_gpu && !host_res.empty()) {
7061            int64_t res_n = 0;
7062            for (const int32_t r : host_res) res_n += r >= 0;
7063            const double res_share = (double) res_n / (double) host_res.size();
7064            const char* v = std::getenv("STRATA_SPLIT_RING");
7065            const int ring = v ? std::atoi(v) : (res_share >= 0.75 ? 96 : 0);
7066            if (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)
7076        if (pf_borrow && d_res != nullptr) {
7077            pf_parts.push_back({&xcache, &ss, &sp, -1, 0, multi_gpu ? split_at[0] : g.n_layers, -1, -1, 0, {}});
7078            for (auto& st : stages)
7079                pf_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.
7084            auto fits_one = [&](const PfPart& p, int64_t c, bool cap) -> bool {
7085                const int64_t k = part_slots(p, c);
7086                if (k <= 0 || k + 128 > p.cache->slots()) return false;
7087                return !(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
7090            auto fits = [&](int64_t c, bool cap, const PfPart* only = nullptr) -> bool {
7091                if (only != nullptr) return fits_one(*only, c, cap);
7092                for (const PfPart& p : pf_parts)
7093                    if (!fits_one(p, c, cap)) return false;
7094                return 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.
7105            constexpr 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.
7110            const int64_t kBlob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;
7111            auto ring_room = [&](int64_t c, const PfPart* only, int64_t cap) -> int64_t {
7112                int64_t room = cap;
7113                for (const PfPart& p : pf_parts) {
7114                    if (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
7118                    const int64_t budget = std::max<int64_t>(0, std::min(p.cache->slots() - 128,
7119                                                                        kAutoLendPct * p.cache->slots() / 100));
7120                    const uint64_t avail = part_bytes(p, (int32_t) (p.cache->slots() - budget));
7121                    const uint64_t nonring = strata::prefill::Prefill::bytes_needed_no_ring(g, *p.ses, c);
7122                    room = std::min(room, (int64_t) ((avail - std::min(avail, nonring)) / (uint64_t) kBlob));
7123                }
7124                return 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
7131            auto old_pick = [&](const PfPart* only) -> int64_t {
7132                strata::prefill::Prefill::set_ring_budget(0, 0);
7133                static constexpr int64_t kAutoChunks[] = {32768, 16384, 8192, 6144, 4096, 3072, 2048, 1024, 512, 256};
7134                for (const int64_t c : kAutoChunks) {
7135                    if (c > 8192 && (c > o.prefill_auto_max || c > o.max_context)) continue;   // #282, as plan_lend
7136                    if (fits(c, true, only)) return c;
7137                }
7138                return 0;
7139            };
7140            auto scan = [&](const PfPart* only) -> int64_t {
7141                if (!o.prefill_auto) {   // an explicit --prefill is the operator's number, and a loan of it only has to fit
7142                    for (int64_t c = o.prefill_chunk; c >= 256; c /= 2)
7143                        if (fits(c, false, only)) return c;
7144                    return 0;
7145                }
7146                if (!strata::prefill::Prefill::ring_bytes_enabled()) return old_pick(only);   // STRATA_RING_BYTES=0
7147                const int64_t small = old_pick(only);
7148                const int64_t cap = strata::prefill::Prefill::ring_cap_for(small);
7149                auto probe = [&](int64_t floor) -> int64_t {
7150                    return biggest_chunk(auto_ceiling, [&](int64_t t) -> bool {
7151                        const int64_t room = ring_room(t, only, cap);
7152                        if (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
7156                        return fits(t, true, only);
7157                    });
7158                };
7159                int64_t c = probe(cap);
7160                if (c == 0 && cap < strata::prefill::Prefill::ring_default_slots()) c = probe(kRingMin);
7161                return std::max(c, small);   // never a smaller chunk than 0.1.39's
7162            };
7163            const 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.
7167            const 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
7170            if (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
7173                const int64_t small = old_pick(nullptr);
7174                strata::prefill::Prefill::set_ring_budget(
7175                    small >= chunk ? 0 : (int) ring_room(chunk, nullptr, strata::prefill::Prefill::ring_cap_for(small)),
7176                    small);
7177            }
7178            if (chunk > 0 && alone > chunk) {
7179                for (size_t i = 1; i < pf_parts.size(); ++i) {
7180                    const PfPart& p = pf_parts[i];
7181                    if (fits_one(p, alone, o.prefill_auto)) continue;
7182                    const int dev = p.dev < 0 ? 0 : p.dev;
7183                    dpct::device_info prop{};
7184                    if (DPCT_CHECK_ERROR(
7185                            dpct::get_device(dev).get_device_info(prop)) != 0) {
7186                        /*
7187                        DPCT1010: SYCL uses exceptions to report errors and
7188                        does not use the error codes. The cudaGetLastError
7189                        function call was replaced with 0. You need to rewrite
7190                        this code.
7191                        */
7192                        (void)0;
7193                        prop.get_name()[0] = 0;
7194                    }
7195                    const std::string pct =
7196                        o.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,
7205                                 prop.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",
7212                                 dev == 1 ? "--expert-cache-device1 N" : "--expert-cache-device1..3 N, in order");
7213                }
7214            }
7215            if (chunk > 0) {
7216                if (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));
7223                else 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);
7226                o.prefill_chunk = chunk;
7227                for (PfPart& p : pf_parts) {
7228                    p.first = (int32_t) (p.cache->slots() - part_slots(p, chunk));
7229                    p.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).
7237                static const bool own_ok = [] {
7238                    const char* v = std::getenv("STRATA_SPLIT_OWN_BUFFERS");
7239                    return v == nullptr || v[0] != '0';
7240                }();
7241                if (pf_parts.size() > 1 && own_ok) {
7242                    for (PfPart& p : pf_parts) {
7243                        const strata::core::OnDevice on(p.dev);
7244                        size_t fb = 0, tb = 0;
7245                        /*
7246                        DPCT1010: SYCL uses exceptions to report errors and
7247                        does not use the error codes. The cudaGetLastError
7248                        function call was replaced with 0. You need to rewrite
7249                        this code.
7250                        */
7251                        /*
7252                        DPCT1106: 'cudaMemGetInfo' was migrated with the
7253                        Intel extensions for device information which may not be
7254                        supported by all compilers or runtimes. You may need to
7255                        adjust the code.
7256                        */
7257                        if (DPCT_CHECK_ERROR(
7258                                dpct::get_current_device().get_memory_info(
7259                                    fb, tb)) != 0) {
7260                            (void)0; continue;
7261                        }
7262                        const uint64_t need = strata::prefill::Prefill::bytes_needed(g, *p.ses, chunk);
7263                        if ((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);
7267                            p.first = -1;
7268                            p.first_now = -1;
7269                        }
7270                    }
7271                }
7272                lend_first = pf_parts[0].first;
7273                borrow = lend_first >= 0 ? xcache.device_slot(lend_first) : nullptr;
7274                borrow_bytes = lend_first >= 0 ? part_bytes(pf_parts[0], lend_first) : 0;
7275            } else if (o.prefill_auto) {
7276                o.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);
7284                for (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) {
7291            o.prefill_chunk = 1024;       // #85: no expert cache at all (a full 8 GB card): small buffers of its own
7292        }
7293        bool any_loan = borrow != nullptr;
7294        for (size_t i = 1; i < pf_parts.size(); ++i) any_loan = any_loan || pf_parts[i].first >= 0;
7295        if (any_loan) {
7296            if (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);
7299            for (size_t i = 1; i < pf_parts.size(); ++i)   // one loan per stage, from that stage's own cache
7300                if (pf_parts[i].first >= 0) std::fprintf(stderr, "strata serve:   CUDA%d prompt path borrows %lld of its %lld slots (%.2f GiB)\n",
7301                             pf_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        }
7307        rss_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).
7313        auto init_prompt_paths = [&]() -> int {   // 0: ready; 1: failed (err set); 2: failed with "do not fit"
7314            for (size_t i = 0; i < stages.size(); ++i) {
7315                GpuStage& st = *stages[i];
7316                st.sp.set_stage(st.lb, i + 1 < stages.size() ? st.le : -1, i + 1 < stages.size() ? &stages[i + 1]->sp : nullptr);
7317                const strata::core::OnDevice on(st.dev);
7318                void* sb = nullptr;              // this stage's own loan, out of its own cache
7319                uint64_t sbb = 0;
7320                // `first < 0`: no loan was taken (nothing was lendable), so this stage allocates its own buffers
7321                if (i + 1 < pf_parts.size() && pf_parts[i + 1].first >= 0) {
7322                    sb = st.cache.device_slot(pf_parts[i + 1].first);
7323                    sbb = part_bytes(pf_parts[i + 1], pf_parts[i + 1].first);
7324                }
7325                if (!st.sp.init(st.wt, g, st.ss, srcp, &st.cache, host_res.data(), o.prefill_chunk, (void*) st.stream,
7326                                err, sb, sbb)) {
7327                    err = "layer split, CUDA" + std::to_string(st.dev) + " prompt path: " + err;
7328                    return err.find("do not fit") != std::string::npos ? 2 : 1;
7329                }
7330            }
7331            if (multi_gpu) sp.set_stage(0, split_at[0], &stages[0]->sp);
7332            if (!sp.init(wt, g, ss, srcp, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes))
7333                return err.find("do not fit") != std::string::npos ? 2 : 1;
7334            return 0;
7335        };
7336        static 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.
7341            const int64_t kHeadroom = 512ll << 20;
7342            auto own_fits = [&](int64_t c, int &dev_out, int64_t &need_out,
7343                                int64_t &free_out) -> bool {
7344                try {
7345            for (size_t i = 0; i <= stages.size(); ++i) {
7346                    const bool loan = i == 0 ? borrow != nullptr : (i < pf_parts.size() && pf_parts[i].first >= 0);
7347                    if (loan) continue;
7348                    const int dev = i == 0 ? -1 : stages[i - 1]->dev;
7349                    const strata::core::OnDevice on(dev);
7350                    size_t fb = 0, tb = 0;
7351                    /*
7352                    DPCT1106: 'cudaMemGetInfo' was migrated with the Intel
7353                    extensions for device information which may not be supported
7354                    by all compilers or runtimes. You may need to adjust the
7355                    code.
7356                    */
7357                    dpct::get_current_device().get_memory_info(fb, tb);
7358                    const int64_t need = (int64_t) strata::prefill::Prefill::bytes_needed(g, i == 0 ? ss : stages[i - 1]->ss, c);
7359                    if (need + kHeadroom > (int64_t) fb) {
7360                        dev_out = dev < 0 ? 0 : dev; need_out = need; free_out = (int64_t) fb;
7361                        return false;
7362                    }
7363                }
7364                return true;
7365            }
7366            catch (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            };
7372            int dev = 0;
7373            int64_t need = 0, fb = 0;
7374            if (!own_fits(o.prefill_chunk, dev, need, fb)) {
7375                int64_t c = 0;
7376                for (const int64_t s : kStepChunks) {
7377                    int d2 = 0;
7378                    int64_t n2 = 0, f2 = 0;
7379                    if (s < o.prefill_chunk && own_fits(s, d2, n2, f2)) { c = s; break; }
7380                }
7381                if (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);
7385                    o.prefill_chunk = c;
7386                }
7387            }
7388        }
7389        for (;;) {
7390            const int r = init_prompt_paths();
7391            if (r == 0) break;
7392            int64_t next = 0;
7393            for (const int64_t c : kStepChunks)
7394                if (c < o.prefill_chunk) { next = c; break; }
7395            if (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
7399                for (auto& stp : stages) {
7400                    const strata::core::OnDevice on(stp->dev);
7401                    stp->sp.reset();
7402                    /*
7403                    DPCT1010: SYCL uses exceptions to report errors and
7404                    does not use the error codes. The cudaGetLastError function
7405                    call was replaced with 0. You need to rewrite this code.
7406                    */
7407                    (void)0;
7408                }
7409                sp.reset();
7410                /*
7411                DPCT1010: SYCL uses exceptions to report errors and does
7412                not use the error codes. The cudaGetLastError function call was
7413                replaced with 0. You need to rewrite this code.
7414                */
7415                (void)0;
7416                o.prefill_chunk = next;
7417                if (any_loan) {                  // smaller loans for the smaller chunk
7418                    for (PfPart& p : pf_parts)
7419                        if (p.first >= 0) {
7420                            p.first = (int32_t) (p.cache->slots() - part_slots(p, next));
7421                            p.first_now = p.first;
7422                        }
7423                    lend_first = pf_parts[0].first;
7424                    borrow = lend_first >= 0 ? xcache.device_slot(lend_first) : nullptr;
7425                    borrow_bytes = lend_first >= 0 ? part_bytes(pf_parts[0], lend_first) : 0;
7426                }
7427                err.clear();
7428                continue;
7429            }
7430            std::fprintf(stderr, "strata serve: %s\n", err.c_str());
7431            if (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");
7435            return 1;
7436        }
7437        if (peer.valid() && o.peer_prefill_rows != 0) {
7438            const int64_t rows = o.peer_prefill_rows > 0 ? o.peer_prefill_rows : o.prefill_chunk * K / 2;
7439            if (!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());
7441                err.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
7446        if (multi_gpu && !stages.empty()) {
7447            std::vector<std::pair<strata::prefill::Prefill*, int>> paths{{&sp, 0}};
7448            for (const auto& st : stages) paths.emplace_back(&st->sp, st->dev);
7449            for (size_t i = 0; i < paths.size(); ++i) {
7450                const strata::core::OnDevice on(paths[i].second);
7451                if (!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);
7453                    err.clear();
7454                }
7455            }
7456        }
7457        mem_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.
7464        int64_t split_small = 0, split_small_max = 0;
7465        if (multi_gpu && !pf_parts.empty() && !host_res.empty()) {
7466            const char* v = std::getenv("STRATA_SPLIT_SMALL_OWN");
7467            const int64_t S = v ? request_chunk(std::atoll(v), o.prefill_chunk) : 0;
7468            const char* vm = std::getenv("STRATA_SPLIT_SMALL_MAX");
7469            split_small = S;
7470            split_small_max = S > 0 ? std::max<int64_t>(S, vm ? std::atoll(vm) : S) : 0;
7471            int64_t evicted = 0;
7472            for (PfPart& p : pf_parts) {
7473                if (S <= 0 || p.first < 0) continue;
7474                const int32_t first_s = std::max<int32_t>(p.first, (int32_t) (p.cache->slots() - part_slots(p, S)));
7475                int64_t n = 0;
7476                for (int64_t l = p.lb; l < p.le; ++l)
7477                    for (int64_t ex = 0; ex < g.n_expert; ++ex) {
7478                        int32_t& r = host_res[(size_t) (l * g.n_expert + ex)];
7479                        if (r >= first_s) { r = strata::core::kNotResident; ++n; }
7480                    }
7481                evicted += 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            }
7486            if (evicted > 0) {
7487                if (d_res != nullptr)
7488                    res_put(d_res);
7489                for (auto& st : stages) {
7490                    const strata::core::OnDevice on(st->dev);
7491                    res_put(st->d_res);
7492                }
7493            }
7494        }
7495        kvg_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).
7500        constexpr int kPenaltyWindowCap = 4096;
7501        constexpr size_t kHistSlots = (size_t) kPenaltyWindowCap * (size_t) strata::kernels::kVerifyMaxT;
7502        int32_t* d_hist = nullptr;
7503        std::vector<int32_t> hist_stage(kHistSlots, -1);
7504        const int hist_dev = last_st ? last_st->dev : -1;   // with the head: the last stage's device
7505        if (const strata::core::OnDevice on_h(hist_dev);
7506            DPCT_CHECK_ERROR(d_hist = sycl::malloc_device<int32_t>(
7507                                 kHistSlots, dpct::get_in_order_queue())) !=
7508            0) {
7509            std::fprintf(stderr, "strata serve: the penalty-history allocation failed\n");
7510            return 1;
7511        }
7512        strata::core::Verifier ver;
7513        strata::core::VerifyHits vh;
7514        int32_t* usage_dev_srv = nullptr;
7515        vh.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.
7518        if (mirror_table_d && !o.expert_profile_save.empty()) {
7519            usage_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        }
7522        if (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));
7523        vh.h_res = host_res.empty() ? nullptr : host_res.data();
7524        vh.cache_base = thits.cache_base;
7525        vh.blob = thits.blob;
7526        vh.slot_off = xcache.slot_offsets();   // E-6: the device plan's pointers
7527        vh.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;
7532        SplitDrive split_drive;
7533        auto stage_ver = [&](int st) -> strata::core::Verifier& {
7534            return st == 0 ? ver : split_same ? ver_same : stages[(size_t) st - 1]->ver;
7535        };
7536        auto pcie_num_of = [](double f) { return std::max(0, std::min(256, (int) (f * 256.0 + 0.5))); };
7537        const 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
7541        const bool pipe = o.pipeline_windows > 0 && n_stages == 2 && !split_same && stages.size() == 1;
7542        strata::core::Verifier ver_b;
7543        SplitDrive split_drive_b;
7544        dpct::queue_ptr pl_stream[2] = {&dpct::get_in_order_queue(),
7545                                        &dpct::get_in_order_queue()};
7546        if (pipe) {
7547            /*
7548            DPCT1025: The SYCL queue is created ignoring the flag and
7549            priority options.
7550            */
7551            bool ok_p =
7552                DPCT_CHECK_ERROR(
7553                    pl_stream[0] =
7554                        dpct::get_current_device().create_queue(true)) == 0;
7555            {
7556                const strata::core::OnDevice on(stages[0]->dev);
7557                /*
7558                DPCT1025: The SYCL queue is created ignoring the flag and
7559                priority options.
7560                */
7561                ok_p =
7562                    ok_p &&
7563                    DPCT_CHECK_ERROR(
7564                        pl_stream[1] =
7565                            dpct::get_current_device().create_queue(true)) == 0;
7566            }
7567            if (!ok_p) { std::fprintf(stderr, "strata serve: --pipeline-windows: stream creation failed\n"); return 1; }
7568            for (strata::core::Verifier* v : {&ver, &ver_b}) {
7569                v->set_stream(pl_stream[0]);
7570                v->set_always_publish(true);
7571                v->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            }
7574            for (strata::core::Verifier* v : {&stages[0]->ver, &stages[0]->ver_b}) {
7575                v->set_stream(pl_stream[1]);
7576                v->set_always_publish(true);
7577                v->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        }
7581        if (n_stages > 1) {
7582            const 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);
7585            for (float*& h : hand) {
7586                float* hh = nullptr;
7587                /*
7588                DPCT1048: The original value cudaHostAllocMapped is not
7589                meaningful in the migrated code and was removed or replaced with
7590                0. You may need to check the migrated code.
7591                */
7592                /*
7593                DPCT1048: The original value cudaHostAllocPortable is not
7594                meaningful in the migrated code and was removed or replaced with
7595                0. You may need to check the migrated code.
7596                */
7597                if (DPCT_CHECK_ERROR(hh = (float *)sycl::malloc_host(
7598                                         hb, dpct::get_in_order_queue())) !=
7599                        0 ||
7600                    DPCT_CHECK_ERROR(*(void **)&h = (float *)hh) != 0) {
7601                    std::fprintf(stderr, "strata serve: the layer-split hand-off allocation failed\n");
7602                    return 1;
7603                }
7604                std::memset(hh, 0, hb);
7605            }
7606            split_drive.base = &drive;
7607            split_drive.n = n_stages;
7608            for (int st = 0; st < n_stages; ++st) {
7609                stage_ver(st).set_stage(st == 0 ? 0 : split_at[(size_t) st - 1], st + 1 < n_stages ? split_at[(size_t) st] : -1,
7610                                        st == 0 ? nullptr : hand[(size_t) st - 1], st + 1 < n_stages ? hand[(size_t) st] : nullptr);
7611                split_drive.end[st] = st + 1 < n_stages ? split_at[(size_t) st] : g.n_layers;
7612                split_drive.cache_base[st] = drive.d.cache_base;
7613                split_drive.cache_slot_off[st] = drive.d.cache_slot_off;
7614                split_drive.pcie_num[st] = pcie_num_of(o.pcie_frac);
7615            }
7616            for (int st = 1; st < n_stages; ++st) {
7617                bool ok_s = false;
7618                if (split_same) {
7619                    ok_s = ver_same.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, std::max(o.spec, o.batch), err);
7620                } else {
7621                    GpuStage& gs = *stages[(size_t) st - 1];
7622                    const strata::core::OnDevice on(gs.dev);
7623                    strata::core::VerifyHits vs;
7624                    vs.d_res = gs.d_res;
7625                    vs.h_res = host_res.empty() ? nullptr : host_res.data();
7626                    vs.cache_base = gs.cache.device_slot(0);
7627                    vs.blob = thits.blob;
7628                    vs.slot_off = gs.cache.slot_offsets();
7629                    vs.n_slots = gs.cache.slots();
7630                    gs.ver.set_remote_expert_opt(remote_opt.get());
7631                    ok_s = gs.ver.init(gs.wt, g, gs.ss, vs, gs.head.loaded() ? &gs.head : nullptr, std::max(o.spec, o.batch), err);
7632                    split_drive.cache_base[st] = gs.cache.device_slot(0);
7633                    split_drive.cache_slot_off[st] = gs.cache.slot_offsets();
7634                    split_drive.pcie_num[st] = pcie_num_of(gs.pcie_frac);
7635                }
7636                if (!ok_s) {
7637                    std::fprintf(stderr, "strata serve: layer split, stage %d: %s\n", st + 1, err.c_str());
7638                    return 1;
7639                }
7640            }
7641            for (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)";
7643            for (int st = 1; st < n_stages; ++st)
7644                plan_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
7650        float* pl_mtp_R = nullptr;
7651        if (pipe) {
7652            const size_t hb = (size_t) strata::kernels::kVerifyMaxT *
7653                              (size_t) strata::core::Verifier::handoff_floats(g) * sizeof(float);
7654            float *hh = nullptr, *hand_b = nullptr;
7655            /*
7656            DPCT1048: The original value cudaHostAllocMapped is not
7657            meaningful in the migrated code and was removed or replaced with 0.
7658            You may need to check the migrated code.
7659            */
7660            /*
7661            DPCT1048: The original value cudaHostAllocPortable is not
7662            meaningful in the migrated code and was removed or replaced with 0.
7663            You may need to check the migrated code.
7664            */
7665            if (DPCT_CHECK_ERROR(hh = (float *)sycl::malloc_host(
7666                                     hb, dpct::get_in_order_queue())) != 0 ||
7667                DPCT_CHECK_ERROR(*(void **)&hand_b = (float *)hh) != 0) {
7668                std::fprintf(stderr, "strata serve: --pipeline-windows: the second hand-off allocation failed\n");
7669                return 1;
7670            }
7671            std::memset(hh, 0, hb);
7672            GpuStage& gs = *stages[0];
7673            ver_b.set_stage(0, split_at[0], nullptr, hand_b);
7674            gs.ver_b.set_stage(split_at[0], -1, hand_b, nullptr);
7675            {
7676                const strata::core::OnDevice on(gs.dev);
7677                strata::core::VerifyHits vs;
7678                vs.d_res = gs.d_res;
7679                vs.h_res = host_res.empty() ? nullptr : host_res.data();
7680                vs.cache_base = gs.cache.device_slot(0);
7681                vs.blob = thits.blob;
7682                vs.slot_off = gs.cache.slot_offsets();
7683                vs.n_slots = gs.cache.slots();
7684                if (!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",
7687                                 gs.dev, err.c_str());
7688                    return 1;
7689                }
7690                if (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");
7695                    return 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.
7701                const strata::core::OnDevice on_first(0);
7702                if (!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());
7705                    return 1;
7706                }
7707            }
7708            ver_b.set_next(&gs.ver_b, &split_drive_b);   // the setters reach it; the pipeline never chains run/commit
7709        }
7710        ver.set_remote_expert_opt(remote_opt.get());
7711        if (use_df2) ver.set_taps(df2.tap_layers());
7712        if (batch_mtp) ver.set_batch_graph_limit(64);   // --batch-mtp only: slot rotation makes many layouts (LRU); 0.1.39 keeps all
7713        if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr,
7714                      batch_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,
7716                                  pipe ? pl_mtp_R : ver.final_R_all(), err))) {
7717            print_start_refusal("strata serve", err);
7718            return 1;
7719        }
7720        if (pipe) mtp.set_source_R(ver.final_R_all());   // the serial decode's rows (the last stage's even verifier)
7721        if (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;
7723            df2.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
7724            if (!ver.tapping()) why_not = "the verifier keeps no taps here";
7725            else 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)) {
7727                if (why_not.empty()) why_not = "the drafter could not be set up";
7728            }
7729            if (!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());
7732                return 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
7736            sp.on_taps = [&](const float* taps, int64_t rows, int64_t pos0, std::string& e) -> bool {
7737                static const bool skip = std::getenv("STRATA_DF2_NO_PROMPT_CTX") != nullptr;
7738                static const bool timing = std::getenv("STRATA_DF2_TIMING") != nullptr;
7739                if (skip) return true;
7740                const Clock::time_point t = Clock::now();
7741                const bool ok = df2.context(taps, rows, pos0, e);
7742                if (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());
7743                return 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",
7746                         o.draft_model.c_str(), df2.ms_capture, o.spec);
7747        }
7748        const bool draft_on = use_mtp || use_df2;   // some drafter proposes
7749        auto free_slot_mtp_rows = [](float *p) {
7750                                                 try {
7751        if (p != nullptr) (void) DPCT_CHECK_ERROR(sycl::free(p, dpct::get_in_order_queue())); }
7752        catch (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;
7759        if (batch_mtp) {
7760            for (int b = 0; b < o.batch; ++b) {
7761                float* r = nullptr;
7762                const size_t bytes = (size_t) o.spec * (size_t) g.hc * (size_t) g.n_embd * sizeof(float);
7763                if (DPCT_CHECK_ERROR(r = (float *)sycl::malloc_device(
7764                                         bytes, dpct::get_in_order_queue())) !=
7765                    0) {
7766                    std::fprintf(stderr, "strata serve: batch MTP slot %d residual buffer does not fit%s\n",
7767                                 b, vram_free_note().c_str());
7768                    return 1;
7769                }
7770                slot_mtp_rows.emplace_back(r, free_slot_mtp_rows);
7771                if (!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(),
7773                                 vram_free_note().c_str());
7774                    return 1;
7775                }
7776            }
7777        }
7778        // each stage's verifier gets its stage's slot sessions
7779        if (o.batch > 0) {
7780            for (size_t k = 0; k < bslot_ss.size(); ++k) {
7781                std::vector<strata::core::SessionState*> ptrs;
7782                for (auto& u : bslot_ss[k]) ptrs.push_back(u.get());
7783                strata::core::Verifier& vk = k == 0 ? ver : stages[k - 1]->ver;
7784                const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev);
7785                if (!vk.init_slots(ptrs, err)) {
7786                    std::fprintf(stderr, "strata serve: --batch, stage %zu: %s\n", k + 1, err.c_str());
7787                    return 1;
7788                }
7789            }
7790        }
7791        for (int st = 0; st < n_stages && n_stages > 1; ++st) {
7792            split_drive.plan[st] = stage_ver(st).plan_sink();
7793            if (st > 0) {
7794                stage_ver(st).set_split(o.spec_split);
7795                stage_ver(st).set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2);
7796            }
7797        }
7798        if (pipe) {   // the odd windows' pool routing: the same as the even ones', with their plans
7799            split_drive_b = split_drive;
7800            split_drive_b.plan[0] = ver_b.plan_sink();
7801            split_drive_b.plan[1] = stages[0]->ver_b.plan_sink();
7802            stages[0]->ver_b.set_split(o.spec_split);
7803            stages[0]->ver_b.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2);
7804            ver_b.set_split(o.spec_split);
7805            ver_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
7808        const strata::core::PoolMultiFn win_pool_fn = n_stages > 1 ? &drive_pool_split : &drive_pool_multi;
7809        void* const win_pool_user = n_stages > 1 ? (void*) &split_drive : (void*) &drive;
7810        mem_mark("the verifier and the drafter's binding");
7811        ver.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).
7816        ver.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).
7821        const size_t pl_snap_bytes = pipe ? gdn_snapshot_bytes(ss) : 0;
7822        float* 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},
7825                        pl_snap_ev[2] = {nullptr, nullptr};
7826        bool pl_snap_overlap = false;
7827        if (pipe && o.pipeline_windows >= 2) {
7828            if (DPCT_CHECK_ERROR(
7829                    pl_snap2[0] = (float *)sycl::malloc_device(
7830                        pl_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                /*
7834                DPCT1026: The call to cudaGetLastError was removed because
7835                this functionality is redundant in SYCL.
7836                */
7837                pl_snap2[0] = nullptr;
7838            } else if ([] { const char* v = pipe_dbg_env("STRATA_PIPELINE_SNAP_OVERLAP"); return v == nullptr || std::atoi(v) != 0; }()) {
7839                pl_snap_overlap =
7840                    DPCT_CHECK_ERROR(
7841                        pl_snap2[1] = (float *)sycl::malloc_device(
7842                            pl_snap_bytes, dpct::get_in_order_queue())) == 0 &&
7843                    /*
7844                    DPCT1025: The SYCL queue is created ignoring the flag
7845                    and priority options.
7846                    */
7847                    DPCT_CHECK_ERROR(
7848                        pl_snap_stream =
7849                            dpct::get_current_device().create_queue(true)) == 0;
7850                for (int i = 0; i < 2 && pl_snap_overlap; ++i)
7851                    pl_snap_overlap =
7852                        DPCT_CHECK_ERROR(pl_snap_pre[i] = new sycl::event()) ==
7853                            0 &&
7854                        DPCT_CHECK_ERROR(pl_snap_ev[i] = new sycl::event()) ==
7855                            0;
7856                /*
7857                DPCT1010: SYCL uses exceptions to report errors and does
7858                not use the error codes. The cudaGetLastError function call was
7859                replaced with 0. You need to rewrite this code.
7860                */
7861                if (!pl_snap_overlap) 0;
7862            }
7863        }
7864        if (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,
7867                         pl_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}};
7872        SplitDrive* PSD[2] = {&split_drive, &split_drive_b};
7873        dpct::event_ptr pl_mtp_ev[2] = {nullptr, nullptr};
7874        bool pl_mtp_live[2] = {false, false};
7875        bool pl_prepared = false;
7876        if(strata::kernels::b60_layout_requested()&&strata::kernels::b60_single_actor_requested()){
7877            b60_layouts.bind_single(xcache,host_res,strata::kernels::cpu::expert_layout());
7878            b60_layouts.packed(true);
7879        } else if(strata::kernels::b60_layout_requested()){
7880            if(!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)
7881                throw std::invalid_argument("B60 layout candidate requires the fixed all-resident two-stage decode scene");
7882            const char* pvr=std::getenv("STRATA_PRIVATE_PACKED_REGISTER");
7883            if(!pvr||pvr[0]!='1')throw std::invalid_argument("B60 packed weights require the packed register reader");
7884            const auto& layout=strata::kernels::cpu::expert_layout();
7885            b60_layouts.add_device(0,0,split_at[0],wt,xcache,host_res,layout);
7886            for(auto& st:stages)b60_layouts.add_device(st->dev,st->lb,st->le,st->wt,st->cache,host_res,layout,&st->head);
7887            b60_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)
7890        auto pl_prepare = [&](std::string &e) -> bool {
7891            try {
7892        if (pl_prepared) return true;
7893            for (int st = 0; st < 2; ++st)
7894                for (int par = 0; par < 2; ++par) {
7895                    const strata::core::OnDevice on(PV[st][par]->device());
7896                    if (!PV[st][par]->capture_all(e)) return false;
7897                }
7898            if (!mtp.prepare_prefill(e)) return false;
7899            if (o.pipeline_windows >= 2 && pl_snap2[0] != nullptr && !mtp.prepare_chain(e)) return false;
7900            const strata::core::OnDevice on(mtp.device());
7901            for (dpct::event_ptr &ev : pl_mtp_ev)
7902                if (ev == nullptr &&
7903                    DPCT_CHECK_ERROR(ev = new sycl::event()) != 0) {
7904                    e = "pipeline: event creation failed";
7905                    return false;
7906                }
7907            pl_prepared = true;
7908            return true;
7909        }
7910        catch (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.
7919        auto pl_drain = [&]() {
7920            try {
7921        std::string e2;
7922            for (int round = 0; round < 10000000; ++round) {
7923                bool any = false;
7924                for (int st = 0; st < 2; ++st)
7925                    for (int par = 0; par < 2; ++par) {
7926                        strata::core::Verifier& v = *PV[st][par];
7927                        if (!v.in_flight()) continue;
7928                        any = true;
7929                        if (v.service(&drive_pool_split, PSD[par], e2) < 0) return;
7930                        if (v.done(e2)) v.pl_finish(nullptr, e2);
7931                        else if (!e2.empty()) return;
7932                    }
7933                if (!any) break;
7934            }
7935            for (int st = 0; st < 2; ++st) {
7936                const strata::core::OnDevice on(PV[st][0]->device());
7937                PV[st][0]->stream()->wait();
7938            }
7939            const strata::core::OnDevice on(mtp.device());
7940            mtp.stream()->wait();
7941        }
7942        catch (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;
7958        bool live_ok = false;
7959        std::vector<ConvCheckpoint> checks;
7960        uint64_t check_clock = 0;   // the checkpoints' LRU clock; creation and every use advance it
7961        int64_t tail_ckpt_len = -1;   // --prompt-cache-tail: the length of the one tail checkpoint alive (-1 = none)
7962        bool 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(
7966            o.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;
7973        auto session_identity = [&](strata::core::SessionFileIdentity& id, std::string& e,
7974                                    const std::function<void()>& next_file) -> bool {
7975            if (!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;
7979                in.native_shards = o.native_shards;
7980                in.native_dense = o.native_dense_gguf;
7981                in.native_head = o.native_head_shards;
7982                in.embedding = o.embd_gguf;
7983                in.ple = o.ple_gguf;
7984                in.pack = o.pack;
7985                in.mtp = o.mtp.empty() ? std::string() : o.mtp + "/dense.bin";
7986                if (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)
7989                if (!o.pack.empty()) {
7990                    for (const char* n : {"index.txt", "dense.bin"}) files.push_back({std::string("pack ") + n, o.pack + "/" + n});
7991                    for (const char* n : {"embd.bin", "extra.bin", "manifest.json"})
7992                        files.push_back({std::string("pack ") + n, o.pack + "/" + n, true});
7993                    if (srcp == nullptr) files.push_back({"pack experts.bin", o.pack + "/experts.bin", true});
7994                }
7995                if (!o.mtp.empty()) {
7996                    for (const char* n : {"dense.txt", "experts.bin"}) files.push_back({std::string("mtp ") + n, o.mtp + "/" + n});
7997                    files.push_back({"mtp draft_vocab.bin", o.mtp + "/draft_vocab.bin", true});
7998                }
7999                uint64_t fp = 0;
8000                // each file is one blocking read of at most 2 MiB (head and tail): announced before it starts
8001                if (next_file) next_file();
8002                if (!strata::core::session_model_fingerprint(files, fp, e, next_file))
8003                    return false;
8004                model_fp = fp;
8005            }
8006            if (!config_fp) {
8007                strata::core::SessionConfig c;
8008                c.engine_version = STRATA_VERSION;
8009#if defined(STRATA_USE_HIP)
8010                c.backend = "hip";
8011#else
8012                c.backend = "cuda";
8013#endif
8014                c.kv = o.kv;
8015                c.max_context = o.max_context;
8016                c.kv_resident = o.kv_resident;
8017                c.mtp_window = o.mtp.empty() ? -1 : o.mtp_window;
8018                const char* rot = std::getenv("STRATA_KV_ROT");
8019                c.kv_rot = rot != nullptr && rot[0] == '1';
8020                c.rope = {(int64_t) rope_cfg.type, rope_cfg.freq_base, rope_cfg.factor, rope_cfg.freq_scale(),
8021                          rope_cfg.orig_ctx, rope_cfg.ext_factor, rope_cfg.attn_factor, rope_cfg.beta_fast,
8022                          rope_cfg.beta_slow};
8023                c.cvec = cvec_digest;
8024                c.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}};
8036                config_fp = strata::core::session_config_fingerprint(c);
8037            }
8038            id.model = *model_fp;
8039            id.config = *config_fp;
8040            return 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.
8044        struct ParkSource {
8045            const std::vector<int32_t>& ids;
8046            const std::vector<ImgKey>& imgs;
8047            std::vector<ConvCheckpoint>& checks;          ///< moved apart into stage parts for the capture, put back after
8048            bool 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)
8051            const strata::core::QsaState* draft0;         ///< the draft layer's K/V saved with stage 0's image (or none)
8052            const strata::core::QsaState* draft_last;     ///< ... with the last stage's image (a split: the drafter's GPU)
8053            bool 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.
8058        auto 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)
8061            if (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).
8067            const 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
8070            const strata::core::QsaState* draft0 = src.draft0;   // no --mtp: no draft K/V (snapshots accept null)
8071            auto 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;
8074            if (n_st > 0) cs = strata::core::conversation_checkpoints_split(std::move(checks), n_st);   // #752: two-phase; a bad_alloc leaves `checks` whole
8075            struct 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};
8079            const strata::core::ConversationView view{src.ids, src.imgs, n_st > 0 ? cs.stage0 : checks, src.cvec};
8080            const 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
8083            auto reuse = src.with_reuse ? conversations.take_reuse_for(src.ids)   // never another conversation's K/V
8084                                        : strata::core::ConversationKvReuse{};
8085            if (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);
8090            stage_reuse.resize(n_st);
8091            reuse.stages.clear();
8092            // the later stages' estimates, each with its own retained K/V when it still fits
8093            size_t stage_estimate = 0, stage_retained = 0;
8094            for (size_t k = 0; k < n_st; ++k) {
8095                auto& st = stages[k];
8096                const strata::core::OnDevice on(st->dev);
8097                const strata::core::ConversationView view_k{src.ids, src.imgs, cs.parts[k], src.cvec};
8098                size_t b = 0;
8099                if (!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",
8101                                 st->dev, err.c_str());
8102                    err.clear();
8103                    return true;
8104                }
8105                if (!stage_reuse[k].kv.empty()) {
8106                    size_t r = 0;
8107                    if (strata::core::conversation_snapshot_capture_bytes(stage_reuse[k], view_k, *src.stage_sessions[k], g,
8108                                                                          draft_of(k), r, err)) {
8109                        b = r;
8110                        stage_retained += stage_reuse[k].bytes();
8111                    } else {
8112                        stage_reuse[k] = {};
8113                        err.clear();
8114                    }
8115                }
8116                stage_estimate += b;
8117            }
8118            size_t estimate = 0;
8119            if (!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());
8121                err.clear(); // A recoverable miss must not poison the batched draft prefill's error channel.
8122                return true;
8123            }
8124            const size_t fresh_estimate = estimate;
8125            if (!reuse.kv.empty() && !strata::core::conversation_snapshot_capture_bytes(
8126                    reuse, view, src.session, g, draft0, estimate, err)) {
8127                reuse = {};
8128                estimate = fresh_estimate;
8129                err.clear();
8130            }
8131            estimate += 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.
8138            if (!conversations.make_room(estimate, held)) {
8139                std::fprintf(stderr, "strata serve: conversation cache: skip parking (snapshot %zu MiB exceeds available budget)\n",
8140                             estimate >> 20);
8141                return true;
8142            }
8143            const auto t0 = Clock::now();
8144            try {
8145                const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib * 1024 * 1024;
8146                const size_t retained = reuse.bytes() + stage_retained;
8147                const size_t additional = estimate > retained ? estimate - retained : 0;
8148                if (!strata::core::conversation_memory_admit(strata::core::available_host_bytes(),
8149                        additional, 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",
8151                                 additional >> 20, (long long) o.conversation_cache_min_free_mib);
8152                    return true;
8153                }
8154                strata::core::SavedConversation image;
8155                size_t reused_bytes = 0;
8156                if (!strata::core::conversation_snapshot_save(image, view, src.session, g, draft0, err,
8157                        std::move(reuse), &reused_bytes)) return false;
8158                for (size_t k = 0; k < n_st; ++k) {   // the later stages (the last one with the draft layer's K/V)
8159                    auto& st = stages[k];
8160                    const strata::core::OnDevice on(st->dev);
8161                    if (DPCT_CHECK_ERROR(dpct::get_current_device()
8162                                             .queues_wait_and_throw()) != 0) {
8163                        err = "stage sync failed"; return false;
8164                    }
8165                    const strata::core::ConversationView view_k{src.ids, src.imgs, cs.parts[k], src.cvec};
8166                    strata::core::SavedConversation part;
8167                    if (!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))
8169                        return false;
8170                    image.stage_images.push_back(std::move(part));
8171                }
8172                if (!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");
8174                    return true;
8175                }
8176                const size_t snapshot_bytes = image.bytes();
8177                const 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",
8179                             stored ? "parked" : "skipped", src.ids.size(), src.what.c_str(),
8180                             std::chrono::duration<double, std::milli>(Clock::now() - t0).count(),
8181                             conversations.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            }
8187            return true;
8188        };
8189        auto park_current_body = [&](size_t held) -> bool {
8190            if (!conversations.enabled() || !live_ok || live.empty()) return true;
8191            const size_t n_st = stages.size();
8192            ParkSource src{live, live_imgs, checks, cvec_cached, ss, {},
8193                           n_st > 0 || !use_mtp ? nullptr : &mtp.kv_state(),
8194                           use_mtp && n_st > 0 ? &mtp.kv_state() : nullptr, true, ""};
8195            for (auto& st : stages) src.stage_sessions.push_back(&st->ss);
8196            return 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
8200        auto park_current = [&](size_t held) -> bool {
8201            try { return park_current_body(held); }
8202            catch (const std::bad_alloc&) {
8203                std::fprintf(stderr, "strata serve: conversation cache: allocation failed; skip parking\n");
8204                return true;
8205            }
8206        };
8207        int64_t pp_total = 0, pp_from = 0, pp_next_check = 0;
8208        bool 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
8211        int64_t pp_reached = 0;
8212        Clock::time_point pp_t0 = Clock::now();
8213        auto imgs_below = [&](const std::vector<ImgKey>& all, int64_t L) {
8214            std::vector<ImgKey> v;
8215            for (const ImgKey& k : all) if (k.start < L) v.push_back(k);
8216            return 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;
8230        auto gpu_sync_ok = [&]() -> bool {
8231            try {
8232        const dpct::err0 e = DPCT_CHECK_ERROR(
8233            dpct::get_current_device().queues_wait_and_throw());
8234            if (e == 0) return true;
8235            /*
8236            DPCT1009: SYCL reports errors using exceptions and does not use
8237            error codes. Please replace the "get_error_string_dummy(...)" with a
8238            real error-handling function.
8239            */
8240            ckpt_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";
8243            return false;
8244        }
8245        catch (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        };
8251        auto checkpoint_at = [&](int64_t L, std::vector<ConvCheckpoint>* parts = nullptr, bool as_tail = false) -> bool {
8252            ckpt_why.clear();
8253            if (o.prompt_cache <= 0 || L < 1) return true;
8254            for (ConvCheckpoint& c : checks)
8255                if ((int64_t) c.ids.size() == L) {
8256                    c.used = ++check_clock;
8257                    if (!as_tail && L == tail_ckpt_len) tail_ckpt_len = -1;   // a periodic one lands here: a normal item now
8258                    return true;
8259                }
8260            ConvCheckpoint c;
8261            c.ids.assign(cur.begin(), cur.begin() + L);
8262            c.imgs = imgs_below(req_imgs, L);
8263            if (parts != nullptr) {
8264                if (parts->size() != stages.size() + 1) return false;
8265                c.gdn = std::move((*parts)[0].gdn);
8266                c.ple = std::move((*parts)[0].ple);
8267                c.tails = std::move((*parts)[0].tails);
8268                c.dead = std::move((*parts)[0].dead);
8269                c.block_pos = std::move((*parts)[0].block_pos);
8270                for (size_t i = 1; i < parts->size(); ++i) c.stage_parts.push_back(std::move((*parts)[i]));
8271            } else {
8272                if (!gpu_sync_ok() || !checkpoint_save(c, ss, g)) return false;
8273                for (auto& st : stages) {   // a layer split's later stages: their sessions' part
8274                    const strata::core::OnDevice on(st->dev);
8275                    ConvCheckpoint part;
8276                    part.ids = c.ids;
8277                    if (!gpu_sync_ok() || !checkpoint_save(part, st->ss, g)) return false;
8278                    c.stage_parts.push_back(std::move(part));
8279                }
8280            }
8281            c.used = ++check_clock;
8282            if (as_tail) {   // only one tail checkpoint stays alive: the previous request's goes
8283                const int64_t old_tail = tail_ckpt_len;
8284                checks.erase(std::remove_if(checks.begin(), checks.end(), [&](const ConvCheckpoint& k) {
8285                                 return old_tail >= 0 && (int64_t) k.ids.size() == old_tail;
8286                             }), checks.end());
8287                tail_ckpt_len = L;
8288            } else if (L == tail_ckpt_len) {
8289                tail_ckpt_len = -1;   // the flagged tail was dropped and a normal checkpoint takes its length
8290            }
8291            checks.push_back(std::move(c));
8292            while ((int) checks.size() > o.prompt_cache) {
8293                std::vector<uint64_t> stamps;
8294                std::vector<char> is_tail;
8295                stamps.reserve(checks.size());
8296                for (const ConvCheckpoint& k : checks) {
8297                    stamps.push_back(k.used);
8298                    is_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()]);
8302                for (size_t i = 0; i < is_tail.size(); ++i) tail_flags[i] = is_tail[i] != 0;
8303                const size_t victim = strata::program::conv_cache::eviction_victim(
8304                    stamps.data(), stamps.size(), o.prompt_cache, tail_flags.get());
8305                checks.erase(checks.begin() + (std::ptrdiff_t) victim);
8306            }
8307            return true;
8308        };
8309        sp.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);
8311            for (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)
8313            const bool batched = use_mtp && !multi_gpu && sp.draft_kv(mtp, R_rows, nxt.data(), T, p0, e);
8314            if (!e.empty() || (use_mtp && !batched && !mtp.prefill(R_rows, nxt.data(), T, p0, e))) return false;
8315            if (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);
8317                for (int64_t t = 0; t < T; ++t) tk[(size_t) t] = (int32_t) cur[(size_t) (p0 + t)];
8318                df2.note_rows(tk.data(), T, p0);
8319            }
8320            if (use_mtp && std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr)
8321                std::fprintf(stderr, "strata serve: DRAFT_PREFILL path=%s mode=%d cells=%lld\n",
8322                             batched ? "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>
8324            const int64_t done = p0 + T;
8325            pp_reached = done;
8326            const 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,
8328                        ms > 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);
8332            const 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.
8335            const 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) &&
8337                pp_total - done <= T;   // this chunk's real size (--prefill auto chunks differ from o.prefill_chunk)
8338            if (periodic_checkpoint || tail_checkpoint) {
8339                bool saved = false;
8340                if (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);
8344                        auto it = part_at.find(done);
8345                        if (it != part_at.end()) parts = std::move(it->second);
8346                        part_at.erase(part_at.begin(), part_at.upper_bound(done));
8347                    }
8348                    bool complete = parts.size() == stages.size() + 1;
8349                    for (const ConvCheckpoint& k : parts) complete = complete && !k.gdn.empty();
8350                    saved = !complete || checkpoint_at(done, &parts);   // an incomplete set: no checkpoint here
8351                } else {
8352                    saved = checkpoint_at(done, nullptr, tail_checkpoint && !periodic_checkpoint);
8353                }
8354                if (!saved) {
8355                    // #3350: only a GPU that is unwell ends the request; a copy that ran out of memory skips this checkpoint
8356                    if (!ckpt_why.empty() || !checkpoint_failure_is_survivable()) {
8357                        e = "saving a conversation checkpoint failed" + ckpt_why;
8358                        return 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                }
8363                if (periodic_checkpoint) pp_next_check = done + o.prompt_cache_every;
8364                if (tail_checkpoint) pp_tail_saved = true;
8365            }
8366            return true;
8367        };
8368        if (multi_gpu) {   // the batched prompt is reported by its last stage (the drafter's rows are there)
8369            stages.back()->sp.on_chunk = std::move(sp.on_chunk);
8370            sp.on_chunk = nullptr;
8371            for (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;
8374                stage_sp.on_stage_chunk = [&, i](int64_t done, std::string& e) -> bool {
8375                    if (o.prompt_cache <= 0 || o.prompt_cache_every <= 0 || done < part_next[i]) return true;
8376                    part_next[i] = done + o.prompt_cache_every;
8377                    ConvCheckpoint part;   // this stage's state at `done` (its stream is synchronized)
8378                    part.ids.assign(cur.begin(), cur.begin() + done);
8379                    if (!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
8382                        if (!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);
8386                        part_at[done].resize(stages.size() + 1);   // (marks the set as seen; its empty parts make it incomplete)
8387                        return true;
8388                    }
8389                    std::lock_guard<std::mutex> lk(part_mu);
8390                    auto& v = part_at[done];
8391                    v.resize(stages.size() + 1);
8392                    v[i] = std::move(part);
8393                    return true;
8394                };
8395            }
8396        }
8397        drive.d.plan = ver.plan_sink();
8398        drive.d.pcie_num = std::max(0, std::min(256, (int) (o.pcie_frac * 256.0 + 0.5)));
8399        const bool all_experts_resident = !host_res.empty() &&
8400            std::all_of(host_res.begin(), host_res.end(), [](int32_t r) { return r >= 0; });
8401        if (o.adapt_every > 0 && o.adapt_swaps > 0 && !all_experts_resident)
8402            drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f);
8403        PcieAuto pcie_auto;
8404        if (o.pcie_frac_auto && !all_experts_resident && o.batch == 0 && n_stages == 1) {
8405            const auto& pl = strata::kernels::cpu::expert_layout();
8406            double sum = 0.0;
8407            for (int64_t l = 0; l < g.n_layers; ++l) sum += (double) pl.blob_bytes(l);
8408            pcie_auto.on = true;
8409            pcie_auto.link_gbps = o.pcie_probe_gbps;
8410            pcie_auto.blob_bytes = g.n_layers > 0 ? sum / (double) g.n_layers : 0.0;
8411        }
8412        auto pcie_auto_step = [&](double& req_pcie_frac) {
8413            if (!pcie_auto.on) return;
8414            double tc_us = 0.0, rate = 0.0;
8415            const 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);
8418            if (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",
8421                         tc_us, rate, pcie_auto.link_gbps, nf, o.pcie_frac);
8422            o.pcie_frac = nf;
8423            req_pcie_frac = nf;
8424            drive.d.pcie_num = std::max(0, std::min(256, (int) (nf * 256.0 + 0.5)));
8425        };
8426        if (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;
8430        if (!o.expert_profile_save.empty() && !all_experts_resident) {
8431            if (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");
8436            else
8437                heat.assign(drive.d.usage.size(), 0.0);
8438        }
8439        Clock::time_point profile_saved_at = Clock::now();
8440        dpct::queue_ptr adapt_stream = &dpct::get_in_order_queue();
8441        /*
8442        DPCT1025: The SYCL queue is created ignoring the flag and priority
8443        options.
8444        */
8445        if (DPCT_CHECK_ERROR(
8446                adapt_stream = dpct::get_current_device().create_queue(true)) !=
8447            0) {
8448            std::fprintf(stderr, "strata serve: cannot create the refill stream\n");
8449            return 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;
8453        int 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;
8456        adapt_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
8458        auto res_upload = [&]() {
8459            try {
8460        if (d_res != nullptr)
8461                res_put(d_res);
8462            for (auto& st : stages) {
8463                const strata::core::OnDevice on(st->dev);
8464                res_put(st->d_res);
8465            }
8466        }
8467        catch (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        };
8473        auto apply_pending = [&](bool wait) {
8474            try {
8475        if (peer.valid()) peer.apply_pending(wait);
8476            if (pending.empty()) return;
8477            if (wait) adapt_ev->wait_and_throw();
8478            else if (adapt_ev->get_info<
8479                         sycl::info::event::command_execution_status>() !=
8480                     sycl::info::event_command_status::complete) return;
8481            for (auto& st : stages)
8482                if (st->adapt_live) {
8483                    if (wait) st->adapt_ev->wait_and_throw();
8484                    else if ((st->adapt_ev)
8485                                 ->get_info<sycl::info::event::
8486                                                command_execution_status>() !=
8487                             sycl::info::event_command_status::complete) return;
8488                }
8489            for (auto& st : stages) st->adapt_live = false;
8490            unpin_blobs(pin_live);
8491            src.commit_exchanges();   // the resident RAM mode: the evicted experts take their places in RAM
8492            for (const auto& [i, slot] : pending) {
8493                host_res[(size_t) i] = slot;
8494                srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert);   // in VRAM now: RAM not needed
8495            }
8496            pending.clear();
8497            pending_age = 0;
8498            res_upload();
8499        }
8500        catch (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)
8509        auto adapt = [&]() -> bool {
8510            if (!pending.empty()) return true;   // the previous swaps are still in flight
8511            if (remote_opt && !remote_opt->adapt(drive.d.usage, host_res, pending, o.adapt_swaps, *srcp)) return false;
8512            struct Swap { float gain; int32_t layer, in, out; };
8513            std::vector<Swap> swaps;
8514            std::vector<std::pair<float, int32_t>> cand, vict;
8515            for (int64_t l = 0; l < g.n_layers; ++l) {
8516                cand.clear();
8517                vict.clear();
8518                const float* u = drive.d.usage.data() + l * g.n_expert;
8519                const int32_t* r = host_res.data() + l * g.n_expert;
8520                for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) {
8521                    if (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); }
8522                    else vict.emplace_back(u[e], e);
8523                }
8524                if (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; });
8526                const 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; });
8529                for (size_t i = 0; i < nc; ++i) {
8530                    if (cand[i].first < vict[i].first + 1.5f) break;
8531                    swaps.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; });
8535            if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps);
8536            if (sycl_mirror_adapt()) {
8537                std::string error;
8538                for (const Swap& s : swaps) {
8539                    const size_t in = (size_t)s.layer * g.n_expert + s.in;
8540                    const size_t out = (size_t)s.layer * g.n_expert + s.out;
8541                    const int32_t slot = host_res[out];
8542                    if (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                    }
8546                    xcache.replace(s.layer, s.out, s.in);
8547                    host_res[out] = strata::core::kNotResident;
8548                    host_res[in] = slot;
8549                }
8550                if (!swaps.empty()) {
8551                    std::vector<unsigned long long> tab(host_res.size(), 0ull);
8552                    for (int64_t l = 0; l < g.n_layers; ++l) for (int64_t e = 0; e < g.n_expert; ++e) {
8553                        const size_t at = (size_t)(l * g.n_expert + e);
8554                        if (host_res[at] < 0) {
8555                            if (!gguf_src.pinned(l, e)) { std::fprintf(stderr, "SYCL mirror adaptive mirror complement missing\n"); return false; }
8556                            tab[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();
8562                    res_upload();
8563                }
8564                for (float& value : drive.d.usage) value *= o.adapt_decay;
8565                return true;
8566            }
8567            // the copies back read the cache of the card that owns each layer (see resident_stage_swaps)
8568            auto home_of = [&](int64_t layer) -> SwapHome {
8569                const int stn = multi_gpu ? stage_of(layer) : 0;
8570                if (stn > 0) {
8571                    GpuStage* gs = stages[(size_t) stn - 1].get();
8572                    return {&gs->cache, gs->adapt_stream, gs->dev};
8573                }
8574                return {&xcache, adapt_stream, -1};
8575            };
8576            if (!resident_stage_swaps(src, host_res, g.n_expert, swaps, home_of)) return false;
8577            if (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;
8579                for (const Swap& s : swaps)
8580                    if (const uint8_t* b = srcp->blob(s.layer, s.in))
8581                        spans.emplace_back((uintptr_t) b,
8582                                           (uintptr_t) b + strata::kernels::cpu::expert_layout().blob_bytes(s.layer));
8583                pin_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;
8590            if (adapt_fence && !swaps.empty()) {
8591                for (const Swap& s : swaps) {
8592                    const size_t out = (size_t) s.layer * g.n_expert + s.out;
8593                    fenced_slots.push_back(host_res[out]);
8594                    host_res[out] = strata::core::kNotResident;
8595                }
8596                std::atomic_thread_fence(std::memory_order_seq_cst);
8597                adapt_fence();
8598            }
8599            bool main_live = false;
8600            // STRATA_DMA_BATCH (F12): the main device's copies as one cudaMemcpyBatchAsync (mode 0: one each)
8601            const 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;
8605            for (size_t si = 0; si < swaps.size(); ++si) {
8606                const Swap& s = swaps[si];
8607                const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out;
8608                const int32_t slot = fenced_slots.empty() ? host_res[out] : fenced_slots[si];
8609                const uint8_t* b = srcp->blob(s.layer, s.in);
8610                const int stn = multi_gpu ? stage_of(s.layer) : 0;   // the swap stays in the layer's own cache
8611                GpuStage* gs = stn > 0 ? stages[(size_t) stn - 1].get() : nullptr;
8612                const strata::core::OnDevice on(gs ? gs->dev : -1);
8613                if (dma_mode != 0 && slot >= 0 && b != nullptr) {
8614                    cp_dst.push_back(xcache.device_slot(slot));
8615                    cp_src.push_back(b);
8616                    cp_bytes.push_back((size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer));
8617                    main_live = true;
8618                    host_res[out] = strata::core::kNotResident;
8619                    srcp->prefetch(s.layer, s.out);
8620                    pending.emplace_back((int32_t) in, slot);
8621                    continue;
8622                }
8623                if (slot < 0 || b == nullptr ||
8624                    adapt_copy_h2d(gs ? gs->cache.device_slot(slot)
8625                                      : xcache.device_slot(slot),
8626                                   b,
8627                                   (size_t)strata::kernels::cpu::expert_layout()
8628                                       .blob_bytes(s.layer),
8629                                   gs ? 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                                 /*
8634                                 DPCT1009: SYCL reports errors using
8635                                 exceptions and does not use error codes. Please
8636                                 replace the "get_error_string_dummy(...)" with
8637                                 a real error-handling function.
8638                                 */
8639                                 /*
8640                                 DPCT1010: SYCL uses exceptions to report
8641                                 errors and does not use the error codes. The
8642                                 cudaGetLastError function call was replaced
8643                                 with 0. You need to rewrite this code.
8644                                 */
8645                                 (int)s.layer, (int)slot,
8646                                 pin_live.empty() ? 0 : 1,
8647                                 dpct::get_error_string_dummy(0));
8648                    return false;
8649                }
8650                if (gs) gs->adapt_live = true;
8651                else main_live = true;
8652                host_res[out] = strata::core::kNotResident;   // evicted now: the CPU computes it meanwhile
8653                srcp->prefetch(s.layer, s.out);   // a file-backed arena released its pages: read them back ahead
8654                pending.emplace_back((int32_t) in, slot);      // resident once the copy has landed
8655            }
8656            if (!cp_dst.empty() &&
8657                strata::core::copy_blobs(cp_dst.data(), cp_src.data(),
8658                                         cp_bytes.data(), cp_dst.size(),
8659                                         adapt_stream, dma_mode) != 0) {
8660                std::fprintf(
8661                    stderr,
8662                    "strata serve: adaptive swap copy failed (batched): %s\n",
8663                    /*
8664                    DPCT1009: SYCL reports errors using exceptions and does
8665                    not use error codes. Please replace the
8666                    "get_error_string_dummy(...)" with a real error-handling
8667                    function.
8668                    */
8669                    /*
8670                    DPCT1010: SYCL uses exceptions to report errors and
8671                    does not use the error codes. The cudaGetLastError function
8672                    call was replaced with 0. You need to rewrite this code.
8673                    */
8674                    dpct::get_error_string_dummy(0));
8675                return false;
8676            }
8677            if (!swaps.empty()) dpct::sync_barrier(adapt_ev, adapt_stream);
8678            (void) main_live;
8679            for (auto& st : stages)
8680                if (st->adapt_live) {
8681                    const 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
8687            for (size_t i = 0; i < heat.size(); ++i) heat[i] += (double) drive.d.usage[i];
8688            if (peer.valid()) {                   // multi-GPU: the peer takes the next most-routed CPU misses
8689                std::vector<int32_t> r0 = host_res;
8690                for (const auto& [i, slot] : pending) r0[(size_t) i] = slot;   // swapped into the primary already
8691                std::string perr;
8692                if (!peer.adapt(drive.d.usage.data(), r0.data(),
8693                                o.peer_adapt_swaps >= 0 ? o.peer_adapt_swaps : o.adapt_swaps, perr)) {
8694                    std::fprintf(stderr, "strata serve: %s\n", perr.c_str());
8695                    return false;
8696                }
8697            }
8698            for (float& v : drive.d.usage) v *= o.adapt_decay;
8699            return 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).
8719        struct ASwap { int32_t layer, in, out, slot; int home; int64_t j; bool exchange; };
8720        struct AHome {
8721            strata::core::ExpertCache *cache; dpct::queue_ptr stream;
8722            dpct::event_ptr ev;
8723            int dev;
8724            bool used;
8725        };
8726        enum class AState { Idle, CopyBack, SwapIn, Commit };
8727        AState astate = AState::Idle;
8728        std::vector<ASwap> aswaps;
8729        std::vector<float> a_usage;
8730        std::vector<int32_t> a_res;
8731        int64_t a_win = 0, a_last = 0, a_rounds = 0, a_swapped = 0;
8732        double a_ms = 0;                  // wall time from a round's start to its flip, summed (the "ms/round" stat)
8733        Clock::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;
8737        const int64_t a_cap = std::min<int64_t>(o.adapt_swaps, 96);   // as the blocking tier's exchange buffers
8738        if (o.adapt_async && !drive.d.usage.empty() && src.complement_ready() && src.exchange_capacity() >= 2 * a_cap) {
8739            ahomes.push_back({&xcache, adapt_stream, adapt_ev, 0, false});
8740            for (auto& st : stages) ahomes.push_back({&st->cache, st->adapt_stream, st->adapt_ev, st->dev, false});
8741            ajob = 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        }
8745        auto a_flush = [&]() { // the job's copies: an event after them on every
8746                               // stream used, submitted now (WDDM)
8747            try {
8748        for (AHome &h : ahomes)
8749                if (h.used) {
8750                    const strata::core::OnDevice on(h.dev);
8751                    /*
8752                    DPCT1024: The original code returned the error code
8753                    that was further consumed by the program logic. This
8754                    original code was replaced with 0. You may need to rewrite
8755                    the program logic consuming the error code.
8756                    */
8757                    if (DPCT_CHECK_ERROR(dpct::sync_barrier(h.ev, h.stream)) !=
8758                        0) a_err = true;
8759                    (void)DPCT_CHECK_ERROR(((h.stream)->ext_oneapi_empty()));
8760                }
8761        }
8762        catch (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        };
8768        auto a_choose = [&]() { // step 1, on the job thread
8769            try {
8770        struct C { float gain; int32_t layer, in, out; };
8771            std::vector<C> all;
8772            std::vector<std::pair<float, int32_t>> cand, vict;
8773            for (int64_t l = 0; l < g.n_layers; ++l) {
8774                cand.clear();
8775                vict.clear();
8776                const float* u = a_usage.data() + l * g.n_expert;
8777                const int32_t* r = a_res.data() + l * g.n_expert;
8778                for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) {
8779                    if (r[e] < 0) { if (u[e] >= 2.0f && !helper_holds(l, e)) cand.emplace_back(u[e], e); }
8780                    else vict.emplace_back(u[e], e);
8781                }
8782                if (cand.empty() || vict.empty()) continue;
8783                std::sort(cand.begin(), cand.end(), [](auto& a, auto& b) { return a.first > b.first; });
8784                const 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; });
8787                for (size_t i = 0; i < nc; ++i) {
8788                    if (cand[i].first < vict[i].first + 1.5f) break;
8789                    all.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; });
8793            aswaps.clear();
8794            for (const C& c : all) {
8795                if ((int64_t) aswaps.size() >= a_cap) break;
8796                const int32_t slot = a_res[(size_t) c.layer * g.n_expert + c.out];
8797                if (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)
8800                const bool x = src.has_resident(c.layer, c.in) && !src.has_resident(c.layer, c.out);
8801                aswaps.push_back({c.layer, c.in, c.out, slot, multi_gpu ? stage_of(c.layer) : 0, (int64_t) aswaps.size(), x});
8802            }
8803            for (AHome& h : ahomes) h.used = false;
8804            for (const ASwap& w : aswaps) {
8805                if (!w.exchange) continue;
8806                AHome& h = ahomes[(size_t) w.home];
8807                const strata::core::OnDevice on(h.dev);
8808                /*
8809                DPCT1000: Error handling if-stmt was detected but could not
8810                be rewritten.
8811                */
8812                /*
8813                DPCT1124: cudaMemcpyAsync is migrated to asynchronous
8814                memcpy API. While the origin API might be synchronous, it
8815                depends on the type of operand memory, so you may need to call
8816                wait() on event return by memcpy API to ensure synchronization
8817                behavior.
8818                */
8819                if (const dpct::err0 e = DPCT_CHECK_ERROR(h.stream->memcpy(
8820                        src.exchange_buffer(w.j), h.cache->device_slot(w.slot),
8821                        (size_t)strata::kernels::cpu::expert_layout()
8822                            .blob_bytes(w.layer)));
8823                    e != 0) {
8824                    std::fprintf(stderr,
8825                                 "strata serve: adaptive tier: copy back of "
8826                                 "layer %d slot %d (CUDA%d) failed: %s\n",
8827                                 /*
8828                                 DPCT1009: SYCL reports errors using
8829                                 exceptions and does not use error codes. Please
8830                                 replace the "get_error_string_dummy(...)" with
8831                                 a real error-handling function.
8832                                 */
8833                                 (int)w.layer, (int)w.slot, h.dev,
8834                                 dpct::get_error_string_dummy(e));
8835                    /*
8836                    DPCT1001: The statement could not be removed.
8837                    */
8838                    a_err = true;
8839                }
8840                h.used = true;
8841            }
8842            a_flush();
8843        }
8844        catch (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        };
8850        auto a_copy_in = [&]() { // step 2, on the job thread
8851            try {
8852        for (AHome &h : ahomes) h.used = false;
8853            for (const ASwap& w : aswaps) {
8854                AHome& h = ahomes[(size_t) w.home];
8855                const size_t nb = (size_t) strata::kernels::cpu::expert_layout().blob_bytes(w.layer);
8856                const uint8_t* b = src.pinned(w.layer, w.in) ? src.resident_blob(w.layer, w.in) : nullptr;
8857                if (b == nullptr) {   // pageable, or not in the RAM copy: through a bounce buffer (an async copy)
8858                    uint8_t* bb = src.exchange_buffer(a_cap + w.j);
8859                    if (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);
8862                        a_err = true;
8863                        continue;
8864                    }
8865                    b = bb;
8866                }
8867                const strata::core::OnDevice on(h.dev);
8868                /*
8869                DPCT1000: Error handling if-stmt was detected but could not
8870                be rewritten.
8871                */
8872                /*
8873                DPCT1124: cudaMemcpyAsync is migrated to asynchronous
8874                memcpy API. While the origin API might be synchronous, it
8875                depends on the type of operand memory, so you may need to call
8876                wait() on event return by memcpy API to ensure synchronization
8877                behavior.
8878                */
8879                if (const dpct::err0 e = DPCT_CHECK_ERROR(
8880                        h.stream->memcpy(h.cache->device_slot(w.slot), b, nb));
8881                    e != 0) {
8882                    std::fprintf(stderr,
8883                                 "strata serve: adaptive tier: copy of layer "
8884                                 "%d into slot %d (CUDA%d) failed: %s\n",
8885                                 /*
8886                                 DPCT1009: SYCL reports errors using
8887                                 exceptions and does not use error codes. Please
8888                                 replace the "get_error_string_dummy(...)" with
8889                                 a real error-handling function.
8890                                 */
8891                                 (int)w.layer, (int)w.slot, h.dev,
8892                                 dpct::get_error_string_dummy(e));
8893                    /*
8894                    DPCT1001: The statement could not be removed.
8895                    */
8896                    a_err = true;
8897                }
8898                h.used = true;
8899            }
8900            a_flush();
8901        }
8902        catch (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        };
8908        auto a_ready =
8909            [&](bool wait) -> bool { // the job and its copies are done
8910            try {
8911        if (wait) ajob->wait();
8912            else if (!ajob->idle()) return false;
8913            for (AHome& h : ahomes)
8914                if (h.used) {
8915                    const strata::core::OnDevice on(h.dev);
8916                    if (wait) {
8917                        if (DPCT_CHECK_ERROR(h.ev->wait_and_throw()) != 0)
8918                            a_err = true;
8919                    } else if (const dpct::err0 q =
8920                                   dpct::sycl_event_query(h.ev);
8921                               q == 1) return false;
8922                    /*
8923                    DPCT1001: The statement could not be removed.
8924                    */
8925                    /*
8926                    DPCT1000: Error handling if-stmt was detected but could
8927                    not be rewritten.
8928                    */
8929                    else if (q != 0) a_err = true;
8930                }
8931            return true;
8932        }
8933        catch (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.
8940        auto adapt_tick = [&](bool drain) -> bool {
8941            if (!ajob) return true;
8942            if (!drain) ++a_win;   // one tick per window
8943            for (;;) {
8944                if (a_err.load()) return false;
8945                switch (astate) {
8946                case AState::Idle:
8947                    if (drain || a_win - a_last < (int64_t) o.adapt_every) return true;
8948                    a_last = a_win;
8949                    ++a_rounds;
8950                    a_t0 = Clock::now();
8951                    a_usage = drive.d.usage;
8952                    a_res = host_res;
8953                    // #477: the routing counted, as adapt() counts it (--expert-profile-save; else `heat` is empty)
8954                    for (size_t i = 0; i < heat.size(); ++i) heat[i] += (double) drive.d.usage[i];
8955                    for (float& v : drive.d.usage) v *= o.adapt_decay;
8956                    ajob->post(a_choose);
8957                    astate = AState::CopyBack;
8958                    return true;
8959                case AState::CopyBack: {   // step 2: the evicted experts leave the GPU's plan
8960                    if (!a_ready(drain)) return true;
8961                    if (a_err.load()) return false;
8962                    size_t k = 0;
8963                    for (size_t i = 0; i < aswaps.size(); ++i) {
8964                        const ASwap w = aswaps[i];
8965                        const size_t out = (size_t) w.layer * g.n_expert + w.out;
8966                        if (host_res[out] != w.slot) continue;   // the table moved since the snapshot: not this one
8967                        if (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);
8970                            return false;
8971                        }
8972                        host_res[out] = strata::core::kNotResident;   // the CPU computes it from the next window on
8973                        srcp->prefetch(w.layer, w.out);
8974                        aswaps[k++] = w;
8975                    }
8976                    aswaps.resize(k);
8977                    res_upload();
8978                    ajob->post(a_copy_in);
8979                    astate = AState::SwapIn;
8980                    if (!drain) return true;
8981                    continue;
8982                }
8983                case AState::SwapIn:   // step 3: the new experts are in their slots
8984                    if (!a_ready(drain)) return true;
8985                    if (a_err.load()) return false;
8986                    for (const ASwap& w : aswaps) {
8987                        host_res[(size_t) w.layer * g.n_expert + w.in] = w.slot;
8988                        srcp->release(w.layer, w.in);
8989                    }
8990                    res_upload();
8991                    a_swapped += (int64_t) aswaps.size();
8992                    ajob->post([&] { src.commit_copies(); });
8993                    astate = AState::Commit;
8994                    if (!drain) return true;
8995                    continue;
8996                case AState::Commit:   // step 4
8997                    if (!a_ready(drain)) return true;
8998                    if (a_err.load()) return false;
8999                    src.commit_flip();
9000                    a_ms += std::chrono::duration<double, std::milli>(Clock::now() - a_t0).count();
9001                    aswaps.clear();
9002                    astate = AState::Idle;
9003                    continue;   // 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.
9009        auto save_profile = [&](const char* why) {
9010            if (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).
9013                const 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();
9016                double total = 0;
9017                for (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)
9020                const double lam = 2.0;
9021                double prior_entries = 800000.0;
9022                if (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);
9024                for (size_t i = 0; i < n; ++i) hv[i] = (double) uh[i];
9025                for (size_t r = 0; r < profile_loaded.size(); ++r) {
9026                    const auto [l, e] = profile_loaded[r];
9027                    if (l < 0 || l >= g.n_layers || e < 0 || e >= g.n_expert) continue;
9028                    const double x = (double) r / (double) n;
9029                    hv[(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;
9033                const auto ranked = strata::core::rank_learned_profile(g.n_layers, g.n_expert, none, hv, profile_loaded);
9034                if (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",
9036                                 o.expert_profile_save.c_str(), why, total);
9037                else
9038                    std::fprintf(stderr, "strata serve: the expert profile was not saved: %s\n", e.c_str());
9039                profile_saved_at = Clock::now();
9040                return;
9041            }
9042            if (heat.empty()) return;
9043            std::vector<uint8_t> resident(host_res.size(), 0);
9044            for (size_t i = 0; i < host_res.size(); ++i) resident[i] = host_res[i] >= 0;
9045            for (const auto& p : pending) resident[(size_t) p.first] = 1;
9046            if (astate == AState::SwapIn)   // --adapt-async: the same for a round past its step 2
9047                for (const ASwap& w : aswaps) resident[(size_t) w.layer * g.n_expert + w.in] = 1;
9048            std::string e;
9049            const auto ranked = strata::core::rank_learned_profile(g.n_layers, g.n_expert, resident, heat,
9050                                                                   profile_loaded);
9051            if (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(),
9053                             why);
9054            else
9055                std::fprintf(stderr, "strata serve: the expert profile was not saved: %s\n", e.c_str());
9056            profile_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).
9063        struct StdinShared {
9064            std::atomic<bool> stop_req{false};
9065            std::mutex mu;
9066            std::condition_variable cv;
9067            std::deque<std::string> lines;
9068            bool eof = false;
9069        };
9070        const 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;
9075        bool& 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;
9081            char chunk[4096];
9082            auto getline_fd = [&](std::string& out) -> bool {
9083                for (;;) {
9084                    const size_t nlpos = buf.find('\n');
9085                    if (nlpos != std::string::npos) {
9086                        out.assign(buf, 0, nlpos);
9087                        buf.erase(0, nlpos + 1);
9088                        return true;
9089                    }
9090#if defined(_WIN32)
9091                    const int n = _read(0, chunk, (unsigned) sizeof chunk);
9092#else
9093                    const ssize_t n = ::read(0, chunk, sizeof chunk);
9094                    if (n < 0 && errno == EINTR) continue;
9095#endif
9096                    if (n <= 0) {
9097                        if (buf.empty()) return false;
9098                        out.swap(buf);
9099                        buf.clear();
9100                        return true;
9101                    }
9102                    buf.append(chunk, (size_t) n);
9103                }
9104            };
9105            while (getline_fd(l)) {
9106                if (!l.empty() && l.back() == '\r') l.pop_back();
9107                if (l == "STOP") { st->stop_req.store(true); continue; }
9108                std::lock_guard<std::mutex> lk(st->mu);
9109                st->lines.push_back(l);
9110                st->cv.notify_one();
9111            }
9112            std::lock_guard<std::mutex> lk(st->mu);
9113            st->eof = true;
9114            st->cv.notify_one();
9115        }).detach();
9116        auto next_line = [&](std::string& out) -> bool {
9117            std::unique_lock<std::mutex> lk(in_mu);
9118            in_cv.wait(lk, [&] { return !in_lines.empty() || in_eof; });
9119            if (in_lines.empty()) return false;
9120            out = std::move(in_lines.front());
9121            in_lines.pop_front();
9122            return true;
9123        };
9124        sp.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)
9126        const bool trace = std::getenv("STRATA_TRACE") != nullptr;
9127        auto tr = [&](const char* what, long long a = -1, long long b = -1) {
9128            if (!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
9135            size_t free_b = 0, total_b = 0;
9136            /*
9137            DPCT1106: 'cudaMemGetInfo' was migrated with the Intel
9138            extensions for device information which may not be supported by all
9139            compilers 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
9144            const int64_t free_mib = (int64_t) (free_b >> 20);
9145            if (free_mib >= 256) {
9146                std::fprintf(stderr, "strata serve: %lld MiB of VRAM free with everything loaded\n", (long long) free_mib);
9147                rss_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        {
9162            size_t free_b = 0, total_b = 0;
9163            /*
9164            DPCT1106: 'cudaMemGetInfo' was migrated with the Intel
9165            extensions for device information which may not be supported by all
9166            compilers 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.
9173            const int64_t slots_primary = (int64_t) xcache.slots();
9174            const int64_t mib_primary = (int64_t) (xcache.bytes() >> 20);
9175            int64_t slots_all = slots_primary, mib_all = mib_primary;
9176            for (const auto& st : stages) {
9177                slots_all += (int64_t) st->cache.slots();
9178                mib_all += (int64_t) (st->cache.bytes() >> 20);
9179            }
9180            for (int r = 0; r < 3; ++r)
9181                if (o.expert_cache_remote[(size_t) r] > 0) {
9182                    slots_all += remote_experts[(size_t) r].resident();
9183                    mib_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,
9195                        o.spec, o.mtp_max_t,
9196                        o.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),
9198                        pool.workers(), o.pcie_frac,
9199                        o.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,
9201                        o.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        {
9210            const char* ws = std::getenv("STRATA_WATCHDOG_S");
9211            const int limit = ws ? std::atoi(ws) : 60;   // one step (a prompt layer, a verify window) takes seconds
9212            if (limit > 0)
9213                std::thread([limit] {
9214                    strata::core::Progress& p = strata::core::progress();
9215                    uint64_t last = p.beats.load(), ticks_at = p.ticks.load();
9216                    auto since = std::chrono::steady_clock::now();
9217                    for (;;) {
9218                        std::this_thread::sleep_for(std::chrono::seconds(1));
9219                        const auto now = std::chrono::steady_clock::now();
9220                        const uint64_t b = p.beats.load();
9221                        if (!p.busy.load() || b != last) { last = b; ticks_at = p.ticks.load(); since = now; continue; }
9222                        if (now - since < std::chrono::seconds(limit)) continue;
9223                        // a blocking step's explicit allowance (session files): still within it, not yet stuck
9224                        if (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",
9227                                     limit, stage_text().c_str());
9228                        stall_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;
9239        int64_t rounds = 0;
9240        const int S = o.spec;
9241        const 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
9242        if (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
9244        else 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).
9251        constexpr int64_t kImagePad = 248056;   // qwen4exp.ple.image_token_id: the PLE hash reads it for image cells
9252        bool 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
9264        const int64_t chunk_full = o.prefill_chunk;              // the loan's chunk with the whole cache
9265        auto relend = [&]() {   // the prompt path's loan: the end of the slots left, its chunk as large as fits
9266            if (pf_parts.empty() || pf_parts[0].first < 0) return;
9267            PfPart& p = pf_parts[0];
9268            const int64_t live = xcache.slots();
9269            auto fits = [&](int64_t c) {
9270                const int64_t k = part_slots(p, c);
9271                return k > 0 && k + 128 <= live && !(o.prefill_auto && k * 100 > kAutoLendPct * live);
9272            };
9273            int64_t c = chunk_full;
9274            while (c > 256 && !fits(c)) c = std::max<int64_t>(256, c / 2 / 256 * 256);
9275            o.prefill_chunk = c;
9276            p.first = (int32_t) std::max<int64_t>(0, live - part_slots(p, c));
9277            p.first_now = -1;   // laid out again at the next loan
9278        };
9279        auto vram_command = [&](const std::string &cmd,
9280                                std::string &e) -> bool {
9281            // `VRAM` alone: the reserve the engine started with (--vram-reserve-mib)
9282            try {
9283        char *end = nullptr;
9284            const bool bare = cmd.find_first_not_of(' ', 4) == std::string::npos;
9285            const long long reserve = bare ? (long long) o.vram_reserve_mib : std::strtoll(cmd.c_str() + 4, &end, 10);
9286            if (!bare && (end == cmd.c_str() + 4 || reserve < 0)) { e = "expected: VRAM [reserve_mib]"; return false; }
9287            if (!xcache.segmented()) {
9288                e = "VRAM needs an engine started with --vram-elastic (one NVIDIA GPU, --serve)";
9289                return false;
9290            }
9291            if (src.complement_ready()) {
9292                e = "VRAM: not with the resident low-RAM mode (the cache holds experts RAM does not)";
9293                return false;
9294            }
9295            if (peer.valid()) { e = "VRAM: not with --peer-device"; return false; }
9296            for (const PfPart& p : pf_parts)
9297                if (!p.lent.empty()) { e = "VRAM: a prompt's loan is still out"; return false; }
9298            if (!ver.wait_commit(e)) return false;
9299            apply_pending(true);                     // the adaptive tier's swaps in flight land first
9300            if (DPCT_CHECK_ERROR(
9301                    dpct::get_current_device().queues_wait_and_throw()) != 0) {
9302                /*
9303                DPCT1009: SYCL reports errors using exceptions and does not
9304                use error codes. Please replace the
9305                "get_error_string_dummy(...)" with a real error-handling
9306                function.
9307                */
9308                /*
9309                DPCT1010: SYCL uses exceptions to report errors and does
9310                not use the error codes. The cudaGetLastError function call was
9311                replaced with 0. You need to rewrite this code.
9312                */
9313                e = std::string("VRAM: ") + dpct::get_error_string_dummy(0);
9314                return false;
9315            }
9316            const auto t0 = Clock::now();
9317            size_t free_b = 0, total_b = 0;
9318            /*
9319            DPCT1106: 'cudaMemGetInfo' was migrated with the Intel
9320            extensions for device information which may not be supported by all
9321            compilers or runtimes. You may need to adjust the code.
9322            */
9323            dpct::get_current_device().get_memory_info(free_b, total_b);
9324            const int64_t want_free = (int64_t) reserve << 20, mapped = xcache.mapped_bytes();
9325            const 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
9327            const int64_t floor_slots = std::min<int64_t>(xcache.full_slots(),
9328                128 + (pf_parts.empty() || pf_parts[0].first < 0 ? 0 : part_slots(pf_parts[0], 256)));
9329            std::string note;
9330            if ((int64_t) free_b < want_free) {
9331                const int64_t floor_b = xcache.bytes_of(floor_slots);
9332                int64_t keep = mapped - (want_free - (int64_t) free_b);
9333                if (keep < floor_b) {
9334                    keep = floor_b;
9335                    note = " (the cache keeps its smallest size: the prompt path's buffers)";
9336                }
9337                if (!xcache.shrink(keep, e)) return false;
9338                const int64_t live = xcache.slots();
9339                for (size_t i = 0; i < host_res.size(); ++i)
9340                    if (host_res[i] >= live) {
9341                        vram_evicted.emplace_back((int32_t) i, host_res[i]);
9342                        host_res[i] = strata::core::kNotResident;
9343                    }
9344                res_upload();
9345            } else if (mapped < xcache.full_bytes()) {
9346                std::string gerr;
9347                if (!xcache.grow(mapped + ((int64_t) free_b - want_free), gerr)) note = " (" + gerr + ")";
9348                const int64_t live = xcache.slots();
9349                std::string ferr;
9350                std::vector<std::pair<int32_t, int32_t>> keep_out;
9351                for (const auto& [i, slot] : vram_evicted) {
9352                    if (slot >= live) { keep_out.emplace_back(i, slot); continue; }
9353                    const int64_t layer = i / g.n_expert;
9354                    int64_t pick = i;
9355                    if (host_res[(size_t) i] >= 0) {   // back already (the adaptive tier): the layer's most-routed miss
9356                        pick = -1;
9357                        float best = -1.0f;
9358                        for (int64_t ex = 0; ex < g.n_expert; ++ex) {
9359                            const size_t j = (size_t) (layer * g.n_expert + ex);
9360                            if (host_res[j] >= 0) continue;
9361                            const float u = drive.d.usage.empty() ? 0.0f : drive.d.usage[j];
9362                            if (u > best) { best = u; pick = (int64_t) j; }
9363                        }
9364                    }
9365                    if (pick < 0) continue;
9366                    const uint8_t* b = srcp->blob(layer, pick % g.n_expert);
9367                    if (b == nullptr || !xcache.fill_slot_queued(slot, b, ferr,
9368                            (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(layer))) {
9369                        e = "VRAM: refilling the cache failed: " + ferr;
9370                        return false;
9371                    }
9372                    host_res[(size_t) pick] = slot;
9373                }
9374                vram_evicted.swap(keep_out);
9375                if (!xcache.sync_queued(ferr)) { e = "VRAM: " + ferr; return false; }
9376                res_upload();
9377            }
9378            relend();
9379            /*
9380            DPCT1106: 'cudaMemGetInfo' was migrated with the Intel
9381            extensions for device information which may not be supported by all
9382            compilers 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",
9387                         reserve, (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);
9396            return true;
9397        }
9398        catch (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
9405        struct BSlot {
9406            bool active = false, stop = false;
9407            int32_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
9409            bool draft_ready = false;
9410            int64_t p = 0;                 ///< its position
9411            int64_t produced = 0, max_new = 0;
9412            Clock::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;
9417            int64_t reply0 = 0;            ///< the index in `ids` where its penalty window starts (the last prompt token; 0 with STRATA_PENALTY_PROMPT=1)
9418            int pen_n = 0;                 ///< its request's penalty window (penalty_last_n) when it has a repeat / frequency / presence penalty, else 0
9419            bool cached = false;           ///< idle, and its sessions still hold `ids`
9420            bool cvec = true;              ///< the control vector setting `ids` were read with
9421            bool 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)
9428            bool 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)
9432        double bt_run = 0, bt_commit = 0, bt_emit = 0;
9433        double bt_wait0 = 0, bt_pool0 = 0;
9434        int64_t bt_miss0 = 0, bt_hits0 = 0, bt_pcie0 = 0;
9435        int64_t bt_windows = 0, bt_rows = 0, bt_tokens = 0;
9436        Clock::time_point bt_start = Clock::now();
9437        int admit_slot = -1;               ///< the slot the request being read will continue in (BGEN)
9438        long long admit_max_new = 0;
9439        auto batch_on = [&] { for (const BSlot& b : bs) if (b.active) return true; return false; };
9440        auto try_next_line = [&](std::string& out) -> bool {
9441            std::lock_guard<std::mutex> lk(in_mu);
9442            if (in_lines.empty()) return false;
9443            out = std::move(in_lines.front());
9444            in_lines.pop_front();
9445            return true;
9446        };
9447        // the session a request just left behind (its prompt) -> slot b's sessions, on every stage
9448        auto copy_to_slot = [&](int b, const std::vector<int32_t> &ids,
9449                                std::string &e) -> bool {
9450            try {
9451        const int64_t upto = (int64_t)ids.size();
9452            for (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];
9455                const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev);
9456                if (DPCT_CHECK_ERROR(
9457                        dpct::get_current_device().queues_wait_and_throw()) !=
9458                    0) {
9459                    e = "batch admission: device sync failed"; return false;
9460                }
9461                strata::core::ConversationCheckpoint ck;
9462                ck.ids = ids;
9463                if (!strata::core::conversation_checkpoint_save(ck, from, g, e) ||
9464                    !strata::core::conversation_checkpoint_restore(ck, to, g, e))
9465                    return false;
9466                for (int64_t j = 0; j < from.qsa_alloc; ++j) {
9467                    strata::core::ConversationKv img;
9468                    if (!strata::core::conversation_kv_save(img, from.qsa_states[from.qsa_ord0 + j], g, upto, true, e))
9469                        return false;
9470                    if (DPCT_CHECK_ERROR(dpct::get_current_device()
9471                                             .queues_wait_and_throw()) != 0) {
9472                        e = "batch admission: device sync failed"; return false;
9473                    }
9474                    if (!strata::core::conversation_kv_restore(img, to.qsa_states[to.qsa_ord0 + j], g, upto, true, e))
9475                        return false;
9476                }
9477                if (DPCT_CHECK_ERROR(
9478                        dpct::get_current_device().queues_wait_and_throw()) !=
9479                    0) {
9480                    e = "batch admission: device sync failed"; return false;
9481                }
9482            }
9483            if (batch_mtp) {
9484                // Admission first builds the solo draft KV; copy it into the slot before drafting.
9485                strata::core::ConversationKv image;
9486                if (!mtp.idle(e) || !slot_mtp[(size_t)b]->idle(e) ||
9487                    !strata::core::conversation_kv_save(image, mtp.kv_state(),
9488                                                        draft_geometry, upto,
9489                                                        false, e) ||
9490                    !strata::core::conversation_kv_restore(
9491                        image, slot_mtp[(size_t)b]->kv_state(), draft_geometry,
9492                        upto, false, e) ||
9493                    DPCT_CHECK_ERROR(
9494                        dpct::get_current_device().queues_wait_and_throw()) !=
9495                        0)
9496                    return false;
9497                slot_mtp[(size_t) b]->set_prompt_len(upto);
9498            }
9499            return true;
9500        }
9501        catch (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
9510        auto 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
9513            conversations.take_reuse();
9514            try {
9515        const int64_t upto = at != nullptr ? (int64_t)at->ids.size()
9516                                           : (int64_t)bs[(size_t)b].ids.size();
9517            if (at != nullptr && at->stage_parts.size() != stages.size()) { e = "a checkpoint without its stage parts"; return false; }
9518            for (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;
9521                const strata::core::OnDevice on_k(k == 0 ? 0 : stages[k - 1]->dev);
9522                if (DPCT_CHECK_ERROR(
9523                        dpct::get_current_device().queues_wait_and_throw()) !=
9524                    0) {
9525                    e = "batch slot restore: device sync failed"; return false;
9526                }
9527                if (at != nullptr) {
9528                    if (!strata::core::conversation_checkpoint_restore(k == 0 ? *at : at->stage_parts[k - 1], to, g, e))
9529                        return false;
9530                } else {
9531                    strata::core::ConversationCheckpoint ck;
9532                    ck.ids = bs[(size_t) b].ids;
9533                    if (!strata::core::conversation_checkpoint_save(ck, from, g, e) ||
9534                        !strata::core::conversation_checkpoint_restore(ck, to, g, e))
9535                        return false;
9536                }
9537                for (int64_t j = 0; j < from.qsa_alloc; ++j) {
9538                    strata::core::ConversationKv img;
9539                    if (!strata::core::conversation_kv_save(img, from.qsa_states[from.qsa_ord0 + j], g, upto, true, e))
9540                        return false;
9541                    if (DPCT_CHECK_ERROR(dpct::get_current_device()
9542                                             .queues_wait_and_throw()) != 0) {
9543                        e = "batch slot restore: device sync failed";
9544                        return false;
9545                    }
9546                    if (!strata::core::conversation_kv_restore(img, to.qsa_states[to.qsa_ord0 + j], g, upto, true, e))
9547                        return false;
9548                }
9549                if (DPCT_CHECK_ERROR(
9550                        dpct::get_current_device().queues_wait_and_throw()) !=
9551                    0) {
9552                    e = "batch slot restore: device sync failed"; return false;
9553                }
9554            }
9555            if (batch_mtp) {
9556                // A returning solo request resumes from its slot's draft KV.
9557                strata::core::ConversationKv image;
9558                if (!slot_mtp[(size_t)b]->idle(e) || !mtp.idle(e) ||
9559                    !strata::core::conversation_kv_save(
9560                        image, slot_mtp[(size_t)b]->kv_state(), draft_geometry,
9561                        upto, false, e) ||
9562                    !strata::core::conversation_kv_restore(
9563                        image, mtp.kv_state(), draft_geometry, upto, false,
9564                        e) ||
9565                    DPCT_CHECK_ERROR(
9566                        dpct::get_current_device().queues_wait_and_throw()) !=
9567                        0)
9568                    return false;
9569                mtp.set_prompt_len(upto);
9570            }
9571            return true;
9572        }
9573        catch (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.
9589        auto park_slot = [&](int b) {
9590            BSlot& sl = bs[(size_t) b];
9591            if (!conversations.enabled() || sl.active || !sl.cached || sl.img || sl.ids.empty()) return;
9592            auto prefix_of = [&](const std::vector<int32_t>& whole) {
9593                return whole.size() >= sl.ids.size() && std::equal(sl.ids.begin(), sl.ids.end(), whole.begin());
9594            };
9595            const bool in_main = live_ok && cvec_cached == sl.cvec && prefix_of(live) &&
9596                                 imgs_below(live_imgs, (int64_t) sl.ids.size()).empty();
9597            if (in_main || conversations.holds(sl.ids, {}, sl.cvec)) return;
9598            if (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());
9601                return;
9602            }
9603            try {
9604                if (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);
9607                    return;
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;
9614            if (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",
9616                             b, why.c_str());
9617                return;
9618            }
9619            const size_t n_st = stages.size();
9620            static const std::vector<ImgKey> no_imgs;
9621            ParkSource src{sl.ids, no_imgs, sl.checks, sl.cvec, *bslot_ss[0][(size_t) b], {},
9622                           n_st > 0 || !batch_mtp ? nullptr : &slot_mtp[(size_t) b]->kv_state(),
9623                           batch_mtp && n_st > 0 ? &slot_mtp[(size_t) b]->kv_state() : nullptr, false,
9624                           " from slot " + std::to_string(b)};
9625            for (size_t k = 1; k < bslot_ss.size(); ++k) src.stage_sessions.push_back(bslot_ss[k][(size_t) b].get());
9626            try {
9627                if (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",
9631                             b, err.empty() ? "the snapshot failed" : err.c_str());
9632                err.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
9640        auto batch_step = [&]() -> bool {
9641            int S = 0;
9642            int rows[strata::kernels::kVerifyMaxT] = {};
9643            int32_t tok[strata::kernels::kVerifyMaxT] = {}, outb[strata::kernels::kVerifyMaxT] = {};
9644            int64_t pos[strata::kernels::kVerifyMaxT] = {};
9645            int first[strata::kernels::kVerifyMaxT] = {}, active[strata::kernels::kVerifyMaxT] = {};
9646            static size_t next_slot = 0;
9647            // Each MTP slot uses two rows; rotate slots when more than four are active.
9648            int A = 0;
9649            for (size_t offset = 0; offset < bs.size() && S + (batch_mtp ? 2 : 1) <= strata::kernels::kVerifyMaxT; ++offset) {
9650                const int b = (int) ((next_slot + offset) % bs.size());
9651                if (bs[(size_t) b].active) {
9652                    first[A] = S;
9653                    active[A++] = b;
9654                    rows[S] = b;
9655                    tok[S] = bs[(size_t) b].x;
9656                    pos[S] = bs[(size_t) b].p;
9657                    ++S;
9658                    if (batch_mtp) {
9659                        rows[S] = b;
9660                        if (!bs[(size_t) b].draft_ready) {
9661                            err = "batch MTP: a live slot has no draft";
9662                            return false;
9663                        }
9664                        tok[S] = bs[(size_t) b].draft[0];
9665                        pos[S] = bs[(size_t) b].p + 1;
9666                        ++S;
9667                    }
9668                }
9669            }
9670            if (batch_mtp && A > 0) next_slot = ((size_t) active[A - 1] + 1) % bs.size();
9671            if (S == 0) return true;
9672            const bool was_busy = strata::core::progress().busy.load();
9673            strata::core::progress().busy.store(true);
9674            drive.d.layers = 0;
9675            drive.d.experts = 0;
9676            drive.d.failed = false;
9677            apply_pending(false);
9678            if (bt_windows == 0) {
9679                bt_start = Clock::now();
9680                bt_wait0 = ver.ms_wait; bt_pool0 = ver.ms_pool;
9681                bt_miss0 = drive.d.multi_misses; bt_hits0 = drive.d.cache_hits; bt_pcie0 = drive.d.pcie_experts;
9682            }
9683            for (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)
9684                const BSlot& ps = bs[(size_t) rows[t]];
9685                if (ps.pen_n <= 0 || (t > 0 && rows[t - 1] == rows[t])) continue;
9686                const int64_t from = std::max<int64_t>(ps.reply0, (int64_t) ps.ids.size() - ps.pen_n);
9687                ver.set_slot_history(rows[t], ps.ids.data() + from, (int64_t) ps.ids.size() - from);
9688            }
9689            const Clock::time_point w0 = Clock::now();
9690            if (!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());
9692                return false;
9693            }
9694            const 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);
9697            for (int a = 0; a < A; ++a) {
9698                const int b = active[a], i = first[a];
9699                const BSlot& sl = bs[(size_t) b];
9700                const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outb[i]) != o.eos_ids.end();
9701                keep[b] = batch_mtp && outb[i] == tok[i + 1] && !eos && !sl.stop &&
9702                          sl.produced + 2 <= sl.max_new && sl.p + 3 <= o.max_context ? 2 : 1;
9703            }
9704            if (!(batch_mtp ? ver.commit_slot_prefixes(keep.data(), err) : ver.commit_slots(err))) {
9705                std::printf("ERR %s\n", err.c_str());
9706                return false;
9707            }
9708            const Clock::time_point w2 = Clock::now();
9709            auto msd = [](Clock::time_point a0, Clock::time_point b0) { return std::chrono::duration<double, std::milli>(b0 - a0).count(); };
9710            bt_run += msd(w0, w1);
9711            bt_commit += msd(w1, w2);
9712            ++bt_windows;
9713            for (int a = 0; a < A; ++a) bt_rows += keep[active[a]];
9714            for (int t = 0; t < A; ++t) {
9715                const int b = active[t];
9716                BSlot& sl = bs[(size_t) b];
9717                for (int j = 0; j < keep[b]; ++j) {
9718                    const int32_t y = outb[first[t] + j];
9719                    sl.ids.push_back(tok[first[t] + j]);
9720                    std::printf("BT %d %d\n", b, (int) y);
9721                    ++sl.produced;
9722                    const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end();
9723                    const char* fin = eos ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length"
9724                                    : sl.p + 2 > o.max_context ? "length" : nullptr;
9725                    if (fin != nullptr) {
9726                        const 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);
9728                        sl.active = false;
9729                        sl.cached = o.prompt_cache > 0 && !sl.img;
9730                        break;
9731                    }
9732                    sl.x = y;
9733                    sl.p += 1;
9734                }
9735                if (batch_mtp && sl.active) {
9736                    const size_t stride = (size_t) g.hc * (size_t) g.n_embd;
9737                    if (DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
9738                            slot_mtp_rows[(size_t)b].get(),
9739                            ver.final_R_all() + (size_t)first[t] * stride,
9740                            2 * stride * sizeof(float)).wait()) != 0 ||
9741                        !slot_mtp[(size_t)b]->draft(2, outb + first[t],
9742                                                    pos[first[t]], keep[b] - 1,
9743                                                    sl.draft.data(), err)) {
9744                        std::printf("ERR batch MTP slot %d: %s\n", b, err.c_str());
9745                        return false;
9746                    }
9747                    sl.draft_ready = true;
9748                }
9749            }
9750            std::fflush(stdout);
9751            bt_emit += msd(w2, Clock::now());
9752            strata::core::progress().busy.store(was_busy);
9753            if (!batch_on() && bt_windows > 0) {
9754                const double w = (double) bt_windows, wall = msd(bt_start, Clock::now());
9755                const 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);
9764                for (size_t k = 0; k <= stages.size(); ++k) {
9765                    const std::string pr = (k == 0 ? ver : stages[k - 1]->ver).profile_report();
9766                    if (!pr.empty()) std::fprintf(stderr, "strata batch GPU stages, stage %zu (ms/window):%s\n", k + 1, pr.c_str());
9767                }
9768                bt_run = bt_commit = bt_emit = 0;
9769                bt_windows = bt_rows = bt_tokens = 0;
9770            }
9771            return true;
9772        };
9773        // ---- --batch-groups: the slot groups pipelined through the stages (--batch-groups G > 1 with a layer split)
9774        const int n_pipe = (int) stages.size() + 1;
9775        const bool piped = o.batch > 0 && o.batch_groups > 1 && n_pipe > 1;
9776        const int GS = piped ? o.batch / o.batch_groups : o.batch;
9777        struct PGroup {
9778            bool inflight = false;
9779            int stage = 0;                  ///< the stage it runs on or waits for
9780            int32_t tok[strata::kernels::kVerifyMaxT] = {};
9781            int64_t pos[strata::kernels::kVerifyMaxT] = {};
9782            int64_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);
9786        int64_t pipe_tick = 0, rr = 0;
9787        auto stage_verifier = [&](int k) -> strata::core::Verifier& { return k == 0 ? ver : stages[(size_t) k - 1]->ver; };
9788        auto pipe_inflight = [&] { for (const PGroup& x : pg) if (x.inflight) return true; return false; };
9789        auto group_active = [&](int gi) {
9790            for (int t = 0; t < GS; ++t) if (bs[(size_t) (gi * GS + t)].active) return true;
9791            return false;
9792        };
9793        // one turn: serve every running stage, hand finished groups on, start what can start
9794        auto pump = [&](bool may_start) -> bool {
9795            ++pipe_tick;
9796            if (bt_windows == 0 && !pipe_inflight()) {
9797                bt_start = Clock::now();
9798                bt_wait0 = ver.ms_wait; bt_pool0 = ver.ms_pool;
9799                bt_miss0 = drive.d.multi_misses; bt_hits0 = drive.d.cache_hits; bt_pcie0 = drive.d.pcie_experts;
9800            }
9801            for (int k = 0; k < n_pipe; ++k) {
9802                const int gi = stage_group[(size_t) k];
9803                if (gi < 0) continue;
9804                strata::core::Verifier& vk = stage_verifier(k);
9805                const int r = vk.batch_poll(win_pool_fn, win_pool_user, err);
9806                if (r < 0) { std::printf("ERR %s\n", err.c_str()); return false; }
9807                if (r == 0) continue;
9808                stage_group[(size_t) k] = -1;
9809                PGroup& G = pg[(size_t) gi];
9810                if (k + 1 < n_pipe) { G.stage = k + 1; G.since = pipe_tick; continue; }
9811                // the last stage: the group's picks
9812                const int32_t* outb = vk.batch_out();
9813                for (int t = 0; t < GS; ++t) {
9814                    BSlot& sl = bs[(size_t) (gi * GS + t)];
9815                    if (!sl.active) continue;
9816                    const int32_t y = outb[t];
9817                    std::printf("BT %d %d\n", gi * GS + t, (int) y);
9818                    ++sl.produced;
9819                    ++bt_rows;
9820                    const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end();
9821                    const char* fin = eos ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length"
9822                                    : sl.p + 2 > o.max_context ? "length" : nullptr;
9823                    sl.ids.push_back(sl.x);
9824                    if (fin != nullptr) {
9825                        const 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);
9827                        sl.active = false;
9828                        sl.cached = false;   // the pipeline's pad rows: a pipelined slot is not reused as a cache
9829                    } else {
9830                        sl.x = y;
9831                        sl.p += 1;
9832                    }
9833                }
9834                std::fflush(stdout);
9835                ++bt_windows;
9836                G.inflight = false;
9837            }
9838            // start waiting groups on free stages, the longest waiting first; a new step on stage 0 round-robin
9839            for (int k = n_pipe - 1; k >= 0; --k) {
9840                if (stage_group[(size_t) k] >= 0) continue;
9841                int pick = -1;
9842                if (k > 0) {
9843                    for (int gi = 0; gi < (int) pg.size(); ++gi)
9844                        if (pg[(size_t) gi].inflight && pg[(size_t) gi].stage == k &&
9845                            (pick < 0 || pg[(size_t) gi].since < pg[(size_t) pick].since))
9846                            pick = gi;
9847                    if (pick < 0) continue;
9848                } else {
9849                    if (!may_start) continue;
9850                    for (int j = 0; j < (int) pg.size() && pick < 0; ++j) {
9851                        const int gi = (int) ((rr + j) % (int64_t) pg.size());
9852                        if (!pg[(size_t) gi].inflight && group_active(gi)) pick = gi;
9853                    }
9854                    if (pick < 0) continue;
9855                    rr = pick + 1;
9856                    PGroup& G = pg[(size_t) pick];
9857                    for (int t = 0; t < GS; ++t) {
9858                        BSlot& sl = bs[(size_t) (pick * GS + t)];
9859                        G.tok[t] = sl.active ? sl.x : 0;
9860                        G.pos[t] = sl.active ? sl.p : 0;
9861                        if (!sl.active) sl.cached = false;   // its pad row writes its state
9862                    }
9863                    G.inflight = true;
9864                    G.stage = 0;
9865                    drive.d.failed = false;
9866                    apply_pending(false);
9867                }
9868                PGroup& G = pg[(size_t) pick];
9869                strata::core::progress().busy.store(true);
9870                if (k == 0) {   // the penalised slots' reply tails for the group's rows (the last stage draws them)
9871                    for (int t = 0; t < GS && t < (int) strata::kernels::kVerifyMaxT; ++t) {
9872                        const BSlot& ps = bs[(size_t) (pick * GS + t)];
9873                        if (ps.pen_n <= 0) continue;
9874                        const int64_t from = std::max<int64_t>(ps.reply0, (int64_t) ps.ids.size() - ps.pen_n);
9875                        ver.set_slot_history(pick * GS + t, ps.ids.data() + from, (int64_t) ps.ids.size() - from);
9876                    }
9877                }
9878                if (!stage_verifier(k).batch_launch(pick * GS, GS, G.tok, G.pos, err)) {
9879                    std::printf("ERR %s\n", err.c_str());
9880                    return false;
9881                }
9882                stage_group[(size_t) k] = pick;
9883            }
9884            if (drive.d.failed) { std::printf("ERR %s\n", drive.d.fail ? drive.d.fail : "the expert pool failed"); return false; }
9885            if (!pipe_inflight() && !batch_on() && bt_windows > 0) {   // all idle: the timing line, as batch_step
9886                const 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));
9890                for (int k = 0; k < n_pipe; ++k) {
9891                    const std::string pr = stage_verifier(k).profile_report();
9892                    if (!pr.empty()) std::fprintf(stderr, "strata batch GPU stages, stage %d (ms/window):%s\n", k + 1, pr.c_str());
9893                }
9894                bt_windows = bt_rows = 0;
9895                strata::core::progress().busy.store(false);
9896            }
9897            return true;
9898        };
9899        auto pipe_drain = [&]() -> bool {
9900            while (pipe_inflight())
9901                if (!pump(false)) return false;
9902            return true;
9903        };
9904        for (;;) {
9905            if (batch_on() || (piped && pipe_inflight())) {
9906                if (!try_next_line(line)) {
9907                    if (!(piped ? pump(true) : batch_step())) return 1;
9908                    continue;
9909                }
9910                // a request reads its prompt through every stage: the groups in flight finish first
9911                if (piped && line.rfind("BSTOP ", 0) != 0 && !pipe_drain()) return 1;
9912            } else if (!next_line(line)) {
9913                break;
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
9917            if (line.rfind("BSTOP ", 0) == 0) {
9918                const int b = std::atoi(line.c_str() + 6);
9919                if (b >= 0 && b < (int) bs.size()) bs[(size_t) b].stop = true;
9920                continue;
9921            }
9922            if (line.rfind("BYIELD", 0) == 0) continue;   // for a prompt read that has ended meanwhile
9923            if (line.rfind("VRAM", 0) == 0) {   // #533 (above): between requests, not a request
9924                std::string verr;
9925                if (batch_on()) verr = "VRAM: not while batch slots are decoding";
9926                else vram_command(line, verr);
9927                if (!verr.empty()) std::printf("ERR %s\n", verr.c_str());
9928                std::fflush(stdout);
9929                continue;
9930            }
9931            admit_slot = -1;
9932            if (line.rfind("BGEN ", 0) == 0 || line.rfind("BGENI ", 0) == 0) {
9933                const bool bimg = line.rfind("BGENI ", 0) == 0;
9934                char* e1 = nullptr;
9935                const long b = std::strtol(line.c_str() + (bimg ? 6 : 5), &e1, 10);
9936                char* e2 = nullptr;
9937                const long long mn = std::strtoll(e1, &e2, 10);
9938                if (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);
9941                    continue;
9942                }
9943                admit_slot = (int) b;
9944                admit_max_new = mn;
9945                line = 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)
9948            if ((!heat.empty() || usage_dev_srv != nullptr) && line != "QUIT" && o.expert_profile_save_min > 0 &&
9949                Clock::now() - profile_saved_at >= std::chrono::duration<double>(o.expert_profile_save_min * 60.0))
9950                save_profile("periodic");
9951            if (line == "QUIT") break;
9952            // the watchdog watches a request from here until this iteration ends, whichever way it ends
9953            struct BusyScope {
9954                BusyScope() {
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;
9965            stop_req.store(false);   // a STOP that arrived between requests is stale
9966            err.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.)
9977            if (line.rfind("SAVE ", 0) == 0 || line.rfind("RESTORE ", 0) == 0) {
9978                const bool save = line[0] == 'S';
9979                const std::string path = line.substr(save ? 5 : 8);
9980                const auto t0 = Clock::now();
9981                auto ms = [&] { return std::chrono::duration<double, std::milli>(Clock::now() - t0).count(); };
9982                auto refuse = [&](const std::string& why, strata::core::SessionError kind = strata::core::SessionError::invalid,
9983                                  bool published = false) {
9984                    std::fprintf(stderr, "strata serve: session %s %s: %s\n", save ? "save" : "restore", path.c_str(),
9985                                 why.c_str());
9986                    std::string one = why;   // one protocol line
9987                    for (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);
9990                    err.clear();
9991                };
9992                auto 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
10000                auto blocking = [&](const char* phase, uint64_t bytes) {
10001                    const 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");
10008                if (path.empty()) { refuse("missing path"); continue; }
10009                if (!stages.empty() || multi_gpu) { refuse("session files do not support --layer-split"); continue; }
10010                if (o.peer_device >= 1) { refuse("session files do not support --peer-device"); continue; }
10011                if (o.batch > 0) { refuse("session files do not support --batch (parallel requests)"); continue; }
10012                if (o.prompt_cache <= 0) { refuse("session files need --prompt-cache > 0"); continue; }
10013                if (!ver.wait_commit(err)) {
10014                    std::printf("ERR %s\n", err.c_str());
10015                    return 1;
10016                }
10017                strata::core::SessionFileIdentity id;
10018                try {
10019                    if (!session_identity(id, err, [&] { blocking("fingerprint", 2u << 20); })) {
10020                        refuse(err, strata::core::SessionError::io);
10021                        continue;
10022                    }
10023                } catch (const std::bad_alloc&) {
10024                    refuse("session identity: out of memory", strata::core::SessionError::memory);
10025                    continue;
10026                } catch (const std::exception& e) {
10027                    refuse(std::string("session identity: ") + e.what(), strata::core::SessionError::io);
10028                    continue;
10029                }
10030                if (save) {
10031                    if (!live_ok || live.empty()) { refuse("no complete session to save"); continue; }
10032                    size_t bytes = 0, kept = 0;
10033                    double capture_ms = 0;
10034                    try {
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;
10045                            uint64_t state = UINT64_MAX;   // unknown sizes: the preflight refuses rather than guesses
10046                            if (strata::core::conversation_session_sizes(g, ss, z, why)) {
10047                                const uint64_t q = (uint64_t) std::max<int64_t>(ss.qsa_alloc, 0);
10048                                const uint64_t per = (uint64_t) z.tail + z.dead + z.block_pos;
10049                                if (q == 0 || per <= (UINT64_MAX - z.gdn - z.ple) / q) state = z.gdn + z.ple + q * per;
10050                            }
10051                            sl.state_bytes = state;
10052                            sl.tokens = live.size();
10053                            sl.images = live_imgs.size();
10054                            sl.kv_layers = (uint64_t) std::max<int64_t>(ss.qsa_alloc, 0) + 1;
10055                        }
10056                        const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20;
10057                        auto admit = [&](uint64_t need, std::string& why) {
10058                            const auto avail = strata::core::available_host_bytes();
10059                            if (strata::core::conversation_memory_admit(avail, need, floor)) return true;
10060                            why = "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)");
10065                            return false;
10066                        };
10067                        std::vector<ConvCheckpoint> disk_checks;
10068                        std::string why;
10069                        if (!strata::core::session_save_checkpoints(checks, sl, admit, disk_checks, why)) {
10070                            refuse(why, strata::core::SessionError::memory);
10071                            continue;
10072                        }
10073                        kept = disk_checks.size();
10074                        const 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
10078                        blocking("capture", sl.state_bytes == UINT64_MAX ? 0 : sl.state_bytes);
10079                        if (!strata::core::conversation_snapshot_sources(meta, sources, view, ss, g, mtp.kv_state(),
10080                                                                         err)) {
10081                            refuse(err, strata::core::SessionError::io);
10082                            continue;
10083                        }
10084                        capture_ms = ms();
10085                        strata::core::SessionWriteOptions wo;
10086                        wo.min_free_bytes = (uint64_t) o.session_min_free_mib << 20;
10087                        wo.progress = moving;
10088                        wo.phase = blocking;
10089                        strata::core::SessionStatus st;
10090                        if (!strata::core::session_file_write(path, meta, sources, id, bytes, err, wo, &st)) {
10091                            refuse(err, st.error, st.published);
10092                            continue;
10093                        }
10094                        if (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&) {
10098                        refuse("not enough RAM to save the session", strata::core::SessionError::memory);
10099                        continue;
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,
10103                                 path.c_str(), ms(), capture_ms);
10104                    std::printf("SAVED %zu %zu %.1f\n", live.size(), bytes, ms());
10105                } else {
10106                    strata::core::SavedConversation image;
10107                    size_t bytes = 0;
10108                    try {
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;
10113                        limits.progress = moving;
10114                        const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20;
10115                        limits.admit = [floor, &o](uint64_t need, std::string& why) {
10116                            const auto avail = strata::core::available_host_bytes();
10117                            if (strata::core::conversation_memory_admit(avail, need, floor)) return true;
10118                            why = "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)");
10121                            return false;
10122                        };
10123                        if (!strata::core::conversation_session_read_limits(
10124                                limits, ss, g, mtp.kv_state(), (uint64_t) o.max_context,
10125                                (uint64_t) std::max(o.prompt_cache, 1), err)) {
10126                            refuse(err, strata::core::SessionError::io);
10127                            continue;
10128                        }
10129                        strata::core::SessionStatus st;
10130                        if (!strata::core::session_file_read(path, id, image, bytes, err, limits, &st)) {
10131                            refuse(err, st.error);
10132                            continue;
10133                        }
10134                    } catch (const std::bad_alloc&) {
10135                        refuse("not enough RAM to read the session", strata::core::SessionError::memory);
10136                        continue;
10137                    }
10138                    const double read_ms = ms();
10139                    // the whole image against this engine, still without any device write
10140                    blocking("validate", bytes);
10141                    if (!strata::core::conversation_snapshot_validate(image, ss, g, mtp.kv_state(), err)) {
10142                        refuse(err);
10143                        continue;
10144                    }
10145                    // the elastic K/V (--kv-grow) maps only the cells it has grown to: make room for the file's cells
10146                    if (!kvg_ensure((int64_t) image.live.ids.size() + 256, [&] {
10147                                                                                 dpct::get_current_device()
10148                                                                                     .queues_wait_and_throw();
10149                                                                                     apply_pending(
10150                                                                                         true); })) {
10151                        refuse("the K/V cannot grow to the saved conversation: no VRAM is left", strata::core::SessionError::memory);
10152                        continue;
10153                    }
10154                    conversations.take_reuse();   // retained K/V described the outgoing session
10155                    live_ok = false;
10156                    // host -> device in synchronous copies of the whole state: one bounded allowance
10157                    blocking("transfer", bytes);
10158                    if (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(),
10163                                     err.c_str());
10164                        std::printf("FATAL restoring the session file failed after the device state was changed: %s\n",
10165                                    err.c_str());
10166                        std::fflush(stdout);
10167                        return 1;
10168                    }
10169                    live = std::move(image.live.ids);
10170                    live_imgs = std::move(image.live.imgs);
10171                    checks = std::move(image.checkpoints);
10172                    for (const ConvCheckpoint& c : checks) check_clock = std::max(check_clock, c.used);
10173                    cvec_cached = image.cvec;
10174                    live_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(),
10177                                 ms(), read_ms);
10178                    std::printf("RESTORED %zu %zu %.1f\n", live.size(), bytes, ms());
10179                }
10180                std::fflush(stdout);
10181                continue;
10182            }
10183            const bool geni = line.rfind("GENI ", 0) == 0;
10184            if (!geni && line.rfind("GEN ", 0) != 0) {
10185                std::printf("ERR expected: GEN <max_new> <id,id,...> or GENI <max_new> <file> <id,id,...>\n");
10186                continue;
10187            }
10188            char* endp = nullptr;
10189            const 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.
10193            float req_temperature = 0.0f, req_top_p = 1.0f;
10194            int req_top_k = 20;   // the sampler's own default; the sampled path REQUIRES top_k in 1..64
10195            unsigned long long req_seed = 0;
10196            float req_min_p = 0.0f, req_penalty_repeat = 1.0f, req_penalty_freq = 0.0f, req_penalty_present = 0.0f;
10197            int req_penalty_last_n = 0;
10198            long 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
10199            int 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.
10203            int 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.
10211            int 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;
10217            double req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p;
10218            if (endp != nullptr) {   // GENI takes the same keys (#75: image requests were always greedy); its
10219                                     // embedding file path is the first token without an =
10220                for (;;) {
10221                    while (*endp == ' ') ++endp;
10222                    const char* start = endp;
10223                    while (*endp != '\0' && *endp != ' ') ++endp;
10224                    if (endp == start) break;
10225                    const std::string tok(start, (size_t) (endp - start));
10226                    const size_t eq = tok.find('=');
10227                    if (eq == std::string::npos) { endp = const_cast<char*>(start); break; }
10228                    const std::string key = tok.substr(0, eq);
10229                    const float fv = std::strtof(tok.c_str() + eq + 1, nullptr);
10230                    if (key == "cvec") req_cvec = std::atoi(tok.c_str() + eq + 1);
10231                    else if (key == "ckpt") req_ckpt = std::atoi(tok.c_str() + eq + 1) != 0;
10232                    else if (key == "temperature") req_temperature = fv;
10233                    else if (key == "top_p") req_top_p = fv;
10234                    else if (key == "top_k") req_top_k = std::atoi(tok.c_str() + eq + 1);
10235                    else if (key == "min_p") req_min_p = fv;
10236                    else if (key == "penalty_last_n") req_penalty_last_n = std::atoi(tok.c_str() + eq + 1);
10237                    else if (key == "pen_from") req_pen_from = std::atoll(tok.c_str() + eq + 1);
10238                    else if (key == "penalty_repeat") req_penalty_repeat = fv;
10239                    else if (key == "penalty_freq") req_penalty_freq = fv;
10240                    else if (key == "penalty_present") req_penalty_present = fv;
10241                    else if (key == "seed") req_seed = std::strtoull(tok.c_str() + eq + 1, nullptr, 10);
10242                    else if (key == "logprobs") req_logprobs = std::clamp(std::atoi(tok.c_str() + eq + 1), -1, 20);
10243                    else if (key == "allowed") {
10244                        const std::string csv = tok.substr(eq + 1);
10245                        size_t p = 0;
10246                        while (p < csv.size()) {
10247                            const size_t c = csv.find(",", p);
10248                            const std::string one = csv.substr(p, c == std::string::npos ? std::string::npos : c - p);
10249                            if (!one.empty()) req_allowed.push_back((int32_t) std::atoi(one.c_str()));
10250                            if (c == std::string::npos) break;
10251                            p = c + 1;
10252                        }
10253                    }
10254                    else if (key == "pcie_frac") req_pcie_frac = std::clamp((double) fv, 0.0, 1.0);
10255                    else if (key == "spec_min_p") req_spec_min_p = std::clamp((double) fv, 0.0, 1.0);
10256                    else if (key == "img_keys") {
10257                        req_img_keys.clear();
10258                        const char* q = tok.c_str() + eq + 1;
10259                        while (*q != '\0') {
10260                            char* qe = nullptr;
10261                            const unsigned long long v = std::strtoull(q, &qe, 16);
10262                            if (qe == q) { req_img_keys.clear(); break; }
10263                            req_img_keys.push_back((uint64_t) v);
10264                            q = *qe == ',' ? qe + 1 : qe;
10265                            if (*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;
10272            if (geni && endp != nullptr) {
10273                while (*endp == ' ') ++endp;
10274                char* gap = std::strchr(endp, ' ');
10275                if (gap != nullptr) { emb_path.assign(endp, (size_t) (gap - endp)); endp = gap; }
10276            }
10277            std::vector<int64_t> ids;
10278            std::string pe;
10279            if (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());
10281                continue;
10282            }
10283            const int64_t n = (int64_t) ids.size();
10284            req_imgs.clear();
10285            if (geni && !o.vision) { std::printf("ERR this engine was started without --vision\n"); continue; }
10286            if (geni || !mrope_identity) {
10287                // positions for every cell this request can reach; the identity again for a text request
10288                std::string ve;
10289                row_ptr.assign((size_t) n, nullptr);
10290                const int64_t cells = (int64_t) mrope_host.size() / 3;
10291                auto put = [&](int64_t c, int64_t t, int64_t h, int64_t w) {
10292                    mrope_host[(size_t) c * 3] = (int32_t) t;
10293                    mrope_host[(size_t) c * 3 + 1] = (int32_t) h;
10294                    mrope_host[(size_t) c * 3 + 2] = (int32_t) w;
10295                };
10296                if (!geni) {
10297                    for (int64_t c = 0; c < cells; ++c) put(c, c, c, c);
10298                } else {
10299                    struct Img { int64_t n, nx, ny; size_t off; };
10300                    std::vector<Img> imgs;
10301                    img_rows.clear();
10302                    std::FILE* f = std::fopen(emb_path.c_str(), "rb");
10303                    if (!f) ve = "cannot open " + emb_path;
10304                    while (f && ve.empty()) {
10305                        int32_t hdr[5];
10306                        const size_t got = std::fread(hdr, sizeof(int32_t), 5, f);
10307                        if (got == 0) break;
10308                        if (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) {
10310                            ve = "bad embeddings file (expected strata-vision records of width " +
10311                                 std::to_string((long long) g.n_embd) + ")";
10312                            break;
10313                        }
10314                        const size_t off = img_rows.size(), cnt = (size_t) hdr[1] * (size_t) hdr[4];
10315                        img_rows.resize(off + cnt);
10316                        if (std::fread(img_rows.data() + off, sizeof(float), cnt, f) != cnt) { ve = "short embeddings file"; break; }
10317                        imgs.push_back({hdr[1], hdr[2], hdr[3], off});
10318                    }
10319                    if (f) std::fclose(f);
10320                    int64_t p = 0, i = 0;
10321                    size_t k = 0;
10322                    while (ve.empty() && i < n) {
10323                        if (ids[(size_t) i] != kImagePad) { put(i, p, p, p); ++p; ++i; continue; }
10324                        if (k >= imgs.size()) { ve = "the prompt has more images than the embeddings file"; break; }
10325                        const Img& im = imgs[k++];
10326                        {   // what the conversation cache compares: a picture is its grid and its embeddings
10327                            const int64_t grid[3] = {im.n, im.nx, im.ny};
10328                            uint64_t h = fnv1a(grid, sizeof grid);
10329                            if (req_img_keys.size() == imgs.size())   // #2228: the server's key for picture k
10330                                h = fnv1a(&req_img_keys[k - 1], sizeof(uint64_t), h);
10331                            else
10332                                h = fnv1a(img_rows.data() + im.off, (size_t) im.n * (size_t) g.n_embd * sizeof(float), h);
10333                            req_imgs.push_back({i, h});
10334                        }
10335                        for (int64_t j = 0; j < im.n && ve.empty(); ++j)
10336                            if (i + j >= n || ids[(size_t) (i + j)] != kImagePad)
10337                                ve = "image " + std::to_string(k) + " has " + std::to_string((long long) im.n) +
10338                                     " rows but fewer <|image_pad|> tokens";
10339                        for (int64_t j = 0; j < im.n && ve.empty(); ++j) {
10340                            const int64_t y = j / im.nx, x = j % im.nx;
10341                            put(i + j, p, p + y, p + x);
10342                            row_ptr[(size_t) (i + j)] = img_rows.data() + im.off + (size_t) j * (size_t) g.n_embd;
10343                        }
10344                        i += im.n;
10345                        p += std::max(im.nx, im.ny);
10346                    }
10347                    if (ve.empty() && k != imgs.size()) ve = "the embeddings file has more images than the prompt";
10348                    if (ve.empty() && n > 0 && ids[(size_t) (n - 1)] == kImagePad) ve = "the prompt cannot end in an image";
10349                    for (int64_t c = n; ve.empty() && c < cells; ++c) put(c, p + (c - n), p + (c - n), p + (c - n));
10350                }
10351                tr("positions built", (long long) img_rows.size());
10352                dpct::get_current_device().queues_wait_and_throw();
10353                tr("device idle");
10354                // CUDA0's table and, with a layer split, every later stage's (each device reads its own)
10355                auto upload_mrope = [&]() -> bool {
10356                    try {
10357                bool ok = DPCT_CHECK_ERROR(
10358                              dpct::get_in_order_queue()
10359                                  .memcpy(d_mrope, mrope_host.data(),
10360                                          mrope_host.size() * sizeof(int32_t))
10361                                  .wait()) == 0;
10362                    for (auto& st : stages) {
10363                        const strata::core::OnDevice on(st->dev);
10364                        dpct::get_current_device().queues_wait_and_throw();
10365                        ok =
10366                            ok &&
10367                            DPCT_CHECK_ERROR(
10368                                dpct::get_in_order_queue()
10369                                    .memcpy(st->mrope, mrope_host.data(),
10370                                            mrope_host.size() * sizeof(int32_t))
10371                                    .wait()) == 0;
10372                    }
10373                    return ok;
10374                }
10375                catch (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                };
10382                if (ve.empty() && !upload_mrope()) ve = "the image position upload failed";
10383                if (!ve.empty()) {
10384                    // leave the table as the identity so the next text request is untouched
10385                    for (int64_t c = 0; c < cells; ++c) put(c, c, c, c);
10386                    upload_mrope();
10387                    mrope_identity = true;
10388                    std::printf("ERR %s\n", ve.c_str());
10389                    std::fflush(stdout);
10390                    continue;
10391                }
10392                mrope_identity = !geni;
10393            }
10394            sp.embd_rows = geni ? row_ptr.data() : nullptr;
10395            if (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);
10398                continue;
10399            }
10400            bool bad = false;
10401            for (int64_t t : ids) bad = bad || t < 0 || t >= n_vocab;
10402            if (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{};
10409            for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0)
10410            {
10411                remote_before[(size_t) r] = remote_experts[(size_t) r].computed();
10412                launches_before[(size_t) r] = remote_experts[(size_t) r].launched_layers();
10413                compact_before[(size_t) r] = remote_experts[(size_t) r].returned_bytes();
10414                full_before[(size_t) r] = remote_experts[(size_t) r].full_row_bytes();
10415                begin_before[(size_t) r] = remote_experts[(size_t) r].ms_begin();
10416                wait_before[(size_t) r] = remote_experts[(size_t) r].ms_wait();
10417            }
10418            cur = ids;
10419            const 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
10422            auto starts_with = [&](const std::vector<int32_t>& pre, const std::vector<ImgKey>& pre_imgs) -> bool {
10423                const int64_t L = (int64_t) pre.size();
10424                if (L < 1 || L > n - 1) return false;
10425                for (int64_t i = 0; i < L; ++i)
10426                    if ((int32_t) ids[(size_t) i] != pre[(size_t) i]) return false;
10427                return imgs_below(req_imgs, L) == pre_imgs;
10428            };
10429            const 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)
10433            if (!ver.wait_commit(err)) {
10434                std::printf("ERR %s\n", err.c_str());
10435                return 1;
10436            }
10437            auto kv_quiesce = [&] {
10438                                    try {
10439            dpct::get_current_device().queues_wait_and_throw(); apply_pending(true); }
10440            catch (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            };
10446            if (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)
10448                if (!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);
10451                    return 1;
10452                }
10453            }
10454            int64_t resume = 0;
10455            bool from_live = false;
10456            if (o.prompt_cache > 0 && want_cvec == cvec_cached) {
10457                if (live_ok && starts_with(live, live_imgs)) { resume = (int64_t) live.size(); from_live = true; }
10458                for (const ConvCheckpoint& c : checks)
10459                    if ((int64_t) c.ids.size() > resume && starts_with(c.ids, c.imgs)) {
10460                        resume = (int64_t) c.ids.size();
10461                        from_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
10466            int slot_source = -1;
10467            int64_t slot_tokens = 0;
10468            bool resumed_from0 = false;   // a prompt read parked in a slot (BYIELD) that had started at token 0
10469            const ConvCheckpoint* slot_ck = nullptr;   // the slot's checkpoint the prompt continues from (else its end)
10470            if (o.prompt_cache > 0 && req_imgs.empty())
10471                for (int b = 0; b < (int) bs.size(); ++b) {
10472                    const BSlot& sl = bs[(size_t) b];
10473                    if (sl.active || !sl.cached || sl.cvec != want_cvec) continue;
10474                    if ((int64_t) sl.ids.size() > std::max(resume, slot_tokens) && starts_with(sl.ids, {})) {
10475                        slot_source = b;
10476                        slot_tokens = (int64_t) sl.ids.size();
10477                        slot_ck = nullptr;
10478                    }
10479                    for (const ConvCheckpoint& c : sl.checks)
10480                        if ((int64_t) c.ids.size() > std::max(resume, slot_tokens) && starts_with(c.ids, c.imgs)) {
10481                            slot_source = b;
10482                            slot_tokens = (int64_t) c.ids.size();
10483                            slot_ck = &c;
10484                        }
10485                }
10486            const auto parked = conversations.best(ids, req_imgs, want_cvec);
10487            std::optional<strata::core::SavedConversation> incoming;
10488            if (parked.tokens > std::max(resume, slot_tokens)) incoming.emplace(conversations.take(parked.index));
10489            if (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.
10492            if (incoming && incoming->stage_images.size() != stages.size()) {
10493                std::fprintf(stderr, "strata serve: conversation cache: discard snapshot (stage count)\n");
10494                incoming.reset();
10495            }
10496            if (incoming) for (size_t i = 0; i < stages.size(); ++i) {
10497                const strata::core::OnDevice on(stages[i]->dev);
10498                if (!strata::core::conversation_snapshot_validate(incoming->stage_images[i], stages[i]->ss, g,
10499                        use_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",
10501                                 err.c_str());
10502                    incoming.reset();
10503                    err.clear();
10504                    break;
10505                }
10506            }
10507            if (incoming && !strata::core::conversation_snapshot_validate(*incoming, ss, g,
10508                    use_mtp && stages.empty() ? &mtp.kv_state() : nullptr, err)) {
10509                std::fprintf(stderr, "strata serve: conversation cache: discard invalid snapshot (%s)\n", err.c_str());
10510                incoming.reset();
10511                err.clear();
10512            }
10513            // Preserve the outgoing branch before any checkpoint rewind, reset,
10514            // or incoming restore overwrites the positional state it requires.
10515            if ((!from_live || incoming || slot_source >= 0) && !park_current(incoming ? incoming->bytes() : 0)) {
10516                std::printf("ERR %s\n", err.c_str());
10517                return 1;
10518            }
10519            if (slot_source >= 0) {
10520                const auto t0 = Clock::now();
10521                if (!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",
10524                                 slot_source, err.c_str());
10525                    err.clear();
10526                    live.clear();
10527                    live_imgs.clear();
10528                    checks.clear();
10529                    resume = 0;
10530                    from_live = false;
10531                } else {
10532                    checks.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
10535                    if (slot_ck == nullptr && bs[(size_t) slot_source].partial && admit_slot == slot_source) {
10536                        resumed_from0 = bs[(size_t) slot_source].partial_from0;
10537                        bs[(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
10543                    try {   // 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)
10545                        const std::vector<int32_t>& copied_back = slot_ck != nullptr ? slot_ck->ids : bs[(size_t) slot_source].ids;
10546                        for (const ConvCheckpoint& c : bs[(size_t) slot_source].checks)
10547                            if ((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()))
10549                                checks.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                    }
10553                    if (slot_ck != nullptr) {
10554                        live = slot_ck->ids;
10555                        for (ConvCheckpoint& c : checks)   // the main session's chain has it now
10556                            if (c.ids.size() == slot_ck->ids.size()) c.used = ++check_clock;
10557                    } else {
10558                        live = bs[(size_t) slot_source].ids;
10559                    }
10560                    live_imgs.clear();
10561                    resume = slot_tokens;
10562                    from_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,
10565                                 slot_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
10570            if (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");
10572                return 1;
10573            }
10574            if (incoming) {
10575                const auto t0 = Clock::now();
10576                if (strata::core::conversation_snapshot_restore(*incoming, ss, g,
10577                        use_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());
10582                    return 1;
10583                }
10584                for (size_t i = 0; i < stages.size(); ++i) {   // the later stages' parts
10585                    const strata::core::OnDevice on(stages[i]->dev);
10586                    if (strata::core::conversation_snapshot_restore(incoming->stage_images[i], stages[i]->ss, g,
10587                            use_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,
10590                                    err.c_str());
10591                        return 1;
10592                    }
10593                    if (DPCT_CHECK_ERROR(dpct::get_current_device()
10594                                             .queues_wait_and_throw()) != 0) {
10595                        std::printf("ERR stage sync\n"); return 1;
10596                    }
10597                }
10598                if (use_mtp && std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) {
10599                    uint64_t draft_hash = 0;
10600                    const auto& draft_kv = stages.empty() ? incoming->kv.back() : incoming->stage_images.back().kv.back();
10601                    const strata::core::OnDevice on_d(stages.empty() ? 0 : stages.back()->dev);
10602                    if (!strata::core::conversation_kv_verify(draft_kv, mtp.kv_state(), g,
10603                            int64_t(incoming->live.ids.size()), false, draft_hash, err)) {
10604                        std::printf("ERR verifying restored draft KV: %s\n", err.c_str());
10605                        return 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,
10609                                 mtp.kv_state().kv_mode, "ram",
10610                                 (long long) (mtp.kv_state().n_slots * strata::kernels::qsa_real_shapes().page_size));
10611                }
10612                live = std::move(incoming->live.ids);
10613                live_imgs = std::move(incoming->live.imgs);
10614                if (stages.empty()) {
10615                    checks = 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;
10618                    cs.stage0 = std::move(incoming->checkpoints);
10619                    for (auto& si : incoming->stage_images) cs.parts.push_back(std::move(si.checkpoints));
10620                    if (!strata::core::conversation_checkpoints_merge(std::move(cs), checks)) checks.clear();
10621                }
10622                cvec_cached = incoming->cvec;
10623                resume = parked.tokens;
10624                from_live = parked.live;
10625                if (std::getenv("STRATA_SNAPSHOT_FULL_CAPTURE") == nullptr) {
10626                    std::vector<std::vector<strata::core::ConversationKv>> stage_kv;   // every stage's, for its next park
10627                    for (auto& si : incoming->stage_images) stage_kv.push_back(std::move(si.kv));
10628                    conversations.retain(std::move(incoming->kv), int64_t(live.size()), std::move(stage_kv), live);
10629                }
10630                incoming.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(),
10634                             conversations.size(), conversations.bytes());
10635            }
10636            if (want_cvec != cvec_cached) {
10637                live_ok = false;
10638                checks.clear();
10639                cvec_cached = want_cvec;
10640            }
10641            if (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
10644            checks.erase(std::remove_if(checks.begin(), checks.end(), [&](const ConvCheckpoint& c) {
10645                             return (int64_t) c.ids.size() > resume || !starts_with(c.ids, c.imgs);
10646                         }), checks.end());
10647            live_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
10650            if (kvg.on) {
10651                kv_quiesce();
10652                if (!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);
10655                    return 1;
10656                }
10657            }
10658            int64_t reread_to = -1;   // STRATA_CKPT_REREAD only: read [0, reread_to) again instead of restoring
10659            if (resume == 0) {
10660                strata::core::session_zero(ss, g, nullptr, main_cs);
10661                main_stream->wait();
10662                for (auto& st : stages) {
10663                    const strata::core::OnDevice on(st->dev);
10664                    strata::core::session_zero(st->ss, g, nullptr, (void*) st->stream);
10665                    st->stream->wait();
10666                }
10667                checks.clear();
10668            } else if (!from_live) {
10669                ConvCheckpoint* c = nullptr;
10670                for (ConvCheckpoint& k : checks) if ((int64_t) k.ids.size() == resume) c = &k;
10671                if (c != nullptr) c->used = ++check_clock;   // mounting through it is the use LRU counts
10672                static const bool reread = std::getenv("STRATA_CKPT_REREAD") != nullptr;
10673                if (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);
10680                    main_stream->wait();
10681                    for (auto& st : stages) {
10682                        const strata::core::OnDevice on(st->dev);
10683                        strata::core::session_zero(st->ss, g, nullptr, (void*) st->stream);
10684                        st->stream->wait();
10685                    }
10686                    reread_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                           [&] {
10691                               for (size_t i = 0; i < stages.size(); ++i) {
10692                                   const strata::core::OnDevice on(stages[i]->dev);
10693                                   if (!checkpoint_restore(c->stage_parts[i], stages[i]->ss, g)) return true;
10694                               }
10695                               return false;
10696                           }()) {
10697                    std::printf("ERR restoring a conversation checkpoint failed\n");
10698                    return 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
10703            if (use_mtp && resume > 0 && reread_to <= 0) mtp.kv_restore(resume);
10704            tr("request", n, geni ? 1 : 0);
10705            strata::workload_trace::set_context(0, n, -1);
10706            strata::workload_trace::Scope request_trace("request", nullptr, n);
10707            if (use_mtp) mtp.set_prompt_len(n);
10708            if (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());
10710                bool cold = false;
10711                df2.begin_request(idv.data(), (int64_t) idv.size(), reread_to > 0 ? 0 : resume, &cold);
10712                if (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",
10714                                 df2.last_swapped ? "a parked conversation came back: " : "", (long long) df2.last_rebuilt, df2.last_ms,
10715                                 df2.last_missing >= 64 ? " (the rest were never logged)" : "");
10716                if (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));
10720                sp.set_taps(df2.tap_layers(), std::max<int64_t>(0, n - 2047), 2048);
10721            }
10722            const int64_t read_from = reread_to > 0 ? 0 : resume;
10723            conversations.limit_reuse(read_from);
10724            pp_total = n;
10725            pp_from = read_from;
10726            pp_reached = read_from;
10727            pp_t0 = r0;
10728            pp_next_check = reread_to > 0 || !req_ckpt ? INT64_MAX : resume + o.prompt_cache_every;   // ckpt=0: none
10729            pp_tail_saved = reread_to > 0 || !req_ckpt;   // ckpt=0 (#861): no tail checkpoint either
10730            {
10731                std::lock_guard<std::mutex> lk(part_mu);
10732                part_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.
10745            static const bool no_short = std::getenv("STRATA_CKPT_REREAD") != nullptr;
10746            int64_t req_short_read = o.short_read;   // STRATA_PIPELINE_SWITCH may set it per request (short_read=)
10747            auto windows_ok = [&](int64_t a, int64_t b) -> bool {
10748                if (no_short || b - a > req_short_read) return false;
10749                if (sp.embd_rows != nullptr)
10750                    for (int64_t i = a; i < b; ++i)
10751                        if (sp.embd_rows[i] != nullptr) return false;
10752                return 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
10757            int pl_pw = pipe ? o.pipeline_windows : 0;
10758            float pl_theta = [] {   // a speculative window is launched only when its estimated chance is at least this
10759                const char* v = pipe_dbg_env("STRATA_PIPELINE_THETA");
10760                return v ? (float) std::atof(v) : 0.2f;
10761            }();
10762            int pl_force_miss = [] {   // exactness test: every k-th speculative window gets a wrong first token
10763                const char* v = pipe_dbg_env("STRATA_PIPELINE_FORCE_MISS");
10764                return v ? std::max(0, std::atoi(v)) : 0;
10765            }();
10766            if (static const char* sw = pipe_dbg_env("STRATA_PIPELINE_SWITCH"); sw != nullptr && pipe) {
10767                if (std::FILE* f = std::fopen(sw, "r")) {
10768                    char buf[256] = {};
10769                    const size_t nr = std::fread(buf, 1, sizeof buf - 1, f);
10770                    std::fclose(f);
10771                    buf[nr] = 0;
10772                    if (const char* q = std::strstr(buf, "pw=")) pl_pw = std::max(0, std::min(2, std::atoi(q + 3)));
10773                    if (const char* q = std::strstr(buf, "theta=")) pl_theta = (float) std::atof(q + 6);
10774                    if (const char* q = std::strstr(buf, "force_miss=")) pl_force_miss = std::max(0, std::atoi(q + 11));
10775                    if (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,
10777                                 pl_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.
10784            auto 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);
10786                if (!pl_prepare(e)) return false;
10787                for (int par = 0; par < 2; ++par) PV[0][par]->set_head_sampling(false);   // reaches stage 1 (set_next)
10788                struct 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]}};
10792                struct Win { int T; int64_t q; };
10793                std::vector<Win> wins;
10794                for (int64_t q = a; q < b;) {
10795                    const int T = (int) std::min<int64_t>(S, b - q);
10796                    wins.push_back({T, q});
10797                    q += T;
10798                }
10799                const size_t N = wins.size();
10800                std::vector<int32_t> w0((size_t) S), w1((size_t) S), nx((size_t) S);
10801                size_t l0 = 0, f0 = 0, l1 = 0, f1 = 0;   // stage 0 launched / finished, stage 1 launched / finished
10802                drive.d.layers = 0;
10803                drive.d.experts = 0;
10804                drive.d.failed = false;
10805                auto fail = [&](std::string why) -> bool {
10806                    pl_drain();
10807                    e = why.empty() ? std::string("a pipelined prompt window failed") : why;
10808                    return false;
10809                };
10810                while (f1 < N) {
10811                    if (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
10814                    while (l0 < N && l0 < f0 + 2 && l0 < f1 + 2) {
10815                        const Win& w = wins[l0];
10816                        for (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];
10818                        if (!v.pl_launch(w.T, w0.data(), w.q, e) || !v.pl_commit_async(w.T, e)) return fail(e);
10819                        ++l0;
10820                    }
10821                    if (f0 < l0) {
10822                        strata::core::Verifier& v = *PV[0][f0 & 1];
10823                        if (v.service(win_pool_fn, PSD[f0 & 1], e) < 0) return fail(e);
10824                        if (v.done(e)) {
10825                            if (!v.pl_finish(nullptr, e)) return fail(e);
10826                            ++f0;
10827                        } else if (!e.empty()) return fail(e);
10828                    }
10829                    if (l1 < f0 && l1 == f1) {   // stage 1: the next window, its stage 0 done
10830                        const Win& w = wins[l1];
10831                        for (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];
10833                        if (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.
10839                            if (mtp.device() == v.device()) {
10840                                const 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) {
10845                                return fail("the drafter's rows did not land before the window");
10846                            }
10847                        }
10848                        if (!v.pl_launch(w.T, w1.data(), w.q, e) || !v.pl_commit_async(w.T, e)) return fail(e);
10849                        ++l1;
10850                    }
10851                    if (f1 < l1) {
10852                        strata::core::Verifier& v = *PV[1][f1 & 1];
10853                        if (v.service(win_pool_fn, PSD[f1 & 1], e) < 0) return fail(e);
10854                        if (v.done(e)) {
10855                            if (!v.pl_finish(nullptr, e)) return fail(e);
10856                            const Win& w = wins[f1];
10857                            for (int t = 0; t < w.T; ++t) nx[(size_t) t] = (int32_t) cur[(size_t) (w.q + t + 1)];
10858                            if (!mtp.prefill(v.final_R(0), nx.data(), w.T, w.q, e, false)) return fail(e);
10859                            {
10860                                const strata::core::OnDevice on(mtp.device());
10861                                dpct::sync_barrier(pl_mtp_ev[f1 & 1],
10862                                                   mtp.stream());
10863                            }
10864                            pl_mtp_live[f1 & 1] = true;
10865                            pp_reached = w.q + w.T;   // #471
10866                            ++f1;
10867                        } else if (!e.empty()) return fail(e);
10868                    }
10869                    if (drive.d.failed) return fail(drive.d.fail ? drive.d.fail : "the expert pool failed");
10870                }
10871                pl_drain();   // nothing in flight: both stages' commits and the drafter's rows have landed
10872                pl_mtp_live[0] = pl_mtp_live[1] = false;
10873                const 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,
10875                            ms > 0.0 ? 1000.0 * (double) (b - pp_from) / ms : 0.0);
10876                strata::core::progress_beat();
10877                std::fflush(stdout);
10878                return true;
10879            };
10880            // tokens [a, b) through the windows: commit all of them, then give the draft layer their residuals
10881            auto read_windows = [&](int64_t a, int64_t b, std::string& e) -> bool {
10882                // (STRATA_LOGPOS reads every window's logits: the serial loop)
10883                if (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)
10886                struct NoHeadSampling {
10887                    strata::core::Verifier& v;
10888                    explicit 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);
10892                for (int64_t q = a; q < b;) {
10893                    if (stop_req.load()) { e = "cancelled"; return false; }
10894                    const int T = (int) std::min<int64_t>(S, b - q);
10895                    for (int t = 0; t < T; ++t) {
10896                        win[(size_t) t] = (int32_t) cur[(size_t) (q + t)];
10897                        nxt[(size_t) t] = (int32_t) cur[(size_t) (q + t + 1)];
10898                    }
10899                    drive.d.layers = 0;
10900                    drive.d.experts = 0;
10901                    drive.d.failed = false;
10902                    if (!ver.run(T, win.data(), q, win_pool_fn, win_pool_user, outw.data(), e) || drive.d.failed) {
10903                        if (drive.d.failed && drive.d.fail) e = drive.d.fail;
10904                        return 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
10910                    static std::FILE* logpos = [] {
10911                        const char* p = std::getenv("STRATA_LOGPOS");
10912                        return p != nullptr ? std::fopen(p, "ab") : nullptr;
10913                    }();
10914                    static const int32_t logpos_extra = [] {
10915                        const char* p = std::getenv("STRATA_LOGPOS_EXTRA");
10916                        return p != nullptr ? (int32_t) std::atoi(p) : (int32_t) 248046;
10917                    }();
10918                    if (logpos != nullptr && !ver.window_logprobs(nxt.data(), T, q, logpos_extra, logpos, e))
10919                        return false;
10920                    if (!ver.commit(T, e) || (use_mtp && !mtp.prefill(ver.final_R_all(), nxt.data(), T, q, e))) return false;
10921                    if (use_df2) {
10922                        if (!df2.context(ver.tap_dev(), T, q, e)) return false;
10923                        df2.note_rows(win.data(), T, q);
10924                    }
10925                    q += T;
10926                    pp_reached = q;   // #471
10927                }
10928                // the batched prompt path (other streams), checkpoints and snapshots may follow: the last commit first
10929                if (!ver.wait_commit(e)) return false;
10930                const 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,
10932                            ms > 0.0 ? 1000.0 * (double) (b - pp_from) / ms : 0.0);
10933                strata::core::progress_beat();
10934                std::fflush(stdout);
10935                return 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)
10944            auto refill_issue = [&](PfPart& p, std::string& e) -> bool {
10945                tr("refill start", (long long) p.lent.size());
10946                const strata::core::OnDevice on(p.dev);
10947                size_t queued = 0;
10948                for (const auto& [i, slot] : p.lent) {   // D-4: queued, one wait (STRATA_REFILL_BLOCKING=1: each)
10949                    const uint8_t* b = srcp->blob(i / g.n_expert, i % g.n_expert);
10950                    const int64_t nb = (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(i / g.n_expert);
10951                    if (b == nullptr || !(refill_blocking() ? p.cache->fill_slot_blocking(slot, b, e, nb)
10952                                                            : p.cache->fill_slot_queued(slot, b, e, nb)))
10953                        return false;
10954                    host_res[(size_t) i] = slot;
10955                    // SYCL port: drain before GgufExpertSource's 512-buffer blob ring can wrap onto a queued copy
10956                    if (!refill_blocking() && ++queued % 256 == 0 && !p.cache->sync_queued(e)) return false;
10957                }
10958                return true;
10959            };
10960            auto refill_wait = [&](PfPart& p, std::string& e) -> bool {
10961                const strata::core::OnDevice on(p.dev);
10962                if (!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.
10965                for (const auto& [i, slot] : p.lent)
10966                    srcp->release(i / g.n_expert, i % g.n_expert);
10967#endif
10968                p.lent.clear();
10969                p.lent_chunk = 0;
10970                return true;
10971            };
10972            auto refill_one = [&](PfPart& p, std::string& e) -> bool {
10973                if (p.lent.empty()) return true;
10974                return 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.
10979            static const bool refill_serial = std::getenv("STRATA_REFILL_SERIAL") != nullptr;
10980            auto refill = [&](std::string& e) -> bool {
10981                const auto t_rf = Clock::now();
10982                int64_t n_lent = 0, n_parts = 0;
10983                for (PfPart& p : pf_parts)
10984                    if (!p.lent.empty()) { n_lent += (int64_t) p.lent.size(); ++n_parts; }
10985                if (n_parts > 1 && !refill_serial) {
10986                    for (PfPart& p : pf_parts)
10987                        if (!p.lent.empty() && !refill_issue(p, e)) return false;
10988                    for (PfPart& p : pf_parts)
10989                        if (!p.lent.empty() && !refill_wait(p, e)) return false;
10990                } else {
10991                    for (PfPart& p : pf_parts)
10992                        if (!p.lent.empty() && !refill_one(p, e)) return false;
10993                }
10994                if (n_parts > 0) res_upload();
10995                if (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                }
11001                return 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
11006            auto lend = [&](int64_t tokens, std::string& e) -> bool {
11007                if (pf_parts.empty()) return true;                     // its own buffers: nothing to lend
11008                const 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
11011                const 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)
11013                const int64_t want = split_small > 0 && tokens <= split_small_max ? std::min(want_full, split_small)
11014                                                                                 : want_full;
11015                if (want <= 0) {
11016                    e = "prefill: cannot lend buffers for an empty request segment";
11017                    return false;
11018                }
11019                bool any = false;
11020                for (PfPart& p : pf_parts) {
11021                    if (p.first < 0) continue;
11022                    if (!p.lent.empty()) {
11023                        if (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
11027                        if (!refill_one(p, e)) return false;
11028                    }
11029                    const strata::core::OnDevice on(p.dev);
11030                    const int32_t first = std::max<int32_t>(p.first, (int32_t) (p.cache->slots() - part_slots(p, want)));
11031                    if (want != p.sp->chunk() || first != p.first_now) {
11032                        if (!p.sp->relayout(want, p.cache->device_slot(first), part_bytes(p, first), e)) return false;
11033                        p.first_now = first;
11034                    }
11035                    for (int64_t l = p.lb; l < p.le; ++l)              // THIS participant's layers only
11036                        for (int64_t ex = 0; ex < g.n_expert; ++ex) {
11037                            const size_t i = (size_t) (l * g.n_expert + ex);
11038                            if (host_res[i] >= first) {
11039                                p.lent.emplace_back((int32_t) i, host_res[i]);
11040                                host_res[i] = strata::core::kNotResident;
11041                                any = true;
11042                            }
11043                        }
11044                    p.lent_chunk = want;
11045                }
11046                if (any) res_upload();
11047                if (trace) {
11048                    int64_t n_lent = 0;
11049                    for (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                }
11054                return 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.
11061            static const double decode_share = [] {
11062                const char* v = std::getenv("STRATA_BATCH_DECODE_SHARE");
11063                return v != nullptr ? std::max(0.0, std::atof(v)) : 0.5;
11064            }();
11065            bool batch_fatal = false;
11066            int64_t il_parts = 0;   // the slots' windows run between this prompt's chunks
11067            double il_ms = 0;
11068            int64_t yielded_at = -1;   // BYIELD: the read stopped here and its slot holds it
11069            int 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.
11074            auto 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)
11076                if (o.batch <= 0 || piped || (!stages.empty() && !batch_on())) {
11077                    b60_layouts.packed(false);
11078                    const bool ok=sp.run(ids.data()+a0,b0-a0,a0,e);
11079                    b60_layouts.packed(true);
11080                    return ok;
11081                }
11082                const int64_t C = std::max<int64_t>(sp.chunk(), 1);
11083                for (int64_t q = a0; q < b0;) {
11084                    const int64_t r = std::min(b0, q + C);
11085                    const auto tq = Clock::now();
11086                    if (!sp.run(ids.data() + q, r - q, q, e)) return false;
11087                    q = r;
11088                    if (q >= b0) continue;
11089                    int 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);
11092                        for (auto it = in_lines.begin(); it != in_lines.end();) {
11093                            if (it->rfind("BSTOP ", 0) == 0) {
11094                                const int b = std::atoi(it->c_str() + 6);
11095                                if (b >= 0 && b < (int) bs.size()) bs[(size_t) b].stop = true;
11096                                it = in_lines.erase(it);
11097                            } else if (it->rfind("BYIELD ", 0) == 0) {
11098                                ys = std::atoi(it->c_str() + 7);
11099                                it = in_lines.erase(it);
11100                            } else {
11101                                ++it;
11102                            }
11103                        }
11104                    }
11105                    if (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
11108                        const 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 &&
11110                                         b0 - q > std::max<int64_t>(C, o.short_read);
11111                        std::string ye;
11112                        const auto ty = Clock::now();
11113                        std::vector<int32_t> pre(ids.begin(), ids.begin() + q);
11114                        if (can) park_slot(ys);   // the conversation the slot holds, before this read overwrites it
11115                        if (can && copy_to_slot(ys, pre, ye)) {
11116                            BSlot& sl = bs[(size_t) ys];
11117                            sl = BSlot{};
11118                            sl.ids = std::move(pre);
11119                            sl.cached = true;
11120                            sl.partial = true;
11121                            sl.partial_from0 = read_from == 0 || resumed_from0;
11122                            sl.cvec = cvec_cached;
11123                            for (const ConvCheckpoint& c : checks)   // the root / periodic checkpoints of this read
11124                                if ((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; }))
11126                                    sl.checks.push_back(c);
11127                            yielded_at = q;
11128                            yielded_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());
11132                            e = "yield";
11133                            return false;
11134                        }
11135                        if (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                    }
11139                    if (decode_share <= 0.0 || !batch_on()) continue;
11140                    const double budget = decode_share * std::chrono::duration<double, std::milli>(Clock::now() - tq).count();
11141                    const auto td = Clock::now();
11142                    do {
11143                        if (!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;
11146                    il_ms += std::chrono::duration<double, std::milli>(Clock::now() - td).count();
11147                    if (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                }
11153                return true;
11154            };
11155            apply_pending(true);
11156            if (!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");
11158                return 1;
11159            }
11160            // per-request sampling for the verify window's head (greedy when temperature is absent)
11161            strata::kernels::SamplerParams req_sp;
11162            req_sp.greedy = req_temperature <= 0.0f;
11163            req_sp.temperature = req_temperature;
11164            req_sp.top_p = req_top_p;
11165            req_sp.top_k = req_top_k;
11166            req_sp.seed = req_seed ? req_seed
11167                                   : (unsigned long long) std::chrono::steady_clock::now().time_since_epoch().count();
11168            req_sp.min_p = std::clamp(req_min_p, 0.0f, 1.0f);
11169            req_sp.penalty_last_n = std::max(req_penalty_last_n, 0);
11170            req_sp.penalty_repeat = req_penalty_repeat;
11171            req_sp.penalty_freq = req_penalty_freq;
11172            req_sp.penalty_present = req_penalty_present;
11173            req_sp.counter = 0;
11174            ver.set_sampling(req_sp);
11175            if (pipe) ver_b.set_sampling(req_sp);   // (reaches the later stage's odd verifier)
11176            if (use_mtp) mtp.set_draft_sampling(req_sp);   // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise)
11177            drive.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
11179            for (int st = 0; st < split_drive.n; ++st)
11180                split_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);
11182            if (pipe) for (int st = 0; st < split_drive.n; ++st) split_drive_b.pcie_num[st] = split_drive.pcie_num[st];
11183            const 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.
11188            static const bool pen_prompt = strata::kernels::penalty_counts_prompt(std::getenv("STRATA_PENALTY_PROMPT"));
11189            ver.set_history(hist_n > 0 ? d_hist : nullptr, hist_n);
11190            if (pipe) ver_b.set_history(hist_n > 0 ? d_hist : nullptr, hist_n);
11191            bool cancelled = false;
11192            tr("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.
11198            int64_t turn_at = -1;
11199            if (o.prompt_cache > 0 && o.turn_token >= 0)
11200                for (int64_t i = n - 1; i > resume; --i)
11201                    if (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
11205            if (turn_at > 0 && o.tail_role_token >= 0)
11206                for (int64_t i = turn_at - 1; i > resume; --i)
11207                    if (ids[(size_t) i] == o.turn_token) {
11208                        if (ids[(size_t) i + 1] == o.tail_role_token) turn_at = i;
11209                        break;
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).
11216            const int64_t last_turn = turn_at;   // ckpt=0 drops the split there, the root is still looked for before it
11217            if (!req_ckpt) turn_at = -1;
11218            int64_t root_at = -1;
11219            if (o.prompt_cache > 0 && o.turn_token >= 0 && o.prompt_cache_root > 0 && (read_from == 0 || resumed_from0))
11220                for (int64_t i = 1; i < last_turn; ++i)
11221                    if (ids[(size_t) i] == o.turn_token) {
11222                        if (i >= o.prompt_cache_root) root_at = i;
11223                        break;
11224                    }
11225            static const bool message_checkpoint = [] {
11226                const char* e = std::getenv("STRATA_CACHE_MESSAGE_BOUNDARY");
11227                return e != nullptr && std::atoi(e) != 0;
11228            }();
11229            // Only add a snapshot; the existing token and image checks still decide reuse.
11230            const 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;
11232            int64_t at = read_from;
11233            for (const int64_t to : {reread_to, root_at, message_at, turn_at, n - 1}) {
11234                if (to <= at) continue;
11235                err.clear();
11236                const bool win = windows_ok(at, to);
11237                if (win && !refill(err)) {
11238                    std::printf("ERR refilling a lent slot failed: %s\n", err.c_str());
11239                    return 1;
11240                }
11241                if (!win && !lend(to - at, err)) {
11242                    std::printf("ERR lending the prompt path its slots failed: %s\n", err.c_str());
11243                    return 1;
11244                }
11245                const auto tsp = Clock::now();
11246                const bool sp_ok = win ? read_windows(at, to, err) : read_part(at, to, err);
11247                if (trace) {
11248                    std::fprintf(stderr, "strata trace: read %lld tokens (%s) in %.1f ms\n", (long long) (to - at),
11249                                 win ? "windows" : "batched",
11250                                 std::chrono::duration<double, std::milli>(Clock::now() - tsp).count());
11251                    std::fflush(stderr);
11252                }
11253                if (!sp_ok) {
11254                    if (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                        /*
11260                        DPCT1010: SYCL uses exceptions to report errors and
11261                        does not use the error codes. The cudaPeekAtLastError
11262                        function call was replaced with 0. You need to rewrite
11263                        this code.
11264                        */
11265                        if (0 != 0) {
11266                            std::fflush(stdout);
11267                            std::fflush(stderr);
11268                            std::_Exit(1);
11269                        }
11270                        return 1;
11271                    }
11272                    cancelled = true;   // stopped while reading the prompt: refill the lent slots below, then DONE cancel
11273                    break;
11274                }
11275                at = to;
11276                if ((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
11278                    if (!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());
11280                        return 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                }
11285                if (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            }
11289            if (!refill(err)) {
11290                std::printf("ERR refilling a lent slot failed: %s\n", err.c_str());
11291                return 1;
11292            }
11293            tr("prompt done (slots refilled)");
11294            if (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);
11297            prompt_trace.finish();
11298            const 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
11302            int64_t p = n - 1;
11303            int32_t x = (int32_t) ids[(size_t) (n - 1)];
11304            // (the drafter writes max_t - 1 drafts: 8 rows with --pipeline-windows 2)
11305            const 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);
11309            const bool sfx_on = o.suffix_draft > 0 || o.lookup_chain > 0;
11310            if (sfx_on) {
11311                sfx.reset();
11312                for (int64_t t : ids) sfx.append((int32_t) t);
11313            }
11314            if (o.lookup_chain > 0) {
11315                extra_sources_reset();
11316                for (int64_t t : ids) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); }
11317            }
11318            bool first_window = true;
11319            int64_t produced_n = 0, sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0;
11320            int64_t chain_windows = 0, chain_drafts = 0, chain_ok = 0;   // --lookup-chain's own counts
11321            int64_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);
11324            static const bool chain_fixed = std::getenv("STRATA_LOOKUP_CHAIN_FIXED") != nullptr;   // no policy gate
11325            int64_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;
11328            consumed.reserve((size_t) (n + max_new + S));
11329            for (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`.
11332            size_t pen_gen0 = strata::kernels::penalty_window_from(consumed.size(), pen_prompt);
11333            if (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
11334            const char* finish = "length";
11335            const 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)
11339            static const bool dec_timing = std::getenv("STRATA_DECODE_TIMING") != nullptr;
11340            struct DecSnap {
11341                double wait, pool, host, plan, actq, jobs, run;
11342                int64_t misses, entries, hits, pcie;
11343            };
11344            auto dec_snap = [&]() {
11345                return DecSnap{ver.ms_wait, ver.ms_pool, ver.ms_host, drive.d.ms_plan, drive.d.ms_actq, drive.d.ms_jobs,
11346                               drive.d.ms_run, drive.d.multi_misses, drive.d.multi_entries, drive.d.cache_hits,
11347                               drive.d.pcie_experts};
11348            };
11349            const DecSnap ds0 = dec_snap();
11350            double dt_run = 0, dt_commit = 0, dt_draft = 0;
11351            int64_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;
11357            if (const char* fp = std::getenv("STRATA_FOLLOW")) {
11358                if (std::FILE* ff = std::fopen(fp, "r")) {
11359                    long long v;
11360                    while (std::fscanf(ff, "%lld", &v) == 1) fol.push_back((int32_t) v);
11361                    std::fclose(ff);
11362                    std::remove(fp);
11363                }
11364            }
11365            static std::FILE* fol_lp = [] {
11366                const char* p = std::getenv("STRATA_FOLLOW_LOGPOS");
11367                return p != nullptr ? std::fopen(p, "ab") : nullptr;
11368            }();
11369            const int64_t decode_hits0 = drive.d.cache_hits;
11370            pcie_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)
11372            const int64_t ram0 = src.ram_reads(), files0 = src.file_reads();
11373            const uint64_t file_bytes0 = src.file_read_bytes();
11374            const int64_t decode_look0 = drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused;
11375            const int64_t offload0 = drive.d.offload_entries;   // #588
11376            if (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).
11385            bool pl_ran = false;
11386            const bool pl_want = pipe && pl_pw >= 2 && pl_snap2[0] != nullptr;
11387            const char* pl_serial = !pl_want ? nullptr
11388                                  : hist_n > 0 ? "repetition penalties (penalty_last_n)"
11389                                  : mtp.coupled() ? "coupled draft sampling" : nullptr;
11390            if (pl_serial != nullptr) {   // said once per reason
11391                static std::set<std::string> said;
11392                if (said.insert(pl_serial).second)
11393                    std::fprintf(stderr, "strata serve: --pipeline-windows: a request with %s decodes serially\n",
11394                                 pl_serial);
11395            }
11396            if (pl_want && pl_serial == nullptr && !cancelled && produced_n < max_new) {
11397                pl_ran = true;
11398                if (!pl_prepare(err)) {
11399                    std::printf("ERR %s\n", err.c_str());
11400                    return 1;
11401                }
11402                struct PW {
11403                    int T = 0, seq = 0;
11404                    int64_t p = 0;
11405                    int32_t tok[8] = {};
11406                    float prob[8] = {};    // prob[i]: the drafter's probability of tok[i + 1]
11407                    float p_on = 0.0f;     // the chain's estimate that the window before is accepted whole, tok[0] its bonus
11408                    bool ready = false, launched = false, finished = false, committed = false, s1 = false, s1_done = false;
11409                    bool spec = false;     // launched speculatively (behind the window before, ahead of its verdict)
11410                    bool made = false;     // made from a chain (its outcome can be scored even when the gate held it)
11411                    bool sfx = false;      // a lookup window (the suffix drafter's drafts)
11412                    int sfx_match = 0;
11413                };
11414                auto V0 = [&](const PW& w) -> strata::core::Verifier& { return *PV[0][w.seq & 1]; };
11415                auto V1 = [&](const PW& w) -> strata::core::Verifier& { return *PV[1][w.seq & 1]; };
11416                auto SDf = [&](const PW& w) { return (void*) PSD[w.seq & 1]; };
11417                const float theta = pl_theta;
11418                const int force_miss = pl_force_miss;
11419                static const bool pl_log = pipe_dbg_env("STRATA_PIPELINE_LOG") != nullptr;
11420                const 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)
11423                auto snap_take = [&](int seq) -> bool {
11424                    try {
11425                if (!pl_snap_overlap) return true;
11426                    const strata::core::OnDevice on(dev0);
11427                    const int q = seq & 1;
11428                    /*
11429                    DPCT1024: The original code returned the error code
11430                    that was further consumed by the program logic. This
11431                    original code was replaced with 0. You may need to rewrite
11432                    the program logic consuming the error code.
11433                    */
11434                    return DPCT_CHECK_ERROR(
11435                               dpct::sync_barrier(pl_snap_pre[q], s0)) == 0 &&
11436                           DPCT_CHECK_ERROR(
11437                               pl_snap_stream->ext_oneapi_submit_barrier(
11438                                   {*pl_snap_pre[q]})) == 0 &&
11439                           /*
11440                           DPCT1124: cudaMemcpyAsync is migrated to
11441                           asynchronous memcpy API. While the origin API might
11442                           be synchronous, it depends on the type of operand
11443                           memory, so you may need to call wait() on event
11444                           return by memcpy API to ensure synchronization
11445                           behavior.
11446                           */
11447                           DPCT_CHECK_ERROR(pl_snap_stream->memcpy(
11448                               pl_snap2[q], ss.gdn_state, pl_snap_bytes)) ==
11449                               0 &&
11450                           /*
11451                           DPCT1024: The original code returned the error
11452                           code that was further consumed by the program logic.
11453                           This original code was replaced with 0. You may need
11454                           to rewrite the program logic consuming the error
11455                           code.
11456                           */
11457                           DPCT_CHECK_ERROR(dpct::sync_barrier(
11458                               pl_snap_ev[q], pl_snap_stream)) == 0 &&
11459                           (DPCT_CHECK_ERROR(
11460                                (pl_snap_stream->ext_oneapi_empty())),
11461                            true);
11462                }
11463                catch (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                };
11470                PW A, B, D;              // A: the oldest window not verified; B: the next; D: a wrong speculative window
11471                bool doomed = false;     // D still runs: when it finishes, stage 0 goes back to undo_w's real commit
11472                PW undo_w;
11473                int undo_keep = 0;
11474                int32_t undo_ple[2] = {-1, -1};
11475                int chain_kind = 0;      // 1: after an on-path verdict (A's drafts forced); 2: fresh (A's drafts from it)
11476                bool early_used = false;
11477                bool b_done = false;     // B has been made from the chain in flight
11478                int chain_n = 0;
11479                int64_t pl_spec = 0, pl_on = 0, pl_undo = 0, pl_gate = 0, pl_fm = 0;
11480                std::vector<int32_t> outp(8, 0);
11481                bool ending = false;
11482                A.T = 1;
11483                A.p = p;
11484                A.tok[0] = x;
11485                A.ready = true;
11486                drive.d.layers = 0;
11487                drive.d.experts = 0;
11488                drive.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};
11493                bool 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
11496                auto 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);
11500                    if (pl_adapt_thr.joinable()) pl_adapt_thr.join();
11501                    std::printf("ERR %s\n", m.c_str());
11502                    std::fflush(stdout);
11503                    return 1;
11504                };
11505                // STRATA_PIPELINE_TRACE=<file>: every event of the loop with its time (appended per request)
11506                static const char* pl_trace_path = pipe_dbg_env("STRATA_PIPELINE_TRACE");
11507                std::string pl_trace;
11508                const Clock::time_point pl_tr0 = Clock::now();
11509                auto tre = [&](const char* ev, int seq, int x0 = 0, int x1 = 0) {
11510                    if (pl_trace_path == nullptr) return;
11511                    char 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);
11514                    pl_trace += b;
11515                };
11516                auto pump0 = [&](PW& w) -> bool {
11517                    if (!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.
11522                    static const bool doom_skip = [] { const char* e = pipe_dbg_env("STRATA_PIPELINE_DOOM_SKIP"); return e == nullptr || std::atoi(e) != 0; }();
11523                    const bool skip = doom_skip && doomed && &w == &D;
11524                    if (v.service(skip ? nullptr : &drive_pool_split, SDf(w), err) < 0) return false;
11525                    if (v.done(err)) {
11526                        if (!v.pl_finish(nullptr, err)) return false;
11527                        w.finished = true;
11528                        tre("F0", w.seq, w.T, w.spec);
11529                    }
11530                    return err.empty();
11531                };
11532                // the serial loop's window size over the chain's outputs from index `from` (`avail` of them)
11533                auto t_rule = [&](const float* pr, int from, int avail) {
11534                    int T = S_mtp;
11535                    if (req_spec_min_p > 0.0) {
11536                        T = 1;
11537                        while (T < S_mtp && from + T - 1 < avail && pr[from + T - 1] >= (float) req_spec_min_p) ++T;
11538                    }
11539                    return 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
11542                auto make_b = [&](const int32_t* oc, const float* op, int base, int avail, float pa) {
11543                    B = PW{};
11544                    if (base >= avail) return;
11545                    B.seq = A.seq + 1;
11546                    B.p = A.p + A.T;
11547                    B.tok[0] = oc[base];
11548                    B.T = t_rule(op, base + 1, avail);
11549                    for (int i = 1; i < B.T; ++i) {
11550                        B.tok[i] = oc[base + i];
11551                        B.prob[i - 1] = op[base + i];
11552                    }
11553                    B.p_on = pa * op[base];
11554                    if (force_miss > 0 && ++pl_fm % force_miss == 0) B.tok[0] = B.tok[0] == 0 ? 1 : 0;
11555                    B.ready = true;
11556                    B.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},
11560                                exch_ev[2] = {nullptr, nullptr};
11561                {
11562                    const strata::core::OnDevice on0(dev0);
11563                    fence_ev[0] = new sycl::event();
11564                    exch_ev[0] = new sycl::event();
11565                }
11566                {
11567                    const strata::core::OnDevice on1(stages[0]->dev);
11568                    fence_ev[1] = new sycl::event();
11569                    exch_ev[1] = new sycl::event();
11570                }
11571                auto stage_record = [&](dpct::event_ptr *ev) {
11572                    try {
11573                {
11574                        const strata::core::OnDevice on(dev0);
11575                        dpct::sync_barrier(ev[0], s0);
11576                        (void)DPCT_CHECK_ERROR((s0->ext_oneapi_empty()));
11577                    }
11578                    const 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                }
11583                catch (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                };
11590                auto stage_passed = [&](dpct::event_ptr *ev) {
11591                    try {
11592                return dpct::sycl_event_query(ev[0]) != 1 &&
11593                       dpct::sycl_event_query(ev[1]) != 1;
11594                }
11595                catch (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.
11604                adapt_fence = [&]() {
11605                    stage_record(fence_ev);
11606                    while (!stage_passed(fence_ev)) std::this_thread::yield();
11607                };
11608                src.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.
11613                bool exch_wait = false;
11614                std::vector<int32_t> pl_landed;
11615                auto pl_release = [&]() {
11616                    unpin_blobs(pin_live);
11617                    src.commit_exchanges();
11618                    for (const int32_t i : pl_landed) srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert);
11619                    pl_landed.clear();
11620                    exch_wait = false;
11621                };
11622                auto pl_apply = [&]() {
11623                    try {
11624                if (exch_wait) {
11625                        if (stage_passed(exch_ev)) pl_release();
11626                        return;
11627                    }
11628                    if (pending.empty() ||
11629                        adapt_ev->get_info<
11630                            sycl::info::event::command_execution_status>() !=
11631                            sycl::info::event_command_status::complete) return;
11632                    for (auto& st : stages)
11633                        if (st->adapt_live &&
11634                            (st->adapt_ev)
11635                                    ->get_info<
11636                                        sycl::info::event::
11637                                            command_execution_status>() !=
11638                                sycl::info::event_command_status::
11639                                    complete) return;
11640                    for (auto& st : stages) st->adapt_live = false;
11641                    for (const auto& [i, slot] : pending) {
11642                        host_res[(size_t) i] = slot;
11643                        pl_landed.push_back(i);
11644                    }
11645                    pending.clear();
11646                    pending_age = 0;
11647                    res_upload();
11648                    stage_record(exch_ev);
11649                    exch_wait = true;
11650                }
11651                catch (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                };
11658                auto pl_adapt = [&]() -> bool {
11659                    if (pl_adapt_thr.joinable() && pl_adapt_done.load()) {
11660                        pl_adapt_thr.join();
11661                        if (!pl_adapt_ok) return false;
11662                    }
11663                    if (pl_adapt_thr.joinable()) return true;   // still adapting
11664                    pl_apply();
11665                    if (!drive.d.usage.empty() && o.adapt_every > 0 && (rounds % o.adapt_every) == 0 && pending.empty() &&
11666                        !exch_wait) {
11667                        pl_adapt_done = false;
11668                        pl_adapt_thr = std::thread([&] { pl_adapt_ok = adapt(); pl_adapt_done = true; });
11669                    }
11670                    return 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)
11678                static const float pl_lookup_pon = [] {
11679                    const char* v = pipe_dbg_env("STRATA_PIPELINE_LOOKUP_PON");
11680                    return v ? (float) std::atof(v) : 0.75f;
11681                }();
11682                auto pick_lookup = [&](PW& w, const int32_t* chain0) {
11683                    if (o.suffix_draft <= 0 || w.seq == 0) return;
11684                    const int k = sfx.propose(2 * S - 1, pl_sbuf.data());
11685                    const int match = sfx.last_match();
11686                    if (k <= 0 || pl_sbuf[0] != chain0[0]) return;
11687                    const strata::spec::DraftPolicy::Pick pk = policy.choose(w.T, std::min(k, S - 1), match);
11688                    if (!pk.lookup) return;
11689                    w.T = pk.t;
11690                    for (int i = 1; i < w.T; ++i) {
11691                        w.tok[i] = pl_sbuf[(size_t) i - 1];
11692                        w.prob[i - 1] = 1.0f;
11693                    }
11694                    w.sfx = true;
11695                    w.sfx_match = match;
11696                    const int rest = k - (w.T - 1);   // lookup tokens past w: B's row 0 (w's bonus guess) and its drafts
11697                    if (&w == &A && rest >= 1 && pl_lookup_pon > 0.0f && !b_done) {
11698                        B = PW{};
11699                        B.seq = A.seq + 1;
11700                        B.p = A.p + A.T;
11701                        B.T = std::min(S, rest);
11702                        for (int i = 0; i < B.T; ++i) B.tok[i] = pl_sbuf[(size_t) (A.T - 1 + i)];
11703                        for (int i = 1; i < B.T; ++i) B.prob[i - 1] = 1.0f;
11704                        B.p_on = pl_lookup_pon;
11705                        B.ready = true;
11706                        B.made = true;
11707                        b_done = true;   // the chain in flight makes no B for this A
11708                        tre("CD", A.seq + 1, 3, (int) (1000.0f * B.p_on));
11709                    }
11710                };
11711                const Clock::time_point pl_t0 = Clock::now();
11712                for (int st = 0; st < 2; ++st)
11713                    for (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);
11715                auto pw_bits = [](const PW& w) {
11716                    return (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
11721                double cls_ms[2] = {0, 0}, cls_tok[2] = {0, 0}, cls_n[2] = {0, 0};
11722                int64_t cal_n[10] = {}, cal_on[10] = {};   // per p_on decile: windows scored, on the path
11723                double last_verdict = 0.0;
11724                int64_t pl_disagree = 0, pl_late = 0;
11725                static const bool pl_prestage = [] {   // STRATA_PIPELINE_PRESTAGE=0: B staged at its launch
11726                    const char* v = pipe_dbg_env("STRATA_PIPELINE_PRESTAGE");
11727                    return v == nullptr || std::atoi(v) != 0;
11728                }();
11729                static const bool pl_agree = [] {   // STRATA_PIPELINE_AGREE=0: only the old chain's probabilities
11730                    const char* v = pipe_dbg_env("STRATA_PIPELINE_AGREE");
11731                    return 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.
11735                const 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);
11737                auto ms_now = [&]() { return std::chrono::duration<double, std::milli>(Clock::now() - pl_t0).count(); };
11738                while (true) {
11739                    g_pl_diag.iters.fetch_add(1, std::memory_order_relaxed);
11740                    g_pl_diag.a_seq.store(A.seq, std::memory_order_relaxed);
11741                    g_pl_diag.a_bits.store(pw_bits(A), std::memory_order_relaxed);
11742                    g_pl_diag.b_bits.store(pw_bits(B), std::memory_order_relaxed);
11743                    g_pl_diag.d_bits.store(pw_bits(D), std::memory_order_relaxed);
11744                    g_pl_diag.chain_kind.store(chain_kind, std::memory_order_relaxed);
11745                    g_pl_diag.chain_live.store(mtp.chain_live() ? 1 : 0, std::memory_order_relaxed);
11746                    g_pl_diag.doomed.store(doomed ? 1 : 0, std::memory_order_relaxed);
11747                    g_pl_diag.ending.store(ending ? 1 : 0, std::memory_order_relaxed);
11748                    // ---- every window in flight served
11749                    if ((doomed && !pump0(D)) || !pump0(A) || !pump0(B)) return die(err);
11750                    if (A.s1 && !A.s1_done) {
11751                        strata::core::Verifier& v = V1(A);
11752                        if (v.service(&drive_pool_split, SDf(A), err) < 0) return die(err);
11753                        if (v.done(err)) {
11754                            if (!v.pl_finish(outp.data(), err)) return die(err);
11755                            A.s1_done = true;
11756                            tre("F1", A.seq, A.T);
11757                        } else if (!err.empty()) return die(err);
11758                    }
11759                    if (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
11761                    if (doomed && D.finished) {
11762                        {
11763                            const strata::core::OnDevice on(dev0);
11764                            /*
11765                            DPCT1124: cudaMemcpyAsync is migrated to
11766                            asynchronous memcpy API. While the origin API might
11767                            be synchronous, it depends on the type of operand
11768                            memory, so you may need to call wait() on event
11769                            return by memcpy API to ensure synchronization
11770                            behavior.
11771                            */
11772                            if (DPCT_CHECK_ERROR(s0->memcpy(
11773                                    ss.gdn_state,
11774                                    pl_snap2[pl_snap_overlap ? (undo_w.seq & 1)
11775                                                             : 0],
11776                                    pl_snap_bytes)) != 0)
11777                                return die("restoring the GDN snapshot failed");
11778                        }
11779                        ss.ple_prev[0] = undo_ple[0];
11780                        ss.ple_prev[1] = undo_ple[1];
11781                        if (!V0(undo_w).pl_commit_async(undo_keep, err)) return die(err);
11782                        doomed = false;
11783                        ++pl_undo;
11784                        tre("U", undo_w.seq, undo_keep);
11785                    }
11786                    if (ending) {
11787                        if (!doomed) break;
11788                        continue;
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
11793                    if (chain_kind != 0) {
11794                        const int k_ready = mtp.chain_outputs_ready(err);
11795                        if (k_ready < 0) return die(err);
11796                        if (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
11799                            const int k = k_ready;
11800                            bool decided = k >= S_mtp - 1;
11801                            if (!decided && req_spec_min_p > 0.0)
11802                                for (int j = 0; j < k; ++j)
11803                                    if (mtp.chain_prob()[j] < (float) req_spec_min_p) { decided = true; break; }
11804                            if (decided) {
11805                                A.T = t_rule(mtp.chain_prob(), 0, std::min(k, S_mtp - 1));
11806                                for (int i = 1; i < A.T; ++i) {
11807                                    A.tok[i] = mtp.chain_tok()[i - 1];
11808                                    A.prob[i - 1] = mtp.chain_prob()[i - 1];
11809                                }
11810                                pick_lookup(A, mtp.chain_tok());
11811                                A.ready = true;
11812                                early_used = true;
11813                                tre("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.
11821                        if (auto* ds = strata::private_demand::get(&mtp)) {
11822                            const int k = k_ready;
11823                            bool final = k >= ds->limit, dead_b = false;
11824                            if (k > 0 && (chain_kind == 1 || early_used) && !A.sfx) {
11825                                const int base = A.T - 1;
11826                                const float* op = mtp.chain_prob();
11827                                const int32_t* oc = mtp.chain_tok();
11828                                float pa = 1.0f;
11829                                bool finite = true, agree = true;
11830                                if (chain_kind == 1) {
11831                                    for (int j = 0; j < std::min(k, base); ++j) {
11832                                        finite = finite && std::isfinite(op[j]) && op[j] >= 0.0f && op[j] <= 1.0f;
11833                                        agree = agree && oc[j] == A.tok[j + 1];
11834                                        pa *= op[j];
11835                                    }
11836                                } else {
11837                                    for (int j = 0; j < base; ++j) {
11838                                        finite = finite && std::isfinite(A.prob[j]) && A.prob[j] >= 0.0f && A.prob[j] <= 1.0f;
11839                                        pa *= A.prob[j];
11840                                    }
11841                                }
11842                                if (finite && (!agree || pa < theta)) dead_b = true;
11843                                if (finite && k > base && std::isfinite(op[base]) && op[base] >= 0.0f && op[base] <= 1.0f && pa * op[base] < theta)
11844                                    dead_b = true;
11845                                bool size_known = k >= base + S_mtp;
11846                                if (!size_known && k > base + 1 && req_spec_min_p > 0.0)
11847                                    for (int j = base + 1; j < k; ++j)
11848                                        if (op[j] < (float) req_spec_min_p) { size_known = true; break; }
11849                                final = final || dead_b || size_known;
11850                            }
11851                            if (dead_b && !b_done) {
11852                                // Do not fabricate an uncomputed bonus or B
11853                                // calibration record. Such a B cannot launch.
11854                                B = PW{}; b_done = true; ++ds->dead;
11855                            }
11856                            ds->final = final;
11857                            ds->target = final ? ds->submitted : std::min(ds->limit, k + 1);
11858                        }
11859
11860                        const int r = mtp.chain_poll(err);
11861                        if (r < 0) return die(err);
11862                        const auto* demand_state = strata::private_demand::get(&mtp);
11863                        const int completed_n = demand_state ? demand_state->submitted : chain_n;
11864                        const int k = r == 1 ? completed_n : k_ready;
11865                        // Optional functional evidence, excluded from timing.
11866                        static const bool demand_detail = std::getenv("STRATA_PRIVATE_MTP_DEMAND_LOG") != nullptr;
11867                        if (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\":[",
11869                                demand_state->chains, A.seq, chain_kind, chain_n, k, A.T, (long long) A.p, A.sfx ? "true" : "false");
11870                            for (int j = 0; j < A.T; ++j) std::fprintf(stderr, "%s%d", j ? "," : "", A.tok[j]);
11871                            std::fprintf(stderr, "],\"tok\":[");
11872                            for (int j = 0; j < k; ++j) std::fprintf(stderr, "%s%d", j ? "," : "", mtp.chain_tok()[j]);
11873                            std::fprintf(stderr, "],\"prob\":[");
11874                            for (int j = 0; j < k; ++j) std::fprintf(stderr, "%s%.9g", j ? "," : "", double(mtp.chain_prob()[j]));
11875                            std::fprintf(stderr, "]}\n");
11876                        }
11877
11878                        const int32_t* oc = mtp.chain_tok();
11879                        const float* op = mtp.chain_prob();
11880                        if (r == 1 && chain_kind == 2 && !early_used) {
11881                            A.T = t_rule(op, 0, std::min(chain_n, S_mtp - 1));
11882                            for (int i = 1; i < A.T; ++i) {
11883                                A.tok[i] = oc[i - 1];
11884                                A.prob[i - 1] = op[i - 1];
11885                            }
11886                            pick_lookup(A, oc);
11887                            A.ready = true;
11888                            early_used = true;
11889                        }
11890                        if (!b_done && (chain_kind == 1 || early_used)) {
11891                            const int base = A.T - 1;                    // B's row 0: the guess of A's bonus
11892                            bool decided = r == 1 || k >= base + S_mtp;
11893                            if (!decided && k > base + 1 && req_spec_min_p > 0.0)
11894                                for (int j = base + 1; j < k; ++j)
11895                                    if (op[j] < (float) req_spec_min_p) { decided = true; break; }
11896                            if (decided) {
11897                                float pa = 1.0f;
11898                                if (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
11902                                    bool agree = true;
11903                                    for (int i = 0; i + 1 < A.T; ++i) {
11904                                        if (oc[i] != A.tok[i + 1]) agree = false;
11905                                        pa *= pl_agree ? op[i] : A.prob[i];
11906                                    }
11907                                    if (pl_agree && !agree) { pa = 0.0f; ++pl_disagree; }
11908                                } else {
11909                                    for (int i = 0; i + 1 < A.T; ++i) pa *= A.prob[i];
11910                                }
11911                                if (!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)
11915                                if (B.ready && B.p_on >= theta && pl_prestage && !V0(B).in_flight() && !doomed) {
11916                                    int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]};
11917                                    for (int i = 0; i < A.T; ++i) { prev[0] = prev[1]; prev[1] = A.tok[i]; }
11918                                    if (!V0(B).prestage(B.T, B.tok, B.p, prev, err)) return die(err);
11919                                }
11920                                b_done = true;
11921                                tre("CD", A.seq, chain_kind, (int) (1000.0f * B.p_on));
11922                                if (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                        }
11927                        if (r == 1) chain_kind = 0;
11928                    }
11929                    // ---- stage 0: A (never while a wrong window still holds stage 0's state)
11930                    if (A.ready && !A.launched && !doomed) {
11931                        if (A.p + A.T > o.max_context) { ending = true; continue; }
11932                        if (!snap_take(A.seq)) return die("the GDN snapshot failed");
11933                        if (!V0(A).pl_launch(A.T, A.tok, A.p, err)) return die(err);
11934                        A.launched = true;
11935                        tre("L0", A.seq, A.T, 0);
11936                    }
11937                    // ---- stage 0: B, speculatively, right behind A
11938                    if (B.ready && !B.launched && A.finished && !A.committed && !doomed) {
11939                        if (B.p_on >= theta && B.p + B.T <= o.max_context) {
11940                            {
11941                                const strata::core::OnDevice on(dev0);
11942                                if (pl_snap_overlap
11943                                        ? DPCT_CHECK_ERROR(
11944                                              s0->ext_oneapi_submit_barrier(
11945                                                  {*pl_snap_ev[A.seq & 1]})) !=
11946                                              0
11947                                        /*
11948                                        DPCT1124: cudaMemcpyAsync is
11949                                        migrated to asynchronous memcpy API.
11950                                        While the origin API might be
11951                                        synchronous, it depends on the type of
11952                                        operand memory, so you may need to call
11953                                        wait() on event return by memcpy API to
11954                                        ensure synchronization behavior.
11955                                        */
11956                                        : DPCT_CHECK_ERROR(s0->memcpy(
11957                                              pl_snap2[0], ss.gdn_state,
11958                                              pl_snap_bytes)) != 0)
11959                                    return die("the GDN snapshot failed");
11960                            }
11961                            undo_ple[0] = ss.ple_prev[0];
11962                            undo_ple[1] = ss.ple_prev[1];
11963                            if (!V0(A).pl_commit_async(A.T, err) || !snap_take(B.seq) ||
11964                                !V0(B).pl_launch(B.T, B.tok, B.p, err))
11965                                return die(err.empty() ? std::string("the GDN snapshot failed") : err);
11966                            A.committed = true;
11967                            B.launched = true;
11968                            B.spec = true;
11969                            tre("L0", B.seq, B.T, 1);
11970                            ++pl_spec;
11971                        } else {
11972                            B.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
11977                    if (A.finished && !A.s1 && strata::private_demand::can_enqueue_s1(&mtp)) {
11978                        if (chain_kind == 1 && !B.ready) ++pl_late;   // stage 0 idles until the chain has B
11979                        if (!V1(A).pl_launch(A.T, A.tok, A.p, err)) return die(err);
11980                        A.s1 = true;
11981                        tre("L1", A.seq, A.T);
11982                    }
11983                    // ---- A's verdict
11984                    if (!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.
11988                    while (chain_kind != 0 && mtp.chain_live())
11989                        if (mtp.chain_poll(err) < 0) return die(err);
11990                    if (chain_kind != 0 && !B.launched && !B.made) B = PW{};
11991                    chain_kind = 0;
11992                    int a = 0;
11993                    while (a < A.T - 1 && A.tok[a + 1] == outp[(size_t) a]) ++a;
11994                    if (!V1(A).pl_commit_async(a + 1, err)) return die(err);
11995                    for (int i = 0; i <= a; ++i) consumed.push_back(A.tok[i]);
11996                    draft_offered += A.T - 1;
11997                    draft_accepted += a;
11998                    ++rounds;
11999                    ++dec_windows;
12000                    dec_T += A.T;
12001                    bool eos = false;
12002                    for (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;
12006                        if (o.suffix_draft > 0) sfx.append(outp[(size_t) i]);
12007                        eos = 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);
12010                    if (eos) finish = "stop";
12011                    else if (stop_req.load()) finish = "cancel";
12012                    const bool last = eos || produced_n >= max_new || stop_req.load();
12013                    const bool on = B.launched && a == A.T - 1 && B.tok[0] == outp[(size_t) A.T - 1];
12014                    if (B.made) {   // the gate's calibration: would B have been on the path, by its estimate p_on
12015                        const bool would = a == A.T - 1 && B.tok[0] == outp[(size_t) A.T - 1];
12016                        const int bin = std::min(9, std::max(0, (int) (B.p_on * 10.0f)));
12017                        cal_n[bin] += 1;
12018                        cal_on[bin] += would ? 1 : 0;
12019                    }
12020                    tre("V", A.seq, a, on ? 1 : (B.launched ? -1 : 0));
12021                    {
12022                        const double now = ms_now();
12023                        const int c = A.spec ? 1 : 0;
12024                        if (A.sfx) { ++sfx_windows; sfx_drafts += A.T - 1; sfx_ok += a; }
12025                        if (A.seq > 0 && !last) policy.observe(A.sfx, A.T, a, A.sfx_match, now - last_verdict);
12026                        cls_ms[c] += now - last_verdict;
12027                        cls_tok[c] += a + 1;
12028                        cls_n[c] += 1;
12029                        last_verdict = now;
12030                    }
12031                    if (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,
12033                                     B.launched ? "launched" : B.ready ? "ready" : "none", on ? " ON" : "");
12034                    x = outp[(size_t) a];
12035                    p = 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.
12040                    static const char* pl_dump = std::getenv("STRATA_PIPELINE_DUMP");   // read once
12041                    if (pl_dump != nullptr) {
12042                        const int64_t gdn_floats = g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +
12043                                                   g.ssm_conv_channels * (g.ssm_d_conv - 1);
12044                        const 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
12048                        const size_t n_rec = (size_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
12049                        const size_t n_cnv = (size_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);
12050                        double rec_sum = 0.0, cnv_sum = 0.0;
12051                        uint64_t rec_hash = 1469598103934665603ull, cnv_hash = 1469598103934665603ull;
12052                        for (int64_t l = 0; l < ss.gdn_alloc; ++l) {
12053                            const size_t base = (size_t) l * (size_t) gdn_floats;
12054                            uint64_t rh = 1469598103934665603ull, ch = 1469598103934665603ull;
12055                            for (size_t i = 0; i < n_rec; ++i) {
12056                                uint64_t b = 0;
12057                                std::memcpy(&b, &h[base + i], sizeof(float));
12058                                rh = (rh ^ b) * 1099511628211ull;
12059                                rec_sum += (double) h[base + i];
12060                            }
12061                            for (size_t i = 0; i < n_cnv; ++i) {
12062                                uint64_t b = 0;
12063                                std::memcpy(&b, &h[base + n_rec + i], sizeof(float));
12064                                ch = (ch ^ b) * 1099511628211ull;
12065                                cnv_sum += (double) h[base + n_rec + i];
12066                            }
12067                            rec_hash = (rec_hash ^ rh) * 1099511628211ull;
12068                            cnv_hash = (cnv_hash ^ ch) * 1099511628211ull;
12069                        }
12070                        if (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                    }
12077                    if (!last && !pl_adapt()) return die("an adaptive refill failed");
12078                    if (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
12081                        mtp.set_source_R(V1(A).final_R(0));
12082                        chain_n = std::min(strata::kernels::kVerifyMaxT - 1, B.T + S_mtp - 1);
12083                        if (!mtp.chain_launch(A.T, outp.data(), A.p, a, B.tok + 1, B.T - 1, chain_n, chain_n, err))
12084                            return die(err);
12085                        chain_kind = 1;
12086                        tre("CL", A.seq, 1);
12087                        early_used = false;
12088                        b_done = false;
12089                        A = B;
12090                        B = PW{};
12091                    } else {
12092                        if (B.launched) {   // a wrong guess (or the end): undo once it has finished
12093                            doomed = true;
12094                            D = B;
12095                            undo_w = A;
12096                            undo_keep = a + 1;
12097                        } else if (!A.committed) {
12098                            if (!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)
12102                        B = PW{};
12103                        if (!last) {
12104                            mtp.set_source_R(V1(A).final_R(0));
12105                            chain_n = strata::kernels::kVerifyMaxT - 1;
12106                            if (!mtp.chain_launch(A.T, outp.data(), A.p, a, nullptr, 0, chain_n, chain_n, err))
12107                                return die(err);
12108                            chain_kind = 2;
12109                            tre("CL", A.seq, 2);
12110                            early_used = false;
12111                            b_done = false;
12112                            PW nA;
12113                            nA.seq = A.seq + 1;
12114                            nA.p = A.p + a + 1;
12115                            nA.tok[0] = outp[(size_t) a];
12116                            A = nA;
12117                        }
12118                    }
12119                    if (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);
12124                if (mtp.chain_live() && mtp.chain_outputs_ready(err) < 0) return die(err);
12125                pl_drain();   // nothing in flight: both stages' commits and the drafter have landed
12126                strata::core::diag_pipeline_fn().store(nullptr);
12127                if (pl_adapt_thr.joinable()) pl_adapt_thr.join();   // its copies waited only for finished work
12128                adapt_fence = nullptr;
12129                if (exch_wait) pl_release();   // every window has completed (drained)
12130                for (dpct::event_ptr ev : fence_ev) if (ev)
12131                    dpct::destroy_event(ev);
12132                for (dpct::event_ptr ev : exch_ev) if (ev)
12133                    dpct::destroy_event(ev);
12134                if (pl_trace_path != nullptr && !pl_trace.empty()) {
12135                    if (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
12142                PV[0][0]->absorb_stats(*PV[0][1]);
12143                PV[1][0]->absorb_stats(*PV[1][1]);
12144                if (!pl_adapt_ok) {
12145                    std::printf("ERR an adaptive refill failed\n");
12146                    return 1;
12147                }
12148                while (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.
12153                const char* demand_micro = std::getenv("STRATA_PRIVATE_MTP_DEMAND_MICRO");
12154                if (auto* ds = strata::private_demand::get(&mtp);
12155                    ds && demand_micro && ds->ordinal == std::atoi(demand_micro)) {
12156                    const auto saved = *ds;
12157                    const double old_ms = mtp.ms_draft;
12158                    const int64_t old_rounds = mtp.rounds;
12159                    const int outputs = saved.limit;
12160                    int32_t ref_tok[8] = {}; float ref_prob[8] = {};
12161                    auto run_chain = [&](bool segmented, int take, bool set_reference) {
12162                        ds->enabled = segmented;
12163                        if (!mtp.chain_launch(saved.T, saved.tokens, saved.p, saved.a,
12164                                              saved.force, saved.n_force, outputs, outputs, err)) return false;
12165                        if (segmented) {
12166                            while (mtp.chain_live()) {
12167                                const int ready = mtp.chain_outputs_ready(err);
12168                                if (ready < 0) return false;
12169                                ds->final = ready >= take;
12170                                ds->target = ds->final ? ds->submitted : std::min(take, ready + 1);
12171                                const int rc = mtp.chain_poll(err);
12172                                if (rc < 0) return false;
12173                            }
12174                        } else {
12175                            int rc;
12176                            do { rc = mtp.chain_poll(err); } while (rc == 0);
12177                            if (rc < 0) return false;
12178                        }
12179                        if (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))) {
12184                            err = "private demand micro: token/probability prefix differs"; return false;
12185                        }
12186                        strata::core::progress_beat();  // a real, retired benchmark chain
12187                        return true;
12188                    };
12189                    if (!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.
12192                    for (int k = 1; k <= outputs; ++k)
12193                        if (!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",
12195                                 saved.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.
12198                    for (int arm = 0; arm < 3; ++arm) {
12199                        const bool segmented = arm == 1;
12200                        for (int sample = 0; sample < 3; ++sample) {
12201                            int warm_n = 0; auto start = Clock::now();
12202                            do {
12203                                if (!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);
12206                            int measured_n = 0; start = Clock::now();
12207                            do {
12208                                if (!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);
12211                            const 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",
12213                                         arm, sample, warm_n, measured_n, us);
12214                            std::fflush(stderr);
12215                        }
12216                    }
12217                    *ds = saved; mtp.ms_draft = old_ms;
12218                    mtp.rounds = old_rounds;
12219                }
12220                if (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",
12222                                 ds->chains, ds->requested, ds->actual, ds->continuations, ds->dead,
12223                                 ds->reaction_ns, ds->submit_ns, ds->max_reaction_ns);
12224                strata::private_demand::begin(&mtp, false);
12225                mtp.set_source_R(ver.final_R_all());   // the serial loop's rows again
12226                const double pl_ms = std::chrono::duration<double, std::milli>(Clock::now() - pl_t0).count();
12227                dt_run += pl_ms;
12228                if (dec_timing) {
12229                    auto 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",
12236                                 cls_n[0], avg(cls_ms[0], cls_n[0]), avg(cls_tok[0], cls_n[0]), cls_n[1],
12237                                 avg(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;
12240                    char b[48];
12241                    for (int i = 0; i < 10; ++i)
12242                        if (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]);
12244                            cal += 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)
12251            const int df2_skip_min = strata::spec::df2_lookup_skip_min(0);
12252            bool df2_deferred = false;
12253            int dfr_n = 0;
12254            int64_t dfr_pos = 0;
12255            int32_t dfr_anchor = 0;
12256            auto defer_df2 = [&](int a_) -> bool {
12257                if (!use_df2 || o.suffix_draft <= 0 || df2_skip_min <= 0) return false;
12258                const int ks = sfx.propose(S - 1, sbuf.data());
12259                if (!strata::spec::skip_draft_for_lookup(true, df2_skip_min, ks, sfx.last_match())) return false;
12260                df2_deferred = true; dfr_n = a_ + 1; dfr_pos = p; dfr_anchor = outv[(size_t) a_];
12261                return 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)
12264            auto draft_df2 = [&](int a_) -> bool {
12265                int32_t dd[strata::core::Dflash2Drafter::kDrafts];
12266                float pp[strata::core::Dflash2Drafter::kDrafts];
12267                if (!df2.draft(ver.tap_dev(), a_ + 1, p, outv[(size_t) a_], dd, pp, err)) return false;
12268                for (size_t i = 0; i < drafts.size() && i < (size_t) strata::core::Dflash2Drafter::kDrafts; ++i) { drafts[i] = dd[i]; dprob[i] = pp[i]; }
12269                return true;
12270            };
12271            while (!pl_ran && !cancelled && produced_n < max_new) {
12272                bool dfr_lookup = false;
12273                int dfr_T = 0, dfr_match = 0;
12274                if (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)
12275                    df2_deferred = false;
12276                    const int kd = sfx.propose(S - 1, sbuf.data());
12277                    const int md = sfx.last_match();
12278                    const strata::spec::DraftPolicy::Pick pkd = kd > 0 ? policy.choose(S_mtp, kd, md) : strata::spec::DraftPolicy::Pick{};
12279                    if (kd > 0 && pkd.lookup) {
12280                        dfr_lookup = true; dfr_T = pkd.t; dfr_match = md;
12281                        if (!df2.context(ver.tap_dev(), dfr_n, dfr_pos, err)) { std::printf("ERR %s\n", err.c_str()); return 1; }
12282                    } else {
12283                        int32_t dd[strata::core::Dflash2Drafter::kDrafts];
12284                        float pp[strata::core::Dflash2Drafter::kDrafts];
12285                        if (!df2.draft(ver.tap_dev(), dfr_n, dfr_pos, dfr_anchor, dd, pp, err)) { std::printf("ERR %s\n", err.c_str()); return 1; }
12286                        for (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                }
12289                int 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;
12292                    wr.use_mtp = draft_on; wr.draft_on = draft_on; wr.df2_active = use_df2; wr.spec_cost = false; wr.first_window = first_window;
12293                    wr.chain_rows = 1; wr.cap = S_mtp; wr.start = T; wr.spec_min_p = req_spec_min_p;
12294                    wr.draft_conf = o.draft_conf; wr.dprob = dprob.data();
12295                    T = strata::spec::choose_window(wr);
12296                }
12297                if (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
12300                bool from_sfx = false;
12301                int sfx_match = 0;
12302                if (o.suffix_draft > 0 && !first_window) {
12303                    const int k = sfx.propose(S - 1, sbuf.data());
12304                    sfx_match = sfx.last_match();
12305                    if (k > 0 && (!draft_on || sbuf[0] == drafts[0])) {
12306                        const strata::spec::DraftPolicy::Pick pk = policy.choose(T, k, sfx_match);
12307                        if (pk.lookup) { T = pk.t; from_sfx = true; }
12308                    }
12309                }
12310                if (dfr_lookup) {   // the lookup window chosen before the draft (the draft was skipped)
12311                    sfx.propose(S - 1, sbuf.data());
12312                    T = 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
12315                int chain_n = 0, cm = 0;
12316                if (o.lookup_chain > 0 && !first_window && !from_sfx && T < S) {
12317                    int csrc = -1;
12318                    const int nt = chain_tail(sfx, drafts.data(), T - 1, ctail);
12319                    chain_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,
12321                                                                 cbuf.data(), &cm, &csrc);
12322                    // the policy keeps the chained tokens that pay at this machine's measured window costs
12323                    if (chain_n > 0 && !chain_fixed) {
12324                        double p_mtp = 1.0;
12325                        for (int i = 0; i < T - 1; ++i) p_mtp *= dprob[(size_t) i];
12326                        chain_n = policy.chain(T, p_mtp, chain_n, cm);
12327                    }
12328                }
12329                const int T_mtp = T;
12330                T += chain_n;
12331                const bool timed_round = !first_window;
12332                const Clock::time_point round0 = Clock::now();
12333                if (p + T > o.max_context) break;
12334                window[0] = x;
12335                for (int i = 1; i < T_mtp; ++i) window[(size_t) i] = from_sfx ? sbuf[(size_t) i - 1] : drafts[(size_t) i - 1];
12336                for (int i = 0; i < chain_n; ++i) window[(size_t) (T_mtp + i)] = cbuf[(size_t) i];
12337                drive.d.layers = 0;
12338                drive.d.experts = 0;
12339                drive.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)
12343                if (adapt_nowait()) apply_pending(false);
12344                else if (pending.empty() || ++pending_age >= adapt_lag()) apply_pending(true);
12345                if (!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");
12347                    return 1;
12348                }
12349                if (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,
12355                                                  hist_n, hist_stage.data());
12356                    const 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
12363                if (kvg.on && p + T + 64 > kvg.cells &&
12364                    !kvg_ensure(p + T + 64, [&] {
12365                                                  dpct::get_current_device()
12366                                                      .queues_wait_and_throw();
12367                                                      apply_pending(true); })) {
12368                    std::printf("ERR the K/V cannot grow: no VRAM is left\n");
12369                    return 1;
12370                }
12371                tr("window", p, T);
12372                strata::workload_trace::set_context(p, T, -1);
12373                strata::workload_trace::Scope verify_trace("decode.verify", nullptr, T);
12374                const Clock::time_point tw0 = Clock::now();
12375                if (!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());
12377                    return 1;
12378                }
12379                int32_t fol_tgt[16];
12380                if (!fol.empty()) {   // STRATA_FOLLOW: the forced continuation stands in for the argmax
12381                    for (int i = 0; i < T && i < 16; ++i) {
12382                        const size_t k = (size_t) produced_n + (size_t) i;
12383                        fol_tgt[i] = k < fol.size() ? fol[k] : -1;
12384                        if (fol_tgt[i] >= 0) outv[(size_t) i] = fol_tgt[i];
12385                    }
12386                }
12387                int a = 0;
12388                while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a;
12389                if (!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());
12391                    return 1;
12392                }
12393                if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; }
12394                if (chain_n > 0) { ++chain_windows; chain_drafts += chain_n; chain_ok += std::max(0, a - (T_mtp - 1)); }
12395                if (strata::core::MtpDrafter::top2_env() && !from_sfx && !first_window && a < T_mtp - 1 && a < 8) {
12396                    ++t2_rej[a];
12397                    if (mtp.top2(a) == outv[(size_t) a]) ++t2_hit[a];
12398                }
12399                const Clock::time_point tw1 = Clock::now();
12400                verify_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)
12403                bool adapt_ok = true;
12404                if (!drive.d.usage.empty() && !ajob && ((rounds + 1) % o.adapt_every) == 0) {
12405                    if (sycl_mirror_adapt()) adapt_ok = adapt();
12406                    else adapt_thr = std::thread([&] { adapt_ok = adapt(); });
12407                }
12408                if (sycl_mirror_adapt() && !adapt_ok) { std::printf("ERR SYCL mirror adaptive exchange failed\n"); return 1; }
12409                if (!ver.commit(a + 1, err)) {
12410                    if (adapt_thr.joinable()) adapt_thr.join();
12411                    std::printf("ERR %s\n", err.c_str());
12412                    return 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                {
12418                    static const char* sd = std::getenv("STRATA_PIPELINE_DUMP");
12419                    if (sd != nullptr) {
12420                        const int64_t gf = g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +
12421                                           g.ssm_conv_channels * (g.ssm_d_conv - 1);
12422                        const 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());
12425                        const size_t n_rec = (size_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
12426                        const size_t n_cnv = (size_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);
12427                        double rec_sum = 0.0, cnv_sum = 0.0;
12428                        uint64_t rec_hash = 1469598103934665603ull, cnv_hash = 1469598103934665603ull;
12429                        for (int64_t l = 0; l < ss.gdn_alloc; ++l) {
12430                            const size_t base = (size_t) l * (size_t) gf;
12431                            uint64_t rh = 1469598103934665603ull, ch = 1469598103934665603ull;
12432                            for (size_t i = 0; i < n_rec; ++i) {
12433                                uint64_t bb = 0;
12434                                std::memcpy(&bb, &h[base + i], sizeof(float));
12435                                rh = (rh ^ bb) * 1099511628211ull;
12436                                rec_sum += (double) h[base + i];
12437                            }
12438                            for (size_t i = 0; i < n_cnv; ++i) {
12439                                uint64_t bb = 0;
12440                                std::memcpy(&bb, &h[base + n_rec + i], sizeof(float));
12441                                ch = (ch ^ bb) * 1099511628211ull;
12442                                cnv_sum += (double) h[base + n_rec + i];
12443                            }
12444                            rec_hash = (rec_hash ^ rh) * 1099511628211ull;
12445                            cnv_hash = (cnv_hash ^ ch) * 1099511628211ull;
12446                        }
12447                        if (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),
12449                                         rec_sum, (unsigned long long) rec_hash, cnv_sum,
12450                                         (unsigned long long) cnv_hash);
12451                            std::fclose(df);
12452                        }
12453                    }
12454                }
12455                for (int i = 0; i <= a; ++i) consumed.push_back(window[(size_t) i]);
12456                if (use_df2) df2.note_rows(window.data(), a + 1, p);
12457                draft_offered += T - 1;
12458                draft_accepted += a;
12459                first_window = false;
12460                bool eos = false;
12461                for (int i = 0; i <= a && produced_n < max_new && !eos; ++i) {
12462                    std::printf("T %d\n", (int) outv[(size_t) i]);
12463                    if (req_logprobs >= 0) {   // row i of this window's head logits is the distribution token i came from
12464                        static std::vector<float> lrow;
12465                        static std::vector<int32_t> lord;
12466                        lrow.resize((size_t) ver.vocab());
12467                        if (!ver.copy_logits(i, lrow.data())) {
12468                            std::printf("LP nan\n");
12469                        } else {
12470                            float mx = -INFINITY;
12471                            for (const float v : lrow) mx = std::max(mx, v);
12472                            double se = 0.0;
12473                            for (const float v : lrow) se += std::exp((double) v - mx);
12474                            const double lse = (double) mx + std::log(se);
12475                            std::printf("LP %.6f", (double) lrow[(size_t) outv[(size_t) i]] - lse);
12476                            if (!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
12479                                for (const int32_t id : req_allowed) {
12480                                    if (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) {
12484                                lord.resize(lrow.size());
12485                                for (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]; });
12488                                for (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;
12496                    if (sfx_on) sfx.append(outv[(size_t) i]);
12497                    if (o.lookup_chain > 0) extra_sources_append(&outv[(size_t) i], 1);
12498                    eos = 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;
12502                const Clock::time_point tw2 = Clock::now();
12503                commit_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
12507                if (use_mtp && hist_n > 0 && mtp.coupled() && !eos && produced_n < max_new)
12508                    mtp.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.
12511                if (use_df2 && (eos || produced_n >= max_new)) {
12512                    const Clock::time_point tctx = Clock::now();
12513                    if (!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; }
12514                    static const bool ctx_timing = std::getenv("STRATA_DF2_TIMING") != nullptr;
12515                    if (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                }
12517                const 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));
12519                draft_trace.finish();
12520                {
12521                    const Clock::time_point tw3 = Clock::now();
12522                    auto msd = [](Clock::time_point a0, Clock::time_point b0) { return std::chrono::duration<double, std::milli>(b0 - a0).count(); };
12523                    dt_run += msd(tw0, tw1); dt_commit += msd(tw1, tw2); dt_draft += msd(tw2, tw3);
12524                    ++dec_windows; dec_T += T;
12525                }
12526                pcie_auto_step(req_pcie_frac);   // PcieAuto (opt-in): the share refined from the CPU pool's speed
12527                if (adapt_thr.joinable()) adapt_thr.join();
12528                if (!adapt_ok) {
12529                    std::printf("ERR an adaptive refill failed\n");
12530                    return 1;
12531                }
12532                if (!drafted) {
12533                    std::printf("ERR %s\n", err.c_str());
12534                    return 1;
12535                }
12536                if (timed_round && !eos && chain_n == 0)
12537                    policy.observe(from_sfx, T, a, sfx_match,
12538                                   std::chrono::duration<double, std::milli>(Clock::now() - round0).count());
12539                else if (timed_round && !eos)   // a chained window: its MTP part, its chain, its cost
12540                    policy.observe_chain(T_mtp, chain_n, a, cm,
12541                                         std::chrono::duration<double, std::milli>(Clock::now() - round0).count());
12542                if (eos) { finish = "stop"; break; }
12543                if (stop_req.load()) { finish = "cancel"; break; }
12544                x = outv[(size_t) a];
12545                p += a + 1;
12546            }
12547            const double decode_ms = std::chrono::duration<double, std::milli>(Clock::now() - d0).count();
12548            decode_trace.finish();
12549            // the last commit (set_commit_async): the session is complete before anything reads or copies it
12550            if (!ver.wait_commit(err)) {
12551                std::printf("ERR %s\n", err.c_str());
12552                return 1;
12553            }
12554            if (dec_timing && dec_windows > 0) {
12555                const DecSnap d1 = dec_snap();
12556                const 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));
12566                for (int st = 0; st < n_stages; ++st) {   // every stage's GPU profile, not only the first card's
12567                    const std::string pr = stage_ver(st).profile_report();
12568                    if (pr.empty()) continue;
12569                    if (st == 0) std::fprintf(stderr, "strata decode GPU stages (ms/window):%s\n", pr.c_str());   // text as before
12570                    else std::fprintf(stderr, "strata decode GPU stages, stage %d (ms/window):%s\n", st, pr.c_str());
12571                }
12572            }
12573            if (!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)
12576                live.swap(consumed);
12577                live_imgs = imgs_below(req_imgs, (int64_t) live.size());
12578                live_ok = o.prompt_cache > 0 && req_ckpt;   // ckpt=0: nothing to continue or park (#830)
12579            }
12580            static const bool state_hash = std::getenv("STRATA_STATE_HASH") != nullptr;
12581            if (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)
12584                if (DPCT_CHECK_ERROR(
12585                        dpct::get_current_device().queues_wait_and_throw()) !=
12586                    0) {
12587                    std::printf("ERR synchronizing state fingerprint\n");
12588                    return 1;
12589                }
12590                const int64_t L = (int64_t) live.size();
12591                const strata::kernels::QsaShapes qs = strata::core::qsa_shapes(g);
12592                bool hash_ok = true;
12593                std::array<uint8_t, 65536> hash_buffer;
12594                auto hash_dev = [&](const void *p, size_t bytes, uint64_t h) {
12595                    try {
12596                for (size_t offset = 0; hash_ok && offset < bytes;) {
12597                        const size_t n = std::min(hash_buffer.size(), bytes - offset);
12598                        // VRAM or a streamed host copy, with fixed diagnostic workspace.
12599                        if (DPCT_CHECK_ERROR(
12600                                dpct::get_in_order_queue()
12601                                    .memcpy(hash_buffer.data(),
12602                                            static_cast<const uint8_t *>(p) +
12603                                                offset,
12604                                            n)
12605                                    .wait()) != 0) {
12606                            hash_ok = false;
12607                            break;
12608                        }
12609                        h = fnv1a(hash_buffer.data(), n, h);
12610                        offset += n;
12611                    }
12612                    return h;
12613                }
12614                catch (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`
12622                auto hash_cells = [&](const void* pool, int64_t per_cell, int64_t c0, int64_t c1, uint64_t h) {
12623                    const int64_t ps = qs.page_size;
12624                    for (int64_t pg = c0 / ps; pg * ps < c1; ++pg)
12625                        for (int64_t hd = 0; hd < qs.n_head_kv; ++hd) {
12626                            const int64_t a = std::max(c0, pg * ps) - pg * ps, e = std::min(c1, (pg + 1) * ps) - pg * ps;
12627                            const size_t off = (size_t) (((pg * qs.n_head_kv + hd) * ps + a) * per_cell);
12628                            h = hash_dev((const uint8_t*) pool + off, (size_t) ((e - a) * per_cell), h);
12629                        }
12630                    return h;
12631                };
12632                const ConvStateSizes z = conv_state_sizes(g, ss);
12633                uint64_t h_gdn = hash_dev(ss.gdn_state, z.gdn, 1469598103934665603ull);
12634                if (std::getenv("STRATA_STATE_HASH_GDN") != nullptr && ss.gdn_alloc > 0) {   // per GDN layer: which one differs first
12635                    const size_t per = z.gdn / (size_t) ss.gdn_alloc;
12636                    std::string s;
12637                    char b[8];
12638                    for (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));
12640                        s += b;
12641                    }
12642                    std::fprintf(stderr, "strata serve: STATE_HASH_GDN %s\n", s.c_str());
12643                }
12644                uint64_t h_ple = hash_dev(ss.ple_hist, ss.ple_hist ? z.ple : 0, 1469598103934665603ull);
12645                uint64_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
12649                uint64_t h_dead = h_tail, h_pool_full = h_tail;
12650                const 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
12652                auto kv_arrays = [&](const strata::core::QsaState& st) {
12653                    const bool h = st.kv_mode != 0;
12654                    std::vector<std::pair<const void*, int64_t>> a;
12655                    if (st.kv_q4) {
12656                        const int64_t q4b = (int64_t) strata::kernels::kv_q4_bytes_per_head((int) qs.head_dim);
12657                        a = {{h ? st.host.k_q4 : st.k_q4, q4b}, {h ? st.host.v_q4 : st.v_q4, q4b}};
12658                    } else if (st.kv_hybrid) {
12659                        const int64_t q4b = (int64_t) strata::kernels::kv_q4_bytes_per_head((int) qs.head_dim);
12660                        a = {{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) {
12663                        a = {{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 {
12666                        a = {{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                    }
12669                    return a;
12670                };
12671                const int64_t end_cell = std::min<int64_t>(((L + qs.page_size - 1) / qs.page_size) * qs.page_size,
12672                                                           ss.max_cells);   // = the primary state's max_cells
12673                for (int64_t j = 0; j < ss.qsa_alloc; ++j) {   // this session's owned QSA ordinals only
12674                    const strata::core::QsaState& st = ss.qsa_states[ss.qsa_ord0 + j];
12675                    h_tail = hash_dev(st.idx_tail, z.tail, h_tail);
12676                    h_dead = hash_dev(st.idx_dead, z.dead, h_dead);
12677                    h_pool = hash_dev(st.idx_pooled, (size_t) (L / qs.idx_block) * qs.idx_dim * 4, h_pool);
12678                    h_pool_full = hash_dev(st.idx_pooled, (size_t) (L > 0 ? L / qs.idx_block + 1 : 0) * qs.idx_dim * 4,
12679                                           h_pool_full);
12680                    // KV streaming: the host copy is the identity layout and holds every cell
12681                    for (const auto& [pool, w] : kv_arrays(st)) {
12682                        h_kv = hash_cells(pool, w, 0, L, h_kv);
12683                        h_stale = hash_cells(pool, w, L, end_cell, h_stale);
12684                    }
12685                }
12686                uint64_t h_mtp = 1469598103934665603ull;
12687                if (use_mtp) {
12688                    const strata::core::QsaState& ms = mtp.kv_state();
12689                    const int64_t mL = std::min<int64_t>(L, ms.max_cells);
12690                    for (const auto& [pool, w] : kv_arrays(ms))
12691                        if (pool != nullptr) h_mtp = hash_cells(pool, w, 0, mL, h_mtp);
12692                }
12693                if (!hash_ok) {
12694                    std::printf("ERR reading state fingerprint\n");
12695                    return 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            }
12704            const int64_t req_hits = drive.d.cache_hits - decode_hits0;
12705            const int64_t req_look = (drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused) - decode_look0;
12706            const 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)
12709            const int64_t fresh = n - resume;
12710            const 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)
12718            char chain_txt[128] = "";
12719            if (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);
12722            if (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");
12732            if (admit_slot >= 0) {   // --batch: BADM <slot> <1 = continues in the batch windows | 0 = done>
12733                bool cont = !cancelled && produced_n == 1 && admit_max_new > 1 && std::strcmp(finish, "length") == 0 &&
12734                            (int64_t) live.size() == p;
12735                const auto tc0 = Clock::now();
12736                if (cont) park_slot(admit_slot);   // the conversation the slot holds, before this one overwrites it
12737                if (cont && !copy_to_slot(admit_slot, live, err)) {
12738                    std::fprintf(stderr, "strata serve: batch admission failed: %s\n", err.c_str());
12739                    bs[(size_t) admit_slot].cached = false;   // its sessions may be half written
12740                    cont = false;
12741                }
12742                if (cont) {
12743                    ver.set_slot_sampling(admit_slot, req_sp);   // the request's own sampling, row by row
12744                    BSlot& sl = bs[(size_t) admit_slot];
12745                    sl = BSlot{};
12746                    sl.active = true;
12747                    sl.x = x;
12748                    sl.p = p;
12749                    sl.produced = 1;
12750                    sl.max_new = admit_max_new;
12751                    sl.t0 = Clock::now();
12752                    sl.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
12754                        const 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);
12755                        sl.pen_n = slot_pen ? std::min(req_sp.penalty_last_n, kPenaltyWindowCap) : 0;
12756                        sl.reply0 = (int64_t) strata::kernels::penalty_window_from(live.size() > 0 ? live.size() - 1 : 0, pen_prompt);
12757                        if (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                    }
12759                    if (batch_mtp) {
12760                        if (!slot_mtp[(size_t) admit_slot]->draft_first(1, ver.final_R_all(), sl.x,
12761                                                                        sl.p - 1, sl.draft.data(), err)) {
12762                            std::fprintf(stderr, "strata batch: MTP admission for slot %d failed: %s\n",
12763                                         admit_slot, err.c_str());
12764                            return 1;
12765                        }
12766                        sl.draft_ready = true;
12767                    }
12768                    sl.cvec = cvec_cached;
12769                    sl.img = !live_imgs.empty();   // pictures: not matched again by tokens alone, so not cached
12770                    const ConvCheckpoint* best = nullptr;
12771                    for (const ConvCheckpoint& c : checks)
12772                        if (c.ids.size() < live.size() && (best == nullptr || c.ids.size() > best->ids.size()) &&
12773                            std::equal(c.ids.begin(), c.ids.end(), live.begin()))
12774                            best = &c;
12775                    if (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);
12781                admit_slot = -1;
12782            }
12783            if (drive.routing != nullptr) std::fflush(drive.routing);   // the routing trace survives a crash and is watchable mid-session
12784            request_trace.finish();
12785            strata::workload_trace::flush();
12786            // "12288 of 98179" when cancelled mid-read (#471), the rate from what was read
12787            char read_txt[64];
12788            if (cancelled)
12789                std::snprintf(read_txt, sizeof(read_txt), "%lld of %lld", (long long) read_n, (long long) fresh);
12790            else
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,
12795                         prompt_ms > 0 ? 1000.0 * read_n / prompt_ms : 0.0, (long long) produced_n, decode_ms,
12796                         decode_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)
12801            if (req_look > 0) {
12802                char off[160] = "";
12803                if (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,
12806                                  100.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",
12809                             100.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)
12814            if (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());
12819            if (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);
12823            if (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)
12828            if (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,
12832                             src.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)
12835            if (static const bool st_timing = std::getenv("STRATA_SPLIT_TIMING") != nullptr; st_timing)
12836                for (int st = 0; st < n_stages; ++st) {
12837                    const strata::core::Verifier& v = stage_ver(st);
12838                    const 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                }
12843            if (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)
12846                uint64_t miss = 0, look = 0;
12847                bool over = false;
12848                for (int64_t j = 0; j < ss.qsa_alloc; ++j) {
12849                    const strata::kernels::KvStreamCounters c =
12850                        strata::kernels::kv_stream_counters(ss.qsa_states[ss.qsa_ord0 + j].map);
12851                    miss += 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,
12856                             over ? " - OVERFLOW (too few resident cells)" : "");
12857            }
12858            if (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);
12861            if (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);
12864            if (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);
12869            for (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,
12877                             remote_experts[(size_t) r].ms_begin() - begin_before[(size_t) r],
12878                             remote_experts[(size_t) r].ms_wait() - wait_before[(size_t) r]);
12879        }
12880        save_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).
12883        try {
12884            dpct::get_current_device().queues_wait_and_throw();
12885            // Release the direct-access USM host mirror before process teardown.
12886            gguf_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.
12899    int64_t pos_start = 0;
12900    int64_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;
12903    bool kvg_started = false;   // the elastic K/V took this run's cells
12904    double 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
12908    const int64_t n_batched = (o.prefill_until > 0 && o.prefill_until < n_prompt - 1) ? o.prefill_until : n_prompt - 1;
12909    if (o.prefill_chunk > 0 && n_prompt > 1) {
12910        void* borrow = nullptr;
12911        uint64_t borrow_bytes = 0;
12912        if (!o.no_prefill_borrow && !host_res.empty() && d_res != nullptr) {
12913            int64_t chunk = o.prefill_chunk;
12914            int64_t k = plan_lend(chunk);             // auto: the largest chunk that fits; fixed: halved to fit
12915            const int64_t request_sized = equal_chunk(n_batched, chunk);
12916            if (k > 0 && request_sized < chunk) {                     // no bigger than this prompt segment needs
12917                chunk = request_sized;
12918                k = lend_slots(chunk);
12919                if (k + 128 > xcache.slots()) k = 0;
12920                if (!o.prefill_auto) o.prefill_chunk = chunk;
12921            }
12922            if (o.prefill_auto) {
12923                o.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) {
12926                k = 0;                                 // a fixed chunk that does not fit: its own buffers, as before
12927            }
12928            const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;
12929            if (k > 0) {   // the lent slots are refilled after the prompt
12930                const 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
12932                kvg_started = true;
12933                kvg_start(first);
12934                if (!kvg_ensure(n_prompt + o.max_new + 64, [] {
12935                                                                dpct::get_current_device().queues_wait_and_throw(); })) return 1;
12936                for (size_t i = 0; i < host_res.size(); ++i)
12937                    if (host_res[i] >= first) {
12938                        lent.emplace_back((int32_t) i, host_res[i]);
12939                        host_res[i] = strata::core::kNotResident;
12940                    }
12941                res_put(d_res);
12942                borrow = xcache.device_slot(first);
12943                borrow_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        }
12949        if (borrow == nullptr)
12950            std::fprintf(stderr, "strata generate: prompt path allocates its own buffers (no cache slots to borrow)\n");
12951        if (!prefill.init(wt, g, ss, srcp, o.expert_cache > 0 ? &xcache : nullptr,
12952                          host_res.empty() ? nullptr : host_res.data(), o.prefill_chunk, main_cs, err, borrow,
12953                          borrow_bytes)) {
12954            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
12955            return 1;
12956        }
12957        if (!o.mtp.empty()) {
12958            if (!mtp.bind(wt, &native_head, nullptr, err)) {
12959                std::fprintf(stderr, "strata generate: %s\n", err.c_str());
12960                return 1;
12961            }
12962            prefill.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);
12965                for (int64_t t = 0; t < T; ++t) nxt[(size_t) t] = (int32_t) o.tokens[(size_t) (p0 + t + 1)];
12966                if (prefill.draft_kv(mtp, R_rows, nxt.data(), T, p0, e)) return true;   // E-9
12967                return e.empty() && mtp.prefill(R_rows, nxt.data(), T, p0, e);
12968            };
12969        }
12970        if (use_df2) {   // the drafter's context: the last 2047 prompt rows' taps
12971            df2.reset();
12972            prefill.set_taps(df2.tap_layers(), std::max<int64_t>(0, n_prompt - 2047), 2048);
12973            prefill.on_taps = [&](const float* taps, int64_t rows, int64_t pos0, std::string& e) -> bool { return df2.context(taps, rows, pos0, e); };
12974        }
12975        if (!kvg_started) {   // the elastic K/V: every cell this run can reach (no loan)
12976            kvg_started = true;
12977            kvg_start(xcache.slots());
12978            if (!kvg_ensure(n_prompt + o.max_new + 64, [] {
12979                                                            dpct::get_current_device().queues_wait_and_throw(); })) return 1;
12980        }
12981        const Clock::time_point tp0 = Clock::now();
12982        if (!prefill.run(o.tokens.data(), n_batched, 0, err)) {
12983            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
12984            return 1;
12985        }
12986        prefill.clear_taps();
12987        // refill the lent slots from the arena and give them back to the decode tier
12988        if (!lent.empty()) {
12989            const Clock::time_point tr = Clock::now();
12990            size_t queued = 0;
12991            for (const auto& [i, slot] : lent) {   // D-4: queued, one wait (STRATA_REFILL_BLOCKING=1: each)
12992                const uint8_t* b = srcp->blob(i / g.n_expert, i % g.n_expert);
12993                const int64_t nb = (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(i / g.n_expert);
12994                if (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());
12997                    return 1;
12998                }
12999                host_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)
13003                if (!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());
13005                    return 1;
13006                }
13007            }
13008            if (!xcache.sync_queued(err)) {
13009                std::fprintf(stderr, "strata generate: refilling the lent slots failed: %s\n", err.c_str());
13010                return 1;
13011            }
13012#if defined(_WIN32)
13013            for (const auto& [i, slot] : lent)
13014                srcp->release(i / g.n_expert, i % g.n_expert);
13015#endif
13016            res_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        }
13020        prefill_batched_ms = std::chrono::duration<double, std::milli>(Clock::now() - tp0).count();
13021        prefill_ms += prefill_batched_ms;
13022        strata::uc_probe("after-prefill");
13023        pos_start = n_batched;
13024        tok = o.tokens[(size_t) pos_start];
13025        // the PLE window of the token path: the two tokens before `pos_start`
13026        ss.ple_prev[0] = pos_start >= 2 ? (int32_t) o.tokens[(size_t) (pos_start - 2)] : -1;
13027        ss.ple_prev[1] = pos_start >= 1 ? (int32_t) o.tokens[(size_t) (pos_start - 1)] : -1;
13028        const 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,
13032                     ps.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
13036    if (!kvg_started) {   // the elastic K/V of a prompt that was not read in batches
13037        kvg_started = true;
13038        kvg_start(xcache.slots());
13039        if (!kvg_ensure(n_prompt + o.max_new + 64, [] {
13040                                                        dpct::get_current_device().queues_wait_and_throw(); })) return 1;
13041    }
13042    for (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)
13044        if (native_pack) { spec_pos = pos; break; }
13045        if (pos >= o.max_context) {
13046            std::fprintf(stderr, "strata generate: ran out of context at position %lld\n", (long long) pos);
13047            return 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.
13054        const 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.
13060        ss.ple_token = (int32_t) tok;
13061        Clock::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.
13064        if (ss.ple.ready() && !strata::core::ple_issue_token(ss.ple, err)) {
13065            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
13066            return 1;
13067        }
13068        {
13069            const Clock::time_point n = Clock::now();
13070            ms_ple += std::chrono::duration<double, std::milli>(n - tp).count();
13071            tp = n;
13072        }
13073        if (!put_input(tok, pos)) return 1;
13074        {
13075            const Clock::time_point n = Clock::now();
13076            ms_embed += std::chrono::duration<double, std::milli>(n - tp).count();
13077            tp = n;
13078        }
13079        if (ss.ple.ready() && !strata::core::ple_finish_token(ss.ple, token_stream, err)) {
13080            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
13081            return 1;
13082        }
13083        {
13084            const Clock::time_point n = Clock::now();
13085            ms_ple += std::chrono::duration<double, std::milli>(n - tp).count();
13086            tp = n;
13087        }
13088
13089        if (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,
13091                         pos < 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.
13097        drive.d.layers = 0;
13098        drive.d.experts = 0;
13099        drive.d.failed = false;
13100        err.clear();
13101        if (o.no_capture) {
13102            if (!strata::core::session_token(wt, g, pos, /*pos_base=*/0, ss, d_parts, main_cs,
13103                                             o.sync_every_layer, err)) {
13104                std::fprintf(stderr, "strata generate: session_token: %s\n", err.c_str());
13105                return 1;
13106            }
13107        } else {
13108            strata::core::doorbell_reset(db);
13109            if (tgraph.captured) {
13110                if (!strata::core::session_run_token(g, pos, /*pos_base=*/0, ss, tgraph, pool_fn, pool_user,
13111                                                     loop_scratch.y_miss, main_cs, err)) {
13112                    std::fprintf(stderr, "strata generate: %s\n", err.c_str());
13113                    return 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,
13116                                        err, layer_stage, &loop_scratch)) {
13117                std::fprintf(stderr, "strata generate: session_loop: %s\n", err.c_str());
13118                return 1;
13119            }
13120        }
13121        if (final_r != nullptr) {
13122            dpct::get_in_order_queue()
13123                .memcpy(final_r_host.data(), ss.R,
13124                        final_r_host.size() * sizeof(float))
13125                .wait();
13126            const 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        }
13130        if (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,
13133                         drive.d.fail ? drive.d.fail : "(no message)");
13134            return 1;
13135        }
13136        {
13137            // **THE LAYER LOOP ITSELF, WHICH IS WHAT `--gpu-only-full` HAS TO BE COMPARED AGAINST.**
13138            const Clock::time_point n = Clock::now();
13139            ms_layers += std::chrono::duration<double, std::milli>(n - tp).count();
13140            tp = n;
13141        }
13142        // ---- the ladder for THIS position, in the order `session_loop` filled it: layer 0 first.
13143        if (layer_dump != nullptr) std::fwrite(layer_stage, sizeof(float), layer_floats, layer_dump);
13144        if (half_dump != nullptr) {
13145            std::fwrite(half_stage, sizeof(float), (size_t) g.n_layers * (size_t) half_stride, half_dump);
13146        }
13147        if (!run_head(token_stream)) {
13148            std::fprintf(stderr, "strata generate: lm_head: %s\n", err.c_str());
13149            return 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.
13156        if (!o.stream_token &&
13157            DPCT_CHECK_ERROR(
13158                dpct::get_current_device().queues_wait_and_throw()) != 0) {
13159            std::fprintf(
13160                stderr,
13161                "strata generate: the device faulted in lm_head at position "
13162                "%lld: %s\n",
13163                /*
13164                DPCT1009: SYCL reports errors using exceptions and does not
13165                use error codes. Please replace the
13166                "get_error_string_dummy(...)" with a real error-handling
13167                function.
13168                */
13169                /*
13170                DPCT1010: SYCL uses exceptions to report errors and does
13171                not use the error codes. The cudaGetLastError function call was
13172                replaced with 0. You need to rewrite this code.
13173                */
13174                (long long)pos, dpct::get_error_string_dummy(0));
13175            return 1;
13176        }
13177        {
13178            const Clock::time_point n = Clock::now();
13179            ms_head += std::chrono::duration<double, std::milli>(n - tp).count();
13180            tp = n;
13181        }
13182        const bool emit_logits = dump != nullptr &&
13183            strata::program::logits_selection::selected(pos, dump_positions, o.logits_stride);
13184        const bool read_logits = !o.stream_token || o.check_logits || emit_logits;
13185        /*
13186        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
13187        While the origin API might be synchronous, it depends on the type of
13188        operand memory, so you may need to call wait() on event return by memcpy
13189        API to ensure synchronization behavior.
13190        */
13191        if (read_logits &&
13192            (DPCT_CHECK_ERROR(strata::q_of(token_stream)->memcpy(
13193                 logits.data(), d_logits, (size_t)n_vocab * 4)) != 0 ||
13194             DPCT_CHECK_ERROR(strata::q_of(token_stream)->wait()) != 0)) {
13195            std::fprintf(stderr, "strata generate: reading the logits back failed\n");
13196            return 1;
13197        }
13198        int bad = 0;
13199        if (read_logits) for (float v : logits) if (!std::isfinite(v)) ++bad;
13200        if (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);
13203            return 1;
13204        }
13205        // the header with the first row (see `hdr`): a run that dumps nothing leaves an empty file
13206        if (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);
13209            return 1;
13210        }
13211        if (emit_logits) hdr_written = true;
13212        if (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);
13215            return 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.
13224            const Clock::time_point n = Clock::now();
13225            ms_readback += std::chrono::duration<double, std::milli>(n - tp).count();
13226            tp = n;
13227        }
13228
13229        int 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.
13232        sp.counter = (uint64_t) pos;
13233        strata::kernels::sample_tokens(d_logits, 1, (int) n_vocab, nullptr, 0, sp, d_next, token_stream);
13234        /*
13235        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
13236        While the origin API might be synchronous, it depends on the type of
13237        operand memory, so you may need to call wait() on event return by memcpy
13238        API to ensure synchronization behavior.
13239        */
13240        if (DPCT_CHECK_ERROR(strata::q_of(token_stream)->memcpy(
13241                &next, d_next, sizeof(int))) != 0 ||
13242            DPCT_CHECK_ERROR(strata::q_of(token_stream)->wait()) != 0) {
13243            std::fprintf(
13244                stderr,
13245                "strata generate: reading the sampled token back failed: %s\n",
13246                /*
13247                DPCT1009: SYCL reports errors using exceptions and does not
13248                use error codes. Please replace the
13249                "get_error_string_dummy(...)" with a real error-handling
13250                function.
13251                */
13252                /*
13253                DPCT1010: SYCL uses exceptions to report errors and does
13254                not use the error codes. The cudaGetLastError function call was
13255                replaced with 0. You need to rewrite this code.
13256                */
13257                dpct::get_error_string_dummy(0));
13258            return 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.
13263        if (o.native_flash_attn_short) for (int64_t j = 0; j < ss.qsa_alloc; ++j) {
13264            const int64_t i = ss.qsa_ord0 + j;   // the global ordinal, as the session's carve names it
13265            const int32_t status = ss.qsa_states[i].host_step[strata::kernels::kStepCount];
13266            if (status != 0) {
13267                std::fprintf(stderr, "strata generate: native attention status %d at QSA layer %lld, position %lld\n",
13268                             status, (long long) i, (long long) pos);
13269                return 1;
13270            }
13271        }
13272        if (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));
13275            return 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.
13280            const Clock::time_point n = Clock::now();
13281            ms_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.
13287        if (pos >= n_prompt - 1) total_ms += std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
13288        else prefill_ms += std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
13289        if (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.
13294        if (pos >= n_prompt - 1) produced.push_back(next);
13295        if ((int64_t) produced.size() >= o.max_new) break;
13296        if (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.
13302        ss.ple_prev[0] = ss.ple_prev[1];
13303        ss.ple_prev[1] = (int32_t) tok;
13304        tok = (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.
13306        if (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.
13314    const 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();
13316    if (spec_pos > 0 && (int64_t) produced.size() < o.max_new && !ended) {
13317        auto 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;
13321            return (bool) in && parse_i64_list(text.c_str(), ids, e);
13322        };
13323        std::vector<int64_t> oracle, follow;
13324        if (!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());
13326            return 2;
13327        }
13328        if (!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());
13330            return 2;
13331        }
13332        // --spec-follow: the run ends with the continuation
13333        const int64_t max_new = follow.empty() ? o.max_new : std::min<int64_t>(o.max_new, (int64_t) follow.size());
13334        int64_t follow_differ = 0, follow_emitted = 0;
13335        if (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");
13338            return 2;
13339        }
13340        mem_mark("the head and the prompt path");
13341        strata::core::Verifier ver;
13342        strata::core::VerifyHits vh;
13343        vh.d_res = thits.d_res;
13344        int32_t* usage_dev = nullptr;   // STRATA_USAGE_DUMP=PATH: the device plan counts every routed expert (measurement)
13345        const char* usage_dump = std::getenv("STRATA_USAGE_DUMP");
13346        if (mirror_table_d && usage_dump && *usage_dump) {
13347            usage_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        }
13350        if (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));
13351        vh.h_res = host_res.empty() ? nullptr : host_res.data();
13352        vh.cache_base = thits.cache_base;
13353        vh.blob = thits.blob;
13354        vh.slot_off = xcache.slot_offsets();   // E-6: the device plan's pointers
13355        vh.n_slots = xcache.slots();
13356        if (use_df2) ver.set_taps(df2.tap_layers());
13357        if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err)) {
13358            print_start_refusal("strata generate", err);
13359            return 1;
13360        }
13361        const bool use_mtp = !o.mtp.empty();
13362        if (use_mtp && !mtp.bind(wt, &native_head, ver.final_R_all(), err)) {
13363            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
13364            return 1;
13365        }
13366        if (use_df2) {   // no MTP to draft instead: anything DFlash2 cannot do ends the run
13367            if (!ver.tapping()) {
13368                std::fprintf(stderr, "strata generate: --draft dflash2: the verifier keeps no taps here, so the run ends here\n");
13369                return 1;
13370            }
13371            df2.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
13372            if (!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());
13374                return 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        }
13378        const bool draft_on = use_mtp || use_df2;   // some drafter proposes
13379        mem_mark("the verifier and the drafter's binding");
13380        ver.set_sampling(sp);   // the CLI's own sampling (until 0.1.19 this loop was always greedy); no penalties here
13381        if (use_mtp) mtp.set_draft_sampling(sp);   // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise)
13382        ver.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).
13387        ver.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2);
13388        drive.d.plan = ver.plan_sink();
13389        drive.d.pcie_num = (int) (o.pcie_frac * 256.0 + 0.5);
13390        if (drive.d.pcie_num < 0) drive.d.pcie_num = 0;
13391        if (drive.d.pcie_num > 256) drive.d.pcie_num = 256;
13392        const 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)
13394        const int64_t files0 = src.file_reads(), ram0 = src.ram_reads();
13395        const uint64_t fbytes0 = src.file_blob_bytes(), fall0 = src.file_read_bytes();
13396        const double fms0 = src.file_ms();
13397        if (o.adapt_every > 0 && o.adapt_swaps > 0) drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f);
13398        int64_t swaps_total = 0;
13399        double ms_adapt = 0;
13400        dpct::queue_ptr adapt_stream = &dpct::get_in_order_queue();
13401        /*
13402        DPCT1025: The SYCL queue is created ignoring the flag and priority
13403        options.
13404        */
13405        if (!drive.d.usage.empty() &&
13406            DPCT_CHECK_ERROR(
13407                adapt_stream = dpct::get_current_device().create_queue(true)) !=
13408                0) {
13409            std::fprintf(stderr, "strata generate: cannot create the refill stream\n");
13410            return 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;
13414        int 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;
13417        adapt_ev = new sycl::event();
13418        int64_t adapt_rounds = 0;   // counted here: `rounds` is declared below the adapt lambda
13419        auto apply_pending = [&](bool wait) {
13420            try {
13421        if (pending.empty()) return;
13422            // STRATA_TRACE_ADAPT=1: whether a round's copies had landed when the next window read the table
13423            static const bool trace_pending = std::getenv("STRATA_TRACE_ADAPT") != nullptr;
13424            if (wait) adapt_ev->wait_and_throw();
13425            else if (adapt_ev->get_info<
13426                         sycl::info::event::command_execution_status>() !=
13427                     sycl::info::event_command_status::complete) {
13428                if (trace_pending)
13429                    std::fprintf(stderr, "strata: PENDING not landed, %zu stay non-resident this window\n",
13430                                 pending.size());
13431                return;
13432            }
13433            if (trace_pending)
13434                std::fprintf(stderr, "strata: PENDING landed, %zu experts become resident\n", pending.size());
13435            unpin_blobs(pin_live);
13436            src.commit_exchanges();   // the resident RAM mode: the evicted experts take their places in RAM
13437            for (const auto& [i, slot] : pending) {
13438                host_res[(size_t) i] = slot;
13439                srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert);   // in VRAM now: RAM not needed
13440            }
13441            pending.clear();
13442            pending_age = 0;
13443            if (d_res != nullptr)
13444                res_put(d_res);
13445        }
13446        catch (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.
13455        auto adapt = [&]() -> bool {
13456            const 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.
13461            static const bool trace_adapt = std::getenv("STRATA_TRACE_ADAPT") != nullptr;
13462            if (!pending.empty()) {
13463                if (trace_adapt)
13464                    std::fprintf(stderr, "strata: ADAPT round=%lld SKIPPED, %zu swaps still in flight\n",
13465                                 (long long) adapt_rounds, pending.size());
13466                return true;   // the previous swaps are still in flight
13467            }
13468            if (trace_adapt) std::fprintf(stderr, "strata: ADAPT round=%lld considering\n", (long long) adapt_rounds);
13469            struct Swap { float gain; int32_t layer, in, out; };
13470            std::vector<Swap> swaps;
13471            std::vector<std::pair<float, int32_t>> cand, vict;
13472            for (int64_t l = 0; l < g.n_layers; ++l) {
13473                cand.clear();
13474                vict.clear();
13475                const float* u = drive.d.usage.data() + l * g.n_expert;
13476                const int32_t* r = host_res.data() + l * g.n_expert;
13477                for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) {
13478                    if (r[e] < 0) { if (u[e] >= 2.0f && !helper_holds(l, e)) cand.emplace_back(u[e], e); }
13479                    else vict.emplace_back(u[e], e);
13480                }
13481                if (cand.empty() || vict.empty()) continue;
13482                std::sort(cand.begin(), cand.end(), [](auto& a, auto& b) { return a.first > b.first; });
13483                const 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; });
13486                for (size_t i = 0; i < nc; ++i) {
13487                    if (cand[i].first < vict[i].first + 1.5f) break;
13488                    swaps.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; });
13492            if ((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
13494            if (!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");
13497                return false;
13498            }
13499            if (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;
13501                for (const Swap& s : swaps)
13502                    if (const uint8_t* b = srcp->blob(s.layer, s.in))
13503                        spans.emplace_back((uintptr_t) b,
13504                                           (uintptr_t) b + strata::kernels::cpu::expert_layout().blob_bytes(s.layer));
13505                pin_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
13508            const 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;
13512            for (const Swap& s : swaps) {
13513                const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out;
13514                const int32_t slot = host_res[out];
13515                const uint8_t* b = srcp->blob(s.layer, s.in);
13516                const 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
13518                if (slot < 0 || b == nullptr) {
13519                    std::fprintf(stderr, "strata generate: an adaptive refill failed\n");
13520                    return false;
13521                }
13522                if (dma_mode != 0) {
13523                    cp_dst.push_back(xcache.device_slot(slot));
13524                    cp_src.push_back(b);
13525                    cp_bytes.push_back(blob_n);
13526                } else if (adapt_copy_h2d(xcache.device_slot(slot), b, blob_n,
13527                                          adapt_stream) != 0) {
13528                    std::fprintf(stderr, "strata generate: an adaptive refill failed\n");
13529                    return false;
13530                }
13531                host_res[out] = strata::core::kNotResident;   // evicted now: the CPU computes it meanwhile
13532                srcp->prefetch(s.layer, s.out);   // a file-backed arena released its pages: read them back ahead
13533                pending.emplace_back((int32_t) in, slot);      // resident once the copy has landed
13534            }
13535            if (!cp_dst.empty() &&
13536                strata::core::copy_blobs(cp_dst.data(), cp_src.data(),
13537                                         cp_bytes.data(), cp_dst.size(),
13538                                         adapt_stream, dma_mode) != 0) {
13539                std::fprintf(stderr, "strata generate: an adaptive refill failed\n");
13540                return false;
13541            }
13542            if (!swaps.empty()) dpct::sync_barrier(adapt_ev, adapt_stream);
13543            if (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);
13546            for (float& v : drive.d.usage) v *= o.adapt_decay;
13547            swaps_total += (int64_t) swaps.size();
13548            ms_adapt += std::chrono::duration<double, std::milli>(Clock::now() - ta).count();
13549            return true;
13550        };
13551        int64_t p = spec_pos;
13552        int32_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.
13558        bool 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        {
13562            static const bool warm_on = [] { const char* v = std::getenv("STRATA_WARM_GRAPHS"); return !(v && v[0] == '0'); }();
13563            if (warm_on) {
13564                const Clock::time_point tw = Clock::now();
13565                if (!ver.warm(err) || (use_mtp && !mtp.warm(err))) {
13566                    std::fprintf(stderr, "strata generate: warm-up capture: %s\n", err.c_str());
13567                    return 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        }
13574        if (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());
13577            return 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");
13582        if (!o.window_hashes.empty() && hashes == nullptr) {
13583            std::fprintf(stderr, "strata generate: cannot write %s\n", o.window_hashes.c_str());
13584            return 1;
13585        }
13586        std::vector<float> hash_rows;
13587        std::vector<int64_t> accepted_hist((size_t) o.spec, 0);
13588        int64_t rounds = 0, drafts_total = 0, drafts_ok = 0, corrupt_counter = 0;
13589        const int S_mtp = o.mtp_max_t > 0 ? std::min(o.mtp_max_t, o.spec) : o.spec;
13590        if (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);
13594        int64_t sfx_windows = 0, sfx_drafts = 0, sfx_ok = 0;
13595        int64_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);
13598        const bool sfx_on = o.suffix_draft > 0 || o.lookup_chain > 0;
13599        if (sfx_on) {
13600            for (int64_t t : o.tokens) sfx.append((int32_t) t);
13601            for (int64_t t : produced) sfx.append((int32_t) t);
13602        }
13603        if (o.lookup_chain > 0) {
13604            extra_sources_reset();
13605            for (int64_t t : o.tokens) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); }
13606            for (int64_t t : produced) { const int32_t t32 = (int32_t) t; extra_sources_append(&t32, 1); }
13607        }
13608        const double pool_ms0 = drive.cpu_ms;
13609        const 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)
13611        const int df2_skip_min = strata::spec::df2_lookup_skip_min(0);
13612        bool df2_deferred = false;
13613        int dfr_n = 0;
13614        int64_t dfr_pos = 0;
13615        int32_t dfr_anchor = 0;
13616        auto defer_df2 = [&](int a_) -> bool {
13617            if (!use_df2 || o.suffix_draft <= 0 || df2_skip_min <= 0) return false;
13618            const int ks = sfx.propose(o.spec - 1, sbuf.data());
13619            if (!strata::spec::skip_draft_for_lookup(true, df2_skip_min, ks, sfx.last_match())) return false;
13620            df2_deferred = true; dfr_n = a_ + 1; dfr_pos = p; dfr_anchor = outv[(size_t) a_];
13621            return 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)
13624        auto draft_df2 = [&](int a_) -> bool {
13625            int32_t dd[strata::core::Dflash2Drafter::kDrafts];
13626            float pp[strata::core::Dflash2Drafter::kDrafts];
13627            if (!df2.draft(ver.tap_dev(), a_ + 1, p, outv[(size_t) a_], dd, pp, err)) return false;
13628            for (size_t i = 0; i < drafts.size() && i < (size_t) strata::core::Dflash2Drafter::kDrafts; ++i) { drafts[i] = dd[i]; dprob[i] = pp[i]; }
13629            return true;
13630        };
13631        while ((int64_t) produced.size() < max_new) {
13632            const Clock::time_point t0 = Clock::now();
13633            bool dfr_lookup = false;
13634            int dfr_T = 0, dfr_match = 0;
13635            if (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)
13636                df2_deferred = false;
13637                const int kd = sfx.propose(o.spec - 1, sbuf.data());
13638                const int md = sfx.last_match();
13639                const strata::spec::DraftPolicy::Pick pkd = kd > 0 ? policy.choose(S_mtp, kd, md) : strata::spec::DraftPolicy::Pick{};
13640                if (kd > 0 && pkd.lookup) {
13641                    dfr_lookup = true; dfr_T = pkd.t; dfr_match = md;
13642                    if (!df2.context(ver.tap_dev(), dfr_n, dfr_pos, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; }
13643                } else {
13644                    int32_t dd[strata::core::Dflash2Drafter::kDrafts];
13645                    float pp[strata::core::Dflash2Drafter::kDrafts];
13646                    if (!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; }
13647                    for (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            }
13650            int T = S_mtp;
13651            {   // the window rule of the round's ACTIVE source (spec/window_rule.hpp)
13652                strata::spec::WindowRuleIn wr;
13653                wr.use_mtp = draft_on; wr.draft_on = draft_on; wr.df2_active = use_df2; wr.spec_cost = false; wr.first_window = first_window;
13654                wr.chain_rows = 1; wr.cap = S_mtp; wr.start = T; wr.spec_min_p = o.spec_min_p;
13655                wr.draft_conf = o.draft_conf; wr.dprob = dprob.data();
13656                T = strata::spec::choose_window(wr);
13657            }
13658            if (first_window) T = 1;
13659            bool from_sfx = false;
13660            int sfx_match = 0;
13661            if (o.suffix_draft > 0 && !first_window) {
13662                const int k = sfx.propose(o.spec - 1, sbuf.data());
13663                sfx_match = sfx.last_match();
13664                if (k > 0 && (!draft_on || sbuf[0] == drafts[0])) {
13665                    const strata::spec::DraftPolicy::Pick pk = policy.choose(T, k, sfx_match);
13666                    if (pk.lookup) { T = pk.t; from_sfx = true; }
13667                }
13668            }
13669            if (dfr_lookup) {   // the lookup window chosen before the draft (the draft was skipped)
13670                sfx.propose(o.spec - 1, sbuf.data());
13671                T = 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
13674            int chain_n = 0, cm = 0;
13675            if (o.lookup_chain > 0 && use_mtp && !first_window && !from_sfx && T < o.spec) {
13676                int csrc = -1;
13677                const int nt = chain_tail(sfx, drafts.data(), T - 1, ctail);
13678                chain_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,
13680                                                             cbuf.data(), &cm, &csrc);
13681                if (chain_n > 0 && std::getenv("STRATA_LOOKUP_CHAIN_FIXED") == nullptr) {
13682                    double p_mtp = 1.0;
13683                    for (int i = 0; i < T - 1; ++i) p_mtp *= dprob[(size_t) i];
13684                    chain_n = policy.chain(T, p_mtp, chain_n, cm);
13685                }
13686            }
13687            const int T_mtp = T;
13688            T += chain_n;
13689            const bool timed_round = !first_window;
13690            ++window_hist[(size_t) T];
13691            if (p + T > o.max_context) {
13692                std::fprintf(stderr, "strata generate: ran out of context at position %lld\n", (long long) p);
13693                return 2;
13694            }
13695            window[0] = x;
13696            for (int i = 1; i < T; ++i) {
13697                const size_t at = produced.size() - 1 + (size_t) i;
13698                int32_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;
13700                if (i >= T_mtp) d = cbuf[(size_t) (i - T_mtp)];
13701                if (o.spec_corrupt > 0 && (++corrupt_counter % o.spec_corrupt) == 0) d = (d + 1) % (int32_t) n_vocab;
13702                window[(size_t) i] = d;
13703            }
13704            drive.d.layers = 0;
13705            drive.d.experts = 0;
13706            drive.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)
13710            if (adapt_nowait()) apply_pending(false);
13711                else if (pending.empty() || ++pending_age >= adapt_lag()) apply_pending(true);
13712            if (!ver.run(T, window.data(), p, &drive_pool_multi, &drive, outv.data(), err)) {
13713                std::fprintf(stderr, "strata generate: %s\n", err.c_str());
13714                return 1;
13715            }
13716            if (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,
13719                             drive.d.fail ? drive.d.fail : "(no message)");
13720                return 1;
13721            }
13722            if (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")
13723                static std::FILE* wlf = std::fopen(wl, "w");
13724                std::vector<float> lrow((size_t) ver.vocab());
13725                for (int t = 0; wlf != nullptr && t < T; ++t) {
13726                    if (!ver.copy_logits(t, lrow.data())) break;
13727                    int i1 = 0, i2 = -1;
13728                    for (int v = 1; v < (int) lrow.size(); ++v) {
13729                        if (lrow[(size_t) v] > lrow[(size_t) i1]) { i2 = i1; i1 = v; }
13730                        else 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                }
13734                if (wlf) std::fflush(wlf);
13735            }
13736            if (hashes != nullptr) {   // FNV-1a over the window's final residual rows (a test path: a plain copy)
13737                const size_t n_floats = (size_t) T * (size_t) (g.hc * g.n_embd);
13738                hash_rows.resize(n_floats);
13739                dpct::get_in_order_queue()
13740                    .memcpy(hash_rows.data(), ver.final_R_all(),
13741                            n_floats * sizeof(float))
13742                    .wait();
13743                uint64_t h = 1469598103934665603ull;
13744                const auto* bytes = (const uint8_t*) hash_rows.data();
13745                for (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);
13747                for (int i = 0; i < T; ++i) std::fprintf(hashes, " %d", (int) outv[(size_t) i]);
13748                std::fprintf(hashes, "\n");
13749            }
13750            if (!follow.empty()) {   // the continuation stands in for the argmax
13751                const size_t k0 = produced.size();
13752                for (int i = 0; i < T && k0 + (size_t) i < follow.size(); ++i) {
13753                    fdiff[(size_t) i] = outv[(size_t) i] != (int32_t) follow[k0 + (size_t) i];
13754                    outv[(size_t) i] = (int32_t) follow[k0 + (size_t) i];
13755                }
13756            }
13757            int a = 0;
13758            while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a;
13759            if (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            }
13764            if (first_window) {
13765                first_window = false;
13766                ttft_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.
13770                if (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;
13773                    if (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);
13775                    if (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;
13781            bool adapt_ok = true;
13782            if (!drive.d.usage.empty() && ((rounds + 1) % o.adapt_every) == 0)
13783                adapt_thr = std::thread([&] { adapt_ok = adapt(); });
13784            if (!ver.commit(a + 1, err)) {
13785                if (adapt_thr.joinable()) adapt_thr.join();
13786                std::fprintf(stderr, "strata generate: %s\n", err.c_str());
13787                return 1;
13788            }
13789            ++rounds;
13790            drafts_total += T - 1;
13791            drafts_ok += a;
13792            ++accepted_hist[(size_t) a];
13793            if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; }
13794            if (chain_n > 0) { ++chain_windows; chain_drafts += chain_n; chain_ok += std::max(0, a - (T_mtp - 1)); }
13795            bool eos = false;
13796            for (int i = 0; i <= a && (int64_t) produced.size() < max_new && !eos; ++i) {
13797                produced.push_back(outv[(size_t) i]);
13798                if (sfx_on) sfx.append(outv[(size_t) i]);
13799                if (o.lookup_chain > 0) extra_sources_append(&outv[(size_t) i], 1);
13800                eos = o.stop_eos && std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outv[(size_t) i]) != o.eos_ids.end();
13801                if (!follow.empty()) { follow_differ += fdiff[(size_t) i]; ++follow_emitted; }
13802            }
13803            if (eos) {
13804                if (adapt_thr.joinable()) adapt_thr.join();
13805                if (!ver.wait_commit(err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; }
13806                total_ms += std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
13807                break;
13808            }
13809            const 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));
13811            if (adapt_thr.joinable()) adapt_thr.join();
13812            if (!adapt_ok) return 1;
13813            if (!drafted) {
13814                std::fprintf(stderr, "strata generate: %s\n", err.c_str());
13815                return 1;
13816            }
13817            x = outv[(size_t) a];
13818            p += a + 1;
13819            const double round_ms = std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
13820            total_ms += round_ms;
13821            if (timed_round && chain_n == 0) policy.observe(from_sfx, T, a, sfx_match, round_ms);
13822            else if (timed_round) policy.observe_chain(T_mtp, chain_n, a, cm, round_ms);
13823            if (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
13828        if (!ver.wait_commit(err)) {
13829            std::fprintf(stderr, "strata generate: %s\n", err.c_str());
13830            return 1;
13831        }
13832        if (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,
13835                    drafts_total > 0 ? (double) drafts_ok / (double) drafts_total : 0.0,
13836                    rounds > 0 ? (double) (drafts_ok + rounds) / (double) rounds : 0.0);
13837        if (!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);
13840        if (o.spec_min_p > 0.0 || o.draft_conf > 0.0) {
13841            std::printf("%-24s", "window sizes");
13842            for (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        }
13845        if (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);
13848        if (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");
13852        for (size_t i = 0; i < accepted_hist.size(); ++i) std::printf(" %zu:%lld", i, (long long) accepted_hist[i]);
13853        std::printf("\n");
13854        if (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,
13858                        ver.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));
13861        if (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,
13864                        pool.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);
13867        if (rounds > 0)
13868            std::printf("%-24s plan %.3f  activation quantize %.3f  jobs %.3f  run %.3f ms/round\n", "dispatch",
13869                        drive.d.ms_plan / rounds, drive.d.ms_actq / rounds, drive.d.ms_jobs / rounds,
13870                        drive.d.ms_run / rounds);
13871        if (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();
13874            if (FILE* uf = std::fopen(usage_dump, "wb")) {
13875                int64_t total = 0;
13876                for (int64_t l = 0; l < g.n_layers; ++l)
13877                    for (int64_t e = 0; e < g.n_expert; ++e)
13878                        for (int32_t c = 0; c < uh[(size_t) (l * g.n_expert + e)]; ++c, ++total) {
13879                            const int32_t hdr[3] = {(int32_t) l, 1, (int32_t) e};
13880                            const 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        }
13889        if (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);
13892        if (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)
13898        if (src.complement_ready())
13899            if (const char* chk = std::getenv("STRATA_CHECK_SWAPS"); chk != nullptr && chk[0] != '\0' && chk[0] != '0') {
13900                int64_t held_ram = 0, held_gpu = 0, lost = 0, stale = 0;
13901                std::vector<uint8_t> ref;
13902                for (int64_t l = 0; l < g.n_layers; ++l)
13903                    for (int64_t e = 0; e < g.n_expert; ++e) {
13904                        const bool ram = src.has_resident(l, e);
13905                        const bool gpu = host_res[(size_t) l * (size_t) g.n_expert + (size_t) e] >= 0;
13906                        held_ram += ram;
13907                        held_gpu += gpu;
13908                        if (!ram && !gpu) { ++lost; continue; }
13909                        if (!ram) continue;
13910                        ref.resize((size_t) strata::kernels::cpu::expert_layout().blob_bytes(l));
13911                        if (!src.copy_blob_from_file(l, e, ref.data()) ||
13912                            std::memcmp(ref.data(), src.resident_blob(l, e), ref.size()) != 0) {
13913                            if (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            }
13921        if (srcp == &src) {  // CS-T: the RAM and file tiers (the GPU cache's share is the hit rate above)
13922            const 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),
13926                        fmb, rounds > 0 ? fmb / rounds : 0.0, rounds > 0 ? fms / rounds : 0.0,
13927                        fms > 0 ? fmb / fms : 0.0, src.gguf_mode() ? " (the GGUF in place)" : "",
13928                        (double) (fall0 - fbytes0) / 1e6);
13929            if (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),
13934                            src.file_reads() > files0 ? 100.0 * (double) src.warmed_hits() / (double) (src.file_reads() - files0) : 0.0,
13935                            rounds > 0 ? drive.d.lookahead->busy_ms() / rounds : 0.0, (long long) drive.d.lookahead->skipped());
13936        }
13937        if (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),
13940                        drive.d.pcie_num);
13941        (void) pool_ms0;
13942        if (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);
13945        if (use_mtp && rounds > 0)
13946            std::printf("%-24s %.3f ms/round drafting (%lld rounds), MTP prompt %.1f ms, %.0f MiB of VRAM\n", "mtp",
13947                        mtp.ms_draft / (double) mtp.rounds, (long long) mtp.rounds, mtp.ms_prefill,
13948                        (double) mtp.vram_bytes() / 1048576.0);
13949    }
13950
13951    if (dump != nullptr && std::fclose(dump) != 0) {
13952        std::fprintf(stderr, "strata generate: cannot finish logits dump\n");
13953        return 1;
13954    }
13955    if (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",
13959                    o.dump_layers.c_str(), (long long) g.n_layers, (int) g.hc, (long long) g.n_embd);
13960    }
13961    if (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    }
13967    if (routing != nullptr) {
13968        std::fclose(routing);
13969        drive.routing = nullptr;
13970        std::printf("%-24s %s (%lld records of layer, k, ids, weights)\n", "routing dumped",
13971                    o.dump_routing.c_str(), (long long) drive.calls);
13972    }
13973    if (o.stage_timing) strata::core::stage_timing_report(g.n_layers);
13974
13975    const int64_t decoded = (int64_t) produced.size();
13976    std::printf("prompt  :");
13977    for (int64_t t : o.tokens) std::printf(" %lld", (long long) t);
13978    std::printf("\noutput  :");
13979    for (int64_t t : produced) std::printf(" %lld", (long long) t);
13980    std::printf("\n");
13981    const 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,
13984                decode_ms > 0.0 ? 1000.0 / decode_ms : 0.0);
13985    if (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,
13988                    prefill_ms > 0 ? 1000.0 * (double) (n_prompt - 1) / prefill_ms : 0.0, ttft_ms);
13989    if (!o.dump_mixed.empty()) {
13990        std::vector<float> mx((size_t) g.n_embd);
13991        if (DPCT_CHECK_ERROR(dpct::get_in_order_queue()
13992                                 .memcpy(mx.data(), ss.block.mixed,
13993                                         mx.size() * sizeof(float))
13994                                 .wait()) != 0) {
13995            std::fprintf(stderr, "strata generate: reading mixed back failed\n");
13996            return 1;
13997        }
13998        std::FILE* mf = std::fopen(o.dump_mixed.c_str(), "wb");
13999        if (mf == nullptr) {
14000            std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_mixed.c_str());
14001            return 1;
14002        }
14003        std::fwrite(mx.data(), sizeof(float), mx.size(), mf);
14004        std::fclose(mf);
14005        double s2 = 0, mag = 0;
14006        for (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)
14012    if (!o.dump_residual.empty()) {
14013        std::vector<float> R((size_t) g.hc * g.n_embd);
14014        if (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");
14019            return 1;
14020        }
14021        std::FILE* rf = std::fopen(o.dump_residual.c_str(), "wb");
14022        if (rf == nullptr) {
14023            std::fprintf(stderr, "strata generate: cannot write %s\n", o.dump_residual.c_str());
14024            return 1;
14025        }
14026        const 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);
14030        double mag = 0, mx = 0;
14031        int bad = 0;
14032        for (float v : R) {
14033            if (!std::isfinite(v)) ++bad;
14034            else { 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",
14037                    o.dump_residual.c_str(), (int) g.hc, (long long) g.n_embd, bad, mag / (double) R.size(), mx);
14038    }
14039
14040    if (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.
14046        if (phase_tokens > 0) {
14047            const 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,
14051                        ms_readback / pt, ms_sample / pt,
14052                        (ms_ple + ms_embed + ms_layers + ms_head + ms_readback + ms_sample) / pt, decode_ms);
14053        }
14054        if (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".
14060        const 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.
14068        if (pool_positions > 0.0) {
14069            double wp = 0, dr = 0, rp = 0;
14070            pool.phase_ms(wp, dr, rp);
14071            const 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());
14076        for (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",
14078                        r + 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.
14083        if (o.expert_cache > 0) {
14084            const int64_t look = drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused;
14085            const 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,
14090                        look > 0 ? (double) drive.d.cache_hits / (double) look : 0.0,
14091                        (long long) drive.d.cache_admitted, (long long) drive.d.cache_refused,
14092                        100.0 * (double) (drive.d.cache_admitted + drive.d.cache_hits > 0
14093                                              ? (double) xcache.resident() / (double) xcache.slots()
14094                                              : 0.0));
14095        }
14096        if (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);
14100        if (tgraph.captured && tgraph.calls > 0) {
14101            const 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        }
14106        if (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.
14111            const 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",
14116                        gr.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.
14124            const 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,
14127                        pool_positions, gr.ms_host / perlap);
14128        }
14129    }
14130
14131    if (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());
14141    return 0;
14142}
14143catch (sycl::exception const &exc) {
14144  const std::string what = exc.what();
14145  if (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}