okami.mom/strata

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

waveringanaedge0 port: gate or drop the fork's remaining unconditional debug printsd510921bc

main
338.0 KiB5817 linesraw
1// src/core/verify.cpp - see include/strata/core/verify.hpp.
2// HostGraphLaunch (the graph launched by the calling thread, or by a helper thread so this one can serve the doorbells): CUDA builds,
3// and the Windows HIP build (STRATA_VERIFY_ASYNC_LAUNCH=1 launches from a helper thread; STRATA_LAUNCH_PROBE=1 logs the launch timing).
4#if (!defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)) || (defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && defined(_WIN32))
5#define STRATA_VERIFY_HGL 1
6#endif
7#include "strata/core/batch_rows.hpp"
8#include "strata/core/sm75_series.hpp"
9#include "strata/core/sm120_series.hpp"
10#include "strata/core/defaults_026.hpp"
11#include "strata/kernels/gfx_arch.hpp"
12#include "strata/core/verify.hpp"
13#include "strata/core/latent_share.hpp"
14#include "strata/core/window_evict.hpp"
15#include "strata/core/expert_nibble.hpp"
16#include "strata/latent/latent_moe.hpp"
17#include "strata/kernels/latent.hpp"
18#include "strata/core/pin_budget.hpp"
19#if defined(STRATA_VERIFY_HGL)
20#include "strata/core/host_graph_launch.hpp"
21#endif
22#include "strata/core/remote_expert_opt.hpp"
23#include "strata/core/dma_batch.hpp"
24#include "strata/core/spec_prob.hpp"
25#include "strata/core/spec_proposal.hpp"
26#if defined(_WIN32)
27#ifndef NOMINMAX
28#define NOMINMAX
29#endif
30#include <windows.h>
31#include <intrin.h>
32#endif
33
34#include "strata/core/native_head.hpp"
35#include "strata/core/on_device.hpp"
36#include "strata/core/peer_experts.hpp"
37#include "strata/kernels/iq_kernels.hpp"
38#include "strata/kernels/cpu/expert_layout.hpp"
39#include "strata/kernels/cpu/hadamard.hpp"
40#include "strata/kernels/bf16_gemv.hpp"
41#include "strata/kernels/native_router.hpp"
42#include "strata/kernels/native_moe.hpp"
43#include "strata/kernels/cpu/expert.hpp"
44#include "strata/kernels/elementwise.hpp"
45#include "strata/kernels/qsa_prompt_attn.hpp"
46#include "strata/kernels/fused_gr.hpp"
47#include "strata/kernels/route_prior.hpp"
48#include "strata/kernels/cvec.hpp"
49#include "strata/kernels/gr.hpp"
50#include "strata/kernels/kv_q4.hpp"
51#include "strata/kernels/kv_q8.hpp"
52#include "strata/kernels/native_mmvq.hpp"
53#include "strata/core/dispatch_stats.hpp"
54#include "strata/kernels/native_gr_postops.hpp"
55#include "strata/kernels/native_ple_postops.hpp"
56#include "strata/kernels/native_qsa.hpp"
57#include "strata/kernels/native_qsa_indexer.hpp"
58#include "strata/kernels/native_rope.hpp"
59#include "strata/kernels/ngram.hpp"
60#include "strata/kernels/pdl.hpp"
61#include "strata/kernels/ple.hpp"
62#include "strata/kernels/qsa.hpp"
63#include "strata/kernels/qsa_decode_attn.hpp"
64#include "strata/kernels/qsa_select.hpp"
65#include "strata/kernels/quantize_act.hpp"
66#include "strata/kernels/rope.hpp"
67#include "strata/kernels/s2_expert_grouped.hpp"
68#include "strata/kernels/sampler.hpp"
69#include "strata/core/progress.hpp"
70#include "strata/kernels/shared_expert.hpp"
71#include "strata/kernels/verify_kernels.hpp"
72#if defined(STRATA_HAVE_DFLASH2)
73#include "strata/kernels/dflash2.hpp"
74#endif
75
76#include <algorithm>
77#include <atomic>
78#include <map>
79#include <set>
80#include <mutex>
81#include <string>
82#include <optional>
83#include <thread>
84#include <vector>
85#include <chrono>
86#include <cmath>
87#include <cstdio>
88#include <cstdlib>
89#include <cstring>
90#include <exception>
91#include "strata/platform/cpu_relax.hpp"
92
93#if defined(STRATA_GPU_METAL)
94// The Metal backend's decode window (metal/src/engine/window.cpp): this file's init/run/commit hand over to it.
95namespace strata::metal_engine {
96void window_destroy(void* w);
97void* window_create();
98bool window_init(void* w, const strata::core::ModelGeometry& g, strata::core::SessionState& ss, int max_t, int64_t max_cells,
99                 int64_t* n_vocab, std::string& err);
100bool window_run(void* w, int T, const int32_t* tokens, int64_t pos0, bool head, int32_t* out, std::string& err);
101bool window_commit(void* w, int n_keep, std::string& err);
102bool window_copy_logits(void* w, int t, float* host);
103void window_set_sampling(void* w, const strata::kernels::SamplerParams* sp, const int32_t* hist, int hist_len);
104bool window_sample_slot_row(void* w, int row, const strata::kernels::SamplerParams& sp, const int32_t* hist, int hist_len, int32_t* tok, std::string& err);
105bool window_init_slots(void* w, const std::vector<strata::core::SessionState*>& slots, std::string& err);
106bool window_run_slots(void* w, const int* rows, int S, const int32_t* tokens, const int64_t* pos, int32_t* out, std::string& err);
107bool window_taps(void* w, const std::vector<int>& layers, const float** tap_dev, std::string& err);   // dflash2.inc
108}  // namespace strata::metal_engine
109#endif
110
111namespace strata::core {
112namespace {
113
114constexpr float EPS = 1e-6f;
115using Clock = std::chrono::steady_clock;
116double ms_since(Clock::time_point t) { return std::chrono::duration<double, std::milli>(Clock::now() - t).count(); }
117const bool g_dbg = std::getenv("STRATA_VERIFY_DEBUG") != nullptr;
118inline bool g_lfuse() { static const bool on = [] { const char* v = std::getenv("STRATA_LFUSE"); return v != nullptr && v[0] == '1'; }(); return on; }
119// STRATA_ROUTE_RESIDENT=<margin logits> (+ STRATA_ROUTE_RESIDENT_RANKS=lo-hi, default 6-9): residency-biased routing.
120struct RouteResidentCfg;
121RouteResidentCfg& route_resident_cfg();
122struct RouteResidentCfg {
123    float margin = 0.0f;
124    int lo = 6, hi = 9;
125    // #1578: one counter block per GPU.  A layer split inits a verifier per stage; a block allocated on whichever device
126    // was current at the first init is unreachable from the other stage's kernels without P2P (illegal memory access).
127    // The Verifier asks for its device's block in init (outside graph capture) and keeps the pointer: a launch never
128    // picks the block by the host thread's current device.  nullptr (the allocation failed): the kernel runs without counters.
129    std::mutex mu;
130    std::map<int, unsigned long long*> blocks;
131    unsigned long long* stats_on(int dev) {
132        if (margin <= 0.0f || dev < 0) return nullptr;
133        std::lock_guard<std::mutex> lk(mu);
134        const auto it = blocks.find(dev);
135        if (it != blocks.end()) return it->second;
136        unsigned long long* p = nullptr;
137        {
138            const OnDevice on(dev);
139            if (cudaMalloc((void**) &p, 8 * sizeof(unsigned long long)) != cudaSuccess ||
140                cudaMemset(p, 0, 8 * sizeof(unsigned long long)) != cudaSuccess) {
141                (void) cudaGetLastError();
142                if (p != nullptr) cudaFree(p);
143                p = nullptr;
144                std::fprintf(stderr, "route-resident: the counters could not be allocated on GPU %d; it runs without them\n", dev);
145            }
146        }
147        if (blocks.empty()) {
148            std::atexit([] {
149                RouteResidentCfg& c = route_resident_cfg();
150                for (const auto& kv : c.blocks) {
151                    if (kv.second == nullptr) continue;
152                    unsigned long long h[8] = {};   // (the counter block allocated above: 8 words)
153                    if (cudaSetDevice(kv.first) != cudaSuccess || cudaDeviceSynchronize() != cudaSuccess ||
154                        cudaMemcpy(h, kv.second, sizeof(h), cudaMemcpyDeviceToHost) != cudaSuccess) {
155                        (void) cudaGetLastError();
156                        continue;
157                    }
158                    char who[32] = "";
159                    if (c.blocks.size() > 1) std::snprintf(who, sizeof who, " (GPU %d)", kv.first);
160                    std::fprintf(stderr, "route-resident%s: margin=%g ranks=%d-%d windows T>8 (prompt reads): tail_nonres=%llu swaps=%llu (%.1f%%) nonres_entries before=%llu after=%llu\n",
161                                 who, c.margin, c.lo, c.hi, h[0], h[1], h[0] ? 100.0 * h[1] / h[0] : 0.0, h[2], h[3]);
162                    std::fprintf(stderr, "route-resident%s: margin=%g ranks=%d-%d windows T<=8 (decode): tail_nonres=%llu swaps=%llu (%.1f%%) nonres_entries before=%llu after=%llu\n",
163                                 who, c.margin, c.lo, c.hi, h[4], h[5], h[4] ? 100.0 * h[5] / h[4] : 0.0, h[6], h[7]);
164                }
165            });
166        }
167        blocks[dev] = p;
168        return p;
169    }
170};
171RouteResidentCfg& route_resident_cfg() {
172    static RouteResidentCfg c;
173    static const bool parsed = [] {
174        if (const char* v = std::getenv("STRATA_ROUTE_RESIDENT")) c.margin = (float) std::atof(v);
175        if (const char* v = std::getenv("STRATA_ROUTE_RESIDENT_RANKS")) std::sscanf(v, "%d-%d", &c.lo, &c.hi);
176        return true;
177    }();
178    (void) parsed;
179    return c;
180}
181inline bool g_lfuse_gate() { static const bool on = [] { const char* v = std::getenv("STRATA_LFUSE_GATE"); return v == nullptr || v[0] != '0'; }(); return on; }
182inline bool g_lfuse_pair() { static const bool on = [] { const char* v = std::getenv("STRATA_LFUSE_PAIR"); return v == nullptr || v[0] != '0'; }(); return on; }
183inline bool g_qdedup() { static const bool on = [] { const char* v = std::getenv("STRATA_VERIFY_QDEDUP"); return v != nullptr && std::atoi(v) != 0; }(); return on; }
184// S26 STRATA_QFUSE=1: activation q8_1 images written by their producers (the GDN output norm) - the same bytes
185// fork F4 (Eddoursul): 2-4 token dense projections read an interleaved copy of the q8_1 activations (bitwise the same
186// outputs); STRATA_MMVQ_IL=0 keeps native_mmvq's multi-column kernels
187inline bool g_mmvq_il() { static const bool on = [] { const char* v = std::getenv("STRATA_MMVQ_IL"); return v == nullptr || v[0] != '0'; }(); return on; }
188// STRATA_SELECT_LONG=1 (opt-in): a window graph past select_long_at() cells takes the long-context QSA select
189// (qsa_block_topk_long's multi-CTA top-k through topk_scratch_, qsa_block_scores_long's shuffle-free decode scorer;
190// both compute capability 6.x by default, the same ids and score bits).  Each costs ~6 more kernels a call, which only
191// a longer context pays back (4x GP100: 0.5 ms a window more at 1K, even at 30K, 4.0-4.7 ms less at 300K), so the
192// verifier keeps a second set of window graphs for it.  Off: no scratch, no second graphs.
193inline bool select_long_on() {
194    static const bool on = [] {
195        const char* v = std::getenv("STRATA_SELECT_LONG");
196        if (v == nullptr || v[0] != '1') return false;
197        if (strata::kernels::qsa_topk_multi_scratch_ints(1) <= 0) {   // a build without the multi-CTA kernels: no second graphs
198            std::fprintf(stderr, "strata verify: STRATA_SELECT_LONG=1 needs the CUDA build with STRATA_EXPERIMENTAL_SM60; "
199                                 "ignored\n");
200            return false;
201        }
202        return true;
203    }();
204    return on;
205}
206// STRATA_SELECT_LONG_AT: the threshold in cells (default 65536; 0: always)
207inline int64_t select_long_at() {
208    static const int64_t at = [] {
209        const char* v = std::getenv("STRATA_SELECT_LONG_AT");
210        return v != nullptr && v[0] != 0 ? (int64_t) std::atoll(v) : (int64_t) 65536;
211    }();
212    return at;
213}
214// 143-amdk: STRATA_QFUSE_HC - only the hyper-connection read writes its consumer's q8_1 image (not the GDN recurrence): gfx12 default (=0 / 1 forces off / on)
215inline bool g_qfuse_hc() {
216#if defined(STRATA_USE_HIP)
217    static const bool on = [] {
218        const char* v = std::getenv("STRATA_QFUSE_HC");
219        if (v != nullptr) return std::atoi(v) != 0;
220        int dev = 0;
221        cudaDeviceProp p;
222        return cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess &&
223               strata::kernels::gfx_arch_is_gfx12(p.gcnArchName);
224    }();
225    return on;
226#else
227    return false;
228#endif
229}
230// STRATA_GRAPH_PRIO=1 (opt-in): the window graph's kernel nodes keep their capturing stream's
231// priority (side_ high, sh_cs_ low).  Unset / 0: every node at the launch stream's priority, as before.
232[[maybe_unused]] inline bool graph_prio_on() {   // (every HIP caller is guarded off)
233#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_GPU_METAL)
234    return false;
235#else
236    static const bool on = [] { const char* v = std::getenv("STRATA_GRAPH_PRIO"); return v != nullptr && std::atoi(v) != 0; }();
237    return on;
238#endif
239}
240// STRATA_GRAPH_PRIO: the capture and graph queries by CUDA version (13 renamed the edge-data forms: the same split as
241// verify_kernels.cu's and the PDL edge check above).  Nothing is returned for the edge data.
242#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL)
243inline cudaError_t prio_capture_deps(cudaStream_t s, cudaStreamCaptureStatus* st, const cudaGraphNode_t** deps, size_t* n) {
244#if CUDART_VERSION >= 13000
245    return cudaStreamGetCaptureInfo(s, st, nullptr, nullptr, deps, nullptr, n);
246#elif CUDART_VERSION >= 12030
247    return cudaStreamGetCaptureInfo_v3(s, st, nullptr, nullptr, deps, nullptr, n);
248#else
249    return cudaStreamGetCaptureInfo_v2(s, st, nullptr, nullptr, deps, n);
250#endif
251}
252inline cudaError_t prio_node_deps(cudaGraphNode_t node, cudaGraphNode_t* deps, size_t* n) {
253#if CUDART_VERSION >= 13000
254    return cudaGraphNodeGetDependencies(node, deps, nullptr, n);
255#elif CUDART_VERSION >= 12030
256    return cudaGraphNodeGetDependencies_v2(node, deps, nullptr, n);
257#else
258    return cudaGraphNodeGetDependencies(node, deps, n);
259#endif
260}
261#endif
262// fork 34a35db + b063c13 (Eddoursul), STRATA_SIDE_MIXER=1 / =2: the mixer's work that reads only the layer's input on
263// branches of the window's graph (bitwise the same outputs); 0 = in line, and no branch stream is created.  Unset: 2 on a
264// compute capability 12.0 card (sm120_series.hpp; STRATA_SM120_PERF=0 turns it off), 0 elsewhere.
265inline int g_side_mixer() {
266    static const int env = [] { const char* v = std::getenv("STRATA_SIDE_MIXER"); return v ? std::max(0, std::min(2, std::atoi(v))) : -1; }();
267    if (env >= 0) return env;
268#if defined(STRATA_USE_HIP) || defined(STRATA_GPU_METAL)
269    return 0;
270#else
271    static int per_dev[64];   // 0 unknown, else mode + 1
272    int dev = 0;
273    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return 0; }
274    if (!per_dev[dev]) {
275        int maj = 0, mnr = 0;
276        const bool ok = cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
277                        cudaDeviceGetAttribute(&mnr, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess;
278        if (!ok) cudaGetLastError();
279        per_dev[dev] = 1 + (ok && strata::sm120_default(maj, mnr) ? 2 : 0);
280    }
281    return per_dev[dev] - 1;
282#endif
283}
284// STRATA_ROUTE_PRIOR=lambda: residency-biased routing (the top-10 picked again with a logit bonus for the resident
285// experts; route_prior.cu).  OFF unless asked for (STRATA_ROUTE_PRIOR=1.5, strata::kRoutePriorSmallCard in sm120_series.hpp, is the value the
286// app's Expert-settings row writes): 0.2.7 turned 1.5 on by itself on a discrete NVIDIA card of 13 GiB or less, and the owner took that default
287// back on 2026-10-29 (#4402: repetition loops and weaker results in long agent sessions).  With nothing set this is 0.2.6's behaviour, exactly.
288// Measured on an RTX 3060 12 GB only (IQ3_XXS; at 1.5 story +15%, code +37% decode against off).  Any value in the variable wins on every card.
289// The value is read once.
290inline float g_route_prior() {
291    static const char* const env_s = std::getenv("STRATA_ROUTE_PRIOR");
292    static const float lambda = strata::route_prior_resolve(env_s, false, false, 0.0);
293    return lambda;
294}
295inline bool g_qfuse() { static const bool on = [] { const char* v = std::getenv("STRATA_QFUSE"); return v != nullptr && std::atoi(v) != 0; }(); return on; }
296#define VDBG(...) do { if (g_dbg) { std::fprintf(stderr, "verify dbg: " __VA_ARGS__); std::fflush(stderr); } } while (0)
297
298struct Bump {
299    uint8_t* base = nullptr;
300    uint64_t used = 0;
301    template <typename T> T* take(uint64_t n) {
302        T* p = base ? (T*) (base + used) : nullptr;
303        used += (n * sizeof(T) + 255) & ~255ull;
304        return p;
305    }
306};
307
308// #649 (HIP, opt-in A/Bs for the gfx1030 verify timeouts; CUDA never reads them)
309//   STRATA_VERIFY_COHERENT=1  the handshake words and rows in explicitly coherent (fine-grained) host memory
310//   STRATA_DOORBELL_STORE=1   the GPU stores each step's ring instead of read-modify-writing it over PCIe
311bool env_on(const char* name) {
312    const char* e = std::getenv(name);
313    return e != nullptr && e[0] != 0 && e[0] != '0';
314}
315#if defined(STRATA_USE_HIP)
316const bool g_coherent = env_on("STRATA_VERIFY_COHERENT");
317const bool g_doorbell_store = env_on("STRATA_DOORBELL_STORE");
318#endif
319const bool g_trace = env_on("STRATA_VERIFY_TRACE");
320// STRATA_LAUNCH_PROBE (STRIX-TDR): process start, and the first windows' launch timing
321const Clock::time_point g_proc_t0 = Clock::now();
322Clock::time_point probe_proc_t0() { return g_proc_t0; }
323const bool g_no_multi_gr = env_on("STRATA_NO_MULTI_GR");   // #783 PR-g: per-token GR reads/writes and generic-T kernels again
324const bool g_no_batch_kv = env_on("STRATA_NO_BATCH_KV_STEP");   // #783 PR-d: per-token K/V and indexer appends again
325// STRATA_BATCH_SELF_COMMIT=1 (opt-in): a batch window whose rows are each another slot's one token keeps them itself,
326// as a one-token window does (record_window): the GDN conv histories and states advance inside the window graph, and
327// no commit graph runs after it.  Such a window's commit is unconditional (each slot keeps its one row), and the rest
328// of the commit graph only repeats what the window wrote: the indexer tails are put back and appended again from the
329// same rows, the PLE histories are put back to the window's own snapshot.
330// Read at the first use, not at program start: the engine sets the Windows gfx1151 parallel-request defaults (arch_defaults.cpp) in main(),
331// after namespace-scope constants are initialised, so a constant here would never see them.
332bool batch_self_commit_on() { static const bool v = env_on("STRATA_BATCH_SELF_COMMIT"); return v; }
333#define g_batch_self_commit (batch_self_commit_on())
334// STRATA_QSA_SLOTS=1 (opt-in): in a batch window, a QSA layer's block scores, top-k and attention run as one launch
335// each over the window's rows (up to 8 per launch, each row reading its own slot's indexer keys and K/V) instead of
336// one call per row; every row is computed by the same kernel with the same arithmetic as its own call.  Not with a
337// streamed KV cache (a row's block resolve could evict the blocks an earlier row of the same slot selected).
338bool qsa_slots_on() { static const bool v = env_on("STRATA_QSA_SLOTS"); return v; }
339#define g_qsa_slots (qsa_slots_on())
340
341// every row of a batch window is another slot's (no slot has proposal rows)
342bool one_row_per_slot(const int* rows, int S) {
343    for (int i = 0; i < S; ++i)
344        for (int j = i + 1; j < S; ++j)
345            if (rows[i] == rows[j]) return false;
346    return S >= 1;
347}
348bool batch_self_commits(const int* rows, int S) { return g_batch_self_commit && one_row_per_slot(rows, S); }
349
350// The shared expert runs on its own stream, forked off and joined back per layer (`sh_fork` in record_window).  The
351// overlap pays off on CUDA, where it was added (cfd3b72).  On HIP a cross-stream event dependency costs more than the
352// shared expert takes to run, so there the fork starts off: same binary, same 48,067-token prompt, three runs each on a
353// Radeon AI PRO R9700 (gfx1201, ROCm 6.4.3), the fork off decodes at 62.9 t/s against 43.4 t/s with it on.  The
354// profiler turns the fork off to time the stages, so a profiled run never showed that.  #816 reports the same fall on a
355// gfx1030 (RX 6800, Windows, 42.5 -> 56.4 t/s).  STRATA_SH_STREAM overrides either default: `=1` forks, `=0` does not.
356// Strix Halo (gfx1151, unified memory) is the exception: the fork pays there (+1.8% UD-IQ4_XS, +6.7% UD-Q4_K_XL decode
357// at 8K, ids identical), so the gfx1151 arch table sets STRATA_SH_STREAM=1 on Linux.  On Windows gfx1151 the fork is slower (0.2.7,
358// Qwen IQ3_S: decode -6.4% with it, ids identical), so there the table leaves it out and this default (off on HIP) applies.
359// Read on first use, after that table ran.
360bool sh_stream_on() {
361    static const bool on = [] {
362        if (const char* v = std::getenv("STRATA_SH_STREAM")) return v[0] != '0';
363#if defined(STRATA_USE_HIP)
364        return false;
365#else
366        return true;
367#endif
368    }();
369    return on;
370}
371
372// 0.2.2: the zero-doorbell window graph has one host wait, the PLE flag (layer 1's wait kernel spins until the host has read
373// the window's PLE rows).  Raised after the launch returns, it can deadlock HIP on the very first launch of a graph: the
374// stall report of a hung first window (gfx1151, 910-token prompt, about 1 run in 6) shows the host inside hipGraphLaunch
375// waiting for a runtime lock while the runtime's worker waits for the GPU, which is spinning on this flag; the raise that
376// would free it sits behind the launch.  So the first launch of each window graph reads the rows and raises the flag BEFORE
377// the launch (the wait then passes at once); later launches keep the order that overlaps the read with layer 0 (reading
378// first costs about 1.4% decode on gfx1151).  Mode 0: never, 1: every launch, 2: the first launch of each graph.  Default:
379// 2 on HIP, 0 elsewhere (the CUDA path is unchanged).  STRATA_VERIFY_EARLY_PLE_FLAG=0 / 1 / 2 forces a mode.
380int early_ple_flag_mode() {
381    static const int mode = [] {
382        if (const char* v = std::getenv("STRATA_VERIFY_EARLY_PLE_FLAG")) return std::atoi(v) < 0 ? 0 : std::min(2, std::atoi(v));
383#if defined(STRATA_USE_HIP)
384        return 2;
385#else
386        return 0;
387#endif
388    }();
389    return mode;
390}
391
392// A one-token window always keeps its token, so its graph advances the sequence state itself (the GDN conv history
393// and recurrence state) and Verifier::commit launches no commit graph after it (eddoursul's fork, F7).  CUDA only:
394// HIP keeps the commit graph after every window (STRATA_ONE_TOKEN_COMMIT=0 does too).
395// The head's hyper-connection read for the window's tokens in one launch set (CUDA; HIP: opt-in STRATA_HEAD_MIX_MULTI=1, which the
396// gfx12 table sets; =0 keeps gr_read per token): bitwise the same sums.
397bool head_mix_multi_enabled() {
398#if defined(STRATA_USE_HIP)
399    static const bool on = [] {
400        const char* v = std::getenv("STRATA_HEAD_MIX_MULTI");
401        return v != nullptr && std::atoi(v) != 0;
402    }();
403    return on;
404#else
405    static const bool on = [] {
406        const char* v = std::getenv("STRATA_HEAD_MIX_MULTI");
407        return v == nullptr || std::atoi(v) != 0;
408    }();
409    return on;
410#endif
411}
412
413// 143-amdk: the wait for a host flag folded into the copy that follows it (wait_copy_i32_from_mapped,
414// copy_rows_from_mapped_after): same reads, same values, one kernel node fewer each.  A dependent kernel costs ~2.4 us in a
415// gfx1201 graph whatever it does; measured on gfx12 only, so it is on there by default.  STRATA_FUSE_WAIT=0 / 1 forces it
416// off / on (HIP builds; a CUDA build never fuses).
417// the Turing series (STRATA_SM75_PERF=1, sm75_series.hpp) defaults of the CUDA build's switches below, read per device
418bool device_is_sm75() {
419#if defined(STRATA_USE_HIP)
420    return false;
421#else
422    static int per_dev[64];   // 0 unknown, 1 no, 2 yes
423    int dev = 0;
424    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false;
425    if (!per_dev[dev]) {
426        int maj = 0, mnr = 0;
427        const bool ok = cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
428                        cudaDeviceGetAttribute(&mnr, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess;
429        if (!ok) cudaGetLastError();
430        per_dev[dev] = ok && strata::sm75_default(maj, mnr) ? 2 : 1;   // a Turing card with STRATA_SM75_PERF=1
431    }
432    return per_dev[dev] == 2;
433#endif
434}
435
436bool fuse_wait_on() {
437#if defined(STRATA_USE_HIP)
438    static const int env = [] {
439        const char* v = std::getenv("STRATA_FUSE_WAIT");
440        return v != nullptr ? (std::atoi(v) != 0 ? 1 : 0) : -1;
441    }();
442    if (env >= 0) return env != 0;
443    static int per_dev[64];   // 0 unknown, 1 no, 2 yes
444    int dev = 0;
445    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false;
446    if (!per_dev[dev]) {
447        cudaDeviceProp p;
448        per_dev[dev] = cudaGetDeviceProperties(&p, dev) == cudaSuccess && strata::kernels::gfx_arch_is_gfx12(p.gcnArchName) ? 2 : 1;
449    }
450    return per_dev[dev] == 2;
451#else
452    // CUDA: STRATA_FUSE_WAIT=1 folds both waits (the plan's and the CPU rows'), =2 only the plan's, =0 neither.  Turing
453    // default 2 (RTX 2080 Ti, Flash-Next Q2_0, two runs each: +0.6..+1.4 % decode); the rows' version makes every row
454    // block of the copy poll the flag over PCIe and was -1.5 % there, so it stays opt-in.
455    static const int env = [] { const char* v = std::getenv("STRATA_FUSE_WAIT"); return v != nullptr ? std::atoi(v) : -1; }();
456    if (env >= 0) return env == 1 || env == 2;
457    return device_is_sm75();
458#endif
459}
460// 143-amdk's rows version of the folded wait (copy_rows_from_mapped_after): HIP with fuse_wait_on, CUDA STRATA_FUSE_WAIT=1
461bool fuse_rows_on() {
462#if defined(STRATA_USE_HIP)
463    return fuse_wait_on();
464#else
465    static const bool on = [] { const char* v = std::getenv("STRATA_FUSE_WAIT"); return v != nullptr && std::atoi(v) == 1; }();
466    return on;
467#endif
468}
469
470// 143-amdk: STRATA_FUSE_CONVAB=1 - the GDN conv and the a/b projections in one launch.  Opt-in: measured -0.3% on gfx1201 (the a/b dot chain is the longer one).
471bool fuse_convab_on() {
472#if defined(STRATA_USE_HIP)
473    static const bool on = [] { const char* v = std::getenv("STRATA_FUSE_CONVAB"); return v != nullptr && std::atoi(v) != 0; }();
474    return on;
475#else
476    return false;
477#endif
478}
479
480// 143-amdk: STRATA_FUSE_HITS - moe_hit_add folded into the combine (gfx12 default; =0 / 1 forces off / on)
481bool fuse_hits_on() {
482#if defined(STRATA_USE_HIP)
483    static const int env = [] { const char* v = std::getenv("STRATA_FUSE_HITS"); return v != nullptr ? (std::atoi(v) != 0 ? 1 : 0) : -1; }();
484    if (env >= 0) return env != 0;
485    static int per_dev[64];   // 0 unknown, 1 no, 2 yes
486    int dev = 0;
487    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false;
488    if (!per_dev[dev]) {
489        cudaDeviceProp p;
490        per_dev[dev] = cudaGetDeviceProperties(&p, dev) == cudaSuccess && strata::kernels::gfx_arch_is_gfx12(p.gcnArchName) ? 2 : 1;
491    }
492    return per_dev[dev] == 2;
493#else
494    return false;
495#endif
496}
497
498bool one_token_self_commit() {
499#if defined(STRATA_USE_HIP)
500    static const bool on = [] {
501        const char* v = std::getenv("STRATA_ONE_TOKEN_COMMIT");   // HIP: opt-in (=1)
502        return v != nullptr && std::atoi(v) != 0;
503    }();
504    return on;
505#else
506    static const bool on = [] {
507        const char* v = std::getenv("STRATA_ONE_TOKEN_COMMIT");
508        return v == nullptr || std::atoi(v) != 0;
509    }();
510    return on;
511#endif
512}
513
514bool mapped(size_t bytes, void** h, void** d) {
515#if defined(STRATA_USE_HIP)
516    if (g_coherent) {
517        if (hipHostMalloc(h, bytes, hipHostMallocMapped | hipHostMallocCoherent |
518                                        (peer_portable() ? hipHostMallocPortable : 0)) != hipSuccess)
519            return false;
520        std::memset(*h, 0, bytes);
521        return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess;
522    }
523#endif
524    if (strata::core::host_alloc_guarded(h, bytes, cudaHostAllocMapped | (peer_portable() ? cudaHostAllocPortable : 0)) != cudaSuccess) return false;   // multi-GPU: portable only with a peer - the peer card writes its rows into them
525    std::memset(*h, 0, bytes);
526    return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess;
527}
528
529strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { return qsa_shapes(g); }
530
531const WeightRef* need(const LayerView& v, const char* suffix, std::string& err) {
532    const WeightRef* r = v.get(suffix);
533    if (r == nullptr && err.empty()) err = v.name(suffix) + " is missing";
534    return r;
535}
536
537bool native_of(const WeightRef* w, const std::string& name, std::string& err) {
538    if (w == nullptr) return false;
539    if (w->native_data == nullptr) {
540        err = "verify: " + name + " is not served natively (run with --native)";
541        return false;
542    }
543    return true;
544}
545
546}  // namespace
547
548namespace {
549std::atomic<const Verifier*> g_diag_verifier{nullptr};
550void diag_active_verifier(std::FILE* f) {
551    if (const Verifier* v = g_diag_verifier.load()) v->diag(f);
552}
553// #267: every live verifier (a layer split has one per stage), for the release before the engine ends
554constexpr int kLiveMax = 16;
555std::atomic<Verifier*> g_live[kLiveMax];
556void release_live_verifiers(std::FILE* f) {
557    for (auto& slot : g_live)
558        if (Verifier* v = slot.load()) {
559            const Clock::time_point t0 = Clock::now();
560            const bool done = v->release_gpu_waits(5000);
561            if (f != nullptr)
562                std::fprintf(f, "strata: released the verify window's GPU waits (#267): the GPU %s\n",
563                             done ? ("finished in " + std::to_string((long long) ms_since(t0)) + " ms").c_str()
564                                  : "did not finish within 5 s");
565        }
566    if (f != nullptr) std::fflush(f);
567}
568// the same, silent, with one bound for all of them (kfd_quiet.hpp, EXIT: an integrated gfx11's stop on a signal)
569bool release_live_verifiers_within(int ms) {
570    const Clock::time_point t0 = Clock::now();
571    bool all = true;
572    for (auto& slot : g_live)
573        if (Verifier* v = slot.load()) {
574            const int64_t left = (int64_t) ms - (int64_t) ms_since(t0);
575            if (!v->release_gpu_waits(left > 0 ? (int) left : 0)) all = false;
576        }
577    return all;
578}
579// #649: the host side of STRATA_VERIFY_TRACE - a ring of the last kTraceN handshake events of every verifier
580struct TraceEv {
581    int64_t t_ns;
582    const void* who;
583    int64_t window, step, layer, aux;
584    uint32_t seq, flag, a, b;
585    const char* what;
586};
587constexpr uint64_t kTraceN = 4096;
588TraceEv g_trace_ring[kTraceN];
589std::atomic<uint64_t> g_trace_next{0};
590int64_t trace_now_ns() {
591    return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count();
592}
593std::string released_note(bool drained) {
594    return drained ? "; its GPU waits were released and the GPU finished (#267)"
595                   : "; its GPU waits were released but the GPU did not finish within 5 s (#267)";
596}
597// #267 test hook: STRATA_TEST_VERIFY_STALL=N withholds the last layer's flag in the N-th window (1-based), so the
598// GPU spins on a flag nobody raises - the bounded window wait and the release are then what ends it.  Unset: never.
599const int64_t g_test_stall = [] {
600    const char* e = std::getenv("STRATA_TEST_VERIFY_STALL");
601    return e != nullptr ? (int64_t) std::atoll(e) : (int64_t) 0;
602}();
603// The overlapped split's hand-off wait on the GPU is bounded: STRATA_SPLIT_WAIT_MS (default 30000, 0 = no bound).
604// The host's own per-layer wait (20 s, #267) normally ends a stalled window first; this bound is the backstop for
605// a host that is gone (a killed process must not leave a kernel spinning on its card).
606const unsigned long long g_split_wait_ns = [] {
607    const char* e = std::getenv("STRATA_SPLIT_WAIT_MS");
608    return (unsigned long long) (e != nullptr ? std::atoll(e) : 30000) * 1000000ull;
609}();
610// test hook: STRATA_TEST_HANDOFF_DROP=N - the writing stage's N-th window (1-based) leaves its hand-off flag down, as
611// if the publish were lost; the reading stage's bounded wait (or the host's) must then end the window cleanly.
612const int64_t g_test_drop = [] {
613    const char* e = std::getenv("STRATA_TEST_HANDOFF_DROP");
614    return e != nullptr ? (int64_t) std::atoll(e) : (int64_t) 0;
615}();
616}  // namespace
617
618bool Verifier::release_gpu_waits(int timeout_ms) {
619    released_.store(true);
620    trace_ev("RELEASE", -1, -1, timeout_ms);
621    // the words the spin kernels read (wait_flag_ge, wait_flag_ge_or) are mapped host memory, so a store here
622    // reaches them with no API call; UINT32_MAX is past every ring.  (E-6's skip words are device memory, but
623    // wait_flag_ge_or also returns on its flag.)  A host function raising flag B later only raises.
624    for (uint32_t* p : {h_flag_, h_flagA_, h_flagB_, hflag_in_h_})   // + an overlapped split's hand-off wait
625        if (p != nullptr) *(volatile uint32_t*) p = UINT32_MAX;
626    std::atomic_thread_fence(std::memory_order_seq_cst);
627    strata_store_fence();
628    const OnDevice on_device(device_);
629    const Clock::time_point t0 = Clock::now();
630    for (cudaStream_t s : {cs_, copy_}) {
631        if (s == nullptr) continue;
632        while (cudaStreamQuery(s) == cudaErrorNotReady) {
633            if (ms_since(t0) > timeout_ms) {
634                trace_ev("RELEASE-NOT-DRAINED", -1, -1, (int64_t) ms_since(t0));
635                return false;
636            }
637            std::this_thread::sleep_for(std::chrono::milliseconds(1));
638        }
639    }
640    trace_ev("RELEASE-DRAINED", -1, -1, (int64_t) ms_since(t0));   // aux: ms the GPU took to finish once released
641    return true;
642}
643
644void Verifier::trace_ev(const char* what, int64_t step, int64_t layer, int64_t aux) const {
645    if (!g_trace) return;
646    auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; };
647    TraceEv& e = g_trace_ring[g_trace_next.fetch_add(1) % kTraceN];
648    e = {trace_now_ns(), this, windows, step, layer, aux, rd(h_seq_), rd(h_flag_), rd(h_flagA_), rd(h_flagB_), what};
649}
650
651void Verifier::trace_dump(std::FILE* f) const {
652    if (!g_trace || f == nullptr) return;
653    static const char* names[kProfPer] = {"pre", "hc-read0", "qkv gemv", "conv", "ab", "z", "rec", "kv-idx", "k/v rope", "kv append", "q", "scores+topk", "kv-resolve", "attention", "gate", "", "out-proj", "router+ring", "shared", "waitA", "VRAM hits", "waitB", "PCIe grp", "waitCPU", "combine", "", "head", "", "", "ymWait", "ymCopy", "ymAdd", "", "", "", ""};
654    const uint64_t end = g_trace_next.load();
655    const uint64_t n = end < 160 ? end : 160;
656    std::fprintf(f, "strata verify trace (#649): the last %llu handshake events (host clock, us before the last; "
657                    "words: seq = GPU rang, flag = CPU served, A = plan, B = copies)\n", (unsigned long long) n);
658    const int64_t t_last = n ? g_trace_ring[(end - 1) % kTraceN].t_ns : 0;
659    for (uint64_t i = end - n; i < end; ++i) {
660        const TraceEv& e = g_trace_ring[i % kTraceN];
661        if (e.what == nullptr) continue;
662        std::fprintf(f, "  %10.1f %-20s v%p window %lld step %lld layer %lld aux %lld | seq %u flag %u A %u B %u\n",
663                     (double) (t_last - e.t_ns) / 1000.0, e.what, e.who, (long long) e.window, (long long) e.step,
664                     (long long) e.layer, (long long) e.aux, e.seq, e.flag, e.a, e.b);
665    }
666    if (trace_h_ == nullptr || g_ == nullptr) return;
667    // the breadcrumbs: every stamp point the GPU passed in this window (ns of the GPU clock after the window's first)
668    unsigned long long t0 = ~0ull;
669    for (size_t i = 0; i < trace_n_; ++i) {
670        const unsigned long long t = *(const volatile unsigned long long*) (trace_h_ + i);
671        if (t != 0 && t < t0) t0 = t;
672    }
673    if (t0 == ~0ull) {
674        std::fprintf(f, "strata verify trace: no GPU breadcrumb in this window (the GPU never started it)\n");
675        return;
676    }
677    int64_t last_l = -1;
678    for (int64_t l = 0; l <= g_->n_layers; ++l)
679        for (int i = 0; i < kProfPer; ++i)
680            for (int grp = 0; grp < 2; ++grp)
681                if (trace_h_[(size_t) ((l * kProfPer + i) * 2 + grp)] != 0) last_l = l;
682    std::fprintf(f, "strata verify trace: GPU breadcrumbs (us after the window's first), the GPU got as far as layer "
683                    "%lld:\n", (long long) last_l);
684    for (int64_t l = 0; l <= g_->n_layers; ++l) {   // T-TRI: every layer's wait(33-32) + compute(34-33), grp=0 (us)
685        const unsigned long long t32 = trace_h_[((l * kProfPer + 32) * 2 + 0)];
686        const unsigned long long t33 = trace_h_[((l * kProfPer + 33) * 2 + 0)];
687        const unsigned long long t34 = trace_h_[((l * kProfPer + 34) * 2 + 0)];
688        std::fprintf(f, "  T-TRI l=%2lld wait=%.1f us compute=%.1f us (32=%llu 33=%llu 34=%llu)\n",
689                     (long long) l, (double)(t33 - t32) / 1000.0, (double)(t34 - t33) / 1000.0,
690                     t32, t33, t34);
691    }
692    for (int64_t l = std::max<int64_t>(0, last_l - 2); l <= std::min<int64_t>(g_->n_layers, last_l + 1); ++l)
693        for (int grp = 0; grp < 2; ++grp) {
694            std::string line;
695            char b[64];
696            for (int i = 0; i < kProfPer; ++i) {
697                const unsigned long long t = trace_h_[(size_t) ((l * kProfPer + i) * 2 + grp)];
698                if (t == 0) continue;
699                std::snprintf(b, sizeof b, " %s(%d)=%.1f", names[i], i, (double) (t - t0) / 1000.0);
700                line += b;
701            }
702            if (!line.empty())
703                std::fprintf(f, "  layer %lld group %d:%s\n", (long long) l, grp, line.c_str());
704        }
705    std::fflush(f);
706}
707
708void Verifier::diag(std::FILE* f) const {
709    auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; };
710    // #251: outside a verify stage these are the LAST window's numbers (it finished), not the stalled work's
711    const char* where = progress().where.load();
712    const bool current = where != nullptr && std::strncmp(where, "verify window", 13) == 0;
713    std::fprintf(f, "  verify window%s: %d tokens at position %lld, host at layer step %u; the GPU rang %u; flags: "
714                    "served %u, plan (A) %u, copies (B) %u\n", current ? "" : " (last window, not the current stage)",
715                 last_t_, (long long) last_pos0_, cur_layer_ + 1, rd(h_seq_), rd(h_flag_), rd(h_flagA_), rd(h_flagB_));
716    trace_dump(f);   // #649: STRATA_VERIFY_TRACE=1 only
717}
718
719
720Verifier::~Verifier() {
721#if defined(STRATA_GPU_METAL)
722    strata::metal_engine::window_destroy(metal_);
723    metal_ = nullptr;
724#endif
725    const Verifier* self = this;
726    g_diag_verifier.compare_exchange_strong(self, nullptr);
727    for (auto& slot : g_live) {
728        Verifier* me = this;
729        slot.compare_exchange_strong(me, nullptr);
730    }
731    if (cs_) cudaStreamSynchronize(cs_);
732    if (sh_cs_) cudaStreamSynchronize(sh_cs_);
733    if (prof_on_) {   // knife-0 A: the per-window segment table at exit (STRATA_VERIFY_PROFILE=1; no compute change)
734        const std::string prof_report = profile_by_t_report();
735        if (!prof_report.empty()) std::fprintf(stderr, "PROF-T %s", prof_report.c_str());
736    }
737    for (auto& row : exec_)
738        for (auto& e : row)
739            if (e) cudaGraphExecDestroy(e);
740    for (auto& row : exec_nr_)
741        for (auto& e : row)
742            if (e) cudaGraphExecDestroy(e);
743    if (commit_exec_) cudaGraphExecDestroy(commit_exec_);
744    for (auto& kv : exec_bm_)
745        if (kv.second) cudaGraphExecDestroy(kv.second);
746    for (auto& kv : commit_bm_)
747        if (kv.second) cudaGraphExecDestroy(kv.second);
748    if (arena_b_) cudaFree(arena_b_);
749    if (h_commitb_) cudaFreeHost(h_commitb_);
750    for (auto* m : {&save_bm_, &dcommit_bm_})
751        for (auto& kv : *m)
752            if (kv.second) cudaGraphExecDestroy(kv.second);
753    if (dc_arena_) cudaFree(dc_arena_);
754    if (h_commitd_) cudaFreeHost(h_commitd_);
755    if (qcnt_) cudaFree(qcnt_);
756    if (d_spec_) cudaFree(d_spec_);
757    if (tap_file_) std::fclose(tap_file_);
758#if !defined(STRATA_GPU_METAL)   // (on Metal tap_dev_ is the window's unified-memory buffer, not an allocation of this object)
759    if (tap_dev_) cudaFree(tap_dev_);
760#endif
761    if (tap_scratch_) cudaFree(tap_scratch_);
762    if (h_tap_) cudaFreeHost(h_tap_);
763    if (logit_bias_device_) cudaFree(logit_bias_device_);
764    for (float* b : slot_bias_dev_) if (b) cudaFree(b);
765    if (slot_hist_d_) cudaFree(slot_hist_d_);
766    if (cs_ && cs_ != ext_stream_) cudaStreamDestroy(cs_);   // set_stream: the stage's stream, shared, not ours
767    if (sh_cs_) cudaStreamDestroy(sh_cs_);
768    if (copy_) { cudaStreamSynchronize(copy_); cudaStreamDestroy(copy_); }
769    if (side_) cudaStreamDestroy(side_);
770    if (side2_) cudaStreamDestroy(side2_);
771    for (cudaEvent_t e : {mfork_, mjoin_, pfork_, pjoin_})
772        if (e) cudaEventDestroy(e);
773    if (commit_done_) cudaEventDestroy(commit_done_);
774    if (ev_done_) cudaEventDestroy(ev_done_);
775    if (ev_commit_) cudaEventDestroy(ev_commit_);
776    if (prof_pin_) cudaFreeHost(prof_pin_);
777    if (ev_fork_) cudaEventDestroy(ev_fork_);
778    if (ev_join_) cudaEventDestroy(ev_join_);
779    if (ev_hq_) cudaEventDestroy(ev_hq_);
780    for (cudaStream_t s : df_side_)
781        if (s) cudaStreamDestroy(s);
782    if (df_fork_) cudaEventDestroy(df_fork_);
783    for (cudaEvent_t e : df_join_)
784        if (e) cudaEventDestroy(e);
785    if (arena_) cudaFree(arena_);
786    if (hcount_d_) cudaFree(hcount_d_);
787    void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_,
788                     h_flagA_, h_plan_, h_flagB_, h_plan_err_, h_nf_, herr_h_, hdrop_h_, h_bal_, h_latxlq_};
789    for (void* h : hosts)
790        if (h) cudaFreeHost(h);
791}
792
793int Verifier::tap_total() const {
794    int n = 0;
795    if (g_ == nullptr) return 0;
796    for (int l : tap_req_) if (l >= 0 && l < g_->n_layers - 1) ++n;
797    return n;
798}
799
800bool Verifier::tapping_chain() const {
801    if (g_ == nullptr || tap_req_.empty()) return false;
802    int have = 0;
803    for (const Verifier* v = this; v != nullptr; v = v->next_) {
804        have += (int) v->tap_layers_.size();
805        if (v->tap_layers_.size() > 0 && !v->tap_on_) return false;
806        if (v->le_ >= g_->n_layers) break;
807    }
808    return have == tap_total();
809}
810
811bool Verifier::gather_taps_host(float* dst, int row0, int rows, std::string& err) {
812    const int64_t N = g_->n_embd;
813    const int nt_all = tap_total();
814    for (Verifier* v = this; v != nullptr; v = v->next_) {
815        if (!v->tap_layers_.empty() && v->tap_on_) {
816            const OnDevice on_stage(v->device_);
817            if (v->tap_cs_ == nullptr &&
818                (cudaStreamCreateWithFlags(&v->tap_cs_, cudaStreamNonBlocking) != cudaSuccess ||
819                 cudaEventCreateWithFlags(&v->tap_ev_, cudaEventDisableTiming) != cudaSuccess)) {
820                err = "verify: the tap gather stream could not be created";
821                return false;
822            }
823            int slot0 = 0;
824            for (int l : tap_req_) if (l >= 0 && l < g_->n_layers - 1 && l < v->lb_) ++slot0;
825            const int64_t nv = (int64_t) v->tap_layers_.size();
826            for (int r = 0; r < rows; ++r) {
827                const cudaError_t ce = cudaMemcpyAsync(dst + ((size_t) r * (size_t) nt_all + (size_t) slot0) * (size_t) N,
828                                                       v->tap_dev_ + (size_t) (row0 + r) * (size_t) (nv * N), (size_t) (nv * N) * 4,
829                                                       cudaMemcpyDeviceToHost, v->tap_cs_);
830                if (ce != cudaSuccess) { err = std::string("verify: the tap gather to the host: ") + cudaGetErrorString(ce); return false; }
831            }
832            if (cudaStreamSynchronize(v->tap_cs_) != cudaSuccess) { err = "verify: the tap gather to the host did not finish"; return false; }
833        }
834        if (v->le_ >= g_->n_layers) break;
835    }
836    return true;
837}
838
839bool Verifier::gather_taps(float* landing, int landing_device, int row0, int rows, int dst_row0, cudaStream_t wait_stream, std::string& err) {
840    const int64_t N = g_->n_embd;
841    const int nt_all = tap_total();
842    for (Verifier* v = this; v != nullptr; v = v->next_) {
843        if (!v->tap_layers_.empty() && v->tap_on_) {
844            const OnDevice on_stage(v->device_);
845            if (v->tap_cs_ == nullptr &&
846                (cudaStreamCreateWithFlags(&v->tap_cs_, cudaStreamNonBlocking) != cudaSuccess ||
847                 cudaEventCreateWithFlags(&v->tap_ev_, cudaEventDisableTiming) != cudaSuccess)) {
848                err = "verify: the tap gather stream could not be created";
849                return false;
850            }
851            // this stage's first tap among all of them: the requested layers below its first layer
852            int slot0 = 0;
853            for (int l : tap_req_) if (l >= 0 && l < g_->n_layers - 1 && l < v->lb_) ++slot0;
854            const int64_t nv = (int64_t) v->tap_layers_.size();
855            for (int r = 0; r < rows; ++r) {
856                const float* src = v->tap_dev_ + (size_t) (row0 + r) * (size_t) (nv * N);
857                float* dst = landing + ((size_t) (dst_row0 + r) * (size_t) nt_all + (size_t) slot0) * (size_t) N;
858                const cudaError_t ce = v->device_ == landing_device
859                    ? cudaMemcpyAsync(dst, src, (size_t) (nv * N) * 4, cudaMemcpyDeviceToDevice, v->tap_cs_)
860                    : cudaMemcpyPeerAsync(dst, landing_device, src, v->device_, (size_t) (nv * N) * 4, v->tap_cs_);
861                if (ce != cudaSuccess) { err = std::string("verify: the tap gather copy: ") + cudaGetErrorString(ce); return false; }
862            }
863            if (cudaEventRecord(v->tap_ev_, v->tap_cs_) != cudaSuccess) { err = "verify: the tap gather event"; return false; }
864            const OnDevice on_dst(landing_device);
865            if (cudaStreamWaitEvent(wait_stream, v->tap_ev_, 0) != cudaSuccess) { err = "verify: the drafter stream cannot wait on a stage's taps"; return false; }
866        }
867        if (v->le_ >= g_->n_layers) break;
868    }
869    return true;
870}
871
872// STRATA_TAP_FILE: one record per row of the window: int32 position, int32 input token, then n_taps x n_embd floats
873void Verifier::tap_write(int T, const int32_t* tokens, int64_t pos0) {
874    if (tap_file_ == nullptr) return;
875    const size_t per = tap_layers_.size() * (size_t) g_->n_embd;
876    for (int t = 0; t < T; ++t) {
877        const int32_t hdr[2] = {(int32_t) (pos0 + t), tokens[t]};
878        std::fwrite(hdr, sizeof hdr, 1, tap_file_);
879        std::fwrite(h_tap_ + (size_t) t * per, sizeof(float), per, tap_file_);
880    }
881    std::fflush(tap_file_);
882}
883
884bool Verifier::set_logit_bias(const std::vector<float>& bias, std::string& err) {
885    if (next_ && !next_->set_logit_bias(bias, err)) return false;
886    if (le_ >= 0 && le_ < g_->n_layers) return true;   // (the Metal window never sets le_: -1 = the last stage)
887    const OnDevice on_device(device_);
888    if (!bias.empty() && bias.size() != (size_t) n_vocab_) {
889        err = "logit_bias vocabulary size mismatch"; return false;
890    }
891    if (bias != logit_bias_host_ && !bias.empty()) {
892        const size_t bytes = bias.size() * sizeof(float);
893        if ((!logit_bias_device_ && cudaMalloc((void**) &logit_bias_device_, bytes) != cudaSuccess) ||
894            cudaMemcpy(logit_bias_device_, bias.data(), bytes, cudaMemcpyHostToDevice) != cudaSuccess) {
895            err = "cannot upload logit_bias"; return false;
896        }
897    }
898    logit_bias_host_ = bias;
899    sampling_.logit_bias = bias.empty() ? nullptr : logit_bias_device_;
900    return true;
901}
902
903bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& ss, const VerifyHits& hits,
904                    const NativeHead* head, int max_t, std::string& err) {
905    g_diag_verifier.store(this);
906    diag_verify_fn().store(&diag_active_verifier);
907    for (auto& slot : g_live) {
908        Verifier* none = nullptr;
909        if (slot.load() == this || slot.compare_exchange_strong(none, this)) break;
910    }
911    release_gpu_fn().store(&release_live_verifiers);
912    release_gpu_within_fn().store(&release_live_verifiers_within);
913    cudaGetDevice(&device_);   // a layer split's stage on another GPU: its streams, graphs and buffers live there
914    rr_stats_ = route_resident_cfg().stats_on(device_);   // STRATA_ROUTE_RESIDENT: this GPU's counters, outside graph capture
915    strata::kernels::fused_gr_check();   // once per card: which bitwise-equal hyper-connection read runs there
916    strata::kernels::fused_gr_persist_init();   // opt-in STRATA_HC_PERSIST=1 (HIP)
917    wt_ = &wt;
918    g_ = &g;
919    ss_ = &ss;
920    hits_ = hits;
921    head_ = head;
922    max_t_ = max_t;
923    sampling_.greedy = true;      // a fresh verifier samples greedily until set_sampling says otherwise
924    sampling_.temperature = 0.0f;
925#if defined(STRATA_GPU_METAL)
926    if (metal_ == nullptr) metal_ = strata::metal_engine::window_create();
927    if (!strata::metal_engine::window_init(metal_, g, ss, max_t, ss.qsa_states[ss.qsa_primary()].max_cells, &n_vocab_, err)) return false;
928    if (!tap_req_.empty()) {   // DFlash2: the Metal window writes the taps itself (metal/src/engine/dflash2.inc); tap_dev() is its unified-memory buffer
929        const float* tp = nullptr;
930        if (!strata::metal_engine::window_taps(metal_, tap_req_, &tp, err)) return false;
931        tap_layers_ = tap_req_;
932        tap_dev_ = const_cast<float*>(tp);
933        tap_on_ = true;
934    }
935    return true;
936#endif
937    // a window past kVerifyMaxT tokens runs as two token groups of at most kVerifyMaxT (record_window): the CPU experts
938    // see one group at a time (and take a wider group as jobs of at most cpu::MAXT tokens)
939    if (max_t < 2 || max_t > strata::kernels::kVerifyLongT) {
940        err = "verify: the window must hold 2.." + std::to_string(strata::kernels::kVerifyLongT) + " tokens";
941        return false;
942    }
943    if (hits.d_res == nullptr || hits.cache_base == nullptr || hits.blob <= 0) {
944        err = "verify: needs the profile-filled VRAM expert tier (--expert-profile and --expert-cache); with "
945              "--expert-cache auto, no VRAM was left for it - the 'no VRAM is left for the expert cache' line above "
946              "says how much is short and what makes room (a smaller --max-context, --kv q4_0, setup --draft-vocab en, "
947              "images on the CPU)";
948        return false;
949    }
950    std::string why;
951    if (!layer_verify_compatible(why)) {
952        err = "verify: " + why + " (the verify window reproduces the default native decode path)";
953        return false;
954    }
955    if (!strata::kernels::fused_gr_supported(g.n_embd, g.hc, g.hc_lr) || ss.k != (int) strata::core::kCompiledGeometry.n_expert_used || g.ssm_state_size != 128 ||
956        g.ssm_d_conv != 4) {
957        err = "verify: geometry differs from the artifact's";
958        return false;
959    }
960    if (le_ < 0) le_ = g.n_layers;
961    if (lb_ < 0 || lb_ >= le_ || le_ > g.n_layers || (lb_ > 0 && hand_in_ == nullptr) ||
962        (le_ < g.n_layers && hand_out_ == nullptr)) {
963        err = "verify: the stage's layer range or its hand-off buffers are wrong";
964        return false;
965    }
966    const WeightRef* wo = wt.find("output.weight");
967    if (wo == nullptr) { err = "verify: output.weight is missing"; return false; }
968    n_vocab_ = wo->ne1;
969
970    const strata::kernels::QsaShapes s = shapes_of(g);
971    cap_ = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);
972    max_blocks_ = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2;
973    attn_scratch_floats_ = (int64_t) strata::kernels::qsa_decode_attn_scratch_floats(cap_, s);
974
975    const uint64_t T = (uint64_t) max_t, N = (uint64_t) g.n_embd, HC = (uint64_t) g.hc, K = (uint64_t) ss.k;
976    const uint64_t C = (uint64_t) g.ssm_conv_channels, ZV = (uint64_t) g.ssm_value_dim, HV = (uint64_t) g.ssm_v_heads;
977    const uint64_t NH = (uint64_t) g.n_head, HD = (uint64_t) g.head_dim, NKV = (uint64_t) g.n_head_kv;
978    const uint64_t IQ = (uint64_t) g.idx_q_heads, ID = (uint64_t) g.idx_key_dim;
979    const uint64_t nG = (uint64_t) g.n_gdn_layers(), nQ = (uint64_t) g.n_qsa_layers();
980    const uint64_t HS = (uint64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM;
981    const uint64_t TS = (uint64_t) (s.idx_block - 1) * ID;
982    const int max_in = (int) std::max<uint64_t>(std::max<uint64_t>(N, ZV), NH * HD);
983
984    // latent MoE: the A pack's native expert rows are ELL wide instead of n_embd.
985    {
986        const auto& lay0 = strata::kernels::cpu::expert_layout();
987        latent_ = lay0.native && !lay0.fmt.empty() && lay0.fmt[0].n_embd != (int64_t) N;
988        if (latent_) {
989            lat_H_ = (int64_t) N; lat_ELL_ = lay0.fmt[0].n_embd; lat_I_ = lay0.fmt[0].n_ff;
990            lat_G_ = 8; lat_E_ = (int) lay0.n_expert; lat_K_ = (int) K;
991            const char* dense = std::getenv("STRATA_LATENT_DENSE");
992            if (dense == nullptr || dense[0] == 0) {
993                err = "verify: latent A layout needs STRATA_LATENT_DENSE=<latent_dense_q8.bin>";
994                return false;
995            }
996            if (!lat_dense_.open(dense, g.n_layers, lat_G_, (int64_t) N, lat_ELL_, err)) {
997                err = "verify latent dense: " + err;
998                return false;
999            }
1000            lat_fmt_ = lat_dense_.fmt();   // Q4DU: every D/U kernel call below derives from it
1001            const char* apack = std::getenv("STRATA_LATENT_A");
1002            lat_blob_ = (int64_t) lay0.max_blob;
1003            if (apack == nullptr || apack[0] == 0) {
1004                err = "verify: latent A layout needs STRATA_LATENT_A=<latent_a_pack/experts.bin>";
1005                return false;
1006            }
1007            if (!lat_a_.open(apack, g.n_layers, lat_E_, lat_blob_, err)) {
1008                err = "verify latent A: " + err;
1009                return false;
1010            }
1011            {   // labels.bin beside the A pack: one int32 group label per (layer, expert), rows of E
1012                std::string lp = apack;
1013                const size_t slash = lp.find_last_of('/');
1014                lp = slash == std::string::npos ? std::string("labels.bin") : lp.substr(0, slash + 1) + "labels.bin";
1015                std::FILE* lf = std::fopen(lp.c_str(), "rb");
1016                if (lf == nullptr) { err = "verify latent: " + lp + " missing"; return false; }
1017                lat_labels_.resize((size_t) g.n_layers * (size_t) lat_E_);
1018                const size_t got = std::fread(lat_labels_.data(), sizeof(int32_t), lat_labels_.size(), lf);
1019                std::fclose(lf);
1020                if (got != lat_labels_.size()) { err = "verify latent: " + lp + " is too small"; return false; }
1021                for (const int32_t v : lat_labels_)
1022                    if (v < 0 || v >= lat_G_) { err = "verify latent: bad group label " + std::to_string(v); return false; }
1023            }
1024        }
1025    }
1026
1027    if (latent_) {
1028        if (lat_d_shared_ == nullptr) {
1029            const auto& shared = strata::core::latent_shared();
1030            lat_d_shared_ = shared.d;
1031            lat_u_shared_ = shared.u;
1032            lat_first_layer_ = shared.d != nullptr ? shared.first_layer : 0;
1033            lat_end_layer_ = shared.d != nullptr ? shared.end_layer : -1;
1034        }
1035        if (lat_d_shared_ != nullptr && (lat_u_shared_ == nullptr || lat_first_layer_ < 0 || lb_ < lat_first_layer_ ||
1036                le_ > (lat_end_layer_ < 0 ? g.n_layers : lat_end_layer_))) {
1037            err = "verify: shared latent tables do not cover the stage";
1038            return false;
1039        }
1040    }
1041
1042    // ---- mapped staging
1043    bool ok = mapped(T * 4, (void**) &h_tok_, (void**) &m_tok_) &&
1044              mapped(T * strata::kernels::kStepCount * 4, (void**) &h_step_, (void**) &m_step_) &&
1045              mapped(T * (NH + NKV + IQ) * 4, (void**) &h_pos_, (void**) &m_pos_) &&
1046              mapped((2 + T) * 4 + 16, (void**) &h_commit_, (void**) &m_commit_) &&
1047              mapped(T * N * 4, (void**) &h_ple_, (void**) &m_ple_) &&
1048              mapped(T * 4 + 16, (void**) &h_out_, (void**) &m_out_) &&
1049              mapped((size_t) strata::kernels::kVerifyLongT * strata::kernels::kNonfiniteBlocks * 4, (void**) &h_nf_,
1050                     (void**) &m_nf_) &&
1051              mapped(T * N * 4, (void**) &h_x_, (void**) &m_x_) &&
1052              mapped(T * K * 4, (void**) &h_ids_, (void**) &m_ids_) &&
1053              mapped(T * K * 4, (void**) &h_w_, (void**) &m_w_) &&
1054              mapped(64, (void**) &h_seq_, (void**) &m_seq_) &&
1055              mapped(64, (void**) &h_flag_, (void**) &m_flag_) &&
1056              mapped(64, (void**) &h_flagA_, (void**) &m_flagA_) &&
1057              mapped(64, (void**) &h_flagB_, (void**) &m_flagB_) &&
1058              mapped(64, (void**) &h_plan_err_, (void**) &m_plan_err_) &&
1059              mapped(T * K * N * 4, (void**) &h_ymiss_, (void**) &m_ymiss_);
1060    if (!ok) { err = "verify: mapped staging allocation failed " + strata::core::pin_exhausted_hint(); return false; }
1061    // DFlash2 taps: set_taps (the drafter) or STRATA_TAP_FILE (the research dump); off, and nothing is allocated or captured, otherwise
1062    const char* tap_path = std::getenv("STRATA_TAP_FILE");
1063    if (tap_path != nullptr && tap_path[0] == '\0') tap_path = nullptr;
1064    // A layer split's stage taps the requested layers inside its own range [lb_, le_) into its own buffer [max_t][its taps][n_embd];
1065    // gather_taps() lands every stage's rows on the drafter's card.  The research dump (STRATA_TAP_FILE) needs the whole model in one verifier.
1066    const bool tap_whole = lb_ == 0 && le_ == g.n_layers;
1067    if (!tap_whole) tap_path = nullptr;
1068    if (tap_path != nullptr || !tap_req_.empty()) {
1069        tap_layers_.clear();
1070        if (tap_path == nullptr) {
1071            for (int l : tap_req_) if (l >= lb_ && l < le_ && l < g.n_layers - 1) tap_layers_.push_back(l);
1072        } else {
1073            const char* tl = std::getenv("STRATA_TAP_LAYERS");
1074            std::string list = tl != nullptr && tl[0] != '\0' ? tl : "5,15,25,35,45";
1075            for (size_t i = 0; i < list.size();) {
1076                const size_t j = list.find(',', i);
1077                const int l = std::atoi(list.substr(i, j == std::string::npos ? std::string::npos : j - i).c_str());
1078                if (l >= 0 && l < g.n_layers - 1) tap_layers_.push_back(l);
1079                if (j == std::string::npos) break;
1080                i = j + 1;
1081            }
1082        }
1083        tap_slot_.assign((size_t) g.n_layers, -1);
1084        for (size_t i = 0; i < tap_layers_.size(); ++i) tap_slot_[(size_t) tap_layers_[i]] = (int) i;
1085        const size_t nt = tap_layers_.size();
1086        if (nt == 0 && tap_path == nullptr) {
1087            // a stage that holds none of the tapped layers: nothing to keep, nothing captured
1088        } else
1089        if (nt == 0 || cudaMalloc((void**) &tap_dev_, (size_t) T * nt * N * 4) != cudaSuccess ||
1090            (tap_path != nullptr && (cudaMalloc((void**) &tap_scratch_, (size_t) HC * N * 4) != cudaSuccess ||
1091                                     !mapped((size_t) T * nt * N * 4, (void**) &h_tap_, (void**) &m_tap_)))) {
1092            err = "verify: the DFlash2 tap buffers could not be allocated";
1093            return false;
1094        }
1095        if (tap_path != nullptr) {
1096            tap_file_ = std::fopen(tap_path, "wb");
1097            if (tap_file_ == nullptr) { err = std::string("verify: cannot write STRATA_TAP_FILE ") + tap_path; return false; }
1098            const int32_t hdr[4] = {0x50415453 /* 'STAP' */, 1, (int32_t) N, (int32_t) nt};
1099            std::fwrite(hdr, sizeof hdr, 1, tap_file_);
1100            for (int l : tap_layers_) { const int32_t v = l; std::fwrite(&v, sizeof v, 1, tap_file_); }
1101            std::fprintf(stderr, "strata: STRATA_TAP_FILE %s: %zu taps of %lld floats per row\n", tap_path, nt, (long long) N);
1102        }
1103        tap_on_ = true;
1104    }
1105    if (bal_ != nullptr) {   // set_pcie_balance: four stamp words per (layer, group)
1106        if (!mapped((size_t) g.n_layers * 2 * 4 * 8, (void**) &h_bal_, (void**) &m_bal_)) {
1107            err = "verify: mapped balance stamps allocation failed";
1108            return false;
1109        }
1110        bal_p_.assign((size_t) g.n_layers * 2, 0.0);
1111        bal_nc_.assign((size_t) g.n_layers * 2, 0);
1112        bal_np_.assign((size_t) g.n_layers * 2, 0);
1113        bal_ok_.assign((size_t) g.n_layers * 2, 0);
1114        bal_->on = true;
1115    }
1116    // the GPU plan: counts(4) | start(cap+1) | dst(cap) | tok(cap) | pad | ptr(cap u64) | ptr2(cap u64) | start2(cap+1)
1117    // | pad | dst2(kStagingBlobs u64)
1118    {
1119        const int64_t cap = (int64_t) (T * K);
1120        const int64_t i32 = 4 + (cap + 1) + cap + cap;
1121        const int64_t ptr_off = (i32 + 1) & ~1ll;
1122        dst2_off_ = (ptr_off + 4 * cap + (cap + 1) + 1 + 1) & ~1ll;
1123        plan_i32_ = dst2_off_ + 2 * kStagingBlobs;
1124        if (!mapped((size_t) plan_i32_ * 4 * 2 + 64, (void**) &h_plan_, (void**) &m_plan_)) {
1125            err = "verify: mapped plan allocation failed " + strata::core::pin_exhausted_hint();
1126            return false;
1127        }
1128        sink_.counts = h_plan_;
1129        sink_.start = h_plan_ + 4;
1130        sink_.dst = sink_.start + cap + 1;
1131        sink_.tok = sink_.dst + cap;
1132        sink_.ptr = (unsigned long long*) (h_plan_ + ptr_off);
1133        sink_.ptr2 = sink_.ptr + cap;
1134        sink_.start2 = h_plan_ + ptr_off + 4 * cap;
1135        sink_.dst2 = (unsigned long long*) (h_plan_ + dst2_off_);
1136        sink_.cap = cap;
1137        sink_.publish = &Verifier::publish_plan;
1138        sink_.fetch = &Verifier::fetch_dma;
1139        sink_.ctx = this;
1140    }
1141    if (latent_) {   // edge0 CPU share: the D stage's f32 xl rows land in mapped host memory (row t*G + g); the
1142        // pool quantizes them into the native Q8_0 A activation on the host.  One cudaHostAlloc, OUTSIDE the
1143        // carve so the count pass never touches it (running it inside ran the alloc twice and leaked the first).
1144        if (!mapped((size_t) T * (size_t) lat_G_ * (size_t) lat_ELL_ * 4, (void**) &h_latxlq_, (void**) &m_latxlq_) ||
1145            !mapped((size_t) T * (size_t) lat_G_ * ((size_t) lat_ELL_ / 32) * 34, (void**) &m_latact0_, (void**) &m_latact0_) ||
1146            !mapped(64, (void**) &h_xlseq_, (void**) &m_xlseq_)) {
1147            err = "verify: the latent xl mapped buffer failed"; return false;
1148        }
1149        if (cudaMalloc(&lat_act0_dev_, (size_t) T * (size_t) lat_G_ * ((size_t) lat_ELL_ / 32) * 34) != cudaSuccess) {
1150            err = "verify: the latent act0 device scratch failed"; return false;
1151        }
1152    }
1153
1154    // APR: the rotated copy of the expert input (nat_xr_, T x N floats) only where a layer's gate/up is
1155    // Hadamard-folded; its one reader is that layer's f.had_gu branch in the expert-input step below
1156    bool had_gu_any = false;
1157    {
1158        const auto& lay = strata::kernels::cpu::expert_layout();
1159        for (size_t l = 0; lay.native && l < lay.fmt.size(); ++l) had_gu_any = had_gu_any || lay.fmt[l].had_gu;
1160    }
1161    // ---- the device arena: the same sequence counted, then carved
1162    auto carve = [&](Bump& b) {
1163        tok_ = b.take<int32_t>(T); step_ = b.take<int32_t>(T * strata::kernels::kStepCount);
1164        pos_ = b.take<int32_t>(T * (NH + NKV + IQ)); commit_ = b.take<int32_t>(2 + T);
1165        ple_ = b.take<float>(T * N); emb_ = b.take<float>(T * N); R_ = b.take<float>(T * HC * N);
1166        mixed_ = b.take<float>(T * N); bo_ = b.take<float>(T * N);
1167        inj_ = b.take<float>(T * HC); inj2_ = b.take<float>(T * HC);
1168        lo_ = b.take<float>(T * (uint64_t) g.hc_lr); rs_ = b.take<float>(T * HC); xn_ = b.take<float>(T * HC * N);
1169        // the q8_1 activations of one token group (or one column chunk of the head): at most kVerifyMaxT columns
1170        const int qcols = (int) std::min<uint64_t>(T, (uint64_t) strata::kernels::kVerifyMaxT);
1171        xq_ = b.take<uint8_t>(strata::kernels::native_q8_1_bytes(max_in, qcols));
1172        sh_xq_ = b.take<uint8_t>(strata::kernels::native_q8_1_bytes(max_in, qcols));
1173        xil_ = b.take<uint8_t>(strata::kernels::native_q8_1_il_bytes(max_in, std::max(4, qcols)));   // 147-verify: 5-8 columns too
1174        qkv_L_ = b.take<float>(nG * T * C); h_L_ = b.take<float>(nG * T * C);
1175        gate_L_ = b.take<float>(nG * T * HV); beta_L_ = b.take<float>(nG * T * HV);
1176        z_ = b.take<float>(T * ZV); y_ = b.take<float>(T * ZV); y_dummy_ = b.take<float>(T * ZV);
1177        qfull_ = b.take<float>(T * NH * 2 * HD); qcur_ = b.take<float>(T * NH * HD);
1178        kcur_ = b.take<float>(T * NKV * HD); vcur_ = b.take<float>(T * NKV * HD);
1179        idx_raw_L_ = b.take<float>(nQ * T * ID); qidx_ = b.take<float>(T * IQ * ID);
1180        scores_ = b.take<float>(T * (uint64_t) max_blocks_); sel_ = b.take<int32_t>(T * (uint64_t) cap_);
1181        if (select_long_on() && strata::kernels::qsa_topk_multi_scratch_ints(T) > 0)   // STRATA_SELECT_LONG only
1182            topk_scratch_ = b.take<int32_t>((uint64_t) strata::kernels::qsa_topk_multi_scratch_ints(T));
1183        attn_ = b.take<float>(T * NH * HD); attn32_ = b.take<float>(T * NH * HD);
1184        attn_scratch_ = b.take<float>(T * (uint64_t) attn_scratch_floats_);
1185        tail_snap_ = b.take<float>(nQ * TS);
1186        logits_ = b.take<float>(T * (uint64_t) g.n_expert); w_ = b.take<float>(T * K); ids_ = b.take<int32_t>(T * K);
1187        shared_ = b.take<float>(T * N); parts_ = b.take<float>(T * K * N); hit_out_ = b.take<float>(T * K * N);
1188        hit_slot_ = b.take<int32_t>(T * K); hit_dst_ = b.take<int32_t>(T * K); hit_count_ = b.take<int32_t>(4);
1189        plan_ = b.take<int32_t>(2 * ((uint64_t) plan_i32_ + 16));
1190        staging_ = b.take<uint8_t>((uint64_t) (latent_ ? 8 : 1) * kStagingBlobs * strata::kernels::cpu::expert_layout().max_blob);
1191        hit_xq_ = b.take<uint8_t>(T * (N / 32) * 34); hit_xs_ = b.take<float>(T * (N / 32));
1192        nat_xq_ = b.take<uint8_t>(T * (N / 32) * 36);
1193        nat_xr_ = had_gu_any ? b.take<float>(T * N) : nullptr;
1194        hit_scratch_ = b.take<uint8_t>(std::max<uint64_t>(
1195            strata::kernels::moe_hit_grouped_scratch_bytes((int64_t) (T * K), g.n_embd, g.n_ff),
1196            strata::kernels::native_expert_scratch_bytes((int64_t) (T * K), g.n_ff)));
1197        head_mixed_ = b.take<float>(T * N); head_inj_ = b.take<float>(HC);
1198        sh_bf16_ = b.take<uint16_t>(T * N); sh_gate_ = b.take<float>(T * (uint64_t) g.n_ff);
1199        sh_up_ = b.take<float>(T * (uint64_t) g.n_ff); sh_g_ = b.take<float>(T + 4);
1200        head_logits_ = b.take<float>(T * (uint64_t) n_vocab_);
1201        arg_scratch_ = b.take<uint8_t>(strata::kernels::argmax_rows_scratch_bytes((int) T));
1202        one_ = b.take<int32_t>(4);
1203        hist_snap_ = b.take<float>(T * HS);
1204        ple_key_ = b.take<float>(T * (uint64_t) strata::kernels::NG_HC_DIM); ple_val_ = b.take<float>(T * N);
1205        if (latent_) {
1206            const uint64_t LG = (uint64_t) lat_G_, LELL = (uint64_t) lat_ELL_;
1207            lat_xq_ = b.take<uint8_t>(T * (N / 32) * 36);
1208            lat_xlq_ = b.take<uint8_t>(T * LG * (LELL / 32) * 36);
1209            lat_uq_ = b.take<uint8_t>(T * K * (LELL / 32) * 36);
1210            hq_dev_ = b.take<uint8_t>(T * K * (LELL / 32) * 36);
1211            lat_xl_ = b.take<float>(T * LG * LELL);
1212            lat_yl_ = b.take<float>(T * K * LELL);
1213            // Shared tables cover this stage; the standalone arena keeps the full layer-major layout.
1214            if (lat_d_shared_ == nullptr) {
1215                lat_d_ = b.take<uint8_t>((uint64_t) g.n_layers * lat_dense_.d_bytes());
1216                lat_u_ = b.take<uint8_t>((uint64_t) g.n_layers * lat_dense_.u_bytes());
1217            } else {
1218                lat_d_ = const_cast<uint8_t*>(lat_d_shared_);
1219                lat_u_ = const_cast<uint8_t*>(lat_u_shared_);
1220            }
1221            // Q3_K colscale: allocate every layer's device 1/s vector NOW, in plain stream
1222            // context - the D stage's first call can otherwise land inside the verify
1223            // window's CUDA graph capture, and cudaMalloc is not permitted while capturing
1224            // (the serve-mode failure that killed engine instance 1 on 2026-11-07).
1225            for (int64_t l = 0; l < g.n_layers; ++l)
1226                if (strata::kernels::lat_gu_colscale_dev((int) l, (int) lat_ELL_) == nullptr &&
1227                    strata::kernels::lat_gu_colscale_host(l) != nullptr)
1228                    throw std::runtime_error("the column-scale vectors could not be uploaded");
1229        }
1230    };
1231    Bump count;
1232    carve(count);
1233    if (cudaMalloc(&arena_, count.used) != cudaSuccess) {
1234        err = "verify: the device arena (" + std::to_string(count.used >> 20) + " MiB) does not fit";
1235        return false;
1236    }
1237    cudaMemset(arena_, 0, count.used);
1238    if (hflag_out_d_ != nullptr && hcount_d_ == nullptr) {   // the overlapped split's hand-off counter
1239        if (cudaMalloc((void**) &hcount_d_, 64) != cudaSuccess) { err = "verify: hand-off counter allocation failed"; return false; }
1240        cudaMemset(hcount_d_, 0, 64);
1241        if (!mapped(64, (void**) &hdrop_h_, (void**) &hdrop_d_)) { err = "verify: hand-off test word allocation failed"; return false; }
1242    }
1243    if (hflag_in_d_ != nullptr && herr_h_ == nullptr &&
1244        !mapped(64, (void**) &herr_h_, (void**) &herr_d_)) { err = "verify: hand-off error word allocation failed"; return false; }
1245    if (g_trace && trace_h_ == nullptr) {   // #649: the breadcrumbs, mapped so they read while the GPU hangs
1246        trace_n_ = (size_t) (g.n_layers + 1) * kProfPer * 2;
1247        if (!mapped(trace_n_ * 8, (void**) &trace_h_, (void**) &trace_m_)) {
1248            (void) cudaGetLastError();
1249            trace_h_ = trace_m_ = nullptr;
1250            trace_n_ = 0;
1251        }
1252#if defined(STRATA_USE_HIP)
1253        std::fprintf(stderr, "strata verify trace (#649): on; coherent words %s, doorbell %s, HIP_HOST_COHERENT=%s "
1254                             "HSA_ENABLE_SDMA=%s GPU_MAX_HW_QUEUES=%s\n", g_coherent ? "explicit" : "default",
1255                     g_doorbell_store ? "stored" : "incremented", std::getenv("HIP_HOST_COHERENT") ? std::getenv("HIP_HOST_COHERENT") : "-",
1256                     std::getenv("HSA_ENABLE_SDMA") ? std::getenv("HSA_ENABLE_SDMA") : "-",
1257                     std::getenv("GPU_MAX_HW_QUEUES") ? std::getenv("GPU_MAX_HW_QUEUES") : "-");
1258#else
1259        std::fprintf(stderr, "strata verify trace (#649): on\n");
1260#endif
1261    }
1262    prof_on_ = std::getenv("STRATA_VERIFY_PROFILE") != nullptr;
1263    if (const char* rs = std::getenv("STRATA_ROUTE_STATS"); rs != nullptr && rs[0] == '1') {
1264        const size_t nrs = (size_t) 17 * (size_t) g.n_layers * 16;   // [T 0..16][layer][row 0..15]
1265        if (cudaMalloc((void**) &rs_dev_, nrs * 8) == cudaSuccess) {
1266            cudaMemset(rs_dev_, 0, nrs * 8);
1267            rs_on_ = true;
1268        } else {
1269            rs_dev_ = nullptr;
1270            cudaGetLastError();
1271        }
1272    }
1273    if (prof_on_) {
1274        const size_t np = (size_t) g.n_layers * kProfPer + 4;
1275        if (cudaMalloc((void**) &prof_, np * 8) != cudaSuccess) { prof_on_ = false; prof_ = nullptr; cudaGetLastError(); }
1276        else { cudaMemset(prof_, 0, np * 8); prof_h_.assign(np, 0); }
1277    }
1278    Bump real;
1279    real.base = (uint8_t*) arena_;
1280    carve(real);
1281    if (latent_ && lat_d_shared_ == nullptr) {   // the carved pointers are real now: one blocking init-time
1282        // upload, before any graph capture (with a shared pair there is nothing to upload)
1283        for (int64_t l = 0; l < g.n_layers; ++l) {
1284            const cudaError_t cd = cudaMemcpy(lat_d_ + (size_t) l * lat_dense_.d_bytes(), lat_dense_.d(l),
1285                                              lat_dense_.d_bytes(), cudaMemcpyHostToDevice);
1286            const cudaError_t cu = cd == cudaSuccess ? cudaMemcpy(lat_u_ + (size_t) l * lat_dense_.u_bytes(),
1287                                                                  lat_dense_.u(l), lat_dense_.u_bytes(),
1288                                                                  cudaMemcpyHostToDevice) : cd;
1289            if (cu != cudaSuccess) {
1290                err = "verify latent: the D/U upload failed at layer " + std::to_string(l) + " (" +
1291                      std::string(cudaGetErrorString(cu)) + ")";
1292                return false;
1293            }
1294        }
1295    }
1296    // the labels upload must not ride on the shared D/U pair: serve hands the pair to every verifier
1297    // (set_shared_latent), in which case lat_d_shared_ != nullptr and the block above is skipped -
1298    // the labels device copy is still required by latent_plan_rows / latent_u_grouped
1299    if (latent_) {
1300        const size_t lb = lat_labels_.size() * sizeof(int32_t);
1301        if (cudaMalloc((void**) &lat_labels_dev_, lb) != cudaSuccess ||
1302            cudaMemcpy(lat_labels_dev_, lat_labels_.data(), lb, cudaMemcpyHostToDevice) != cudaSuccess) {
1303            err = "verify latent: the labels upload failed";
1304            return false;
1305        }
1306    }
1307    {
1308        const int32_t one = 1;
1309        if (cudaMemcpy(one_, &one, sizeof one, cudaMemcpyHostToDevice) != cudaSuccess) {
1310            err = "verify: the arena could not be set";
1311            return false;
1312        }
1313    }
1314    {   // APR (prism.hadamard, hadamard.txt): the sign vectors on this device, before any graph capture
1315        had_sx_ = strata::kernels::hadamard_device_signs(strata::kernels::cpu::hadamard_signs((int) g.n_embd), (int) g.n_embd);
1316        had_sh_ = strata::kernels::hadamard_device_signs(strata::kernels::cpu::hadamard_signs((int) g.n_ff), (int) g.n_ff);
1317    }
1318    sink_.staging = (unsigned long long) staging_;
1319    sink_.staging_cap = kStagingBlobs;
1320    (void) TS;
1321    // STRATA_GRAPH_PRIO=1 (opt-in): the window's streams carry priorities that their captured kernel
1322    // nodes keep (the window graph is instantiated with cudaGraphInstantiateFlagUseNodePriority): the GDN gates / QSA
1323    // indexer branch (side_) at the device's highest, cs_ and side2_ in the middle, the shared expert (sh_cs_) at the
1324    // lowest (= the default).  The indexer chain's 1-block kernels are then dispatched ahead of the q GEMV's queued
1325    // blocks, and the shared expert behind the experts.  Unset: every stream at the default priority, as before.
1326    int gp_lo = 0, gp_hi = 0;
1327#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
1328    const bool gprio = graph_prio_on() && cudaDeviceGetStreamPriorityRange(&gp_lo, &gp_hi) == cudaSuccess && gp_lo != gp_hi;
1329    if (graph_prio_on() && !gprio) (void) cudaGetLastError();   // (only a failed range query's error: unset clears nothing)
1330#else
1331    const bool gprio = false;   // (HIP: the default priority, as make_stream's below)
1332#endif
1333    const int gp_mid = gprio ? (gp_lo + gp_hi) / 2 : 0;
1334    if (gprio) std::fprintf(stderr, "strata verify: STRATA_GRAPH_PRIO: stream priorities side %d, cs / side2 %d, shared expert %d\n",
1335                            gp_hi, gp_mid, gp_lo);
1336    // STRATA_PIPED_CONCURRENT=1 (opt-in): a prompt can run on the same GPU while the batch windows run, so the windows'
1337    // streams get the device's highest priority (HIP: the default priority, as the drafter's)
1338    auto make_stream = [&](cudaStream_t* s, int gp = 0) -> cudaError_t {
1339#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
1340        static const bool hi = [] {   // (STRATA_PIPED_CONCURRENT_PRIO=0: the default priority)
1341            const char* v = std::getenv("STRATA_PIPED_CONCURRENT");
1342            const char* p = std::getenv("STRATA_PIPED_CONCURRENT_PRIO");
1343            return v != nullptr && std::atoi(v) != 0 && (p == nullptr || std::atoi(p) != 0);
1344        }();
1345        int lo = 0, top = 0;
1346        if (hi) {
1347            if (cudaDeviceGetStreamPriorityRange(&lo, &top) == cudaSuccess &&
1348                cudaStreamCreateWithPriority(s, cudaStreamNonBlocking, top) == cudaSuccess)
1349                return cudaSuccess;
1350            cudaGetLastError();   // (only the failed priority call's error: the default path clears nothing)
1351        }
1352        if (gprio) {   // STRATA_GRAPH_PRIO: this stream's own priority (gp)
1353            if (cudaStreamCreateWithPriority(s, cudaStreamNonBlocking, gp) == cudaSuccess) return cudaSuccess;
1354            cudaGetLastError();
1355        }
1356#else
1357        (void) gp;
1358#endif
1359        return cudaStreamCreateWithFlags(s, cudaStreamNonBlocking);
1360    };
1361    bool copy_made = false;
1362#if defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
1363    // engine-latency, STRATA_COPY_HIP_PRIO=1 (opt-in): the copy stream at high priority, so it gets a hardware queue of
1364    // its own (ROCm hands queues out per priority).  Sharing one with the window's stream, --pcie-mode dma's copies and
1365    // their host function queue behind the window's graph, which spins on the flag they raise (a timeout at layer 1).
1366    {
1367        static const bool cp = [] { const char* v = std::getenv("STRATA_COPY_HIP_PRIO"); return v != nullptr && std::atoi(v) != 0; }();
1368        int lo = 0, hi = 0;
1369        if (cp && hipDeviceGetStreamPriorityRange(&lo, &hi) == hipSuccess)
1370            copy_made = hipStreamCreateWithPriority(&copy_, hipStreamNonBlocking, hi) == hipSuccess;
1371        (void) cudaGetLastError();
1372    }
1373#endif
1374    if (!copy_made && make_stream(&copy_) != cudaSuccess) {
1375        err = "verify: copy stream create failed";
1376        return false;
1377    }
1378    if (ext_stream_ != nullptr) cs_ = ext_stream_;   // set_stream (pipelined windows): the stage's shared stream
1379    else if (make_stream(&cs_, gp_mid) != cudaSuccess) cs_ = nullptr;
1380    if (cs_ == nullptr || make_stream(&sh_cs_, gp_lo) != cudaSuccess) {
1381        err = "verify: stream create failed";
1382        return false;
1383    }
1384    if (cudaEventCreateWithFlags(&commit_done_, cudaEventDisableTiming) != cudaSuccess ||
1385        cudaEventCreateWithFlags(&ev_fork_, cudaEventDisableTiming) != cudaSuccess ||
1386        cudaEventCreateWithFlags(&ev_join_, cudaEventDisableTiming) != cudaSuccess ||
1387        cudaEventCreateWithFlags(&ev_hq_, cudaEventDisableTiming) != cudaSuccess) {
1388        err = "verify: event create failed";
1389        return false;
1390    }
1391    {   // STRATA_DF_BRANCH=1 (opt-in): the mixer's side branches.  Off by default: on Linux (open modules, GSP) a
1392        // stage's window with the branches stopped inside its graph when an NVML query (nvidia-smi) came between
1393        // requests (2x RTX 3090 and 2x RTX 2080 Ti, #905); never seen on Windows.  0 / unset: one stream, as before
1394        const char* v = std::getenv("STRATA_DF_BRANCH");
1395        df_branch_ = v != nullptr && std::atoi(v) != 0;
1396        if (df_branch_ && df_fork_ == nullptr) {
1397            bool okb = cudaEventCreateWithFlags(&df_fork_, cudaEventDisableTiming) == cudaSuccess;
1398            for (int i = 0; i < 2 && okb; ++i)
1399                okb = cudaStreamCreateWithFlags(&df_side_[i], cudaStreamNonBlocking) == cudaSuccess &&
1400                      cudaEventCreateWithFlags(&df_join_[i], cudaEventDisableTiming) == cudaSuccess;
1401            if (!okb) { cudaGetLastError(); df_branch_ = false; }
1402        }
1403    }
1404    // Check whether 100% of experts across [lb_, le_) are resident in this stage's VRAM cache.
1405    // When true, every layer plans on device and writes directly into parts_ without any CPU doorbells,
1406    // wait_flag_ge spins, PCIe empty launches, or moe_hit_add copies.
1407    all_resident_ = false;
1408    ar_off_ = false;
1409    h_res_ = hits.h_res;
1410    if (hits.h_res == nullptr || hits.d_res == nullptr || hits.cache_base == nullptr)
1411        strata::dispatch::note("init: all-resident graph declined: no expert table on this device (no cache, or no residency map)");
1412    if (h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0;
1413    if (hits.h_res != nullptr && hits.d_res != nullptr && hits.cache_base != nullptr) {
1414        const char* v_ar = std::getenv("STRATA_VERIFY_ALL_RESIDENT");
1415#if defined(STRATA_CPU_ARM64)
1416        // Windows on ARM64: this all-resident (zero-doorbell) path hangs the first decode window - measured here
1417        // with the q3k l1280 pack, every expert resident: "verify window: 6 tokens at position 0, host at layer
1418        // step 1, the GPU rang 0", no progress for 85 s, then the watchdog's 0xC0000409.  Layer 1 was reached and
1419        // never returned; with STRATA_VERIFY_ALL_RESIDENT=0 the same request answers in 0.8 s.  A 24 GB card never
1420        // reaches this path (its experts do not all fit), which is why the Linux validation passed.  Opt-in here
1421        // until the path is fixed, so the default cannot take it.
1422        const bool ar_enabled = v_ar != nullptr && std::atoi(v_ar) != 0;
1423#else
1424        const bool ar_enabled = v_ar == nullptr || std::atoi(v_ar) != 0;
1425#endif
1426        if (ar_enabled) {
1427            bool all_ok = true;
1428            for (int64_t l = lb_; l < le_ && all_ok; ++l) {
1429                for (int64_t e = 0; e < g.n_expert; ++e) {
1430                    if (hits.h_res[l * g.n_expert + e] < 0) {
1431                        all_ok = false;
1432                        break;
1433                    }
1434                }
1435            }
1436            all_resident_ = all_ok;
1437            if (all_ok) strata::dispatch::note("init: all-resident graph selected (every expert of this stage is in VRAM)");
1438            else strata::dispatch::note("init: all-resident graph declined: some expert is not resident (doorbell graph with CPU / PCIe experts)");
1439        } else
1440            strata::dispatch::note("init: all-resident graph declined: STRATA_VERIFY_ALL_RESIDENT=0");
1441    }
1442    if (g_side_mixer() > 0 &&
1443        ((gprio ? make_stream(&side_, gp_hi) : cudaStreamCreateWithFlags(&side_, cudaStreamNonBlocking)) != cudaSuccess ||
1444        cudaEventCreateWithFlags(&mfork_, cudaEventDisableTiming) != cudaSuccess ||
1445        cudaEventCreateWithFlags(&mjoin_, cudaEventDisableTiming) != cudaSuccess ||
1446        (gprio ? make_stream(&side2_, gp_mid) : cudaStreamCreateWithFlags(&side2_, cudaStreamNonBlocking)) != cudaSuccess ||
1447        cudaEventCreateWithFlags(&pfork_, cudaEventDisableTiming) != cudaSuccess ||
1448        cudaEventCreateWithFlags(&pjoin_, cudaEventDisableTiming) != cudaSuccess)) {
1449        err = "verify: the mixer branch's stream / events could not be created";
1450        return false;
1451    }
1452    // E-6: a layer whose routed experts are all resident is planned on the device (STRATA_VERIFY_DEVICE_PLAN=1: on;
1453    // exact, but neutral on RIBPC 1-2 GPUs: off by default)
1454    {
1455        const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN");
1456        // (not with set_always_publish: the device table may lag the host's while windows are in flight)
1457        device_plan_ = !all_resident_ && !always_publish_ && (v != nullptr && std::atoi(v) != 0);
1458    }
1459    // (halo's STRATA_VERIFY_RESIDENT=1 is this window's all_resident_ graph above, which 0.1.39 has on by default)
1460    if (g_qfuse() || g_qfuse_hc()) {   // S26: the HC read's q8_1 group counters, zeroed once (each launch leaves them zero)
1461        if (cudaMalloc((void**) &qcnt_, sizeof(unsigned) * (size_t) (g.n_embd / 32)) != cudaSuccess ||
1462            cudaMemset(qcnt_, 0, sizeof(unsigned) * (size_t) (g.n_embd / 32)) != cudaSuccess) {
1463            cudaGetLastError();
1464            if (qcnt_) cudaFree(qcnt_);
1465            qcnt_ = nullptr;
1466        }
1467    }
1468    if (all_resident_ || device_plan_) {
1469        bool ok2 = true;
1470        if (device_plan_)
1471            ok2 = cudaMalloc((void**) &skip_, 64) == cudaSuccess && cudaMemset(skip_, 0, 64) == cudaSuccess;
1472        if (ok2 && hits.slot_off != nullptr && hits.n_slots > 0) {
1473            ok2 = cudaMalloc((void**) &slot_off_d_, (size_t) hits.n_slots * sizeof(unsigned long long)) == cudaSuccess &&
1474                  cudaMemcpy(slot_off_d_, hits.slot_off, (size_t) hits.n_slots * sizeof(unsigned long long),
1475                             cudaMemcpyHostToDevice) == cudaSuccess;
1476        }
1477        if (!ok2) { cudaGetLastError(); all_resident_ = false; device_plan_ = false; }
1478    }
1479    std::fprintf(stderr, "strata verify: window up to %d tokens, %.1f MiB of device buffers%s\n", max_t,
1480                 (double) count.used / 1048576.0,
1481                 all_resident_ ? " (100% VRAM resident: zero-doorbell graph)" : "");
1482    return true;
1483}
1484
1485const float* Verifier::final_R(int t) const { return R_ + (size_t) t * (size_t) (g_->hc * g_->n_embd); }
1486
1487// ================================ THE WINDOW, AS CAPTURED ================================
1488//
1489// Plan v0.3 P6 (split window): with `groups_ == 2` the window's tokens are cut into two groups A = [0, T/2 up) and
1490// B = the rest, and the stream is ordered
1491//
1492//     pre(0,A) pre(0,B) | post(0,A) pre(1,A) | post(0,B) pre(1,B) | post(1,A) pre(2,A) | ...
1493//
1494// so the CPU computes A's experts of layer l while the GPU runs B's mixer and router of layer l, and B's experts
1495// while the GPU combines A and runs A's layer l+1.  B's mixer only needs A's mixer of the same layer (K/V, GDN
1496// state), never A's experts, so nothing waits that did not wait before.  Every token's arithmetic is unchanged.
1497bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
1498    using namespace strata::kernels;
1499    const ModelGeometry& g = *g_;
1500    const WeightTable& wt = *wt_;
1501    SessionState& ss = *ss_;
1502    const int64_t N = g.n_embd, HC = g.hc, K = ss.k, C = g.ssm_conv_channels, ZV = g.ssm_value_dim;
1503    const int64_t HV = g.ssm_v_heads, HK = g.ssm_k_heads, NH = g.n_head, HD = g.head_dim, NKV = g.n_head_kv;
1504    const int64_t IQ = g.idx_q_heads, ID = g.idx_key_dim, NE = g.n_expert, MT = max_t_;
1505    const QsaShapes s = shapes_of(g);
1506    const GrShapes gs{g.n_embd, g.hc, g.hc_lr};
1507    const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +
1508                                (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);
1509    const int64_t HS = (int64_t) NG_HIST * NG_HC_DIM;
1510    const int64_t TS = (s.idx_block - 1) * ID;
1511    const bool ple_on = ss.ple.ready() && ple_stage();
1512    auto Rt = [&](int t) { return R_ + (size_t) t * HC * N; };
1513    // a batch window is one group; a window past kVerifyMaxT tokens is always two (--lookup-max-t: each group holds
1514    // at most kVerifyMaxT, what the per-group kernels and the CPU experts take)
1515    const int G = ((split_ && T >= 2) || T > kVerifyMaxT) && !batch_rec_ ? 2 : 1;
1516    // Pipelined windows must wait for the host verdict/snapshot fence before mutating state.
1517    const bool self_commit = T == 1 && !always_publish_ && !batch_rec_ && !g_qfuse() && one_token_self_commit();   // see Verifier::commit
1518    static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }();
1519    // fork 34a35db: the GDN gates and the QSA indexer beside the projections (STRATA_SIDE_MIXER=1; 0 / unset = in line)
1520    const int side_mixer_mode = g_side_mixer();
1521    const bool side_mixer = side_mixer_mode >= 1;
1522    const bool side_proj = side_mixer_mode >= 2 && !batch_rec_;   // fork b063c13: the GDN gate projection, the QSA queries
1523    auto branch = [&](cudaEvent_t e, cudaStream_t from, cudaStream_t to, const char* what) {
1524        if (to == side_) note_prio_fork(from);   // STRATA_GRAPH_PRIO: where the high-priority branch leaves cs
1525        if (cudaEventRecord(e, from) == cudaSuccess && cudaStreamWaitEvent(to, e, 0) == cudaSuccess) return true;
1526        err = std::string("verify: the mixer branch could not ") + what;
1527        return false;
1528    };
1529    // a batch window's rows each read their own slot's indexer: in line there
1530    const bool sidem = side_mixer && !batch_rec_;
1531    auto stamp = [&](int64_t l, int i, int grp) {
1532        if (prof_on_ && grp == 0) gpu_stamp(prof_, (int) (l * kProfPer + i), cs);
1533        if (trace_m_ != nullptr && grp == 0) gpu_stamp(trace_m_, (int) ((l * kProfPer + i) * 2), cs);   // #649: grp=0 only (buffer holds 2 groups/slot; grp 2..7 overflowed into the next slots)
1534    };
1535    const int tb_[2] = {0, (T + 1) / 2}, te_[2] = {G == 2 ? (T + 1) / 2 : T, T};
1536    // S26 STRATA_LFUSE=1: where the shared expert's gate / scale fusions apply (the paths they replace are the ones taken)
1537    auto lfuse_on = [&](int n) {
1538        return g_lfuse() && ar_on() && native_moe_combine_enabled() && dec_batch && n > 1 && n <= 8 &&
1539               shared_expert_native_bf16_enabled();
1540    };
1541    bool sg_gated_[2] = {false, false};   // per group: the combine applies the shared gate
1542    if (!batch_rec_) groups_[T] = G;
1543    // Programmatic dependent launch (pdl.hpp; sm_90+, opt-in: STRATA_DF_PDL=1): the window's quantizations and dense
1544    // projections may start while the kernel before them finishes, loading their weights before they wait for its
1545    // output.  Only a launch whose predecessors in the graph are all kernels gets programmatic edges; every value is
1546    // the same as without them.
1547    struct PdlScope {
1548        bool prev;
1549        explicit PdlScope(bool on) : prev(pdl_scope()) { pdl_scope() = on; }
1550        ~PdlScope() { pdl_scope() = prev; }
1551    } pdl_window(G == 1 && pdl_supported() && (std::getenv("STRATA_DF_PDL") != nullptr || (ar_on() && !batch_rec_)));
1552    // BW-MEASURE (dispatch counters, include/strata/core/dispatch_stats.hpp): the window's counts go to the bin of this T and graph kind
1553    // (0 = zero-doorbell all-resident, 1 = doorbell graph with CPU / PCIe experts, 2 = batch)
1554    strata::dispatch::Scope dsp_scope(T, batch_rec_ ? 2 : (ar_on() ? 0 : 1));
1555    strata::dispatch::notef("win groups=%ld all_resident=%ld device_plan=%ld", (long) G, (long) ar_on(), (long) device_plan_);
1556    strata::dispatch::notef("win pdl=%ld side_mixer=%ld side_proj=%ld", (long) (G == 1 && pdl_supported() && (std::getenv("STRATA_DF_PDL") != nullptr || (ar_on() && !batch_rec_))), (long) side_mixer_mode, (long) side_proj);
1557    strata::dispatch::notef("win df_branch=%ld sh_stream=%ld prof=%ld", (long) (df_branch_ && G == 1 && !batch_rec_ && !prof_on_ && !side_mixer), (long) sh_stream_on(), (long) prof_on_);
1558    // STRATA_DF_BRANCH: mixer work that reads only the layer's input runs on a side stream inside the graph.  fork(i)
1559    // makes side i depend on everything captured on `cs` so far, join(i) makes `cs` depend on everything captured on
1560    // side i: a branch never races with what came before its fork or after its join.  Not in a split or batch window,
1561    // nor under the stage profiler (whose stamps are on `cs`).
1562    const bool br = df_branch_ && G == 1 && !batch_rec_ && !prof_on_ && !side_mixer;   // STRATA_SIDE_MIXER wins
1563    auto fork = [&](int i) {
1564        cudaEventRecord(df_fork_, cs);
1565        cudaStreamWaitEvent(df_side_[i], df_fork_, 0);
1566    };
1567    auto join = [&](int i) {
1568        cudaEventRecord(df_join_[i], df_side_[i]);
1569        cudaStreamWaitEvent(cs, df_join_[i], 0);
1570    };
1571    const int64_t nQall = g.n_qsa_layers();
1572    // a batch window: row t is slot t, whose state lives in its own session
1573    auto slot_ss = [&](int t) -> SessionState& { return batch_rec_ ? *slots_[(size_t) brow_[t]] : ss; };
1574    const int hrow0 = batch_rec_ ? row_base_ : 0;   // a slot group's own hand-off rows
1575    // STRATA_BATCH_SELF_COMMIT: the window keeps its rows (no commit graph, nothing to snapshot for one)
1576    const bool keep_rows = batch_rec_ && batch_self_commits(brow_, T);
1577
1578    // ---- the window's inputs, from mapped staging.  With branches the steps and positions (first read by the first
1579    // layer's mixer) cross PCIe on side 1 beside the embedding and the first hyper-connection read.
1580    copy_i32_from_mapped(tok_, m_tok_, T, cs);
1581    bool inputs_pending = false;
1582    cudaStream_t in_s = cs;
1583    if (br) {
1584        fork(1);
1585        in_s = df_side_[1];
1586        inputs_pending = true;
1587    }
1588    copy_i32_from_mapped(step_, m_step_, (int64_t) T * kStepCount, in_s);
1589    copy_i32_from_mapped(pos_, m_pos_, (int64_t) MT * (NH + NKV + IQ), in_s);
1590    // per-ROW positions of the K rows [t][NKV] and the indexer query rows [t][IQ] (for batched RoPE)
1591    const int32_t* pos_k = pos_ + MT * NH;
1592    const int32_t* pos_i = pos_ + MT * (NH + NKV);
1593
1594    // ---- the embeddings, broadcast to the hc streams - or, in a later stage of a layer split, the previous stage's
1595    // residual, pending write and inject (see set_stage)
1596    const int64_t HB = Verifier::handoff_floats(g);
1597    if (lb_ > 0) {
1598        const float* hin = hand_in_ + (size_t) hrow0 * HB;   // the group's rows: [R][bo][inj] contiguous
1599        // the overlapped split: this graph was launched before the previous stage finished - wait for its hand-off
1600        if (hflag_in_d_ != nullptr && !batch_rec_) wait_handoff(hflag_in_d_, 1u, herr_d_, g_split_wait_ns, cs);
1601        copy_from_mapped(R_, hin, (int64_t) T * HC * N, cs);
1602        copy_from_mapped(bo_, hin + (size_t) T * HC * N, (int64_t) T * N, cs);
1603        copy_from_mapped(inj2_, hin + (size_t) T * (HC + 1) * N, (int64_t) T * HC, cs);
1604    } else if (const NativeEmbed* ne = native_embed()) {       // plan v0.3 P6: the GGUF-form table
1605        ne->gather_dev(tok_, T, emb_, cs);
1606        broadcast_streams(emb_, R_, N, (int) HC, T, cs);
1607    } else {
1608        const WeightRef* w = wt.find("token_embd.weight");
1609        if (w == nullptr || w->codebook_iq4nl || (w->code_bits != 2 && w->code_bits != 4 && w->code_bits != 8)) {
1610            err = "verify: token_embd.weight is missing or not an S2/S4/S8 tensor";
1611            return false;
1612        }
1613        const auto* codes = (const uint8_t*) w->data;
1614        const auto* scales = (const float*) (codes + w->codes_bytes);
1615        const auto* offsets = w->has_offset ? (const float*) (codes + w->codes_bytes + w->scales_bytes) : nullptr;
1616        const uint64_t row_codes = (uint64_t) (w->ne0 / (8 / w->code_bits));
1617        const uint64_t row_groups = (uint64_t) (w->ne0 / w->group_elems);
1618        embedding_gather_dev(codes, scales, offsets, tok_, T, w->ne0, w->code_bits, w->code_bias, w->group_elems,
1619                             row_codes, row_groups, emb_, cs);
1620        broadcast_streams(emb_, R_, N, (int) HC, T, cs);
1621    }
1622
1623    // per-layer state indices (GDN and QSA layers are numbered separately)
1624    std::vector<int64_t> gdn_idx((size_t) g.n_layers, -1), qsa_idx((size_t) g.n_layers, -1);
1625    {
1626        int64_t qi = 0, gi = 0;
1627        for (int64_t l = 0; l < g.n_layers; ++l) {
1628            if (is_qsa_layer(g, l)) qsa_idx[(size_t) l] = qi++;
1629            else gdn_idx[(size_t) l] = gi++;
1630        }
1631    }
1632
1633    // ---------------------------------------------------------------- pre(l, group): up to the ring
1634    auto pre = [&](int64_t l, int grp) -> bool {
1635        const int tb = tb_[grp], te = te_[grp], n = te - tb;
1636        stamp(l, 0, grp);
1637        const LayerView v(wt, l);
1638        const char* pfx[2] = {"hc_attn_", "hc_ffn_"};
1639        const WeightRef *wn[2], *wd[2], *wu[2], *wi[2];
1640        for (int h = 0; h < 2; ++h) {
1641            wn[h] = need(v, (std::string(pfx[h]) + "norm.weight").c_str(), err);
1642            wd[h] = need(v, (std::string(pfx[h]) + "down.weight").c_str(), err);
1643            wu[h] = need(v, (std::string(pfx[h]) + "up.weight").c_str(), err);
1644            wi[h] = need(v, (std::string(pfx[h]) + "inject.weight").c_str(), err);
1645            if (!wn[h] || !wd[h] || !wu[h] || !wi[h]) return false;
1646        }
1647        // the previous layer's FFN write, folded into this layer's first read (a control vector after it has
1648        // already applied it)
1649        bool pending = l > 0 && !cvec().covers(l - 1);
1650        if (l == 1 && ple_on) {
1651            if (grp == 0) {
1652                if (ar_on()) wait_flag_ge(m_flag_, 1, cs);
1653                copy_from_mapped(ple_, m_ple_, (int64_t) T * N, cs);
1654            }
1655            float* normalized = (float*) ((uint8_t*) ss.ple.scratch + ple_block_scratch_bytes());
1656            static const bool ple_batch_env = [] {
1657                const char* e = std::getenv("STRATA_PLE_BATCH");
1658                return !e || e[0] != '0';
1659            }();
1660            const bool ple_batch_kv = ple_batch_env && dec_batch && n > 1 && ss.ple.w.key_bf16 != nullptr &&
1661                                      ss.ple.w.value_bf16 != nullptr && ple_native_bf16_enabled() &&
1662                                      ple_native_postops_enabled();
1663            // S25 (STRATA_PLE_BATCH=1): the key and value projections depend only on each row's n-gram embedding, so
1664            // the group's rows run through the multi-row forms of the same kernels (the weights read once); every
1665            // row's arithmetic is the single-row call's. The history-dependent rest stays row by row.
1666            static const bool ple_batch = [] { const char* e = std::getenv("STRATA_PLE_BATCH"); return e && e[0] == '1'; }();
1667            PleWeights pw = ss.ple.w;
1668            const bool nkey = pw.key_native_data != nullptr && pw.key_bf16 == nullptr;
1669            const bool batched = !ple_batch_kv && ple_batch && n > 1 && (pw.key_bf16 != nullptr || nkey) && ple_native_bf16_enabled();
1670            if (ple_batch_kv) {
1671                try {
1672                    bf16_gemv_fp32_mmvf_multi(ple_ + (size_t) tb * N, N, ss.ple.w.key_bf16,
1673                                              xn_ + (size_t) tb * HC * N, HC * N, N, HC * N, n, cs);
1674                    bf16_gemv_fp32_mmvf_multi(ple_ + (size_t) tb * N, N, ss.ple.w.value_bf16,
1675                                              z_ + (size_t) tb * N, N, N, N, n, cs);
1676                } catch (const std::exception& e) {
1677                    err = std::string("verify PLE multi: ") + e.what();
1678                    return false;
1679                }
1680            } else if (batched) {
1681                try {
1682                    if (pw.key_bf16 != nullptr)
1683                        bf16_gemv_fp32_mmvf_multi(ple_ + tb * N, N, pw.key_bf16, ple_key_ + (size_t) tb * NG_HC_DIM,
1684                                                  NG_HC_DIM, N, NG_HC_DIM, n, cs);
1685                    else {
1686                        native_quantize_q8_1(ple_ + tb * N, xq_, (int) N, n, cs);
1687                        native_mmvq(pw.key_native_type, pw.key_native_data, xq_, ple_key_ + (size_t) tb * NG_HC_DIM,
1688                                    (int) N, NG_HC_DIM, n, cs);
1689                    }
1690                    bf16_gemv_fp32_mmvf_multi(ple_ + tb * N, N, pw.value_bf16, ple_val_ + tb * N, N, N, N, n, cs);
1691                } catch (const std::exception& e) {
1692                    err = std::string("verify PLE batch: ") + e.what();
1693                    return false;
1694                }
1695            }
1696            // STRATA_DF_PLE (opt-in: STRATA_DF_PLE=1): the window's post-projection steps in one pass, bitwise the per-token loop
1697            // below (the norms divide at run time as its norms do; the history advances token by token), which also
1698            // writes the commit's history snapshots.  Scratch: layer 0's expert rows, combined by now, and the
1699            // hyper-connection read's `lo_`, which the read below rewrites.
1700            static const bool ple_post_env = [] {
1701                const char* e = std::getenv("STRATA_DF_PLE");
1702                return e != nullptr && std::atoi(e) != 0;
1703            }();
1704            const bool ple_post = ple_batch_kv && ple_post_env && !batch_rec_;
1705            // #783 PR-g (stuchapin909): the window's residual writes in one launch (STRATA_NO_MULTI_GR=1: per token)
1706            const bool multi_write = !ple_post && dec_batch && !g_no_multi_gr && n > 1;
1707            if (multi_write) gr_write_multi(Rt(tb), bo_ + tb * N, inj2_ + tb * HC, gs, Rt(tb), n, cs);
1708            if (ple_post) {
1709                float* qn = parts_ + (size_t) tb * K * N;           // n x 10240 (K * N = 25600 per row)
1710                float* gated = hit_out_ + (size_t) tb * K * N;      // n x 10240
1711                float* pgate = lo_ + (size_t) tb * g.hc_lr;         // n x 4
1712                try {
1713                    if (gr_native_mmvf_enabled())   // gr_write's native write for the n rows in one launch
1714                        native_gr_post_multi(Rt(tb), bo_ + tb * N, inj2_ + tb * HC, Rt(tb), (int) N, (int) HC, n, HC * N,
1715                                             N, HC, cs);
1716                    else
1717                        for (int t = tb; t < te; ++t) gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs);
1718                    native_ple_postops_batch_snap(xn_ + (size_t) tb * HC * N, Rt(tb), z_ + (size_t) tb * N, ss.ple.hist,
1719                                                  ss.ple.w, qn, gated, pgate, n, hist_snap_ + (size_t) tb * HS, cs);
1720                } catch (const std::exception& e) {
1721                    err = std::string("verify PLE (window): ") + e.what();
1722                    return false;
1723                }
1724            } else
1725            for (int t = tb; t < te; ++t) {
1726                if (batched) { pw.pre_key = ple_key_ + (size_t) t * NG_HC_DIM; pw.pre_value = ple_val_ + t * N; }
1727                if (!multi_write) gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs);
1728                PleOut po;
1729                po.normalized = normalized;
1730                po.result = Rt(t);
1731                float* hist = batch_rec_ ? slot_ss(t).ple_hist : ss.ple.hist;   // the row's own history
1732                try {
1733                    if (ple_batch_kv) {
1734                        ple_block_projected(xn_ + (size_t) t * HC * N, z_ + (size_t) t * N, Rt(t), hist,
1735                                            ss.ple.w, po, ss.ple.scratch, cs);
1736                    } else {
1737                        ple_block(ple_ + t * N, Rt(t), hist, pw, po, ss.ple.scratch, cs);
1738                    }
1739                    ple_history_advance(hist, normalized, cs);
1740                } catch (const std::exception& e) {
1741                    err = std::string("verify PLE: ") + e.what();
1742                    return false;
1743                }
1744                if (!keep_rows) copy_from_mapped(hist_snap_ + (size_t) t * HS, hist, HS, cs);
1745            }
1746            pending = false;
1747        }
1748        auto gr_read_group = [&](int half, bool apply, float* inj_prev, float* inj_out) {
1749            strata::dispatch::notef("hc read: weights Q8_0 copies=%ld (0 = bf16 rows), half=%ld, qfuse=%ld", (long) (wd[half]->hc_q8 != nullptr), (long) half, (long) (qcnt_ != nullptr));
1750            FusedGrArgs fa[kFusedGrWideT];
1751            for (int t = tb; t < te; ++t) {
1752                FusedGrArgs& a = fa[t - tb];
1753                a.R = Rt(t); a.R_out = Rt(t); a.apply = apply;
1754                a.bo_prev = bo_ + t * N; a.inj_prev = inj_prev + t * HC;
1755                a.w_norm = (const float*) wn[half]->data; a.w_down = (const uint16_t*) wd[half]->data;
1756                a.w_up = (const uint16_t*) wu[half]->data; a.w_inject = (const uint16_t*) wi[half]->data;
1757                a.q8_down = (const uint8_t*) wd[half]->hc_q8; a.q8_up = (const uint8_t*) wu[half]->hc_q8;
1758                a.q8_inject = (const uint8_t*) wi[half]->hc_q8;
1759                a.s_down = wd[half]->q8_scale; a.s_up = wu[half]->q8_scale;
1760                a.eps = EPS; a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC;
1761                a.inject_out = inj_out + t * HC; a.mixed = mixed_ + t * N;
1762                if (qcnt_ != nullptr) {   // S26 STRATA_QFUSE: the consumer's q8_1 image written by the read itself
1763                    a.q8_cnt = qcnt_;
1764                    if (half == 0) a.q8_mixed = xq_ + (size_t) (t - tb) * (N / 32) * 36;
1765                    else if (strata::kernels::cpu::expert_layout().native) a.q8_mixed = nat_xq_ + (size_t) t * (N / 32) * 36;
1766                }
1767            }
1768            if (strata::kernels::fused_gr_read_persist(fa, n, cs)) return false;   // STRATA_HC_PERSIST=1; q8_mixed is never set there
1769            return fused_gr_read_multi(fa, n, xn_ + (size_t) tb * HC * N, cs, (prof_on_ && grp == 0) ? prof_ : nullptr,
1770                                (int) (l * kProfPer + (half == 0 ? 27 : 30)));
1771        };
1772        const bool q8_attn = gr_read_group(0, pending, inj2_, inj_);   // true: xq_ holds mixed's q8_1 (STRATA_QFUSE)
1773        {   // measurement only: STRATA_DUMMY_NODES=k adds k empty kernel nodes per layer (what one node costs in a window)
1774            static const int dummy = [] { const char* e = std::getenv("STRATA_DUMMY_NODES"); return e != nullptr ? std::atoi(e) : 0; }();
1775            for (int d = 0; d < dummy; ++d) gpu_noop(cs);
1776        }
1777        if (inputs_pending) {   // the window's steps and positions, before the first mixer reads them
1778            join(1);
1779            inputs_pending = false;
1780        }
1781        stamp(l, 1, grp);
1782        float* xm = mixed_ + tb * N;
1783        bool il_ready = false;   // xil_ holds xq_'s interleaved copy (reset whenever xq_ is rewritten)
1784        // a projection input's q8_1 blocks and their interleaved copy in one launch (native_quantize_q8_1_il, the same
1785        // bytes): Turing default (+0.5..+1 % decode, two launches fewer per GDN layer and per QSA layer); STRATA_QIL=0 / 1
1786        // forces it off / on
1787        auto quant_in = [&](const float* x, int n_in) {
1788#if !defined(STRATA_USE_HIP)
1789            static const int qil_env = [] { const char* v = std::getenv("STRATA_QIL"); return v != nullptr ? std::atoi(v) : -1; }();
1790            const bool qil = qil_env >= 0 ? qil_env != 0 : device_is_sm75();
1791            if (qil && n >= 2 && n <= 4 && g_mmvq_il()) {
1792                strata::kernels::native_quantize_q8_1_il(x, xq_, xil_, n_in, n, cs);
1793                il_ready = true;
1794                return;
1795            }
1796#endif
1797            native_quantize_q8_1(x, xq_, n_in, n, cs);
1798            il_ready = false;
1799        };
1800        auto mm = [&](const WeightRef* w, float* out, int n_in, int n_out) {
1801            if (g_mmvq_il() && strata::kernels::native_mmvq_il_supported(w->native_type, n, n_out)) {
1802                if (!il_ready && n >= 2) {   // one column reads the plain q8_1 blocks
1803                    strata::kernels::native_q8_1_interleave(xq_, xil_, n_in, n, cs);
1804                    il_ready = true;
1805                }
1806                strata::kernels::native_mmvq_il(w->native_type, w->native_data, xq_, xil_, out, n_in, n_out, n, cs);
1807            } else {
1808                native_mmvq(w->native_type, w->native_data, xq_, out, n_in, n_out, n, cs);
1809            }
1810        };
1811        try {
1812            if (!is_qsa_layer(g, l)) {
1813                // ======================= GDN =======================
1814                const WeightRef *wqkv = need(v, "attn_qkv.weight", err), *wg = need(v, "attn_gate.weight", err),
1815                                *wout = need(v, "ssm_out.weight", err), *wa = need(v, "ssm_alpha.weight", err),
1816                                *wb = need(v, "ssm_beta.weight", err), *wc = need(v, "ssm_conv1d.weight", err),
1817                                *wnm = need(v, "ssm_norm.weight", err), *wdt = need(v, "ssm_dt.bias", err),
1818                                *wsa = need(v, "ssm_a", err);
1819                if (!wqkv || !wg || !wout || !wa || !wb || !wc || !wnm || !wdt || !wsa) return false;
1820                if (!native_of(wqkv, v.name("attn_qkv.weight"), err) || !native_of(wg, v.name("attn_gate.weight"), err) ||
1821                    !native_of(wout, v.name("ssm_out.weight"), err))
1822                    return false;
1823                const int64_t gi = gdn_idx[(size_t) l];
1824                float* state = ss.gdn_state + (size_t) (gi - ss.gdn_ord0) * gdn_floats;
1825                float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
1826                float* qkv = qkv_L_ + (size_t) gi * MT * C;
1827                float* hb = h_L_ + (size_t) gi * MT * C;
1828                float* gate = gate_L_ + (size_t) gi * MT * HV;
1829                float* beta = beta_L_ + (size_t) gi * MT * HV;
1830                if (sidem) {   // the gates (a few blocks, latency-bound) beside the projections, joined below
1831                    if (!branch(mfork_, cs, side_, "fork")) return false;
1832                    gdn_ab_multi(xm, (const uint16_t*) wa->data, (const uint16_t*) wb->data, (const float*) wdt->data,
1833                                 (const float*) wsa->data, gate + (size_t) tb * HV, beta + (size_t) tb * HV, (int) N,
1834                                 (int) HV, n, side_);
1835                    note_prio_tail(side_, 1);
1836                    if (cudaEventRecord(mjoin_, side_) != cudaSuccess) { err = "verify: the GDN gates' branch could not join"; return false; }
1837                }
1838                if (!q8_attn) quant_in(xm, (int) N);
1839                if (side_proj) {   // the gate projection (compute-bound for i-quants) beside qkv and the conv
1840                    // the branch reads F4's interleaved copy too (written on cs before the fork; bitwise native_mmvq's
1841                    // output), and qkv is recorded before the branch's launch, so its grid is dispatched first and the
1842                    // conv / recurrence that wait for it start sooner (z is read only after the recurrence)
1843                    const bool g_il = g_mmvq_il() && strata::kernels::native_mmvq_il_supported(wg->native_type, n, (int) ZV);
1844                    if (g_il && !il_ready && n >= 2) {
1845                        strata::kernels::native_q8_1_interleave(xq_, xil_, (int) N, n, cs);
1846                        il_ready = true;
1847                    }
1848                    if (!branch(pfork_, cs, side2_, "fork")) return false;
1849                    mm(wqkv, qkv + (size_t) tb * C, (int) N, (int) C);
1850                    if (g_il) strata::kernels::native_mmvq_il(wg->native_type, wg->native_data, xq_, xil_, z_ + (size_t) tb * ZV,
1851                                                              (int) N, (int) ZV, n, side2_);
1852                    else native_mmvq(wg->native_type, wg->native_data, xq_, z_ + (size_t) tb * ZV, (int) N, (int) ZV, n, side2_);
1853                    if (cudaEventRecord(pjoin_, side2_) != cudaSuccess) { err = "verify: the gate projection's branch could not join"; return false; }
1854                }
1855                if (br) {   // STRATA_DF_BRANCH: a/b and z beside q/k/v and the conv; all of them read only this layer's input
1856                    fork(0);
1857                    gdn_ab_multi(xm, (const uint16_t*) wa->data, (const uint16_t*) wb->data, (const float*) wdt->data,
1858                                 (const float*) wsa->data, gate + (size_t) tb * HV, beta + (size_t) tb * HV, (int) N,
1859                                 (int) HV, n, df_side_[0]);
1860                    fork(1);
1861                    native_mmvq(wg->native_type, wg->native_data, xq_, z_ + (size_t) tb * ZV, (int) N, (int) ZV, n,
1862                                df_side_[1]);
1863                }
1864                const bool fuse_ab = fuse_convab_on() && !br && !batch_rec_ && !prof_on_ && !sidem;   // the side mixer computes the gates on its branch
1865                strata::dispatch::notef("gdn layer: side_gates=%ld side_proj=%ld df_branch=%ld", (long) sidem, (long) side_proj, (long) br);
1866                strata::dispatch::notef("gdn layer: conv+ab fused=%ld batch_rows=%ld", (long) fuse_ab, (long) batch_rec_);
1867                if (!side_proj) mm(wqkv, qkv + (size_t) tb * C, (int) N, (int) C);   // with side_proj: above, first
1868                stamp(l, 2, grp);
1869                if (batch_rec_) {   // contiguous rows may be proposals for the same slot
1870                    for (int t = tb; t < te;) {
1871                        const int first = t;
1872                        while (t < te && brow_[t] == brow_[first]) ++t;
1873                        SessionState& sx = slot_ss(first);
1874                        const float* cx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats +
1875                                          (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
1876                        gdn_conv_l2_multi(cx, qkv + (size_t) first * C, (const float*) wc->data,
1877                                          hb + (size_t) first * C, (int) C, (int) (2 * HK), EPS, t - first, cs, 0,
1878                                          keep_rows);
1879                    }
1880                } else
1881                // a one-token window keeps its token: it advances the conv history and the state itself (commit)
1882                if (fuse_ab)   // 143-amdk: the conv and the a/b projections in one launch
1883                    gdn_conv_ab_multi(conv, qkv, (const float*) wc->data, hb, (int) C, (int) (2 * HK), EPS, n, tb, self_commit,
1884                                      xm, (const uint16_t*) wa->data, (const uint16_t*) wb->data, (const float*) wdt->data,
1885                                      (const float*) wsa->data, gate + (size_t) tb * HV, beta + (size_t) tb * HV, (int) N,
1886                                      (int) HV, cs);
1887                else
1888                gdn_conv_l2_multi(conv, qkv, (const float*) wc->data, hb, (int) C, (int) (2 * HK), EPS, n, cs, tb,
1889                                  self_commit);
1890                stamp(l, 3, grp);
1891                if (br) {   // gate, beta and z, before the recurrence reads them
1892                    join(0);
1893                    join(1);
1894                } else {
1895                if (!fuse_ab && !sidem)   // the gates: the HIP fused conv kernel (143-amdk) or the side mixer's branch, else here
1896                gdn_ab_multi(xm, (const uint16_t*) wa->data, (const uint16_t*) wb->data, (const float*) wdt->data,
1897                             (const float*) wsa->data, gate + (size_t) tb * HV, beta + (size_t) tb * HV, (int) N, (int) HV,
1898                             n, cs);
1899                stamp(l, 4, grp);
1900                if (!side_proj) mm(wg, z_ + (size_t) tb * ZV, (int) N, (int) ZV);
1901                stamp(l, 5, grp);
1902                if (side_proj && cudaStreamWaitEvent(cs, pjoin_, 0) != cudaSuccess) {
1903                    err = "verify: the gate projection's branch could not join";
1904                    return false;
1905                }
1906                if (sidem && cudaStreamWaitEvent(cs, mjoin_, 0) != cudaSuccess) {
1907                    err = "verify: the GDN gates' branch could not join";
1908                    return false;
1909                }
1910                }
1911                // the recurrence from the untouched state over tokens [0, te); outputs only for this group's
1912                static const bool gdn_groups_on = [] {   // STRATA_BATCH_GDN_GROUPS=1, all slots in one launch
1913                    const char* v = std::getenv("STRATA_BATCH_GDN_GROUPS");
1914                    return v != nullptr && std::atoi(v) != 0;
1915                }();
1916                if (batch_rec_ && gdn_groups_on && te - tb <= 8) {
1917                    strata::kernels::GdnGroups gg;
1918                    for (int t = tb; t < te;) {
1919                        const int first = t;
1920                        while (t < te && brow_[t] == brow_[first]) ++t;
1921                        SessionState& sx = slot_ss(first);
1922                        gg.state[gg.n] = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats;
1923                        gg.first[gg.n] = first;
1924                        gg.ntok[gg.n] = t - first;
1925                        gg.keep[gg.n] = keep_rows ? one_ : nullptr;   // STRATA_BATCH_SELF_COMMIT: the window keeps its one-row groups itself
1926                        ++gg.n;
1927                    }
1928                    strata::kernels::gdn_step_norm_groups(gg, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS,
1929                                                          y_, (int) HK, (int) HV, keep_rows, cs);
1930                } else
1931                if (batch_rec_) {   // each slot's recurrence over its own proposed-token group
1932                    for (int t = tb; t < te;) {
1933                        const int first = t;
1934                        while (t < te && brow_[t] == brow_[first]) ++t;
1935                        SessionState& sx = slot_ss(first);
1936                        float* stx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats;
1937                        gdn_step_norm_multi(stx, hb + (size_t) first * C, (int) C, gate + (size_t) first * HV,
1938                                            beta + (size_t) first * HV, z_ + (size_t) first * ZV,
1939                                            (const float*) wnm->data, EPS, y_ + (size_t) first * ZV,
1940                                            (int) HK, (int) HV, t - first, keep_rows ? one_ : nullptr, cs, 0);
1941                    }
1942                } else
1943                gdn_step_norm_multi(state, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, y_, (int) HK,
1944                                    (int) HV, te, self_commit ? one_ : nullptr, cs, tb, g_qfuse() ? (void*) xq_ : nullptr);
1945                stamp(l, 6, grp);
1946                // STRATA_QFUSE: done above by gdn_step_norm_multi - but a batch's per-slot recurrence passes it no q8_1
1947                // destination (#1139: the out-projection read stale bytes), so that case quantizes here as without it
1948                if (!g_qfuse() || batch_rec_) quant_in(y_ + (size_t) tb * ZV, (int) ZV);
1949                else il_ready = false;
1950                mm(wout, bo_ + tb * N, (int) ZV, (int) N);
1951            } else {
1952                // ======================= QSA =======================
1953                const int64_t qi = qsa_idx[(size_t) l];
1954                const QsaState& st = ss.qsa_states[qi];
1955                const WeightRef *wik = need(v, "indexer.k_proj.weight", err), *wq = need(v, "attn_q.weight", err),
1956                                *wk = need(v, "attn_k.weight", err), *wv = need(v, "attn_v.weight", err),
1957                                *wo = need(v, "attn_output.weight", err), *wiq = need(v, "indexer.q_proj.weight", err),
1958                                *wqn = need(v, "attn_q_norm.weight", err), *wkn = need(v, "attn_k_norm.weight", err),
1959                                *wiqn = need(v, "indexer.q_norm.weight", err), *wikn = need(v, "indexer.k_norm.weight", err);
1960                if (!wik || !wq || !wk || !wv || !wo || !wiq || !wqn || !wkn || !wiqn || !wikn) return false;
1961                if (!native_of(wq, v.name("attn_q.weight"), err) || !native_of(wk, v.name("attn_k.weight"), err) ||
1962                    !native_of(wv, v.name("attn_v.weight"), err) || !native_of(wo, v.name("attn_output.weight"), err))
1963                    return false;
1964                auto norm_rope_on = [&](float* data, const WeightRef* norm, int rows, int cols, const int32_t* pos,
1965                                        cudaStream_t sx) {
1966                    if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, EPS, sx);
1967                    else rms_norm_weighted(data, (const float*) norm->data, rows, cols, EPS, sx);
1968                    if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), pos, sx);
1969                    else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, pos, sx);
1970                };
1971                // #783 PR-f (stuchapin909): the per-head RMSNorm and the rope in one launch, bit-identical to the pair
1972                // (rope_parity check 6); STRATA_NO_NORM_ROPE=1 keeps the two; off on HIP until its parity check passes
1973                const bool fuse_nr = native_qsa_enabled() && native_rope_enabled() && native_norm_rope_usable((int) HD, (int) s.n_rot);
1974                auto norm_rope = [&](float* data, const WeightRef* norm, int rows, int cols, const int32_t* pos) {
1975                    if (fuse_nr && native_norm_rope_usable(cols, (int) s.n_rot)) {
1976                        native_qsa_rms_norm_rope(data, cols, (const float*) norm->data, data, rows, cols, (int) s.n_rot, EPS,
1977                                                 rope_scaling(), pos, cs);
1978                        return;
1979                    }
1980                    norm_rope_on(data, norm, rows, cols, pos, cs);
1981                };
1982                float* idx_raw = idx_raw_L_ + (size_t) qi * MT * ID;
1983                // the per-token GEMVs / norms / RoPEs / copies of this layer as one launch over the
1984                // window's rows each - row-wise identical arithmetic (STRATA_DEC_BATCH=0: token by token)
1985                // STRATA_DF_QB_Q4 (default on since 0.1.45; STRATA_DF_QB_Q4=0 gives the old token-by-token path): a Q4_0 KV cache
1986                // takes the batched window too - its one per-token extra, the query's rotation, is row-wise and the batched
1987                // path rotates (270650e).  The generated ids are identical (p620 gfx1201, A4000 sm_86, P100 sm_60, short and
1988                // long prompts), and the 6-token verify graph is 1950 nodes instead of 2610 (#2403: an RX 6900 XT faulted in
1989                // the first verify graph launch with --kv q4_0 + KV streaming + MTP; whether the graph size is the cause is
1990                // not confirmed)
1991                static const bool qb_q4 = [] {
1992                    const char* e = std::getenv("STRATA_DF_QB_Q4");
1993                    return e == nullptr || std::atoi(e) != 0;
1994                }();
1995                const bool qb = dec_batch && n > 1 && native_qsa_enabled() && native_rope_enabled() && (!st.kv_q4 || qb_q4);
1996                if (!q8_attn) quant_in(xm, (int) N);
1997                // STRATA_DF_BRANCH: the query side (q and its norm/RoPE/rotation on side 0, the indexer query on side 1)
1998                // beside the K/V side; the indexer query joins before the block scores, the query before attention
1999                const bool qbr = br && qb;
2000                if (qbr) {
2001                    fork(0);
2002                    native_mmvq(wq->native_type, wq->native_data, xq_, qfull_ + tb * NH * 2 * HD, (int) N,
2003                                (int) (NH * 2 * HD), n, df_side_[0]);
2004                    copy_rows_strided(qcur_ + tb * NH * HD, qfull_ + tb * NH * 2 * HD, (int64_t) n * NH, HD, 2 * HD,
2005                                      df_side_[0]);
2006                    norm_rope_on(qcur_ + tb * NH * HD, wqn, (int) (n * NH), (int) HD, pos_ + tb * NH, df_side_[0]);
2007                    if (st.kv_rot) fwht256_inplace_cuda(qcur_ + tb * NH * HD, (int64_t) n * NH, df_side_[0]);   // <Hq, Hk> = <q, k>
2008                    fork(1);
2009                    bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wiq->data, qidx_ + tb * IQ * ID,
2010                                              IQ * ID, N, IQ * ID, n, df_side_[1]);
2011                    norm_rope_on(qidx_ + tb * IQ * ID, wiqn, (int) (n * IQ), (int) ID, pos_i + tb * IQ, df_side_[1]);
2012                }
2013                // STRATA_SIDE_MIXER=1 / =2 (fork Eddoursul 34a35db + b063c13): the indexer's key projection,
2014                // the tail's snapshot, its keys appended, its query projection, norm and RoPE, the block scores and the
2015                // top-k read only the mixer's input and the indexer's own state - =1 runs them on a branch beside the
2016                // attention's projections; =2 also the queries' chain on a second branch.  Each step below is
2017                // the in-line code with its stream as a parameter; with the switch off they run on cs in the same order
2018                // as before (STRATA_DF_BRANCH, the same idea for fewer of these steps, is off whenever this is on).
2019                auto norm_rope_s = [&](float* data, const WeightRef* norm, int rows, int cols, const int32_t* pos, cudaStream_t ns) {
2020                    if (fuse_nr && native_norm_rope_usable(cols, (int) s.n_rot)) {
2021                        native_qsa_rms_norm_rope(data, cols, (const float*) norm->data, data, rows, cols, (int) s.n_rot, EPS,
2022                                                 rope_scaling(), pos, ns);
2023                        return;
2024                    }
2025                    norm_rope_on(data, norm, rows, cols, pos, ns);
2026                };
2027                auto idx_key = [&](cudaStream_t ns) {
2028                    if (qb) bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wik->data, idx_raw + tb * ID, ID, N, ID, n, ns);
2029                    else for (int t = tb; t < te; ++t)
2030                        bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wik->data, idx_raw + t * ID, (int) N, (int) ID, ns);
2031                };
2032                auto idx_snap = [&](cudaStream_t ns) {
2033                    if (batch_rec_) {   // snapshot each slot's indexer tail before its first proposed row
2034                        for (int t = tb; t < te && !keep_rows; ++t)
2035                            if (t == tb || brow_[t] != brow_[t - 1])
2036                                copy_from_mapped(tail_snap_b_ + ((size_t) brow_[t] * nQall + qi) * TS,
2037                                                 slot_ss(t).qsa_states[qi].idx_tail, TS, ns);
2038                    } else
2039                    if (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, ns);
2040                };
2041                auto idx_append = [&](cudaStream_t ns) {
2042                    if (dec_batch && !g_no_batch_kv && !batch_rec_) {
2043                        const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};
2044                        native_qsa_indexer_append_steps(idx_raw + tb * ID, step_ + tb * kStepCount + kStepPos, kStepCount,
2045                                                        n, 0, (const float*) wikn->data, EPS, ib, s, st.max_cells,
2046                                                        rope_scaling(), ns);
2047                    } else {
2048                        for (int t = tb; t < te; ++t) {
2049                            const QsaState& sx = slot_ss(t).qsa_states[qi];
2050                            const QsaIndexerBuffers ib{sx.idx_tail, sx.idx_dead, sx.idx_pooled, sx.idx_block_pos};
2051                            native_qsa_indexer_append(idx_raw + t * ID, step_ + t * kStepCount + kStepPos, 0,
2052                                                      (const float*) wikn->data, EPS, ib, s, sx.max_cells,
2053                                                      rope_scaling(), ns);
2054                        }
2055                    }
2056                };
2057                auto idx_query = [&](cudaStream_t ns) {
2058                    if (qb) {
2059                        bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wiq->data, qidx_ + tb * IQ * ID, IQ * ID,
2060                                                  N, IQ * ID, n, ns);
2061                        norm_rope_s(qidx_ + tb * IQ * ID, wiqn, (int) (n * IQ), (int) ID, pos_i + tb * IQ, ns);
2062                    } else
2063                        for (int t = tb; t < te; ++t) {
2064                            float* qx = qidx_ + t * IQ * ID;
2065                            bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wiq->data, qx, (int) N, (int) (IQ * ID), ns);
2066                            norm_rope_s(qx, wiqn, (int) IQ, (int) ID, pos_ + t * NH, ns);
2067                        }
2068                };
2069                auto idx_select = [&](cudaStream_t ns) {
2070                    if (sel_long_) {   // STRATA_SELECT_LONG: the long-context window graphs (the same ids)
2071                        qsa_block_scores_long(st.idx_pooled, st.idx_dead, qidx_ + tb * IQ * ID, step_ + tb * kStepCount, n,
2072                                              max_blocks_, s, scores_ + (size_t) tb * max_blocks_, ns, -1);
2073                        qsa_block_topk_long(scores_ + (size_t) tb * max_blocks_, step_ + tb * kStepCount, n, max_blocks_,
2074                                            cap_, s, sel_ + (size_t) tb * cap_, ns, -1, topk_scratch_);
2075                        return;
2076                    }
2077                    qsa_block_scores(st.idx_pooled, st.idx_dead, qidx_ + tb * IQ * ID, step_ + tb * kStepCount, n, max_blocks_,
2078                                     s, scores_ + (size_t) tb * max_blocks_, ns);
2079                    qsa_block_topk(scores_ + (size_t) tb * max_blocks_, step_ + tb * kStepCount, n, max_blocks_, cap_, s,
2080                                   sel_ + (size_t) tb * cap_, ns);
2081                };
2082                // the attention's queries: the projection (mm on cs, which may read F4's interleaved copy; on a branch
2083                // F4's kernel too, its copy written on cs before the fork - bitwise the same), the q/gate
2084                // split with norm and RoPE, the rotation
2085                const bool q_il = side_proj && g_mmvq_il() &&
2086                                  strata::kernels::native_mmvq_il_supported(wq->native_type, n, (int) (NH * 2 * HD));
2087                auto q_chain = [&](cudaStream_t ns) -> bool {
2088                    if (ns == cs) mm(wq, qfull_ + tb * NH * 2 * HD, (int) N, (int) (NH * 2 * HD));
2089                    else if (q_il) strata::kernels::native_mmvq_il(wq->native_type, wq->native_data, xq_, xil_,
2090                                                                   qfull_ + tb * NH * 2 * HD, (int) N, (int) (NH * 2 * HD), n, ns);
2091                    else native_mmvq(wq->native_type, wq->native_data, xq_, qfull_ + tb * NH * 2 * HD, (int) N,
2092                                     (int) (NH * 2 * HD), n, ns);
2093                    if (qb) {
2094                        if (fuse_nr) {   // the q/gate split reads q straight out of the q|gate rows (stride 2 * HD)
2095                            native_qsa_rms_norm_rope(qfull_ + tb * NH * 2 * HD, (int) (2 * HD), (const float*) wqn->data,
2096                                                     qcur_ + tb * NH * HD, (int) (n * NH), (int) HD, (int) s.n_rot, EPS,
2097                                                     rope_scaling(), pos_ + tb * NH, ns);
2098                        } else {
2099                            copy_rows_strided(qcur_ + tb * NH * HD, qfull_ + tb * NH * 2 * HD, (int64_t) n * NH, HD, 2 * HD, ns);
2100                            norm_rope_s(qcur_ + tb * NH * HD, wqn, (int) (n * NH), (int) HD, pos_ + tb * NH, ns);
2101                        }
2102                        if (st.kv_rot) fwht256_inplace_cuda(qcur_ + tb * NH * HD, (int64_t) n * NH, ns);   // <Hq, Hk> = <q, k>
2103                    } else {
2104                        for (int t = tb; t < te; ++t) {
2105                            float* qc = qcur_ + t * NH * HD;
2106                            if (fuse_nr) {
2107                                native_qsa_rms_norm_rope(qfull_ + t * NH * 2 * HD, (int) (2 * HD), (const float*) wqn->data, qc,
2108                                                         (int) NH, (int) HD, (int) s.n_rot, EPS, rope_scaling(), pos_ + t * NH, ns);
2109                            } else {
2110                                if (cudaMemcpy2DAsync(qc, (size_t) HD * 4, qfull_ + t * NH * 2 * HD, (size_t) HD * 2 * 4,
2111                                                      (size_t) HD * 4, (size_t) NH, cudaMemcpyDeviceToDevice, ns) != cudaSuccess) {
2112                                    err = "verify: the q/gate split failed";
2113                                    return false;
2114                                }
2115                                norm_rope_s(qc, wqn, (int) NH, (int) HD, pos_ + t * NH, ns);
2116                            }
2117                            if (st.kv_rot) fwht256_inplace_cuda(qc, NH, ns);   // <Hq, Hk> = <q, k>
2118                        }
2119                    }
2120                    return true;
2121                };
2122                if (sidem) {
2123                    if (!branch(mfork_, cs, side_, "fork")) return false;
2124                    idx_key(side_);
2125                    idx_snap(side_);
2126                    idx_append(side_);
2127                    idx_query(side_);
2128                    idx_select(side_);
2129                    note_prio_tail(side_, 1);
2130                    if (cudaEventRecord(mjoin_, side_) != cudaSuccess) { err = "verify: the indexer's branch could not join"; return false; }
2131                }
2132                if (side_proj) {   // the queries beside the keys and values (fork b063c13)
2133                    if (q_il && !il_ready && n >= 2) {   // the copy before the fork (mm(wk) / mm(wv) on cs reuse it)
2134                        strata::kernels::native_q8_1_interleave(xq_, xil_, (int) N, n, cs);
2135                        il_ready = true;
2136                    }
2137                    if (!branch(pfork_, cs, side2_, "fork") || !q_chain(side2_)) return false;
2138                    if (cudaEventRecord(pjoin_, side2_) != cudaSuccess) { err = "verify: the queries' branch could not join"; return false; }
2139                }
2140                if (!sidem) idx_key(cs);
2141                stamp(l, 7, grp);
2142                mm(wk, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD));
2143                mm(wv, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD));
2144                if (qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV);
2145                else for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH);
2146                if (st.kv_rot) {   // K and V rotated before they are stored (kv_q4.hpp)
2147                    fwht256_inplace_cuda(kcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);
2148                    fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);
2149                } else if (st.kv_hybrid) {   // K8V4: only V is rotated
2150                    fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);
2151                }
2152                stamp(l, 8, grp);
2153                if (!sidem) idx_snap(cs);
2154                // #783 PR-d (stuchapin909): the window's K/V cells in one launch per pool instead of one per token (a
2155                // batch's rows each have their own K/V, so that case keeps the loop)
2156                if (dec_batch && !g_no_batch_kv && !batch_rec_) {
2157                    const int32_t* step_b = step_ + tb * kStepCount;
2158                    const float* kc_b = kcur_ + tb * NKV * HD;
2159                    const float* vc_b = vcur_ + tb * NKV * HD;
2160                    if (st.kv_hybrid) {   // K8V4: the unused half's lanes folded onto the used pool (layer.cpp)
2161                        // #1188: a streamed state's host copy gets the window's cells too, as the per-token path below
2162                        // writes them - without it a block that was not resident when its cells were appended came
2163                        // back from the host copy without them, and free generation degenerated into repetition
2164                        const KvHostPools hk = kv_hybrid_k_half(st.host), hv = kv_hybrid_v_half(st.host);
2165                        const bool mirror = st.host.present();
2166                        kv_append_q8_steps(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, step_b, kStepCount,
2167                                           kc_b, kc_b, (int) (NKV * HD), n, s, cs, mirror ? &hk : nullptr);
2168                        kv_append_q4_steps(st.v_q4, st.v_q4, st.page_table, step_b, kStepCount, n, vc_b, vc_b, s, cs,
2169                                           mirror ? &hv : nullptr);
2170                    } else if (st.kv_q4)
2171                        kv_append_q4_steps(st.k_q4, st.v_q4, st.page_table, step_b, kStepCount, n, kc_b, vc_b, s, cs,
2172                                           &st.host);
2173                    else if (st.kv_int8)
2174                        kv_append_q8_steps(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, step_b, kStepCount,
2175                                           kc_b, vc_b, (int) (NKV * HD), n, s, cs, &st.host);
2176                    else
2177                        for (int t = tb; t < te; ++t)
2178                            kv_append_step(st.k_pool, st.v_pool, st.page_table, step_ + t * kStepCount,
2179                                           kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st.host);
2180                } else
2181                for (int t = tb; t < te; ++t) {
2182                    const QsaState& st = slot_ss(t).qsa_states[qi];   // the row's own K/V (ss's outside a batch)
2183                    const int32_t* step_t = step_ + t * kStepCount;
2184                    if (st.kv_hybrid) {   // K8V4: the unused half's lanes folded onto the used pool (layer.cpp)
2185                        const KvHostPools hk = kv_hybrid_k_half(st.host), hv = kv_hybrid_v_half(st.host);
2186                        const bool mirror = st.host.present();   // streamed: the host copy too
2187                        kv_append_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, step_t,
2188                                          kcur_ + t * NKV * HD, kcur_ + t * NKV * HD, s, cs, mirror ? &hk : nullptr);
2189                        kv_append_q4_step(st.v_q4, st.v_q4, st.page_table, step_t, vcur_ + t * NKV * HD,
2190                                          vcur_ + t * NKV * HD, s, cs, mirror ? &hv : nullptr);
2191                    } else if (st.kv_q4)
2192                        kv_append_q4_step(st.k_q4, st.v_q4, st.page_table, step_t, kcur_ + t * NKV * HD,
2193                                          vcur_ + t * NKV * HD, s, cs, &st.host);
2194                    else if (st.kv_int8)
2195                        kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, step_t,
2196                                          kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st.host);
2197                    else
2198                        kv_append_step(st.k_pool, st.v_pool, st.page_table, step_t, kcur_ + t * NKV * HD,
2199                                       vcur_ + t * NKV * HD, s, cs, &st.host);
2200                }
2201                if (!sidem) idx_append(cs);
2202                stamp(l, 9, grp);
2203                if (qbr) {
2204                    join(1);   // the indexer query, for the block scores
2205                } else {
2206                    if (!side_proj && !q_chain(cs)) return false;
2207                    if (!sidem) idx_query(cs);
2208                }
2209                stamp(l, 10, grp);
2210                bool streamed = false;   // a streamed KV cache keeps the per-row resolve-then-attend order
2211                if (batch_rec_ && g_qsa_slots)
2212                    for (int t = tb; t < te; ++t) streamed = streamed || slot_ss(t).qsa_states[qi].kv_mode == 1;
2213                // STRATA_BATCH_ATTN_ROWS=1: the window's rows in ONE launch per step - scores with each row's
2214                // own indexer keys, the top-k over all rows (row-independent), attention with each row's own pools -
2215                // instead of 3-4 one-row launches per row; the same per-row arithmetic.  Not with KV streaming
2216                // (qsa_kv_resolve has work per slot then).
2217                static const bool attn_rows = [] {
2218                    const char* v = std::getenv("STRATA_BATCH_ATTN_ROWS");
2219                    return v != nullptr && std::atoi(v) != 0;
2220                }();
2221                bool rows_ok = batch_rec_ && attn_rows && te - tb <= strata::kernels::kAttnRowsMax;
2222                for (int t = tb; rows_ok && t < te; ++t) rows_ok = slot_ss(t).qsa_states[qi].kv_mode != 1;
2223                if (rows_ok) {
2224                    const int n_rows = te - tb;
2225                    strata::kernels::QsaScoreRows sr;
2226                    strata::kernels::QsaAttnPoolsRows pr;
2227                    sr.n = pr.n = n_rows;
2228                    for (int t = tb; t < te; ++t) {
2229                        const QsaState& sx = slot_ss(t).qsa_states[qi];
2230                        sr.pooled[t - tb] = sx.idx_pooled;
2231                        sr.dead[t - tb] = sx.idx_dead;
2232                        pr.p[t - tb] = qsa_attn_pools(sx);
2233                    }
2234                    qsa_block_scores_rows(sr, qidx_ + tb * IQ * ID, step_ + tb * kStepCount, n_rows, max_blocks_, s,
2235                                          scores_ + (size_t) tb * max_blocks_, cs);
2236                    qsa_block_topk(scores_ + (size_t) tb * max_blocks_, step_ + tb * kStepCount, n_rows, max_blocks_, cap_,
2237                                   s, sel_ + (size_t) tb * cap_, cs);
2238                    qsa_decode_attn_batch_rows(qcur_ + tb * NH * HD, pr, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount,
2239                                               cap_, s, attn_scratch_ + (size_t) tb * attn_scratch_floats_,
2240                                               attn_ + tb * NH * HD, n_rows, cs);
2241                } else
2242                if (batch_rec_ && g_qsa_slots && !streamed) {
2243                    // the rows' block scores, top-k and attention, up to 8 rows per launch.  The rows only read
2244                    // their slots' keys and K/V here and write their own scores/sel/scratch/attn rows, so running
2245                    // each step for all rows before the next is the per-row loop's result
2246                    for (int t0 = tb; t0 < te; t0 += kQsaAttnMaxSlots) {
2247                        const int m = std::min(te - t0, kQsaAttnMaxSlots);
2248                        const float* pooled[kQsaAttnMaxSlots];
2249                        const float* dead[kQsaAttnMaxSlots];
2250                        QsaAttnSlotPools px;
2251                        for (int i = 0; i < m; ++i) {
2252                            const QsaState& sx = slot_ss(t0 + i).qsa_states[qi];
2253                            pooled[i] = sx.idx_pooled;
2254                            dead[i] = sx.idx_dead;
2255                            px.p[i] = qsa_attn_pools(sx);
2256                        }
2257                        // a launcher that would not run the per-row call's kernel launches nothing: per-row calls
2258                        if (!qsa_block_scores_slots(pooled, dead, qidx_ + t0 * IQ * ID, step_ + t0 * kStepCount, m,
2259                                                    max_blocks_, s, scores_ + (size_t) t0 * max_blocks_, cs))
2260                            for (int t = t0; t < t0 + m; ++t)
2261                                qsa_block_scores(pooled[t - t0], dead[t - t0], qidx_ + t * IQ * ID, step_ + t * kStepCount,
2262                                                 1, max_blocks_, s, scores_ + (size_t) t * max_blocks_, cs);
2263                        qsa_block_topk(scores_ + (size_t) t0 * max_blocks_, step_ + t0 * kStepCount, m, max_blocks_,
2264                                       cap_, s, sel_ + (size_t) t0 * cap_, cs);
2265                        if (!qsa_decode_attn_slots(qcur_ + t0 * NH * HD, px, sel_ + (size_t) t0 * cap_,
2266                                                   step_ + t0 * kStepCount, cap_, s,
2267                                                   attn_scratch_ + (size_t) t0 * attn_scratch_floats_,
2268                                                   attn_ + t0 * NH * HD, m, cs))
2269                            for (int t = t0; t < t0 + m; ++t)
2270                                qsa_decode_attn_batch(qcur_ + t * NH * HD, px.p[t - t0], sel_ + (size_t) t * cap_,
2271                                                      step_ + t * kStepCount, cap_, s,
2272                                                      attn_scratch_ + (size_t) t * attn_scratch_floats_,
2273                                                      attn_ + t * NH * HD, 1, cs);
2274                    }
2275                } else if (batch_rec_) {   // each row selects and attends over its own slot's K/V
2276                    for (int t = tb; t < te; ++t) {
2277                        const QsaState& sx = slot_ss(t).qsa_states[qi];
2278                        qsa_block_scores(sx.idx_pooled, sx.idx_dead, qidx_ + t * IQ * ID, step_ + t * kStepCount, 1,
2279                                         max_blocks_, s, scores_ + (size_t) t * max_blocks_, cs);
2280                        qsa_block_topk(scores_ + (size_t) t * max_blocks_, step_ + t * kStepCount, 1, max_blocks_, cap_, s,
2281                                       sel_ + (size_t) t * cap_, cs);
2282                        qsa_kv_resolve(sx, *g_, sel_ + (size_t) t * cap_, step_ + t * kStepCount, 1, cap_, cs);
2283                        const QsaAttnPools px = qsa_attn_pools(sx);
2284                        qsa_decode_attn_batch(qcur_ + t * NH * HD, px, sel_ + (size_t) t * cap_, step_ + t * kStepCount,
2285                                              cap_, s, attn_scratch_ + (size_t) t * attn_scratch_floats_,
2286                                              attn_ + t * NH * HD, 1, cs);
2287                    }
2288                } else {
2289                if (!sidem) idx_select(cs);
2290                else if (cudaStreamWaitEvent(cs, mjoin_, 0) != cudaSuccess) {
2291                    err = "verify: the indexer's branch could not join";
2292                    return false;
2293                }
2294                if (side_proj && cudaStreamWaitEvent(cs, pjoin_, 0) != cudaSuccess) {
2295                    err = "verify: the queries' branch could not join";
2296                    return false;
2297                }
2298                stamp(l, 11, grp);
2299                // KV streaming: the n selections' blocks resident (device-side, inside the graph)
2300                qsa_kv_resolve(st, *g_, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, n, cap_, cs);
2301                stamp(l, 12, grp);
2302                if (qbr) join(0);   // the query, for attention
2303                const QsaAttnPools pools = qsa_attn_pools(st);
2304                // STRATA_QSA_SPLIT_ATTN=1: the split tensor-core attention where it applies (int8 KV, sm_80+)
2305                static const bool split_attn = [] { const char* v = std::getenv("STRATA_QSA_SPLIT_ATTN"); return v != nullptr && std::atoi(v) != 0; }();
2306                if (!(split_attn && qsa_decode_attn_split(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_,
2307                                                          step_ + tb * kStepCount, cap_, s,
2308                                                          attn_scratch_ + (size_t) tb * attn_scratch_floats_,
2309                                                          (uint64_t) n * (uint64_t) attn_scratch_floats_, attn_ + tb * NH * HD, n, cs)))
2310                {
2311                strata::dispatch::notef("qsa layer: decode attention batch kernels (split tensor-core attention off or declined) kv_rot=%ld", (long) st.kv_rot);
2312                qsa_decode_attn_batch(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, cap_,
2313                                      s, attn_scratch_ + (size_t) tb * attn_scratch_floats_, attn_ + tb * NH * HD, n, cs);
2314                }
2315                }
2316                stamp(l, 13, grp);
2317                if (st.kv_rot || st.kv_hybrid) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs);   // back: H^-1 = H
2318                if (qb) native_qsa_gate_apply(attn_ + tb * NH * HD, qfull_ + tb * NH * 2 * HD, attn32_ + tb * NH * HD,
2319                                              (int) (n * NH), (int) HD, cs);
2320                else
2321                for (int t = tb; t < te; ++t) {
2322                    if (native_qsa_enabled())
2323                        native_qsa_gate_apply(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, attn32_ + t * NH * HD,
2324                                              (int) NH, (int) HD, cs);
2325                    else
2326                        qsa_gate_apply_f32(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, s, attn32_ + t * NH * HD, cs);
2327                }
2328                stamp(l, 14, grp);
2329                quant_in(attn32_ + tb * NH * HD, (int) (NH * HD));
2330                mm(wo, bo_ + tb * N, (int) (NH * HD), (int) N);
2331            }
2332        } catch (const std::exception& e) {
2333            err = "verify layer " + std::to_string(l) + ": " + e.what();
2334            return false;
2335        }
2336        stamp(l, 16, grp);
2337        const bool q8_ffn = gr_read_group(1, true, inj_, inj2_);   // true: nat_xq_ holds the MoE input's q8_1 (STRATA_QFUSE)
2338        if (latent_ && grp == 0 && h_latxlq_ != nullptr) {   // edge0 CPU share: the D stage RIGHT HERE - mixed_ is
2339            // just normed, the router/plan/doorbell still run after it, and the host's pool call (which starts at
2340            // the ring this pre publishes) waits on the xl doorbell: the D stage now has the whole router+plan+bell
2341            // stretch (~0.6 ms) of head start instead of starting when the pool is already waiting.
2342            quantize_q8_1_rows(mixed_, T, (int) N, lat_xq_, cs);
2343            iq_mmvq(strata::kernels::lat_dense_fmt_to_type(lat_fmt_),
2344                    lat_d_ + (size_t) (l - lat_first_layer_) * lat_dense_.d_bytes(), lat_xq_, lat_xl_, (int) N,
2345                    (int) (lat_G_ * lat_ELL_), T, cs);   // Q4DU: fmt->ggml type (8 Q8_0 / 2 Q4_0)
2346            // Q3_K shared column scales: the pack's A rows are A*diag(s), so scale x by 1/s HERE - once, before
2347            // every consumer below (the GPU experts' q8_1, the act0 q8_0, the CPU pool's f32 doorbell) reads
2348            // lat_xl_.  Packs without scales skip the launch entirely.
2349            if (const float* inv = strata::kernels::lat_gu_colscale_dev((int) l, (int) lat_ELL_))
2350                strata::kernels::lat_colscale_rows(lat_xl_, (int64_t) T * (int64_t) lat_G_, (int) lat_ELL_, inv, cs);
2351            quantize_q8_1_rows(lat_xl_, T * lat_G_, (int) lat_ELL_, lat_xlq_, cs);
2352            // DESIGN-4 + the write-path cut: quantize into a DEVICE buffer, then the copy engine
2353            // lands it in mapped host memory (async, off the compute stream's serial chain - the
2354            // same path the f32 rows take).  Bit-exact to the host's from_float (probe_std); the
2355            // xlseq doorbell after both copies covers it.
2356            quantize_q8_0_rows(lat_xl_, (long long) T * lat_G_, (long long) lat_ELL_, lat_act0_dev_, cs);
2357            cudaMemcpyAsync(m_latact0_, lat_act0_dev_,
2358                            (size_t) T * (size_t) lat_G_ * ((size_t) lat_ELL_ / 32) * 34,
2359                            cudaMemcpyDeviceToHost, cs);
2360            cudaMemcpyAsync(m_latxlq_, lat_xl_, (size_t) T * (size_t) lat_G_ * (size_t) lat_ELL_ * 4,
2361                            cudaMemcpyDeviceToHost, cs);
2362            if (trace_m_ != nullptr) gpu_stamp(trace_m_, (l * kProfPer + 35) * 2, cs);   // K0-probe: D2H done
2363            doorbell_publish_value(nullptr, nullptr, nullptr, 0, 0, nullptr, nullptr, nullptr,
2364                                   (uint32_t*) m_xlseq_, (uint32_t) l + 1, cs);
2365        }
2366        stamp(l, 32, grp);   // the profile only: the FFN-side read ends here, the router starts
2367        // with CPU experts in the window the shared expert forks off once the doorbell is published (it no longer
2368        // competes with it for the GPU's first microseconds); STRATA_SH_FORK_LATE=0 forks at the top as before
2369        static const bool sh_fork_late_env = [] {
2370            const char* e = std::getenv("STRATA_SH_FORK_LATE");
2371            return !e || e[0] != '0';
2372        }();
2373        const bool sh_fork = sh_stream_on() && !prof_on_ && sh_cs_ != nullptr && ev_fork_ != nullptr && ev_join_ != nullptr;
2374        const bool sh_fork_late = sh_fork && sh_fork_late_env && !ar_on();
2375        cudaStream_t sh_stream = sh_fork ? sh_cs_ : cs;
2376        if (sh_fork && !sh_fork_late) {
2377            note_prio_fork(cs);
2378            cudaEventRecord(ev_fork_, cs);
2379            cudaStreamWaitEvent(sh_cs_, ev_fork_, 0);
2380        }
2381        // the window's rows routed in 2 launches (one router GEMV reading the weight once, one
2382        // top-10) instead of 2 per token; every row's arithmetic is the single-token call's (STRATA_DEC_BATCH=0: old)
2383        const WeightRef* w_router = v.get("ffn_gate_inp.weight");
2384        // S26 STRATA_LFUSE=1: the shared expert's gate row rides in the router GEMV launch, its sigmoid + row scale
2385        // move into the combine, gate + up share one launch (all bitwise; resident combine path, 2-8 rows only)
2386        const WeightRef* w_sgi = lfuse_on(n) && g_lfuse_gate() ? v.get("ffn_gate_inp_shexp.weight") : nullptr;
2387        bool sg_ready = false;
2388        if (dec_batch && n > 1 && w_router != nullptr && native_router_enabled() && NE == 512 && K == 10) {
2389            try {
2390                if (w_sgi != nullptr)
2391                    sg_ready = bf16_gemv_fp32_mmvf_multi_aux(mixed_ + tb * N, N, (const uint16_t*) w_router->data,
2392                                                             logits_ + tb * NE, NE, N, NE, n,
2393                                                             (const uint16_t*) w_sgi->data, sh_g_ + tb, 1, cs);
2394                if (!sg_ready)
2395                bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) w_router->data, logits_ + tb * NE, NE, N,
2396                                          NE, n, cs);
2397                native_router_top10_multi(logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, n, cs);
2398            } catch (const std::exception& e) { err = "verify router: " + std::string(e.what()); return false; }
2399#if defined(STRATA_HIP_GFX906)
2400        } else if (dec_batch) {
2401            // gfx906: the Coder's 256-expert router (the native router is 512 x 10 only) for the whole window in one
2402            // multi-column BF16 projection and one top-k, bitwise the per-token calls (route_window_parity); ~3 ms
2403            // of a ~55 ms verify window on 2x MI50.  STRATA_ROUTE_PER_TOKEN=1: the per-token calls.
2404            if (!moe_route_window(wt, g, l, K, ss.moe, mixed_ + tb * N, logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, n,
2405                                  cs, err))
2406                return false;
2407#endif
2408        } else
2409        for (int t = tb; t < te; ++t) {
2410            MoEBuffers mb = ss.moe;
2411            mb.logits = logits_ + t * NE; mb.ids = ids_ + t * K; mb.weights = w_ + t * K;
2412            if (!moe_route(wt, g, l, K, mb, mixed_ + t * N, cs, err, nullptr)) return false;
2413        }
2414        strata::dispatch::notef("router layer: batched native router=%ld, shared-expert gate in the router launch=%ld, route_prior=%ld", (long) (dec_batch && n > 1 && w_router != nullptr && native_router_enabled() && NE == 512 && K == 10), (long) sg_ready, (long) (g_route_prior() > 0.0f));
2415        // STRATA_ROUTE_PRIOR=lambda (changes the output): the top-10 picked again with a logit bonus for the resident
2416        // experts; the weights stay the router's (route_prior.cu).  g_route_prior() above: off unless STRATA_ROUTE_PRIOR is set
2417        // (measured on an RTX 3060 12 GB at 2.0: story +37.6%, code +35.2%; on an RTX PRO 5000 72 GB -1.9% / -0.5%, on 2x RTX A4000
2418        // -4.2% / +11.0%, so it only helps a card that streams most experts).
2419        const float route_prior = g_route_prior();
2420        if (route_prior > 0.0f && NE == 512 && K == 10 && hits_.d_res != nullptr)
2421            route_prior_top10(logits_ + tb * NE, hits_.d_res + l * g.n_expert, route_prior, ids_ + tb * K, w_ + tb * K, n, cs);
2422        if (route_resident_cfg().margin > 0.0f && NE == 512 && K == 10 && hits_.d_res != nullptr) {
2423            // STRATA_ROUTE_RESIDENT: after the router, before the plan/doorbell read ids_/w_ (opt-in, changes the output)
2424            try {
2425                native_route_resident(logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, hits_.d_res + l * g.n_expert, n,
2426                                      route_resident_cfg().margin, route_resident_cfg().lo, route_resident_cfg().hi,
2427                                      rr_stats_ != nullptr ? rr_stats_ + (n <= 8 ? 4 : 0) : nullptr, cs);
2428            } catch (const std::exception& e) { err = "verify route-resident: " + std::string(e.what()); return false; }
2429        }
2430        if (rs_on_ && G == 1 && n <= 16 && T <= 16)
2431            strata::kernels::route_marginal_stats(ids_ + tb * K, n, (int) K, rs_dev_ + ((size_t) T * (size_t) g.n_layers + (size_t) l) * 16, cs);
2432        if (ar_on()) {
2433            resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert,
2434                          hits_.cache_base, slot_off_d_, (long long) hits_.blob,
2435                          plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, nullptr, 0, cs, m_plan_err_);
2436        } else {
2437            if (device_plan_)   // E-6: every routed expert resident: this group's plan without the host
2438                resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert,
2439                              hits_.cache_base, slot_off_d_, (long long) hits_.blob,
2440                              plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, skip_ + grp,
2441                              (uint32_t) ((l - lb_) * G + grp + 1), cs);
2442#if defined(STRATA_USE_HIP)
2443            if (g_doorbell_store)   // #649 A/B: the step's ring stored, not incremented over PCIe
2444                doorbell_publish_value(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N,
2445                                       m_ids_ + tb * K, m_w_ + tb * K, m_seq_, (uint32_t) ((l - lb_) * G + grp + 1), cs);
2446            else
2447#endif
2448            // #578: the helper GPUs reduce with the routing weights - publish them; set_always_publish: the rows
2449            // whatever the device's residency table says (pipelined windows)
2450            if (remote_opt_ || always_publish_)
2451                doorbell_publish(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N,
2452                                 m_ids_ + tb * K, m_w_ + tb * K, m_seq_, cs);
2453            else {
2454                const int32_t* layer_res = hits_.d_res != nullptr ? (hits_.d_res + l * g.n_expert) : nullptr;
2455                doorbell_publish_res(xm, ids_ + tb * K, layer_res, (int) g.n_expert, (int64_t) n * N, (int64_t) n * K,
2456                                     m_x_ + tb * N, m_ids_ + tb * K, m_seq_, cs);
2457            }
2458            if (sh_fork_late) {
2459                note_prio_fork(cs);
2460                cudaEventRecord(ev_fork_, cs);
2461                cudaStreamWaitEvent(sh_cs_, ev_fork_, 0);
2462            }
2463        }
2464        stamp(l, 17, grp);
2465        bool qdedup = false;   // STRATA_VERIFY_QDEDUP took effect: the experts' q8_1 image of xm is already made
2466        {
2467            const WeightRef *wgi = need(v, "ffn_gate_inp_shexp.weight", err), *wsg = need(v, "ffn_gate_shexp.weight", err),
2468                            *wsu = need(v, "ffn_up_shexp.weight", err), *wsd = need(v, "ffn_down_shexp.weight", err);
2469            if (!wgi || !wsg || !wsu || !wsd) return false;
2470            if (!native_of(wsg, v.name("ffn_gate_shexp.weight"), err) || !native_of(wsu, v.name("ffn_up_shexp.weight"), err) ||
2471                !native_of(wsd, v.name("ffn_down_shexp.weight"), err))
2472                return false;
2473            NativeSharedWeights nsw;
2474            nsw.gate_type = wsg->native_type; nsw.gate_data = wsg->native_data;
2475            nsw.up_type = wsu->native_type; nsw.up_data = wsu->native_data;
2476            nsw.down_type = wsd->native_type; nsw.down_data = wsd->native_data;
2477            nsw.q8_1 = sh_fork ? sh_xq_ : xq_;
2478            // STRATA_VERIFY_QDEDUP=1 (not with the forked shared-expert stream, which quantizes into its own buffer): the
2479            // experts' q8_1 image of xm is made first and the shared expert's gate/up read it (quantize_q8_1_rows and
2480            // native_quantize_q8_1 write the same bytes)
2481            qdedup = g_qdedup() && !sh_fork && strata::kernels::cpu::expert_layout().native;
2482            if (qdedup && !q8_ffn) quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs);
2483            if (!shared_expert_native_bf16_enabled()) {
2484                if (dec_batch) f32_to_bf16_bulk(mixed_ + tb * N, sh_bf16_ + tb * N, (int64_t) n * N, sh_stream);   // contiguous rows
2485                else for (int t = tb; t < te; ++t) f32_to_bf16_bulk(mixed_ + t * N, sh_bf16_ + t * N, N, sh_stream);
2486            }
2487            try {
2488                shared_expert_multi(n, xm, sh_bf16_ + tb * N, nsw, (const uint16_t*) wgi->data, sh_gate_ + (size_t) tb * g.n_ff,
2489                                    sh_up_ + (size_t) tb * g.n_ff, sh_g_ + tb, shared_ + tb * N, N, g.n_ff, sh_stream,
2490                                    qdedup ? (const void*) (nat_xq_ + (size_t) tb * (N / 32) * 36) : nullptr,
2491                                    (sg_ready ? 1 : 0) | (lfuse_on(n) && g_lfuse_pair() ? 2 : 0));
2492                sg_gated_[grp] = sg_ready;
2493            } catch (const std::exception& e) {
2494                err = std::string("verify shared expert: ") + e.what();
2495                return false;
2496            }
2497            if (sh_fork) {
2498                note_prio_tail(sh_cs_, -1);
2499                cudaEventRecord(ev_join_, sh_cs_);
2500            }
2501        }
2502        if (strata::kernels::cpu::expert_layout().native) {
2503            // APR: Hadamard-folded gate/up take H (s * x); xm itself stays as it is (the shared expert above and the
2504            // doorbell copy for the CPU pool, which rotates its own in native_quant_act). The q8_1 image of xm that
2505            // STRATA_QFUSE / STRATA_VERIFY_QDEDUP may already have written is of the unrotated input, so a folded layer
2506            // always rewrites it from the rotated rows (same stream, after the shared expert has read it).
2507            const auto& f = strata::kernels::cpu::expert_layout().fmt[(size_t) l];
2508            if (f.had_gu) {   // nat_xr_ exists: init carved it because this layer is folded (had_gu_any)
2509                hadamard_rows(xm, nat_xr_ + (size_t) tb * N, n, N, f.had_block, had_sx_, cs);
2510                quantize_q8_1_rows(nat_xr_ + (size_t) tb * N, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs);
2511            } else if (!qdedup && !q8_ffn) {
2512                quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs);
2513            }
2514        } else
2515            quantize_q8_0_scaled(xm, hit_xq_ + (size_t) tb * (N / 32) * 34, hit_xs_ + (size_t) tb * (N / 32), (int64_t) n * N, cs);
2516        stamp(l, 18, grp);
2517        return true;
2518    };
2519
2520    // ---------------------------------------------------------------- post(l, group): experts, combine
2521    static const bool fuse_head_gr_env = [] {
2522        const char* e = std::getenv("STRATA_FUSE_HEAD_GR");
2523        return e && e[0] == '1';
2524    }();
2525    const bool fuse_head_gr = fuse_head_gr_env && (le_ == g.n_layers) && (head_ != nullptr && head_->loaded()) &&
2526                              !cvec().covers(g.n_layers - 1);
2527    auto post = [&](int64_t l, int grp) -> bool {
2528        const int tb = tb_[grp], te = te_[grp], n = te - tb;
2529        const uint32_t ring = (uint32_t) ((l - lb_) * G + grp + 1);
2530        const int64_t cap = (int64_t) n * K, capx = (int64_t) max_t_ * K;
2531        int32_t* pl = plan_ + (size_t) grp * (size_t) (plan_i32_ + 16);
2532        const int32_t* p_counts = pl;
2533        const int32_t* p_start = pl + 4;
2534        const int32_t* p_dst = p_start + capx + 1;
2535        const int32_t* p_tok = p_dst + capx;
2536        const int64_t ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll;
2537        const unsigned long long* p_ptr = (const unsigned long long*) (pl + ptr_off);
2538        const unsigned long long* p_ptr2 = p_ptr + capx;
2539        const int32_t* p_start2 = pl + ptr_off + 4 * capx;
2540        float* hit_out = hit_out_ + (size_t) tb * K * N;
2541        float* parts_out = parts_ + (size_t) tb * K * N;
2542        const auto& lay = strata::kernels::cpu::expert_layout();
2543        // plan v0.3 P6: the VRAM groups now; the PCIe groups once the copy engine has landed them in staging.
2544        // `gy`: the native launch's groups side by side (0: cap, one block row per possible group).
2545        // `vram`: the groups point into this GPU's expert slots - a layer STRATA_EXPERT_NIBBLE converted holds its
2546        // gate/up there as 4-bit codes (expert_nibble.hpp); the PCIe share's blobs (host memory, staging) never do.
2547        auto grouped = [&](const unsigned long long* gp, const int32_t* gs, const int32_t* gn, int64_t gy, float* dst_buf,
2548                           bool vram) {
2549            if (lay.native) {
2550                // the layer's GGUF formats (i-quant gate/up, Q2_0 / IQ4_NL down)
2551                const auto& f = lay.fmt[(size_t) l];
2552#if STRATA_EXPERT_NIBBLE_BUILT
2553                NativeExpertLayout L = vram && strata::core::nibble::layer(l).on
2554                                           ? native_expert_layout_nib(f.gu_type, f.d_type, f.n_embd, f.n_ff)
2555                                           : native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff);
2556#else
2557                (void) vram;
2558                NativeExpertLayout L = native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff);
2559#endif
2560                if (f.had_d) { L.had_block = f.had_block; L.d_signs = had_sh_; }   // APR: h is rotated in there
2561                native_expert_grouped(L, gp, gs, gn, p_dst, p_tok, cap, cap,
2562                                      nat_xq_ + (size_t) tb * (N / 32) * 36, hit_scratch_, dst_buf, cs, gy);
2563            } else {
2564                moe_grouped_s2_window(gp, gs, gn, p_dst, p_tok, cap, cap, hit_xq_ + (size_t) tb * (N / 32) * 34,
2565                                      hit_xs_ + (size_t) tb * (N / 32), hit_scratch_, dst_buf, cs, n);   // (a group holds <= n entries)
2566            }
2567        };
2568        bool hits_in_combine = false;
2569        if (latent_) {
2570            static const bool u_gpu_mode = [] { const char* v = std::getenv("STRATA_LATENT_U_GPU"); return v != nullptr && std::atoi(v) != 0; }();
2571            if (device_plan_ && !u_gpu_mode) {   // the non-u_gpu tail ends in moe_hit_add_mapped's fused wait: no
2572                err = "verify latent: device-plan requires STRATA_LATENT_U_GPU=1";   // skip-aware variant yet
2573                return false;
2574            }
2575            // (the D stage + its mapped copy + doorbell run in pre(l, 0), right after the FFN read - see there)
2576            // The GPU plan arrives through mapped memory, exactly like the non-resident path below.
2577            if (device_plan_) {                            // E-6 latent: the device built this group's plan (all-resident)
2578                wait_flag_ge_or(m_flagA_, ring, skip_ + grp, cs);
2579                copy_i32_from_mapped_unless(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, skip_ + grp, ring, cs);
2580            } else {
2581            wait_flag_ge(m_flagA_, ring, cs);              // the pool published this group's GPU plan
2582            copy_i32_from_mapped(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs);
2583            }
2584            // A reads q8_1 rows of xl (row = token*G + labels[expert]), not the plain token rows.
2585            int32_t* p_tokw = const_cast<int32_t*>(p_tok);
2586            latent_plan_rows(p_tokw, p_dst, p_counts, ids_ + (size_t) tb * K,
2587                             lat_labels_dev_ + (size_t) l * (size_t) lat_E_, lat_E_, tb, lat_G_, (int) K, cs);
2588            // (the D stage + its mapped copy + doorbell ran in pre(l, G-1): see the tail of `pre`)
2589            float* lat_yl_grp = lat_yl_ + (size_t) tb * K * (size_t) lat_ELL_;
2590            const auto& LF = lay.fmt[(size_t) l];
2591            const NativeExpertLayout La = native_expert_layout(LF.gu_type, LF.d_type, (int) lat_ELL_, (int) lat_I_);
2592            stamp(l, 19, grp);
2593            native_expert_grouped(La, p_ptr, p_start, p_counts, p_dst, p_tok, cap, cap, lat_xlq_, hit_scratch_,
2594                                  lat_yl_grp, cs, 0);   // the VRAM-resident share
2595            stamp(l, 20, grp);
2596            if (device_plan_)
2597                wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs);   // E-6 latent: no PCIe share in an all-resident plan
2598            else
2599            wait_flag_ge(m_flagB_, ring, cs);           // the PCIe share's blobs are staged (DMA) or mapped
2600            if (sink_.pcie_mode == 2) {                 // stage with a copy kernel, then point at staging (plan v0.3 P6)
2601                const int64_t per = 4 * kStagingBlobs;   // latent: each group's whole PCIe share fits (n*K <= 64 (edge0: T=4 x K=10 = 40))
2602                uint8_t* stage = staging_ + (size_t) (grp * per) * lay.max_blob;
2603                fetch_blobs(p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), (int) per, cs);
2604                rebase_ptrs((unsigned long long*) p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), cs);
2605            }
2606            stamp(l, 21, grp);
2607            native_expert_grouped(La, p_ptr2, p_start2, p_counts + 2, p_dst, p_tok, cap, cap, lat_xlq_, hit_scratch_,
2608                                  lat_yl_grp, cs, kPcieGroupRows);   // the PCIe share
2609            // U: route r reads yl[r] and U[labels[ids[r]]]; the result is parts_ (one K*N block per group, route order)
2610            quantize_q8_1_rows(lat_yl_grp, cap, (int) lat_ELL_, lat_uq_, cs);
2611            latent_u_grouped(lat_u_ + (size_t) (l - lat_first_layer_) * lat_dense_.u_bytes(), (const uint8_t*) lat_uq_, ids_ + (size_t) tb * K,
2612                             lat_labels_dev_ + (size_t) l * (size_t) lat_E_, lat_E_, cap, (int) lat_ELL_, (int) N,
2613                             hit_out, cs, lat_fmt_);
2614            // The CPU pool's share: its full N-dim contributions land in the mapped rows (m_ymiss_); copy them into
2615            // parts_ (the GPU's own rows are zeroed there), then add the GPU's U-stage rows computed above into hit_out.
2616            static const bool seg_split = std::getenv("STRATA_SEG_SPLIT") != nullptr;   // the copy-segment breakdown
2617            static const bool u_gpu = [] { const char* v = std::getenv("STRATA_LATENT_U_GPU"); return v != nullptr && std::atoi(v) != 0; }();
2618            if (u_gpu) {   // knife-0: the CPU's hq rows -> U on the GPU, into parts_ directly (fused wait + U.hq + hit_out)
2619                if (trace_m_ != nullptr) gpu_stamp(trace_m_, (l * kProfPer + 36) * 2, cs);   // T-TRI breadcrumb (not a profile slot)
2620                if (device_plan_)
2621                    wait_flag_ge_or(m_flag_, ring, skip_ + grp, cs);   // E-6 latent: no CPU rows in an all-resident plan
2622                else
2623                wait_flag_ge(m_flag_, ring, cs);   // separate 1-block wait (not 12800 fused spins)
2624                if (trace_m_ != nullptr) gpu_stamp(trace_m_, (l * kProfPer + 37) * 2, cs);   // T-TRI breadcrumb
2625                // knife-0: a copy KERNEL, not cudaMemcpyAsync: a host-issued H2D inside the verify window (the GPU
2626                // spinning on the flag it raises) is the issue #31 driver-lock deadlock; the kernel moves the same
2627                // bytes with no host CUDA call (the engine's own remedy for this path, generate.cpp:10329-10333).
2628                strata::kernels::copy_bytes_from_mapped(hq_dev_, m_ymiss_ + (size_t) tb * K * N,
2629                                                        (size_t) cap * ((size_t) lat_ELL_ / 32 * 36), cs);
2630                strata::kernels::latent_u_matvec(lat_u_ + (size_t) (l - lat_first_layer_) * lat_dense_.u_bytes(),
2631                                                 (const uint8_t*) hq_dev_,
2632                                                 ids_ + (size_t) tb * K, lat_labels_dev_ + (size_t) l * (size_t) lat_E_,
2633                                                 p_dst, p_counts + 1, (int64_t) lat_E_, cap,
2634                                                 (int) lat_ELL_, (int) N, (int) lat_G_, parts_out, cs, lat_fmt_);
2635                moe_hit_set(parts_out, hit_out, p_dst, p_counts + 1, cap, N, cs);   // knife-0: assign, as u0 does
2636                if (trace_m_ != nullptr) gpu_stamp(trace_m_, (l * kProfPer + 38) * 2, cs);   // T-TRI breadcrumb
2637            } else if (seg_split) {   // SEGSPLIT: the measured three-step form (wait / copy / add separated)
2638                stamp(l, 32, grp);                                        // before-wait (slot 32: unused)
2639                wait_flag_ge(m_flag_, ring, cs);
2640                stamp(l, 33, grp);                                        // wait done (ymWait ends)
2641                copy_rows_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K, N,
2642                                      p_dst, p_counts + 1, cs);
2643                stamp(l, 34, grp);                                        // copy done (ymCopy ends)
2644                moe_hit_add(parts_out, hit_out, p_dst, p_counts + 1, cap, N, cs);
2645                stamp(l, 35, grp);                                        // add done (ymAdd ends)
2646            } else {
2647            moe_hit_add_mapped(parts_out, hit_out, m_ymiss_ + (size_t) tb * K * N, p_dst, p_counts + 1, cap, N,
2648                               (const volatile uint32_t*) m_flag_, ring, cs);   // LATENT-CUT-A: the fused wait+add
2649            }
2650            hits_in_combine = false;
2651        } else if (ar_on()) {
2652            strata::dispatch::note("experts layer: all-resident device plan, grouped experts straight into the parts (no doorbell, no CPU rows)");
2653            stamp(l, 19, grp);
2654            grouped(p_ptr, p_start, p_counts, 0, parts_out, true);
2655            stamp(l, 20, grp);
2656        } else {
2657            strata::dispatch::notef("experts layer: partial residency, plan from %ld (1 = device plan, 0 = host pool), pcie_mode=%ld, remote_opt=%ld", (long) device_plan_, (long) sink_.pcie_mode, (long) (remote_opt_ != nullptr));
2658            if (device_plan_) {   // E-6: skipped when the device planned this group (all its experts resident)
2659                wait_flag_ge_or(m_flagA_, ring, skip_ + grp, cs);
2660                copy_i32_from_mapped_unless(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, skip_ + grp, ring, cs);
2661            } else {
2662                if (fuse_wait_on() && !prof_on_ && m_bal_ == nullptr) {   // 143-amdk: one launch for the wait and the copy
2663                    wait_copy_i32_from_mapped(m_flagA_, ring, pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs);
2664                } else {
2665                if (m_bal_ != nullptr)   // set_pcie_balance: the GPU's share starts as the plan arrives
2666                    wait_flag_ge_stamped(m_flagA_, ring, nullptr, m_bal_ + ((l - lb_) * 2 + grp) * 4, cs);
2667                else
2668                    wait_flag_ge(m_flagA_, ring, cs);              // the pool published this group's GPU plan
2669                copy_i32_from_mapped(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs);
2670                }
2671            }
2672            stamp(l, 19, grp);
2673            grouped(p_ptr, p_start, p_counts, 0, hit_out, true);
2674            stamp(l, 20, grp);
2675            if (device_plan_) wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs);
2676            else if (m_bal_ != nullptr)   // set_pcie_balance: the PCIe part starts
2677                wait_flag_ge_stamped(m_flagB_, ring, m_bal_ + ((l - lb_) * 2 + grp) * 4 + 1, nullptr, cs);
2678            else { if (trace_m_ != nullptr) gpu_stamp(trace_m_, (l * kProfPer + 15) * 2, cs); wait_flag_ge(m_flagB_, ring, cs); if (trace_m_ != nullptr) gpu_stamp(trace_m_, (l * kProfPer + 25) * 2, cs); }   // K0: flagB wait enter(40)/exit(41)
2679            if (sink_.pcie_mode == 2) {                            // stage it with a copy kernel, then point at staging
2680                const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs;
2681                uint8_t* stage = staging_ + (size_t) (grp * per) * lay.max_blob;
2682                const unsigned long long* p_dst2 = (const unsigned long long*) (pl + dst2_off_);   // STRATA_ADAPT_FETCH
2683                fetch_blobs(p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), (int) per, cs, p_dst2);
2684                rebase_ptrs((unsigned long long*) p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), cs, p_dst2);
2685            }
2686            stamp(l, 21, grp);
2687            // the PCIe share is pcie_frac of the misses: a few groups when the cache is cold, usually none (always none at
2688            // pcie_frac 0), so its launch is kPcieGroupRows block rows striding over the groups, not cap of them
2689            grouped(p_ptr2, p_start2, p_counts + 2, kPcieGroupRows, hit_out, false);
2690            stamp(l, 22, grp);
2691            if (device_plan_) {   // no CPU share when the device planned the group: its rows are zeros
2692                wait_flag_ge_or(m_flag_, ring, skip_ + grp, cs);
2693                copy_or_zero_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (long long) n * K * N,
2694                                         skip_ + grp, ring, cs);
2695            } else {
2696                const bool fuse_rows = fuse_rows_on() && !prof_on_ && !remote_opt_ && dec_batch && m_bal_ == nullptr;   // 143-amdk
2697                if (!fuse_rows) {
2698                    if (m_bal_ != nullptr)   // set_pcie_balance: ... and ends as it waits for the CPU's rows
2699                        wait_flag_ge_stamped(m_flag_, ring, m_bal_ + ((l - lb_) * 2 + grp) * 4 + 2, nullptr, cs);
2700                    else {
2701                        if (trace_m_ != nullptr) gpu_stamp(trace_m_, (l * kProfPer + 27) * 2, cs);
2702                        wait_flag_ge(m_flag_, ring, cs);           // the CPU's share is in the mapped rows
2703                        if (trace_m_ != nullptr) gpu_stamp(trace_m_, (l * kProfPer + 28) * 2, cs);
2704                    }
2705                }
2706                stamp(l, 23, grp);
2707                if (remote_opt_)   // #578: the helper's rows come back reduced; skip them as well
2708                    remote_opt_->copy_rows(parts_out, m_ymiss_ + (size_t) tb * K * N, tb, n, p_dst, p_counts + 1, cs);
2709                else if (fuse_rows)   // the wait folded into the copy's blocks
2710                    copy_rows_from_mapped_after(m_flag_, ring, parts_out, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K, N,
2711                                                p_dst, p_counts + 1, cs);
2712                else if (dec_batch)   // only the CPU rows cross PCIe (p_dst[0, counts[1]) = the GPU's own rows)
2713                    copy_rows_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K, N,
2714                                          p_dst, p_counts + 1, cs);
2715                else
2716                    copy_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K * N, cs);
2717            }
2718            // 143-amdk: the add of the GPU's hit rows is done by the combine that follows (one launch fewer)
2719            hits_in_combine = fuse_hits_on() && !prof_on_ && !remote_opt_ && !sg_gated_[grp] && dec_batch && n > 1 &&
2720                              native_moe_combine_enabled() && n <= 8 &&
2721                              native_moe_combine_hits_supported(parts_ + (size_t) tb * K * N, shared_ + tb * N, bo_ + tb * N, N, K, n);
2722            strata::dispatch::notef("experts layer: cpu rows via %ld (1 = fused wait+copy, 0 = wait then copy), hits in combine=%ld", (long) (fuse_rows_on() && !prof_on_ && !remote_opt_ && dec_batch && m_bal_ == nullptr), (long) hits_in_combine);
2723            if (!hits_in_combine) moe_hit_add(parts_out, hit_out, p_dst, p_counts + 1, cap, N, cs);
2724        }
2725        // Same condition as `sh_fork` above, which is per group and out of scope here: wait only when the fork
2726        // actually ran (a wait on an event never recorded is a no-op, but saying it outright reads better).
2727        if (sh_stream_on() && !prof_on_ && sh_cs_ != nullptr && ev_fork_ != nullptr && ev_join_ != nullptr) {
2728            cudaStreamWaitEvent(cs, ev_join_, 0);
2729        }
2730        strata::dispatch::notef("combine layer: kind %ld (0 per-token, 1 multi, 2 multi+hits, 3 multi+hits gated)", (long) (sg_gated_[grp] ? 3 : hits_in_combine ? 2 : (dec_batch && n > 1 && native_moe_combine_enabled()) ? 1 : 0));
2731        if (sg_gated_[grp]) {   // STRATA_LFUSE: the shared expert's gate was not applied: the combine applies it (all rows are hits)
2732            try {
2733                native_moe_combine_multi_hits_gated(parts_out, w_ + tb * K, shared_ + tb * N, sh_g_ + tb, bo_ + tb * N, N, K, n, cs);
2734            } catch (const std::exception& e) { err = "verify combine: " + std::string(e.what()); return false; }
2735        } else
2736        if (hits_in_combine) {
2737            try {
2738                native_moe_combine_multi_hits_added(parts_ + (size_t) tb * K * N, hit_out, p_dst, p_counts + 1, w_ + tb * K,
2739                                                    shared_ + tb * N, bo_ + tb * N, N, K, n, cs);
2740            } catch (const std::exception& e) { err = "verify combine: " + std::string(e.what()); return false; }
2741        } else
2742        if (dec_batch && n > 1 && native_moe_combine_enabled()) {   // one launch for the window's rows
2743            try {
2744                native_moe_combine_multi(parts_ + (size_t) tb * K * N, w_ + tb * K, shared_ + tb * N, bo_ + tb * N, N, K, n, cs);
2745            } catch (const std::exception& e) { err = "verify combine: " + std::string(e.what()); return false; }
2746        } else
2747        for (int t = tb; t < te; ++t) {
2748            MoEBuffers mb = ss.moe;
2749            mb.weights = w_ + t * K; mb.shared = shared_ + t * N;
2750            if (!moe_combine_parts(g, l, K, mb, parts_ + (size_t) t * K * N, bo_ + t * N, cs, err)) return false;
2751        }
2752        if (remote_opt_) remote_opt_->combine(bo_ + tb * N, y_dummy_ + tb * N, tb, n,
2753                              device_plan_ ? skip_ + grp : nullptr, ring, cs);
2754        stamp(l, 24, grp);
2755        if (tap_on_ && (!batch_rec_ || tap_batch_) && l < (int64_t) tap_slot_.size() && tap_slot_[(size_t) l] >= 0) {
2756            // the layer's completed output: R with this FFN half's write applied (the next layer's read would fold it), the mean of
2757            // the hc streams, all rows of the group in one launch
2758            const int64_t nt = (int64_t) tap_layers_.size();
2759#if defined(STRATA_HAVE_DFLASH2)
2760            strata::kernels::df2_tap_gr(Rt(tb), HC * N, bo_ + tb * N, N, inj2_ + tb * HC, HC, tap_dev_ + ((size_t) tb * nt + (size_t) tap_slot_[(size_t) l]) * N,
2761                                        nt * N, n, N, (int) HC, cs);
2762#else   // builds without the DFlash2 kernels (Metal, SYCL): the research dump's per-row path
2763            for (int t = tb; t < te; ++t) {
2764                cudaMemcpyAsync(tap_scratch_, Rt(t), (size_t) HC * N * 4, cudaMemcpyDeviceToDevice, cs);
2765                gr_write(tap_scratch_, bo_ + t * N, inj2_ + t * HC, gs, tap_scratch_, cs);
2766                hc_mean_streams(tap_scratch_, tap_dev_ + ((size_t) t * nt + (size_t) tap_slot_[(size_t) l]) * N, N, (int) HC, cs);
2767            }
2768#endif
2769        }
2770        if (l == g.n_layers - 1) {
2771            if (!fuse_head_gr) {
2772                if (dec_batch && !g_no_multi_gr) gr_write_multi(Rt(tb), bo_ + tb * N, inj2_ + tb * HC, gs, Rt(tb), n, cs);
2773                else for (int t = tb; t < te; ++t) gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs);
2774                if (cvec().covers(l)) cvec_apply(Rt(tb), l, n, HC * N, nullptr, 0, nullptr, 0, false, cs);
2775            }
2776        } else if (cvec().covers(l)) {
2777            cvec_apply(Rt(tb), l, n, HC * N, bo_ + tb * N, N, inj2_ + tb * HC, HC, true, cs);
2778        }
2779        return true;
2780    };
2781
2782    for (int grp = 0; grp < G; ++grp)
2783        if (!pre(lb_, grp)) return false;
2784    for (int64_t l = lb_; l < le_; ++l)
2785        for (int grp = 0; grp < G; ++grp) {
2786            if (!post(l, grp)) return false;
2787            if (l + 1 < le_ && !pre(l + 1, grp)) return false;
2788        }
2789    if (le_ < g.n_layers) {   // a layer split's earlier stage: hand the residual on, no head
2790        float* hout = hand_out_ + (size_t) hrow0 * HB;
2791        if (hflag_out_d_ != nullptr && !batch_rec_) {   // the overlapped split: payload + the next stage's flag
2792            handoff_publish(hout, R_, (int64_t) T * HC * N, bo_, (int64_t) T * N, inj2_, (int64_t) T * HC, hcount_d_,
2793                            hflag_out_d_, cs, g_test_drop > 0 ? hdrop_d_ : nullptr);   // the test word only with the hook on
2794            return true;
2795        }
2796        copy_from_mapped(hout, R_, (int64_t) T * HC * N, cs);
2797        copy_from_mapped(hout + (size_t) T * HC * N, bo_, (int64_t) T * N, cs);
2798        copy_from_mapped(hout + (size_t) T * (HC + 1) * N, inj2_, (int64_t) T * HC, cs);
2799        return true;
2800    }
2801
2802    // ---- the head, T columns, and the argmax of each.  The final mixer and the head matvec take at most
2803    // kFusedGrMaxT columns a launch: a longer window (--lookup-max-t) runs them in chunks of that many columns (one
2804    // chunk - the same launches as before - for every window up to kFusedGrMaxT tokens)
2805    stamp(g.n_layers, 0, 0);
2806    {
2807        const WeightRef *hn = wt.find("output_hc_norm.weight"), *hd = wt.find("output_hc_down.weight"),
2808                        *hu = wt.find("output_hc_up.weight");
2809        if (!hn || !hd || !hu) { err = "verify: an output_hc_* weight is missing"; return false; }
2810      for (int h0 = 0; h0 < T; h0 += kFusedGrMaxT) {
2811        const int HT = std::min(T - h0, kFusedGrMaxT);   // this chunk's columns: h0 .. h0 + HT
2812        // S25 (STRATA_HC_Q8=1): the final mixer from the GGUF's Q8_0 projections too, through the same multi read
2813        // (no pending write, no inject)
2814        const bool mix_q8 = hd->hc_q8 != nullptr && hu->hc_q8 != nullptr && head_ != nullptr && head_->loaded();
2815        bool q8_head = false;   // the fused read wrote the head's q8_1 activation image (xq_) itself
2816        strata::dispatch::notef("head: final mixer q8=%ld fuse_head_gr=%ld native_head=%ld", (long) mix_q8, (long) fuse_head_gr, (long) (head_ != nullptr && head_->loaded()));
2817        if (head_ != nullptr && head_->loaded())   // the head matrix itself is counted by native_mmvq / native_mmvq_il (n_out = the vocabulary)
2818            strata::dispatch::notef("head: type %ld, T=%ld columns, vocabulary %ld", (long) head_->type(), (long) T, (long) n_vocab_);
2819        if (mix_q8) {
2820            FusedGrArgs fa[kFusedGrMaxT];
2821            for (int t = h0; t < h0 + HT; ++t) {
2822                FusedGrArgs& a = fa[t - h0];
2823                a.R = Rt(t); a.R_out = Rt(t); a.apply = false;
2824                a.w_norm = (const float*) hn->data; a.w_down = (const uint16_t*) hd->data;
2825                a.w_up = (const uint16_t*) hu->data; a.w_inject = nullptr;
2826                a.q8_down = (const uint8_t*) hd->hc_q8; a.q8_up = (const uint8_t*) hu->hc_q8;
2827                a.eps = EPS; a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC;
2828                a.mixed = head_mixed_ + t * N;
2829                if (qcnt_ != nullptr) { a.q8_cnt = qcnt_; a.q8_mixed = xq_ + (size_t) (t - h0) * (N / 32) * 36; }
2830            }
2831            q8_head = fused_gr_read_multi(fa, HT, xn_ + (size_t) h0 * HC * N, cs);
2832        }
2833        else if (fuse_head_gr) {
2834            FusedGrArgs fa[kFusedGrMaxT];
2835            for (int t = h0; t < h0 + HT; ++t) {
2836                FusedGrArgs& a = fa[t - h0];
2837                a.R = Rt(t); a.R_out = Rt(t); a.apply = true;
2838                a.bo_prev = bo_ + t * N; a.inj_prev = inj2_ + t * HC;
2839                a.w_norm = (const float*) hn->data;
2840                a.w_down = (const uint16_t*) hd->data;
2841                a.w_up = (const uint16_t*) hu->data;
2842                a.w_inject = nullptr;
2843                a.eps = EPS;
2844                a.lo = lo_ + t * g.hc_lr;
2845                a.rs = rs_ + t * HC;
2846                a.inject_out = head_inj_;
2847                a.mixed = head_mixed_ + t * N;
2848                if (qcnt_ != nullptr && head_ != nullptr && head_->loaded()) {
2849                    a.q8_cnt = qcnt_;
2850                    a.q8_mixed = xq_ + (size_t) (t - h0) * (N / 32) * 36;
2851                }
2852            }
2853            q8_head = fused_gr_read_multi(fa, HT, xn_ + (size_t) h0 * HC * N, cs);
2854        } else if (head_mix_multi_enabled() && head_ != nullptr && head_->loaded()) {
2855            // the final mixer, the window's tokens in one read (fused_gr_read_multi without the pending write: the
2856            // last layer's write was done above; its sums are gr_read's)
2857            if (hn->kind != WeightKind::F32 || hd->kind != WeightKind::Bf16InF32 || hu->kind != WeightKind::Bf16InF32) {
2858                err = "verify: the output_hc_* weights have the wrong engine forms";
2859                return false;
2860            }
2861            FusedGrArgs fa[kFusedGrMaxT];
2862            for (int t = h0; t < h0 + HT; ++t) {
2863                FusedGrArgs& a = fa[t - h0];
2864                a.R = Rt(t); a.R_out = Rt(t); a.apply = false;
2865                a.w_norm = (const float*) hn->data; a.w_down = (const uint16_t*) hd->data;
2866                a.w_up = (const uint16_t*) hu->data; a.eps = EPS;
2867                a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC; a.mixed = head_mixed_ + t * N;
2868                if (qcnt_ != nullptr) { a.q8_cnt = qcnt_; a.q8_mixed = xq_ + (size_t) (t - h0) * (N / 32) * 36; }
2869            }
2870            q8_head = fused_gr_read_multi(fa, HT, xn_ + (size_t) h0 * HC * N, cs);
2871        } else {
2872            for (int t = h0; t < h0 + HT; ++t) {
2873                BlockBuffers bb = ss.block;
2874                bb.R = Rt(t);
2875                bb.mixed = head_mixed_ + t * N;
2876                if (head_ != nullptr && head_->loaded()) {
2877                    if (!lm_head_mix(wt, g, bb, cs, err)) return false;
2878                } else if (!lm_head(wt, g, bb, head_logits_ + (size_t) t * n_vocab_, cs, err)) {
2879                    return false;
2880                }
2881            }
2882        }
2883        if (head_ != nullptr && head_->loaded()) {
2884            try {
2885                float* const hl = head_logits_ + (size_t) h0 * (size_t) n_vocab_;
2886                if (!q8_head) native_quantize_q8_1(head_mixed_ + (size_t) h0 * N, xq_, (int) N, HT, cs);   // (else the fused read wrote this chunk's image at xq_)
2887                if (g_mmvq_il() && strata::kernels::native_mmvq_il_supported(head_->type(), (int) HT, (int) n_vocab_)) {
2888                    if (HT >= 2) strata::kernels::native_q8_1_interleave(xq_, xil_, (int) N, (int) HT, cs);
2889                    strata::kernels::native_mmvq_il(head_->type(), head_->weights(), xq_, xil_, hl, (int) N,
2890                                                    (int) n_vocab_, (int) HT, cs);
2891                } else
2892                native_mmvq(head_->type(), head_->weights(), xq_, hl, (int) N, (int) n_vocab_, HT, cs);
2893            } catch (const std::exception& e) {
2894                err = std::string("verify head: ") + e.what();
2895                return false;
2896            }
2897        }
2898      }   // the head's column chunks
2899        // Greedy, the default, is recorded here as before (no extra launch or sync per window). A request that
2900        // samples or penalizes is sampled again host-side after the replay (run()) with its own parameters and a
2901        // fresh draw counter: a captured sampler would bake them in and replay the same draws forever.
2902        if (argmax_rows_wanted()) {   // sm_80 to sm_89 (sm_7x opt-in): the pick over many blocks a row (bitwise the one-block kernel's)
2903            argmax_rows(head_logits_, T, (int) n_vocab_, arg_scratch_, m_out_, cs);
2904        } else {
2905            SamplerParams sp;
2906            sp.greedy = true;
2907            sp.temperature = 0.0f;
2908            sample_tokens(head_logits_, T, (int) n_vocab_, nullptr, 0, sp, m_out_, cs);
2909        }
2910        // #879: whether each row's logits are all finite, beside the pick (read after the window's own sync)
2911        if (nan_guard_on()) strata::kernels::logits_nonfinite_rows(head_logits_, T, (int) n_vocab_, m_nf_, cs);
2912        if (g_dbg && windows <= 12 && n_vocab_ > 0 && T > 0) {   // STRATA_VERIFY_DEBUG: the first windows' top-3
2913            static std::vector<float> tmp;
2914            tmp.resize((size_t) n_vocab_);
2915            cudaMemcpy(tmp.data(), head_logits_, sizeof(float) * (size_t) n_vocab_, cudaMemcpyDeviceToHost);
2916            float va = -1e30f, vb = -1e30f, vc = -1e30f;
2917            int ia = -1, ib = -1, ic = -1;
2918            double s2 = 0.0;
2919            for (int k = 0; k < n_vocab_; ++k) {
2920                float v = tmp[(size_t) k];
2921                s2 += (double) v * (double) v;
2922                if (v > va) { vc = vb; ic = ib; vb = va; ib = ia; va = v; ia = k; }
2923                else if (v > vb) { vc = vb; ic = ib; vb = v; ib = k; }
2924                else if (v > vc) { vc = v; ic = k; }
2925            }
2926            std::fprintf(stderr, "verify top3: win=%lld T=%d -> %d(%.3f) %d(%.3f) %d(%.3f) rms=%.4f\n",
2927                         (long long) windows, (int) T, ia, (double) va, ib, (double) vb, ic, (double) vc,
2928                         std::sqrt(s2 / (double) n_vocab_));
2929            std::fflush(stderr);
2930        }
2931    }
2932    stamp(g.n_layers, 1, 0);
2933    if (tap_on_ && !batch_rec_ && tap_file_ != nullptr) copy_from_mapped(m_tap_, tap_dev_, (int64_t) T * (int64_t) tap_layers_.size() * N, cs);
2934    return true;
2935}
2936
2937std::string Verifier::profile_by_t_report() {
2938    if (!prof_on_) return std::string();
2939    static const char* names[kProfPer] = {"-", "hc-read0", "qkv gemv", "conv", "ab", "z", "rec", "q8+kv-idx", "k/v+norm-rope", "kv+idx append", "q+q-idx", "scores+topk", "kv-resolve", "attention", "gate", "", "out-proj", "router+plan", "shared+quant", "waitA", "VRAM hits", "waitB", "PCIe grp", "waitCPU", "copy+combine", "(gap)", "head", "hc0 norm", "hc0 down", "hc0 up", "hc1 norm", "hc1 down", "hc1 up", "ymWait", "ymCopy", "ymAdd"};
2940    std::string out;
2941    char b[96];
2942    for (int T = 1; T <= 16; ++T) {
2943        if (prof_t_win_[T] == 0) continue;
2944        double total = 0;
2945        std::snprintf(b, sizeof b, "T%d (n=%lld):", T, (long long) prof_t_win_[T]);
2946        out += b;
2947        for (int k = 0; k < 2; ++k) {
2948            out += k == 0 ? " GDN[" : " | QSA[";
2949            for (int i = 0; i < kProfPer; ++i) {
2950                if (prof_t_sum_[T][k][i] <= 0) continue;
2951                total += prof_t_sum_[T][k][i];
2952                std::snprintf(b, sizeof b, " %s %.3f", names[i], prof_t_sum_[T][k][i] / 1e6 / (double) prof_t_win_[T]);
2953                out += b;
2954            }
2955            out += " ]";
2956        }
2957        std::snprintf(b, sizeof b, " | total %.2f ms\n", total / 1e6 / (double) prof_t_win_[T]);
2958        out += b;
2959    }
2960    std::memset(prof_t_sum_, 0, sizeof prof_t_sum_);
2961    std::memset(prof_t_win_, 0, sizeof prof_t_win_);
2962    return out;
2963}
2964
2965std::string Verifier::route_stats_report() {
2966    if (!rs_on_ || rs_dev_ == nullptr || g_ == nullptr) return std::string();
2967    const int64_t L = g_->n_layers;
2968    std::vector<unsigned long long> h((size_t) 17 * (size_t) L * 16);
2969    cudaMemcpy(h.data(), rs_dev_, h.size() * 8, cudaMemcpyDeviceToHost);
2970    std::string out;
2971    char b[160];
2972    for (int T = 1; T <= 16; ++T) {
2973        if (rs_win_[T] == 0) continue;
2974        double row[16] = {};
2975        for (int64_t l = 0; l < L; ++l)
2976            for (int r = 0; r < 16; ++r) row[r] += (double) h[((size_t) T * (size_t) L + (size_t) l) * 16 + (size_t) r];
2977        const double denom = (double) rs_win_[T] * (double) L;
2978        double sum = 0;
2979        for (int r = 0; r < T; ++r) sum += row[r] / denom;
2980        std::snprintf(b, sizeof b, "T%d (n=%lld): distinct experts per layer %.2f; new per row:", T, (long long) rs_win_[T], sum);
2981        out += b;
2982        for (int r = 0; r < T; ++r) {
2983            std::snprintf(b, sizeof b, " %.2f", row[r] / denom);
2984            out += b;
2985        }
2986        out += "\n";
2987    }
2988    cudaMemset(rs_dev_, 0, h.size() * 8);
2989    std::memset(rs_win_, 0, sizeof rs_win_);
2990    return out;
2991}
2992
2993std::string Verifier::profile_report() {
2994    if (!prof_on_ || prof_windows_ == 0) return std::string();
2995    static const char* names[kProfPer] = {"-", "hc-read0", "q8+qkv/q-idx gemv", "conv", "ab", "z", "rec", "q8+kv-idx", "k/v+norm-rope", "kv+idx append", "q+q-idx", "scores+topk", "kv-resolve", "attention", "gate", "", "out-proj", "router+plan+bell", "shared+quant", "waitA", "VRAM hits", "waitB", "PCIe grp", "waitCPU", "copy+combine", "(gap)", "head", "  hc0 norm", "  hc0 down", "  hc0 up", "  hc1 norm", "  hc1 down", "  hc1 up", "", "", ""};
2996    std::string out;
2997    char b[80];
2998    double total = 0;
2999    for (int k = 0; k < 2; ++k) {
3000        out += k == 0 ? " GDN layers:" : " | QSA layers:";
3001        for (int i = 0; i < kProfPer; ++i) {
3002            if (prof_sum_[k][i] <= 0) continue;
3003            total += prof_sum_[k][i];
3004            std::snprintf(b, sizeof b, " %s %.2f", names[i], prof_sum_[k][i] / 1e6 / (double) prof_windows_);
3005            out += b;
3006        }
3007    }
3008    std::snprintf(b, sizeof b, " | total %.2f ms/window over %lld windows", total / 1e6 / (double) prof_windows_, (long long) prof_windows_);
3009    out += b;
3010    for (auto& r : prof_sum_) for (double& d : r) d = 0;
3011    prof_windows_ = 0;
3012    return out;
3013}
3014
3015// #871: is the zero-doorbell graph right for the next window?  Only while every expert of [lb_, le_) is in VRAM now
3016// (the host table is the one the device copy was uploaded from; a loan, a VRAM shrink or a swap in flight has
3017// marked some -1).  Not: the doorbell graph, which asks the pool for what the device does not hold.
3018void Verifier::refresh_ar() {
3019    if (!all_resident_ || h_res_ == nullptr || g_ == nullptr) return;
3020    const int64_t ne = g_->n_expert;
3021    const int32_t* r = h_res_ + lb_ * ne;
3022    const int64_t n = (le_ < 0 ? g_->n_layers : le_) * ne - lb_ * ne;
3023    int32_t lo = 0;
3024    for (int64_t i = 0; i < n; ++i) lo = std::min(lo, r[i]);
3025    const bool off = lo < 0;
3026    if (off != ar_off_) {
3027        ar_off_ = off;
3028        std::fprintf(stderr, "strata verify: layers [%lld, %lld) %s\n", (long long) lb_, (long long) (le_ < 0 ? g_->n_layers : le_),
3029                     off ? "have experts out of VRAM (a prompt loan, a shrink or a swap): the doorbell graph runs the windows"
3030                         : "are 100% VRAM resident again: the zero-doorbell graph");
3031    }
3032}
3033
3034bool Verifier::capture(int T, std::string& err) {
3035    const auto cap_t0 = std::chrono::steady_clock::now();
3036    cudaGraphExec_t& exec_t = ar_off_ ? exec_nr_[sel_long_][T] : exec_[sel_long_][T];
3037    if (exec_t != nullptr) return true;
3038    {   // said before the capture: a process that exits inside it (#1275: Windows, 313 MiB free) leaves this line as the trace
3039        size_t free_b = 0, total_b = 0;
3040        if (cudaMemGetInfo(&free_b, &total_b) == cudaSuccess)
3041            std::fprintf(stderr, "strata verify: capturing the %d-token window (%zu MiB of VRAM free)\n", T, free_b >> 20);
3042        else
3043            (void) cudaGetLastError();
3044    }
3045    if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) {
3046        err = "verify: begin capture failed";
3047        return false;
3048    }
3049#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL)
3050    prio_forks_.clear();
3051    prio_tails_.clear();
3052#endif
3053    std::string rerr;
3054    const bool ok = record_window(T, cs_, rerr);
3055    cudaGraph_t graph = nullptr;
3056    const cudaError_t ce = cudaStreamEndCapture(cs_, &graph);
3057    if (!ok) {
3058        if (graph) cudaGraphDestroy(graph);
3059        err = rerr;
3060        return false;
3061    }
3062    if (ce != cudaSuccess) {
3063        err = std::string("verify: end capture: ") + cudaGetErrorString(ce);
3064        return false;
3065    }
3066    if (graph && std::getenv("STRATA_VERIFY_NODES") != nullptr) {   // the captured node order (D2H / wait_flag / H2D / kernel)
3067        size_t nn = 0;
3068        if (cudaGraphGetNodes(graph, nullptr, &nn) == cudaSuccess && nn > 0) {
3069            std::vector<cudaGraphNode_t> nodes(nn);
3070            if (cudaGraphGetNodes(graph, nodes.data(), &nn) == cudaSuccess) {
3071                std::fprintf(stderr, "capture: %zu graph nodes:\n", nn);
3072                for (size_t i = 0; i < nn; ++i) {
3073                    cudaGraphNodeType t = cudaGraphNodeTypeEmpty; cudaGraphNodeGetType(nodes[i], &t);
3074                    if (t == cudaGraphNodeTypeMemcpy) {
3075                        cudaMemcpy3DParms mp{};
3076                        const char* k = "?";
3077                        if (cudaGraphMemcpyNodeGetParams(nodes[i], &mp) == cudaSuccess)
3078                            k = mp.kind == cudaMemcpyHostToDevice ? "H2D" : mp.kind == cudaMemcpyDeviceToHost ? "D2H" : mp.kind == cudaMemcpyDeviceToDevice ? "D2D" : "?";
3079                        std::fprintf(stderr, "  [%3zu] M %s\n", i, k);
3080                    } else if (t == cudaGraphNodeTypeKernel) {
3081                        cudaKernelNodeParams kp{};
3082                        const void* f = nullptr;
3083                        if (cudaGraphKernelNodeGetParams(nodes[i], &kp) == cudaSuccess) f = kp.func;
3084                        std::fprintf(stderr, "  [%3zu] K func=%p\n", i, f);
3085                    } else {
3086                        std::fprintf(stderr, "  [%3zu] type=%d\n", i, (int) t);
3087                    }
3088                }
3089            }
3090        }
3091    }
3092#if defined(STRATA_USE_HIP)   // 143-amdk: the same listing on HIP (kernel names by hipKernelNameRefByPtr); STRATA_VERIFY_NODES=2 also lists the first nodes in graph order
3093    if (std::getenv("STRATA_VERIFY_NODES") != nullptr) {
3094        size_t nn = 0;
3095        hipGraphGetNodes(graph, nullptr, &nn);
3096        std::vector<hipGraphNode_t> nodes(nn);
3097        hipGraphGetNodes(graph, nodes.data(), &nn);
3098        std::map<std::string, int> kinds;
3099        std::string seq;
3100        size_t shown = 0;
3101        for (hipGraphNode_t nd : nodes) {
3102            hipGraphNodeType ty;
3103            hipGraphNodeGetType(nd, &ty);
3104            std::string name = "type" + std::to_string((int) ty);
3105            if (ty == hipGraphNodeTypeKernel) {
3106                hipKernelNodeParams kp{};
3107                if (hipGraphKernelNodeGetParams(nd, &kp) == hipSuccess && kp.func != nullptr) {
3108#if defined(_WIN32)
3109                    using Fn_hipKernelNameRefByPtr = const char* (*)(const void*, hipStream_t);
3110                    static auto p_hipKernelNameRefByPtr = reinterpret_cast<Fn_hipKernelNameRefByPtr>(
3111                        GetProcAddress(GetModuleHandleA("amdhip64_7.dll"), "hipKernelNameRefByPtr"));
3112                    const char* fn = p_hipKernelNameRefByPtr ? p_hipKernelNameRefByPtr(kp.func, nullptr) : nullptr;
3113#else
3114                    const char* fn = hipKernelNameRefByPtr(kp.func, nullptr);
3115#endif
3116                    if (fn != nullptr) name = fn;
3117                }
3118            } else if (ty == hipGraphNodeTypeMemcpy) name = "memcpy";
3119            else if (ty == hipGraphNodeTypeMemset) name = "memset";
3120            ++kinds[name];
3121            if (std::atoi(std::getenv("STRATA_VERIFY_NODES")) >= 2 && shown++ < 400) seq += "\n  " + name.substr(0, 110);
3122        }
3123        std::vector<std::pair<int, std::string>> v;
3124        for (auto& [k2, c] : kinds) v.push_back({c, k2});
3125        std::sort(v.rbegin(), v.rend());
3126        std::fprintf(stderr, "strata verify: the %d-token window graph has %zu nodes:", T, nn);
3127        for (size_t i = 0; i < v.size() && i < 80; ++i) std::fprintf(stderr, "\n %4d x %.110s", v[i].first, v[i].second.c_str());
3128        std::fprintf(stderr, "\n%s\n", seq.c_str());
3129    }
3130#endif
3131#if !defined(STRATA_USE_HIP) && !defined(STRATA_GPU_METAL)   // a CUDA debug listing (node types, kernel names)
3132    if (std::getenv("STRATA_VERIFY_NODES") != nullptr) {   // what the window graph holds
3133        size_t nn = 0;
3134        cudaGraphGetNodes(graph, nullptr, &nn);
3135        std::vector<cudaGraphNode_t> nodes(nn);
3136        cudaGraphGetNodes(graph, nodes.data(), &nn);
3137        std::map<std::string, int> kinds;
3138        for (cudaGraphNode_t nd : nodes) {
3139            cudaGraphNodeType ty;
3140            cudaGraphNodeGetType(nd, &ty);
3141            std::string name = "type" + std::to_string((int) ty);
3142            if (ty == cudaGraphNodeTypeKernel) {
3143                cudaKernelNodeParams kp{};
3144                if (cudaGraphKernelNodeGetParams(nd, &kp) == cudaSuccess) {
3145#if CUDART_VERSION >= 12030   // cudaFuncGetName arrived in CUDA 12.3
3146                    const char* fn = nullptr;
3147                    if (cudaFuncGetName(&fn, kp.func) == cudaSuccess && fn) name = fn;
3148#endif
3149                }
3150            } else if (ty == cudaGraphNodeTypeMemcpy) name = "memcpy";
3151            else if (ty == cudaGraphNodeTypeMemset) name = "memset";
3152            ++kinds[name];
3153        }
3154        std::vector<std::pair<int, std::string>> v;
3155        for (auto& [k2, c] : kinds) v.push_back({c, k2});
3156        std::sort(v.rbegin(), v.rend());
3157        std::fprintf(stderr, "strata verify: the %d-token window graph has %zu nodes:", T, nn);
3158        for (size_t i = 0; i < v.size() && i < 40; ++i) std::fprintf(stderr, " %d x %.60s;", v[i].first, v[i].second.c_str());
3159        std::fprintf(stderr, "\n");
3160#if CUDART_VERSION >= 12030   // the programmatic (PDL) edges: CUDA allows them only from a kernel node to a kernel node
3161        size_t ne = 0;
3162#if CUDART_VERSION >= 13000
3163        cudaGraphGetEdges(graph, nullptr, nullptr, nullptr, &ne);
3164#else
3165        cudaGraphGetEdges_v2(graph, nullptr, nullptr, nullptr, &ne);
3166#endif
3167        std::vector<cudaGraphNode_t> from(ne), to(ne);
3168        std::vector<cudaGraphEdgeData> ed(ne);
3169#if CUDART_VERSION >= 13000
3170        const cudaError_t ge = cudaGraphGetEdges(graph, from.data(), to.data(), ed.data(), &ne);
3171#else
3172        const cudaError_t ge = cudaGraphGetEdges_v2(graph, from.data(), to.data(), ed.data(), &ne);
3173#endif
3174        size_t prog = 0, bad = 0;
3175        for (size_t i = 0; ge == cudaSuccess && i < ne; ++i) {
3176            if (ed[i].type != cudaGraphDependencyTypeProgrammatic) continue;
3177            ++prog;
3178            cudaGraphNodeType ta, tb2;
3179            if (cudaGraphNodeGetType(from[i], &ta) != cudaSuccess || cudaGraphNodeGetType(to[i], &tb2) != cudaSuccess ||
3180                ta != cudaGraphNodeTypeKernel || tb2 != cudaGraphNodeTypeKernel)
3181                ++bad;
3182        }
3183        if (ge != cudaSuccess) cudaGetLastError();
3184        std::fprintf(stderr, "strata verify: %zu edges, %zu programmatic (PDL), %zu of them not kernel to kernel%s\n", ne,
3185                     prog, bad, ge != cudaSuccess ? " (the edge query failed)" : "");
3186#endif
3187    }
3188#endif
3189    unsigned long long iflags = 0;
3190#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL)
3191    if (graph_prio_on()) {   // STRATA_GRAPH_PRIO: the nodes run at their own (captured or repaired) priorities
3192        apply_node_priorities(graph, T);
3193        iflags = cudaGraphInstantiateFlagUseNodePriority;
3194    }
3195#endif
3196#if defined(STRATA_USE_HIP)
3197    if (env_on("STRATA_LAUNCH_PROBE")) {   // STRIX-TDR: how many nodes (about one AQL packet each) the window graph holds
3198        size_t nn = 0, nk = 0;
3199        hipGraphGetNodes(graph, nullptr, &nn);
3200        std::vector<hipGraphNode_t> nodes(nn);
3201        hipGraphGetNodes(graph, nodes.data(), &nn);
3202        for (hipGraphNode_t nd : nodes) {
3203            hipGraphNodeType ty;
3204            if (hipGraphNodeGetType(nd, &ty) == hipSuccess && ty == hipGraphNodeTypeKernel) ++nk;
3205        }
3206        std::fprintf(stderr, "strata tdr-probe: the %d-token window graph has %zu nodes, %zu of them kernels\n", T, nn, nk);
3207    }
3208#endif
3209    const bool made = instantiate_evicting(exec_t, graph, {}, "verify: instantiate: ", err, T, iflags);
3210    cudaGraphDestroy(graph);
3211    if (!made) return false;
3212    const cudaError_t ue = cudaGraphUpload(exec_t, cs_);
3213    const cudaError_t us = cudaStreamSynchronize(cs_);
3214    std::fprintf(stderr, "strata verify: captured the %d-token window (upload %s, sync %s) in %.1f ms\n", T,
3215                 cudaGetErrorString(ue), cudaGetErrorString(us),
3216                 std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - cap_t0).count());
3217    // The upload only warms the graph; the first launch does it otherwise. A failed one (out of memory on a full card)
3218    // must not stay pending: the next kernel wrapper's cudaGetLastError would read it and end the engine (#3702).
3219    if (ue != cudaSuccess || us != cudaSuccess) {
3220        (void) cudaGetLastError();
3221        std::fprintf(stderr, "strata verify: the %d-token window's upload was skipped (the first launch does it)\n", T);
3222    }
3223    return true;
3224}
3225
3226bool Verifier::capture_commit(std::string& err) {
3227    if (commit_exec_ != nullptr) return true;
3228    using namespace strata::kernels;
3229    const ModelGeometry& g = *g_;
3230    SessionState& ss = *ss_;
3231    const QsaShapes s = shapes_of(g);
3232    const int64_t C = g.ssm_conv_channels, HV = g.ssm_v_heads, ID = g.idx_key_dim, MT = max_t_;
3233    const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +
3234                                (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);
3235    const int64_t TS = (s.idx_block - 1) * ID;
3236    const int64_t HS = (int64_t) NG_HIST * NG_HC_DIM;
3237    if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) {
3238        err = "verify: begin commit capture failed";
3239        return false;
3240    }
3241    bool ok = true;
3242    try {
3243        copy_i32_from_mapped(commit_, m_commit_, 2 + MT, cs_);
3244        int64_t qsa_index = 0, gdn_index = 0;
3245        for (int64_t l = 0; l < lb_; ++l) (is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1;
3246        // engine-latency (STRATA_COMMIT_BATCH, default on; =0 keeps the per-layer loop): every GDN layer's conv history and
3247        // state in two launches instead of two per layer (~70 graph nodes fewer; the same arithmetic per layer, bitwise).
3248        // The commit runs between a window and the draft round, which on HIP waits for it.
3249#if defined(STRATA_GPU_METAL)   // no batched commit kernels on Metal: the per-layer loop (the Mac engine's gated path)
3250        static const bool commit_batch = false;
3251#else
3252        static const bool commit_batch = [] { const char* e = std::getenv("STRATA_COMMIT_BATCH"); return !e || e[0] != '0'; }();
3253#endif
3254        bool gdn_batched = false;
3255        if (commit_batch) {
3256            int64_t n_gdn = 0;
3257            bool norms_ok = true;   // the per-layer loop checks each layer's ssm_norm.weight: keep that check
3258            for (int64_t l = lb_; l < le_ && norms_ok; ++l)
3259                if (!is_qsa_layer(g, l)) {
3260                    ++n_gdn;
3261                    norms_ok = need(LayerView(*wt_, l), "ssm_norm.weight", err) != nullptr;
3262                }
3263            if (!norms_ok) ok = false;
3264            else if (n_gdn > 0)
3265                gdn_batched = gdn_commit_layers(
3266                    ss.gdn_state + (size_t) (gdn_index - ss.gdn_ord0) * gdn_floats, (int64_t) gdn_floats,
3267                    (int64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size, qkv_L_ + (size_t) gdn_index * MT * C,
3268                    MT * C, h_L_ + (size_t) gdn_index * MT * C, MT * C, gate_L_ + (size_t) gdn_index * MT * HV,
3269                    beta_L_ + (size_t) gdn_index * MT * HV, MT * HV, (int) C, (int) g.ssm_k_heads, (int) HV, (int) MT,
3270                    (int) n_gdn, commit_, cs_);
3271        }
3272        // the QSA layers' tail restore + indexer append, one launch for all of them (one block per layer)
3273        bool qsa_batched = false;
3274        if (commit_batch && ok && !g_no_batch_kv) {
3275            QsaIndexerLayers il;
3276            int nq = 0;
3277            int64_t mc = -1;
3278            bool fits = true;
3279            for (int64_t l = lb_, qi = qsa_index; l < le_ && fits; ++l) {
3280                if (!is_qsa_layer(g, l)) continue;
3281                const WeightRef* wikn = need(LayerView(*wt_, l), "indexer.k_norm.weight", err);
3282                if (!wikn) { ok = false; fits = false; break; }
3283                const QsaState& st = ss.qsa_states[qi];
3284                if (nq >= QsaIndexerLayers::kMax || (mc >= 0 && st.max_cells != mc)) { fits = false; break; }
3285                mc = st.max_cells;
3286                il.gamma[nq] = (const float*) wikn->data;
3287                il.tail_src[nq] = tail_snap_ + (size_t) qi * TS;
3288                il.tail[nq] = st.idx_tail; il.dead[nq] = st.idx_dead; il.pooled[nq] = st.idx_pooled;
3289                il.block_pos[nq] = st.idx_block_pos;
3290                ++nq;
3291                ++qi;
3292            }
3293            if (ok && fits && nq > 0) {
3294                native_qsa_indexer_append_steps_layers(idx_raw_L_ + (size_t) qsa_index * MT * ID, MT * ID, commit_ + 2, 1,
3295                                                       (int) MT, 0, EPS, il, nq, s, mc, rope_scaling(), cs_);
3296                qsa_batched = true;
3297            }
3298        }
3299        for (int64_t l = lb_; l < le_ && ok; ++l) {
3300            const LayerView v(*wt_, l);
3301            if (is_qsa_layer(g, l) && qsa_batched) {
3302                ++qsa_index;
3303            } else if (!is_qsa_layer(g, l) && gdn_batched) {
3304                ++gdn_index;
3305            } else if (!is_qsa_layer(g, l)) {
3306                if (MT > kVerifyMaxT) {   // gdn_step_norm_multi takes kVerifyMaxT tokens; gdn_commit_layers takes more
3307                    err = "verify commit: windows past " + std::to_string(kVerifyMaxT) + " tokens (--lookup-max-t) need "
3308                          "the batched GDN commit (unset STRATA_COMMIT_BATCH=0, STRATA_GDN_SPLIT, STRATA_GDN_COMMIT_SPLIT=0)";
3309                    ok = false;
3310                    break;
3311                }
3312                const WeightRef* wnm = need(v, "ssm_norm.weight", err);
3313                if (!wnm) { ok = false; break; }
3314                float* state = ss.gdn_state + (size_t) (gdn_index - ss.gdn_ord0) * gdn_floats;
3315                float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
3316                const float* qkv = qkv_L_ + (size_t) gdn_index * MT * C;
3317                gdn_conv_commit(conv, qkv, (int) C, commit_, cs_);
3318                gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C, (int) C, gate_L_ + (size_t) gdn_index * MT * HV,
3319                                    beta_L_ + (size_t) gdn_index * MT * HV, z_, (const float*) wnm->data, EPS, y_dummy_,
3320                                    (int) g.ssm_k_heads, (int) HV, (int) MT, commit_, cs_,
3321                                    (int) MT);   // S26: t_out_begin = MT - the replay's outputs (y_dummy_) are never read
3322                ++gdn_index;
3323            } else {
3324                const QsaState& st = ss.qsa_states[qsa_index];
3325                const WeightRef* wikn = need(v, "indexer.k_norm.weight", err);
3326                if (!wikn) { ok = false; break; }
3327                copy_from_mapped(st.idx_tail, tail_snap_ + (size_t) qsa_index * TS, TS, cs_);
3328                const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};
3329                if (!g_no_batch_kv) {
3330                    native_qsa_indexer_append_steps(idx_raw_L_ + (size_t) qsa_index * MT * ID, commit_ + 2, 1, (int) MT, 0,
3331                                                    (const float*) wikn->data, EPS, ib, s, st.max_cells, rope_scaling(), cs_);
3332                } else {
3333                    for (int64_t t = 0; t < MT; ++t)
3334                        native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + t) * ID, commit_ + 2 + t, 0,
3335                                                  (const float*) wikn->data, EPS, ib, s, st.max_cells,
3336                                                  rope_scaling(), cs_);
3337                }
3338                ++qsa_index;
3339            }
3340        }
3341        if (ok && ss.ple.ready() && ple_stage()) copy_indexed(ss.ple.hist, hist_snap_, HS, commit_ + 1, HS, cs_);
3342    } catch (const std::exception& e) {
3343        err = std::string("verify commit: ") + e.what();
3344        ok = false;
3345    }
3346    cudaGraph_t graph = nullptr;
3347    const cudaError_t ce = cudaStreamEndCapture(cs_, &graph);
3348    if (!ok) {
3349        if (graph) cudaGraphDestroy(graph);
3350        return false;
3351    }
3352    if (ce != cudaSuccess) {
3353        if (graph) cudaGraphDestroy(graph);
3354        err = std::string("verify: commit capture: ") + cudaGetErrorString(ce);
3355        return false;
3356    }
3357    // (through the same path as the window graphs: on a full card it frees older batch layouts and retries, and the error
3358    // it reports is the instantiate's own)
3359    const bool made = instantiate_evicting(commit_exec_, graph, {}, "verify: commit instantiate: ", err, 0);
3360    cudaGraphDestroy(graph);
3361    return made;
3362}
3363
3364void Verifier::stage_inputs(int T, const int32_t* tokens, int64_t pos0) {
3365    using namespace strata::kernels;
3366    const ModelGeometry& g = *g_;
3367    const QsaShapes s = shapes_of(g);
3368    int32_t* const pk = h_pos_ + (size_t) max_t_ * g.n_head;
3369    int32_t* const pi = pk + (size_t) max_t_ * g.n_head_kv;
3370    for (int t = 0; t < T; ++t) {
3371        h_tok_[t] = tokens[t];
3372        qsa_step_fill(h_step_ + t * kStepCount, pos0 + t, s);
3373        const int32_t pos_t = (int32_t) (pos0 + t);
3374        for (int64_t h = 0; h < g.n_head; ++h) h_pos_[t * g.n_head + h] = pos_t;
3375        for (int64_t h = 0; h < g.n_head_kv; ++h) pk[t * g.n_head_kv + h] = pos_t;
3376        for (int64_t h = 0; h < g.idx_q_heads; ++h) pi[t * g.idx_q_heads + h] = pos_t;
3377    }
3378    if (g_trace) std::fprintf(stderr, "K0-STAGE-RESET t=%.3f h_seq=%u\n", (double) std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6, *(volatile uint32_t*) h_seq_);
3379    *(volatile uint32_t*) h_seq_ = 0;
3380    *(volatile uint32_t*) h_flag_ = 0;
3381    *(volatile uint32_t*) h_flagA_ = 0;
3382    *(volatile uint32_t*) h_flagB_ = 0;
3383    if (h_xlseq_ != nullptr) *(volatile uint32_t*) h_xlseq_ = 0;   // edge0: the D stage's doorbell restarts
3384    // the overlapped split: the next stage's graph is launched after this, and must see THIS window's raise
3385    if (hflag_out_h_ != nullptr) *(volatile uint32_t*) hflag_out_h_ = 0;
3386    if (herr_h_ != nullptr) *(volatile uint32_t*) herr_h_ = 0;
3387    if (hdrop_h_ != nullptr) *(volatile uint32_t*) hdrop_h_ = (g_test_drop > 0 && windows + 1 == g_test_drop) ? 1u : 0u;
3388    std::atomic_thread_fence(std::memory_order_seq_cst);
3389    strata_store_fence();
3390    last_t_ = T;
3391    if (rs_on_ && T >= 1 && T <= 16) ++rs_win_[T];
3392    last_pos0_ = pos0;
3393    for (int t = 0; t < T; ++t) last_tokens_[t] = tokens[t];
3394    staged_ = true;
3395}
3396
3397void Verifier::collect_profile() {
3398    cudaMemcpy(prof_h_.data(), prof_, prof_h_.size() * 8, cudaMemcpyDeviceToHost);
3399    accumulate_profile(prof_h_.data());
3400    if (g_trace) trace_dump(stderr);   // T-TRI: dump the GPU breadcrumbs (slots 32/33/34) each collect
3401}
3402
3403void Verifier::accumulate_profile(const unsigned long long* stamps) {
3404    double before[2][kProfPer];
3405    std::memcpy(before, prof_sum_, sizeof before);
3406    accumulate_profile_inner(stamps);
3407    if (last_t_ >= 1 && last_t_ <= 16) {
3408        for (int k = 0; k < 2; ++k)
3409            for (int i = 0; i < kProfPer; ++i) prof_t_sum_[last_t_][k][i] += prof_sum_[k][i] - before[k][i];
3410        ++prof_t_win_[last_t_];
3411    }
3412}
3413
3414void Verifier::accumulate_profile_inner(const unsigned long long* stamps) {
3415    const ModelGeometry& g = *g_;
3416    const int64_t L = g.n_layers;
3417    auto at = [&](int64_t l, int i) { return stamps[(size_t) (l * kProfPer + i)]; };
3418    // D8: the derived columns below read stamps the hc-read kernels write themselves or the next
3419    // layer's first.  A slot no kernel stamped is 0 and its unsigned difference wrapped to ~1e19 ns -
3420    // which is why (gap)/head/hc0 printed ~1e14 ms per window.  A missing or out-of-order stamp now
3421    // contributes nothing.
3422    const auto gap = [](unsigned long long to, unsigned long long from) {
3423        return (from != 0 && to != 0 && to >= from) ? (double) (to - from) : 0.0;
3424    };
3425    // only this stage's layers [lb_, le_) are ever stamped (a layer split); the head only on the last stage
3426    for (int64_t l = lb_; l < le_; ++l) {
3427        const int kind = is_qsa_layer(g, l) ? 1 : 0;
3428        unsigned long long prev = at(l, 0);
3429        for (int i = 1; i <= 24; ++i) {
3430            const unsigned long long x = at(l, i);
3431            if (x == 0 || x < prev) continue;
3432            prof_sum_[kind][i] += (double) (x - prev);
3433            prev = x;
3434        }
3435        {   // the FFN-side read split like hc-read0: norm 30, down 31, up 32; what is left of 17 is the router, plan, doorbell
3436            const double n1 = gap(at(l, 30), at(l, 16)), d1 = gap(at(l, 31), at(l, 30)), u1 = gap(at(l, 32), at(l, 31));
3437            if (n1 > 0 && d1 > 0 && u1 > 0) {
3438                prof_sum_[kind][30] += n1;
3439                prof_sum_[kind][31] += d1;
3440                prof_sum_[kind][32] += u1;
3441                prof_sum_[kind][17] -= gap(at(l, 32), at(l, 16));
3442            }
3443        }
3444        if (l + 1 < le_) prof_sum_[kind][25] += gap(at(l + 1, 0), at(l, 24));
3445        const double dn = gap(at(l, 27), at(l, 0)), dd = gap(at(l, 28), at(l, 27)), du = gap(at(l, 1), at(l, 28));
3446        if (dn > 0 && dd > 0 && du > 0) {   // the split exists: show it split, not twice
3447            prof_sum_[kind][27] += dn;      // hc-read0: norm
3448            prof_sum_[kind][28] += dd;      //           down
3449            prof_sum_[kind][29] += du;      //           up (through both halves, as before)
3450            prof_sum_[kind][1] -= gap(at(l, 1), at(l, 0));   // (hc-read0 shown split)
3451        }
3452    }
3453    if (le_ == L) prof_sum_[0][26] += gap(at(L, 1), at(L, 0));
3454    ++prof_windows_;
3455}
3456
3457// 0.1.43 (STRATA_ADAPT_OVERLAP): hold the host until the adaptive tier's copies up to `layer` have landed.  The wait
3458// is a spin on an atomic the copy stream's host functions raise (no driver call here); 20 s is the window's own limit.
3459bool Verifier::adapt_gate_wait(int32_t layer, std::string& err) {
3460    const Clock::time_point t0 = Clock::now();
3461    uint32_t spins = 0;
3462    // each tier's counter climbs to the last layer it swaps this round, so an all-layers wait asks for that layer
3463    const AdaptGate& ag = *adapt_gate_;
3464    const int32_t want = std::min(layer, ag.last), want_peer = std::min(layer, ag.peer_last);
3465    const bool wait_main = ag.last >= 0 && ((size_t) layer >= ag.has.size() || ag.has[(size_t) layer] != 0);
3466    const bool wait_peer = ag.peer_last >= 0 && ((size_t) layer >= ag.peer_has.size() || ag.peer_has[(size_t) layer] != 0);
3467    bool announced = false;   // the watchdog's label is set only once the wait really starts: no cost when the copies landed
3468    while ((wait_main && ag.reached() < want) || (wait_peer && ag.peer_reached() < want_peer)) {
3469        if (!announced) {
3470            progress_at("verify window: waiting for the adaptive tier's copies of layer", layer);
3471            announced = true;
3472        }
3473        strata_cpu_pause();
3474        if ((++spins & 1023u) != 0) continue;
3475        if (Clock::now() - t0 > std::chrono::seconds(20)) {
3476            // the release drains the window's own streams, never the tier's copy stream: say so, and hand out the
3477            // gate's words and this window's GPU breadcrumbs (STRATA_VERIFY_TRACE) - the last landed layer is the
3478            // exact place the stream stopped, which the released window's error line alone never told (#2188's class)
3479            const int32_t reach = adapt_gate_->reached(), land = adapt_gate_->landed.load();
3480            const int32_t hl = adapt_gate_->hland != nullptr ? *adapt_gate_->hland : -2;
3481            if (g_trace) trace_ev("GATE-TIMEOUT", -1, layer, reach);
3482            std::fprintf(stderr, "strata verify: the adaptive gate waited %lld ms for layer %d: reached %d "
3483                                 "(atomic %d, copy signal %d) - the tier's copy stream was not drained by the release\n",
3484                         (long long) ms_since(t0), (int) layer, (int) reach, (int) land, (int) hl);
3485            if (g_trace) trace_dump(stderr);
3486            err = "verify: the adaptive tier's copies for layer " + std::to_string(layer) + " never landed" +
3487                  released_note(release_gpu_waits(5000)) +
3488                  " (the copy stream itself is not drained: reached " + std::to_string(reach) + " of " +
3489                  std::to_string(layer) + ", STRATA_VERIFY_TRACE=1 prints where the stream stopped)";
3490            std::fflush(stderr);
3491            return false;
3492        }
3493    }
3494    ms_gate += ms_since(t0);
3495    return true;
3496}
3497
3498bool Verifier::handoff_failed(std::string& err) const {
3499    if (herr_h_ == nullptr || *(const volatile uint32_t*) herr_h_ == 0) return false;
3500    err = "verify: layer split: the hand-off into layer " + std::to_string(lb_) + " did not arrive within " +
3501          std::to_string(g_split_wait_ns / 1000000ull) + " ms (STRATA_SPLIT_WAIT_MS); the window was not used. "
3502          "STRATA_SPLIT_OVERLAP=0 runs the serial order";
3503    trace_ev("HANDOFF-TIMEOUT", -1, lb_, (int64_t) (g_split_wait_ns / 1000000ull));
3504    return true;
3505}
3506
3507bool Verifier::chain_overlap() const {
3508    return next_ != nullptr && hflag_out_h_ != nullptr && hflag_out_d_ != nullptr && hcount_d_ != nullptr &&
3509           next_->hflag_in_h_ == hflag_out_h_ && next_->device_ != device_ && !next_->ple_stage();
3510}
3511
3512bool Verifier::prelaunch(int T, const int32_t* tokens, int64_t pos0, std::string& err) {
3513    const OnDevice on_device(device_);
3514    prelaunched_ = 0;
3515    sel_long_ = select_long_on() && pos0 + T >= select_long_at() ? 1 : 0;   // the variant the previous stage captured
3516    cudaGraphExec_t exec_t = ar_off_ ? exec_nr_[sel_long_][T] : exec_[sel_long_][T];   // #871: the variant the previous stage refreshed
3517    if (T < 1 || T > max_t_ || exec_t == nullptr) { err = "verify: prelaunch before the window was captured"; return false; }
3518    if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }
3519    if (pos0 + T > ss_->qsa_states[ss_->qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; }
3520    const Clock::time_point t0 = Clock::now();
3521    stage_inputs(T, tokens, pos0);
3522    if (trace_h_ != nullptr) std::memset(trace_h_, 0, trace_n_ * 8);
3523    std::atomic_thread_fence(std::memory_order_seq_cst);
3524    trace_ev("WINDOW-PRE", -1, -1, pos0 * 16 + T);
3525    ms_host += ms_since(t0);
3526    if (h_bal_ != nullptr) std::memset(h_bal_, 0, (size_t) bal_p_.size() * 4 * 8);   // this window's stamps only
3527    if (ar_on() && h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0;
3528    // 0.1.43: the same gate run() applies before it launches (the adaptive tier's copies land first)
3529    if (adapt_gate_ != nullptr && adapt_gate_->active.load(std::memory_order_acquire) && ar_on() &&
3530        !adapt_gate_wait((int32_t) g_->n_layers, err)) return false;
3531    strata::dispatch::Stats::get().graph_launch(T, ar_on() ? 0 : 1);
3532    const cudaError_t le = cudaGraphLaunch(exec_t, cs_);
3533    trace_ev("LAUNCHED", -1, -1, (int64_t) le);
3534    if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; }
3535    (void) cudaStreamQuery(cs_);
3536    prelaunched_ = T;
3537    return true;
3538}
3539
3540bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out,
3541                   std::string& err) {
3542    const bool measure = spec_measure_;
3543    // Clear this borrow and propagated stage borrows on every exit.
3544    struct ProposalBorrow {
3545        Verifier* verifier;
3546        bool active;
3547        ~ProposalBorrow() { if (active) verifier->set_spec_q(nullptr, 0); }
3548    } proposal_borrow{this, measure};
3549    if (measure && (T < 1 || T > strata::kernels::kVerifyMaxT ||
3550                    spec_nq_ < 0 || spec_nq_ > T || (spec_nq_ > 0 && spec_q_ == nullptr))) {
3551        err = "verify: proposal row count/pointer is invalid"; return false;
3552    }
3553    if (measure && (!head_sampling_ || sampling_.greedy || sampling_.temperature <= 0.0f)) {
3554        err = "verify: proposal requires sampled head"; return false;
3555    }
3556#if defined(STRATA_GPU_METAL)
3557    if (measure) { err = "verify: proposal unsupported on Metal"; return false; }
3558    (void) pool;
3559    (void) user;
3560    {   // a sampled, penalised or biased request: the head rows are sampled on the GPU (metal/kernels/sample.metal), Philox(seed, pos0 + t) as the CUDA head
3561        const bool sampled_m = !sampling_.greedy && sampling_.temperature > 0.0f;
3562        if (head_sampling_ && (sampled_m || hist_d_ != nullptr || sampling_.logit_bias != nullptr)) {
3563            strata::kernels::SamplerParams sp_m = sampling_;
3564            sp_m.counter = (uint64_t) pos0;
3565            strata::metal_engine::window_set_sampling(metal_, &sp_m, hist_d_, hist_len_);
3566        } else {
3567            strata::metal_engine::window_set_sampling(metal_, nullptr, nullptr, 0);
3568        }
3569    }
3570    return strata::metal_engine::window_run(metal_, T, tokens, pos0, head_sampling_, out, err);
3571#endif
3572    using namespace strata::kernels;
3573    const OnDevice on_device(device_);
3574    last_batch_ = false;
3575    if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; }
3576    // a layer split's hand-off buffers hold kVerifyMaxT rows
3577    if (T > kVerifyMaxT && (next_ != nullptr || lb_ > 0)) { err = "verify: windows past 8 tokens need one stage"; return false; }
3578    if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }
3579    const ModelGeometry& g = *g_;
3580    SessionState& ss = *ss_;
3581    if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; }
3582    // the overlapped split launched this stage's window already: keep the graph variant (#871) chosen for it then,
3583    // or this thread would serve the window as the other variant
3584    const bool pre = prelaunched_ == T;
3585    prelaunched_ = 0;
3586    if (!pre && pre_launch_ && !pre_launch_(cs_, err)) return false;   // (a prelaunched window's was served with the first stage's)
3587    if (!pre) refresh_ar();
3588    // STRATA_SELECT_LONG: the select kernels this window's context pays off with (the same on every stage)
3589    sel_long_ = select_long_on() && pos0 + T >= select_long_at() ? 1 : 0;
3590    if (!capture(T, err) || !capture_commit(err)) return false;
3591    const bool chain = chain_overlap();
3592    if (chain) {   // capture the next stage's window here, on this thread, so the helper only stages and launches
3593        const OnDevice on_next(next_->device_);
3594        next_->refresh_ar();                     // #871: the variant its prelaunch and its run() will both use
3595        next_->sel_long_ = sel_long_;
3596        if (!next_->capture(T, err) || !next_->capture_commit(err)) return false;
3597    }
3598    VDBG("captured; staging\n");
3599    const Clock::time_point t0 = Clock::now();
3600    if (!pre && !staged_) stage_inputs(T, tokens, pos0);
3601    staged_ = false;
3602    const bool do_ple = ss.ple.ready() && ple_stage();
3603    uint32_t ple_rows[kVerifyLongT * PLE_N_HEADS];
3604    if (do_ple) {
3605        int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]};
3606        for (int t = 0; t < T; ++t) {
3607            ngram_rows(&tokens[t], prev, 1, ss.ple.consts, ple_rows + t * PLE_N_HEADS);
3608            prev[0] = prev[1];
3609            prev[1] = tokens[t];
3610            ss.ple.table->prefetch_rows(ple_rows + t * PLE_N_HEADS);
3611        }
3612    }
3613#if defined(STRATA_VERIFY_HGL)
3614    std::optional<HostGraphLaunch> launch_o;   // (not set when the previous stage launched this window already)
3615#endif
3616    const bool test_stall = g_test_stall > 0 && windows + 1 == g_test_stall;   // #267 test hook (off: false)
3617    bool flag_raised = false;   // the PLE flag went up before the launch (early_ple_flag_mode)
3618    bool ple_gathered = false;
3619    bool& graph_launched = ar_off_ ? launched_nr_[sel_long_][T] : launched_[sel_long_][T];
3620    if (!pre && ar_on() && !test_stall && (early_ple_flag_mode() == 1 || (early_ple_flag_mode() == 2 && !graph_launched))) {
3621        if (do_ple) {
3622            const Clock::time_point tp = Clock::now();
3623            if (!ss.ple.table->gather_batch(ple_rows, (size_t) T, h_ple_, err)) return false;
3624            std::atomic_thread_fence(std::memory_order_seq_cst);
3625            strata_store_fence();
3626            ms_host += ms_since(tp);
3627        }
3628        *(volatile uint32_t*) h_flag_ = 1;
3629        flag_raised = true;
3630    }
3631    static const bool probe_on = env_on("STRATA_LAUNCH_PROBE");
3632    static std::atomic<int> probe_count{0};
3633    const int probe_idx = probe_on && !pre ? probe_count.fetch_add(1) : -1;
3634    const bool probe_this = probe_idx >= 0 && probe_idx < 12;
3635    Clock::time_point probe_t0 = Clock::now();
3636    // knife-0: with the CPU share's U on the GPU (STRATA_LATENT_U_GPU) the flag means "this group's hq rows are
3637    // written", so pre-raising it here would let the graph copy the rows before the pool writes them (a wrong first
3638    // token, then a repetition loop).  The u_gpu graph waits for the pool's own raise below; only the CPU-U path,
3639    // whose consumers read the mapped rows, needs the pre-raise (the staging reset zeroes the flag).
3640    static const bool u_gpu_flag = [] { const char* v = std::getenv("STRATA_LATENT_U_GPU"); return v != nullptr && std::atoi(v) != 0; }();
3641    if (latent_ && !pre && !test_stall && !ar_on() && !u_gpu_flag) {
3642        if (do_ple) {
3643            const Clock::time_point tp = Clock::now();
3644            if (!ss.ple.table->gather_batch(ple_rows, (size_t) T, h_ple_, err)) return false;
3645            std::atomic_thread_fence(std::memory_order_seq_cst);
3646            strata_store_fence();
3647            ms_host += ms_since(tp);
3648            ple_gathered = true;
3649        }
3650        *(volatile uint32_t*) h_flag_ = 1;
3651        flag_raised = true;
3652    }
3653    if (!pre) {
3654        if (trace_h_ != nullptr) std::memset(trace_h_, 0, trace_n_ * 8);   // #649: this window's breadcrumbs only
3655        std::atomic_thread_fence(std::memory_order_seq_cst);
3656        trace_ev("WINDOW", -1, -1, pos0 * 16 + T);
3657        ms_host += ms_since(t0);
3658        VDBG("staged; launching\n");
3659        if (h_bal_ != nullptr) std::memset(h_bal_, 0, (size_t) bal_p_.size() * 4 * 8);   // this window's stamps only
3660        if (ar_on() && h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0;
3661        // 0.1.43: with the all-resident graph the host serves no layer, so nothing can hold a layer back: every copy first
3662        if (adapt_gate_ != nullptr && adapt_gate_->active.load(std::memory_order_acquire) && ar_on() &&
3663            !adapt_gate_wait((int32_t) g.n_layers, err)) return false;
3664#if defined(STRATA_VERIFY_HGL)
3665        // A blocking instrumented launch cannot also serve the graph's CPU doorbells.
3666        static const bool threaded_launch = [] {
3667            const char* value = std::getenv("STRATA_VERIFY_ASYNC_LAUNCH");
3668            return value != nullptr && value[0] == '1';
3669        }();
3670        strata::dispatch::Stats::get().graph_launch(T, ar_on() ? 0 : 1);
3671        // STRATA_LAUNCH_PROBE=1 (diagnostic, the first 12 windows): how long the launch call takes, whether the GPU has rung a layer
3672        // before the call returns, and what a call that has not returned looks like after 50 ms ... 10 s (STRIX-TDR).
3673        std::atomic<bool> probe_done{false};
3674        std::thread probe_th;
3675        if (probe_this) {
3676            probe_t0 = Clock::now();
3677            size_t fm = 0, tm = 0;
3678            (void) cudaMemGetInfo(&fm, &tm);
3679            std::fprintf(stderr, "strata tdr-probe: window %d T=%d pos=%lld: t=%.0f ms since start, %.0f MiB free, launching%s\n", probe_idx, T,
3680                         (long long) pos0, ms_since(probe_proc_t0()), (double) fm / 1048576.0, threaded_launch ? " (helper thread)" : "");
3681            probe_th = std::thread([this, &probe_done, probe_t0, probe_idx, T] {
3682                static const double marks[] = {50, 250, 500, 1000, 2000, 3000, 5000, 10000, 30000};
3683                size_t mi = 0;
3684                while (!probe_done.load(std::memory_order_acquire) && mi < sizeof marks / sizeof marks[0]) {
3685                    std::this_thread::sleep_for(std::chrono::milliseconds(2));
3686                    if (ms_since(probe_t0) < marks[mi]) continue;
3687                    std::fprintf(stderr,
3688                                 "strata tdr-probe: window %d T=%d: the launch call has not returned after %.0f ms; GPU rang %u, flags served %u A %u B %u\n",
3689                                 probe_idx, T, marks[mi], h_seq_ ? *(volatile uint32_t*) h_seq_ : 0u, h_flag_ ? *(volatile uint32_t*) h_flag_ : 0u,
3690                                 h_flagA_ ? *(volatile uint32_t*) h_flagA_ : 0u, h_flagB_ ? *(volatile uint32_t*) h_flagB_ : 0u);
3691                    ++mi;
3692                }
3693            });
3694        }
3695        launch_o.emplace(ar_off_ ? exec_nr_[sel_long_][T] : exec_[sel_long_][T], cs_, device_, threaded_launch,
3696                         [this] { (void) release_gpu_waits(5000); });
3697        const cudaError_t le = launch_o->status();
3698        if (probe_this) {
3699            probe_done.store(true, std::memory_order_release);
3700            probe_th.join();
3701            std::fprintf(stderr, "strata tdr-probe: window %d T=%d: launch call %s in %.2f ms; the GPU had rung %u layer(s) and the host served %u at the return\n",
3702                         probe_idx, T, threaded_launch ? "handed to the helper" : "returned", ms_since(probe_t0),
3703                         h_seq_ ? *(volatile uint32_t*) h_seq_ : 0u, h_flag_ ? *(volatile uint32_t*) h_flag_ : 0u);
3704        }
3705#else
3706        strata::dispatch::Stats::get().graph_launch(T, ar_on() ? 0 : 1);
3707        const cudaError_t le = cudaGraphLaunch(ar_off_ ? exec_nr_[sel_long_][T] : exec_[sel_long_][T], cs_);
3708#endif
3709        trace_ev("LAUNCHED", -1, -1, (int64_t) le);
3710        graph_launched = true;
3711        if (g_trace) { cudaError_t q = cudaStreamQuery(cs_); std::fprintf(stderr, "K0-LAUNCH-QUERY %s\n", q == cudaSuccess ? "SUCCESS(idle)" : (q == cudaErrorNotReady ? "NOTREADY(busy)" : cudaGetErrorString(q))); }
3712        if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; }
3713#if defined(STRATA_VERIFY_HGL)
3714        (void) launch_o->query();
3715#else
3716        (void) cudaStreamQuery(cs_);
3717#endif
3718        VDBG("launched\n");
3719    }
3720    // The overlapped split: the next stage's window is staged and launched on a helper thread while this thread
3721    // serves this stage's layers; its graph waits on the GPU for this stage's hand-off flag.  The guard joins the
3722    // helper on every return, and on an early return (an error after the launch) releases the next stage's GPU
3723    // waits so no spin kernel outlives the window (#267).
3724    struct NextLaunch {
3725        Verifier* next = nullptr;
3726        std::thread th;
3727        bool ok = true;
3728        bool handed = false;
3729        std::string err;
3730        bool join(std::string& e) {
3731            if (th.joinable()) th.join();
3732            if (!ok) e = err;
3733            return ok;
3734        }
3735        ~NextLaunch() {
3736            if (th.joinable()) th.join();
3737            if (next != nullptr && !handed) (void) next->release_gpu_waits(5000);
3738        }
3739    } nl;
3740    if (chain) {
3741        nl.next = next_;
3742        nl.th = std::thread([&nl, T, tokens, pos0] { nl.ok = nl.next->prelaunch(T, tokens, pos0, nl.err); });
3743    }
3744    volatile uint32_t* const seq = h_seq_;
3745    volatile uint32_t* const flag = h_flag_;
3746    const int G = groups_[T] > 0 ? groups_[T] : 1;
3747    const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T};
3748    const int64_t steps = (le_ - lb_) * G;
3749    if (ar_on() && !test_stall) {
3750        if (flag_raised) {
3751            // up before the launch (early_ple_flag_mode)
3752        } else if (do_ple) {
3753            const Clock::time_point tp = Clock::now();
3754            if (!ss.ple.table->gather_batch(ple_rows, (size_t) T, h_ple_, err)) return false;
3755            std::atomic_thread_fence(std::memory_order_seq_cst);
3756            strata_store_fence();
3757            *flag = 1;
3758            ms_host += ms_since(tp);
3759        } else {
3760            *flag = 1;
3761        }
3762    } else
3763    for (int64_t k = 0; k < steps; ++k) {
3764        const int64_t l = lb_ + k / G;
3765        const int grp = (int) (k % G);
3766        const uint32_t want = (uint32_t) (k + 1);
3767        const Clock::time_point a = Clock::now();
3768        auto last_flush = a;
3769        uint32_t spins = 0;
3770        progress_at("verify window: waiting for the GPU to reach layer", l);
3771        while (*seq < want) {
3772            strata_cpu_pause();
3773            if ((++spins & 1023u) != 0) continue;
3774            const auto now = Clock::now();
3775            if (now - last_flush > std::chrono::microseconds(2000)) {
3776                last_flush = now;
3777#if defined(STRATA_VERIFY_HGL)
3778                const cudaError_t q = launch_o ? launch_o->query() : cudaStreamQuery(cs_);
3779#else
3780                const cudaError_t q = cudaStreamQuery(cs_);
3781#endif
3782                if (q != cudaErrorNotReady && *seq < want) {
3783                    trace_ev("NEVER-RANG", k, l, (int64_t) q);
3784                    trace_dump(stderr);
3785                    err = "verify: layer " + std::to_string(l) + " never rang (" +
3786                          (q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")";
3787                    return false;
3788                }
3789            }
3790            if (now - a > std::chrono::seconds(20)) {
3791                // #267: the caller ends the engine; no spin kernel may outlive it
3792#if defined(STRATA_VERIFY_HGL)
3793                trace_ev("TIMEOUT", k, l, (int64_t) (launch_o ? launch_o->query() : cudaStreamQuery(cs_)));
3794#else
3795                trace_ev("TIMEOUT", k, l, (int64_t) cudaStreamQuery(cs_));
3796#endif
3797                if (g_trace) {
3798                    diag(stderr);   // the words and the breadcrumbs before the release ...
3799                    const bool drained = release_gpu_waits(5000);
3800                    trace_dump(stderr);   // ... and after it: did the GPU move once its waits were raised?
3801                    err = "verify: timed out at layer " + std::to_string(l) + released_note(drained);
3802                    return false;
3803                }
3804                err = "verify: timed out at layer " + std::to_string(l) + released_note(release_gpu_waits(5000));
3805                return false;
3806            }
3807        }
3808        strata_load_fence();   // the layer rang: the GPU's activations are read after it (a no-op on x86)
3809        const Clock::time_point b = Clock::now();
3810        if (probe_this && k == 0)
3811            std::fprintf(stderr, "strata tdr-probe: window %d T=%d: the first doorbell (layer %lld) seen %.2f ms after the launch began\n", probe_idx, T,
3812                         (long long) l, ms_since(probe_t0));
3813        if (g_trace) trace_ev("RANG", k, l, (int64_t) std::chrono::duration_cast<std::chrono::microseconds>(b - a).count());
3814        VDBG("layer %lld rang\n", (long long) l);
3815        if (adapt_gate_ != nullptr && adapt_gate_->active.load(std::memory_order_acquire) && l >= 0 &&
3816            (((size_t) l < adapt_gate_->has.size() && adapt_gate_->has[(size_t) l] != 0) ||
3817             ((size_t) l < adapt_gate_->peer_has.size() && adapt_gate_->peer_has[(size_t) l] != 0)) &&
3818            !adapt_gate_wait((int32_t) l, err)) return false;
3819        cur_layer_ = want - 1;
3820        set_plan_slot(grp);
3821        const int tb = gtb[grp], n = gte[grp] - gtb[grp];
3822        progress_at("verify window: the CPU experts of layer", l);
3823        if (remote_opt_) remote_opt_->begin(h_w_ + (size_t) tb * ss.k, tb, n);
3824        if (pool != nullptr) {
3825            strata::core::latent_xl_current() = h_latxlq_;
3826            strata::core::latent_xlseq_current() = h_xlseq_;
3827        strata::core::latent_act0_current() = m_latact0_;
3828            pool(user, h_x_ + (size_t) tb * g.n_embd, h_ids_ + (size_t) tb * ss.k, n, ss.k,
3829                 h_ymiss_ + (size_t) tb * ss.k * g.n_embd, l);
3830        }
3831        if (remote_opt_) remote_opt_->end();
3832        VDBG("layer %lld served\n", (long long) l);
3833        if (g_trace) trace_ev(*(volatile uint32_t*) h_flagA_ == want ? "SERVED" : "SERVED-NO-PLAN-YET", k, l,
3834                              (int64_t) ms_since(b));   // aux: ms the CPU experts took
3835        progress_tick();
3836        std::atomic_thread_fence(std::memory_order_seq_cst);
3837        strata_store_fence();
3838        if (h_bal_ != nullptr) {   // set_pcie_balance: the step's plan, its CPU and its PCIe experts
3839            const size_t bi = (size_t) ((k / G) * 2 + grp);
3840            bal_ok_[bi] = *(volatile uint32_t*) h_flagA_ == want;
3841            bal_nc_[bi] = bal_ok_[bi] ? sink_.cpu_jobs : 0;
3842            bal_np_[bi] = bal_ok_[bi] ? sink_.counts[2] : 0;
3843            sink_.cpu_jobs = 0;
3844        }
3845        if (*(volatile uint32_t*) h_flagA_ != want) {        // the pool did not publish a plan: an empty one
3846            sink_.counts[0] = 0;
3847            sink_.counts[1] = 0;
3848            sink_.counts[2] = 0;
3849            sink_.start[0] = 0;
3850            sink_.start2[0] = 0;
3851            std::atomic_thread_fence(std::memory_order_seq_cst);
3852            *(volatile uint32_t*) h_flagA_ = want;
3853            raise_flag_b_ordered(want);   // behind any copy still queued from an earlier layer
3854        }
3855        // Layer 1's pre(1, 0) copies h_ple_ -> ple_ after Layer 0's wait_flag_ge(m_flag_, 1).
3856        // By collecting PLE here at k == 0 (after publishing flagA/flagB for Layer 0 so the GPU can run
3857        // Layer 0's VRAM experts, and before raising *flag = 1), the NVMe PLE reads overlap with both
3858        // MtpDrafter::draft and Layer 0's attention + router + expert execution!
3859        if (k == 0 && do_ple && !ple_gathered) {
3860            const Clock::time_point tp = Clock::now();
3861            if (!ss.ple.table->gather_batch(ple_rows, (size_t) T, h_ple_, err)) return false;
3862            std::atomic_thread_fence(std::memory_order_seq_cst);
3863            strata_store_fence();
3864            ms_host += ms_since(tp);
3865        }
3866        if (!(test_stall && k + 1 == steps)) *flag = want;
3867        if (h_bal_ != nullptr) bal_p_[(size_t) ((k / G) * 2 + grp)] = ms_since(b);
3868        ms_wait += std::chrono::duration<double, std::milli>(b - a).count();
3869        ms_pool += ms_since(b);
3870    }
3871    // (#646 staged the next stage's inputs here; 0.1.39b keeps the layer split's order: each stage stages its own)
3872    if (chain) {
3873        // The overlapped split: no host sync between the stages.  The next stage's GPU starts on this stage's flag;
3874        // this thread goes straight to serving the next stage's layers, and syncs this stage once the chain is done.
3875        if (!nl.join(err)) return false;
3876        nl.handed = true;
3877        ++windows;
3878        const bool ok = next_->run(T, tokens, pos0, pool, next_user_, out, err);
3879        const OnDevice back(device_);
3880        const cudaError_t se = cudaStreamSynchronize(cs_);
3881        if (copy_used_) {
3882            cudaStreamSynchronize(copy_);
3883            copy_used_ = false;
3884        }
3885        if (!ok) return false;
3886        if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; }
3887        if (handoff_failed(err)) return false;   // a middle stage of three or more: its own hand-in
3888        if (ar_on() && h_plan_err_ != nullptr && *(volatile uint32_t*) h_plan_err_ != 0) {   // #871, as below
3889            *(volatile uint32_t*) h_plan_err_ = 0;
3890            err = "verify: the all-resident plan met an expert that is not in VRAM (the residency table changed during the window)";
3891            return false;
3892        }
3893        commit_pending_ = false;
3894        if (prof_on_ && G == 1) collect_profile();
3895        return true;
3896    }
3897    progress_at("verify window: waiting for the GPU to finish the window (flags A/B/M raised)", (int64_t) T);
3898    // #267: a window the GPU never finishes (a spin kernel that never sees its flag) holds the host here; the stall
3899    // watchdog then releases every verifier's GPU waits (release_live_verifiers) before it ends the engine, so no
3900    // spin kernel outlives the process - the case that left Windows GPUs "lost" until a power cycle.  The wait
3901    // itself stays a blocking sync: a cudaStreamQuery poll here cost IQ3_S ~3% decode (a core calling the driver
3902    // beside the expert workers).
3903#if defined(STRATA_VERIFY_HGL)
3904    const cudaError_t launch_result = launch_o ? launch_o->finish() : cudaSuccess;
3905    if (launch_result != cudaSuccess) {
3906        err = std::string("verify: launch: ") + cudaGetErrorString(launch_result);
3907        return false;
3908    }
3909#endif
3910    trace_ev("SYNC", -1, -1, 0);
3911    { static const bool k0print = std::getenv("STRATA_K0SYNC_PRINT") != nullptr; if (k0print) { double tb = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6; std::fprintf(stderr, "K0-SYNC-BEFORE %.3f\n", tb); } }
3912    const cudaError_t se = cudaStreamSynchronize(cs_);
3913    { static const bool k0print = std::getenv("STRATA_K0SYNC_PRINT") != nullptr; if (k0print) { double ta = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6; std::fprintf(stderr, "K0-SYNC-AFTER %.3f se=%s\n", ta, cudaGetErrorString(se)); } }
3914    trace_ev("SYNCED", -1, -1, (int64_t) se);
3915    if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; }
3916    if (handoff_failed(err)) return false;   // a stale hand-off: nothing of this window is used
3917    if (ar_on() && h_plan_err_ != nullptr && *(volatile uint32_t*) h_plan_err_ != 0) {   // #871: refresh_ar saw the table whole
3918        *(volatile uint32_t*) h_plan_err_ = 0;
3919        err = "verify: the all-resident plan met an expert that is not in VRAM (the residency table changed during the window)";
3920        return false;
3921    }
3922    commit_pending_ = false;
3923    progress_at("verify window: waiting for the expert copies", (int64_t) T);
3924    if (copy_used_) {
3925        cudaStreamSynchronize(copy_);   // no host function of this window may raise flag B in the next one
3926        copy_used_ = false;
3927    }
3928    if (h_bal_ != nullptr && !all_resident_ && !bal_paused_) pcie_balance_window(steps, G);
3929    if (prof_on_ && G == 1) collect_profile();   // the window's GPU stage stamps
3930    // ---- a sampled or penalized request: the head's sampling again, host-side so its parameters are this call's
3931    // own (a captured kernel would replay the same draws forever).  Row t's draw is Philox(seed, pos0 + t): tied to
3932    // the POSITION it samples, not to how the text was cut into windows, so a seed replays the same text whatever
3933    // the drafts were. Exact: a rejected row's draw is discarded, and no kept decision depends on a reused draw.
3934    if (le_ < g.n_layers) {   // a layer split's earlier stage: the hand-off is written (synced above)
3935        ++windows;
3936        return next_ == nullptr || next_->run(T, tokens, pos0, pool, next_user_, out, err);
3937    }
3938    const bool sampled = !sampling_.greedy && sampling_.temperature > 0.0f;
3939    if (head_sampling_ && (sampled || hist_d_ != nullptr || sampling_.logit_bias != nullptr)) {
3940        SamplerParams sp = sampling_;
3941        sp.counter = (uint64_t) pos0;
3942        // STRATA_SPEC_PROB: the drafter's q lists for this window, judged by rejection sampling (spec_prob.hpp)
3943        bool judged = false;
3944        if (sampled && (measure || (spec_q_ != nullptr && spec_nq_ > 0 && T > 1)) && T <= kVerifyMaxT) {
3945            if (d_spec_ == nullptr &&
3946                cudaMalloc((void**) &d_spec_, (size_t) kVerifyMaxT * (1 + strata::core::kSpecQStride) * sizeof(int32_t)) !=
3947                    cudaSuccess) {
3948                (void) cudaGetLastError();
3949                d_spec_ = nullptr;
3950            }
3951            if (d_spec_ != nullptr) {
3952                const int nq = measure ? spec_nq_ : std::min(spec_nq_, T - 1);
3953                int32_t* d_q = d_spec_ + kVerifyMaxT;
3954                if ((T == 1 || cudaMemcpyAsync(d_spec_, tokens + 1, (size_t) (T - 1) * sizeof(int32_t), cudaMemcpyHostToDevice, cs_) ==
3955                        cudaSuccess) &&
3956                    (nq == 0 || cudaMemcpyAsync(d_q, spec_q_, (size_t) nq * strata::core::kSpecQStride * sizeof(int32_t),
3957                                               cudaMemcpyHostToDevice, cs_) == cudaSuccess))
3958                    judged = measure
3959                        ? sample_tokens_proposal(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp,
3960                                                 d_spec_, d_q, nq, m_out_, cs_)
3961                        : sample_tokens_spec(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp,
3962                                             d_spec_, d_q, nq, m_out_, cs_);
3963            }
3964        }
3965        spec_q_ = nullptr;
3966        spec_nq_ = 0;
3967        if (measure && !judged) {
3968            (void) cudaStreamSynchronize(cs_);
3969            err = "verify: proposal sampler unavailable or allocation/copy/launch failed";
3970            return false;
3971        }
3972        if (judged) ++spec_windows;
3973        else sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_);
3974        if (cudaStreamSynchronize(cs_) != cudaSuccess) {   // m_out_ is the mapped h_out_: synced, it is readable
3975            err = "verify: the head sampling failed";
3976            return false;
3977        }
3978    }
3979    if (measure) {
3980        for (int t = 0; t < T; ++t)
3981            if (((volatile int32_t*) h_out_)[t] == strata::core::proposal::kProposalSamplerErrorToken) {
3982                err = "verify: invalid proposal candidate or zero NULL residual";
3983                return false;
3984            }
3985    }
3986    for (int t = 0; t < T; ++t) out[t] = ((volatile int32_t*) h_out_)[t];
3987    if (tap_file_ != nullptr && !batch_rec_) tap_write(T, tokens, pos0);
3988    note_nonfinite(T, nullptr);
3989    // STRATA_LOGITS_DUMP=<path> (debug tap, off by default): the window's logits as the sampler saw them, written
3990    // AFTER the window (the stream is synchronised above and the graph capture is over, so a plain copy is legal -
3991    // the same place STRATA_DBG_NAN copies from).  One record is
3992    // {int32 magic, int32 T, int32 n_vocab, int32 record, int64 position}, then T * n_vocab FP32 rows; row 0 is
3993    // the window's first position (the last prompt token of a prefill), which is what a KL comparison wants.
3994    if (const char* logits_path = std::getenv("STRATA_LOGITS_DUMP")) {
3995        static std::FILE* lf = std::fopen(logits_path, "wb");
3996        static int32_t lrec = 0;
3997        if (lf != nullptr) {
3998            std::vector<float> h((size_t) T * (size_t) n_vocab_);
3999            const cudaError_t le = cudaMemcpy(h.data(), head_logits_, h.size() * sizeof(float), cudaMemcpyDeviceToHost);
4000            if (le == cudaSuccess) {
4001                const int32_t hdr[4] = {0x53474F4C /*"LOGS"*/, T, (int32_t) n_vocab_, lrec++};
4002                const int64_t hpos = pos0;
4003                std::fwrite(hdr, sizeof hdr, 1, lf);
4004                std::fwrite(&hpos, sizeof hpos, 1, lf);
4005                std::fwrite(h.data(), sizeof(float), h.size(), lf);
4006                std::fflush(lf);
4007            } else {
4008                static bool said = false;
4009                if (!said) {
4010                    said = true;
4011                    std::fprintf(stderr, "strata verify: STRATA_LOGITS_DUMP copy failed: %s\n", cudaGetErrorString(le));
4012                    (void) cudaGetLastError();
4013                }
4014            }
4015        }
4016    }
4017    if (static const bool dbg = std::getenv("STRATA_DBG_NAN") != nullptr; dbg) {   // debug: the first non-finite head
4018        static bool reported = false;
4019        if (!reported) {
4020            std::vector<float> h((size_t) T * (size_t) n_vocab_);
4021            cudaMemcpy(h.data(), head_logits_, h.size() * 4, cudaMemcpyDeviceToHost);
4022            for (int t = 0; t < T && !reported; ++t) {
4023                int64_t bad = 0;
4024                for (int64_t v = 0; v < n_vocab_; ++v) bad += !std::isfinite(h[(size_t) t * n_vocab_ + v]);
4025                if (bad) {
4026                    reported = true;
4027                    std::fprintf(stderr, "strata dbg: verify window at position %lld, row %d: %lld of %lld logits non-finite "
4028                                         "(token out %d)\n", (long long) pos0, t, (long long) bad, (long long) n_vocab_, out[t]);
4029                }
4030            }
4031        }
4032    }
4033    VDBG("window done\n");
4034    ++windows;
4035    progress_at("decode");
4036    progress_beat();
4037    return true;
4038}
4039
4040// set_pcie_balance: each stamped step's times into the model's fits (PcieModel::sample), solved once a window.
4041void Verifier::pcie_balance_window(int64_t steps, int G) {
4042    const volatile unsigned long long* st = h_bal_;
4043    PcieModel& M = *bal_;
4044    for (int64_t k = 0; k < steps; ++k) {
4045        const size_t i = (size_t) ((k / G) * 2 + k % G);
4046        if (!bal_ok_[i]) continue;
4047        const unsigned long long ta = st[4 * i], tb = st[4 * i + 1], tw = st[4 * i + 2];
4048        if (ta == 0 || tb < ta || tw < tb || tw - ta > 1000000000ull) continue;   // not stamped in this window
4049        M.sample(bal_nc_[i], bal_np_[i], bal_p_[i], (double) (tw - ta) * 1e-6);
4050    }
4051    M.solve();
4052}
4053
4054void Verifier::set_plan_slot(int grp) {
4055    const int64_t cap = sink_.cap;
4056    int32_t* base = h_plan_ + (size_t) grp * (size_t) plan_i32_;
4057    const int64_t i32 = 4 + (cap + 1) + cap + cap;
4058    const int64_t ptr_off = (i32 + 1) & ~1ll;
4059    sink_.counts = base;
4060    sink_.start = base + 4;
4061    sink_.dst = sink_.start + cap + 1;
4062    sink_.tok = sink_.dst + cap;
4063    sink_.ptr = (unsigned long long*) (base + ptr_off);
4064    sink_.ptr2 = sink_.ptr + cap;
4065    sink_.start2 = base + ptr_off + 4 * cap;
4066    sink_.dst2 = (unsigned long long*) (base + dst2_off_);
4067    const int G = last_batch_ ? 1 : (groups_[last_t_] > 0 ? groups_[last_t_] : 1);
4068    const int64_t per = latent_ ? 4 * kStagingBlobs : (G == 2 ? kStagingBlobs / 2 : kStagingBlobs);
4069    sink_.staging = (unsigned long long) (staging_ + (size_t) (grp * per) * strata::kernels::cpu::expert_layout().max_blob);
4070    sink_.staging_cap = per;
4071}
4072
4073// Flag B only rises: a host function of an earlier layer may run after a later layer already raised it directly.
4074void Verifier::raise_flag(uint32_t* flag, uint32_t value) { strata::core::flag_raise_max(flag, value); }
4075
4076// Flag B for layer `want - 1`, behind every copy queued on the copy stream (PR #5096, @AlanJager).  The counter only
4077// rises and the graph waits for "flag B >= layer + 1", so raising it on the spot for a layer with nothing to copy
4078// releases an earlier layer (or the other token group of a split window) whose uploads are still in flight.
4079void Verifier::raise_flag_b_ordered(uint32_t want) {
4080    FlagSet& fs = flag_sets_[(want - 1) % (sizeof flag_sets_ / sizeof flag_sets_[0])];
4081    const cudaError_t e = strata::core::raise_flag_b_ordered(copy_used_, copy_, &fs, h_flagB_, want);
4082    if (e != cudaSuccess) {
4083        // The flag was not raised: the consumers must not be released to staging that is still being written.
4084        std::fprintf(stderr, "strata DMA: ordered flag B completion failed: %s\n", cudaGetErrorString(e));
4085        std::fflush(stderr);
4086        release_gpu_waits(5000);
4087        std::abort();
4088    }
4089}
4090
4091// Plan v0.3 P6: the PCIe share by DMA.  The copy engine moves the blobs while the CPU computes its own share and the
4092// GPU its VRAM experts; a host function raises flag B when they have landed (the graph waits for it before the PCIe
4093// groups).  Staging is split between the two token groups of a split window.
4094void Verifier::fetch_dma(void* ctx, const uint8_t* const* src, int n, size_t bytes) {
4095    Verifier* v = (Verifier*) ctx;
4096    const uint32_t want = v->cur_layer_ + 1;
4097    if (n <= 0) { v->raise_flag_b_ordered(want); return; }   // an empty plan stays behind the copies already queued
4098    v->copy_used_ = true;
4099    uint8_t* stage = (uint8_t*) v->sink_.staging;                  // this group's half in a split window
4100    // STRATA_DMA_BATCH (midhatn's #807, F12): the group's independent uploads as one cudaMemcpyBatchAsync.  Mode 0 is
4101    // the loop the engine always ran, errors unchecked (it never stops the engine).  A batch mode whose uploads
4102    // cannot be submitted stops the engine: flag B must not release the consumers to expert weights that were never
4103    // copied.
4104    const int batch_mode = strata::core::dma_batch_mode();
4105    if (batch_mode == 0) {
4106        for (int i = 0; i < n; ++i) cudaMemcpyAsync(stage + (size_t) i * bytes, src[i], bytes, cudaMemcpyHostToDevice, v->copy_);
4107    } else {
4108        const auto copied = strata::core::copy_expert_blobs(stage, src, n, bytes, v->copy_, batch_mode);
4109        if (copied != cudaSuccess) {
4110            std::fprintf(stderr, "strata DMA: expert upload failed: %s\n", cudaGetErrorString(copied));
4111            std::fflush(stderr);
4112            v->release_gpu_waits(5000);
4113            std::abort();
4114        }
4115    }
4116    v->raise_flag_b_ordered(want);   // copy_used_ is set: the host function runs after this group's uploads
4117}
4118
4119void Verifier::publish_plan(void* ctx) {
4120    Verifier* v = (Verifier*) ctx;
4121    strata_store_fence();
4122    *(volatile uint32_t*) v->h_flagA_ = v->cur_layer_ + 1;
4123}
4124
4125bool Verifier::window_logprobs(const int32_t* targets, int T, int64_t pos0, int32_t extra_id, std::FILE* out,
4126                               std::string& err) {
4127    if (next_ != nullptr) return next_->window_logprobs(targets, T, pos0, extra_id, out, err);
4128    const OnDevice on_device(device_);
4129#if defined(STRATA_GPU_METAL)
4130    // the head logits are the Metal window's (window_copy_logits, row by row)
4131    if (n_vocab_ <= 0 || T <= 0 || targets == nullptr || out == nullptr) {
4132        err = "window_logprobs: no head logits for this window";
4133        return false;
4134    }
4135    std::vector<float> h((size_t) T * (size_t) n_vocab_);
4136    for (int t = 0; t < T; ++t)
4137        if (!strata::metal_engine::window_copy_logits(metal_, t, h.data() + (size_t) t * (size_t) n_vocab_)) {
4138            err = "window_logprobs: the head logits copy failed";
4139            return false;
4140        }
4141#else
4142    if (head_logits_ == nullptr || n_vocab_ <= 0 || T <= 0 || targets == nullptr || out == nullptr) {
4143        err = "window_logprobs: no head logits for this window";
4144        return false;
4145    }
4146    // run() synchronized cs_ before returning, so the head of this window is complete
4147    std::vector<float> h((size_t) T * (size_t) n_vocab_);
4148    if (cudaMemcpy(h.data(), head_logits_, h.size() * sizeof(float), cudaMemcpyDeviceToHost) != cudaSuccess) {
4149        err = "window_logprobs: the head logits copy failed";
4150        return false;
4151    }
4152#endif
4153    // STRATA_FORCE_FAULT=<m>:<bias> (test only, off by default, no output): adds <bias> to the logit of every token id divisible by <m>
4154    // before the rows are scored, so the token-forcing checker (tools/force_check.py) can be shown to reject a faulty build
4155    {
4156        static const std::pair<int64_t, float> fault = [] {
4157            const char* v = std::getenv("STRATA_FORCE_FAULT");
4158            long long m = 0;
4159            float b = 0.0f;
4160            if (v != nullptr && std::sscanf(v, "%lld:%f", &m, &b) == 2 && m > 0) return std::make_pair((int64_t) m, b);
4161            return std::make_pair((int64_t) 0, 0.0f);
4162        }();
4163        if (fault.first > 0)
4164            for (int t = 0; t < T; ++t)
4165                for (int64_t v = 0; v < n_vocab_; v += fault.first) h[(size_t) t * (size_t) n_vocab_ + (size_t) v] += fault.second;
4166    }
4167    for (int t = 0; t < T; ++t) {
4168        const float* row = h.data() + (size_t) t * (size_t) n_vocab_;
4169        const int32_t tgt = targets[t];
4170        if (tgt < 0 || (int64_t) tgt >= n_vocab_) continue;
4171        int64_t top = 0;
4172        for (int64_t v = 1; v < n_vocab_; ++v)
4173            if (row[v] > row[top]) top = v;
4174        const double maxv = row[top];
4175        const bool has_extra = extra_id >= 0 && (int64_t) extra_id < n_vocab_;
4176        double sum = 0.0, sum_without = 0.0;   // the second skips extra_id: no cancellation when it holds ~all mass
4177        for (int64_t v = 0; v < n_vocab_; ++v) {
4178            const double e = std::exp((double) row[v] - maxv);
4179            sum += e;
4180            if (v != (int64_t) extra_id) sum_without += e;
4181        }
4182        const double lse = maxv + std::log(sum);
4183        const double extra = has_extra ? (double) row[extra_id] - lse : NAN;
4184        const double without = has_extra && tgt != extra_id && sum_without > 0.0
4185                                   ? (double) row[tgt] - (maxv + std::log(sum_without)) : NAN;
4186        std::fprintf(out, "%lld\t%d\t%.9f\t%lld\t%.9f\t%d\t%.9f\t%.9f", (long long) (pos0 + t), (int) tgt,
4187                     (double) row[tgt] - lse, (long long) top, maxv - lse, (int) (top == (int64_t) tgt), extra,
4188                     without);
4189        // STRATA_LOGPOS_TOPK=K: the K most likely tokens and their log-probabilities too (`id:logprob`), for a
4190        // top-k comparison with another engine on the same tokens (docs/UNSLOTH_Q4.md)
4191        static const int topk = [] {
4192            const char* v = std::getenv("STRATA_LOGPOS_TOPK");
4193            return v != nullptr ? std::max(0, std::min(256, std::atoi(v))) : 0;
4194        }();
4195        if (topk > 0) {
4196            std::vector<int32_t> order((size_t) n_vocab_);
4197            for (int64_t v = 0; v < n_vocab_; ++v) order[(size_t) v] = (int32_t) v;
4198            std::partial_sort(order.begin(), order.begin() + topk, order.end(),
4199                              [&](int32_t a, int32_t b) { return row[a] > row[b]; });
4200            for (int j = 0; j < topk; ++j)
4201                std::fprintf(out, "\t%d:%.6f", order[(size_t) j], (double) row[order[(size_t) j]] - lse);
4202        }
4203        std::fprintf(out, "\n");
4204    }
4205    std::fflush(out);
4206    return true;
4207}
4208
4209namespace { bool g_commit_async = false; }
4210void Verifier::set_commit_async(bool on) { g_commit_async = on && std::getenv("STRATA_COMMIT_SYNC") == nullptr; }
4211
4212bool Verifier::commit(int n_keep, std::string& err) {
4213#if defined(STRATA_GPU_METAL)
4214    return strata::metal_engine::window_commit(metal_, n_keep, err);
4215#endif
4216    const OnDevice on_device(device_);
4217    if (n_keep < 1 || n_keep > last_t_) { err = "verify: commit count out of range"; return false; }
4218    const Clock::time_point t0 = Clock::now();
4219    h_commit_[0] = n_keep;
4220    h_commit_[1] = n_keep - 1;
4221    for (int t = 0; t < max_t_; ++t) h_commit_[2 + t] = t < n_keep ? (int32_t) (last_pos0_ + t) : -1;
4222    if (last_t_ == 1 && !always_publish_ && one_token_self_commit() && !g_qfuse()) {
4223        // a one-token window has advanced the state itself (record_window): no commit graph. (Not with STRATA_QFUSE: its windows
4224        // do not self-commit, see `self_commit` there - skipping the commit here left the GDN state and the indexer tail one token behind.)
4225    } else {
4226        std::atomic_thread_fence(std::memory_order_seq_cst);
4227        // STRATA_COMMIT_TIMING=1 (measurement only): the commit graph's GPU time, from an event pair around it (read at the
4228        // next commit, when the pair has long completed); printed every 300 commits
4229        static struct CommitTiming {
4230            bool on = false, pending = false;
4231            cudaEvent_t b = nullptr, e = nullptr;
4232            double ms = 0;
4233            int64_t n = 0;
4234            CommitTiming() { const char* v = std::getenv("STRATA_COMMIT_TIMING"); on = v != nullptr && v[0] == '1'; }
4235        } ct;
4236        if (ct.on && ct.b == nullptr &&
4237            (cudaEventCreate(&ct.b) != cudaSuccess || cudaEventCreate(&ct.e) != cudaSuccess)) { ct.on = false; (void) cudaGetLastError(); }
4238        if (ct.on && ct.pending) {
4239            float ms = 0;
4240            if (cudaEventSynchronize(ct.e) == cudaSuccess && cudaEventElapsedTime(&ms, ct.b, ct.e) == cudaSuccess) { ct.ms += ms; ++ct.n; }
4241            ct.pending = false;
4242            if (ct.n > 0 && ct.n % 300 == 0)
4243                std::fprintf(stderr, "strata verify: commit graph %.3f ms GPU on average over %lld commits\n", ct.ms / (double) ct.n,
4244                             (long long) ct.n);
4245        }
4246        if (ct.on) cudaEventRecord(ct.b, cs_);
4247        const cudaError_t le = cudaGraphLaunch(commit_exec_, cs_);
4248        if (ct.on) { cudaEventRecord(ct.e, cs_); ct.pending = true; }
4249        if (le != cudaSuccess) { err = std::string("verify: commit launch: ") + cudaGetErrorString(le); return false; }
4250        // set_commit_async: no wait here - the next window runs on the same stream after it, and the drafter (its own
4251        // stream) reads only this window's final rows and its own K/V. h_commit_ is next written after the next window's
4252        // results are read, i.e. after this graph has run.  Everything else waits on commit_done_ (wait_commit).
4253        if (!g_commit_async || next_ != nullptr) {
4254            const cudaError_t se = cudaStreamSynchronize(cs_);
4255            if (se != cudaSuccess) { err = std::string("verify: commit: ") + cudaGetErrorString(se); return false; }
4256        } else {
4257            const cudaError_t re = cudaEventRecord(commit_done_, cs_);
4258            if (re != cudaSuccess) { err = std::string("verify: commit event: ") + cudaGetErrorString(re); return false; }
4259            (void) cudaStreamQuery(cs_);
4260            commit_pending_ = true;
4261        }
4262    }
4263    if (ple_stage())   // stages that share one session must advance it once
4264        for (int t = 0; t < n_keep; ++t) {
4265            ss_->ple_prev[0] = ss_->ple_prev[1];
4266            ss_->ple_prev[1] = last_tokens_[t];
4267        }
4268    ms_commit += ms_since(t0);
4269    return next_ == nullptr || next_->commit(n_keep, err);
4270}
4271
4272bool Verifier::commit_deferred() const {
4273#if defined(STRATA_GPU_METAL)
4274    return false;   // the Metal window keeps its own bookkeeping: never dropped
4275#else
4276    if (last_t_ < 1) return false;
4277    const bool self = last_t_ == 1 && !always_publish_ && one_token_self_commit() && !g_qfuse();   // as commit() above
4278    return !self && (next_ == nullptr || next_->commit_deferred());
4279#endif
4280}
4281
4282bool Verifier::wait_commit(std::string& err) {
4283#if defined(STRATA_GPU_METAL)
4284    (void) err;
4285    return true;
4286#endif
4287    if (commit_pending_) {
4288        const OnDevice on_device(device_);
4289        commit_pending_ = false;
4290        const cudaError_t se = cudaEventSynchronize(commit_done_);
4291        if (se != cudaSuccess) { err = std::string("verify: commit: ") + cudaGetErrorString(se); return false; }
4292    }
4293    return next_ == nullptr || next_->wait_commit(err);
4294}
4295
4296
4297// ================================ BATCH WINDOWS (see init_slots) ================================
4298
4299bool Verifier::init_slots(const std::vector<SessionState*>& slots, std::string& err) {
4300    const OnDevice on_device(device_);
4301    if (g_ == nullptr || ss_ == nullptr) { err = "verify: init_slots before init"; return false; }
4302    if (slots.empty()) {
4303        err = "verify: init_slots needs at least one session";
4304        return false;
4305    }
4306    for (SessionState* x : slots) {
4307        if (x == nullptr || x->layer_lo != ss_->layer_lo || x->layer_hi != ss_->layer_hi ||
4308            x->max_cells != ss_->max_cells || x->gdn_ord0 != ss_->gdn_ord0 || x->qsa_ord0 != ss_->qsa_ord0) {
4309            err = "verify: a slot's session is not carved like the stage's own (layer range, context)";
4310            return false;
4311        }
4312    }
4313#if defined(STRATA_GPU_METAL)
4314    // the Metal window keeps each slot's running state itself (metal/src/engine/window.cpp): none of the CUDA batch buffers
4315    slots_ = slots;
4316    slot_sp_.assign(slots.size(), sampling_);
4317    slot_bias_dev_.assign(slots.size(), nullptr);
4318    slot_tail_.assign(slots.size(), {});
4319    if (metal_ == nullptr || !strata::metal_engine::window_init_slots(metal_, slots, err)) {
4320        if (err.empty()) err = "verify: the Metal window is not up";
4321        return false;
4322    }
4323    std::fprintf(stderr, "strata verify: batch windows of up to %d sequences, run slot by slot in the Metal window\n", (int) slots.size());
4324    return true;
4325#endif
4326    const strata::kernels::QsaShapes s = shapes_of(*g_);
4327    const int64_t S = (int64_t) slots.size(), CB = 2 + max_t_;
4328    const int64_t TS = (s.idx_block - 1) * g_->idx_key_dim, nQ = g_->n_qsa_layers();
4329    void* d = nullptr;
4330    if (!mapped((size_t) (S * CB * 4 + 16), (void**) &h_commitb_, (void**) &m_commitb_)) {
4331        err = "verify: the batch commit staging failed";
4332        return false;
4333    }
4334    const uint64_t a = ((uint64_t) S * CB * 4 + 255) & ~255ull;
4335    if (cudaMalloc(&d, a + (uint64_t) S * std::max<int64_t>(nQ, 1) * TS * 4) != cudaSuccess) {
4336        err = "verify: the batch buffers do not fit";
4337        return false;
4338    }
4339    arena_b_ = d;
4340    commitb_ = (int32_t*) d;
4341    tail_snap_b_ = (float*) ((uint8_t*) d + a);
4342    slots_ = slots;
4343    slot_sp_.assign(slots.size(), sampling_);   // greedy until set_slot_sampling
4344    slot_bias_dev_.assign(slots.size(), nullptr);
4345    slot_tail_.assign(slots.size(), {});
4346    std::fprintf(stderr, "strata verify: batch windows of up to %lld sequences (layers [%lld, %lld))%s\n", (long long) S,
4347                 (long long) lb_, (long long) le_, g_batch_self_commit ? ", one-row windows keep their rows" : "");
4348    return true;
4349}
4350
4351bool Verifier::capture_batch(const int* rows, int S, int hbase, std::string& err) {
4352    cudaGraphExec_t& ex = exec_bm_[bkey(rows, S, hbase)];
4353    if (ex != nullptr) return true;
4354    if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) {
4355        err = "verify: begin batch capture failed";
4356        return false;
4357    }
4358    batch_rec_ = true;
4359    row_base_ = hbase;
4360    for (int t = 0; t < S; ++t) brow_[t] = rows[t];
4361    std::string rerr;
4362    sel_long_ = 0;   // batch rows: the one-CTA select
4363    const bool ok = record_window(S, cs_, rerr);
4364    batch_rec_ = false;
4365    row_base_ = 0;
4366    cudaGraph_t graph = nullptr;
4367    const cudaError_t ce = cudaStreamEndCapture(cs_, &graph);
4368    if (!ok || ce != cudaSuccess) {
4369        if (graph) cudaGraphDestroy(graph);
4370        err = !ok ? rerr : std::string("verify: end batch capture: ") + cudaGetErrorString(ce);
4371        return false;
4372    }
4373    const bool made = instantiate_evicting(ex, graph, bkey(rows, S, hbase), "verify: batch instantiate: ", err);
4374    cudaGraphDestroy(graph);
4375    if (!made) return false;
4376    if (cudaGraphUpload(ex, cs_) != cudaSuccess || cudaStreamSynchronize(cs_) != cudaSuccess)
4377        (void) cudaGetLastError();   // only a warm-up: the first launch uploads it (see capture)
4378    std::string list;
4379    for (int t = 0; t < S; ++t) list += (t ? "," : "") + std::to_string(rows[t]);
4380    std::fprintf(stderr, "strata verify: captured the batch window over slots %s\n", list.c_str());
4381    return true;
4382}
4383
4384bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::string& err) {
4385    if (batch_self_commits(rows, S)) return true;   // the window keeps its rows: no commit graph
4386    cudaGraphExec_t& cex = commit_bm_[bkey(rows, S, hbase)];
4387    if (cex != nullptr) return true;
4388    using namespace strata::kernels;
4389    const ModelGeometry& g = *g_;
4390    const QsaShapes s = shapes_of(g);
4391    const int64_t C = g.ssm_conv_channels, HV = g.ssm_v_heads, ZV = g.ssm_value_dim, ID = g.idx_key_dim, MT = max_t_;
4392    const int64_t CB = 2 + MT, nQ = g.n_qsa_layers();
4393    const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +
4394                                (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);
4395    const int64_t TS = (s.idx_block - 1) * ID;
4396    const int64_t HS = (int64_t) NG_HIST * NG_HC_DIM;
4397    if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) {
4398        err = "verify: begin batch commit capture failed";
4399        return false;
4400    }
4401    bool ok = true;
4402    try {
4403        for (int t = 0; t < S; ++t)
4404            if (t == 0 || rows[t] != rows[t - 1])
4405                copy_i32_from_mapped(commitb_ + (size_t) rows[t] * CB, m_commitb_ + (size_t) rows[t] * CB, CB, cs_);
4406        int64_t qsa_index = 0, gdn_index = 0;
4407        for (int64_t l = 0; l < lb_; ++l) (is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1;
4408        for (int64_t l = lb_; l < le_ && ok; ++l) {
4409            const LayerView v(*wt_, l);
4410            if (!is_qsa_layer(g, l)) {
4411                const WeightRef* wnm = need(v, "ssm_norm.weight", err);
4412                if (!wnm) { ok = false; break; }
4413                // STRATA_BATCH_GDN_GROUPS=1: one-row groups (no --batch-mtp proposals) commit their recurrence
4414                // in one launch for all slots; the conv commits stay per slot
4415                static const bool gdn_groups_on = [] {
4416                    const char* v = std::getenv("STRATA_BATCH_GDN_GROUPS");
4417                    return v != nullptr && std::atoi(v) != 0;
4418                }();
4419                bool one_row = S <= 8;
4420                for (int t = 1; one_row && t < S; ++t) one_row = rows[t] != rows[t - 1];
4421                strata::kernels::GdnGroups gg;
4422                for (int t = 0; t < S;) {
4423                    const int first = t;
4424                    while (t < S && rows[t] == rows[first]) ++t;
4425                    SessionState& sx = *slots_[(size_t) rows[first]];
4426                    const int32_t* keep = commitb_ + (size_t) rows[first] * CB;
4427                    float* state = sx.gdn_state + (size_t) (gdn_index - sx.gdn_ord0) * gdn_floats;
4428                    float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
4429                    gdn_conv_commit(conv, qkv_L_ + (size_t) gdn_index * MT * C + (size_t) first * C,
4430                                    (int) C, keep, cs_);
4431                    if (gdn_groups_on && one_row) {
4432                        gg.state[gg.n] = state;
4433                        gg.keep[gg.n] = keep;
4434                        gg.first[gg.n] = first;
4435                        gg.ntok[gg.n] = 1;
4436                        ++gg.n;
4437                        continue;
4438                    }
4439                    gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C + (size_t) first * C, (int) C,
4440                                        gate_L_ + (size_t) gdn_index * MT * HV + (size_t) first * HV,
4441                                        beta_L_ + (size_t) gdn_index * MT * HV + (size_t) first * HV,
4442                                        z_ + (size_t) first * ZV, (const float*) wnm->data, EPS,
4443                                        y_dummy_ + (size_t) first * ZV, (int) g.ssm_k_heads,
4444                                        (int) HV, t - first, keep, cs_,
4445                                        t - first > 1 ? t - first : 0);   // a 1-row group keeps the 0.1.39 kernel
4446                }
4447                if (gg.n > 0)
4448                    gdn_step_norm_groups(gg, h_L_ + (size_t) gdn_index * MT * C, (int) C,
4449                                         gate_L_ + (size_t) gdn_index * MT * HV, beta_L_ + (size_t) gdn_index * MT * HV,
4450                                         z_, (const float*) wnm->data, EPS, y_dummy_, (int) g.ssm_k_heads, (int) HV, true,
4451                                         cs_);
4452                ++gdn_index;
4453            } else {
4454                const WeightRef* wikn = need(v, "indexer.k_norm.weight", err);
4455                if (!wikn) { ok = false; break; }
4456                for (int t = 0; t < S;) {
4457                    const int first = t;
4458                    while (t < S && rows[t] == rows[first]) ++t;
4459                    const QsaState& st = slots_[(size_t) rows[first]]->qsa_states[qsa_index];
4460                    copy_from_mapped(st.idx_tail, tail_snap_b_ + ((size_t) rows[first] * nQ + qsa_index) * TS,
4461                                     TS, cs_);
4462                    const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};
4463                    for (int u = first; u < t; ++u)
4464                        native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + u) * ID,
4465                                                  commitb_ + (size_t) rows[first] * CB + 2 + (u - first),
4466                                                  0, (const float*) wikn->data, EPS, ib, s, st.max_cells,
4467                                                  rope_scaling(), cs_);
4468                }
4469                ++qsa_index;
4470            }
4471        }
4472        if (ok && ss_->ple.ready() && ple_stage())
4473            for (int t = 0; t < S;) {
4474                const int first = t;
4475                while (t < S && rows[t] == rows[first]) ++t;
4476                copy_indexed(slots_[(size_t) rows[first]]->ple_hist, hist_snap_ + (size_t) first * HS,
4477                             HS, commitb_ + (size_t) rows[first] * CB + 1, HS, cs_);
4478            }
4479    } catch (const std::exception& e) {
4480        err = std::string("verify batch commit: ") + e.what();
4481        ok = false;
4482    }
4483    cudaGraph_t graph = nullptr;
4484    const cudaError_t ce = cudaStreamEndCapture(cs_, &graph);
4485    if (!ok) {
4486        if (graph) cudaGraphDestroy(graph);
4487        return false;
4488    }
4489    if (ce != cudaSuccess) {
4490        if (graph) cudaGraphDestroy(graph);
4491        err = std::string("verify: batch commit capture: ") + cudaGetErrorString(ce);
4492        return false;
4493    }
4494    const bool made = instantiate_evicting(cex, graph, bkey(rows, S, hbase), "verify: batch commit instantiate: ", err);
4495    cudaGraphDestroy(graph);
4496    return made;
4497}
4498
4499// ---- STRATA_PIPED_MTP: commits after the verdict (see the header)
4500
4501bool Verifier::init_deferred_commit(int rows, std::string& err) {
4502    const OnDevice on_device(device_);
4503    if (slots_.empty()) { err = "verify: init_deferred_commit before init_slots"; return false; }
4504    if (rows < 1) { err = "verify: init_deferred_commit needs at least one row"; return false; }
4505    const ModelGeometry& g = *g_;
4506    const uint64_t R = (uint64_t) rows, C = (uint64_t) g.ssm_conv_channels, HV = (uint64_t) g.ssm_v_heads;
4507    const uint64_t ID = (uint64_t) g.idx_key_dim;
4508    const uint64_t nG = (uint64_t) std::max<int64_t>(g.n_gdn_layers(), 1), nQ = (uint64_t) std::max<int64_t>(g.n_qsa_layers(), 1);
4509    const uint64_t HS = (uint64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM;
4510    const uint64_t CB = 2 + (uint64_t) max_t_, nS = (uint64_t) slots_.size();
4511    const uint64_t floats[6] = {nG * R * C, nG * R * C, nG * R * HV, nG * R * HV, nQ * R * ID, R * HS};
4512    uint64_t bytes = (nS * CB * 4 + 255) & ~255ull;
4513    for (uint64_t f : floats) bytes += (f * 4 + 255) & ~255ull;
4514    if (cudaMalloc(&dc_arena_, bytes) != cudaSuccess) {
4515        err = "verify: the saved commit rows (" + std::to_string(bytes >> 20) + " MiB) do not fit";
4516        return false;
4517    }
4518    uint8_t* p = (uint8_t*) dc_arena_;
4519    commitd_ = (int32_t*) p;
4520    p += (nS * CB * 4 + 255) & ~255ull;
4521    float** dst[6] = {&dc_qkv_, &dc_h_, &dc_gate_, &dc_beta_, &dc_idx_, &dc_hist_};
4522    for (int i = 0; i < 6; ++i) {
4523        *dst[i] = (float*) p;
4524        p += (floats[i] * 4 + 255) & ~255ull;
4525    }
4526    if (!mapped((size_t) (nS * CB * 4 + 16), (void**) &h_commitd_, (void**) &m_commitd_)) {
4527        err = "verify: the deferred commit staging failed";
4528        return false;
4529    }
4530    dc_rows_ = rows;
4531    std::fprintf(stderr, "strata verify: pipelined batch windows commit after the verdict (layers [%lld, %lld), %d rows, "
4532                         "%.1f MiB saved rows)\n", (long long) lb_, (long long) le_, rows, (double) bytes / 1048576.0);
4533    return true;
4534}
4535
4536bool Verifier::capture_deferred(const int* rows, int S, int hbase, std::string& err) {
4537    using namespace strata::kernels;
4538    const auto key = bkey(rows, S, hbase);
4539    cudaGraphExec_t& sex = save_bm_[key];
4540    cudaGraphExec_t& cex = dcommit_bm_[key];
4541    if (sex != nullptr && cex != nullptr) return true;
4542    const ModelGeometry& g = *g_;
4543    const QsaShapes s = shapes_of(g);
4544    const int64_t C = g.ssm_conv_channels, HV = g.ssm_v_heads, ZV = g.ssm_value_dim, ID = g.idx_key_dim, MT = max_t_;
4545    const int64_t R = dc_rows_, CB = 2 + MT, nQ = g.n_qsa_layers();
4546    const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +
4547                                (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);
4548    const int64_t TS = (s.idx_block - 1) * ID;
4549    const int64_t HS = (int64_t) NG_HIST * NG_HC_DIM;
4550    const bool ple = ss_->ple.ready() && ple_stage();
4551    auto layer_index = [&](int64_t& qsa_index, int64_t& gdn_index) {
4552        qsa_index = gdn_index = 0;
4553        for (int64_t l = 0; l < lb_; ++l) (is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1;
4554    };
4555    auto finish = [&](cudaGraphExec_t& ex, bool ok, const char* what) {
4556        cudaGraph_t graph = nullptr;
4557        const cudaError_t ce = cudaStreamEndCapture(cs_, &graph);
4558        if (!ok || ce != cudaSuccess) {
4559            if (graph) cudaGraphDestroy(graph);
4560            if (ok) err = std::string(what) + cudaGetErrorString(ce);
4561            return false;
4562        }
4563        const bool made = instantiate_evicting(ex, graph, key, what, err);
4564        cudaGraphDestroy(graph);
4565        return made;
4566    };
4567    // the save: the window's rows [0, S) of the scratch the commit replays -> the group's saved rows [hbase, +S)
4568    if (sex == nullptr) {
4569        if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) {
4570            err = "verify: begin save capture failed";
4571            return false;
4572        }
4573        bool ok = true;
4574        int64_t qsa_index = 0, gdn_index = 0;
4575        layer_index(qsa_index, gdn_index);
4576        auto copy = [&](float* dst, const float* src, int64_t n) {
4577            ok = ok && cudaMemcpyAsync(dst, src, (size_t) n * sizeof(float), cudaMemcpyDeviceToDevice, cs_) == cudaSuccess;
4578        };
4579        for (int64_t l = lb_; l < le_; ++l) {
4580            if (!is_qsa_layer(g, l)) {
4581                copy(dc_qkv_ + (size_t) (gdn_index * R + hbase) * C, qkv_L_ + (size_t) gdn_index * MT * C, S * C);
4582                copy(dc_h_ + (size_t) (gdn_index * R + hbase) * C, h_L_ + (size_t) gdn_index * MT * C, S * C);
4583                copy(dc_gate_ + (size_t) (gdn_index * R + hbase) * HV, gate_L_ + (size_t) gdn_index * MT * HV, S * HV);
4584                copy(dc_beta_ + (size_t) (gdn_index * R + hbase) * HV, beta_L_ + (size_t) gdn_index * MT * HV, S * HV);
4585                ++gdn_index;
4586            } else {
4587                copy(dc_idx_ + (size_t) (qsa_index * R + hbase) * ID, idx_raw_L_ + (size_t) qsa_index * MT * ID, S * ID);
4588                ++qsa_index;
4589            }
4590        }
4591        if (ple) copy(dc_hist_ + (size_t) hbase * HS, hist_snap_, S * HS);
4592        if (!finish(sex, ok, "verify: save capture: ")) {
4593            if (ok && err.empty()) err = "verify: save capture failed";
4594            return false;
4595        }
4596    }
4597    // the commit: as capture_commit_batch, replaying the saved rows; the accepted prefixes come from commitd_
4598    if (cex == nullptr) {
4599        if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) {
4600            err = "verify: begin deferred commit capture failed";
4601            return false;
4602        }
4603        bool ok = true;
4604        try {
4605            for (int t = 0; t < S; ++t)
4606                if (t == 0 || rows[t] != rows[t - 1])
4607                    copy_i32_from_mapped(commitd_ + (size_t) rows[t] * CB, m_commitd_ + (size_t) rows[t] * CB, CB, cs_);
4608            int64_t qsa_index = 0, gdn_index = 0;
4609            layer_index(qsa_index, gdn_index);
4610            for (int64_t l = lb_; l < le_ && ok; ++l) {
4611                const LayerView v(*wt_, l);
4612                if (!is_qsa_layer(g, l)) {
4613                    const WeightRef* wnm = need(v, "ssm_norm.weight", err);
4614                    if (!wnm) { ok = false; break; }
4615                    for (int t = 0; t < S;) {
4616                        const int first = t;
4617                        while (t < S && rows[t] == rows[first]) ++t;
4618                        SessionState& sx = *slots_[(size_t) rows[first]];
4619                        const int32_t* keep = commitd_ + (size_t) rows[first] * CB;
4620                        float* state = sx.gdn_state + (size_t) (gdn_index - sx.gdn_ord0) * gdn_floats;
4621                        float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
4622                        const int64_t row = gdn_index * R + hbase + first;
4623                        gdn_conv_commit(conv, dc_qkv_ + (size_t) row * C, (int) C, keep, cs_);
4624                        // z only feeds the norm's output, which the commit discards (y_dummy_): the window scratch will do
4625                        gdn_step_norm_multi(state, dc_h_ + (size_t) row * C, (int) C, dc_gate_ + (size_t) row * HV,
4626                                            dc_beta_ + (size_t) row * HV, z_ + (size_t) first * ZV,
4627                                            (const float*) wnm->data, EPS, y_dummy_ + (size_t) first * ZV,
4628                                            (int) g.ssm_k_heads, (int) HV, t - first, keep, cs_,
4629                                            t - first > 1 ? t - first : 0);
4630                    }
4631                    ++gdn_index;
4632                } else {
4633                    const WeightRef* wikn = need(v, "indexer.k_norm.weight", err);
4634                    if (!wikn) { ok = false; break; }
4635                    for (int t = 0; t < S;) {
4636                        const int first = t;
4637                        while (t < S && rows[t] == rows[first]) ++t;
4638                        const QsaState& st = slots_[(size_t) rows[first]]->qsa_states[qsa_index];
4639                        copy_from_mapped(st.idx_tail, tail_snap_b_ + ((size_t) rows[first] * nQ + qsa_index) * TS, TS, cs_);
4640                        const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};
4641                        for (int u = first; u < t; ++u)
4642                            native_qsa_indexer_append(dc_idx_ + (size_t) (qsa_index * R + hbase + u) * ID,
4643                                                      commitd_ + (size_t) rows[first] * CB + 2 + (u - first), 0,
4644                                                      (const float*) wikn->data, EPS, ib, s, st.max_cells,
4645                                                      rope_scaling(), cs_);
4646                    }
4647                    ++qsa_index;
4648                }
4649            }
4650            if (ok && ple)
4651                for (int t = 0; t < S;) {
4652                    const int first = t;
4653                    while (t < S && rows[t] == rows[first]) ++t;
4654                    copy_indexed(slots_[(size_t) rows[first]]->ple_hist, dc_hist_ + (size_t) (hbase + first) * HS, HS,
4655                                 commitd_ + (size_t) rows[first] * CB + 1, HS, cs_);
4656                }
4657        } catch (const std::exception& e) {
4658            err = std::string("verify deferred commit: ") + e.what();
4659            ok = false;
4660        }
4661        if (!finish(cex, ok, "verify: deferred commit capture: ")) {
4662            if (ok && err.empty()) err = "verify: deferred commit capture failed";
4663            return false;
4664        }
4665    }
4666    return true;
4667}
4668
4669bool Verifier::batch_launch_rows(const int* rows, int S, int hbase, const int32_t* tokens, const int64_t* pos,
4670                                 std::string& err) {
4671    const OnDevice on_device(device_);
4672    if (dc_rows_ < 1) { err = "verify: batch_launch_rows without init_deferred_commit"; return false; }
4673    if (b_running_) { err = "verify: batch_launch_rows while this stage is busy"; return false; }
4674    if (S < 1 || hbase < 0 || hbase + S > dc_rows_) { err = "verify: a pipelined window outside the saved rows"; return false; }
4675    if (pre_launch_ && !pre_launch_(cs_, err)) return false;
4676    staging_deferred_ = true;
4677    const bool staged = stage_batch(rows, S, hbase, tokens, pos, err);
4678    staging_deferred_ = false;
4679    if (!staged || !capture_deferred(rows, S, hbase, err)) return false;
4680    const auto key = bkey(rows, S, hbase);
4681    cudaError_t le = cudaGraphLaunch(exec_bm_[key], cs_);
4682    if (le == cudaSuccess) le = cudaGraphLaunch(save_bm_[key], cs_);   // the rows the commit replays, kept for it
4683    if (le != cudaSuccess) { err = std::string("verify: batch launch: ") + cudaGetErrorString(le); return false; }
4684    (void) cudaStreamQuery(cs_);
4685    b_k_ = 0;
4686    b_steps_ = le_ - lb_;
4687    ring_now();
4688    b_running_.store(true, std::memory_order_release);   // last: an external server reads the rest after it
4689    return true;
4690}
4691
4692bool Verifier::batch_commit_rows(const int* rows, int S, int hbase, const int* keep, const int32_t* tokens,
4693                                 const int64_t* pos, std::string& err) {
4694    const OnDevice on_device(device_);
4695    const auto it = dcommit_bm_.find(bkey(rows, S, hbase));
4696    if (it == dcommit_bm_.end() || it->second == nullptr) { err = "verify: a deferred commit without its window"; return false; }
4697    const int64_t CB = 2 + max_t_;
4698    // Each slot's accepted prefix.  The graph reads it from mapped memory when it runs; this slot's entry is written
4699    // again only at its next verdict, which comes after its next window has passed this stage - behind this commit.
4700    for (int t = 0; t < S;) {
4701        const int first = t;
4702        while (t < S && rows[t] == rows[first]) ++t;
4703        const int n = keep[rows[first]];
4704        if (n < 1 || n > t - first) { err = "verify: accepted prefix is outside its slot group"; return false; }
4705        int32_t* c = h_commitd_ + (size_t) rows[first] * CB;
4706        c[0] = n;
4707        c[1] = n - 1;
4708        for (int64_t j = 0; j < max_t_; ++j) c[2 + j] = j < n ? (int32_t) pos[first + j] : -1;
4709    }
4710    std::atomic_thread_fence(std::memory_order_seq_cst);
4711    const cudaError_t le = cudaGraphLaunch(it->second, cs_);
4712    if (le != cudaSuccess) { err = std::string("verify: deferred commit launch: ") + cudaGetErrorString(le); return false; }
4713    (void) cudaStreamQuery(cs_);
4714    if (ple_stage())   // the host's side of the commit (the hash's last two tokens), the accepted rows only
4715        for (int t = 0; t < S;) {
4716            const int first = t;
4717            while (t < S && rows[t] == rows[first]) ++t;
4718            SessionState& sx = *slots_[(size_t) rows[first]];
4719            for (int u = first; u < first + keep[rows[first]]; ++u) {
4720                sx.ple_prev[0] = sx.ple_prev[1];
4721                sx.ple_prev[1] = tokens[u];
4722            }
4723        }
4724    return true;
4725}
4726
4727bool Verifier::evict_batch_graph(const std::vector<int>& keep, bool& evicted, std::string& err) {
4728    evicted = false;
4729    auto old = exec_bm_.end();
4730    uint64_t oldest = UINT64_MAX;
4731    for (auto it = exec_bm_.begin(); it != exec_bm_.end(); ++it) {
4732        if (it->first == keep) continue;
4733        const auto u = bm_used_.find(it->first);
4734        const uint64_t t = u == bm_used_.end() ? 0 : u->second;
4735        if (t < oldest) { oldest = t; old = it; }
4736    }
4737    if (old == exec_bm_.end()) return true;
4738    if (cudaStreamSynchronize(cs_) != cudaSuccess) {
4739        err = "verify: synchronizing before batch graph eviction failed";
4740        return false;
4741    }
4742    const auto old_key = old->first;
4743    if (old->second) cudaGraphExecDestroy(old->second);
4744    exec_bm_.erase(old);
4745    bm_used_.erase(old_key);
4746    auto commit_old = commit_bm_.find(old_key);
4747    if (commit_old != commit_bm_.end()) {
4748        if (commit_old->second) cudaGraphExecDestroy(commit_old->second);
4749        commit_bm_.erase(commit_old);
4750    }
4751    evicted = true;
4752    return true;
4753}
4754
4755bool Verifier::evict_window_graph(int keep_t, bool& evicted, std::string& err) {
4756    evicted = false;
4757    if (no_window_eviction_ || keep_t < 1) return true;
4758    bool have[strata::kernels::kWindowMaxT + 1] = {};
4759    const int top = std::min<int>(max_t_, strata::kernels::kWindowMaxT);
4760    for (int t = 1; t <= top; ++t) have[t] = (ar_off_ ? exec_nr_[sel_long_][t] : exec_[sel_long_][t]) != nullptr;
4761    const int victim = strata::core::pick_window_victim(have, top, keep_t, prelaunched_);
4762    if (victim == 0) return true;
4763    if (cudaStreamSynchronize(cs_) != cudaSuccess) {
4764        err = "verify: synchronizing before window graph eviction failed";
4765        return false;
4766    }
4767    cudaGraphExec_t& e = ar_off_ ? exec_nr_[sel_long_][victim] : exec_[sel_long_][victim];
4768    cudaGraphExecDestroy(e);
4769    e = nullptr;
4770    (ar_off_ ? launched_nr_ : launched_)[sel_long_][victim] = false;   // the next graph of that size is a cold first launch again
4771    evicted = true;
4772    return true;
4773}
4774
4775// STRATA_GRAPH_PRIO: the capture-time notes.  A fork note keeps cs's current tail (the node the branch's first kernel
4776// will depend on); a tail note keeps a priority stream's current tail and the priority its nodes should run at
4777// (1 = the device's highest, -1 = its lowest).  No-ops with the switch off, outside a capture, and on HIP / Metal.
4778void Verifier::note_prio_fork(cudaStream_t from) {
4779#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL)
4780    if (!graph_prio_on()) return;
4781    cudaStreamCaptureStatus st = cudaStreamCaptureStatusNone;
4782    const cudaGraphNode_t* deps = nullptr;
4783    size_t nd = 0;
4784    if (prio_capture_deps(from, &st, &deps, &nd) != cudaSuccess || st != cudaStreamCaptureStatusActive) {
4785        (void) cudaGetLastError();
4786        return;
4787    }
4788    for (size_t i = 0; i < nd; ++i) prio_forks_.push_back(deps[i]);
4789#else
4790    (void) from;
4791#endif
4792}
4793
4794void Verifier::note_prio_tail(cudaStream_t on, int prio) {
4795#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL)
4796    if (!graph_prio_on()) return;
4797    cudaStreamCaptureStatus st = cudaStreamCaptureStatusNone;
4798    const cudaGraphNode_t* deps = nullptr;
4799    size_t nd = 0;
4800    if (prio_capture_deps(on, &st, &deps, &nd) != cudaSuccess || st != cudaStreamCaptureStatusActive) {
4801        (void) cudaGetLastError();
4802        return;
4803    }
4804    for (size_t i = 0; i < nd; ++i) prio_tails_.push_back({deps[i], prio});
4805#else
4806    (void) on; (void) prio;
4807#endif
4808}
4809
4810// STRATA_GRAPH_PRIO: what priorities the captured kernel nodes carry (a histogram, logged once per window graph).  If the
4811// capture copied none from the streams (design 1's R1: some drivers read back 0 everywhere), each priority stream's
4812// nodes are found by walking its noted tails back to the noted forks and the attribute is set per node.
4813void Verifier::apply_node_priorities(cudaGraph_t graph, int T) {
4814#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL)
4815    int lo = 0, hi = 0;
4816    if (cudaDeviceGetStreamPriorityRange(&lo, &hi) != cudaSuccess) { (void) cudaGetLastError(); return; }
4817    auto histogram = [&](std::map<int, int>& h) {
4818        size_t nn = 0;
4819        cudaGraphGetNodes(graph, nullptr, &nn);
4820        std::vector<cudaGraphNode_t> nodes(nn);
4821        cudaGraphGetNodes(graph, nodes.data(), &nn);
4822        h.clear();
4823        for (cudaGraphNode_t nd : nodes) {
4824            cudaGraphNodeType ty;
4825            if (cudaGraphNodeGetType(nd, &ty) != cudaSuccess || ty != cudaGraphNodeTypeKernel) continue;
4826            cudaKernelNodeAttrValue v{};
4827            if (cudaGraphKernelNodeGetAttribute(nd, cudaKernelNodeAttributePriority, &v) == cudaSuccess) ++h[v.priority];
4828            else { (void) cudaGetLastError(); ++h[999]; }
4829        }
4830    };
4831    std::map<int, int> h;
4832    histogram(h);
4833    bool captured = false;
4834    for (auto& [p, c] : h) captured = captured || (p != 0 && p != 999 && c > 0);
4835    int repaired = 0, walked_forks = (int) prio_forks_.size(), walked_tails = (int) prio_tails_.size();
4836    if (!captured && !prio_tails_.empty()) {   // the fallback: per node from the capture-time notes
4837        std::set<cudaGraphNode_t> stop(prio_forks_.begin(), prio_forks_.end()), seen;
4838        for (auto& [tail, pr] : prio_tails_) {
4839            std::vector<cudaGraphNode_t> stack{tail};
4840            while (!stack.empty()) {
4841                cudaGraphNode_t nd = stack.back();
4842                stack.pop_back();
4843                if (stop.count(nd) || !seen.insert(nd).second) continue;
4844                cudaGraphNodeType ty;
4845                if (cudaGraphNodeGetType(nd, &ty) == cudaSuccess && ty == cudaGraphNodeTypeKernel) {
4846                    cudaKernelNodeAttrValue v{};
4847                    v.priority = pr > 0 ? hi : lo;
4848                    if (cudaGraphKernelNodeSetAttribute(nd, cudaKernelNodeAttributePriority, &v) == cudaSuccess) ++repaired;
4849                    else (void) cudaGetLastError();
4850                }
4851                size_t nd_n = 0;
4852                prio_node_deps(nd, nullptr, &nd_n);
4853                std::vector<cudaGraphNode_t> deps(nd_n);
4854                if (nd_n > 0 && prio_node_deps(nd, deps.data(), &nd_n) == cudaSuccess)
4855                    for (size_t i = 0; i < nd_n; ++i) stack.push_back(deps[i]);
4856                else (void) cudaGetLastError();
4857            }
4858        }
4859        histogram(h);
4860    }
4861    std::string s;
4862    for (auto& [p, c] : h) s += " " + std::to_string(c) + " x prio " + (p == 999 ? std::string("?") : std::to_string(p)) + ";";
4863    std::fprintf(stderr, "strata verify: the %d-token window's kernel node priorities (range %d..%d):%s %s (%d forks, %d tails noted%s)\n",
4864                 T, lo, hi, s.c_str(), captured ? "captured from the streams" : "NOT captured from the streams",
4865                 walked_forks, walked_tails, repaired > 0 ? (", " + std::to_string(repaired) + " nodes set from the notes").c_str() : "");
4866#else
4867    (void) graph; (void) T;
4868#endif
4869}
4870
4871bool Verifier::instantiate_evicting(cudaGraphExec_t& ex, cudaGraph_t graph, const std::vector<int>& key,
4872                                   const char* what, std::string& err, int keep_t, unsigned long long flags) {
4873    // #997: every layout of active slots keeps its own graph pair (20-30 MiB each on an L40S), and with an expert cache
4874    // sized to the reserve the next window graph - a batch layout or a one-request window captured on first use - can
4875    // find no VRAM left: free the least recently used layouts until it fits (they are captured again when needed)
4876    // (into a local: what a failed instantiate leaves in the output is not specified, and `ex` is a member that
4877    // capture() reads as "captured" when it is not null)
4878    capture_oom_ = false;
4879    cudaGraphExec_t got = nullptr;
4880    cudaError_t ie = cudaGraphInstantiate(&got, graph, flags);
4881    int freed = 0;
4882    for (bool evicted = true; ie == cudaErrorMemoryAllocation && evicted;) {
4883        (void) cudaGetLastError();
4884        if (!evict_batch_graph(key, evicted, err)) return false;
4885        if (evicted) {
4886            ++freed;
4887            ie = cudaGraphInstantiate(&got, graph, flags);
4888        }
4889    }
4890    if (freed > 0)
4891        std::fprintf(stderr, "strata verify: no VRAM for a new window graph: freed the graphs of %d older batch slot "
4892                             "layouts, %zu kept (a larger --vram-reserve-mib keeps more)\n", freed, exec_bm_.size());
4893    // #3702: a single-request window with nothing of a batch left to free: free the graphs of other window sizes
4894    int freed_sizes = 0;
4895    for (bool evicted = true; ie == cudaErrorMemoryAllocation && evicted && keep_t > 0;) {
4896        (void) cudaGetLastError();
4897        if (!evict_window_graph(keep_t, evicted, err)) return false;
4898        if (evicted) {
4899            ++freed_sizes;
4900            ie = cudaGraphInstantiate(&got, graph, flags);
4901        }
4902    }
4903    if (freed_sizes > 0)
4904        std::fprintf(stderr, "strata verify: no VRAM for the %d-token window graph: freed the graphs of %d other window "
4905                             "sizes (they are captured again when used; a larger --vram-reserve-mib or "
4906                             "--vram-reserve-later-mib keeps them)\n", keep_t, freed_sizes);
4907    if (ie != cudaSuccess) {
4908        capture_oom_ = ie == cudaErrorMemoryAllocation;
4909        if (capture_oom_) (void) cudaGetLastError();
4910        got = nullptr;
4911        err = std::string(what) + cudaGetErrorString(ie);
4912        return false;
4913    }
4914    ex = got;
4915    return true;
4916}
4917
4918bool Verifier::prepare(int T, bool& no_vram, std::string& err) {
4919    no_vram = false;
4920#if defined(STRATA_GPU_METAL)
4921    (void) T;
4922    (void) err;
4923    return true;
4924#else
4925    if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; }
4926    if (next_ != nullptr || lb_ > 0) return true;
4927    const OnDevice on_device(device_);
4928    refresh_ar();
4929    if ((ar_off_ ? exec_nr_[sel_long_][T] : exec_[sel_long_][T]) != nullptr) return true;
4930    capture_oom_ = false;
4931    if (capture(T, err)) return true;
4932    no_vram = capture_oom_;
4933    return false;
4934#endif
4935}
4936
4937bool Verifier::stage_batch(const int* rows, int S, int hbase, const int32_t* tokens, const int64_t* pos,
4938                           std::string& err) {
4939    using namespace strata::kernels;
4940    // the row layout: a slot may own a contiguous group of rows (--batch-mtp), also across the stages of a layer split,
4941    // whose hand-off buffers hold kVerifyNarrowT rows, or set_handoff_rows' (a stage that hands rows on or takes them); a
4942    // batch window keeps kVerifyMaxT rows (the row tables below) when max_t is longer (--lookup-max-t)
4943    if (const char* why = batch_rows_error(rows, S, pos, (int) slots_.size(), std::min(max_t_, kVerifyMaxT), hbase,
4944                                           next_ != nullptr || lb_ > 0, handoff_rows_ > 0 ? handoff_rows_ : kVerifyNarrowT)) {
4945        err = why;
4946        return false;
4947    }
4948    if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }
4949    const ModelGeometry& g = *g_;
4950    for (int t = 0; t < S; ++t)
4951        if (pos[t] < 0 || pos[t] + 1 > slots_[(size_t) rows[t]]->max_cells) {
4952            err = "verify: slot " + std::to_string(rows[t]) + " runs past its context";
4953            return false;
4954        }
4955    refresh_ar();
4956    // --batch-mtp only (limit 0 = 0.1.39: no eviction): slot rotation creates new layouts; bound the captured graph
4957    // pairs, evicting the least recently used layout.  Without a limit the same eviction frees VRAM for a capture.
4958    const auto key = bkey(rows, S, hbase);
4959    bool evicted = false;
4960    if (batch_graph_limit_ > 0 && exec_bm_.find(key) == exec_bm_.end() && exec_bm_.size() >= batch_graph_limit_ &&
4961        !evict_batch_graph(key, evicted, err))
4962        return false;
4963    bm_used_[key] = ++bm_tick_;
4964    // (a pipelined window that commits after the verdict has its own commit graph: capture_deferred)
4965    if (!capture_batch(rows, S, hbase, err) || (!staging_deferred_ && !capture_commit_batch(rows, S, hbase, err)))
4966        return false;
4967    const Clock::time_point t0 = Clock::now();
4968    const QsaShapes s = shapes_of(g);
4969    for (int t = 0; t < S; ++t) {
4970        h_tok_[t] = tokens[t];
4971        qsa_step_fill(h_step_ + t * kStepCount, pos[t], s);
4972        for (int64_t h = 0; h < g.n_head; ++h) h_pos_[t * g.n_head + h] = (int32_t) pos[t];
4973        int32_t* pk = h_pos_ + (size_t) max_t_ * g.n_head;
4974        int32_t* pi = pk + (size_t) max_t_ * g.n_head_kv;
4975        for (int64_t h = 0; h < g.n_head_kv; ++h) pk[t * g.n_head_kv + h] = (int32_t) pos[t];
4976        for (int64_t h = 0; h < g.idx_q_heads; ++h) pi[t * g.idx_q_heads + h] = (int32_t) pos[t];
4977    }
4978    if (ss_->ple.ready() && ple_stage()) {
4979        uint32_t ple_rows[kVerifyMaxT * PLE_N_HEADS];   // (not `rows`: that is the slots of the window's rows)
4980        for (int t = 0; t < S; ++t) {
4981            const SessionState& sx = *slots_[(size_t) rows[t]];
4982            int32_t prev[2] = {sx.ple_prev[0], sx.ple_prev[1]};
4983            if (t > 0 && rows[t] == rows[t - 1]) {
4984                prev[0] = t > 1 && rows[t - 2] == rows[t] ? tokens[t - 2] : sx.ple_prev[1];
4985                prev[1] = tokens[t - 1];
4986            }
4987            ngram_rows(&tokens[t], prev, 1, ss_->ple.consts, ple_rows + t * PLE_N_HEADS);
4988        }
4989        if (!ss_->ple.table->gather_batch(ple_rows, (size_t) S, h_ple_, err)) return false;
4990    }
4991    // Each slot owns a contiguous group. The default commit keeps all its rows; speculative
4992    // decoding may change the prefix length after comparing the draft with these picks.
4993    const int64_t CB = 2 + max_t_;
4994    for (int t = 0; t < S;) {
4995        const int first = t;
4996        while (t < S && rows[t] == rows[first]) ++t;
4997        int32_t* c = h_commitb_ + (size_t) rows[first] * CB;
4998        c[0] = t - first;
4999        c[1] = t - first - 1;
5000        for (int64_t j = 0; j < max_t_; ++j)
5001            c[2 + j] = j < t - first ? (int32_t) pos[first + j] : -1;
5002    }
5003    if (g_trace) std::fprintf(stderr, "K0-STAGE-RESET t=%.3f h_seq=%u\n", (double) std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6, *(volatile uint32_t*) h_seq_);
5004    *(volatile uint32_t*) h_seq_ = 0;
5005    *(volatile uint32_t*) h_flag_ = 0;
5006    *(volatile uint32_t*) h_flagA_ = 0;
5007    *(volatile uint32_t*) h_flagB_ = 0;
5008    if (h_xlseq_ != nullptr) *(volatile uint32_t*) h_xlseq_ = 0;   // edge0: the D stage's doorbell restarts
5009    std::atomic_thread_fence(std::memory_order_seq_cst);
5010    last_t_ = S;
5011    for (int t = 0; t < S; ++t) last_rows_[t] = rows[t];
5012    row_base_ = hbase;   // the graphs' key (and nothing else) reads it until the next stage_batch
5013    last_batch_ = true;
5014    for (int t = 0; t < S; ++t) { last_tokens_[t] = tokens[t]; last_pos_b_[t] = pos[t]; }
5015    ms_host += ms_since(t0);
5016    return true;
5017}
5018
5019bool Verifier::run_slots(int S, const int32_t* tokens, const int64_t* pos, PoolMultiFn pool, void* user, int32_t* out,
5020                         std::string& err) {
5021    int rows[strata::kernels::kVerifyMaxT] = {};
5022    for (int t = 0; t < S && t < strata::kernels::kVerifyMaxT; ++t) rows[t] = t;
5023    return run_slot_rows(rows, S, tokens, pos, pool, user, out, err);
5024}
5025
5026bool Verifier::run_slot_rows(const int* rows, int S, const int32_t* tokens, const int64_t* pos, PoolMultiFn pool,
5027                             void* user, int32_t* out, std::string& err) {
5028#if defined(STRATA_GPU_METAL)
5029    // each row runs in its slot's state and commits there (a one-token window); nothing is left for commit_slots
5030    if (S < 1 || S > (int) strata::kernels::kVerifyMaxT) { err = "verify: batch window size out of range"; return false; }
5031    (void) pool; (void) user;
5032    if (!strata::metal_engine::window_run_slots(metal_, rows, S, tokens, pos, out, err)) return false;
5033    last_t_ = S;
5034    for (int t = 0; t < S; ++t) { last_rows_[t] = rows[t]; last_tokens_[t] = tokens[t]; last_pos_b_[t] = pos[t]; }
5035    last_batch_ = true;
5036    // a slot with its own sampling, penalties or logit bias (set_slot_sampling / set_slot_history / set_slot_logit_bias): its row is drawn again from the
5037    // window's logits with Philox(seed, position), as a solo window draws it; a plain greedy slot keeps the window's argmax token
5038    {
5039        std::vector<int32_t> hrows;
5040        for (int t = 0; t < S; ++t) {
5041            strata::kernels::SamplerParams sp;
5042            const int32_t* hist = nullptr;
5043            int hlen = 0;
5044            const int r = slot_row_draw(S, t, sp, hist, hlen, hrows, err);
5045            if (r < 0) return false;
5046            if (r == 0) continue;
5047            if (!strata::metal_engine::window_sample_slot_row(metal_, t, sp, hist, hlen, &out[t], err)) return false;
5048        }
5049    }
5050    return true;
5051#endif
5052    using namespace strata::kernels;
5053    const OnDevice on_device(device_);
5054    const ModelGeometry& g = *g_;
5055    if (pre_launch_ && !pre_launch_(cs_, err)) return false;
5056    if (!stage_batch(rows, S, 0, tokens, pos, err)) return false;
5057    const cudaError_t le = cudaGraphLaunch(exec_bm_[bkey(rows, S, 0)], cs_);
5058    if (le != cudaSuccess) { err = std::string("verify: batch launch: ") + cudaGetErrorString(le); return false; }
5059    (void) cudaStreamQuery(cs_);
5060    volatile uint32_t* const seq = h_seq_;
5061    volatile uint32_t* const flag = h_flag_;
5062    const int64_t steps = le_ - lb_;
5063    // #646: a stage whose every expert is resident plans on the device and raises no host doorbells, so the
5064    // per-layer spin below has nothing to wait for: without the PLE flag the graph finishes with the ring silent
5065    // ("verify batch: layer K never rang (graph finished)" - K is that stage's first layer), and with it the graph
5066    // sits on the PLE wait until the 20 s timeout.  As run() does: raise the PLE flag the graph's first wait reads,
5067    // let the graph run to the end, and skip the host's per-layer service (there is nothing to serve).
5068    // #646 + #871: the skip is per-window (ar_on), not per-process (all_resident_): a stage that was 100%
5069    // resident at init takes the doorbell graph while a prompt loan/shrink/swap is in flight (ar_off_), and that
5070    // graph waits on host doorbells the skipped service never raises (GPU at 100%, host in the sync below).
5071    if (ar_on()) {
5072        if (ss_->ple.ready() && ple_stage()) {
5073            std::atomic_thread_fence(std::memory_order_seq_cst);
5074            strata_store_fence();
5075            *flag = 1;
5076        }
5077        const cudaError_t se = cudaStreamSynchronize(cs_);
5078        if (se != cudaSuccess) { err = std::string("verify batch: ") + cudaGetErrorString(se); return false; }
5079        cudaStreamSynchronize(copy_);
5080        if (prof_on_) collect_profile();
5081        ++windows;
5082        if (le_ < g.n_layers) return next_ == nullptr || next_->run_slot_rows(rows, S, tokens, pos, pool, next_user_, out, err);
5083        if (!sample_rows(S, err)) return false;
5084        for (int t = 0; t < S; ++t) out[t] = ((volatile int32_t*) h_out_)[t];
5085        note_nonfinite(S, last_pos_b_);
5086        progress_at("decode");
5087        progress_beat();
5088        return true;
5089    }
5090    for (int64_t k = 0; k < steps; ++k) {
5091        const int64_t l = lb_ + k;
5092        const uint32_t want = (uint32_t) (k + 1);
5093        const Clock::time_point a = Clock::now();
5094        auto last_flush = a;
5095        uint32_t spins = 0;
5096        progress_at("verify batch: waiting for the GPU to reach layer", l);
5097        while (*seq < want) {
5098            strata_cpu_pause();
5099            if ((++spins & 1023u) != 0) continue;
5100            const auto now = Clock::now();
5101            if (now - last_flush > std::chrono::microseconds(2000)) {
5102                last_flush = now;
5103                const cudaError_t q = cudaStreamQuery(cs_);
5104                if (q != cudaErrorNotReady && *seq < want) {
5105                    err = "verify batch: layer " + std::to_string(l) + " never rang (" +
5106                          (q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")";
5107                    return false;
5108                }
5109            }
5110            if (now - a > std::chrono::seconds(20)) {
5111                err = "verify batch: timed out at layer " + std::to_string(l) + released_note(release_gpu_waits(5000));
5112                return false;
5113            }
5114        }
5115        strata_load_fence();   // as above, for the batch loop's wait
5116        const Clock::time_point b = Clock::now();
5117        cur_layer_ = want - 1;
5118        set_plan_slot(0);
5119        progress_at("verify batch: the CPU experts of layer", l);
5120        // The recorded graph consumes the helper mask and weighted sum just as
5121        // the solo graph does. Reset both and supply this layer's routing weights.
5122        if (remote_opt_) remote_opt_->begin(h_w_, 0, S);
5123        strata::core::latent_xl_current() = h_latxlq_;
5124        strata::core::latent_xlseq_current() = h_xlseq_;
5125        strata::core::latent_act0_current() = m_latact0_;
5126        if (pool != nullptr) pool(user, h_x_, h_ids_, S, ss_->k, h_ymiss_, l);
5127        if (remote_opt_) remote_opt_->end();
5128        progress_tick();
5129        std::atomic_thread_fence(std::memory_order_seq_cst);
5130        strata_store_fence();
5131        if (*(volatile uint32_t*) h_flagA_ != want) {        // the pool did not publish a plan: an empty one
5132            sink_.counts[0] = 0;
5133            sink_.counts[1] = 0;
5134            sink_.counts[2] = 0;
5135            sink_.start[0] = 0;
5136            sink_.start2[0] = 0;
5137            std::atomic_thread_fence(std::memory_order_seq_cst);
5138            *(volatile uint32_t*) h_flagA_ = want;
5139            raise_flag_b_ordered(want);   // behind any copy still queued from an earlier layer
5140        }
5141        *flag = want;
5142        ms_wait += std::chrono::duration<double, std::milli>(b - a).count();
5143        ms_pool += ms_since(b);
5144    }
5145    const cudaError_t se = cudaStreamSynchronize(cs_);
5146    if (se != cudaSuccess) { err = std::string("verify batch: ") + cudaGetErrorString(se); return false; }
5147    cudaStreamSynchronize(copy_);
5148    if (prof_on_) collect_profile();
5149    ++windows;
5150    if (le_ < g.n_layers) return next_ == nullptr || next_->run_slot_rows(rows, S, tokens, pos, pool, next_user_, out, err);
5151    if (!sample_rows(S, err)) return false;
5152    for (int t = 0; t < S; ++t) out[t] = ((volatile int32_t*) h_out_)[t];
5153    note_nonfinite(S, last_pos_b_);
5154    progress_at("decode");
5155    progress_beat();
5156    return true;
5157}
5158
5159bool Verifier::commit_slots(std::string& err) {
5160    std::vector<int> keep(slots_.size(), 0);
5161    for (int t = 0; t < last_t_; ++t) ++keep[(size_t) last_rows_[t]];
5162    return commit_slot_prefixes(keep.data(), err);
5163}
5164
5165bool Verifier::commit_slot_prefixes(const int* keep, std::string& err) {
5166#if defined(STRATA_GPU_METAL)
5167    (void) keep;   // (greedy one-row windows, committed by window_run_slots)
5168    if (!last_batch_ || last_t_ < 1) { err = "verify: commit_slots without a batch window"; return false; }
5169    return true;
5170#endif
5171    const OnDevice on_device(device_);
5172    if (!last_batch_ || last_t_ < 1) { err = "verify: commit_slots without a batch window"; return false; }
5173    const int S = last_t_;
5174    const Clock::time_point t0 = Clock::now();
5175    const int64_t CB = 2 + max_t_;
5176    // One prefix per slot: rejected draft rows must not enter recurrent state.
5177    for (int t = 0; t < S;) {
5178        const int first = t;
5179        while (t < S && last_rows_[t] == last_rows_[first]) ++t;
5180        const int n = keep[last_rows_[first]];
5181        if (n < 1 || n > t - first) {
5182            err = "verify: accepted prefix is outside its slot group";
5183            return false;
5184        }
5185        int32_t* c = h_commitb_ + (size_t) last_rows_[first] * CB;
5186        c[0] = n;
5187        c[1] = n - 1;
5188        for (int j = 0; j < max_t_; ++j)
5189            c[2 + j] = j < n ? (int32_t) last_pos_b_[first + j] : -1;
5190    }
5191    std::atomic_thread_fence(std::memory_order_seq_cst);
5192    if (!batch_self_commits(last_rows_, S)) {   // (else the window has kept its rows)
5193        const cudaError_t le = cudaGraphLaunch(commit_bm_[bkey(last_rows_, S, row_base_)], cs_);
5194        if (le != cudaSuccess) { err = std::string("verify: batch commit launch: ") + cudaGetErrorString(le); return false; }
5195        const cudaError_t se = cudaStreamSynchronize(cs_);
5196        if (se != cudaSuccess) { err = std::string("verify: batch commit: ") + cudaGetErrorString(se); return false; }
5197    }
5198    if (ple_stage())
5199        for (int t = 0; t < S;) {
5200            const int first = t;
5201            while (t < S && last_rows_[t] == last_rows_[first]) ++t;
5202            SessionState& sx = *slots_[(size_t) last_rows_[first]];
5203            for (int u = first; u < first + keep[last_rows_[first]]; ++u) {
5204                sx.ple_prev[0] = sx.ple_prev[1];
5205                sx.ple_prev[1] = last_tokens_[u];
5206            }
5207        }
5208    ms_commit += ms_since(t0);
5209    return next_ == nullptr || next_->commit_slot_prefixes(keep, err);
5210}
5211
5212bool Verifier::set_slot_logit_bias(int slot, const std::vector<float>& bias, std::string& err) {
5213    if (next_ && !next_->set_slot_logit_bias(slot, bias, err)) return false;
5214    if (le_ >= 0 && le_ < g_->n_layers) return true;
5215    if (slot < 0 || slot >= (int) slot_bias_dev_.size()) return true;
5216    const OnDevice on_device(device_);
5217    if (bias.empty()) { slot_bias_dev_[(size_t) slot] = nullptr; slot_sp_[(size_t) slot].logit_bias = nullptr; return true; }
5218    if (bias.size() != (size_t) n_vocab_) { err = "logit_bias vocabulary size mismatch"; return false; }
5219    const size_t bytes = bias.size() * sizeof(float);
5220    if (slot_bias_dev_[(size_t) slot] == nullptr) {
5221        float* d = nullptr;
5222        if (cudaMalloc((void**) &d, bytes) != cudaSuccess) { err = "cannot allocate the slot's logit_bias"; return false; }
5223        slot_bias_dev_[(size_t) slot] = d;
5224    }
5225    if (cudaMemcpy(slot_bias_dev_[(size_t) slot], bias.data(), bytes, cudaMemcpyHostToDevice) != cudaSuccess) { err = "cannot upload the slot's logit_bias"; return false; }
5226    slot_sp_[(size_t) slot].logit_bias = slot_bias_dev_[(size_t) slot];
5227    return true;
5228}
5229
5230// One batch row's draw inputs: 0 = the row keeps the window's argmax token (a plain greedy slot), 1 = draw it with `sp` (+ `hist` / `hlen`), -1 = error.
5231// Row t of the last window feeds last_tokens_[t] into slot last_rows_[t]; the penalty-history row is the slot's reply tail plus its tokens in this window up to t
5232// (slot_penalty_rows), staged on the device like a solo window's.
5233int Verifier::slot_row_draw(int S, int t, strata::kernels::SamplerParams& sp, const int32_t*& hist, int& hlen, std::vector<int32_t>& hrows,
5234                            std::string& err) {
5235    constexpr int kSlotHistMax = 4096;   // serve's kPenaltyWindowCap
5236    sp = slot_sp_[(size_t) last_rows_[t]];
5237    const bool pen = sp.penalty_last_n > 0 && (sp.penalty_repeat != 1.0f || sp.penalty_freq != 0.0f || sp.penalty_present != 0.0f);
5238    const bool bias = sp.logit_bias != nullptr;
5239    hist = nullptr;
5240    hlen = 0;
5241    if ((sp.greedy || sp.temperature <= 0.0f) && !pen && !bias) return 0;   // a plain greedy slot keeps the window's argmax token untouched
5242    sp.counter = (uint64_t) last_pos_b_[t];   // Philox(seed, position): the solo window's draw for this position
5243    if (!pen) { sp.penalty_last_n = 0; return 1; }
5244    std::vector<const int32_t*> tails(slots_.size(), nullptr);
5245    std::vector<int64_t> n_tails(slots_.size(), 0);
5246    for (size_t b = 0; b < slots_.size() && b < slot_tail_.size(); ++b) { tails[b] = slot_tail_[b].data(); n_tails[b] = (int64_t) slot_tail_[b].size(); }
5247    hlen = std::min(sp.penalty_last_n, kSlotHistMax);
5248    const size_t need = (size_t) S * (size_t) hlen;
5249    hrows.assign(need, -1);
5250    strata::kernels::slot_penalty_rows(last_rows_, last_tokens_, S, tails.data(), n_tails.data(), hlen, hrows.data());
5251    const OnDevice on_hist(device_);
5252    if (slot_hist_cap_ < need) {
5253        if (slot_hist_d_ != nullptr) cudaFree(slot_hist_d_);
5254        slot_hist_d_ = nullptr;
5255        if (cudaMalloc((void**) &slot_hist_d_, need * sizeof(int32_t)) != cudaSuccess) { err = "verify batch: the penalty-history allocation failed"; return -1; }
5256        slot_hist_cap_ = need;
5257    }
5258#if defined(STRATA_GPU_METAL)
5259    if (cudaMemcpy(slot_hist_d_ + (size_t) t * (size_t) hlen, hrows.data() + (size_t) t * (size_t) hlen, (size_t) hlen * sizeof(int32_t), cudaMemcpyHostToDevice) != cudaSuccess)
5260#else
5261    if (cudaMemcpyAsync(slot_hist_d_ + (size_t) t * (size_t) hlen, hrows.data() + (size_t) t * (size_t) hlen, (size_t) hlen * sizeof(int32_t),
5262                        cudaMemcpyHostToDevice, cs_) != cudaSuccess)
5263#endif
5264    { err = "verify batch: the penalty-history copy failed"; return -1; }
5265    hist = slot_hist_d_ + (size_t) t * (size_t) hlen;
5266    return 1;
5267}
5268
5269bool Verifier::sample_rows(int S, std::string& err) {
5270#if defined(STRATA_GPU_METAL)
5271    (void) S;
5272    err = "verify batch: sample_rows is the CUDA / HIP path";
5273    return false;
5274#else
5275    bool any = false;
5276    std::vector<int32_t> hrows;
5277    for (int t = 0; t < S; ++t) {
5278        strata::kernels::SamplerParams sp;
5279        const int32_t* hist = nullptr;
5280        int hlen = 0;
5281        const int r = slot_row_draw(S, t, sp, hist, hlen, hrows, err);
5282        if (r < 0) return false;
5283        if (r == 0) continue;
5284        strata::kernels::sample_tokens(head_logits_ + (size_t) t * (size_t) n_vocab_, 1, (int) n_vocab_, hist, hlen, sp, m_out_ + t, cs_);
5285        any = true;
5286    }
5287    if (any && cudaStreamSynchronize(cs_) != cudaSuccess) { err = "verify batch: the row sampling failed"; return false; }
5288    return true;
5289#endif
5290}
5291
5292bool Verifier::batch_launch(int base, int S, const int32_t* tokens, const int64_t* pos, std::string& err) {
5293    const OnDevice on_device(device_);
5294    if (b_running_) { err = "verify: batch_launch while this stage is busy"; return false; }
5295    int rows[strata::kernels::kVerifyMaxT] = {};
5296    for (int t = 0; t < S && t < strata::kernels::kVerifyMaxT; ++t) rows[t] = base + t;
5297    if (pre_launch_ && !pre_launch_(cs_, err)) return false;
5298    if (!stage_batch(rows, S, base, tokens, pos, err)) return false;
5299    cudaError_t le = cudaGraphLaunch(exec_bm_[bkey(rows, S, base)], cs_);
5300    if (le == cudaSuccess && !batch_self_commits(rows, S))   // (else the window has kept its rows itself)
5301        le = cudaGraphLaunch(commit_bm_[bkey(rows, S, base)], cs_);   // right behind it: every row is kept
5302    if (le != cudaSuccess) { err = std::string("verify: batch launch: ") + cudaGetErrorString(le); return false; }
5303    (void) cudaStreamQuery(cs_);
5304    if (ple_stage())   // the host's side of the commit (the hash's last two tokens)
5305        for (int t = 0; t < S; ++t) {
5306            SessionState& sx = *slots_[(size_t) rows[t]];
5307            sx.ple_prev[0] = sx.ple_prev[1];
5308            sx.ple_prev[1] = tokens[t];
5309        }
5310    b_k_ = 0;
5311    b_steps_ = le_ - lb_;
5312    ring_now();
5313    b_running_.store(true, std::memory_order_release);   // last: an external server reads the rest after it
5314    return true;
5315}
5316
5317int Verifier::batch_serve(PoolMultiFn pool, void* user) {
5318    if (!b_running_.load(std::memory_order_acquire)) return 1;
5319    volatile uint32_t* const seq = h_seq_;
5320    // #646: an all-resident stage's graph raises no host doorbells (see run_slot_rows): nothing to serve per layer,
5321    // except the PLE flag, which the graph's first wait reads and only the host can raise (the same raise
5322    // run_slot_rows makes).  Per-window (ar_on): with a loan in flight the doorbell graph needs the per-layer service.
5323    if (ar_on() && ss_->ple.ready() && ple_stage()) {
5324        std::atomic_thread_fence(std::memory_order_seq_cst);
5325        strata_store_fence();
5326        *h_flag_ = 1;
5327    }
5328    for (;;) {
5329        // the window's row count is read after the served-layer count: with external serving the window this call
5330        // began on can have finished and the next one been launched meanwhile, and batch_launch writes its rows
5331        // (stage_batch) before it resets b_k_, so a count that is the new window's comes with the new rows
5332        const int64_t k = b_k_.load(std::memory_order_acquire);
5333        if (ar_on() || k >= b_steps_) break;
5334        const uint32_t want = (uint32_t) (k + 1);
5335        if (*seq < want) return 0;
5336        const int S = last_t_;
5337        const Clock::time_point b = Clock::now();
5338        cur_layer_ = want - 1;
5339        set_plan_slot(0);
5340        if (remote_opt_) remote_opt_->begin(h_w_, 0, S);
5341        if (pool != nullptr) {
5342            strata::core::latent_xl_current() = h_latxlq_;
5343            strata::core::latent_xlseq_current() = h_xlseq_;
5344        strata::core::latent_act0_current() = m_latact0_;
5345            pool(user, h_x_, h_ids_, S, ss_->k, h_ymiss_, lb_ + k);
5346        }
5347        if (remote_opt_) remote_opt_->end();
5348        progress_tick();
5349        std::atomic_thread_fence(std::memory_order_seq_cst);
5350        strata_store_fence();
5351        if (*(volatile uint32_t*) h_flagA_ != want) {        // the pool did not publish a plan: an empty one
5352            sink_.counts[0] = 0;
5353            sink_.counts[1] = 0;
5354            sink_.counts[2] = 0;
5355            sink_.start[0] = 0;
5356            sink_.start2[0] = 0;
5357            std::atomic_thread_fence(std::memory_order_seq_cst);
5358            *(volatile uint32_t*) h_flagA_ = want;
5359            raise_flag_b_ordered(want);   // behind any copy still queued from an earlier layer
5360        }
5361        *(volatile uint32_t*) h_flag_ = want;
5362        if (g_trace) std::fprintf(stderr, "FLAG-SET want=%u\n", (unsigned) want);
5363        ms_pool += ms_since(b);
5364        ring_now();
5365        b_k_.fetch_add(1, std::memory_order_release);
5366    }
5367    return 1;
5368}
5369
5370int Verifier::batch_poll(PoolMultiFn pool, void* user, std::string& err) {
5371    if (!b_running_) return 1;
5372    // set_external_serve: another thread serves the doorbells (batch_serve) and this one only checks for a window that
5373    // will not finish, as below: its graph ended (or failed) with a layer still to ring, or no layer rang for 20 s.
5374    // The stream query can wait for the driver's lock while a read's call holds it; the doorbells go on meanwhile.
5375    // The served count is read before the query and the ring count after it: a layer served in between rang first.
5376    if (ext_serve_.load(std::memory_order_acquire) && !ar_on()) {
5377        const int64_t k = b_k_.load(std::memory_order_acquire);
5378        if (k < b_steps_) {
5379            const auto now = Clock::now();
5380            if (now - last_ring() <= std::chrono::milliseconds(2) || now - ext_checked_ < std::chrono::milliseconds(1))
5381                return 0;
5382            ext_checked_ = now;   // (at most one query a millisecond: pump calls this in a loop)
5383            const OnDevice on_device(device_);
5384            const cudaError_t q = cudaStreamQuery(cs_);
5385            if (q != cudaErrorNotReady && *(volatile uint32_t*) h_seq_ < (uint32_t) (k + 1)) {
5386                err = "verify batch: layer " + std::to_string(lb_ + k) + " never rang (" +
5387                      (q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")";
5388                b_running_ = false;
5389                return -1;
5390            }
5391            if (now - last_ring() > std::chrono::seconds(20)) {
5392                err = "verify batch: timed out at layer " + std::to_string(lb_ + k) +
5393                      released_note(release_gpu_waits(5000));
5394                b_running_ = false;
5395                return -1;
5396            }
5397            return 0;
5398        }
5399    }
5400    const OnDevice on_device(device_);
5401    const int S = last_t_;
5402    // the layers that have rung so far (batch_serve); with one still to ring: did the graph finish without it, or
5403    // has it waited too long?
5404    if (!batch_serve(pool, user)) {
5405        const auto now = Clock::now();
5406        if (now - last_ring() > std::chrono::milliseconds(2)) {
5407            const cudaError_t q = cudaStreamQuery(cs_);
5408            if (q != cudaErrorNotReady && *(volatile uint32_t*) h_seq_ < (uint32_t) (b_k_ + 1)) {
5409                err = "verify batch: layer " + std::to_string(lb_ + b_k_) + " never rang (" +
5410                      (q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")";
5411                b_running_ = false;
5412                return -1;
5413            }
5414            if (now - last_ring() > std::chrono::seconds(20)) {
5415                err = "verify batch: timed out at layer " + std::to_string(lb_ + b_k_) +
5416                      released_note(release_gpu_waits(5000));
5417                b_running_ = false;
5418                return -1;
5419            }
5420        }
5421        return 0;
5422    }
5423    const cudaError_t q = cudaStreamQuery(cs_);
5424    if (q == cudaErrorNotReady) return 0;
5425    if (q != cudaSuccess) { err = std::string("verify batch: ") + cudaGetErrorString(q); b_running_ = false; return -1; }
5426    const cudaError_t qc = cudaStreamQuery(copy_);   // no host function of this window may raise flag B in the next
5427    if (qc == cudaErrorNotReady) return 0;
5428    if (prof_on_) collect_profile();
5429    if (last_stage()) {
5430        if (!sample_rows(S, err)) { b_running_ = false; return -1; }
5431        for (int t = 0; t < S; ++t) b_out_[t] = ((volatile int32_t*) h_out_)[t];
5432        note_nonfinite(S, last_pos_b_);
5433    }
5434    ++windows;
5435    b_running_ = false;
5436    progress_beat();
5437    return 1;
5438}
5439
5440// #879: STRATA_NAN_GUARD=0 turns the guard off (no kernel is recorded; the graphs are captured once, so it is read once)
5441bool Verifier::nan_guard_on() {
5442    static const bool on = [] {
5443        const char* v = std::getenv("STRATA_NAN_GUARD");
5444        return v == nullptr || std::atoi(v) != 0;
5445    }();
5446    return on;
5447}
5448
5449namespace {
5450// STRATA_NAN_INJECT=<n>[,<n>...] (debug): the windows (counted from 1 over the process) the guard reports as non-finite
5451const std::vector<long long>& nan_inject_list() {
5452    static const std::vector<long long> list = [] {
5453        std::vector<long long> v;
5454        if (const char* e = std::getenv("STRATA_NAN_INJECT"))
5455            for (const char* q = e; *q != 0;) {
5456                char* end = nullptr;
5457                const long long n = std::strtoll(q, &end, 10);
5458                if (end == q) break;
5459                if (n > 0) v.push_back(n);
5460                q = *end == ',' ? end + 1 : end;
5461            }
5462        return v;
5463    }();
5464    return list;
5465}
5466std::atomic<long long> g_nf_windows{0};
5467}  // namespace
5468
5469void Verifier::note_nonfinite(int T, const int64_t* pos_b) {
5470    nf_row_ = -1;
5471    nf_pos_ = -1;
5472    nf_mask_ = 0;
5473    if (!nan_guard_on() || h_nf_ == nullptr || !last_stage()) return;   // (a stage without the head checks nothing)
5474    const volatile uint32_t* f = h_nf_;
5475    for (int t = 0; t < T && t < strata::kernels::kVerifyMaxT; ++t)
5476        for (int b = 0; b < strata::kernels::kNonfiniteBlocks; ++b)
5477            if (f[t * strata::kernels::kNonfiniteBlocks + b] != 0) { nf_mask_ |= 1u << t; break; }
5478    const std::vector<long long>& inject = nan_inject_list();
5479    if (!inject.empty()) {
5480        const long long k = g_nf_windows.fetch_add(1) + 1;
5481        if (nf_mask_ == 0 && std::find(inject.begin(), inject.end(), k) != inject.end()) {
5482            nf_mask_ = 1u;
5483            std::fprintf(stderr, "strata verify: STRATA_NAN_INJECT: window %lld reported as non-finite\n", k);
5484        }
5485    }
5486    for (int t = 0; t < T && nf_row_ < 0; ++t)
5487        if ((nf_mask_ >> t) & 1u) nf_row_ = t;
5488    if (nf_row_ >= 0) nf_pos_ = pos_b != nullptr ? pos_b[nf_row_] : last_pos0_ + nf_row_;
5489}
5490
5491bool Verifier::copy_logits(int t, float* host) const {
5492#if defined(STRATA_GPU_METAL)
5493    return strata::metal_engine::window_copy_logits(metal_, t, host);
5494#endif
5495    if (next_ != nullptr) return next_->copy_logits(t, host);   // a layer split: the head is on the last stage
5496    if (head_logits_ == nullptr || host == nullptr || t < 0 || n_vocab_ <= 0) return false;
5497    return cudaMemcpy(host, head_logits_ + (size_t) t * (size_t) n_vocab_, (size_t) n_vocab_ * sizeof(float),
5498                      cudaMemcpyDeviceToHost) == cudaSuccess;
5499}
5500
5501
5502// ================================ PIPELINED WINDOWS (see verify.hpp) ================================
5503//
5504// The window is run()'s, step for step: the same graph, the same staging, the same per-layer service (the PLE rows
5505// gathered while layer 0 is served, the zero-doorbell graph's one flag), the same commit graph.  Only the waits are
5506// split up: the host polls instead of spinning, so it can serve the other stage's window in between.
5507
5508namespace {
5509double now_ms() { return std::chrono::duration<double, std::milli>(Clock::now().time_since_epoch()).count(); }
5510}  // namespace
5511
5512void Verifier::diag_pipelined(std::FILE* f, const char* name) const {
5513    auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; };
5514    auto ev = [](cudaEvent_t e) {
5515        if (e == nullptr) return "none";
5516        const cudaError_t q = cudaEventQuery(e);
5517        return q == cudaSuccess ? "done" : q == cudaErrorNotReady ? "PENDING" : "error";
5518    };
5519    std::fprintf(f, "  %s: %s T=%d pos %lld served %lld/%lld; GPU rang %u, flags served %u A %u B %u; window event %s, "
5520                    "commit event %s (commit launched %d)\n", name, fl_active_ ? "IN FLIGHT" : "idle", last_t_,
5521                 (long long) last_pos0_, (long long) fl_k_, (long long) fl_total_, rd(h_seq_), rd(h_flag_), rd(h_flagA_),
5522                 rd(h_flagB_), ev(ev_done_), ev(ev_commit_), (int) commit_live_);
5523}
5524
5525bool Verifier::capture_all(std::string& err) {
5526    const OnDevice on_device(device_);
5527    if (g_ == nullptr) { err = "verify: capture_all before init"; return false; }
5528    if (remote_opt_ != nullptr) { err = "verify: pipelined windows do not serve --remote-expert-opt"; return false; }
5529    if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }
5530    struct NoEvict {   // every size is wanted at once here: a capture must not free another size's graph
5531        bool& f;
5532        explicit NoEvict(bool& flag) : f(flag) { f = true; }
5533        ~NoEvict() { f = false; }
5534    } no_evict(no_window_eviction_);
5535    // STRATA_SELECT_LONG: both select variants (see select_long_at): pl_launch takes the one its window's context
5536    // needs, and nothing can be captured once pipelined windows are in flight.  Without it only [0]
5537    for (int sl = 0; sl < (select_long_on() ? 2 : 1); ++sl) {
5538        sel_long_ = sl;
5539        for (int T = 1; T <= max_t_; ++T)
5540            if (!capture(T, err)) return false;
5541    }
5542    sel_long_ = 0;
5543    if (!capture_commit(err)) return false;
5544    if ((ev_done_ == nullptr && cudaEventCreateWithFlags(&ev_done_, cudaEventDisableTiming) != cudaSuccess) ||
5545        (ev_commit_ == nullptr && cudaEventCreateWithFlags(&ev_commit_, cudaEventDisableTiming) != cudaSuccess)) {
5546        err = "verify: event create failed";
5547        return false;
5548    }
5549    if (prof_on_ && prof_pin_ == nullptr &&
5550        cudaHostAlloc((void**) &prof_pin_, prof_h_.size() * 8, cudaHostAllocDefault) != cudaSuccess) {
5551        prof_pin_ = nullptr;   // the pipelined windows go unprofiled
5552        cudaGetLastError();
5553    }
5554    pl_ple_rows_.assign((size_t) strata::kernels::kVerifyMaxT * strata::kernels::PLE_N_HEADS, 0u);
5555    return true;
5556}
5557
5558// The host staging of a pipelined window: run()'s (stage_inputs), and its PLE rows from `ple_prev` with their pages
5559// prefetched (they are gathered into the mapped rows when layer 0 is served, as run() does).
5560void Verifier::pl_stage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2]) {
5561    using namespace strata::kernels;
5562    stage_inputs(T, tokens, pos0);
5563    staged_ = false;   // a later run() stages its own window
5564    SessionState& ss = *ss_;
5565    fl_ple_ = ss.ple.ready() && ple_stage();
5566    if (fl_ple_) {
5567        int32_t prev[2] = {ple_prev[0], ple_prev[1]};
5568        for (int t = 0; t < T; ++t) {
5569            ngram_rows(&tokens[t], prev, 1, ss.ple.consts, pl_ple_rows_.data() + t * PLE_N_HEADS);
5570            prev[0] = prev[1];
5571            prev[1] = tokens[t];
5572            ss.ple.table->prefetch_rows(pl_ple_rows_.data() + t * PLE_N_HEADS);
5573        }
5574    }
5575    pl_prev_[0] = ple_prev[0];
5576    pl_prev_[1] = ple_prev[1];
5577}
5578
5579bool Verifier::prestage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2], std::string& err) {
5580    if (fl_active_) { err = "verify: a window is in flight on this verifier"; return false; }
5581    if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; }
5582    if (pl_ple_rows_.empty()) { err = "verify: pipelined window not prepared (capture_all)"; return false; }
5583    const Clock::time_point t0 = Clock::now();
5584    pl_stage(T, tokens, pos0, ple_prev);
5585    pl_prestaged_ = true;
5586    ms_host += ms_since(t0);
5587    return true;
5588}
5589
5590bool Verifier::pl_launch(int T, const int32_t* tokens, int64_t pos0, std::string& err) {
5591    const OnDevice on_device(device_);
5592    if (fl_active_) { err = "verify: a window is already in flight on this verifier"; return false; }
5593    if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }
5594    if (T < 1 || T > max_t_ || T > strata::kernels::kVerifyMaxT) { err = "verify: window size out of range"; return false; }
5595    SessionState& ss = *ss_;
5596    if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; }
5597    const int sl = select_long_on() && pos0 + T >= select_long_at() ? 1 : 0;   // the variant this window's context pays off with
5598    if (exec_[sl][T] == nullptr || commit_exec_ == nullptr || ev_done_ == nullptr || pl_ple_rows_.empty()) {
5599        err = "verify: pipelined window not prepared (capture_all)";
5600        return false;
5601    }
5602    if (pre_launch_ && !pre_launch_(cs_, err)) return false;
5603    const Clock::time_point t0 = Clock::now();
5604    last_batch_ = false;
5605    bool staged = pl_prestaged_ && last_t_ == T && last_pos0_ == pos0;
5606    for (int t = 0; staged && t < T; ++t) staged = last_tokens_[t] == tokens[t];
5607    if (staged && ss.ple.ready() && ple_stage())
5608        staged = pl_prev_[0] == ss.ple_prev[0] && pl_prev_[1] == ss.ple_prev[1];
5609    pl_prestaged_ = false;
5610    if (!staged) pl_stage(T, tokens, pos0, ss.ple_prev);
5611    const int G = groups_[T] > 0 ? groups_[T] : 1;
5612    fl_T_ = T;
5613    fl_k_ = 0;
5614    fl_total_ = (le_ - lb_) * G;
5615    fl_prof_ = prof_on_ && G == 1 && prof_pin_ != nullptr;
5616    if (trace_h_ != nullptr) std::memset(trace_h_, 0, trace_n_ * 8);   // #649: this window's breadcrumbs only
5617    std::atomic_thread_fence(std::memory_order_seq_cst);
5618    trace_ev("WINDOW (pipelined)", -1, -1, pos0 * 16 + T);
5619    ms_host += ms_since(t0);
5620    strata::dispatch::Stats::get().graph_launch(T, ar_on() ? 0 : 1);
5621    const cudaError_t le = cudaGraphLaunch(exec_[sl][T], cs_);
5622    trace_ev("LAUNCHED", -1, -1, (int64_t) le);
5623    if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; }
5624    if (fl_prof_) cudaMemcpyAsync(prof_pin_, prof_, prof_h_.size() * 8, cudaMemcpyDeviceToHost, cs_);
5625    if (cudaEventRecord(ev_done_, cs_) != cudaSuccess) { err = "verify: event record failed"; return false; }
5626    (void) cudaStreamQuery(cs_);   // WDDM: submit now
5627    fl_active_ = true;
5628    fl_since_ms_ = fl_flush_ms_ = fl_launch_ms_ = now_ms();
5629    return true;
5630}
5631
5632int Verifier::service(PoolMultiFn pool, void* user, std::string& err) {
5633    if (!fl_active_) return 1;
5634    if (fl_k_ >= fl_total_) return 1;
5635    // Nothing rang yet and neither the WDDM flush nor the timeout below is due: return before any CUDA call.  The
5636    // pipelined loop asks both stages' windows this millions of times a second while they wait on their doorbells,
5637    // and the device switch (OnDevice: cudaGetDevice and two cudaSetDevice) made that a few driver calls each time:
5638    // 919 million passes before the host stalled inside one of those cudaSetDevice calls with both stages waiting
5639    // on it (0.1.41, Windows, an RTX 3060 + RTX 5070 Ti split).  The same answer as the loop below gives.
5640    if (!ar_on() && *(volatile uint32_t*) h_seq_ < (uint32_t) (fl_k_ + 1)) {
5641        const double now = now_ms();
5642        if (now - fl_flush_ms_ <= 2.0 && now - fl_since_ms_ <= 20000.0) return 0;
5643    }
5644    const OnDevice on_device(device_);
5645    const ModelGeometry& g = *g_;
5646    SessionState& ss = *ss_;
5647    const int T = fl_T_;
5648    // the PLE rows into the mapped staging (layer 1's pre() copies them once flag 1 is up), as run() does at k == 0
5649    auto gather_ple = [&]() -> bool {
5650        if (!fl_ple_) return true;
5651        const Clock::time_point tp = Clock::now();
5652        if (!ss.ple.table->gather_batch(pl_ple_rows_.data(), (size_t) T, h_ple_, err)) return false;
5653        std::atomic_thread_fence(std::memory_order_seq_cst);
5654        strata_store_fence();
5655        ms_host += ms_since(tp);
5656        return true;
5657    };
5658    if (ar_on()) {   // the zero-doorbell graph never rings: it waits only for flag 1 (stage 0's PLE rows).
5659        // Per-window: with a loan in flight (ar_off_) the doorbell graph needs the per-layer service below.
5660        if (!gather_ple()) return -1;
5661        *(volatile uint32_t*) h_flag_ = 1;
5662        fl_k_ = fl_total_;
5663        progress_tick();
5664        return 1;
5665    }
5666    const int G = groups_[T] > 0 ? groups_[T] : 1;
5667    const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T};
5668    while (fl_k_ < fl_total_) {
5669        const int64_t l = lb_ + fl_k_ / G;
5670        const uint32_t want = (uint32_t) (fl_k_ + 1);
5671        if (*(volatile uint32_t*) h_seq_ < want) {
5672            const double now = now_ms();
5673            if (now - fl_flush_ms_ > 2.0) {   // flush WDDM and notice a dead graph, as run() does
5674                fl_flush_ms_ = now;
5675                const cudaError_t q = cudaEventQuery(ev_done_);
5676                if (q != cudaErrorNotReady && *(volatile uint32_t*) h_seq_ < want) {
5677                    trace_ev("NEVER-RANG", fl_k_, l, (int64_t) q);
5678                    err = "verify: layer " + std::to_string(l) + " never rang (" +
5679                          (q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")";
5680                    return -1;
5681                }
5682                (void) cudaStreamQuery(cs_);
5683            }
5684            if (now - fl_since_ms_ > 20000.0) {   // #267: no spin kernel may outlive the engine
5685                trace_ev("TIMEOUT", fl_k_, l, 0);
5686                err = "verify: timed out at layer " + std::to_string(l) + released_note(release_gpu_waits(5000));
5687                return -1;
5688            }
5689            return 0;
5690        }
5691        const Clock::time_point b = Clock::now();
5692        ms_wait += now_ms() - fl_since_ms_;
5693        const int grp = (int) (fl_k_ % G);
5694        cur_layer_ = want - 1;
5695        set_plan_slot(grp);
5696        const int tb = gtb[grp], n = gte[grp] - gtb[grp];
5697        progress_at("verify window (pipelined): the CPU experts of layer", l);
5698        if (pool != nullptr) {
5699            strata::core::latent_xl_current() = h_latxlq_;
5700            strata::core::latent_xlseq_current() = h_xlseq_;
5701        strata::core::latent_act0_current() = m_latact0_;
5702            pool(user, h_x_ + (size_t) tb * g.n_embd, h_ids_ + (size_t) tb * ss.k, n, ss.k,
5703                 h_ymiss_ + (size_t) tb * ss.k * g.n_embd, l);
5704        }
5705        if (g_trace) trace_ev(*(volatile uint32_t*) h_flagA_ == want ? "SERVED" : "SERVED-NO-PLAN-YET", fl_k_, l,
5706                              (int64_t) ms_since(b));
5707        progress_tick();
5708        std::atomic_thread_fence(std::memory_order_seq_cst);
5709        strata_store_fence();
5710        if (*(volatile uint32_t*) h_flagA_ != want) {        // the pool did not publish a plan: an empty one
5711            sink_.counts[0] = 0;
5712            sink_.counts[1] = 0;
5713            sink_.counts[2] = 0;
5714            sink_.start[0] = 0;
5715            sink_.start2[0] = 0;
5716            std::atomic_thread_fence(std::memory_order_seq_cst);
5717            *(volatile uint32_t*) h_flagA_ = want;
5718            raise_flag_b_ordered(want);   // behind any copy still queued from an earlier layer
5719        }
5720        if (g_trace) std::fprintf(stderr, "GATHER-PLE fl_k=%lld fl_ple=%d\n", (long long) fl_k_, (int) fl_ple_);
5721        if (fl_k_ == 0 && !gather_ple()) return -1;
5722        *(volatile uint32_t*) h_flag_ = want;
5723        if (g_trace) std::fprintf(stderr, "FLAG-SET want=%u seq=%u fl_k=%lld\n", (unsigned) want, *(volatile uint32_t*) h_seq_, (long long) fl_k_);
5724        ++fl_k_;
5725        ms_pool += ms_since(b);
5726        fl_since_ms_ = fl_flush_ms_ = now_ms();
5727    }
5728    return 1;
5729}
5730
5731bool Verifier::done(std::string& err) {
5732    if (!fl_active_ || fl_k_ < fl_total_) return false;
5733    const OnDevice on_device(device_);
5734    const cudaError_t q = cudaEventQuery(ev_done_);
5735    if (q == cudaErrorNotReady) {
5736        const double now = now_ms();
5737        if (now - fl_flush_ms_ > 2.0) { fl_flush_ms_ = now; (void) cudaStreamQuery(cs_); }
5738        if (now - fl_since_ms_ > 20000.0) {   // every layer served, and the graph still runs: #267 as above
5739            err = "verify: the window never finished" + released_note(release_gpu_waits(5000));
5740        }
5741        return false;
5742    }
5743    if (q != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(q); return false; }
5744    if (copy_used_) {   // no host function of this window may raise flag B in the next one
5745        if (cudaStreamQuery(copy_) == cudaErrorNotReady) return false;
5746        copy_used_ = false;
5747    }
5748    return true;
5749}
5750
5751bool Verifier::pl_finish(int32_t* out, std::string& err) {
5752    using namespace strata::kernels;
5753    const OnDevice on_device(device_);
5754    const ModelGeometry& g = *g_;
5755    fl_active_ = false;
5756    if (fl_prof_) accumulate_profile(prof_pin_);
5757    ++windows;
5758    trace_ev("DONE (pipelined)", -1, -1, (int64_t) (now_ms() - fl_launch_ms_));
5759    if (le_ < g.n_layers) return true;   // an earlier stage: the hand-off is written
5760    const int T = fl_T_;
5761    const bool sampled = !sampling_.greedy && sampling_.temperature > 0.0f;
5762    if (head_sampling_ && (sampled || hist_d_ != nullptr || sampling_.logit_bias != nullptr)) {   // run()'s host-side sampling, Philox(seed, pos0 + t)
5763        SamplerParams sp = sampling_;
5764        sp.counter = (uint64_t) last_pos0_;
5765        sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_);
5766        if (cudaStreamSynchronize(cs_) != cudaSuccess) {
5767            err = "verify: the head sampling failed";
5768            return false;
5769        }
5770    }
5771    if (out != nullptr)
5772        for (int t = 0; t < T; ++t) out[t] = ((volatile int32_t*) h_out_)[t];
5773    note_nonfinite(T, nullptr);
5774    progress_beat();
5775    return true;
5776}
5777
5778bool Verifier::pl_commit_async(int n_keep, std::string& err) {
5779    const OnDevice on_device(device_);
5780    if (n_keep < 1 || n_keep > last_t_) { err = "verify: commit count out of range"; return false; }
5781    if (commit_exec_ == nullptr || ev_commit_ == nullptr) { err = "verify: pipelined commit not prepared"; return false; }
5782    const Clock::time_point t0 = Clock::now();
5783    if (commit_live_) {   // its graph reads the words below when it starts: the previous one has (a window ago)
5784        cudaError_t q;
5785        while ((q = cudaEventQuery(ev_commit_)) == cudaErrorNotReady) strata_cpu_pause();
5786        if (q != cudaSuccess) { err = std::string("verify: commit: ") + cudaGetErrorString(q); return false; }
5787    }
5788    h_commit_[0] = n_keep;
5789    h_commit_[1] = n_keep - 1;
5790    for (int t = 0; t < max_t_; ++t) h_commit_[2 + t] = t < n_keep ? (int32_t) (last_pos0_ + t) : -1;
5791    std::atomic_thread_fence(std::memory_order_seq_cst);
5792    const cudaError_t le = cudaGraphLaunch(commit_exec_, cs_);
5793    if (le != cudaSuccess) { err = std::string("verify: commit launch: ") + cudaGetErrorString(le); return false; }
5794    if (cudaEventRecord(ev_commit_, cs_) != cudaSuccess) { err = "verify: event record failed"; return false; }
5795    (void) cudaStreamQuery(cs_);
5796    commit_live_ = true;
5797    if (ple_stage())
5798        for (int t = 0; t < n_keep; ++t) {
5799            ss_->ple_prev[0] = ss_->ple_prev[1];
5800            ss_->ple_prev[1] = last_tokens_[t];
5801        }
5802    ms_commit += ms_since(t0);
5803    return true;
5804}
5805
5806void Verifier::absorb_stats(Verifier& o) {
5807    ms_wait += o.ms_wait; ms_pool += o.ms_pool; ms_host += o.ms_host; ms_commit += o.ms_commit;
5808    windows += o.windows;
5809    o.ms_wait = o.ms_pool = o.ms_host = o.ms_commit = 0;
5810    o.windows = 0;
5811    for (int k = 0; k < 2; ++k)
5812        for (int i = 0; i < kProfPer; ++i) { prof_sum_[k][i] += o.prof_sum_[k][i]; o.prof_sum_[k][i] = 0; }
5813    prof_windows_ += o.prof_windows_;
5814    o.prof_windows_ = 0;
5815}
5816
5817}  // namespace strata::core