okami.mom/strata

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

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

main
236.7 KiB4486 linesraw
1#include "b60_layout_state.hpp"
2// src/core/verify.cpp - see include/strata/core/verify.hpp.
3#define DPCT_PROFILING_ENABLED
4#include <sycl/sycl.hpp>
5#include <dpct/dpct.hpp>
6#include "strata/sycl_queue.hpp"
7#include "strata/kprof.hpp"
8#include "strata/core/verify.hpp"
9#include "strata/kernels/dflash2.hpp"
10#include "strata/core/remote_expert_opt.hpp"
11#include "strata/core/dma_batch.hpp"
12#include "strata/workload_trace.hpp"
13#if defined(_WIN32)
14#include <intrin.h>
15#endif
16
17#include "strata/core/native_head.hpp"
18#include "strata/core/on_device.hpp"
19#include "strata/core/peer_experts.hpp"
20#include "strata/kernels/iq_kernels.hpp"
21#include "strata/kernels/expert_staging.hpp"
22#include "strata/kernels/cpu/expert_layout.hpp"
23#include "strata/kernels/cpu/hadamard.hpp"
24#include "strata/kernels/bf16_gemv.hpp"
25#include "strata/kernels/native_router.hpp"
26#include "strata/kernels/native_moe.hpp"
27#include "strata/kernels/cpu/expert.hpp"
28#include "strata/kernels/elementwise.hpp"
29#include "strata/kernels/fused_gr.hpp"
30#include "strata/kernels/cvec.hpp"
31#include "strata/kernels/gr.hpp"
32#include "strata/kernels/kv_q4.hpp"
33#include "strata/kernels/kv_q8.hpp"
34#include "strata/kernels/native_mmvq.hpp"
35#include "strata/kernels/native_qsa.hpp"
36#include "strata/kernels/native_qsa_indexer.hpp"
37#include "strata/kernels/native_rope.hpp"
38#include "strata/kernels/ngram.hpp"
39#include "strata/kernels/ple.hpp"
40#include "strata/kernels/qsa.hpp"
41#include "strata/kernels/qsa_decode_attn.hpp"
42#include "strata/kernels/qsa_select.hpp"
43#include "strata/kernels/quantize_act.hpp"
44#include "strata/kernels/rope.hpp"
45#include "strata/kernels/s2_expert_grouped.hpp"
46#include "strata/kernels/sampler.hpp"
47#include "strata/core/progress.hpp"
48#include "strata/kernels/shared_expert.hpp"
49#include "strata/kernels/verify_kernels.hpp"
50
51#include <algorithm>
52#include <atomic>
53#include <filesystem>
54#include <map>
55#include <memory>
56#include <string>
57#include <thread>
58#include <vector>
59#include <chrono>
60#include <cmath>
61#include <cstdio>
62#include <cstdlib>
63#include <cstring>
64#include <exception>
65#include <immintrin.h>
66#if defined(__linux__)
67#include <pthread.h>
68#include <sched.h>
69#endif
70
71namespace strata::core {
72namespace {
73bool sycl_mirror_adapt() {
74    static const bool enabled = [] {
75        const char* v = std::getenv("STRATA_SYCL_MIRROR_ADAPT");
76        return v && v[0] == '1';
77    }();
78    return enabled;
79}
80class ExpertRouteCount;
81void count_expert_routes(sycl::queue* q, const int32_t* ids, int entries,
82                         int layer, int experts, uint32_t* counts) {
83    q->parallel_for<ExpertRouteCount>(
84        sycl::nd_range<1>((entries + 31) / 32 * 32, 32),
85        [=](sycl::nd_item<1> item) [[sycl::reqd_sub_group_size(32)]] {
86            const int i = (int)item.get_global_id(0);
87            if (i < entries) {
88                const int expert = ids[i];
89                if (expert >= 0 && expert < experts) {
90                    sycl::atomic_ref<uint32_t, sycl::memory_order::relaxed,
91                        sycl::memory_scope::device, sycl::access::address_space::global_space>
92                        count(counts[layer * experts + expert]);
93                    count.fetch_add(1);
94                }
95            }
96        });
97}
98
99#ifdef STRATA_SYCL_WORKLOAD_TRACE
100// Diagnostic graph copies preserve the actual per-layer plan before its shared
101// scratch is reused. CPU reads them only after the existing end-window wait.
102struct RoutingAudit {
103    int32_t* snapshots = nullptr;
104    FILE* output = nullptr;
105    int64_t words = 0, layers = 0;
106    sycl::queue* queue = nullptr;
107    RoutingAudit(int64_t nwords, int64_t nlayers, sycl::queue* stream, const char* path)
108        : words(nwords), layers(nlayers), queue(stream) {
109        output = std::fopen(path, "a");
110        if (!output) throw std::runtime_error("routing audit output unavailable");
111        snapshots = sycl::malloc_host<int32_t>((size_t)words * layers * 2, *queue);
112        if (!snapshots) { std::fclose(output); output = nullptr; throw std::bad_alloc(); }
113        std::memset(snapshots, 0, (size_t)words * layers * 2 * sizeof(int32_t));
114    }
115    ~RoutingAudit() {
116        if (snapshots) { try { sycl::free(snapshots, *queue); } catch (...) {} }
117        if (output) std::fclose(output);
118    }
119    int32_t* slot(int64_t layer, int group) { return snapshots + (size_t)(layer * 2 + group) * words; }
120};
121std::map<const Verifier*, std::unique_ptr<RoutingAudit>> routing_audits;
122#endif
123
124constexpr float EPS = 1e-6f;
125using Clock = std::chrono::steady_clock;
126double ms_since(Clock::time_point t) { return std::chrono::duration<double, std::milli>(Clock::now() - t).count(); }
127const bool g_dbg = std::getenv("STRATA_VERIFY_DEBUG") != nullptr;
128inline bool g_lfuse() { static const bool on = [] { const char* v = std::getenv("STRATA_LFUSE"); return v != nullptr && v[0] == '1'; }(); return on; }
129inline bool g_lfuse_gate() { static const bool on = [] { const char* v = std::getenv("STRATA_LFUSE_GATE"); return v == nullptr || v[0] != '0'; }(); return on; }
130inline bool g_lfuse_pair() { static const bool on = [] { const char* v = std::getenv("STRATA_LFUSE_PAIR"); return v == nullptr || v[0] != '0'; }(); return on; }
131inline bool g_qdedup() { static const bool on = [] { const char* v = std::getenv("STRATA_VERIFY_QDEDUP"); return v != nullptr && std::atoi(v) != 0; }(); return on; }
132// S26 STRATA_QFUSE=1: activation q8_1 images written by their producers (the GDN output norm) - the same bytes
133inline bool g_qfuse() { static const bool on = [] { const char* v = std::getenv("STRATA_QFUSE"); return v != nullptr && std::atoi(v) != 0; }(); return on; }
134#define VDBG(...) do { if (g_dbg) { std::fprintf(stderr, "verify dbg: " __VA_ARGS__); std::fflush(stderr); } } while (0)
135
136struct Bump {
137    uint8_t* base = nullptr;
138    uint64_t used = 0;
139    template <typename T> T* take(uint64_t n) {
140        T* p = base ? (T*) (base + used) : nullptr;
141        used += (n * sizeof(T) + 255) & ~255ull;
142        return p;
143    }
144};
145
146// #649 (HIP, opt-in A/Bs for the gfx1030 verify timeouts; CUDA never reads them)
147//   STRATA_VERIFY_COHERENT=1  the handshake words and rows in explicitly coherent (fine-grained) host memory
148//   STRATA_DOORBELL_STORE=1   the GPU stores each step's ring instead of read-modify-writing it over PCIe
149bool env_on(const char* name) {
150    const char* e = std::getenv(name);
151    return e != nullptr && e[0] != 0 && e[0] != '0';
152}
153
154// STRATA_LAYER_HASH_FILE=<path> (debug, off by default): after every CPU-expert service the host writes one text line
155// "window layer rows xhash idshash whash yhash" (FNV-1a over the host-visible payload the GPU published for the CPU
156// experts - the activation rows, the routed ids, the weights - and over the CPU experts' output rows).  Two runs of the
157// same teacher-forced window are compared line by line: the first line that differs names the first layer whose input
158// differs (CLEAN-6.0).  The activation rows are published only when a routed expert is not resident, or with
159// STRATA_DOORBELL_CHECK=1 for every layer.
160std::FILE* layer_hash_file() {
161    static std::FILE* f = [] {
162        const char* p = std::getenv("STRATA_LAYER_HASH_FILE");
163        return p != nullptr && p[0] != 0 ? std::fopen(p, "w") : nullptr;
164    }();
165    return f;
166}
167uint64_t layer_hash_fnv(const void* p, size_t bytes) {
168    uint64_t h = 1469598103934665603ull;
169    const auto* b = static_cast<const uint8_t*>(p);
170    for (size_t i = 0; i < bytes; ++i) h = (h ^ b[i]) * 1099511628211ull;
171    return h;
172}
173
174// STRATA_STATE_HASH_FILE=<path> (debug, off by default): before every window the host waits for the queue and writes
175// "window gdn <ordinal> <fnv>" for every GDN layer's recurrent+conv state and "window qsa <ordinal> <fnv>" for the
176// int8 K/V codes and scales of the pages the window's position already filled (page table taken as the identity),
177// so two runs can be compared at the first window to see whether the prompt path left the same state (CLEAN-6.0).
178std::FILE* state_hash_file() {
179    static std::FILE* f = [] {
180        const char* p = std::getenv("STRATA_STATE_HASH_FILE");
181        return p != nullptr && p[0] != 0 ? std::fopen(p, "w") : nullptr;
182    }();
183    return f;
184}
185#if defined(STRATA_USE_HIP)
186const bool g_coherent = env_on("STRATA_VERIFY_COHERENT");
187const bool g_doorbell_store = env_on("STRATA_DOORBELL_STORE");
188#endif
189const bool g_trace = env_on("STRATA_VERIFY_TRACE");
190// STRATA_VERIFY_STEPPED=1 (opt-in, Arc A-series): see Verifier::step_hook_.  STRATA_VERIFY_PIPE=0 serves without the
191// helper thread (serial segments) for A/B runs.
192const bool g_stepped = env_on("STRATA_VERIFY_STEPPED");
193
194// STRATA_PIPE_HELPER_SIBLING=1 (opt-in, stepped mode): the host thread is pinned to one logical CPU and a std::thread
195// inherits that mask, so the pipelined serve's pool helper and the main thread's flag-A wait share one CPU and the
196// early segment is mostly submitted only after the pool finished.  With this set the helper runs on the host CPU's SMT
197// sibling instead.  -1: keep the inherited mask (unset, not pinned to one CPU, or no sibling).
198int pipe_helper_cpu() {
199#if defined(__linux__)
200    static const int cpu = [] {
201        if (!env_on("STRATA_PIPE_HELPER_SIBLING")) return -1;
202        cpu_set_t s;
203        CPU_ZERO(&s);
204        if (pthread_getaffinity_np(pthread_self(), sizeof s, &s) != 0 || CPU_COUNT(&s) != 1) {
205            std::fprintf(stderr, "strata verify: STRATA_PIPE_HELPER_SIBLING: host thread is not pinned to one CPU; unchanged\n");
206            return -1;
207        }
208        int host = -1;
209        for (int c = 0; c < CPU_SETSIZE && host < 0; ++c)
210            if (CPU_ISSET(c, &s)) host = c;
211        char path[96];
212        std::snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", host);
213        int sib = -1;
214        if (FILE* f = std::fopen(path, "r")) {
215            char buf[128] = {};
216            if (std::fgets(buf, sizeof buf, f) != nullptr) {
217                for (char* p = buf; *p != 0 && sib < 0;) {   // "0,8" or "0-1"
218                    char* end = nullptr;
219                    const long a = std::strtol(p, &end, 10);
220                    if (end == p) break;
221                    long b = a;
222                    if (*end == '-') { p = end + 1; b = std::strtol(p, &end, 10); }
223                    for (long c = a; c <= b && sib < 0; ++c)
224                        if (c != host) sib = (int) c;
225                    p = (*end == ',') ? end + 1 : end;
226                    if (*end != ',') break;
227                }
228            }
229            std::fclose(f);
230        }
231        std::fprintf(stderr, "strata verify: pipelined pool helper on CPU %d (host thread CPU %d)%s\n", sib, host,
232                     sib < 0 ? ": no SMT sibling, unchanged" : "");
233        return sib;
234    }();
235    return cpu;
236#else
237    return -1;
238#endif
239}
240const bool g_no_multi_gr = env_on("STRATA_NO_MULTI_GR");   // #783 PR-g: per-token GR reads/writes and generic-T kernels again
241const bool g_no_batch_kv = env_on("STRATA_NO_BATCH_KV_STEP");   // #783 PR-d: per-token K/V and indexer appends again
242
243// The shared expert runs on its own stream, forked off and joined back per layer (`sh_fork` in record_window).  The
244// overlap pays off on CUDA, where it was added (cfd3b72).  On HIP a cross-stream event dependency costs more than the
245// shared expert takes to run, so there the fork starts off: same binary, same 48,067-token prompt, three runs each on a
246// 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
247// profiler turns the fork off to time the stages, so a profiled run never showed that.  #816 reports the same fall on a
248// gfx1030 (RX 6800, Windows, 42.5 -> 56.4 t/s).  STRATA_SH_STREAM overrides either default: `=1` forks, `=0` does not.
249// Strix Halo (gfx1151, unified memory) is the exception: the fork pays there (+1.8% UD-IQ4_XS, +6.7% UD-Q4_K_XL decode
250// at 8K, ids identical), so the gfx1151 arch table sets STRATA_SH_STREAM=1.  Read on first use, after that table ran.
251bool sh_stream_on() {
252    static const bool on = [] {
253        if (const char* v = std::getenv("STRATA_SH_STREAM")) return v[0] != '0';
254#if defined(STRATA_USE_HIP)
255        return false;
256#else
257        return true;
258#endif
259    }();
260    return on;
261}
262
263// A one-token window always keeps its token, so its graph advances the sequence state itself (the GDN conv history
264// and recurrence state) and Verifier::commit launches no commit graph after it (eddoursul's fork, F7).  CUDA only:
265// HIP keeps the commit graph after every window (STRATA_ONE_TOKEN_COMMIT=0 does too).
266// The head's hyper-connection read for the window's tokens in one launch set (CUDA; HIP keeps gr_read per token;
267// STRATA_HEAD_MIX_MULTI=0 does too): bitwise the same sums.
268bool head_mix_multi_enabled() {
269#if defined(STRATA_USE_HIP)
270    return false;
271#else
272    static const bool on = [] {
273        const char* v = std::getenv("STRATA_HEAD_MIX_MULTI");
274        return v == nullptr || std::atoi(v) != 0;
275    }();
276    return on;
277#endif
278}
279
280bool one_token_self_commit() {
281#if defined(STRATA_USE_HIP)
282    return false;
283#else
284    static const bool on = [] {
285        const char* v = std::getenv("STRATA_ONE_TOKEN_COMMIT");
286        return v == nullptr || std::atoi(v) != 0;
287    }();
288    return on;
289#endif
290}
291
292// True when the GPU runs under the i915 kernel driver (Arc Alchemist: A310-A770), read from sysfs.
293bool intel_i915_gpu() { return strata::intel_gpu_driver() == "i915"; }
294
295// How long the host waits for a layer's doorbell before it gives the window up (#267).  20 s by default; the first
296// window of a run on a card that JIT-compiles its kernels (no AOT: an Arc A750 needs FP64 emulation) can take longer
297// to start, so STRATA_RING_TIMEOUT_S raises it.
298std::chrono::seconds strata_ring_timeout() {
299    static const long s = [] {
300        const char* v = std::getenv("STRATA_RING_TIMEOUT_S");
301        const long n = v ? std::atol(v) : 20;
302        return n >= 1 ? n : 20L;
303    }();
304    return std::chrono::seconds(s);
305}
306
307// STRATA_VERIFY_STEPPED: no kernel of the window reads a host store while it runs, and no host reads a kernel's store
308// while it runs - every flag is raised before the segment that waits on it is submitted, and the host reads a
309// segment's rings and payload after the segment drained. So the window's mapped buffers need no uncached host memory
310// (sycl_queue.hpp) and its doorbell publishes need no uncached payload stores (sycl_doorbell.hpp). Both cost the
311// window time on an A770 (xe, Coder IQ1_M, 8K prompt): the GPU waited ~70 ms a window for the CPU with them, ~42
312// without; decode 22.8-25.0 -> 26.9-28.9 tok/s. STRATA_VERIFY_HOST_UNCACHED=1 keeps both.
313bool window_host_uncached() {
314    static const bool v = !g_stepped || env_on("STRATA_VERIFY_HOST_UNCACHED");
315    return v;
316}
317
318bool mapped(size_t bytes, void **h, void **d) try {
319    /*
320    DPCT1048: The original value cudaHostAllocMapped is not meaningful in the
321    migrated code and was removed or replaced with 0. You may need to check the
322    migrated code.
323    */
324    // polled by the window's kernels: uncached host memory (sycl_queue.hpp); a buffer only read or written between
325    // kernels (the stepped window's payload) is ordinary host USM
326    if (DPCT_CHECK_ERROR(*h = window_host_uncached() ? strata::host_malloc_polled(bytes, dpct::get_in_order_queue())
327                                     : sycl::malloc_host(bytes, dpct::get_in_order_queue())) !=
328        0 || *h == nullptr) return false;
329    std::memset(*h, 0, bytes);
330    return DPCT_CHECK_ERROR(*d = (void *)*h) == 0;
331}
332catch (sycl::exception const &exc) {
333  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
334            << ", line:" << __LINE__ << std::endl;
335  std::exit(1);
336}
337
338strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { return qsa_shapes(g); }
339
340const WeightRef* need(const LayerView& v, const char* suffix, std::string& err) {
341    const WeightRef* r = v.get(suffix);
342    if (r == nullptr && err.empty()) err = v.name(suffix) + " is missing";
343    return r;
344}
345
346bool native_of(const WeightRef* w, const std::string& name, std::string& err) {
347    if (w == nullptr) return false;
348    if (w->native_data == nullptr) {
349        err = "verify: " + name + " is not served natively (run with --native)";
350        return false;
351    }
352    return true;
353}
354
355}  // namespace
356
357namespace {
358std::atomic<const Verifier*> g_diag_verifier{nullptr};
359void diag_active_verifier(std::FILE* f) {
360    if (const Verifier* v = g_diag_verifier.load()) v->diag(f);
361}
362// #267: every live verifier (a layer split has one per stage), for the release before the engine ends
363constexpr int kLiveMax = 16;
364std::atomic<Verifier*> g_live[kLiveMax];
365void release_live_verifiers(std::FILE* f) {
366    for (auto& slot : g_live)
367        if (Verifier* v = slot.load()) {
368            const Clock::time_point t0 = Clock::now();
369            const bool done = v->release_gpu_waits(5000);
370            if (f != nullptr)
371                std::fprintf(f, "strata: released the verify window's GPU waits (#267): the GPU %s\n",
372                             done ? ("finished in " + std::to_string((long long) ms_since(t0)) + " ms").c_str()
373                                  : "did not finish within 5 s");
374        }
375    if (f != nullptr) std::fflush(f);
376}
377// #649: the host side of STRATA_VERIFY_TRACE - a ring of the last kTraceN handshake events of every verifier
378struct TraceEv {
379    int64_t t_ns;
380    const void* who;
381    int64_t window, step, layer, aux;
382    uint32_t seq, flag, a, b;
383    const char* what;
384};
385constexpr uint64_t kTraceN = 4096;
386TraceEv g_trace_ring[kTraceN];
387std::atomic<uint64_t> g_trace_next{0};
388int64_t trace_now_ns() {
389    return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count();
390}
391std::string released_note(bool drained) {
392    return drained ? "; its GPU waits were released and the GPU finished (#267)"
393                   : "; its GPU waits were released but the GPU did not finish within 5 s (#267)";
394}
395// #267 test hook: STRATA_TEST_VERIFY_STALL=N withholds the last layer's flag in the N-th window (1-based), so the
396// GPU spins on a flag nobody raises - the bounded window wait and the release are then what ends it.  Unset: never.
397const int64_t g_test_stall = [] {
398    const char* e = std::getenv("STRATA_TEST_VERIFY_STALL");
399    return e != nullptr ? (int64_t) std::atoll(e) : (int64_t) 0;
400}();
401}  // namespace
402
403bool Verifier::release_gpu_waits(int timeout_ms) try {
404    released_.store(true);
405    trace_ev("RELEASE", -1, -1, timeout_ms);
406    // the words the spin kernels read (wait_flag_ge, wait_flag_ge_or) are mapped host memory, so a store here
407    // reaches them with no API call; UINT32_MAX is past every ring.  (E-6's skip words are device memory, but
408    // wait_flag_ge_or also returns on its flag.)  A host function raising flag B later only raises.
409    for (uint32_t* p : {h_flag_, h_flagA_, h_flagB_})
410        if (p != nullptr) *(volatile uint32_t*) p = UINT32_MAX;
411    std::atomic_thread_fence(std::memory_order_seq_cst);
412    _mm_sfence();
413    const OnDevice on_device(device_);
414    const Clock::time_point t0 = Clock::now();
415    // SYCL port: no cudaStreamQuery; a queue with nothing left to run reports ext_oneapi_empty()
416    for (dpct::queue_ptr q : {cs_, copy_}) {
417        if (q == nullptr) continue;
418        while (!q->ext_oneapi_empty()) {
419            if (ms_since(t0) > timeout_ms) {
420                trace_ev("RELEASE-NOT-DRAINED", -1, -1, (int64_t) ms_since(t0));
421                return false;
422            }
423            std::this_thread::sleep_for(std::chrono::milliseconds(1));
424        }
425    }
426    trace_ev("RELEASE-DRAINED", -1, -1, (int64_t) ms_since(t0));   // aux: ms the GPU took to finish once released
427    return true;
428} catch (...) {
429    return false;   // the runtime may already be tearing down (the watchdog's path ends the engine)
430}
431
432void Verifier::trace_ev(const char* what, int64_t step, int64_t layer, int64_t aux) const {
433    if (!g_trace) return;
434    auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; };
435    TraceEv& e = g_trace_ring[g_trace_next.fetch_add(1) % kTraceN];
436    e = {trace_now_ns(), this, windows, step, layer, aux, rd(h_seq_), rd(h_flag_), rd(h_flagA_), rd(h_flagB_), what};
437}
438
439void Verifier::trace_dump(std::FILE* f) const {
440    if (!g_trace || f == nullptr) return;
441    static const char* names[kProfPer] = {"pre", "hc-read0", "qkv gemv", "conv", "ab", "z", "rec", "kv-idx",
442                                          "k/v rope", "kv append", "q", "scores+topk", "kv-resolve", "attention",
443                                          "gate", "", "out-proj", "router+ring", "shared", "waitA", "VRAM hits", "waitB",
444                                          "PCIe grp", "waitCPU", "combine", "", "head", "", "", "", "", "", ""};
445    const uint64_t end = g_trace_next.load();
446    const uint64_t n = end < 160 ? end : 160;
447    std::fprintf(f, "strata verify trace (#649): the last %llu handshake events (host clock, us before the last; "
448                    "words: seq = GPU rang, flag = CPU served, A = plan, B = copies)\n", (unsigned long long) n);
449    const int64_t t_last = n ? g_trace_ring[(end - 1) % kTraceN].t_ns : 0;
450    for (uint64_t i = end - n; i < end; ++i) {
451        const TraceEv& e = g_trace_ring[i % kTraceN];
452        if (e.what == nullptr) continue;
453        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",
454                     (double) (t_last - e.t_ns) / 1000.0, e.what, e.who, (long long) e.window, (long long) e.step,
455                     (long long) e.layer, (long long) e.aux, e.seq, e.flag, e.a, e.b);
456    }
457    if (trace_h_ == nullptr || g_ == nullptr) return;
458    // the breadcrumbs: every stamp point the GPU passed in this window (ns of the GPU clock after the window's first)
459    unsigned long long t0 = ~0ull;
460    for (size_t i = 0; i < trace_n_; ++i) {
461        const unsigned long long t = *(const volatile unsigned long long*) (trace_h_ + i);
462        if (t != 0 && t < t0) t0 = t;
463    }
464    if (t0 == ~0ull) {
465        std::fprintf(f, "strata verify trace: no GPU breadcrumb in this window (the GPU never started it)\n");
466        return;
467    }
468    int64_t last_l = -1;
469    for (int64_t l = 0; l <= g_->n_layers; ++l)
470        for (int i = 0; i < kProfPer; ++i)
471            for (int grp = 0; grp < 2; ++grp)
472                if (trace_h_[(size_t) ((l * kProfPer + i) * 2 + grp)] != 0) last_l = l;
473    std::fprintf(f, "strata verify trace: GPU breadcrumbs (us after the window's first), the GPU got as far as layer "
474                    "%lld:\n", (long long) last_l);
475    for (int64_t l = std::max<int64_t>(0, last_l - 2); l <= std::min<int64_t>(g_->n_layers, last_l + 1); ++l)
476        for (int grp = 0; grp < 2; ++grp) {
477            std::string line;
478            char b[64];
479            for (int i = 0; i < kProfPer; ++i) {
480                const unsigned long long t = trace_h_[(size_t) ((l * kProfPer + i) * 2 + grp)];
481                if (t == 0) continue;
482                std::snprintf(b, sizeof b, " %s(%d)=%.1f", names[i], i, (double) (t - t0) / 1000.0);
483                line += b;
484            }
485            if (!line.empty())
486                std::fprintf(f, "  layer %lld group %d:%s\n", (long long) l, grp, line.c_str());
487        }
488    std::fflush(f);
489}
490
491void Verifier::diag(std::FILE* f) const {
492    auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; };
493    // #251: outside a verify stage these are the LAST window's numbers (it finished), not the stalled work's
494    const char* where = progress().where.load();
495    const bool current = where != nullptr && std::strncmp(where, "verify window", 13) == 0;
496    std::fprintf(f, "  verify window%s: %d tokens at position %lld, host at layer step %u; the GPU rang %u; flags: "
497                    "served %u, plan (A) %u, copies (B) %u\n", current ? "" : " (last window, not the current stage)",
498                 last_t_, (long long) last_pos0_, cur_layer_ + 1, rd(h_seq_), rd(h_flag_), rd(h_flagA_), rd(h_flagB_));
499    trace_dump(f);   // #649: STRATA_VERIFY_TRACE=1 only
500}
501
502Verifier::~Verifier() try {
503    // SYCL port: at process exit the Level Zero context can already be gone (serve mode's end), and a destructor
504    // that throws aborts the process (exit 139); the waits and frees below are best-effort then.
505    const Verifier* self = this;
506    g_diag_verifier.compare_exchange_strong(self, nullptr);
507    for (auto& slot : g_live) {
508        Verifier* me = this;
509        slot.compare_exchange_strong(me, nullptr);
510    }
511    if (cs_) cs_->wait();
512    if (slot_hist_d_ != nullptr && cs_) { try { sycl::free(slot_hist_d_, *cs_); } catch (...) {} slot_hist_d_ = nullptr; }
513    if (sh_cs_) sh_cs_->wait();
514    for (auto& e : exec_)
515        if (e) delete (e);
516    for (auto& e : exec_nr_)
517        if (e) delete (e);
518    for (auto& v : seg_)
519        for (auto* e : v)
520            if (e) delete e;
521    if (commit_exec_) delete (commit_exec_);
522#ifdef STRATA_SYCL_WORKLOAD_TRACE
523    routing_audits.erase(this);
524#endif
525    if (expert_usage_counts_d_) sycl::free(expert_usage_counts_d_, *cs_);
526    for (auto& kv : exec_bm_)
527        if (kv.second) delete (kv.second);
528    for (auto& kv : commit_bm_)
529        if (kv.second) delete (kv.second);
530    if (arena_b_) sycl::free(arena_b_, dpct::get_in_order_queue());
531    if (h_commitb_) sycl::free(h_commitb_, dpct::get_in_order_queue());
532    if (qcnt_) sycl::free(qcnt_, dpct::get_in_order_queue());
533    // (a verifier whose init stopped before it made its own queues still holds the process's default queue in all three (cs_, sh_cs_, copy_): that one is never ours to destroy -
534    // destroying it took the next verifier's wait down with a SIGSEGV in urQueueFinish when a start was refused for lack of VRAM)
535    if (cs_ && cs_ != ext_stream_ && cs_ != &dpct::get_in_order_queue()) dpct::get_current_device().destroy_queue(
536        cs_); // set_stream: the stage's stream, shared, not ours
537    if (sh_cs_ && sh_cs_ != cs_ && sh_cs_ != &dpct::get_in_order_queue()) dpct::get_current_device().destroy_queue(sh_cs_);
538    if (copy_) { copy_->wait(); if (copy_ != &dpct::get_in_order_queue()) dpct::get_current_device().destroy_queue(copy_); }   // (the default one when init never made the copy stream)
539    if (commit_done_) dpct::destroy_event(commit_done_);
540    if (ev_done_) dpct::destroy_event(ev_done_);
541    if (ev_commit_) dpct::destroy_event(ev_commit_);
542    if (prof_pin_) sycl::free(prof_pin_, dpct::get_in_order_queue());
543    if (ev_fork_) dpct::destroy_event(ev_fork_);
544    if (ev_join_) dpct::destroy_event(ev_join_);
545    if (tap_dev_) sycl::free(tap_dev_, dpct::get_in_order_queue());
546    if (arena_) sycl::free(arena_, dpct::get_in_order_queue());
547    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_,
548                     h_flagA_, h_plan_, h_flagB_, h_plan_err_};
549    for (void* h : hosts)
550        if (h) strata::host_free_polled(h, dpct::get_in_order_queue());
551} catch (...) {
552}
553
554
555bool Verifier::init(const WeightTable &wt, const ModelGeometry &g,
556                    SessionState &ss, const VerifyHits &hits,
557                    const NativeHead *head, int max_t, std::string &err) try {
558    g_diag_verifier.store(this);
559    diag_verify_fn().store(&diag_active_verifier);
560    for (auto& slot : g_live) {
561        Verifier* none = nullptr;
562        if (slot.load() == this || slot.compare_exchange_strong(none, this)) break;
563    }
564    release_gpu_fn().store(&release_live_verifiers);
565    device_ = dpct::get_current_device_id(); // a layer split's stage on another
566                                             // GPU: its streams, graphs and
567                                             // buffers live there
568    strata::kernels::fused_gr_check();   // once per card: which bitwise-equal hyper-connection read runs there
569    wt_ = &wt;
570    g_ = &g;
571    ss_ = &ss;
572    hits_ = hits;
573    head_ = head;
574    max_t_ = max_t;
575    sampling_.greedy = true;      // a fresh verifier samples greedily until set_sampling says otherwise
576    sampling_.temperature = 0.0f;
577    if (max_t < 2 || max_t > strata::kernels::kVerifyMaxT || max_t > strata::kernels::cpu::MAXT) {
578        err = "verify: the window must hold 2.." + std::to_string(strata::kernels::kVerifyMaxT) + " tokens";
579        return false;
580    }
581    if (hits.d_res == nullptr || hits.cache_base == nullptr || hits.blob <= 0) {
582        err = "verify: needs the profile-filled VRAM expert tier (--expert-profile and --expert-cache); with "
583              "--expert-cache auto, no VRAM was left for it - the 'no VRAM is left for the expert cache' line above "
584              "says how much is short and what makes room (a smaller --max-context, --kv q4_0, setup --draft-vocab en, "
585              "images on the CPU)";
586        return false;
587    }
588    std::string why;
589    if (!layer_verify_compatible(why)) {
590        err = "verify: " + why + " (the verify window reproduces the default native decode path)";
591        return false;
592    }
593    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 ||
594        g.ssm_d_conv != 4) {
595        err = "verify: geometry differs from the artifact's";
596        return false;
597    }
598    if (le_ < 0) le_ = g.n_layers;
599    if (lb_ < 0 || lb_ >= le_ || le_ > g.n_layers || (lb_ > 0 && hand_in_ == nullptr) ||
600        (le_ < g.n_layers && hand_out_ == nullptr)) {
601        err = "verify: the stage's layer range or its hand-off buffers are wrong";
602        return false;
603    }
604    const WeightRef* wo = wt.find("output.weight");
605    if (wo == nullptr) { err = "verify: output.weight is missing"; return false; }
606    n_vocab_ = wo->ne1;
607
608    const strata::kernels::QsaShapes s = shapes_of(g);
609    cap_ = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);
610    max_blocks_ = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2;
611    attn_scratch_floats_ = (int64_t) strata::kernels::qsa_decode_attn_scratch_floats(cap_, s);
612
613    const uint64_t T = (uint64_t) max_t, N = (uint64_t) g.n_embd, HC = (uint64_t) g.hc, K = (uint64_t) ss.k;
614    const uint64_t C = (uint64_t) g.ssm_conv_channels, ZV = (uint64_t) g.ssm_value_dim, HV = (uint64_t) g.ssm_v_heads;
615    const uint64_t NH = (uint64_t) g.n_head, HD = (uint64_t) g.head_dim, NKV = (uint64_t) g.n_head_kv;
616    const uint64_t IQ = (uint64_t) g.idx_q_heads, ID = (uint64_t) g.idx_key_dim;
617    const uint64_t nG = (uint64_t) g.n_gdn_layers(), nQ = (uint64_t) g.n_qsa_layers();
618    const uint64_t HS = (uint64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM;
619    const uint64_t TS = (uint64_t) (s.idx_block - 1) * ID;
620    const int max_in = (int) std::max<uint64_t>(std::max<uint64_t>(N, ZV), NH * HD);
621
622    // ---- mapped staging
623    bool ok = mapped(T * 4, (void**) &h_tok_, (void**) &m_tok_) &&
624              mapped(T * strata::kernels::kStepCount * 4, (void**) &h_step_, (void**) &m_step_) &&
625              mapped(T * (NH + NKV + IQ) * 4, (void**) &h_pos_, (void**) &m_pos_) &&
626              mapped((2 + T) * 4 + 16, (void**) &h_commit_, (void**) &m_commit_) &&
627              mapped(T * N * 4, (void**) &h_ple_, (void**) &m_ple_) &&
628              mapped(T * 4 + 16, (void**) &h_out_, (void**) &m_out_) &&
629              mapped(T * N * 4, (void**) &h_x_, (void**) &m_x_) &&
630              mapped(T * K * 4, (void**) &h_ids_, (void**) &m_ids_) &&
631              mapped(T * K * 4, (void**) &h_w_, (void**) &m_w_) &&
632              mapped(64, (void**) &h_seq_, (void**) &m_seq_) &&
633              mapped(64, (void**) &h_flag_, (void**) &m_flag_) &&
634              mapped(64, (void**) &h_flagA_, (void**) &m_flagA_) &&
635              mapped(64, (void**) &h_flagB_, (void**) &m_flagB_) &&
636              mapped(64, (void**) &h_plan_err_, (void**) &m_plan_err_) &&
637              mapped(T * K * N * 4, (void**) &h_ymiss_, (void**) &m_ymiss_);
638    if (!ok) { err = "verify: mapped staging allocation failed"; return false; }
639    // DFlash2 taps (set_taps): off, and nothing is allocated or recorded, otherwise
640    if (!tap_req_.empty() && lb_ == 0 && le_ == g.n_layers) {
641        tap_layers_.clear();
642        for (int l : tap_req_) if (l >= 0 && l < g.n_layers - 1) tap_layers_.push_back(l);
643        tap_slot_.assign((size_t) g.n_layers, -1);
644        for (size_t i = 0; i < tap_layers_.size(); ++i) tap_slot_[(size_t) tap_layers_[i]] = (int) i;
645        const size_t nt = tap_layers_.size();
646        if (nt == 0 || (tap_dev_ = sycl::malloc_device<float>((size_t) T * nt * N, dpct::get_in_order_queue())) == nullptr) {
647            err = "verify: the DFlash2 tap buffers could not be allocated";
648            return false;
649        }
650        tap_on_ = true;
651    }
652    // the GPU plan: counts(4) | start(cap+1) | dst(cap) | tok(cap) | pad | ptr(cap u64) | ptr2(cap u64) | start2(cap+1)
653    {
654        const int64_t cap = (int64_t) (T * K);
655        const int64_t i32 = 4 + (cap + 1) + cap + cap;
656        const int64_t ptr_off = (i32 + 1) & ~1ll;
657        plan_i32_ = ptr_off + 4 * cap + (cap + 1) + 1;
658        if (!mapped((size_t) plan_i32_ * 4 * 2 + 64, (void**) &h_plan_, (void**) &m_plan_)) {
659            err = "verify: mapped plan allocation failed";
660            return false;
661        }
662        sink_.counts = h_plan_;
663        sink_.start = h_plan_ + 4;
664        sink_.dst = sink_.start + cap + 1;
665        sink_.tok = sink_.dst + cap;
666        sink_.ptr = (unsigned long long*) (h_plan_ + ptr_off);
667        sink_.ptr2 = sink_.ptr + cap;
668        sink_.start2 = h_plan_ + ptr_off + 4 * cap;
669        sink_.cap = cap;
670        sink_.publish = &Verifier::publish_plan;
671        sink_.fetch = &Verifier::fetch_dma;
672        sink_.ctx = this;
673    }
674
675    // APR: the rotated copy of the expert input (nat_xr_, T x N floats) only where a layer's gate/up is
676    // Hadamard-folded; its one reader is that layer's f.had_gu branch in the expert-input step below
677    bool had_gu_any = false;
678    {
679        const auto& lay = strata::kernels::cpu::expert_layout();
680        for (size_t l = 0; lay.native && l < lay.fmt.size(); ++l) had_gu_any = had_gu_any || lay.fmt[l].had_gu;
681    }
682    // ---- the device arena: the same sequence counted, then carved
683    auto carve = [&](Bump& b) {
684        tok_ = b.take<int32_t>(T); step_ = b.take<int32_t>(T * strata::kernels::kStepCount);
685        pos_ = b.take<int32_t>(T * (NH + NKV + IQ)); commit_ = b.take<int32_t>(2 + T);
686        ple_ = b.take<float>(T * N); emb_ = b.take<float>(T * N); R_ = b.take<float>(T * HC * N);
687        mixed_ = b.take<float>(T * N); bo_ = b.take<float>(T * N);
688        inj_ = b.take<float>(T * HC); inj2_ = b.take<float>(T * HC);
689        lo_ = b.take<float>(T * (uint64_t) g.hc_lr); rs_ = b.take<float>(T * HC); xn_ = b.take<float>(T * HC * N);
690        xq_ = b.take<uint8_t>(strata::kernels::native_q8_1_bytes(max_in, (int) T));
691        sh_xq_ = b.take<uint8_t>(strata::kernels::native_q8_1_bytes(max_in, (int) T));
692        qkv_L_ = b.take<float>(nG * T * C); h_L_ = b.take<float>(nG * T * C);
693        gate_L_ = b.take<float>(nG * T * HV); beta_L_ = b.take<float>(nG * T * HV);
694        z_ = b.take<float>(T * ZV); y_ = b.take<float>(T * ZV); y_dummy_ = b.take<float>(T * ZV);
695        qfull_ = b.take<float>(T * NH * 2 * HD); qcur_ = b.take<float>(T * NH * HD);
696        kcur_ = b.take<float>(T * NKV * HD); vcur_ = b.take<float>(T * NKV * HD);
697        idx_raw_L_ = b.take<float>(nQ * T * ID); qidx_ = b.take<float>(T * IQ * ID);
698        scores_ = b.take<float>(T * (uint64_t) max_blocks_); sel_ = b.take<int32_t>(T * (uint64_t) cap_);
699        attn_ = b.take<float>(T * NH * HD); attn32_ = b.take<float>(T * NH * HD);
700        attn_scratch_ = b.take<float>(T * (uint64_t) attn_scratch_floats_);
701        tail_snap_ = b.take<float>(nQ * TS);
702        logits_ = b.take<float>(T * (uint64_t) g.n_expert); w_ = b.take<float>(T * K); ids_ = b.take<int32_t>(T * K);
703        shared_ = b.take<float>(T * N); parts_ = b.take<float>(T * K * N); hit_out_ = b.take<float>(T * K * N);
704        hit_slot_ = b.take<int32_t>(T * K); hit_dst_ = b.take<int32_t>(T * K); hit_count_ = b.take<int32_t>(4);
705        plan_ = b.take<int32_t>(2 * ((uint64_t) plan_i32_ + 16));
706        staging_ = b.take<uint8_t>((uint64_t) kStagingBlobs * strata::kernels::cpu::expert_layout().max_blob);
707        hit_xq_ = b.take<uint8_t>(T * (N / 32) * 34); hit_xs_ = b.take<float>(T * (N / 32));
708        nat_xq_ = b.take<uint8_t>(T * (N / 32) * 36);
709        nat_xr_ = had_gu_any ? b.take<float>(T * N) : nullptr;
710        hit_scratch_ = b.take<uint8_t>(std::max<uint64_t>(
711            strata::kernels::moe_hit_grouped_scratch_bytes((int64_t) (T * K), g.n_embd, g.n_ff),
712            strata::kernels::native_expert_scratch_bytes((int64_t) (T * K), g.n_ff)));
713        head_mixed_ = b.take<float>(T * N); head_inj_ = b.take<float>(HC);
714        sh_bf16_ = b.take<uint16_t>(T * N); sh_gate_ = b.take<float>(T * (uint64_t) g.n_ff);
715        sh_up_ = b.take<float>(T * (uint64_t) g.n_ff); sh_g_ = b.take<float>(T + 4);
716        head_logits_ = b.take<float>(T * (uint64_t) n_vocab_);
717        arg_scratch_ = b.take<uint8_t>(strata::kernels::argmax_rows_scratch_bytes((int) T));
718        one_ = b.take<int32_t>(4);
719        hist_snap_ = b.take<float>(T * HS);
720        ple_key_ = b.take<float>(T * (uint64_t) strata::kernels::NG_HC_DIM); ple_val_ = b.take<float>(T * N);
721    };
722    Bump count;
723    carve(count);
724    if (DPCT_CHECK_ERROR(arena_ = (void *)strata::malloc_device_guarded(
725                             count.used, dpct::get_in_order_queue())) != 0) {
726        err = "verify: the device arena (" + std::to_string(count.used >> 20) + " MiB) does not fit";
727        return false;
728    }
729    strata::big_fill_zero(dpct::get_in_order_queue(), arena_, count.used);
730    if (g_trace && trace_h_ == nullptr) {   // #649: the breadcrumbs, mapped so they read while the GPU hangs
731        trace_n_ = (size_t) (g.n_layers + 1) * kProfPer * 2;
732        if (!mapped(trace_n_ * 8, (void**) &trace_h_, (void**) &trace_m_)) {
733            trace_h_ = trace_m_ = nullptr;
734            trace_n_ = 0;
735        }
736#if defined(STRATA_USE_HIP)
737        std::fprintf(stderr, "strata verify trace (#649): on; coherent words %s, doorbell %s, HIP_HOST_COHERENT=%s "
738                             "HSA_ENABLE_SDMA=%s GPU_MAX_HW_QUEUES=%s\n", g_coherent ? "explicit" : "default",
739                     g_doorbell_store ? "stored" : "incremented", std::getenv("HIP_HOST_COHERENT") ? std::getenv("HIP_HOST_COHERENT") : "-",
740                     std::getenv("HSA_ENABLE_SDMA") ? std::getenv("HSA_ENABLE_SDMA") : "-",
741                     std::getenv("GPU_MAX_HW_QUEUES") ? std::getenv("GPU_MAX_HW_QUEUES") : "-");
742#else
743        std::fprintf(stderr, "strata verify trace (#649): on\n");
744#endif
745    }
746    prof_on_ = std::getenv("STRATA_VERIFY_PROFILE") != nullptr;
747    if (prof_on_) {
748        const size_t np = (size_t) g.n_layers * kProfPer + 4;
749        /*
750        DPCT1026: The call to cudaGetLastError was removed because this
751        functionality is redundant in SYCL.
752        */
753        if (DPCT_CHECK_ERROR(prof_ = (unsigned long long *)sycl::malloc_device(
754                                 np * 8, dpct::get_in_order_queue())) != 0) {
755            prof_on_ = false; prof_ = nullptr;
756        } else {
757            dpct::get_in_order_queue().memset(prof_, 0, np * 8).wait();
758            prof_h_.assign(np, 0);
759        }
760    }
761    Bump real;
762    real.base = (uint8_t*) arena_;
763    carve(real);
764    {
765        const int32_t one = 1;
766        if (DPCT_CHECK_ERROR(dpct::get_in_order_queue()
767                                 .memcpy(one_, &one, sizeof one)
768                                 .wait()) != 0) {
769            err = "verify: the arena could not be set";
770            return false;
771        }
772    }
773    {   // APR (prism.hadamard, hadamard.txt): the sign vectors on this device, before any graph capture
774        had_sx_ = strata::kernels::hadamard_device_signs(strata::kernels::cpu::hadamard_signs((int) g.n_embd), (int) g.n_embd);
775        had_sh_ = strata::kernels::hadamard_device_signs(strata::kernels::cpu::hadamard_signs((int) g.n_ff), (int) g.n_ff);
776    }
777    sink_.staging = (unsigned long long) staging_;
778    sink_.staging_cap = kStagingBlobs;
779    (void) TS;
780    /*
781    DPCT1025: The SYCL queue is created ignoring the flag and priority
782    options.
783    */
784    if (DPCT_CHECK_ERROR(
785            copy_ = dpct::get_current_device().create_queue(true)) != 0) {
786        err = "verify: copy stream create failed";
787        return false;
788    }
789    if (ext_stream_ != nullptr) cs_ =
790        ext_stream_; // set_stream (pipelined windows): the stage's shared
791                     // stream
792    /*
793    DPCT1025: The SYCL queue is created ignoring the flag and priority
794    options.
795    */
796    else if (DPCT_CHECK_ERROR(
797                 cs_ = dpct::get_current_device().create_queue(true)) != 0)
798        cs_ = &dpct::get_in_order_queue();
799    /*
800    DPCT1025: The SYCL queue is created ignoring the flag and priority
801    options.
802    */
803    if (cs_ == &dpct::get_in_order_queue() ||
804        DPCT_CHECK_ERROR(
805            sh_cs_ = dpct::get_current_device().create_queue(true)) != 0) {
806        err = "verify: stream create failed";
807        return false;
808    }
809    if (std::getenv("STRATA_VERIFY_DEBUG") != nullptr) {
810        // SYCL: a queue belongs to one context, so ev_fork_/ev_join_ (recorded on cs_) can only be waited on by
811        // sh_cs_ when the two streams are the same card.  Print both, and whether the streams are the shared ones.
812        auto dn = [](dpct::queue_ptr q) -> std::string {
813            if (q == nullptr) return "<null>";
814            try { return q->get_device().get_info<sycl::info::device::name>(); } catch (...) { return "<no device>"; }
815        };
816        std::fprintf(stderr, "strata verify: init device %d, cs '%s', sh_cs '%s', ext_stream %s, copy '%s'\n",
817                     device_, dn(cs_).c_str(), dn(sh_cs_).c_str(),
818                     ext_stream_ == nullptr ? "none" : dn(ext_stream_).c_str(), dn(copy_).c_str());
819        std::fflush(stderr);
820    }
821    if (DPCT_CHECK_ERROR(commit_done_ = new sycl::event()) != 0 ||
822        DPCT_CHECK_ERROR(ev_fork_ = new sycl::event()) != 0 ||
823        DPCT_CHECK_ERROR(ev_join_ = new sycl::event()) != 0) {
824        err = "verify: event create failed";
825        return false;
826    }
827    // Check whether 100% of experts across [lb_, le_) are resident in this stage's VRAM cache.
828    // When true, every layer plans on device and writes directly into parts_ without any CPU doorbells,
829    // wait_flag_ge spins, PCIe empty launches, or moe_hit_add copies.
830    all_resident_ = false;
831    ar_off_ = false;
832    h_res_ = hits.h_res;
833    if (h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0;
834    if (hits.h_res != nullptr && hits.d_res != nullptr && hits.cache_base != nullptr) {
835        const char* v_ar = std::getenv("STRATA_VERIFY_ALL_RESIDENT");
836        if (v_ar == nullptr || std::atoi(v_ar) != 0) {
837            bool all_ok = true;
838            for (int64_t l = lb_; l < le_ && all_ok; ++l) {
839                for (int64_t e = 0; e < g.n_expert; ++e) {
840                    if (hits.h_res[l * g.n_expert + e] < 0) {
841                        all_ok = false;
842                        break;
843                    }
844                }
845            }
846            all_resident_ = all_ok;
847        }
848    }
849    // E-6: a layer whose routed experts are all resident is planned on the device (STRATA_VERIFY_DEVICE_PLAN=1: on;
850    // exact, but neutral on RIBPC 1-2 GPUs: off by default)
851    {
852        const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN");
853        // (not with set_always_publish: the device table may lag the host's while windows are in flight)
854        device_plan_ = !all_resident_ && !always_publish_ && (v != nullptr && std::atoi(v) != 0);
855    }
856    // (halo's STRATA_VERIFY_RESIDENT=1 is this window's all_resident_ graph above, which 0.1.39 has on by default)
857    if (g_qfuse()) {   // S26: the HC read's q8_1 group counters, zeroed once (each launch leaves them zero)
858        if (DPCT_CHECK_ERROR(qcnt_ = sycl::malloc_device<unsigned int>(
859                                 (size_t)(g.n_embd / 32),
860                                 dpct::get_in_order_queue())) != 0 ||
861            DPCT_CHECK_ERROR(
862                dpct::get_in_order_queue()
863                    .memset(qcnt_, 0,
864                            sizeof(unsigned) * (size_t)(g.n_embd / 32))
865                    .wait()) != 0) {
866            /*
867            DPCT1026: The call to cudaGetLastError was removed because this
868            functionality is redundant in SYCL.
869            */
870            if (qcnt_) sycl::free(qcnt_, dpct::get_in_order_queue());
871            qcnt_ = nullptr;
872        }
873    }
874    if (all_resident_ || device_plan_) {
875        bool ok2 = true;
876        if (device_plan_)
877            ok2 = DPCT_CHECK_ERROR(skip_ = (uint32_t *)sycl::malloc_device(
878                                       64, dpct::get_in_order_queue())) == 0 &&
879                  DPCT_CHECK_ERROR(
880                      dpct::get_in_order_queue().memset(skip_, 0, 64).wait()) ==
881                      0;
882        if (ok2 && hits.slot_off != nullptr && hits.n_slots > 0) {
883            ok2 = DPCT_CHECK_ERROR(
884                      slot_off_d_ = sycl::malloc_device<unsigned long long>(
885                          (size_t)hits.n_slots, dpct::get_in_order_queue())) ==
886                      0 &&
887                  DPCT_CHECK_ERROR(dpct::get_in_order_queue()
888                                       .memcpy(slot_off_d_, hits.slot_off,
889                                               (size_t)hits.n_slots *
890                                                   sizeof(unsigned long long))
891                                       .wait()) == 0;
892        }
893        /*
894        DPCT1026: The call to cudaGetLastError was removed because this
895        functionality is redundant in SYCL.
896        */
897        if (!ok2) {; all_resident_ = false; device_plan_ = false; }
898    }
899    if (sycl_mirror_adapt()) {
900        if (!device_plan_ || !env_on("STRATA_VERIFY_NO_HOST"))
901            throw std::runtime_error("mirror adaptive expert usage requires NoHost device planning");
902        expert_usage_counts_h_.assign((size_t)g.n_layers * (size_t)g.n_expert, 0);
903        expert_usage_counts_d_ = sycl::malloc_device<uint32_t>(expert_usage_counts_h_.size(), *cs_);
904        if (!expert_usage_counts_d_) throw std::bad_alloc();
905        cs_->memset(expert_usage_counts_d_, 0, expert_usage_counts_h_.size() * sizeof(uint32_t)).wait_and_throw();
906    }
907#ifdef STRATA_SYCL_WORKLOAD_TRACE
908    if (const char* audit = std::getenv("STRATA_SYCL_ROUTING_AUDIT_FILE"); audit && *audit) {
909        if (!device_plan_) throw std::runtime_error("routing audit requires device planning");
910        routing_audits[this] = std::make_unique<RoutingAudit>(plan_i32_, g.n_layers, cs_, audit);
911    }
912#endif
913    if (std::getenv("STRATA_VERIFY_DEBUG") != nullptr) {   // SYCL port: the per-layer residual ladder (token 0)
914        dbgR_ = (float*) sycl::malloc_device((size_t) g.n_layers * g.n_embd * 4, dpct::get_in_order_queue());
915        dbgM_ = (float*) sycl::malloc_device((size_t) g.n_layers * g.n_embd * 4, dpct::get_in_order_queue());
916    }
917    std::fprintf(stderr, "strata verify: window up to %d tokens, %.1f MiB of device buffers%s\n", max_t,
918                 (double) count.used / 1048576.0,
919                 all_resident_ ? " (100% VRAM resident: zero-doorbell graph)" : "");
920    return true;
921}
922catch (sycl::exception const &exc) {
923  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
924            << ", line:" << __LINE__ << std::endl;
925  std::exit(1);
926}
927
928const float* Verifier::final_R(int t) const { return R_ + (size_t) t * (size_t) (g_->hc * g_->n_embd); }
929
930// ================================ THE WINDOW, AS CAPTURED ================================
931//
932// Plan v0.3 P6 (split window): with `groups_ == 2` the window's tokens are cut into two groups A = [0, T/2 up) and
933// B = the rest, and the stream is ordered
934//
935//     pre(0,A) pre(0,B) | post(0,A) pre(1,A) | post(0,B) pre(1,B) | post(1,A) pre(2,A) | ...
936//
937// 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
938// 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
939// state), never A's experts, so nothing waits that did not wait before.  Every token's arithmetic is unchanged.
940bool Verifier::record_window(int T, dpct::queue_ptr cs, std::string &err) {
941    strata::kernels::B60MainActorScope b60_actor_scope;
942    using namespace strata::kernels;
943    const ModelGeometry& g = *g_;
944    // 0.1.43 (STRATA_VERIFY_LEAN=0 turns it off): with the device plan under STRATA_VERIFY_NO_HOST no host ever answers a doorbell, so
945    // a layer's doorbell publish, the three flag waits, the plan copy, the PCIe-share group and its staging kernels are nodes of
946    // the graph that only wait for each other or do nothing: ~9 nodes (~1.4 ms) per layer-window less.  The VRAM / mirror groups, the
947    // combine and the answers are the same kernels on the same data.
948    static const bool lean_env = [] { const char* v = std::getenv("STRATA_VERIFY_LEAN"); return !(v && v[0] == '0'); }();
949    static const bool no_host_env = [] { const char* v = std::getenv("STRATA_VERIFY_NO_HOST"); return v && *v && std::strcmp(v, "0") != 0; }();
950    // Not for a batch window (batch_rec_): unless the stage is all-resident, run_slot_rows / batch_poll wait for each
951    // layer's doorbell, so a lean batch graph finishes with the ring silent ("verify batch: layer 0 never rang (graph
952    // finished)", then the engine dies). Batch windows keep the doorbell nodes; the solo window stays lean.
953    const bool lean = lean_env && no_host_env && device_plan_ && !batch_rec_ && !step_hook_ && !step_hook2_ && !remote_opt_ && !always_publish_ && !g_stepped;
954    const WeightTable& wt = *wt_;
955    SessionState& ss = *ss_;
956    const int64_t N = g.n_embd, HC = g.hc, K = ss.k, C = g.ssm_conv_channels, ZV = g.ssm_value_dim;
957    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;
958    const int64_t IQ = g.idx_q_heads, ID = g.idx_key_dim, NE = g.n_expert, MT = max_t_;
959    const QsaShapes s = shapes_of(g);
960    const GrShapes gs{g.n_embd, g.hc, g.hc_lr};
961    const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +
962                                (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);
963    const int64_t HS = (int64_t) NG_HIST * NG_HC_DIM;
964    const int64_t TS = (s.idx_block - 1) * ID;
965    const bool ple_on = ss.ple.ready() && ple_stage();
966    auto Rt = [&](int t) { return R_ + (size_t) t * HC * N; };
967    const int G = (split_ && T >= 2 && !batch_rec_) ? 2 : 1;   // a batch window is one group
968    const bool self_commit = T == 1 && !batch_rec_ && !g_qfuse() && one_token_self_commit() &&
969                              !self_commit_off_;   // see Verifier::commit
970    static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }();
971    // SYCL port, STRATA_VERIFY_EAGER=1: the window runs on the queue instead of as a graph, and each stage stamp is
972    // a host-side wait + clock (there is no %globaltimer here), so the existing stage profiler reports ms per stage.
973    static const bool eager = std::getenv("STRATA_VERIFY_EAGER") != nullptr;
974    auto stamp = [&](int64_t l, int i, int grp) {
975        if (trace_m_ != nullptr) gpu_stamp(trace_m_, (int) ((l * kProfPer + i) * 2 + grp), cs);   // #649
976        if (!prof_on_ || grp != 0) return;
977        if (eager) { cs->wait(); prof_h_[(size_t) (l * kProfPer + i)] = (unsigned long long) std::chrono::steady_clock::now().time_since_epoch().count(); }
978        else gpu_stamp(prof_, (int) (l * kProfPer + i), cs);
979    };
980    const int tb_[2] = {0, (T + 1) / 2}, te_[2] = {G == 2 ? (T + 1) / 2 : T, T};
981    // S26 STRATA_LFUSE=1: where the shared expert's gate / scale fusions apply (the paths they replace are the ones taken)
982    auto lfuse_on = [&](int n) {
983        return g_lfuse() && ar_on() && native_moe_combine_enabled() && dec_batch && n > 1 && n <= 8 &&
984               shared_expert_native_bf16_enabled();
985    };
986    bool sg_gated_[2] = {false, false};   // per group: the combine applies the shared gate
987    if (!batch_rec_) groups_[T] = G;
988    const int64_t nQall = g.n_qsa_layers();
989    // a batch window: row t is slot t, whose state lives in its own session
990    auto slot_ss = [&](int t) -> SessionState& { return batch_rec_ ? *slots_[(size_t) brow_[t]] : ss; };
991    const int hrow0 = batch_rec_ ? row_base_ : 0;   // a slot group's own hand-off rows
992
993    // ---- the window's inputs, from mapped staging
994    copy_i32_from_mapped(tok_, m_tok_, T, cs);
995    copy_i32_from_mapped(step_, m_step_, (int64_t) T * kStepCount, cs);
996    copy_i32_from_mapped(pos_, m_pos_, (int64_t) MT * (NH + NKV + IQ), cs);
997    // per-ROW positions of the K rows [t][NKV] and the indexer query rows [t][IQ] (for batched RoPE)
998    const int32_t* pos_k = pos_ + MT * NH;
999    const int32_t* pos_i = pos_ + MT * (NH + NKV);
1000
1001    // ---- the embeddings, broadcast to the hc streams - or, in a later stage of a layer split, the previous stage's
1002    // residual, pending write and inject (see set_stage)
1003    const int64_t HB = Verifier::handoff_floats(g);
1004    if (lb_ > 0) {
1005        const float* hin = hand_in_ + (size_t) hrow0 * HB;   // the group's rows: [R][bo][inj] contiguous
1006        copy_from_mapped(R_, hin, (int64_t) T * HC * N, cs);
1007        copy_from_mapped(bo_, hin + (size_t) T * HC * N, (int64_t) T * N, cs);
1008        copy_from_mapped(inj2_, hin + (size_t) T * (HC + 1) * N, (int64_t) T * HC, cs);
1009    } else if (const NativeEmbed* ne = native_embed()) {       // plan v0.3 P6: the GGUF-form table
1010        ne->gather_dev(tok_, T, emb_, cs);
1011        broadcast_streams(emb_, R_, N, (int) HC, T, cs);
1012    } else {
1013        const WeightRef* w = wt.find("token_embd.weight");
1014        if (w == nullptr || w->codebook_iq4nl || (w->code_bits != 2 && w->code_bits != 4 && w->code_bits != 8)) {
1015            err = "verify: token_embd.weight is missing or not an S2/S4/S8 tensor";
1016            return false;
1017        }
1018        const auto* codes = (const uint8_t*) w->data;
1019        const auto* scales = (const float*) (codes + w->codes_bytes);
1020        const auto* offsets = w->has_offset ? (const float*) (codes + w->codes_bytes + w->scales_bytes) : nullptr;
1021        const uint64_t row_codes = (uint64_t) (w->ne0 / (8 / w->code_bits));
1022        const uint64_t row_groups = (uint64_t) (w->ne0 / w->group_elems);
1023        embedding_gather_dev(codes, scales, offsets, tok_, T, w->ne0, w->code_bits, w->code_bias, w->group_elems,
1024                             row_codes, row_groups, emb_, cs);
1025        broadcast_streams(emb_, R_, N, (int) HC, T, cs);
1026    }
1027
1028    // per-layer state indices (GDN and QSA layers are numbered separately)
1029    std::vector<int64_t> gdn_idx((size_t) g.n_layers, -1), qsa_idx((size_t) g.n_layers, -1);
1030    {
1031        int64_t qi = 0, gi = 0;
1032        for (int64_t l = 0; l < g.n_layers; ++l) {
1033            if (is_qsa_layer(g, l)) qsa_idx[(size_t) l] = qi++;
1034            else gdn_idx[(size_t) l] = gi++;
1035        }
1036    }
1037
1038    // ---------------------------------------------------------------- pre(l, group): up to the ring
1039    auto pre = [&](int64_t l, int grp) -> bool {
1040        const int tb = tb_[grp], te = te_[grp], n = te - tb;
1041#ifdef STRATA_SYCL_WORKLOAD_TRACE
1042        strata::workload_trace::ContextGuard layer_context(strata::workload_trace::context.position, n, l);
1043#endif
1044        strata::workload_trace::Scope layer_trace("decode.layer.pre", cs, n, N);
1045        stamp(l, 0, grp);
1046        const LayerView v(wt, l);
1047        const char* pfx[2] = {"hc_attn_", "hc_ffn_"};
1048        const WeightRef *wn[2], *wd[2], *wu[2], *wi[2];
1049        for (int h = 0; h < 2; ++h) {
1050            wn[h] = need(v, (std::string(pfx[h]) + "norm.weight").c_str(), err);
1051            wd[h] = need(v, (std::string(pfx[h]) + "down.weight").c_str(), err);
1052            wu[h] = need(v, (std::string(pfx[h]) + "up.weight").c_str(), err);
1053            wi[h] = need(v, (std::string(pfx[h]) + "inject.weight").c_str(), err);
1054            if (!wn[h] || !wd[h] || !wu[h] || !wi[h]) return false;
1055        }
1056        // the previous layer's FFN write, folded into this layer's first read (a control vector after it has
1057        // already applied it)
1058        bool pending = l > 0 && !cvec().covers(l - 1);
1059        if (l == 1 && ple_on) {
1060            if (grp == 0) {
1061                if (ar_on()) wait_flag_ge(m_flag_, 1, cs);
1062                copy_from_mapped(ple_, m_ple_, (int64_t) T * N, cs);
1063            }
1064            float* normalized = (float*) ((uint8_t*) ss.ple.scratch + ple_block_scratch_bytes());
1065            static const bool ple_batch_env = [] {
1066                const char* e = std::getenv("STRATA_PLE_BATCH");
1067                return !e || e[0] != '0';
1068            }();
1069            const bool ple_batch_kv = ple_batch_env && dec_batch && n > 1 && ss.ple.w.key_bf16 != nullptr &&
1070                                      ss.ple.w.value_bf16 != nullptr && ple_native_bf16_enabled() &&
1071                                      ple_native_postops_enabled();
1072            // S25 (STRATA_PLE_BATCH=1): the key and value projections depend only on each row's n-gram embedding, so
1073            // the group's rows run through the multi-row forms of the same kernels (the weights read once); every
1074            // row's arithmetic is the single-row call's. The history-dependent rest stays row by row.
1075            static const bool ple_batch = [] { const char* e = std::getenv("STRATA_PLE_BATCH"); return e && e[0] == '1'; }();
1076            PleWeights pw = ss.ple.w;
1077            const bool nkey = pw.key_native_data != nullptr && pw.key_bf16 == nullptr;
1078            const bool batched = !ple_batch_kv && ple_batch && n > 1 && (pw.key_bf16 != nullptr || nkey) && ple_native_bf16_enabled();
1079            if (ple_batch_kv) {
1080                try {
1081                    bf16_gemv_fp32_mmvf_multi(ple_ + (size_t) tb * N, N, ss.ple.w.key_bf16,
1082                                              xn_ + (size_t) tb * HC * N, HC * N, N, HC * N, n, cs);
1083                    bf16_gemv_fp32_mmvf_multi(ple_ + (size_t) tb * N, N, ss.ple.w.value_bf16,
1084                                              z_ + (size_t) tb * N, N, N, N, n, cs);
1085                } catch (const std::exception& e) {
1086                    err = std::string("verify PLE multi: ") + e.what();
1087                    return false;
1088                }
1089            } else if (batched) {
1090                try {
1091                    if (pw.key_bf16 != nullptr)
1092                        bf16_gemv_fp32_mmvf_multi(ple_ + tb * N, N, pw.key_bf16, ple_key_ + (size_t) tb * NG_HC_DIM,
1093                                                  NG_HC_DIM, N, NG_HC_DIM, n, cs);
1094                    else {
1095                        native_quantize_q8_1(ple_ + tb * N, xq_, (int) N, n, cs);
1096                        native_mmvq(pw.key_native_type, pw.key_native_data, xq_, ple_key_ + (size_t) tb * NG_HC_DIM,
1097                                    (int) N, NG_HC_DIM, n, cs);
1098                    }
1099                    bf16_gemv_fp32_mmvf_multi(ple_ + tb * N, N, pw.value_bf16, ple_val_ + tb * N, N, N, N, n, cs);
1100                } catch (const std::exception& e) {
1101                    err = std::string("verify PLE batch: ") + e.what();
1102                    return false;
1103                }
1104            }
1105            // #783 PR-g (stuchapin909): the window's residual writes in one launch (STRATA_NO_MULTI_GR=1: per token)
1106            const bool multi_write = dec_batch && !g_no_multi_gr && n > 1;
1107            if (multi_write) gr_write_multi(Rt(tb), bo_ + tb * N, inj2_ + tb * HC, gs, Rt(tb), n, cs);
1108            for (int t = tb; t < te; ++t) {
1109                if (batched) { pw.pre_key = ple_key_ + (size_t) t * NG_HC_DIM; pw.pre_value = ple_val_ + t * N; }
1110                if (!multi_write) gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs);
1111                PleOut po;
1112                po.normalized = normalized;
1113                po.result = Rt(t);
1114                float* hist = batch_rec_ ? slot_ss(t).ple_hist : ss.ple.hist;   // the row's own history
1115                try {
1116                    if (ple_batch_kv) {
1117                        ple_block_projected(xn_ + (size_t) t * HC * N, z_ + (size_t) t * N, Rt(t), hist,
1118                                            ss.ple.w, po, ss.ple.scratch, cs);
1119                    } else {
1120                        ple_block(ple_ + t * N, Rt(t), hist, pw, po, ss.ple.scratch, cs);
1121                    }
1122                    ple_history_advance(hist, normalized, cs);
1123                } catch (const std::exception& e) {
1124                    err = std::string("verify PLE: ") + e.what();
1125                    return false;
1126                }
1127                copy_from_mapped(hist_snap_ + (size_t) t * HS, hist, HS, cs);
1128            }
1129            pending = false;
1130        }
1131        auto gr_read_group = [&](int half, bool apply, float* inj_prev, float* inj_out) {
1132            strata::workload_trace::Scope gr_trace("decode.gr_read", cs, n, HC * N, g.hc_lr, HC, N, half);
1133            FusedGrArgs fa[kFusedGrMaxT];
1134            for (int t = tb; t < te; ++t) {
1135                FusedGrArgs& a = fa[t - tb];
1136                a.R = Rt(t); a.R_out = Rt(t); a.apply = apply;
1137                a.bo_prev = bo_ + t * N; a.inj_prev = inj_prev + t * HC;
1138                a.w_norm = (const float*) wn[half]->data; a.w_down = (const uint16_t*) wd[half]->data;
1139                a.w_up = (const uint16_t*) wu[half]->data; a.w_inject = (const uint16_t*) wi[half]->data;
1140                a.q8_down = (const uint8_t*) wd[half]->hc_q8; a.q8_up = (const uint8_t*) wu[half]->hc_q8;
1141                a.q8_inject = (const uint8_t*) wi[half]->hc_q8;
1142                a.eps = EPS; a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC;
1143                a.inject_out = inj_out + t * HC; a.mixed = mixed_ + t * N;
1144                if (qcnt_ != nullptr || (b60_gr_q8_requested() && n==1)) {   // S26 STRATA_QFUSE: the consumer's q8_1 image written by the read itself
1145                    a.q8_cnt = qcnt_;
1146                    if (half == 0) a.q8_mixed = xq_ + (size_t) (t - tb) * (N / 32) * 36;
1147                    else if (strata::kernels::cpu::expert_layout().native) a.q8_mixed = nat_xq_ + (size_t) t * (N / 32) * 36;
1148                }
1149            }
1150            return fused_gr_read_multi(fa, n, xn_ + (size_t) tb * HC * N, cs, (prof_on_ && grp == 0) ? prof_ : nullptr,
1151                                (int) (l * kProfPer + (half == 0 ? 27 : 30)));
1152        };
1153        const bool q8_attn = gr_read_group(0, pending, inj2_, inj_);   // true: xq_ holds mixed's q8_1 (STRATA_QFUSE)
1154        stamp(l, 1, grp);
1155        float* xm = mixed_ + tb * N;
1156        try {
1157            if (!is_qsa_layer(g, l)) {
1158                // ======================= GDN =======================
1159                const WeightRef *wqkv = need(v, "attn_qkv.weight", err), *wg = need(v, "attn_gate.weight", err),
1160                                *wout = need(v, "ssm_out.weight", err), *wa = need(v, "ssm_alpha.weight", err),
1161                                *wb = need(v, "ssm_beta.weight", err), *wc = need(v, "ssm_conv1d.weight", err),
1162                                *wnm = need(v, "ssm_norm.weight", err), *wdt = need(v, "ssm_dt.bias", err),
1163                                *wsa = need(v, "ssm_a", err);
1164                if (!wqkv || !wg || !wout || !wa || !wb || !wc || !wnm || !wdt || !wsa) return false;
1165                if (!native_of(wqkv, v.name("attn_qkv.weight"), err) || !native_of(wg, v.name("attn_gate.weight"), err) ||
1166                    !native_of(wout, v.name("ssm_out.weight"), err))
1167                    return false;
1168                const int64_t gi = gdn_idx[(size_t) l];
1169                float* state = ss.gdn_state + (size_t) (gi - ss.gdn_ord0) * gdn_floats;
1170                float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
1171                float* qkv = qkv_L_ + (size_t) gi * MT * C;
1172                float* hb = h_L_ + (size_t) gi * MT * C;
1173                float* gate = gate_L_ + (size_t) gi * MT * HV;
1174                float* beta = beta_L_ + (size_t) gi * MT * HV;
1175                if (!q8_attn) native_quantize_q8_1(xm, xq_, (int) N, n, cs);
1176                native_mmvq(wqkv->native_type, wqkv->native_data, xq_, qkv + (size_t) tb * C, (int) N, (int) C, n, cs);
1177                stamp(l, 2, grp);
1178                if (batch_rec_) {   // contiguous rows may be proposals for the same slot
1179                    for (int t = tb; t < te;) {
1180                        const int first = t;
1181                        while (t < te && brow_[t] == brow_[first]) ++t;
1182                        SessionState& sx = slot_ss(first);
1183                        const float* cx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats +
1184                                          (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
1185                        gdn_conv_l2_multi(cx, qkv + (size_t) first * C, (const float*) wc->data,
1186                                          hb + (size_t) first * C, (int) C, (int) (2 * HK), EPS, t - first, cs, 0);
1187                    }
1188                } else
1189                // a one-token window keeps its token: it advances the conv history and the state itself (commit)
1190                gdn_conv_l2_multi(conv, qkv, (const float*) wc->data, hb, (int) C, (int) (2 * HK), EPS, n, cs, tb,
1191                                  self_commit);
1192                stamp(l, 3, grp);
1193                gdn_ab_multi(xm, (const uint16_t*) wa->data, (const uint16_t*) wb->data, (const float*) wdt->data,
1194                             (const float*) wsa->data, gate + (size_t) tb * HV, beta + (size_t) tb * HV, (int) N, (int) HV,
1195                             n, cs);
1196                stamp(l, 4, grp);
1197                native_mmvq(wg->native_type, wg->native_data, xq_, z_ + (size_t) tb * ZV, (int) N, (int) ZV, n, cs);
1198                stamp(l, 5, grp);
1199                // the recurrence from the untouched state over tokens [0, te); outputs only for this group's
1200                static const bool gdn_groups_on = [] {   // STRATA_BATCH_GDN_GROUPS=1, all slots in one launch
1201                    const char* e = std::getenv("STRATA_BATCH_GDN_GROUPS");
1202                    return e != nullptr && std::atoi(e) != 0;
1203                }();
1204                if (batch_rec_ && gdn_groups_on && te - tb <= 8) {
1205                    GdnGroups gg;
1206                    for (int t = tb; t < te;) {
1207                        const int first = t;
1208                        while (t < te && brow_[t] == brow_[first]) ++t;
1209                        SessionState& sx = slot_ss(first);
1210                        gg.state[gg.n] = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats;
1211                        gg.first[gg.n] = first;
1212                        gg.ntok[gg.n] = t - first;
1213                        ++gg.n;
1214                    }
1215                    gdn_step_norm_groups(gg, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, y_, (int) HK,
1216                                         (int) HV, false, cs);
1217                } else
1218                if (batch_rec_) {   // each slot's recurrence over its own proposed-token group
1219                    for (int t = tb; t < te;) {
1220                        const int first = t;
1221                        while (t < te && brow_[t] == brow_[first]) ++t;
1222                        SessionState& sx = slot_ss(first);
1223                        float* stx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats;
1224                        gdn_step_norm_multi(stx, hb + (size_t) first * C, (int) C, gate + (size_t) first * HV,
1225                                            beta + (size_t) first * HV, z_ + (size_t) first * ZV,
1226                                            (const float*) wnm->data, EPS, y_ + (size_t) first * ZV,
1227                                            (int) HK, (int) HV, t - first, nullptr, cs, 0);
1228                    }
1229                } else
1230                gdn_step_norm_multi(state, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, y_, (int) HK,
1231                                    (int) HV, te, self_commit ? one_ : nullptr, cs, tb, g_qfuse() ? (void*) xq_ : nullptr);
1232                stamp(l, 6, grp);
1233                if (!g_qfuse()) native_quantize_q8_1(y_ + (size_t) tb * ZV, xq_, (int) ZV, n, cs);   // STRATA_QFUSE: done above
1234                native_mmvq(wout->native_type, wout->native_data, xq_, bo_ + tb * N, (int) ZV, (int) N, n, cs);
1235            } else {
1236                // ======================= QSA =======================
1237                const int64_t qi = qsa_idx[(size_t) l];
1238                const QsaState& st = ss.qsa_states[qi];
1239                const WeightRef *wik = need(v, "indexer.k_proj.weight", err), *wq = need(v, "attn_q.weight", err),
1240                                *wk = need(v, "attn_k.weight", err), *wv = need(v, "attn_v.weight", err),
1241                                *wo = need(v, "attn_output.weight", err), *wiq = need(v, "indexer.q_proj.weight", err),
1242                                *wqn = need(v, "attn_q_norm.weight", err), *wkn = need(v, "attn_k_norm.weight", err),
1243                                *wiqn = need(v, "indexer.q_norm.weight", err), *wikn = need(v, "indexer.k_norm.weight", err);
1244                if (!wik || !wq || !wk || !wv || !wo || !wiq || !wqn || !wkn || !wiqn || !wikn) return false;
1245                if (!native_of(wq, v.name("attn_q.weight"), err) || !native_of(wk, v.name("attn_k.weight"), err) ||
1246                    !native_of(wv, v.name("attn_v.weight"), err) || !native_of(wo, v.name("attn_output.weight"), err))
1247                    return false;
1248                // #783 PR-f (stuchapin909): the per-head RMSNorm and the rope in one launch, bit-identical to the pair
1249                // (rope_parity check 6); STRATA_NO_NORM_ROPE=1 keeps the two; off on HIP until its parity check passes
1250                const bool fuse_nr = native_qsa_enabled() && native_rope_enabled() && native_norm_rope_usable((int) HD, (int) s.n_rot);
1251                auto norm_rope = [&](float* data, const WeightRef* norm, int rows, int cols, const int32_t* pos) {
1252                    if (fuse_nr && native_norm_rope_usable(cols, (int) s.n_rot)) {
1253                        native_qsa_rms_norm_rope(data, cols, (const float*) norm->data, data, rows, cols, (int) s.n_rot, EPS,
1254                                                 rope_scaling(), pos, cs);
1255                        return;
1256                    }
1257                    if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, EPS, cs);
1258                    else rms_norm_weighted(data, (const float*) norm->data, rows, cols, EPS, cs);
1259                    if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), pos, cs);
1260                    else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, pos, cs);
1261                };
1262                float* idx_raw = idx_raw_L_ + (size_t) qi * MT * ID;
1263                // the per-token GEMVs / norms / RoPEs / copies of this layer as one launch over the
1264                // window's rows each - row-wise identical arithmetic (STRATA_DEC_BATCH=0: token by token)
1265                const bool qb = dec_batch && n > 1 && native_qsa_enabled() && native_rope_enabled() && !st.kv_q4;
1266                if (!q8_attn) native_quantize_q8_1(xm, xq_, (int) N, n, cs);
1267                if (qb) bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wik->data, idx_raw + tb * ID, ID, N, ID, n, cs);
1268                else for (int t = tb; t < te; ++t)
1269                    bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wik->data, idx_raw + t * ID, (int) N, (int) ID, cs);
1270                stamp(l, 7, grp);
1271                native_mmvq(wk->native_type, wk->native_data, xq_, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs);
1272                native_mmvq(wv->native_type, wv->native_data, xq_, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs);
1273                if (qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV);
1274                else for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH);
1275                if (st.kv_rot) {   // K and V rotated before they are stored (kv_q4.hpp)
1276                    fwht256_inplace_cuda(kcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);
1277                    fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);
1278                } else if (st.kv_hybrid) {   // K8V4: only V is rotated
1279                    fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);
1280                }
1281                stamp(l, 8, grp);
1282                if (batch_rec_) {   // snapshot each slot's indexer tail before its first proposed row
1283                    for (int t = tb; t < te; ++t)
1284                        if (t == tb || brow_[t] != brow_[t - 1])
1285                            copy_from_mapped(tail_snap_b_ + ((size_t) brow_[t] * nQall + qi) * TS,
1286                                             slot_ss(t).qsa_states[qi].idx_tail, TS, cs);
1287                } else
1288                if (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, cs);
1289                // #783 PR-d (stuchapin909): the window's K/V cells in one launch per pool instead of one per token (a
1290                // batch's rows each have their own K/V, so that case keeps the loop)
1291                if (dec_batch && !g_no_batch_kv && !batch_rec_) {
1292                    const int32_t* step_b = step_ + tb * kStepCount;
1293                    const float* kc_b = kcur_ + tb * NKV * HD;
1294                    const float* vc_b = vcur_ + tb * NKV * HD;
1295                    if (st.kv_hybrid) {   // K8V4: the unused half's lanes folded onto the used pool (layer.cpp)
1296                        kv_append_q8_steps(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, step_b, kStepCount,
1297                                           kc_b, kc_b, (int) (NKV * HD), n, s, cs, nullptr);
1298                        kv_append_q4_steps(st.v_q4, st.v_q4, st.page_table, step_b, kStepCount, n, vc_b, vc_b, s, cs,
1299                                           nullptr);
1300                    } else if (st.kv_q4)
1301                        kv_append_q4_steps(st.k_q4, st.v_q4, st.page_table, step_b, kStepCount, n, kc_b, vc_b, s, cs,
1302                                           &st.host);
1303                    else if (st.kv_int8)
1304                        kv_append_q8_steps(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, step_b, kStepCount,
1305                                           kc_b, vc_b, (int) (NKV * HD), n, s, cs, &st.host);
1306                    else
1307                        for (int t = tb; t < te; ++t)
1308                            kv_append_step(st.k_pool, st.v_pool, st.page_table, step_ + t * kStepCount,
1309                                           kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st.host);
1310                } else
1311                for (int t = tb; t < te; ++t) {
1312                    const QsaState& st = slot_ss(t).qsa_states[qi];   // the row's own K/V (ss's outside a batch)
1313                    const int32_t* step_t = step_ + t * kStepCount;
1314                    if (st.kv_hybrid) {   // K8V4: the unused half's lanes folded onto the used pool (layer.cpp)
1315                        const KvHostPools hk = kv_hybrid_k_half(st.host), hv = kv_hybrid_v_half(st.host);
1316                        const bool mirror = st.host.present();   // streamed: the host copy too
1317                        kv_append_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, step_t,
1318                                          kcur_ + t * NKV * HD, kcur_ + t * NKV * HD, s, cs, mirror ? &hk : nullptr);
1319                        kv_append_q4_step(st.v_q4, st.v_q4, st.page_table, step_t, vcur_ + t * NKV * HD,
1320                                          vcur_ + t * NKV * HD, s, cs, mirror ? &hv : nullptr);
1321                    } else if (st.kv_q4)
1322                        kv_append_q4_step(st.k_q4, st.v_q4, st.page_table, step_t, kcur_ + t * NKV * HD,
1323                                          vcur_ + t * NKV * HD, s, cs, &st.host);
1324                    else if (st.kv_int8)
1325                        kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, step_t,
1326                                          kcur_ + t * NKV * HD, vcur_ + t * NKV * HD, s, cs, &st.host);
1327                    else
1328                        kv_append_step(st.k_pool, st.v_pool, st.page_table, step_t, kcur_ + t * NKV * HD,
1329                                       vcur_ + t * NKV * HD, s, cs, &st.host);
1330                }
1331                if (dec_batch && !g_no_batch_kv && !batch_rec_) {
1332                    const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};
1333                    native_qsa_indexer_append_steps(idx_raw + tb * ID, step_ + tb * kStepCount + kStepPos, kStepCount,
1334                                                    n, 0, (const float*) wikn->data, EPS, ib, s, st.max_cells,
1335                                                    rope_scaling(), cs);
1336                } else {
1337                    for (int t = tb; t < te; ++t) {
1338                        const QsaState& sx = slot_ss(t).qsa_states[qi];
1339                        const QsaIndexerBuffers ib{sx.idx_tail, sx.idx_dead, sx.idx_pooled, sx.idx_block_pos};
1340                        native_qsa_indexer_append(idx_raw + t * ID, step_ + t * kStepCount + kStepPos, 0,
1341                                                  (const float*) wikn->data, EPS, ib, s, sx.max_cells,
1342                                                  rope_scaling(), cs);
1343                    }
1344                }
1345                stamp(l, 9, grp);
1346                native_mmvq(wq->native_type, wq->native_data, xq_, qfull_ + tb * NH * 2 * HD, (int) N, (int) (NH * 2 * HD),
1347                            n, cs);
1348                if (qb) {
1349                    if (fuse_nr) {   // the q/gate split reads q straight out of the q|gate rows (stride 2 * HD)
1350                        native_qsa_rms_norm_rope(qfull_ + tb * NH * 2 * HD, (int) (2 * HD), (const float*) wqn->data,
1351                                                 qcur_ + tb * NH * HD, (int) (n * NH), (int) HD, (int) s.n_rot, EPS,
1352                                                 rope_scaling(), pos_ + tb * NH, cs);
1353                    } else {
1354                    /*
1355                    DPCT1124: cudaMemcpy2DAsync is migrated to asynchronous
1356                    memcpy API. While the origin API might be synchronous, it
1357                    depends on the type of operand memory, so you may need to
1358                    call wait() on event return by memcpy API to ensure
1359                    synchronization behavior.
1360                    */
1361                    if (DPCT_CHECK_ERROR(dpct::async_dpct_memcpy(
1362                            qcur_ + tb * NH * HD, (size_t)HD * 4,
1363                            qfull_ + tb * NH * 2 * HD, (size_t)HD * 2 * 4,
1364                            (size_t)HD * 4, (size_t)(n * NH),
1365                            dpct::device_to_device, *cs)) != 0) {
1366                        err = "verify: the q/gate split failed";
1367                        return false;
1368                    }
1369                    norm_rope(qcur_ + tb * NH * HD, wqn, (int) (n * NH), (int) HD, pos_ + tb * NH);
1370                    }
1371                    if (st.kv_rot) fwht256_inplace_cuda(qcur_ + tb * NH * HD, (int64_t) n * NH, cs);   // <Hq, Hk> = <q, k>
1372                    bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wiq->data, qidx_ + tb * IQ * ID, IQ * ID,
1373                                              N, IQ * ID, n, cs);
1374                    norm_rope(qidx_ + tb * IQ * ID, wiqn, (int) (n * IQ), (int) ID, pos_i + tb * IQ);
1375                } else {
1376                for (int t = tb; t < te; ++t) {
1377                    float* qc = qcur_ + t * NH * HD;
1378                    if (fuse_nr) {
1379                        native_qsa_rms_norm_rope(qfull_ + t * NH * 2 * HD, (int) (2 * HD), (const float*) wqn->data, qc,
1380                                                 (int) NH, (int) HD, (int) s.n_rot, EPS, rope_scaling(), pos_ + t * NH, cs);
1381                    } else {
1382                    /*
1383                    DPCT1124: cudaMemcpy2DAsync is migrated to asynchronous
1384                    memcpy API. While the origin API might be synchronous, it
1385                    depends on the type of operand memory, so you may need to
1386                    call wait() on event return by memcpy API to ensure
1387                    synchronization behavior.
1388                    */
1389                    if (DPCT_CHECK_ERROR(dpct::async_dpct_memcpy(
1390                            qc, (size_t)HD * 4, qfull_ + t * NH * 2 * HD,
1391                            (size_t)HD * 2 * 4, (size_t)HD * 4, (size_t)NH,
1392                            dpct::device_to_device, *cs)) != 0) {
1393                        err = "verify: the q/gate split failed";
1394                        return false;
1395                    }
1396                    norm_rope(qc, wqn, (int) NH, (int) HD, pos_ + t * NH);
1397                    }
1398                    if (st.kv_rot) fwht256_inplace_cuda(qc, NH, cs);   // <Hq, Hk> = <q, k>
1399                }
1400                for (int t = tb; t < te; ++t) {
1401                    float* qx = qidx_ + t * IQ * ID;
1402                    bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wiq->data, qx, (int) N, (int) (IQ * ID), cs);
1403                    norm_rope(qx, wiqn, (int) IQ, (int) ID, pos_ + t * NH);
1404                }
1405                }
1406                stamp(l, 10, grp);
1407                // STRATA_BATCH_ATTN_ROWS=1: the window's rows in ONE launch per step (scores with each row's own indexer
1408                // keys, the top-k over all rows, attention with each row's own pools): the same per-row arithmetic.
1409                // Not with KV streaming (qsa_kv_resolve has work per slot then).
1410                static const bool attn_rows = [] {
1411                    const char* e = std::getenv("STRATA_BATCH_ATTN_ROWS");
1412                    return e != nullptr && std::atoi(e) != 0;
1413                }();
1414                bool rows_ok = batch_rec_ && attn_rows && te - tb <= kAttnRowsMax;
1415                for (int t = tb; rows_ok && t < te; ++t) rows_ok = slot_ss(t).qsa_states[qi].kv_mode != 1;
1416                if (rows_ok) {
1417                    const int n_rows = te - tb;
1418                    QsaScoreRows sr;
1419                    QsaAttnPoolsRows pr;
1420                    sr.n = pr.n = n_rows;
1421                    for (int t = tb; t < te; ++t) {
1422                        const QsaState& sx = slot_ss(t).qsa_states[qi];
1423                        sr.pooled[t - tb] = sx.idx_pooled;
1424                        sr.dead[t - tb] = sx.idx_dead;
1425                        pr.p[t - tb] = qsa_attn_pools(sx);
1426                    }
1427                    qsa_block_scores_rows(sr, qidx_ + tb * IQ * ID, step_ + tb * kStepCount, n_rows, max_blocks_, s,
1428                                          scores_ + (size_t) tb * max_blocks_, cs);
1429                    qsa_block_topk(scores_ + (size_t) tb * max_blocks_, step_ + tb * kStepCount, n_rows, max_blocks_, cap_,
1430                                   s, sel_ + (size_t) tb * cap_, cs);
1431                    qsa_decode_attn_batch_rows(qcur_ + tb * NH * HD, pr, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount,
1432                                               cap_, s, attn_scratch_ + (size_t) tb * attn_scratch_floats_,
1433                                               attn_ + tb * NH * HD, n_rows, cs);
1434                } else
1435                if (batch_rec_) {   // each row selects and attends over its own slot's K/V
1436                    for (int t = tb; t < te; ++t) {
1437                        const QsaState& sx = slot_ss(t).qsa_states[qi];
1438                        qsa_block_scores(sx.idx_pooled, sx.idx_dead, qidx_ + t * IQ * ID, step_ + t * kStepCount, 1,
1439                                         max_blocks_, s, scores_ + (size_t) t * max_blocks_, cs);
1440                        qsa_block_topk(scores_ + (size_t) t * max_blocks_, step_ + t * kStepCount, 1, max_blocks_, cap_, s,
1441                                       sel_ + (size_t) t * cap_, cs);
1442                        qsa_kv_resolve(sx, *g_, sel_ + (size_t) t * cap_, step_ + t * kStepCount, 1, cap_, cs);
1443                        const QsaAttnPools px = qsa_attn_pools(sx);
1444                        qsa_decode_attn_batch(qcur_ + t * NH * HD, px, sel_ + (size_t) t * cap_, step_ + t * kStepCount,
1445                                              cap_, s, attn_scratch_ + (size_t) t * attn_scratch_floats_,
1446                                              attn_ + t * NH * HD, 1, cs);
1447                    }
1448                } else {
1449                qsa_block_scores(st.idx_pooled, st.idx_dead, qidx_ + tb * IQ * ID, step_ + tb * kStepCount, n, max_blocks_,
1450                                 s, scores_ + (size_t) tb * max_blocks_, cs);
1451                qsa_block_topk(scores_ + (size_t) tb * max_blocks_, step_ + tb * kStepCount, n, max_blocks_, cap_, s,
1452                               sel_ + (size_t) tb * cap_, cs);
1453                stamp(l, 11, grp);
1454                // KV streaming: the n selections' blocks resident (device-side, inside the graph)
1455                qsa_kv_resolve(st, *g_, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, n, cap_, cs);
1456                stamp(l, 12, grp);
1457                const QsaAttnPools pools = qsa_attn_pools(st);
1458                qsa_decode_attn_batch(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, cap_,
1459                                      s, attn_scratch_ + (size_t) tb * attn_scratch_floats_, attn_ + tb * NH * HD, n, cs);
1460                }
1461                stamp(l, 13, grp);
1462                if (st.kv_rot || st.kv_hybrid) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs);   // back: H^-1 = H
1463                if (qb) native_qsa_gate_apply(attn_ + tb * NH * HD, qfull_ + tb * NH * 2 * HD, attn32_ + tb * NH * HD,
1464                                              (int) (n * NH), (int) HD, cs);
1465                else
1466                for (int t = tb; t < te; ++t) {
1467                    if (native_qsa_enabled())
1468                        native_qsa_gate_apply(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, attn32_ + t * NH * HD,
1469                                              (int) NH, (int) HD, cs);
1470                    else
1471                        qsa_gate_apply_f32(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, s, attn32_ + t * NH * HD, cs);
1472                }
1473                stamp(l, 14, grp);
1474                native_quantize_q8_1(attn32_ + tb * NH * HD, xq_, (int) (NH * HD), n, cs);
1475                native_mmvq(wo->native_type, wo->native_data, xq_, bo_ + tb * N, (int) (NH * HD), (int) N, n, cs);
1476            }
1477        } catch (const std::exception& e) {
1478            err = "verify layer " + std::to_string(l) + ": " + e.what();
1479            return false;
1480        }
1481        stamp(l, 16, grp);
1482        const bool q8_ffn = gr_read_group(1, true, inj_, inj2_);   // true: nat_xq_ holds the MoE input's q8_1 (STRATA_QFUSE)
1483        // with CPU experts in the window the shared expert forks off once the doorbell is published (it no longer
1484        // competes with it for the GPU's first microseconds); STRATA_SH_FORK_LATE=0 forks at the top as before
1485        static const bool sh_fork_late_env = [] {
1486            const char* e = std::getenv("STRATA_SH_FORK_LATE");
1487            return !e || e[0] != '0';
1488        }();
1489        const bool sh_fork = sh_stream_on() && !prof_on_ && !g_stepped &&
1490                             sh_cs_ != &dpct::get_in_order_queue() &&
1491                             ev_fork_ != nullptr && ev_join_ != nullptr;
1492        const bool sh_fork_late = sh_fork && sh_fork_late_env && !ar_on();
1493        dpct::queue_ptr sh_stream = sh_fork ? sh_cs_ : cs;
1494        if (sh_fork && !sh_fork_late) {
1495            dpct::sync_barrier(ev_fork_, cs);
1496            (sh_cs_)->ext_oneapi_submit_barrier({*ev_fork_});
1497        }
1498        // the window's rows routed in 2 launches (one router GEMV reading the weight once, one
1499        // top-10) instead of 2 per token; every row's arithmetic is the single-token call's (STRATA_DEC_BATCH=0: old)
1500        const WeightRef* w_router = v.get("ffn_gate_inp.weight");
1501        // S26 STRATA_LFUSE=1: the shared expert's gate row rides in the router GEMV launch, its sigmoid + row scale
1502        // move into the combine, gate + up share one launch (all bitwise; resident combine path, 2-8 rows only)
1503        const WeightRef* w_sgi = lfuse_on(n) && g_lfuse_gate() ? v.get("ffn_gate_inp_shexp.weight") : nullptr;
1504        bool sg_ready = false;
1505        if (dec_batch && n > 1 && w_router != nullptr && native_router_enabled() && (NE == 512 || NE == 256) && K == 10) {
1506            try {   // SYCL port: the fused multi-token router for 256 experts as well (it was 512-only)
1507                if (w_sgi != nullptr)
1508                    sg_ready = bf16_gemv_fp32_mmvf_multi_aux(mixed_ + tb * N, N, (const uint16_t*) w_router->data,
1509                                                             logits_ + tb * NE, NE, N, NE, n,
1510                                                             (const uint16_t*) w_sgi->data, sh_g_ + tb, 1, cs);
1511                if (!sg_ready)
1512                bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) w_router->data, logits_ + tb * NE, NE, N,
1513                                          NE, n, cs);
1514                native_router_top10_multi_ne(logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, n, (int) NE, cs);
1515            } catch (const std::exception& e) { err = "verify router: " + std::string(e.what()); return false; }
1516#if defined(STRATA_HIP_GFX906)
1517        } else if (dec_batch) {
1518            // gfx906: the Coder's 256-expert router (the native router is 512 x 10 only) for the whole window in one
1519            // multi-column BF16 projection and one top-k, bitwise the per-token calls (route_window_parity); ~3 ms
1520            // of a ~55 ms verify window on 2x MI50.  STRATA_ROUTE_PER_TOKEN=1: the per-token calls.
1521            if (!moe_route_window(wt, g, l, K, ss.moe, mixed_ + tb * N, logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, n,
1522                                  cs, err))
1523                return false;
1524#endif
1525        } else
1526        for (int t = tb; t < te; ++t) {
1527            MoEBuffers mb = ss.moe;
1528            mb.logits = logits_ + t * NE; mb.ids = ids_ + t * K; mb.weights = w_ + t * K;
1529            if (!moe_route(wt, g, l, K, mb, mixed_ + t * N, cs, err, nullptr)) return false;
1530        }
1531        if (expert_usage_counts_d_)
1532            count_expert_routes(cs, ids_ + tb * K, (int)(n * K), (int)l,
1533                                (int)g.n_expert, expert_usage_counts_d_);
1534        if (ar_on()) {
1535            resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert,
1536                          hits_.cache_base, slot_off_d_, (long long) hits_.blob,
1537                          plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, nullptr, 0, cs, m_plan_err_);
1538        } else {
1539            if (device_plan_)   // E-6: every routed expert resident: this group's plan without the host
1540                resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert,
1541                              hits_.cache_base, slot_off_d_, (long long) hits_.blob,
1542                              plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, skip_ + grp,
1543                              (uint32_t) ((l - lb_) * G + grp + 1), cs);
1544#if defined(STRATA_USE_HIP)
1545            if (g_doorbell_store)   // #649 A/B: the step's ring stored, not incremented over PCIe
1546                doorbell_publish_value(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N,
1547                                       m_ids_ + tb * K, m_w_ + tb * K, m_seq_, (uint32_t) ((l - lb_) * G + grp + 1), cs);
1548            else
1549#endif
1550            // #578: the helper GPUs reduce with the routing weights - publish them; set_always_publish: the rows
1551            // whatever the device's residency table says (pipelined windows)
1552            if (remote_opt_ || always_publish_)
1553                doorbell_publish(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N,
1554                                 m_ids_ + tb * K, m_w_ + tb * K, m_seq_, cs);
1555            else if (!lean) {   // (lean: nobody reads the doorbell)
1556                const int32_t* layer_res = hits_.d_res != nullptr ? (hits_.d_res + l * g.n_expert) : nullptr;
1557                doorbell_publish_res(xm, ids_ + tb * K, layer_res, (int) g.n_expert, (int64_t) n * N, (int64_t) n * K,
1558                                     m_x_ + tb * N, m_ids_ + tb * K, m_seq_, cs);
1559            }
1560            if (sh_fork_late) {
1561                dpct::sync_barrier(ev_fork_, cs);
1562                (sh_cs_)->ext_oneapi_submit_barrier({*ev_fork_});
1563            }
1564            if (step_hook_ && !step_hook_(l, grp)) { if (err.empty()) err = "verify: stepped serve failed"; return false; }
1565        }
1566        stamp(l, 17, grp);
1567        bool qdedup = false;   // STRATA_VERIFY_QDEDUP took effect: the experts' q8_1 image of xm is already made
1568        {
1569            const WeightRef *wgi = need(v, "ffn_gate_inp_shexp.weight", err), *wsg = need(v, "ffn_gate_shexp.weight", err),
1570                            *wsu = need(v, "ffn_up_shexp.weight", err), *wsd = need(v, "ffn_down_shexp.weight", err);
1571            if (!wgi || !wsg || !wsu || !wsd) return false;
1572            if (!native_of(wsg, v.name("ffn_gate_shexp.weight"), err) || !native_of(wsu, v.name("ffn_up_shexp.weight"), err) ||
1573                !native_of(wsd, v.name("ffn_down_shexp.weight"), err))
1574                return false;
1575            NativeSharedWeights nsw;
1576            nsw.gate_type = wsg->native_type; nsw.gate_data = wsg->native_data;
1577            nsw.up_type = wsu->native_type; nsw.up_data = wsu->native_data;
1578            nsw.down_type = wsd->native_type; nsw.down_data = wsd->native_data;
1579            nsw.q8_1 = sh_fork ? sh_xq_ : xq_;
1580            // STRATA_VERIFY_QDEDUP=1 (not with the forked shared-expert stream, which quantizes into its own buffer): the
1581            // experts' q8_1 image of xm is made first and the shared expert's gate/up read it (quantize_q8_1_rows and
1582            // native_quantize_q8_1 write the same bytes)
1583            qdedup = g_qdedup() && !sh_fork && strata::kernels::cpu::expert_layout().native;
1584            if (qdedup && !q8_ffn) quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs);
1585            if (!shared_expert_native_bf16_enabled()) {
1586                if (dec_batch) f32_to_bf16_bulk(mixed_ + tb * N, sh_bf16_ + tb * N, (int64_t) n * N, sh_stream);   // contiguous rows
1587                else for (int t = tb; t < te; ++t) f32_to_bf16_bulk(mixed_ + t * N, sh_bf16_ + t * N, N, sh_stream);
1588            }
1589            try {
1590                shared_expert_multi(n, xm, sh_bf16_ + tb * N, nsw, (const uint16_t*) wgi->data, sh_gate_ + (size_t) tb * g.n_ff,
1591                                    sh_up_ + (size_t) tb * g.n_ff, sh_g_ + tb, shared_ + tb * N, N, g.n_ff, sh_stream,
1592                                    qdedup ? (const void*) (nat_xq_ + (size_t) tb * (N / 32) * 36) : nullptr,
1593                                    (sg_ready ? 1 : 0) | (lfuse_on(n) && g_lfuse_pair() ? 2 : 0));
1594                sg_gated_[grp] = sg_ready;
1595            } catch (const std::exception& e) {
1596                err = std::string("verify shared expert: ") + e.what();
1597                return false;
1598            }
1599            if (sh_fork) dpct::sync_barrier(ev_join_, sh_cs_);
1600        }
1601        if (strata::kernels::cpu::expert_layout().native) {
1602            // APR: Hadamard-folded gate/up take H (s * x); xm itself stays as it is (the shared expert above and the
1603            // doorbell copy for the CPU pool, which rotates its own in native_quant_act). The q8_1 image of xm that
1604            // STRATA_QFUSE / STRATA_VERIFY_QDEDUP may already have written is of the unrotated input, so a folded layer
1605            // always rewrites it from the rotated rows (same stream, after the shared expert has read it).
1606            const auto& f = strata::kernels::cpu::expert_layout().fmt[(size_t) l];
1607            if (f.had_gu) {   // nat_xr_ exists: init carved it because this layer is folded (had_gu_any)
1608                hadamard_rows(xm, nat_xr_ + (size_t) tb * N, n, N, f.had_block, had_sx_, cs);
1609                quantize_q8_1_rows(nat_xr_ + (size_t) tb * N, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs);
1610            } else if (!qdedup && !q8_ffn) {
1611                quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs);
1612            }
1613        } else
1614            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);
1615        stamp(l, 18, grp);
1616        return true;
1617    };
1618
1619    // ---------------------------------------------------------------- post(l, group): experts, combine
1620    static const bool fuse_head_gr_env = [] {
1621        const char* e = std::getenv("STRATA_FUSE_HEAD_GR");
1622        return e && e[0] == '1';
1623    }();
1624    const bool fuse_head_gr = fuse_head_gr_env && (le_ == g.n_layers) && (head_ != nullptr && head_->loaded()) &&
1625                              !cvec().covers(g.n_layers - 1);
1626    auto post = [&](int64_t l, int grp) -> bool {
1627        const int tb = tb_[grp], te = te_[grp], n = te - tb;
1628#ifdef STRATA_SYCL_WORKLOAD_TRACE
1629        strata::workload_trace::ContextGuard layer_context(strata::workload_trace::context.position, n, l);
1630#endif
1631        strata::workload_trace::Scope layer_trace("decode.layer.post", cs, n, N);
1632        const uint32_t ring = (uint32_t) ((l - lb_) * G + grp + 1);
1633        const int64_t cap = (int64_t) n * K, capx = (int64_t) max_t_ * K;
1634        int32_t* pl = plan_ + (size_t) grp * (size_t) (plan_i32_ + 16);
1635        const int32_t* p_counts = pl;
1636        const int32_t* p_start = pl + 4;
1637        const int32_t* p_dst = p_start + capx + 1;
1638        const int32_t* p_tok = p_dst + capx;
1639        const int64_t ptr_off = ((4 + (capx + 1) + 2 * capx) + 1) & ~1ll;
1640        const unsigned long long* p_ptr = (const unsigned long long*) (pl + ptr_off);
1641        const unsigned long long* p_ptr2 = p_ptr + capx;
1642        const int32_t* p_start2 = pl + ptr_off + 4 * capx;
1643        float* hit_out = hit_out_ + (size_t) tb * K * N;
1644        float* parts_out = parts_ + (size_t) tb * K * N;
1645        const auto& lay = strata::kernels::cpu::expert_layout();
1646        // plan v0.3 P6: the VRAM groups now; the PCIe groups once the copy engine has landed them in staging.
1647        // `gy`: the native launch's groups side by side (0: cap, one block row per possible group).
1648        auto grouped = [&](const unsigned long long* gp, const int32_t* gs, const int32_t* gn, int64_t gy, float* dst_buf) {
1649            if (lay.native) {
1650                // the layer's GGUF formats (i-quant gate/up, Q2_0 / IQ4_NL down)
1651                const auto& f = lay.fmt[(size_t) l];
1652                NativeExpertLayout L = native_expert_layout(f.gu_type, f.d_type, f.n_embd, f.n_ff);
1653                if (f.had_d) { L.had_block = f.had_block; L.d_signs = had_sh_; }   // APR: h is rotated in there
1654                if(b60_single_actor_requested()&&b60_layout_requested()){
1655                    if(!lean||gy!=0)throw std::logic_error("B60 single staging needs the complete device plan");
1656                    b60_stage_single_experts(const_cast<unsigned long long*>(gp),gn,int(cap),f.gu_type,size_t(f.up_off),size_t(f.down_off),size_t(f.bytes),cs);
1657                }
1658                if (!b60_layout_requested() && gy == 0 && device_plan_ && env_on("STRATA_VERIFY_NO_HOST") &&
1659                    env_on("STRATA_SYCL_EXPERT_STAGE")) {
1660                    // NoHost device planning leaves no CPU/DMA owner of this existing workspace.
1661                    const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs;
1662                    uint8_t* stage = staging_ + (size_t)(grp * per) * lay.max_blob;
1663                    const char* batch_env = std::getenv("STRATA_SYCL_EXPERT_STAGE_GROUPS");
1664                    const char* copy_env = std::getenv("STRATA_SYCL_EXPERT_STAGE_COPY");
1665                    native_expert_grouped_staged(L,gp,gs,gn,p_dst,p_tok,cap,cap,
1666                        nat_xq_ + (size_t)tb * (N / 32) * 36,hit_scratch_,dst_buf,cs,
1667                        stage,(size_t)per * lay.max_blob,batch_env ? std::atoi(batch_env) : 8,
1668                        copy_env ? std::atoi(copy_env) : 0);
1669                } else {
1670                    native_expert_grouped(L, gp, gs, gn, p_dst, p_tok, cap, cap,
1671                                          nat_xq_ + (size_t) tb * (N / 32) * 36, hit_scratch_, dst_buf, cs, gy);
1672                }
1673            } else {
1674                moe_grouped_s2(gp, gs, gn, p_dst, p_tok, cap, cap, hit_xq_ + (size_t) tb * (N / 32) * 34,
1675                               hit_xs_ + (size_t) tb * (N / 32), hit_scratch_, dst_buf, cs);
1676            }
1677        };
1678        if (ar_on()) {
1679            stamp(l, 19, grp);
1680            grouped(p_ptr, p_start, p_counts, 0, parts_out);
1681            stamp(l, 20, grp);
1682        } else {
1683            if (device_plan_) {   // E-6: skipped when the device planned this group (all its experts resident)
1684                if (!lean) wait_flag_ge_or(m_flagA_, ring, skip_ + grp, cs);
1685                if (!lean) copy_i32_from_mapped_unless(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, skip_ + grp, ring, cs);
1686            } else {
1687                wait_flag_ge(m_flagA_, ring, cs);                  // the pool published this group's GPU plan
1688                copy_i32_from_mapped(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs);
1689            }
1690            stamp(l, 19, grp);
1691            grouped(p_ptr, p_start, p_counts, 0, hit_out);
1692            stamp(l, 20, grp);
1693            // stepped mode: the plan copy + VRAM groups end a segment, so they run while the CPU computes its rows
1694            if (step_hook2_ && !step_hook2_(l, grp)) { if (err.empty()) err = "verify: stepped split failed"; return false; }
1695            if (device_plan_) { if (!lean) wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs); }
1696            else wait_flag_ge(m_flagB_, ring, cs);                 // the PCIe share is in staging (DMA) or mapped
1697            if (!lean && sink_.pcie_mode == 2) {                 // stage it with a copy kernel, then point at staging
1698                const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs;
1699                uint8_t* stage = staging_ + (size_t) (grp * per) * lay.max_blob;
1700                fetch_blobs(p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), (int) per, cs);
1701                rebase_ptrs((unsigned long long*) p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), cs);
1702            }
1703            stamp(l, 21, grp);
1704            // the PCIe share is pcie_frac of the misses: a few groups when the cache is cold, usually none (always none at
1705            // pcie_frac 0), so its launch is kPcieGroupRows block rows striding over the groups, not cap of them
1706            if (!lean) grouped(p_ptr2, p_start2, p_counts + 2, kPcieGroupRows, hit_out);   // (lean: the device plan leaves it empty)
1707            stamp(l, 22, grp);
1708            if (device_plan_) {   // no CPU share when the device planned the group: its rows are zeros
1709                if (!lean) wait_flag_ge_or(m_flag_, ring, skip_ + grp, cs);
1710                copy_or_zero_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (long long) n * K * N,
1711                                         skip_ + grp, ring, cs);
1712            } else {
1713                wait_flag_ge(m_flag_, ring, cs);               // the CPU's share is in the mapped rows
1714                stamp(l, 23, grp);
1715                if (remote_opt_)   // #578: the helper's rows come back reduced; skip them as well
1716                    remote_opt_->copy_rows(parts_out, m_ymiss_ + (size_t) tb * K * N, tb, n, p_dst, p_counts + 1, cs);
1717                else if (dec_batch)   // only the CPU rows cross PCIe (p_dst[0, counts[1]) = the GPU's own rows)
1718                    copy_rows_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K, N,
1719                                          p_dst, p_counts + 1, cs);
1720                else
1721                    copy_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K * N, cs);
1722            }
1723            moe_hit_add(parts_out, hit_out, p_dst, p_counts + 1, cap, N, cs);
1724        }
1725        // Same condition as `sh_fork` above, which is per group and out of scope here: wait only when the fork
1726        // actually ran (a wait on an event never recorded is a no-op, but saying it outright reads better).
1727        if (sh_stream_on() && !prof_on_ &&
1728            sh_cs_ != &dpct::get_in_order_queue() && ev_fork_ != nullptr &&
1729            ev_join_ != nullptr) {
1730            cs->ext_oneapi_submit_barrier({*ev_join_});
1731        }
1732        if (sg_gated_[grp]) {   // STRATA_LFUSE: the shared expert's gate was not applied: the combine applies it (all rows are hits)
1733            try {
1734                native_moe_combine_multi_hits_gated(parts_out, w_ + tb * K, shared_ + tb * N, sh_g_ + tb, bo_ + tb * N, N, K, n, cs);
1735            } catch (const std::exception& e) { err = "verify combine: " + std::string(e.what()); return false; }
1736        } else
1737        if (dec_batch && n > 1 && native_moe_combine_enabled()) {   // one launch for the window's rows
1738            try {
1739                native_moe_combine_multi(parts_ + (size_t) tb * K * N, w_ + tb * K, shared_ + tb * N, bo_ + tb * N, N, K, n, cs);
1740            } catch (const std::exception& e) { err = "verify combine: " + std::string(e.what()); return false; }
1741        } else
1742        for (int t = tb; t < te; ++t) {
1743            MoEBuffers mb = ss.moe;
1744            mb.weights = w_ + t * K; mb.shared = shared_ + t * N;
1745            if (!moe_combine_parts(g, l, K, mb, parts_ + (size_t) t * K * N, bo_ + t * N, cs, err)) return false;
1746        }
1747        if (remote_opt_) remote_opt_->combine(bo_ + tb * N, y_dummy_ + tb * N, tb, n,
1748                              device_plan_ ? skip_ + grp : nullptr, ring, cs);
1749        stamp(l, 24, grp);
1750        if (tap_on_ && !batch_rec_ && l < (int64_t) tap_slot_.size() && tap_slot_[(size_t) l] >= 0) {
1751            // the layer's completed output: R with this FFN half's write applied (the next layer's read would fold it), the mean of the hc streams,
1752            // all rows of the group in one launch
1753            const int64_t nt = (int64_t) tap_layers_.size();
1754            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,
1755                                        nt * N, n, N, (int) HC, cs);
1756        }
1757#ifdef STRATA_SYCL_WORKLOAD_TRACE
1758        if (auto audit = routing_audits.find(this); audit != routing_audits.end())
1759            cs->memcpy(audit->second->slot(l, grp), pl, (size_t)plan_i32_ * sizeof(int32_t));
1760#endif
1761        if (l == g.n_layers - 1) {
1762            if (!fuse_head_gr) {
1763                if (dec_batch && !g_no_multi_gr) gr_write_multi(Rt(tb), bo_ + tb * N, inj2_ + tb * HC, gs, Rt(tb), n, cs);
1764                else for (int t = tb; t < te; ++t) gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs);
1765                if (cvec().covers(l)) cvec_apply(Rt(tb), l, n, HC * N, nullptr, 0, nullptr, 0, false, cs);
1766            }
1767        } else if (cvec().covers(l)) {
1768            cvec_apply(Rt(tb), l, n, HC * N, bo_ + tb * N, N, inj2_ + tb * HC, HC, true, cs);
1769        }
1770        return true;
1771    };
1772
1773    for (int grp = 0; grp < G; ++grp)
1774        if (!pre(lb_, grp)) return false;
1775    for (int64_t l = lb_; l < le_; ++l)
1776        for (int grp = 0; grp < G; ++grp) {
1777            if (!post(l, grp)) return false;
1778            if (dbgR_ && grp == 0) {   // recorded into the window graph as memcpy nodes
1779                cs->memcpy(dbgR_ + (size_t) l * N, Rt(0), (size_t) N * 4);
1780                cs->memcpy(dbgM_ + (size_t) l * N, mixed_, (size_t) N * 4);
1781            }
1782            if (l + 1 < le_ && !pre(l + 1, grp)) return false;
1783        }
1784    if (le_ < g.n_layers) {   // a layer split's earlier stage: hand the residual on, no head
1785        float* hout = hand_out_ + (size_t) hrow0 * HB;
1786        copy_from_mapped(hout, R_, (int64_t) T * HC * N, cs);
1787        copy_from_mapped(hout + (size_t) T * HC * N, bo_, (int64_t) T * N, cs);
1788        copy_from_mapped(hout + (size_t) T * (HC + 1) * N, inj2_, (int64_t) T * HC, cs);
1789        return true;
1790    }
1791
1792    // ---- the head, T columns, and the argmax of each
1793    stamp(g.n_layers, 0, 0);
1794    {
1795        const WeightRef *hn = wt.find("output_hc_norm.weight"), *hd = wt.find("output_hc_down.weight"),
1796                        *hu = wt.find("output_hc_up.weight");
1797        if (!hn || !hd || !hu) { err = "verify: an output_hc_* weight is missing"; return false; }
1798        // S25 (STRATA_HC_Q8=1): the final mixer from the GGUF's Q8_0 projections too, through the same multi read
1799        // (no pending write, no inject)
1800        bool b60_head_q8=false;
1801        const bool mix_q8 = hd->hc_q8 != nullptr && hu->hc_q8 != nullptr && head_ != nullptr && head_->loaded();
1802        if (mix_q8) {
1803            FusedGrArgs fa[kFusedGrMaxT];
1804            for (int t = 0; t < T; ++t) {
1805                FusedGrArgs& a = fa[t];
1806                a.R = Rt(t); a.R_out = Rt(t); a.apply = false;
1807                a.w_norm = (const float*) hn->data; a.w_down = (const uint16_t*) hd->data;
1808                a.w_up = (const uint16_t*) hu->data; a.w_inject = nullptr;
1809                a.q8_down = (const uint8_t*) hd->hc_q8; a.q8_up = (const uint8_t*) hu->hc_q8;
1810                a.eps = EPS; a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC;
1811                a.mixed = head_mixed_ + t * N; if(b60_gr_q8_requested() && T==1)a.q8_mixed=xq_+size_t(t)*(N/32)*36;
1812            }
1813            b60_head_q8=fused_gr_read_multi(fa, T, xn_, cs);
1814        }
1815        else if (fuse_head_gr) {
1816            FusedGrArgs fa[kFusedGrMaxT];
1817            for (int t = 0; t < T; ++t) {
1818                FusedGrArgs& a = fa[t];
1819                a.R = Rt(t); a.R_out = Rt(t); a.apply = true;
1820                a.bo_prev = bo_ + t * N; a.inj_prev = inj2_ + t * HC;
1821                a.w_norm = (const float*) hn->data;
1822                a.w_down = (const uint16_t*) hd->data;
1823                a.w_up = (const uint16_t*) hu->data;
1824                a.w_inject = nullptr;
1825                a.eps = EPS;
1826                a.lo = lo_ + t * g.hc_lr;
1827                a.rs = rs_ + t * HC;
1828                a.inject_out = head_inj_;
1829                a.mixed = head_mixed_ + t * N; if(b60_gr_q8_requested() && T==1)a.q8_mixed=xq_+size_t(t)*(N/32)*36;
1830            }
1831            b60_head_q8=fused_gr_read_multi(fa, T, xn_, cs);
1832        } else if (head_mix_multi_enabled() && head_ != nullptr && head_->loaded()) {
1833            // the final mixer, the window's tokens in one read (fused_gr_read_multi without the pending write: the
1834            // last layer's write was done above; its sums are gr_read's)
1835            if (hn->kind != WeightKind::F32 || hd->kind != WeightKind::Bf16InF32 || hu->kind != WeightKind::Bf16InF32) {
1836                err = "verify: the output_hc_* weights have the wrong engine forms";
1837                return false;
1838            }
1839            FusedGrArgs fa[kFusedGrMaxT];
1840            for (int t = 0; t < T; ++t) {
1841                fa[t].R = Rt(t); fa[t].R_out = Rt(t); fa[t].apply = false;
1842                fa[t].w_norm = (const float*) hn->data; fa[t].w_down = (const uint16_t*) hd->data;
1843                fa[t].w_up = (const uint16_t*) hu->data; fa[t].eps = EPS;
1844                fa[t].lo = lo_ + t * g.hc_lr; fa[t].rs = rs_ + t * HC; fa[t].mixed = head_mixed_ + t * N; if(b60_gr_q8_requested() && T==1)fa[t].q8_mixed=xq_+size_t(t)*(N/32)*36;
1845            }
1846            b60_head_q8=fused_gr_read_multi(fa, T, xn_, cs);
1847        } else {
1848            for (int t = 0; t < T; ++t) {
1849                BlockBuffers bb = ss.block;
1850                bb.R = Rt(t);
1851                bb.mixed = head_mixed_ + t * N;
1852                if (head_ != nullptr && head_->loaded()) {
1853                    if (!lm_head_mix(wt, g, bb, cs, err)) return false;
1854                } else if (!lm_head(wt, g, bb, head_logits_ + (size_t) t * n_vocab_, cs, err)) {
1855                    return false;
1856                }
1857            }
1858        }
1859        if (head_ != nullptr && head_->loaded()) {
1860            try {
1861                if(!b60_head_q8)native_quantize_q8_1(head_mixed_, xq_, (int) N, T, cs);
1862                native_mmvq(head_->type(), head_->weights(), xq_, head_logits_, (int) N, (int) n_vocab_, T, cs);
1863            } catch (const std::exception& e) {
1864                err = std::string("verify head: ") + e.what();
1865                return false;
1866            }
1867        }
1868        // Greedy, the default, is recorded here as before (no extra launch or sync per window). A request that
1869        // samples or penalizes is sampled again host-side after the replay (run()) with its own parameters and a
1870        // fresh draw counter: a captured sampler would bake them in and replay the same draws forever.
1871        if (argmax_rows_wanted()) {   // sm_80 to sm_89: the pick over many blocks a row (bitwise the one-block kernel's)
1872            argmax_rows(head_logits_, T, (int) n_vocab_, arg_scratch_, m_out_, cs);
1873        } else {
1874            SamplerParams sp;
1875            sp.greedy = true;
1876            sp.temperature = 0.0f;
1877            sample_tokens(head_logits_, T, (int) n_vocab_, nullptr, 0, sp, m_out_, cs);
1878        }
1879    }
1880    stamp(g.n_layers, 1, 0);
1881    return true;
1882}
1883
1884// SYCL port: a failed queue wait reported as what it was.  DPCT_CHECK_ERROR keeps only "error" from the SYCL
1885// exception and drops the device, which made a pipelined-window failure on a layer split impossible to place:
1886// the same text came from either card and from any of the four verifiers.  These two helpers say which.
1887static dpct::err0 queue_wait_diag(sycl::queue *cs, int dev, const char *what) {
1888    if (cs == nullptr) return dpct::default_error;
1889    try {
1890        cs->wait();
1891        return dpct::success;
1892    } catch (std::exception const &e) {
1893        std::string qdev = "<unknown>";
1894        try { qdev = cs->get_device().get_info<sycl::info::device::name>(); } catch (...) {}
1895        std::fprintf(stderr, "strata verify: %s: the queue wait failed on verifier device %d (queue device: %s): %s\n",
1896                     what, dev, qdev.c_str(), e.what());
1897        std::fflush(stderr);
1898        return dpct::default_error;
1899    }
1900}
1901
1902std::string Verifier::profile_report() {
1903    if (!prof_on_ || prof_windows_ == 0) return std::string();
1904    static const char* names[kProfPer] = {"-", "hc-read0", "q8+qkv/q-idx gemv", "conv", "ab", "z", "rec", "q8+kv-idx",
1905                                          "k/v+norm-rope", "kv+idx append", "q+q-idx", "scores+topk", "kv-resolve",
1906                                          "attention", "gate", "", "out-proj", "hc-read1+router", "shared+quant",
1907                                          "waitA", "VRAM hits", "waitB", "PCIe grp", "waitCPU", "copy+combine",
1908                                          "(gap)", "head", "  hc0 norm", "  hc0 down", "  hc0 up", "", "", ""};
1909    std::string out;
1910    char b[80];
1911    double total = 0;
1912    for (int k = 0; k < 2; ++k) {
1913        out += k == 0 ? " GDN layers:" : " | QSA layers:";
1914        for (int i = 0; i < kProfPer; ++i) {
1915            if (prof_sum_[k][i] <= 0) continue;
1916            total += prof_sum_[k][i];
1917            std::snprintf(b, sizeof b, " %s %.2f", names[i], prof_sum_[k][i] / 1e6 / (double) prof_windows_);
1918            out += b;
1919        }
1920    }
1921    std::snprintf(b, sizeof b, " | total %.2f ms/window over %lld windows", total / 1e6 / (double) prof_windows_, (long long) prof_windows_);
1922    out += b;
1923    for (auto& r : prof_sum_) for (double& d : r) d = 0;
1924    prof_windows_ = 0;
1925    return out;
1926}
1927
1928// #871: is the zero-doorbell graph right for the next window?  Only while every expert of [lb_, le_) is in VRAM now
1929// (the host table is the one the device copy was uploaded from; a loan, a VRAM shrink or a swap in flight has
1930// marked some -1).  Not: the doorbell graph, which asks the pool for what the device does not hold.
1931void Verifier::refresh_ar() {
1932    if (!all_resident_ || h_res_ == nullptr || g_ == nullptr) return;
1933    const int64_t ne = g_->n_expert;
1934    const int32_t* r = h_res_ + lb_ * ne;
1935    const int64_t n = (le_ < 0 ? g_->n_layers : le_) * ne - lb_ * ne;
1936    int32_t lo = 0;
1937    for (int64_t i = 0; i < n; ++i) lo = std::min(lo, r[i]);
1938    const bool off = lo < 0;
1939    if (off != ar_off_) {
1940        ar_off_ = off;
1941        std::fprintf(stderr, "strata verify: layers [%lld, %lld) %s\n", (long long) lb_, (long long) (le_ < 0 ? g_->n_layers : le_),
1942                     off ? "have experts out of VRAM (a prompt loan, a shrink or a swap): the doorbell graph runs the windows"
1943                         : "are 100% VRAM resident again: the zero-doorbell graph");
1944    }
1945}
1946
1947bool Verifier::capture_segments(int T, std::string& err) try {
1948    if (!seg_[T].empty()) return true;
1949    // every segment's payload is read after the segment drained: its publishes store plainly (elementwise.dp.cpp)
1950    struct PlainPayload {
1951        PlainPayload() { strata::kernels::doorbell_plain_payload(!window_host_uncached()); }
1952        ~PlainPayload() { strata::kernels::doorbell_plain_payload(false); }
1953    } plain_payload;
1954    namespace sx = sycl::ext::oneapi::experimental;
1955    auto close_segment = [&]() -> bool {
1956        dpct::experimental::command_graph_ptr gph = nullptr;
1957        dpct::experimental::end_recording(cs_, &gph);
1958        if (gph == nullptr) { err = "verify: segment capture produced no graph"; return false; }
1959        seg_[T].push_back(new sx::command_graph<sx::graph_state::executable>(gph->finalize()));
1960        delete gph;
1961        return true;
1962    };
1963    auto boundary = [&](int64_t l, int grp, char kind) -> bool {
1964        if (!close_segment()) return false;
1965        seg_at_[T].push_back({l, grp});
1966        seg_kind_[T].push_back(kind);
1967        dpct::experimental::begin_recording(cs_);
1968        return true;
1969    };
1970    dpct::experimental::begin_recording(cs_);
1971    step_hook_ = [&](int64_t l, int grp) { return boundary(l, grp, 1); };
1972    static const bool split_on = [] { const char* e = std::getenv("STRATA_VERIFY_SPLIT"); return !(e && e[0] == '0'); }();
1973    if (split_on) step_hook2_ = [&](int64_t l, int grp) { return boundary(l, grp, 0); };
1974    std::string rerr;
1975    const bool ok = record_window(T, cs_, rerr);
1976    step_hook_ = nullptr;
1977    step_hook2_ = nullptr;
1978    const bool closed = close_segment();
1979    if (!ok || !closed) {
1980        for (auto* e : seg_[T]) delete e;
1981        seg_[T].clear(); seg_at_[T].clear(); seg_kind_[T].clear();
1982        if (err.empty()) err = "verify: segment capture: " + rerr;
1983        return false;
1984    }
1985    if (std::getenv("STRATA_VERIFY_NODES") != nullptr)
1986        std::fprintf(stderr, "strata verify: the %d-token window as %zu graph segments\n", T, seg_[T].size());
1987    return true;
1988}
1989catch (sycl::exception const& exc) {
1990    err = std::string("verify: segment capture: ") + exc.what();
1991    return false;
1992}
1993
1994bool Verifier::capture(int T, std::string &err) try {
1995    // stepped mode: the doorbell window as segments; the all-resident (zero-doorbell) graph has no serves and is
1996    // captured whole below, its one host flag raised before launch (run)
1997    if (g_stepped && !ar_on() && std::getenv("STRATA_VERIFY_EAGER") == nullptr) return capture_segments(T, err);
1998    dpct::experimental::command_graph_exec_ptr &exec_t =
1999        ar_off_ ? exec_nr_[T] : exec_[T];
2000    if (exec_t != nullptr) return true;
2001    if (std::getenv("STRATA_VERIFY_EAGER") != nullptr) return true;   // SYCL port: no graph, run() replays the body
2002    if (DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs_)) != 0) {
2003        err = "verify: begin capture failed";
2004        return false;
2005    }
2006    std::string rerr;
2007    const bool ok = record_window(T, cs_, rerr);
2008    dpct::experimental::command_graph_ptr graph = nullptr;
2009    const dpct::err0 ce =
2010        DPCT_CHECK_ERROR(dpct::experimental::end_recording(cs_, &graph));
2011    if (!ok) {
2012        if (graph) delete (graph);
2013        err = rerr;
2014        return false;
2015    }
2016    /*
2017    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
2018    */
2019    if (ce != 0) {
2020        /*
2021        DPCT1009: SYCL reports errors using exceptions and does not use error
2022        codes. Please replace the "get_error_string_dummy(...)" with a real
2023        error-handling function.
2024        */
2025        /*
2026        DPCT1001: The statement could not be removed.
2027        */
2028        err = std::string("verify: end capture: ") +
2029              dpct::get_error_string_dummy(ce);
2030        return false;
2031    }
2032    if (std::getenv("STRATA_VERIFY_NODES") != nullptr) {   // what the window graph holds
2033        size_t nn = 0;
2034        dpct::experimental::get_nodes(graph, nullptr, &nn);
2035        std::vector<dpct::experimental::node_ptr> nodes(nn);
2036        dpct::experimental::get_nodes(graph, nodes.data(), &nn);
2037        std::map<std::string, int> kinds;
2038        for (dpct::experimental::node_ptr nd : nodes) {
2039            sycl::ext::oneapi::experimental::node_type ty;
2040            ty = nd->get_type();
2041            std::string name = "type" + std::to_string((int) ty);
2042            if (ty == sycl::ext::oneapi::experimental::node_type::kernel) {
2043                name = "kernel";   // SYCL: no kernel-name introspection on graph nodes
2044            } else if (ty == sycl::ext::oneapi::experimental::node_type::memcpy)
2045                name = "memcpy";
2046            else if (ty == sycl::ext::oneapi::experimental::node_type::memset)
2047                name = "memset";
2048            ++kinds[name];
2049        }
2050        std::vector<std::pair<int, std::string>> v;
2051        for (auto& [k2, c] : kinds) v.push_back({c, k2});
2052        std::sort(v.rbegin(), v.rend());
2053        std::fprintf(stderr, "strata verify: the %d-token window graph has %zu nodes:", T, nn);
2054        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());
2055        std::fprintf(stderr, "\n");
2056    }
2057    const dpct::err0 ie = DPCT_CHECK_ERROR(
2058        exec_t = new sycl::ext::oneapi::experimental::command_graph<
2059            sycl::ext::oneapi::experimental::graph_state::executable>(
2060            graph->finalize()));
2061    delete (graph);
2062    /*
2063    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
2064    */
2065    if (ie != 0) {
2066        /*
2067        DPCT1009: SYCL reports errors using exceptions and does not use error
2068        codes. Please replace the "get_error_string_dummy(...)" with a real
2069        error-handling function.
2070        */
2071        /*
2072        DPCT1001: The statement could not be removed.
2073        */
2074        err = std::string("verify: instantiate: ") +
2075              dpct::get_error_string_dummy(ie);
2076        return false;
2077    }
2078    /*
2079    DPCT1007: Migration of cudaGraphUpload is not supported.
2080    */
2081    const dpct::err0 ue = 0;   // no cudaGraphUpload on SYCL: a finalized command_graph is already resident
2082    const dpct::err0 us = DPCT_CHECK_ERROR(cs_->wait());
2083    std::fprintf(
2084        stderr,
2085        "strata verify: captured the %d-token window (upload %s, sync %s)\n", T,
2086        /*
2087        DPCT1009: SYCL reports errors using exceptions and does not use error
2088        codes. Please replace the "get_error_string_dummy(...)" with a real
2089        error-handling function.
2090        */
2091        dpct::get_error_string_dummy(ue), dpct::get_error_string_dummy(us));
2092    return true;
2093}
2094catch (sycl::exception const &exc) {
2095  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2096            << ", line:" << __LINE__ << std::endl;
2097  std::exit(1);
2098}
2099
2100bool Verifier::capture_commit(std::string &err) try {
2101    if (commit_exec_ != nullptr) return true;
2102    using namespace strata::kernels;
2103    const ModelGeometry& g = *g_;
2104    SessionState& ss = *ss_;
2105    const QsaShapes s = shapes_of(g);
2106    const int64_t C = g.ssm_conv_channels, HV = g.ssm_v_heads, ID = g.idx_key_dim, MT = max_t_;
2107    const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +
2108                                (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);
2109    const int64_t TS = (s.idx_block - 1) * ID;
2110    const int64_t HS = (int64_t) NG_HIST * NG_HC_DIM;
2111    if (DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs_)) != 0) {
2112        err = "verify: begin commit capture failed";
2113        return false;
2114    }
2115    bool ok = true;
2116    try {
2117        copy_i32_from_mapped(commit_, m_commit_, 2 + MT, cs_);
2118        int64_t qsa_index = 0, gdn_index = 0;
2119        for (int64_t l = 0; l < lb_; ++l) (is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1;
2120        for (int64_t l = lb_; l < le_ && ok; ++l) {
2121            const LayerView v(*wt_, l);
2122            if (!is_qsa_layer(g, l)) {
2123                const WeightRef* wnm = need(v, "ssm_norm.weight", err);
2124                if (!wnm) { ok = false; break; }
2125                float* state = ss.gdn_state + (size_t) (gdn_index - ss.gdn_ord0) * gdn_floats;
2126                float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
2127                const float* qkv = qkv_L_ + (size_t) gdn_index * MT * C;
2128                gdn_conv_commit(conv, qkv, (int) C, commit_, cs_);
2129                static const bool state_only = [] { const char* e=std::getenv("STRATA_SYCL_GDN_STATE_COMMIT"); return e && e[0]=='1'; }();
2130                if(state_only)
2131                    gdn_commit_state_multi(state,h_L_+(size_t)gdn_index*MT*C,(int)C,
2132                        gate_L_+(size_t)gdn_index*MT*HV,beta_L_+(size_t)gdn_index*MT*HV,
2133                        (int)g.ssm_k_heads,(int)HV,(int)MT,commit_,cs_);
2134                else {
2135                gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C, (int) C, gate_L_ + (size_t) gdn_index * MT * HV,
2136                                    beta_L_ + (size_t) gdn_index * MT * HV, z_, (const float*) wnm->data, EPS, y_dummy_,
2137                                    (int) g.ssm_k_heads, (int) HV, (int) MT, commit_, cs_,
2138                                    (int) MT);   // S26: t_out_begin = MT - the replay's outputs (y_dummy_) are never read
2139                }
2140                ++gdn_index;
2141            } else {
2142                const QsaState& st = ss.qsa_states[qsa_index];
2143                const WeightRef* wikn = need(v, "indexer.k_norm.weight", err);
2144                if (!wikn) { ok = false; break; }
2145                copy_from_mapped(st.idx_tail, tail_snap_ + (size_t) qsa_index * TS, TS, cs_);
2146                const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};
2147                if (!g_no_batch_kv) {
2148                    native_qsa_indexer_append_steps(idx_raw_L_ + (size_t) qsa_index * MT * ID, commit_ + 2, 1, (int) MT, 0,
2149                                                    (const float*) wikn->data, EPS, ib, s, st.max_cells, rope_scaling(), cs_);
2150                } else {
2151                    for (int64_t t = 0; t < MT; ++t)
2152                        native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + t) * ID, commit_ + 2 + t, 0,
2153                                                  (const float*) wikn->data, EPS, ib, s, st.max_cells,
2154                                                  rope_scaling(), cs_);
2155                }
2156                ++qsa_index;
2157            }
2158        }
2159        if (ok && ss.ple.ready() && ple_stage()) copy_indexed(ss.ple.hist, hist_snap_, HS, commit_ + 1, HS, cs_);
2160    } catch (const std::exception& e) {
2161        err = std::string("verify commit: ") + e.what();
2162        ok = false;
2163    }
2164    dpct::experimental::command_graph_ptr graph = nullptr;
2165    const dpct::err0 ce =
2166        DPCT_CHECK_ERROR(dpct::experimental::end_recording(cs_, &graph));
2167    if (!ok) {
2168        if (graph) delete (graph);
2169        return false;
2170    }
2171    if (ce != 0 ||
2172        DPCT_CHECK_ERROR(
2173            commit_exec_ = new sycl::ext::oneapi::experimental::command_graph<
2174                sycl::ext::oneapi::experimental::graph_state::executable>(
2175                graph->finalize())) != 0) {
2176        if (graph) delete (graph);
2177        /*
2178        DPCT1009: SYCL reports errors using exceptions and does not use error
2179        codes. Please replace the "get_error_string_dummy(...)" with a real
2180        error-handling function.
2181        */
2182        err = std::string("verify: commit capture: ") +
2183              dpct::get_error_string_dummy(ce);
2184        return false;
2185    }
2186    delete (graph);
2187    return true;
2188}
2189catch (sycl::exception const &exc) {
2190  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2191            << ", line:" << __LINE__ << std::endl;
2192  std::exit(1);
2193}
2194
2195void Verifier::stage_inputs(int T, const int32_t* tokens, int64_t pos0) {
2196    using namespace strata::kernels;
2197    const ModelGeometry& g = *g_;
2198    const QsaShapes s = shapes_of(g);
2199    int32_t* const pk = h_pos_ + (size_t) max_t_ * g.n_head;
2200    int32_t* const pi = pk + (size_t) max_t_ * g.n_head_kv;
2201    for (int t = 0; t < T; ++t) {
2202        h_tok_[t] = tokens[t];
2203        qsa_step_fill(h_step_ + t * kStepCount, pos0 + t, s);
2204        const int32_t pos_t = (int32_t) (pos0 + t);
2205        for (int64_t h = 0; h < g.n_head; ++h) h_pos_[t * g.n_head + h] = pos_t;
2206        for (int64_t h = 0; h < g.n_head_kv; ++h) pk[t * g.n_head_kv + h] = pos_t;
2207        for (int64_t h = 0; h < g.idx_q_heads; ++h) pi[t * g.idx_q_heads + h] = pos_t;
2208    }
2209    *(volatile uint32_t*) h_seq_ = 0;
2210    for (int _i = 1; _i <= 8; ++_i) ((volatile uint32_t*) h_seq_)[_i] = 0;   /* + the payload tags/checksums */
2211    *(volatile uint32_t*) h_flag_ = 0;
2212    *(volatile uint32_t*) h_flagA_ = 0;
2213    *(volatile uint32_t*) h_flagB_ = 0;
2214    std::atomic_thread_fence(std::memory_order_seq_cst);
2215    last_t_ = T;
2216    last_pos0_ = pos0;
2217    for (int t = 0; t < T; ++t) last_tokens_[t] = tokens[t];
2218    staged_ = true;
2219}
2220
2221void Verifier::collect_profile() {
2222    if (std::getenv("STRATA_VERIFY_EAGER") == nullptr) {   // eager (SYCL port): prof_h_ already holds the host clocks
2223        // SYCL port: the stamps are written by kernels on THIS verifier's stream, so the readback has to ride the
2224        // same stream.  The device's default queue is neither ordered after the window nor necessarily this
2225        // stage's device (a layer split), so reading there could return the previous window's stamps or another
2226        // card's memory - which is why the table was only ever printed in the eager mode before.
2227        const strata::core::OnDevice on_device(device_);
2228        cs_->memcpy(prof_h_.data(), prof_, prof_h_.size() * 8).wait();
2229    }
2230    accumulate_profile(prof_h_.data());
2231    if (prof_S_ > 0) {   // a batch window: its table (run() prints only its own windows)
2232        static const long long every = [] {
2233            const char* e = std::getenv("STRATA_VERIFY_PROFILE_EVERY");
2234            return e ? std::atoll(e) : 0LL;
2235        }();
2236        if (every > 0 && prof_windows_ >= every) {
2237            std::fprintf(stderr, "verify stages batch window of %d rows (ms/window over %lld, GPU clock):%s\n", prof_S_,
2238                         (long long) prof_windows_, profile_report().c_str());
2239            std::fflush(stderr);
2240        }
2241    }
2242}
2243
2244void Verifier::accumulate_profile(const unsigned long long* stamps) {
2245    const ModelGeometry& g = *g_;
2246    const int64_t L = g.n_layers;
2247    auto at = [&](int64_t l, int i) { return stamps[(size_t) (l * kProfPer + i)]; };
2248    // D8: the derived columns below read stamps the hc-read kernels write themselves or the next
2249    // layer's first.  A slot no kernel stamped is 0 and its unsigned difference wrapped to ~1e19 ns -
2250    // which is why (gap)/head/hc0 printed ~1e14 ms per window.  A missing or out-of-order stamp now
2251    // contributes nothing.
2252    const auto gap = [](unsigned long long to, unsigned long long from) {
2253        return (from != 0 && to != 0 && to >= from) ? (double) (to - from) : 0.0;
2254    };
2255    // only this stage's layers [lb_, le_) are ever stamped (a layer split); the head only on the last stage
2256    for (int64_t l = lb_; l < le_; ++l) {
2257        const int kind = is_qsa_layer(g, l) ? 1 : 0;
2258        unsigned long long prev = at(l, 0);
2259        for (int i = 1; i <= 24; ++i) {
2260            const unsigned long long x = at(l, i);
2261            if (x == 0 || x < prev) continue;
2262            prof_sum_[kind][i] += (double) (x - prev);
2263            prev = x;
2264        }
2265        if (l + 1 < le_) prof_sum_[kind][25] += gap(at(l + 1, 0), at(l, 24));
2266        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));
2267        if (dn > 0 && dd > 0 && du > 0) {   // the split exists: show it split, not twice
2268            prof_sum_[kind][27] += dn;      // hc-read0: norm
2269            prof_sum_[kind][28] += dd;      //           down
2270            prof_sum_[kind][29] += du;      //           up (through both halves, as before)
2271            prof_sum_[kind][1] -= gap(at(l, 1), at(l, 0));   // (hc-read0 shown split)
2272        }
2273    }
2274    if (le_ == L) prof_sum_[0][26] += gap(at(L, 1), at(L, 0));
2275    ++prof_windows_;
2276}
2277
2278bool Verifier::run(int T, const int32_t *tokens, int64_t pos0, PoolMultiFn pool,
2279                   void *user, int32_t *out, std::string &err) try {
2280    using namespace strata::kernels;
2281    strata::kprof::phase("decode");
2282    prof_S_ = 0;
2283    const OnDevice on_device(device_);
2284    last_batch_ = false;
2285    if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; }
2286    const ModelGeometry& g = *g_;
2287    SessionState& ss = *ss_;
2288    if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }
2289    if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; }
2290    refresh_ar();
2291    if (!capture(T, err) || !capture_commit(err)) return false;
2292    VDBG("captured; staging\n");
2293    const Clock::time_point t0 = Clock::now();
2294    if (!staged_) stage_inputs(T, tokens, pos0);
2295    staged_ = false;
2296    const bool do_ple = ss.ple.ready() && ple_stage();
2297    uint32_t ple_rows[kVerifyMaxT * PLE_N_HEADS];
2298    if (do_ple) {
2299        int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]};
2300        for (int t = 0; t < T; ++t) {
2301            ngram_rows(&tokens[t], prev, 1, ss.ple.consts, ple_rows + t * PLE_N_HEADS);
2302            prev[0] = prev[1];
2303            prev[1] = tokens[t];
2304            ss.ple.table->prefetch_rows(ple_rows + t * PLE_N_HEADS);
2305        }
2306    }
2307    if (trace_h_ != nullptr) std::memset(trace_h_, 0, trace_n_ * 8);   // #649: this window's breadcrumbs only
2308    if (std::FILE* sf = state_hash_file()) {   // debug only (STRATA_STATE_HASH_FILE)
2309        cs_->wait();
2310        const uint64_t gf = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +
2311                            (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);
2312        std::vector<char> hb(std::max<uint64_t>(gf * 4, 1u << 20));
2313        for (int64_t i = 0; i < ss.gdn_alloc; ++i) {
2314            cs_->memcpy(hb.data(), ss.gdn_state + (size_t) i * gf, gf * 4).wait();
2315            if (const char* dp = std::getenv("STRATA_STATE_DUMP"); dp != nullptr && windows == 0 && i < 4) {   // raw state of the first GDN layers
2316                const std::string fn = std::string(dp) + "_gdn" + std::to_string(ss.gdn_ord0 + i) + ".bin";
2317                if (std::FILE* df = std::fopen(fn.c_str(), "wb")) { std::fwrite(hb.data(), 1, gf * 4, df); std::fclose(df); }
2318            }
2319            std::fprintf(sf, "%lld gdn %lld %016llx\n", (long long) windows, (long long) (ss.gdn_ord0 + i),
2320                         (unsigned long long) layer_hash_fnv(hb.data(), gf * 4));
2321        }
2322        const int64_t pages = (pos0 + 3) / 4;
2323        for (int64_t i = 0; i < ss.qsa_alloc; ++i) {
2324            const QsaState& q = ss.qsa_states[i];
2325            if (!q.kv_int8 || q.k_q == nullptr) continue;
2326            const size_t kb = (size_t) pages * g.n_head_kv * 4 * g.head_dim;
2327            uint64_t h = 1469598103934665603ull;
2328            auto mix = [&](const void* dev, size_t bytes) {
2329                if (bytes > hb.size()) hb.resize(bytes);
2330                cs_->memcpy(hb.data(), dev, bytes).wait();
2331                h ^= layer_hash_fnv(hb.data(), bytes); h *= 1099511628211ull;
2332            };
2333            mix(q.k_q, kb); mix(q.v_q, kb); mix(q.k_scale, kb / 64 * 2); mix(q.v_scale, kb / 64 * 2);
2334            std::fprintf(sf, "%lld qsa %lld %016llx\n", (long long) windows, (long long) (ss.qsa_ord0 + i), (unsigned long long) h);
2335        }
2336        std::fflush(sf);
2337    }
2338    std::atomic_thread_fence(std::memory_order_seq_cst);
2339    if (expert_usage_counts_d_)
2340        cs_->memset(expert_usage_counts_d_, 0, expert_usage_counts_h_.size() * sizeof(uint32_t));
2341    trace_ev("WINDOW", -1, -1, pos0 * 16 + T);
2342    ms_host += ms_since(t0);
2343    VDBG("staged; launching\n");
2344    static Clock::time_point t_prev_end;   // SYCL port timing: where does a round's wall clock go?
2345    const Clock::time_point t_launch = Clock::now();
2346    if (ar_on() && h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0;
2347    {   // SYCL port: on an Arc A750 the first window after other GPU work (a prefill, the previous request) never
2348        // started when it was launched behind that work still in flight on another queue (no GPU breadcrumb, 20 s
2349        // timeout, the engine dies). Letting the other queues drain before every window removes it (9 of 9 three-request runs pass; before, almost all
2350        // failed; the gap rule alone (=2) did not help, so it is the windows after each other, not only the first). The cost is
2351        // the overlap of a window with the previous commit's tail.  STRATA_WINDOW_SYNC=1 always drains, =0 never, =2 the gap rule; the default is 1 on an i915 card, 0 elsewhere.
2352        // #2194: the same never-starting first window on an Arc A770 under xe (main thread in this function's stepped
2353        // serve, queue::wait, no xe reset) - an Alchemist card, whatever its driver. Reproduced on the A750 with
2354        // STRATA_WINDOW_SYNC=0 (stepped, --resident-experts, IQ3_XXS): 1 of 6 runs hung there (same stack), against 0 of 11
2355        // with the drain. So the default drain is per GPU generation now: every Alchemist card (i915 or xe), as before
2356        // every i915 card; Battlemage and the others are unchanged (0).
2357        static const char* wv = std::getenv("STRATA_WINDOW_SYNC");
2358        static const int wmode = wv ? std::atoi(wv)
2359                                    : ((intel_i915_gpu() || strata::intel_gpu_gen(cs_->get_device()) == strata::IntelGpuGen::Alchemist) ? 1 : 0);
2360        const bool first_or_gap = t_prev_end.time_since_epoch().count() == 0 || (t_launch - t_prev_end) > std::chrono::milliseconds(20);
2361        if (wmode == 1 || (wmode == 2 && first_or_gap)) dpct::get_current_device().queues_wait_and_throw();
2362    }
2363    // STRATA_VERIFY_STEPPED (Arc A-series): the doorbell window runs as segments with the CPU experts served at the
2364    // queue boundaries between them (no mid-kernel host signalling); the all-resident graph gets its one flag (the PLE
2365    // rows are in place) before launch.
2366    const bool stepped_run = g_stepped && !ar_on() && std::getenv("STRATA_VERIFY_EAGER") == nullptr && !seg_[T].empty();
2367    const bool stepped_ar = g_stepped && ar_on() && !(g_test_stall > 0 && windows + 1 == g_test_stall);
2368    if (stepped_ar) {
2369        if (do_ple) {
2370            const Clock::time_point tp = Clock::now();
2371            if (!ss.ple.table->gather_batch(ple_rows, (size_t) T, h_ple_, err)) return false;
2372            std::atomic_thread_fence(std::memory_order_seq_cst);
2373            _mm_sfence();
2374            ms_host += ms_since(tp);
2375        }
2376        *(volatile uint32_t*) h_flag_ = 1;
2377        std::atomic_thread_fence(std::memory_order_seq_cst);
2378    }
2379    dpct::err0 le = 0;
2380    if (stepped_run) {
2381        if (remote_opt_) { err = "verify: STRATA_VERIFY_STEPPED does not serve --remote-expert-opt"; return false; }
2382        const int Gs = groups_[T] > 0 ? groups_[T] : 1;
2383        double st_wait = 0, st_pool = 0;
2384        std::vector<char> submitted(seg_[T].size(), 0);
2385        // one serve: segment i drained (the ring's payload is in mapped memory); run the pool - on a helper thread
2386        // when `nxt` is a split segment, which is submitted as soon as the pool publishes its plan (flag A) - then
2387        // raise flags B and M before the following segment is submitted
2388        auto serve = [&](int64_t l, int grp, size_t nxt) -> bool {
2389            const Clock::time_point a = Clock::now();
2390            cs_->wait();
2391            const Clock::time_point b = Clock::now();
2392            const uint32_t want = (uint32_t) ((l - lb_) * Gs + grp + 1);
2393            if (*(volatile uint32_t*) h_seq_ < want) {
2394                err = "verify (stepped): layer " + std::to_string(l) + " did not ring after its queue drained (seq " +
2395                      std::to_string(*(volatile uint32_t*) h_seq_) + ", want " + std::to_string(want) + ")";
2396                return false;
2397            }
2398            cur_layer_ = want - 1;
2399            set_plan_slot(grp);
2400            const int tb = grp == 0 ? 0 : (T + 1) / 2, n = (Gs == 2 ? (grp == 0 ? (T + 1) / 2 : T) : T) - tb;
2401            auto run_pool = [&]() {
2402                if (pool != nullptr)
2403                    pool(user, h_x_ + (size_t) tb * g.n_embd, h_ids_ + (size_t) tb * ss.k, n, ss.k,
2404                         h_ymiss_ + (size_t) tb * ss.k * g.n_embd, l);
2405            };
2406            auto empty_plan = [&]() {   // the pool did not publish a plan: an empty one
2407                sink_.counts[0] = 0; sink_.counts[1] = 0; sink_.counts[2] = 0;
2408                sink_.start[0] = 0; sink_.start2[0] = 0;
2409                std::atomic_thread_fence(std::memory_order_seq_cst);
2410                *(volatile uint32_t*) h_flagA_ = want;
2411            };
2412            // segment nxt ends at a split point: it is the plan copy + VRAM groups, whose only host wait is flag A
2413            const bool split = nxt < seg_kind_[T].size() && seg_kind_[T][nxt] == 0;
2414            static const bool pipe = [] { const char* e = std::getenv("STRATA_VERIFY_PIPE"); return !(e && e[0] == '0'); }();
2415            if (pipe && split) {
2416                std::atomic<bool> done{false};
2417                std::string herr;
2418                try {
2419                    const int helper_cpu = pipe_helper_cpu();
2420                    std::thread th([&, helper_cpu]() {
2421#if defined(__linux__)
2422                        if (helper_cpu >= 0) {
2423                            cpu_set_t s;
2424                            CPU_ZERO(&s);
2425                            CPU_SET(helper_cpu, &s);
2426                            (void) pthread_setaffinity_np(pthread_self(), sizeof s, &s);
2427                        }
2428#endif
2429                        try { run_pool(); } catch (const std::exception& e) { herr = e.what(); }
2430                        done.store(true, std::memory_order_release);
2431                    });
2432                    while (!done.load(std::memory_order_acquire) && *(volatile uint32_t*) h_flagA_ != want)
2433                        std::this_thread::yield();
2434                    if (done.load(std::memory_order_acquire) && *(volatile uint32_t*) h_flagA_ != want) empty_plan();
2435                    cs_->ext_oneapi_graph(*seg_[T][nxt]);   // flag A is up: its waits pass
2436                    submitted[nxt] = 1;
2437                    th.join();
2438                } catch (const std::exception& e) { err = std::string("verify: pipelined serve: ") + e.what(); return false; }
2439                if (!herr.empty()) { err = "verify: pool: " + herr; return false; }
2440            } else {
2441                run_pool();
2442                std::atomic_thread_fence(std::memory_order_seq_cst);
2443                if (*(volatile uint32_t*) h_flagA_ != want) empty_plan();
2444            }
2445            copy_->wait();   // fetch_dma's copies and its flag-B host task
2446            std::atomic_thread_fence(std::memory_order_seq_cst);
2447            raise_flag(h_flagB_, want);
2448            if (want == 1 && do_ple) {   // layer 1's pre copies h_ple_ after layer 0's wait on the M flag
2449                const Clock::time_point tp = Clock::now();
2450                if (!ss.ple.table->gather_batch(ple_rows, (size_t) T, h_ple_, err)) return false;
2451                ms_host += ms_since(tp);
2452            }
2453            std::atomic_thread_fence(std::memory_order_seq_cst);
2454            _mm_sfence();
2455            *(volatile uint32_t*) h_flag_ = want;
2456            std::atomic_thread_fence(std::memory_order_seq_cst);
2457            st_wait += std::chrono::duration<double, std::milli>(b - a).count();
2458            st_pool += ms_since(b);
2459            return true;
2460        };
2461        try {
2462            for (size_t i = 0; i < seg_[T].size() && le == 0; ++i) {
2463                const bool has_entry = i < seg_at_[T].size();
2464                if (!submitted[i]) cs_->ext_oneapi_graph(*seg_[T][i]);   // (a split segment: its serve submitted it)
2465                if (has_entry && seg_kind_[T][i] == 1 && !serve(seg_at_[T][i].first, seg_at_[T][i].second, i + 1)) {
2466                    if (err.empty()) err = "verify: stepped serve failed";
2467                    le = 1;
2468                }
2469            }
2470        } catch (const std::exception& e) { err = std::string("verify (stepped): ") + e.what(); le = 1; }
2471        ms_wait += st_wait;
2472        ms_pool += st_pool;
2473        if (le != 0) return false;
2474    } else {
2475        le = (std::getenv("STRATA_VERIFY_EAGER") != nullptr)
2476                 ? (record_window(T, cs_, err) ? 0 : 1)   // SYCL port: eager replay of the window body
2477                 : DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*(ar_off_ ? exec_nr_[T] : exec_[T])));
2478    }
2479    /*
2480    DPCT1009: SYCL reports errors using exceptions and does not use error
2481    codes. Please replace the "get_error_string_dummy(...)" with a real
2482    error-handling function.
2483    */
2484    /*
2485    DPCT1001: The statement could not be removed.
2486    */
2487    /*
2488    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
2489    */
2490    trace_ev("LAUNCHED", -1, -1, (int64_t) le);
2491    if (le != 0) {
2492        err =
2493            std::string("verify: launch: ") + dpct::get_error_string_dummy(le);
2494        return false;
2495    }
2496    (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));
2497    VDBG("launched\n");
2498    volatile uint32_t* const seq = h_seq_;
2499    volatile uint32_t* const flag = h_flag_;
2500    const int G = groups_[T] > 0 ? groups_[T] : 1;
2501    const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T};
2502    // SYCL port: with every routed expert resident the GPU takes its own plan (`device_plan_`) and skips every
2503    // host flag, so the host has nothing to do per layer - and on this platform a kernel's writes to host-mapped
2504    // memory are not reliably visible while the graph runs (measured: the ring is seen late or not at all),
2505    // so waiting on them per layer fails. STRATA_VERIFY_NO_HOST=1 waits for the whole window instead. Only for
2506    // an all-resident cache: a missed expert would leave the GPU waiting for a plan that never comes.
2507    static const bool no_host = [] { const char* v = std::getenv("STRATA_VERIFY_NO_HOST"); return v && *v && std::strcmp(v, "0") != 0; }();
2508    const int64_t steps = (le_ - lb_) * G;
2509    const bool test_stall = g_test_stall > 0 && windows + 1 == g_test_stall;   // #267 test hook (off: false)
2510    if (stepped_run || stepped_ar) {
2511        // the stepped window already served every layer (or the all-resident one had its flag before launch)
2512    } else if (ar_on() && !test_stall) {
2513        if (do_ple) {
2514            const Clock::time_point tp = Clock::now();
2515            if (!ss.ple.table->gather_batch(ple_rows, (size_t) T, h_ple_, err)) return false;
2516            std::atomic_thread_fence(std::memory_order_seq_cst);
2517            _mm_sfence();
2518            *flag = 1;
2519            ms_host += ms_since(tp);
2520        } else {
2521            *flag = 1;
2522        }
2523    } else
2524    for (int64_t k = 0; !no_host && k < steps; ++k) {
2525        const int64_t l = lb_ + k / G;
2526        const int grp = (int) (k % G);
2527        const uint32_t want = (uint32_t) (k + 1);
2528        const Clock::time_point a = Clock::now();
2529        auto last_flush = a;
2530        uint32_t spins = 0;
2531        progress_at("verify window: waiting for the GPU to reach layer", l);
2532        while (*seq < want) {
2533            _mm_pause();
2534            if ((++spins & 1023u) != 0) continue;
2535            const auto now = Clock::now();
2536            if (now - last_flush > std::chrono::microseconds(2000)) {
2537                last_flush = now;
2538                // SYCL port fix: cudaStreamQuery's answer (0 finished, 1 still running) was lost in the migration
2539                // (DPCT_CHECK_ERROR of ext_oneapi_empty() is always 0), so ANY wait over 2 ms was reported as
2540                // "graph finished". Layers whose GPU time exceeds 2 ms (host-mirrored experts read over PCIe) failed that way.
2541                const dpct::err0 q = cs_->ext_oneapi_empty() ? 0 : 1;
2542                if (q != 1 && *seq < want) {
2543                    trace_ev("NEVER-RANG", k, l, (int64_t) q);
2544                    trace_dump(stderr);
2545                    err = "verify: layer " + std::to_string(l) +
2546                          " never rang (" +
2547                          /*
2548                          DPCT1009: SYCL reports errors using exceptions and
2549                          does not use error codes. Please replace the
2550                          "get_error_string_dummy(...)" with a real
2551                          error-handling function.
2552                          */
2553                          (q == 0
2554                               ? std::string("graph finished")
2555                               : std::string(dpct::get_error_string_dummy(q))) +
2556                          ")";
2557                    return false;
2558                }
2559            }
2560            if (now - a > strata_ring_timeout()) {
2561                // #267: the caller ends the engine; no spin kernel may outlive it
2562                trace_ev("TIMEOUT", k, l, (int64_t) !cs_->ext_oneapi_empty());   // SYCL port: 1 = still running
2563                if (g_trace) {
2564                    diag(stderr);   // the words and the breadcrumbs before the release ...
2565                    const bool drained = release_gpu_waits(5000);
2566                    trace_dump(stderr);   // ... and after it: did the GPU move once its waits were raised?
2567                    err = "verify: timed out at layer " + std::to_string(l) + released_note(drained);
2568                    return false;
2569                }
2570                err = "verify: timed out at layer " + std::to_string(l) + released_note(release_gpu_waits(5000));
2571                return false;
2572            }
2573        }
2574        const Clock::time_point b = Clock::now();
2575        if (g_trace) trace_ev("RANG", k, l, (int64_t) std::chrono::duration_cast<std::chrono::microseconds>(b - a).count());
2576        VDBG("layer %lld rang\n", (long long) l);
2577        cur_layer_ = want - 1;
2578        set_plan_slot(grp);
2579        const int tb = gtb[grp], n = gte[grp] - gtb[grp];
2580        // the ring can arrive before its payload (elementwise.hpp): the pool must read a whole one
2581        if (!strata::kernels::doorbell_wait_payload(h_seq_, h_x_ + (size_t) tb * g.n_embd, (int64_t) n * g.n_embd,
2582                                                    h_ids_ + (size_t) tb * ss.k, h_w_ + (size_t) tb * ss.k,
2583                                                    (int64_t) n * ss.k, want)) {
2584            err = "verify: layer " + std::to_string(l) + " rang but its payload never arrived whole";
2585            return false;
2586        }
2587        progress_at("verify window: the CPU experts of layer", l);
2588        if (remote_opt_) remote_opt_->begin(h_w_ + (size_t) tb * ss.k, tb, n);
2589        if (pool != nullptr)
2590            pool(user, h_x_ + (size_t) tb * g.n_embd, h_ids_ + (size_t) tb * ss.k, n, ss.k,
2591                 h_ymiss_ + (size_t) tb * ss.k * g.n_embd, l);
2592        if (remote_opt_) remote_opt_->end();
2593        if (std::FILE* lf = layer_hash_file()) {   // debug only (STRATA_LAYER_HASH_FILE)
2594            std::fprintf(lf, "%lld %lld %d %016llx %016llx %016llx %016llx\n", (long long) windows, (long long) l, n,
2595                         (unsigned long long) layer_hash_fnv(h_x_ + (size_t) tb * g.n_embd, (size_t) n * g.n_embd * 4),
2596                         (unsigned long long) layer_hash_fnv(h_ids_ + (size_t) tb * ss.k, (size_t) n * ss.k * 4),
2597                         (unsigned long long) layer_hash_fnv(h_w_ + (size_t) tb * ss.k, (size_t) n * ss.k * 4),
2598                         (unsigned long long) layer_hash_fnv(h_ymiss_ + (size_t) tb * ss.k * g.n_embd, (size_t) n * ss.k * g.n_embd * 4));
2599            std::fflush(lf);
2600        }
2601        VDBG("layer %lld served\n", (long long) l);
2602        if (g_trace) trace_ev(*(volatile uint32_t*) h_flagA_ == want ? "SERVED" : "SERVED-NO-PLAN-YET", k, l,
2603                              (int64_t) ms_since(b));   // aux: ms the CPU experts took
2604        progress_tick();
2605        std::atomic_thread_fence(std::memory_order_seq_cst);
2606        _mm_sfence();
2607        if (*(volatile uint32_t*) h_flagA_ != want) {        // the pool did not publish a plan: an empty one
2608            sink_.counts[0] = 0;
2609            sink_.counts[1] = 0;
2610            sink_.counts[2] = 0;
2611            sink_.start[0] = 0;
2612            sink_.start2[0] = 0;
2613            std::atomic_thread_fence(std::memory_order_seq_cst);
2614            *(volatile uint32_t*) h_flagA_ = want;
2615            raise_flag(h_flagB_, want);
2616        }
2617        // Layer 1's pre(1, 0) copies h_ple_ -> ple_ after Layer 0's wait_flag_ge(m_flag_, 1).
2618        // By collecting PLE here at k == 0 (after publishing flagA/flagB for Layer 0 so the GPU can run
2619        // Layer 0's VRAM experts, and before raising *flag = 1), the NVMe PLE reads overlap with both
2620        // MtpDrafter::draft and Layer 0's attention + router + expert execution!
2621        if (k == 0 && do_ple) {
2622            const Clock::time_point tp = Clock::now();
2623            if (!ss.ple.table->gather_batch(ple_rows, (size_t) T, h_ple_, err)) return false;
2624            std::atomic_thread_fence(std::memory_order_seq_cst);
2625            _mm_sfence();
2626            ms_host += ms_since(tp);
2627        }
2628        if (!(test_stall && k + 1 == steps)) *flag = want;
2629        ms_wait += std::chrono::duration<double, std::milli>(b - a).count();
2630        ms_pool += ms_since(b);
2631    }
2632    // (#646 staged the next stage's inputs here; 0.1.39b keeps the layer split's order: each stage stages its own)
2633    progress_at("verify window: waiting for the GPU to finish the window (flags A/B/M raised)", (int64_t) T);
2634    // #267: a window the GPU never finishes (a spin kernel that never sees its flag) holds the host here; the stall
2635    // watchdog then releases every verifier's GPU waits (release_live_verifiers) before it ends the engine, so no
2636    // spin kernel outlives the process.  The wait itself stays a blocking sync (a polling wait cost decode upstream).
2637    trace_ev("SYNC", -1, -1, 0);
2638    const dpct::err0 se = queue_wait_diag(cs_, device_, "window sync");
2639    trace_ev("SYNCED", -1, -1, (int64_t) se);
2640    const Clock::time_point t_done = Clock::now();
2641    if (std::getenv("STRATA_VERIFY_DEBUG") != nullptr) {
2642        std::fprintf(stderr, "verify dbg: T=%d window: since previous window %.1f ms, staging %.1f ms, gpu %.1f ms\n", T,
2643                     t_prev_end.time_since_epoch().count() ? std::chrono::duration<double, std::milli>(t0 - t_prev_end).count() : 0.0,
2644                     std::chrono::duration<double, std::milli>(t_launch - t0).count(),
2645                     std::chrono::duration<double, std::milli>(t_done - t_launch).count());
2646    }
2647    t_prev_end = t_done;
2648    /*
2649    DPCT1009: SYCL reports errors using exceptions and does not use error
2650    codes. Please replace the "get_error_string_dummy(...)" with a real
2651    error-handling function.
2652    */
2653    /*
2654    DPCT1001: The statement could not be removed.
2655    */
2656    /*
2657    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
2658    */
2659    if (se != 0) {
2660        err = std::string("verify: ") + dpct::get_error_string_dummy(se);
2661        return false;
2662    }
2663    if (expert_usage_counts_d_) {
2664        if (!expert_usage_counter_ || expert_usage_counter_->size() != expert_usage_counts_h_.size())
2665            throw std::runtime_error("mirror adaptive expert usage is unbound");
2666        cs_->memcpy(expert_usage_counts_h_.data(), expert_usage_counts_d_,
2667                    expert_usage_counts_h_.size() * sizeof(uint32_t)).wait_and_throw();
2668        uint64_t total = 0;
2669        for (uint32_t count : expert_usage_counts_h_) total += count;
2670        if (total != (uint64_t)(le_ - lb_) * (uint64_t)T * (uint64_t)ss.k)
2671            throw std::runtime_error("mirror adaptive route histogram coverage mismatch");
2672        // Match the CPU usage counter's scalar increment order.
2673        static const bool presence = [] { const char* e=std::getenv("STRATA_SYCL_ADAPT_WINDOW_PRESENCE"); return e && e[0]=='1'; }();
2674        for (size_t i = 0; i < expert_usage_counts_h_.size(); ++i) {
2675            const uint32_t count=presence ? (expert_usage_counts_h_[i]>0 ? 1u : 0u) : expert_usage_counts_h_[i];
2676            for (uint32_t n=0;n<count;++n) (*expert_usage_counter_)[i] += 1.f;
2677        }
2678    }
2679#ifdef STRATA_SYCL_WORKLOAD_TRACE
2680    if (auto found = routing_audits.find(this); found != routing_audits.end()) {
2681        auto& audit = *found->second;
2682        const int64_t capx = (int64_t)max_t_ * ss.k;
2683        const int64_t ptr_off = ((4 + capx + 1 + 2 * capx) + 1) & ~1ll;
2684        const auto& layout = strata::kernels::cpu::expert_layout();
2685        if (!layout.native) throw std::runtime_error("routing audit requires native expert layout");
2686        for (int64_t layer = lb_; layer < le_; ++layer) for (int group = 0; group < G; ++group) {
2687            const int32_t* data = audit.slot(layer, group);
2688            const int32_t* starts = data + 4;
2689            const int32_t* dst = starts + capx + 1;
2690            const int32_t* tok = dst + capx;
2691            const auto* pointers = reinterpret_cast<const unsigned long long*>(data + ptr_off);
2692            const int n = gte[group] - gtb[group], expected = n * (int)ss.k;
2693            if (data[0] < 0 || data[0] > expected || data[1] != expected || data[2] != 0 || starts[0] != 0 || starts[data[0]] != expected)
2694                throw std::runtime_error("routing audit: incomplete resident plan");
2695            const auto& format = layout.fmt[(size_t)layer];
2696            std::vector<bool> seen((size_t)expected, false);
2697            std::fprintf(audit.output, "{\"kind\":\"expert_plan\",\"raw_ns\":%lld,\"position\":%lld,\"T\":%d,\"layer\":%lld,\"group\":%d,\"rows\":%d,\"GU_type\":%d,\"down_type\":%d,\"n_embd\":%lld,\"n_ff\":%lld,\"gu_row_bytes\":%llu,\"down_row_bytes\":%llu,\"groups\":%d,\"entries\":%d,\"pcie_plan_groups\":%d,\"plans\":[",
2698                (long long)strata::workload_trace::trace_ns(), (long long)pos0, T, (long long)layer, group, n,
2699                format.gu_type, format.d_type, (long long)format.n_embd, (long long)format.n_ff,
2700                (unsigned long long)format.gu_row, (unsigned long long)format.d_row, data[0], data[1], data[2]);
2701            for (int index = 0; index < data[0]; ++index) {
2702                const int begin = starts[index], end = starts[index + 1];
2703                if (begin < 0 || end <= begin || end > expected || end - begin > n)
2704                    throw std::runtime_error("routing audit: invalid group range");
2705                const auto allocation = sycl::get_pointer_type(reinterpret_cast<const void*>(pointers[index]), cs_->get_context());
2706                const char* residency = allocation == sycl::usm::alloc::device ? "device" : allocation == sycl::usm::alloc::host ? "host" : allocation == sycl::usm::alloc::shared ? "shared" : "unknown";
2707                std::fprintf(audit.output, "%s{\"count\":%d,\"allocation\":\"%s\",\"pointer\":%llu,\"dst\":[", index ? "," : "", end - begin, residency, pointers[index]);
2708                for (int e = begin; e < end; ++e) {
2709                    if (dst[e] < 0 || dst[e] >= expected || seen[(size_t)dst[e]] || tok[e] < 0 || tok[e] >= T)
2710                        throw std::runtime_error("routing audit: invalid entry mapping");
2711                    seen[(size_t)dst[e]] = true;
2712                    std::fprintf(audit.output, "%s%d", e == begin ? "" : ",", dst[e]);
2713                }
2714                std::fprintf(audit.output, "],\"tok\":[");
2715                for (int e = begin; e < end; ++e) std::fprintf(audit.output, "%s%d", e == begin ? "" : ",", tok[e]);
2716                std::fprintf(audit.output, "]}");
2717            }
2718            if (std::find(seen.begin(), seen.end(), false) != seen.end()) throw std::runtime_error("routing audit: missing entry");
2719            std::fprintf(audit.output, "]}\n");
2720        }
2721        std::fflush(audit.output);
2722    }
2723#endif
2724    if (no_host && std::getenv("STRATA_VERIFY_DEBUG") != nullptr) {   // SYCL port: what the window left behind
2725        const int Gd = groups_[T] > 0 ? groups_[T] : 1;
2726        std::vector<uint32_t> sk((size_t) Gd, 0);
2727        std::vector<int32_t> id0((size_t) ss.k, 0);
2728        std::vector<int32_t> res0((size_t) 16, 0);
2729        cs_->memcpy(sk.data(), skip_, sk.size() * 4).wait();
2730        cs_->memcpy(id0.data(), ids_, id0.size() * 4).wait();
2731        cs_->memcpy(res0.data(), hits_.d_res, res0.size() * 4).wait();
2732        std::fprintf(stderr, "verify dbg: window T=%d: host seq=%u (expected %lld), skip[]=", T, *(volatile uint32_t*) h_seq_,
2733                     (long long) ((le_ - lb_) * Gd));
2734        for (int i = 0; i < Gd; ++i) std::fprintf(stderr, " %u", sk[(size_t) i]);
2735        std::vector<float> w0((size_t) ss.k, 0.f);
2736        cs_->memcpy(w0.data(), w_, w0.size() * 4).wait();
2737        std::fprintf(stderr, "; layer-0 weights:");
2738        for (size_t i = 0; i < w0.size(); ++i) std::fprintf(stderr, " %.3g", w0[i]);
2739        std::fprintf(stderr, "; layer-0 ids:");
2740        for (size_t i = 0; i < id0.size(); ++i) std::fprintf(stderr, " %d", id0[i]);
2741        std::fprintf(stderr, "; d_res[0..15]:");
2742        for (size_t i = 0; i < res0.size(); ++i) std::fprintf(stderr, " %d", res0[i]);
2743        std::fprintf(stderr, "; out[0..3]: %d %d %d %d\n", ((volatile int32_t*) h_out_)[0], ((volatile int32_t*) h_out_)[1],
2744                     ((volatile int32_t*) h_out_)[2], ((volatile int32_t*) h_out_)[3]);
2745        auto stat = [&](const char* what, const float* dev, size_t n) {   // token 0's vector: where do the zeros begin?
2746            std::vector<float> v(n, 0.f);
2747            cs_->memcpy(v.data(), dev, n * 4).wait();
2748            double sum = 0, mx = 0; size_t nonfinite = 0;
2749            for (float x : v) { if (!std::isfinite(x)) { ++nonfinite; continue; } sum += std::fabs(x); mx = std::max(mx, (double) std::fabs(x)); }
2750            std::fprintf(stderr, "verify dbg:   %-8s n=%zu mean|.|=%.4g max|.|=%.4g nonfinite=%zu first4=%g %g %g %g\n", what, n,
2751                         sum / (double) n, mx, nonfinite, v[0], v[1], v[2], v[3]);
2752        };
2753        if (dbgR_) {
2754            const size_t N = (size_t) g.n_embd;
2755            std::vector<float> r((size_t) g.n_layers * N), m((size_t) g.n_layers * N);
2756            cs_->memcpy(r.data(), dbgR_, r.size() * 4).wait();
2757            cs_->memcpy(m.data(), dbgM_, m.size() * 4).wait();
2758            for (int64_t l = 0; l < g.n_layers; ++l) {
2759                double sr = 0, sm = 0; size_t nr = 0, nm = 0;
2760                for (size_t i = 0; i < N; ++i) {
2761                    const float x = r[(size_t) l * N + i], y = m[(size_t) l * N + i];
2762                    if (std::isfinite(x)) sr += std::fabs(x); else ++nr;
2763                    if (std::isfinite(y)) sm += std::fabs(y); else ++nm;
2764                }
2765                std::fprintf(stderr, "verify dbg:   layer %2lld %s  R mean|.|=%.4g nonfinite=%zu   mixed mean|.|=%.4g nonfinite=%zu\n",
2766                             (long long) l, is_qsa_layer(g, l) ? "QSA" : "GDN", sr / N, nr, sm / N, nm);
2767            }
2768        }
2769        {   // the device plan of the last layer group and the MoE parts it produced (token 0)
2770            std::vector<int32_t> pc(4, 0);
2771            cs_->memcpy(pc.data(), plan_, 16).wait();
2772            std::fprintf(stderr, "verify dbg:   plan (last layer, grp 0): groups=%d entries=%d pcie=%d\n", pc[0], pc[1], pc[2]);
2773        }
2774        stat("parts_", parts_, (size_t) ss.k * g.n_embd);
2775        stat("hit_out_", hit_out_, (size_t) ss.k * g.n_embd);
2776        stat("shared_", shared_, (size_t) g.n_embd);
2777        stat("emb_", emb_, (size_t) g.n_embd);
2778        stat("ple_", ple_, (size_t) g.n_embd);
2779        stat("R_", R_, (size_t) g.n_embd);
2780        stat("mixed_", mixed_, (size_t) g.n_embd);
2781    }
2782    if (ar_on() && h_plan_err_ != nullptr && *(volatile uint32_t*) h_plan_err_ != 0) {   // #871: refresh_ar saw the table whole
2783        *(volatile uint32_t*) h_plan_err_ = 0;
2784        err = "verify: the all-resident plan met an expert that is not in VRAM (the residency table changed during the window)";
2785        return false;
2786    }
2787    commit_pending_ = false;
2788    progress_at("verify window: waiting for the expert copies", (int64_t) T);
2789    if (copy_used_) {
2790        copy_->wait(); // no host function of this window may raise flag B in
2791                       // the next one
2792        copy_used_ = false;
2793    }
2794    strata::kprof::window_end("decode");   // STRATA_KPROF=1 (with STRATA_VERIFY_EAGER=1): this window's per-kernel times
2795    if (prof_on_ && G == 1) {   // the window's GPU stage stamps
2796        collect_profile();
2797        if (std::getenv("STRATA_VERIFY_EAGER") != nullptr)   // SYCL port: the stage table per window, host-clocked
2798            std::fprintf(stderr, "verify stages T=%d (ms/window):%s\n", T, profile_report().c_str());
2799        else {
2800            // SYCL port: the same table from the GPU's own clock, averaged over N windows, so a decode can be
2801            // attributed without the eager mode's drain per stamp (which measures host gaps, not kernel time).
2802            // STRATA_VERIFY_PROFILE=1 STRATA_VERIFY_PROFILE_EVERY=32.
2803            static const long long every = [] {
2804                const char* e = std::getenv("STRATA_VERIFY_PROFILE_EVERY");
2805                return e ? std::atoll(e) : 0LL;
2806            }();
2807            if (every > 0 && prof_windows_ >= every) {
2808                std::fprintf(stderr, "verify stages T=%d (ms/window over %lld, GPU clock):%s\n", T,
2809                             (long long) prof_windows_, profile_report().c_str());
2810                std::fflush(stderr);
2811            }
2812        }
2813    }
2814    // ---- a sampled or penalized request: the head's sampling again, host-side so its parameters are this call's
2815    // own (a captured kernel would replay the same draws forever).  Row t's draw is Philox(seed, pos0 + t): tied to
2816    // the POSITION it samples, not to how the text was cut into windows, so a seed replays the same text whatever
2817    // the drafts were. Exact: a rejected row's draw is discarded, and no kept decision depends on a reused draw.
2818    if (le_ < g.n_layers) {   // a layer split's earlier stage: the hand-off is written (synced above)
2819        ++windows;
2820        return next_ == nullptr || next_->run(T, tokens, pos0, pool, next_user_, out, err);
2821    }
2822    const bool sampled = !sampling_.greedy && sampling_.temperature > 0.0f;
2823    if (head_sampling_ && (sampled || hist_d_ != nullptr)) {
2824        SamplerParams sp = sampling_;
2825        sp.counter = (uint64_t) pos0;
2826        sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_);
2827        if (DPCT_CHECK_ERROR(cs_->wait()) !=
2828            0) { // m_out_ is the mapped h_out_: synced, it is readable
2829            err = "verify: the head sampling failed";
2830            return false;
2831        }
2832    }
2833    for (int t = 0; t < T; ++t) out[t] = ((volatile int32_t*) h_out_)[t];
2834    // STRATA_LOGITS_DUMP=<path> (debug tap, off by default; src/core/verify.cpp's, for the gate-2 judge of the Qwen4 shapes): the window's
2835    // logits as the sampler saw them, written AFTER the window (synchronised above).  One record is
2836    // {int32 magic, int32 T, int32 n_vocab, int32 record, int64 position}, then T * n_vocab FP32 rows; row 0 is the window's first position.
2837    if (const char* logits_path = std::getenv("STRATA_LOGITS_DUMP")) {
2838        static std::FILE* lf = std::fopen(logits_path, "wb");
2839        static int32_t lrec = 0;
2840        if (lf != nullptr) {
2841            std::vector<float> h((size_t) T * (size_t) n_vocab_);
2842            dpct::get_in_order_queue().memcpy(h.data(), head_logits_, h.size() * sizeof(float)).wait();
2843            const int32_t hdr[4] = {0x53474F4C /*"LOGS"*/, T, (int32_t) n_vocab_, lrec++};
2844            const int64_t hpos = pos0;
2845            std::fwrite(hdr, sizeof hdr, 1, lf);
2846            std::fwrite(&hpos, sizeof hpos, 1, lf);
2847            std::fwrite(h.data(), sizeof(float), h.size(), lf);
2848            std::fflush(lf);
2849        }
2850    }
2851    if (static const bool dbg = std::getenv("STRATA_DBG_NAN") != nullptr; dbg) {   // debug: the first non-finite head
2852        static bool reported = false;
2853        if (!reported) {
2854            std::vector<float> h((size_t) T * (size_t) n_vocab_);
2855            dpct::get_in_order_queue()
2856                .memcpy(h.data(), head_logits_, h.size() * 4)
2857                .wait();
2858            for (int t = 0; t < T && !reported; ++t) {
2859                int64_t bad = 0;
2860                for (int64_t v = 0; v < n_vocab_; ++v) bad += !std::isfinite(h[(size_t) t * n_vocab_ + v]);
2861                if (bad) {
2862                    reported = true;
2863                    std::fprintf(stderr, "strata dbg: verify window at position %lld, row %d: %lld of %lld logits non-finite "
2864                                         "(token out %d)\n", (long long) pos0, t, (long long) bad, (long long) n_vocab_, out[t]);
2865                }
2866            }
2867        }
2868    }
2869    VDBG("window done\n");
2870    ++windows;
2871    progress_at("decode");
2872    progress_beat();
2873    return true;
2874}
2875catch (sycl::exception const &exc) {
2876  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2877            << ", line:" << __LINE__ << std::endl;
2878  std::exit(1);
2879}
2880
2881void Verifier::set_plan_slot(int grp) {
2882    const int64_t cap = sink_.cap;
2883    int32_t* base = h_plan_ + (size_t) grp * (size_t) plan_i32_;
2884    const int64_t i32 = 4 + (cap + 1) + cap + cap;
2885    const int64_t ptr_off = (i32 + 1) & ~1ll;
2886    sink_.counts = base;
2887    sink_.start = base + 4;
2888    sink_.dst = sink_.start + cap + 1;
2889    sink_.tok = sink_.dst + cap;
2890    sink_.ptr = (unsigned long long*) (base + ptr_off);
2891    sink_.ptr2 = sink_.ptr + cap;
2892    sink_.start2 = base + ptr_off + 4 * cap;
2893    const int G = last_batch_ ? 1 : (groups_[last_t_] > 0 ? groups_[last_t_] : 1);
2894    const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs;
2895    sink_.staging = (unsigned long long) (staging_ + (size_t) (grp * per) * strata::kernels::cpu::expert_layout().max_blob);
2896    sink_.staging_cap = per;
2897}
2898
2899// Flag B only rises: a host function of an earlier layer may run after a later layer already raised it directly.
2900void Verifier::raise_flag(uint32_t* flag, uint32_t value) {
2901    volatile long* f = (volatile long*) flag;
2902#if defined(_WIN32)
2903    long cur = *f;
2904    while ((uint32_t) cur < value) {
2905        const long prev = _InterlockedCompareExchange(f, (long) value, cur);
2906        if (prev == cur) break;
2907        cur = prev;
2908    }
2909#else
2910    uint32_t cur = __atomic_load_n((uint32_t*) flag, __ATOMIC_SEQ_CST);
2911    while (cur < value && !__atomic_compare_exchange_n((uint32_t*) flag, &cur, value, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {}
2912#endif
2913}
2914
2915// Plan v0.3 P6: the PCIe share by DMA.  The copy engine moves the blobs while the CPU computes its own share and the
2916// GPU its VRAM experts; a host function raises flag B when they have landed (the graph waits for it before the PCIe
2917// groups).  Staging is split between the two token groups of a split window.
2918void Verifier::fetch_dma(void *ctx, const uint8_t *const *src, int n,
2919                         size_t bytes) try {
2920    Verifier* v = (Verifier*) ctx;
2921    const uint32_t want = v->cur_layer_ + 1;
2922    if (n <= 0) { raise_flag(v->h_flagB_, want); return; }
2923    v->copy_used_ = true;
2924    uint8_t* stage = (uint8_t*) v->sink_.staging;                  // this group's half in a split window
2925    // STRATA_DMA_BATCH (midhatn's #807, F12): the group's independent uploads as one cudaMemcpyBatchAsync.  Mode 0 is
2926    // the loop the engine always ran, errors unchecked (it never stops the engine).  A batch mode whose uploads
2927    // cannot be submitted stops the engine: flag B must not release the consumers to expert weights that were never
2928    // copied.
2929    const int batch_mode = strata::core::dma_batch_mode();
2930    if (batch_mode == 0) {
2931        /*
2932        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
2933        While the origin API might be synchronous, it depends on the type of
2934        operand memory, so you may need to call wait() on event return by memcpy
2935        API to ensure synchronization behavior.
2936        */
2937        for (int i = 0; i < n; ++i)
2938            v->copy_->memcpy(stage + (size_t)i * bytes, src[i], bytes);
2939    } else {
2940        const auto copied = strata::core::copy_expert_blobs(stage, src, n, bytes, v->copy_, batch_mode);
2941        /*
2942        DPCT1000: Error handling if-stmt was detected but could not be
2943        rewritten.
2944        */
2945        if (copied != 0) {
2946            /*
2947            DPCT1009: SYCL reports errors using exceptions and does not use
2948            error codes. Please replace the "get_error_string_dummy(...)" with a
2949            real error-handling function.
2950            */
2951            std::fprintf(stderr, "strata DMA: expert upload failed: %s\n",
2952                         dpct::get_error_string_dummy(copied));
2953            /*
2954            DPCT1001: The statement could not be removed.
2955            */
2956            std::fflush(stderr);
2957            v->release_gpu_waits(5000);
2958            std::abort();
2959        }
2960    }
2961    FlagSet& fs = v->flag_sets_[v->cur_layer_ % (sizeof v->flag_sets_ / sizeof v->flag_sets_[0])];
2962    fs.flag = v->h_flagB_;
2963    fs.value = want;
2964  FlagSet* fsp = &fs;
2965  v->copy_->submit([&](sycl::handler &cgh) {
2966    cgh.host_task([=]() { raise_flag(fsp->flag, fsp->value); });
2967  });
2968}
2969catch (sycl::exception const &exc) {
2970  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2971            << ", line:" << __LINE__ << std::endl;
2972  std::exit(1);
2973}
2974
2975void Verifier::publish_plan(void* ctx) {
2976    Verifier* v = (Verifier*) ctx;
2977    _mm_sfence();
2978    *(volatile uint32_t*) v->h_flagA_ = v->cur_layer_ + 1;
2979}
2980
2981bool Verifier::window_logprobs(const int32_t* targets, int T, int64_t pos0, int32_t extra_id, std::FILE* out,
2982                               std::string& err) try {
2983    if (next_ != nullptr) return next_->window_logprobs(targets, T, pos0, extra_id, out, err);
2984    const OnDevice on_device(device_);
2985    if (head_logits_ == nullptr || n_vocab_ <= 0 || T <= 0 || targets == nullptr || out == nullptr) {
2986        err = "window_logprobs: no head logits for this window";
2987        return false;
2988    }
2989    // run() synchronized cs_ before returning, so the head of this window is complete
2990    std::vector<float> h((size_t) T * (size_t) n_vocab_);
2991    cs_->memcpy(h.data(), head_logits_, h.size() * sizeof(float)).wait();
2992    for (int t = 0; t < T; ++t) {
2993        const float* row = h.data() + (size_t) t * (size_t) n_vocab_;
2994        const int32_t tgt = targets[t];
2995        if (tgt < 0 || (int64_t) tgt >= n_vocab_) continue;
2996        int64_t top = 0;
2997        for (int64_t v = 1; v < n_vocab_; ++v)
2998            if (row[v] > row[top]) top = v;
2999        const double maxv = row[top];
3000        const bool has_extra = extra_id >= 0 && (int64_t) extra_id < n_vocab_;
3001        double sum = 0.0, sum_without = 0.0;   // the second skips extra_id: no cancellation when it holds ~all mass
3002        for (int64_t v = 0; v < n_vocab_; ++v) {
3003            const double e = std::exp((double) row[v] - maxv);
3004            sum += e;
3005            if (v != (int64_t) extra_id) sum_without += e;
3006        }
3007        const double lse = maxv + std::log(sum);
3008        const double extra = has_extra ? (double) row[extra_id] - lse : NAN;
3009        const double without = has_extra && tgt != extra_id && sum_without > 0.0
3010                                   ? (double) row[tgt] - (maxv + std::log(sum_without)) : NAN;
3011        std::fprintf(out, "%lld\t%d\t%.9f\t%lld\t%.9f\t%d\t%.9f\t%.9f", (long long) (pos0 + t), (int) tgt,
3012                     (double) row[tgt] - lse, (long long) top, maxv - lse, (int) (top == (int64_t) tgt), extra,
3013                     without);
3014        // STRATA_LOGPOS_TOPK=K: the K most likely tokens and their log-probabilities too (`id:logprob`), for a
3015        // top-k comparison with another engine on the same tokens (docs/UNSLOTH_Q4.md)
3016        static const int topk = [] {
3017            const char* v = std::getenv("STRATA_LOGPOS_TOPK");
3018            return v != nullptr ? std::max(0, std::min(256, std::atoi(v))) : 0;
3019        }();
3020        if (topk > 0) {
3021            std::vector<int32_t> order((size_t) n_vocab_);
3022            for (int64_t v = 0; v < n_vocab_; ++v) order[(size_t) v] = (int32_t) v;
3023            std::partial_sort(order.begin(), order.begin() + topk, order.end(),
3024                              [&](int32_t a, int32_t b) { return row[a] > row[b]; });
3025            for (int j = 0; j < topk; ++j)
3026                std::fprintf(out, "\t%d:%.6f", order[(size_t) j], (double) row[order[(size_t) j]] - lse);
3027        }
3028        std::fprintf(out, "\n");
3029    }
3030    std::fflush(out);
3031    return true;
3032} catch (sycl::exception const& e) {
3033    err = std::string("window_logprobs: ") + e.what();
3034    return false;
3035}
3036
3037namespace { bool g_commit_async = false; }
3038void Verifier::set_commit_async(bool on) { g_commit_async = on && std::getenv("STRATA_COMMIT_SYNC") == nullptr; }
3039
3040bool Verifier::commit(int n_keep, std::string &err) try {
3041    const OnDevice on_device(device_);
3042    if (n_keep < 1 || n_keep > last_t_) { err = "verify: commit count out of range"; return false; }
3043    const Clock::time_point t0 = Clock::now();
3044    h_commit_[0] = n_keep;
3045    h_commit_[1] = n_keep - 1;
3046    for (int t = 0; t < max_t_; ++t) h_commit_[2 + t] = t < n_keep ? (int32_t) (last_pos0_ + t) : -1;
3047    if (last_t_ == 1 && one_token_self_commit() && !self_commit_off_) {
3048        // a one-token window has advanced the state itself (record_window): no commit graph
3049    } else {
3050        std::atomic_thread_fence(std::memory_order_seq_cst);
3051        const dpct::err0 le =
3052            DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*commit_exec_));
3053        /*
3054        DPCT1009: SYCL reports errors using exceptions and does not use error
3055        codes. Please replace the "get_error_string_dummy(...)" with a real
3056        error-handling function.
3057        */
3058        /*
3059        DPCT1001: The statement could not be removed.
3060        */
3061        /*
3062        DPCT1000: Error handling if-stmt was detected but could not be
3063        rewritten.
3064        */
3065        if (le != 0) {
3066          err = std::string("verify: commit launch: ") +
3067                dpct::get_error_string_dummy(le);
3068          return false;
3069        }
3070        // set_commit_async: no wait here - the next window runs on the same stream after it, and the drafter (its own
3071        // stream) reads only this window's final rows and its own K/V. h_commit_ is next written after the next window's
3072        // results are read, i.e. after this graph has run.  Everything else waits on commit_done_ (wait_commit).
3073        if (!g_commit_async || next_ != nullptr) {
3074            const dpct::err0 se = DPCT_CHECK_ERROR(cs_->wait());
3075            /*
3076            DPCT1009: SYCL reports errors using exceptions and does not use
3077            error codes. Please replace the "get_error_string_dummy(...)" with a
3078            real error-handling function.
3079            */
3080            /*
3081            DPCT1001: The statement could not be removed.
3082            */
3083            /*
3084            DPCT1000: Error handling if-stmt was detected but could not be
3085            rewritten.
3086            */
3087            if (se != 0) {
3088              err = std::string("verify: commit: ") +
3089                    dpct::get_error_string_dummy(se);
3090              return false;
3091            }
3092        } else {
3093            /*
3094            DPCT1024: The original code returned the error code that was
3095            further consumed by the program logic. This original code was
3096            replaced with 0. You may need to rewrite the program logic consuming
3097            the error code.
3098            */
3099            const dpct::err0 re =
3100                DPCT_CHECK_ERROR(dpct::sync_barrier(commit_done_, cs_));
3101            /*
3102            DPCT1009: SYCL reports errors using exceptions and does not use
3103            error codes. Please replace the "get_error_string_dummy(...)" with a
3104            real error-handling function.
3105            */
3106            /*
3107            DPCT1001: The statement could not be removed.
3108            */
3109            /*
3110            DPCT1000: Error handling if-stmt was detected but could not be
3111            rewritten.
3112            */
3113            if (re != 0) {
3114              err = std::string("verify: commit event: ") +
3115                    dpct::get_error_string_dummy(re);
3116              return false;
3117            }
3118            (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));
3119            commit_pending_ = true;
3120        }
3121    }
3122    if (ple_stage())   // stages that share one session must advance it once
3123        for (int t = 0; t < n_keep; ++t) {
3124            ss_->ple_prev[0] = ss_->ple_prev[1];
3125            ss_->ple_prev[1] = last_tokens_[t];
3126        }
3127    ms_commit += ms_since(t0);
3128    return next_ == nullptr || next_->commit(n_keep, err);
3129}
3130catch (sycl::exception const &exc) {
3131  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
3132            << ", line:" << __LINE__ << std::endl;
3133  std::exit(1);
3134}
3135
3136bool Verifier::wait_commit(std::string &err) try {
3137    if (commit_pending_) {
3138        const OnDevice on_device(device_);
3139        commit_pending_ = false;
3140        const dpct::err0 se = DPCT_CHECK_ERROR(commit_done_->wait_and_throw());
3141        /*
3142        DPCT1009: SYCL reports errors using exceptions and does not use error
3143        codes. Please replace the "get_error_string_dummy(...)" with a real
3144        error-handling function.
3145        */
3146        /*
3147        DPCT1001: The statement could not be removed.
3148        */
3149        /*
3150        DPCT1000: Error handling if-stmt was detected but could not be
3151        rewritten.
3152        */
3153        if (se != 0) {
3154          err = std::string("verify: commit: ") +
3155                dpct::get_error_string_dummy(se);
3156          return false;
3157        }
3158    }
3159    return next_ == nullptr || next_->wait_commit(err);
3160}
3161catch (sycl::exception const &exc) {
3162  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
3163            << ", line:" << __LINE__ << std::endl;
3164  std::exit(1);
3165}
3166
3167// SYCL port: capture every window graph now (one per window size) instead of on first use, so the first request
3168// does not pay for them (a 2,400-node graph takes tens of ms to finalize on this backend).
3169bool Verifier::warm(std::string &err) {
3170    for (int T = 1; T <= max_t_; ++T)
3171        if (!capture(T, err)) return false;
3172    return true;
3173}
3174
3175// ================================ BATCH WINDOWS (see init_slots) ================================
3176
3177bool Verifier::init_slots(const std::vector<SessionState *> &slots,
3178                          std::string &err) try {
3179    const OnDevice on_device(device_);
3180    if (g_ == nullptr || ss_ == nullptr) { err = "verify: init_slots before init"; return false; }
3181    if (slots.empty()) {
3182        err = "verify: init_slots needs at least one session";
3183        return false;
3184    }
3185    for (SessionState* x : slots) {
3186        if (x == nullptr || x->layer_lo != ss_->layer_lo || x->layer_hi != ss_->layer_hi ||
3187            x->max_cells != ss_->max_cells || x->gdn_ord0 != ss_->gdn_ord0 || x->qsa_ord0 != ss_->qsa_ord0) {
3188            err = "verify: a slot's session is not carved like the stage's own (layer range, context)";
3189            return false;
3190        }
3191    }
3192    const strata::kernels::QsaShapes s = shapes_of(*g_);
3193    const int64_t S = (int64_t) slots.size(), CB = 2 + max_t_;
3194    const int64_t TS = (s.idx_block - 1) * g_->idx_key_dim, nQ = g_->n_qsa_layers();
3195    void* d = nullptr;
3196    if (!mapped((size_t) (S * CB * 4 + 16), (void**) &h_commitb_, (void**) &m_commitb_)) {
3197        err = "verify: the batch commit staging failed";
3198        return false;
3199    }
3200    const uint64_t a = ((uint64_t) S * CB * 4 + 255) & ~255ull;
3201    if (DPCT_CHECK_ERROR(
3202            d = (void *)sycl::malloc_device(
3203                a + (uint64_t)S * std::max<int64_t>(nQ, 1) * TS * 4,
3204                dpct::get_in_order_queue())) != 0) {
3205        err = "verify: the batch buffers do not fit";
3206        return false;
3207    }
3208    arena_b_ = d;
3209    commitb_ = (int32_t*) d;
3210    tail_snap_b_ = (float*) ((uint8_t*) d + a);
3211    slots_ = slots;
3212    slot_sp_.assign(slots.size(), sampling_);   // greedy until set_slot_sampling
3213    slot_tail_.assign(slots.size(), {});
3214    std::fprintf(stderr, "strata verify: batch windows of up to %lld sequences (layers [%lld, %lld))\n", (long long) S,
3215                 (long long) lb_, (long long) le_);
3216    return true;
3217}
3218catch (sycl::exception const &exc) {
3219  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
3220            << ", line:" << __LINE__ << std::endl;
3221  std::exit(1);
3222}
3223
3224bool Verifier::capture_batch(const int *rows, int S, int hbase,
3225                             std::string &err) try {
3226    dpct::experimental::command_graph_exec_ptr &ex =
3227        exec_bm_[bkey(rows, S, hbase)];
3228    if (ex != nullptr) return true;
3229    if (DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs_)) != 0) {
3230        err = "verify: begin batch capture failed";
3231        return false;
3232    }
3233    batch_rec_ = true;
3234    row_base_ = hbase;
3235    for (int t = 0; t < S; ++t) brow_[t] = rows[t];
3236    std::string rerr;
3237    const bool ok = record_window(S, cs_, rerr);
3238    batch_rec_ = false;
3239    row_base_ = 0;
3240    dpct::experimental::command_graph_ptr graph = nullptr;
3241    const dpct::err0 ce =
3242        DPCT_CHECK_ERROR(dpct::experimental::end_recording(cs_, &graph));
3243    if (!ok || ce != 0) {
3244        if (graph) delete (graph);
3245        /*
3246        DPCT1009: SYCL reports errors using exceptions and does not use error
3247        codes. Please replace the "get_error_string_dummy(...)" with a real
3248        error-handling function.
3249        */
3250        err = !ok ? rerr
3251                  : std::string("verify: end batch capture: ") +
3252                        dpct::get_error_string_dummy(ce);
3253        return false;
3254    }
3255    const dpct::err0 ie = DPCT_CHECK_ERROR(
3256        ex = new sycl::ext::oneapi::experimental::command_graph<
3257            sycl::ext::oneapi::experimental::graph_state::executable>(
3258            graph->finalize()));
3259    delete (graph);
3260    /*
3261    DPCT1009: SYCL reports errors using exceptions and does not use error
3262    codes. Please replace the "get_error_string_dummy(...)" with a real
3263    error-handling function.
3264    */
3265    /*
3266    DPCT1001: The statement could not be removed.
3267    */
3268    /*
3269    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
3270    */
3271    if (ie != 0) {
3272      err = std::string("verify: batch instantiate: ") +
3273            dpct::get_error_string_dummy(ie);
3274      return false;
3275    }
3276    /*
3277    DPCT1007: Migration of cudaGraphUpload is not supported.
3278    */
3279    // no cudaGraphUpload on SYCL: a finalized command_graph is already resident
3280    cs_->wait();
3281    std::string list;
3282    for (int t = 0; t < S; ++t) list += (t ? "," : "") + std::to_string(rows[t]);
3283    std::fprintf(stderr, "strata verify: captured the batch window over slots %s\n", list.c_str());
3284    return true;
3285}
3286catch (sycl::exception const &exc) {
3287  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
3288            << ", line:" << __LINE__ << std::endl;
3289  std::exit(1);
3290}
3291
3292bool Verifier::capture_commit_batch(const int *rows, int S, int hbase,
3293                                    std::string &err) try {
3294    dpct::experimental::command_graph_exec_ptr &cex =
3295        commit_bm_[bkey(rows, S, hbase)];
3296    if (cex != nullptr) return true;
3297    using namespace strata::kernels;
3298    const ModelGeometry& g = *g_;
3299    const QsaShapes s = shapes_of(g);
3300    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_;
3301    const int64_t CB = 2 + MT, nQ = g.n_qsa_layers();
3302    const uint64_t gdn_floats = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size +
3303                                (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1);
3304    const int64_t TS = (s.idx_block - 1) * ID;
3305    const int64_t HS = (int64_t) NG_HIST * NG_HC_DIM;
3306    if (DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs_)) != 0) {
3307        err = "verify: begin batch commit capture failed";
3308        return false;
3309    }
3310    bool ok = true;
3311    try {
3312        for (int t = 0; t < S; ++t)
3313            if (t == 0 || rows[t] != rows[t - 1])
3314                copy_i32_from_mapped(commitb_ + (size_t) rows[t] * CB, m_commitb_ + (size_t) rows[t] * CB, CB, cs_);
3315        int64_t qsa_index = 0, gdn_index = 0;
3316        for (int64_t l = 0; l < lb_; ++l) (is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1;
3317        for (int64_t l = lb_; l < le_ && ok; ++l) {
3318            const LayerView v(*wt_, l);
3319            if (!is_qsa_layer(g, l)) {
3320                const WeightRef* wnm = need(v, "ssm_norm.weight", err);
3321                if (!wnm) { ok = false; break; }
3322                static const bool gdn_groups_on = [] {   // STRATA_BATCH_GDN_GROUPS=1: the one-row groups in one launch
3323                    const char* e = std::getenv("STRATA_BATCH_GDN_GROUPS");
3324                    return e != nullptr && std::atoi(e) != 0;
3325                }();
3326                bool one_row = S <= 8;
3327                for (int t = 1; one_row && t < S; ++t) one_row = rows[t] != rows[t - 1];
3328                GdnGroups gg;
3329                for (int t = 0; t < S;) {
3330                    const int first = t;
3331                    while (t < S && rows[t] == rows[first]) ++t;
3332                    SessionState& sx = *slots_[(size_t) rows[first]];
3333                    const int32_t* keep = commitb_ + (size_t) rows[first] * CB;
3334                    float* state = sx.gdn_state + (size_t) (gdn_index - sx.gdn_ord0) * gdn_floats;
3335                    float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
3336                    gdn_conv_commit(conv, qkv_L_ + (size_t) gdn_index * MT * C + (size_t) first * C,
3337                                    (int) C, keep, cs_);
3338                    if (gdn_groups_on && one_row) {
3339                        gg.state[gg.n] = state;
3340                        gg.keep[gg.n] = keep;
3341                        gg.first[gg.n] = first;
3342                        gg.ntok[gg.n] = 1;
3343                        ++gg.n;
3344                        continue;
3345                    }
3346                    gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C + (size_t) first * C, (int) C,
3347                                        gate_L_ + (size_t) gdn_index * MT * HV + (size_t) first * HV,
3348                                        beta_L_ + (size_t) gdn_index * MT * HV + (size_t) first * HV,
3349                                        z_ + (size_t) first * ZV, (const float*) wnm->data, EPS,
3350                                        y_dummy_ + (size_t) first * ZV, (int) g.ssm_k_heads,
3351                                        (int) HV, t - first, keep, cs_,
3352                                        t - first > 1 ? t - first : 0);   // a 1-row group keeps the 0.1.39 kernel
3353                }
3354                if (gg.n > 0)
3355                    gdn_step_norm_groups(gg, h_L_ + (size_t) gdn_index * MT * C, (int) C,
3356                                         gate_L_ + (size_t) gdn_index * MT * HV, beta_L_ + (size_t) gdn_index * MT * HV,
3357                                         z_, (const float*) wnm->data, EPS, y_dummy_, (int) g.ssm_k_heads, (int) HV, true,
3358                                         cs_);
3359                ++gdn_index;
3360            } else {
3361                const WeightRef* wikn = need(v, "indexer.k_norm.weight", err);
3362                if (!wikn) { ok = false; break; }
3363                for (int t = 0; t < S;) {
3364                    const int first = t;
3365                    while (t < S && rows[t] == rows[first]) ++t;
3366                    const QsaState& st = slots_[(size_t) rows[first]]->qsa_states[qsa_index];
3367                    copy_from_mapped(st.idx_tail, tail_snap_b_ + ((size_t) rows[first] * nQ + qsa_index) * TS,
3368                                     TS, cs_);
3369                    const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};
3370                    for (int u = first; u < t; ++u)
3371                        native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + u) * ID,
3372                                                  commitb_ + (size_t) rows[first] * CB + 2 + (u - first),
3373                                                  0, (const float*) wikn->data, EPS, ib, s, st.max_cells,
3374                                                  rope_scaling(), cs_);
3375                }
3376                ++qsa_index;
3377            }
3378        }
3379        if (ok && ss_->ple.ready() && ple_stage())
3380            for (int t = 0; t < S;) {
3381                const int first = t;
3382                while (t < S && rows[t] == rows[first]) ++t;
3383                copy_indexed(slots_[(size_t) rows[first]]->ple_hist, hist_snap_ + (size_t) first * HS,
3384                             HS, commitb_ + (size_t) rows[first] * CB + 1, HS, cs_);
3385            }
3386    } catch (const std::exception& e) {
3387        err = std::string("verify batch commit: ") + e.what();
3388        ok = false;
3389    }
3390    dpct::experimental::command_graph_ptr graph = nullptr;
3391    const dpct::err0 ce =
3392        DPCT_CHECK_ERROR(dpct::experimental::end_recording(cs_, &graph));
3393    if (!ok) {
3394        if (graph) delete (graph);
3395        return false;
3396    }
3397    if (ce != 0 ||
3398        DPCT_CHECK_ERROR(
3399            cex = new sycl::ext::oneapi::experimental::command_graph<
3400                sycl::ext::oneapi::experimental::graph_state::executable>(
3401                graph->finalize())) != 0) {
3402        if (graph) delete (graph);
3403        /*
3404        DPCT1009: SYCL reports errors using exceptions and does not use error
3405        codes. Please replace the "get_error_string_dummy(...)" with a real
3406        error-handling function.
3407        */
3408        err = std::string("verify: batch commit capture: ") +
3409              dpct::get_error_string_dummy(ce);
3410        return false;
3411    }
3412    delete (graph);
3413    return true;
3414}
3415catch (sycl::exception const &exc) {
3416  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
3417            << ", line:" << __LINE__ << std::endl;
3418  std::exit(1);
3419}
3420
3421bool Verifier::stage_batch(const int *rows, int S, int hbase,
3422                           const int32_t *tokens, const int64_t *pos,
3423                           std::string &err) try {
3424    using namespace strata::kernels;
3425    if (S < 1 || S > max_t_ || hbase < 0 ||
3426        (next_ != nullptr && hbase + S > (int) slots_.size())) {
3427        err = "verify: batch rows out of range (init_slots)";
3428        return false;
3429    }
3430    for (int t = 0; t < S; ++t) {
3431        if (rows[t] < 0 || rows[t] >= (int) slots_.size()) {
3432            err = "verify: a batch row's slot is out of range";
3433            return false;
3434        }
3435        for (int u = 0; u < t - 1; ++u)
3436            if (rows[u] == rows[t] && rows[t - 1] != rows[t]) {
3437                err = "verify: a slot's proposed rows must be contiguous";
3438                return false;
3439            }
3440        if (t > 0 && rows[t] == rows[t - 1] && pos[t] != pos[t - 1] + 1) {
3441            err = "verify: proposed rows must have consecutive positions";
3442            return false;
3443        }
3444        if (t > 0 && rows[t] == rows[t - 1] && next_ != nullptr) {
3445            err = "verify: grouped slot rows do not support a layer split yet";
3446            return false;
3447        }
3448    }
3449    if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }
3450    const ModelGeometry& g = *g_;
3451    for (int t = 0; t < S; ++t)
3452        if (pos[t] < 0 || pos[t] + 1 > slots_[(size_t) rows[t]]->max_cells) {
3453            err = "verify: slot " + std::to_string(rows[t]) + " runs past its context";
3454            return false;
3455        }
3456    refresh_ar();
3457    // --batch-mtp only (limit 0 = 0.1.39: no eviction): slot rotation creates new layouts; bound the captured graph
3458    // pairs, evicting the least recently used layout.
3459    if (batch_graph_limit_ > 0) {
3460        const auto key = bkey(rows, S, hbase);
3461        if (exec_bm_.find(key) == exec_bm_.end() && exec_bm_.size() >= batch_graph_limit_) {
3462            if (DPCT_CHECK_ERROR(cs_->wait()) != 0) {
3463                err = "verify: synchronizing before batch graph eviction failed";
3464                return false;
3465            }
3466            auto old = exec_bm_.begin();
3467            uint64_t oldest = UINT64_MAX;
3468            for (auto it = exec_bm_.begin(); it != exec_bm_.end(); ++it) {
3469                const auto u = bm_used_.find(it->first);
3470                const uint64_t t = u == bm_used_.end() ? 0 : u->second;
3471                if (t < oldest) { oldest = t; old = it; }
3472            }
3473            const auto old_key = old->first;
3474            if (old->second) delete (old->second);
3475            exec_bm_.erase(old);
3476            bm_used_.erase(old_key);
3477            auto commit_old = commit_bm_.find(old_key);
3478            if (commit_old != commit_bm_.end()) {
3479                if (commit_old->second) delete (commit_old->second);
3480                commit_bm_.erase(commit_old);
3481            }
3482        }
3483        bm_used_[key] = ++bm_tick_;
3484    }
3485    if (!capture_batch(rows, S, hbase, err) || !capture_commit_batch(rows, S, hbase, err)) return false;
3486    const Clock::time_point t0 = Clock::now();
3487    const QsaShapes s = shapes_of(g);
3488    for (int t = 0; t < S; ++t) {
3489        h_tok_[t] = tokens[t];
3490        qsa_step_fill(h_step_ + t * kStepCount, pos[t], s);
3491        for (int64_t h = 0; h < g.n_head; ++h) h_pos_[t * g.n_head + h] = (int32_t) pos[t];
3492        int32_t* pk = h_pos_ + (size_t) max_t_ * g.n_head;
3493        int32_t* pi = pk + (size_t) max_t_ * g.n_head_kv;
3494        for (int64_t h = 0; h < g.n_head_kv; ++h) pk[t * g.n_head_kv + h] = (int32_t) pos[t];
3495        for (int64_t h = 0; h < g.idx_q_heads; ++h) pi[t * g.idx_q_heads + h] = (int32_t) pos[t];
3496    }
3497    if (ss_->ple.ready() && ple_stage()) {
3498        uint32_t ple_rows[kVerifyMaxT * PLE_N_HEADS];   // (not `rows`: that is the slots of the window's rows)
3499        for (int t = 0; t < S; ++t) {
3500            const SessionState& sx = *slots_[(size_t) rows[t]];
3501            int32_t prev[2] = {sx.ple_prev[0], sx.ple_prev[1]};
3502            if (t > 0 && rows[t] == rows[t - 1]) {
3503                prev[0] = t > 1 && rows[t - 2] == rows[t] ? tokens[t - 2] : sx.ple_prev[1];
3504                prev[1] = tokens[t - 1];
3505            }
3506            ngram_rows(&tokens[t], prev, 1, ss_->ple.consts, ple_rows + t * PLE_N_HEADS);
3507        }
3508        if (!ss_->ple.table->gather_batch(ple_rows, (size_t) S, h_ple_, err)) return false;
3509    }
3510    // Each slot owns a contiguous group. The default commit keeps all its rows; speculative
3511    // decoding may change the prefix length after comparing the draft with these picks.
3512    const int64_t CB = 2 + max_t_;
3513    for (int t = 0; t < S;) {
3514        const int first = t;
3515        while (t < S && rows[t] == rows[first]) ++t;
3516        int32_t* c = h_commitb_ + (size_t) rows[first] * CB;
3517        c[0] = t - first;
3518        c[1] = t - first - 1;
3519        for (int64_t j = 0; j < max_t_; ++j)
3520            c[2 + j] = j < t - first ? (int32_t) pos[first + j] : -1;
3521    }
3522    *(volatile uint32_t*) h_seq_ = 0;
3523    for (int _i = 1; _i <= 8; ++_i) ((volatile uint32_t*) h_seq_)[_i] = 0;   /* + the payload tags/checksums */
3524    *(volatile uint32_t*) h_flag_ = 0;
3525    *(volatile uint32_t*) h_flagA_ = 0;
3526    *(volatile uint32_t*) h_flagB_ = 0;
3527    std::atomic_thread_fence(std::memory_order_seq_cst);
3528    last_t_ = S;
3529    for (int t = 0; t < S; ++t) last_rows_[t] = rows[t];
3530    row_base_ = hbase;   // the graphs' key (and nothing else) reads it until the next stage_batch
3531    last_batch_ = true;
3532    for (int t = 0; t < S; ++t) { last_tokens_[t] = tokens[t]; last_pos_b_[t] = pos[t]; }
3533    ms_host += ms_since(t0);
3534    return true;
3535}
3536catch (sycl::exception const &exc) {
3537  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
3538            << ", line:" << __LINE__ << std::endl;
3539  std::exit(1);
3540}
3541
3542bool Verifier::run_slots(int S, const int32_t* tokens, const int64_t* pos, PoolMultiFn pool, void* user, int32_t* out,
3543                         std::string& err) {
3544    int rows[8] = {};
3545    for (int t = 0; t < S && t < 8; ++t) rows[t] = t;
3546    return run_slot_rows(rows, S, tokens, pos, pool, user, out, err);
3547}
3548
3549bool Verifier::run_slot_rows(const int *rows, int S, const int32_t *tokens,
3550                             const int64_t *pos, PoolMultiFn pool, void *user,
3551                             int32_t *out, std::string &err) try {
3552    using namespace strata::kernels;
3553    const OnDevice on_device(device_);
3554    const ModelGeometry& g = *g_;
3555    prof_S_ = S;
3556    if (!stage_batch(rows, S, 0, tokens, pos, err)) return false;
3557    const dpct::err0 le =
3558        DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*exec_bm_[bkey(rows, S, 0)]));
3559    /*
3560    DPCT1009: SYCL reports errors using exceptions and does not use error
3561    codes. Please replace the "get_error_string_dummy(...)" with a real
3562    error-handling function.
3563    */
3564    /*
3565    DPCT1001: The statement could not be removed.
3566    */
3567    /*
3568    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
3569    */
3570    if (le != 0) {
3571      err = std::string("verify: batch launch: ") +
3572            dpct::get_error_string_dummy(le);
3573      return false;
3574    }
3575    (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));
3576    volatile uint32_t* const seq = h_seq_;
3577    volatile uint32_t* const flag = h_flag_;
3578    const int64_t steps = le_ - lb_;
3579    // #646: a stage whose every expert is resident plans on the device and raises no host doorbells, so the
3580    // per-layer spin below has nothing to wait for: without the PLE flag the graph finishes with the ring silent
3581    // ("verify batch: layer K never rang (graph finished)" - K is that stage's first layer), and with it the graph
3582    // sits on the PLE wait until the 20 s timeout.  As run() does: raise the PLE flag the graph's first wait reads,
3583    // let the graph run to the end, and skip the host's per-layer service (there is nothing to serve).
3584    if (all_resident_) {
3585        if (ss_->ple.ready() && ple_stage()) {
3586            std::atomic_thread_fence(std::memory_order_seq_cst);
3587            _mm_sfence();
3588            *flag = 1;
3589        }
3590        const dpct::err0 se = DPCT_CHECK_ERROR(cs_->wait());
3591        /*
3592        DPCT1009: SYCL reports errors using exceptions and does not use error
3593        codes. Please replace the "get_error_string_dummy(...)" with a real
3594        error-handling function.
3595        */
3596        /*
3597        DPCT1001: The statement could not be removed.
3598        */
3599        /*
3600        DPCT1000: Error handling if-stmt was detected but could not be
3601        rewritten.
3602        */
3603        if (se != 0) {
3604          err =
3605              std::string("verify batch: ") + dpct::get_error_string_dummy(se);
3606          return false;
3607        }
3608        copy_->wait();
3609        if (prof_on_) collect_profile();
3610        ++windows;
3611        if (le_ < g.n_layers) return next_ == nullptr || next_->run_slot_rows(rows, S, tokens, pos, pool, next_user_, out, err);
3612        if (!sample_rows(S, err)) return false;
3613        for (int t = 0; t < S; ++t) out[t] = ((volatile int32_t*) h_out_)[t];
3614        progress_at("decode");
3615        progress_beat();
3616        return true;
3617    }
3618    for (int64_t k = 0; k < steps; ++k) {
3619        const int64_t l = lb_ + k;
3620        const uint32_t want = (uint32_t) (k + 1);
3621        const Clock::time_point a = Clock::now();
3622        auto last_flush = a;
3623        uint32_t spins = 0;
3624        progress_at("verify batch: waiting for the GPU to reach layer", l);
3625        while (*seq < want) {
3626            _mm_pause();
3627            if ((++spins & 1023u) != 0) continue;
3628            const auto now = Clock::now();
3629            if (now - last_flush > std::chrono::microseconds(2000)) {
3630                last_flush = now;
3631                const dpct::err0 q = cs_->ext_oneapi_empty() ? 0 : 1;
3632                if (q != 1 && *seq < want) {
3633                    err = "verify batch: layer " + std::to_string(l) +
3634                          " never rang (" +
3635                          /*
3636                          DPCT1009: SYCL reports errors using exceptions and
3637                          does not use error codes. Please replace the
3638                          "get_error_string_dummy(...)" with a real
3639                          error-handling function.
3640                          */
3641                          (q == 0
3642                               ? std::string("graph finished")
3643                               : std::string(dpct::get_error_string_dummy(q))) +
3644                          ")";
3645                    return false;
3646                }
3647            }
3648            if (now - a > strata_ring_timeout()) {
3649                err = "verify batch: timed out at layer " + std::to_string(l) + released_note(release_gpu_waits(5000));
3650                return false;
3651            }
3652        }
3653        const Clock::time_point b = Clock::now();
3654        cur_layer_ = want - 1;
3655        set_plan_slot(0);
3656        progress_at("verify batch: the CPU experts of layer", l);
3657        if (pool != nullptr) pool(user, h_x_, h_ids_, S, ss_->k, h_ymiss_, l);
3658        progress_tick();
3659        std::atomic_thread_fence(std::memory_order_seq_cst);
3660        _mm_sfence();
3661        if (*(volatile uint32_t*) h_flagA_ != want) {        // the pool did not publish a plan: an empty one
3662            sink_.counts[0] = 0;
3663            sink_.counts[1] = 0;
3664            sink_.counts[2] = 0;
3665            sink_.start[0] = 0;
3666            sink_.start2[0] = 0;
3667            std::atomic_thread_fence(std::memory_order_seq_cst);
3668            *(volatile uint32_t*) h_flagA_ = want;
3669            raise_flag(h_flagB_, want);
3670        }
3671        *flag = want;
3672        ms_wait += std::chrono::duration<double, std::milli>(b - a).count();
3673        ms_pool += ms_since(b);
3674    }
3675    const dpct::err0 se = DPCT_CHECK_ERROR(cs_->wait());
3676    /*
3677    DPCT1009: SYCL reports errors using exceptions and does not use error
3678    codes. Please replace the "get_error_string_dummy(...)" with a real
3679    error-handling function.
3680    */
3681    /*
3682    DPCT1001: The statement could not be removed.
3683    */
3684    /*
3685    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
3686    */
3687    if (se != 0) {
3688      err = std::string("verify batch: ") + dpct::get_error_string_dummy(se);
3689      return false;
3690    }
3691    copy_->wait();
3692    if (prof_on_) collect_profile();
3693    ++windows;
3694    if (le_ < g.n_layers) return next_ == nullptr || next_->run_slot_rows(rows, S, tokens, pos, pool, next_user_, out, err);
3695    if (!sample_rows(S, err)) return false;
3696    for (int t = 0; t < S; ++t) out[t] = ((volatile int32_t*) h_out_)[t];
3697    progress_at("decode");
3698    progress_beat();
3699    return true;
3700}
3701catch (sycl::exception const &exc) {
3702  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
3703            << ", line:" << __LINE__ << std::endl;
3704  std::exit(1);
3705}
3706
3707bool Verifier::commit_slots(std::string& err) {
3708    std::vector<int> keep(slots_.size(), 0);
3709    for (int t = 0; t < last_t_; ++t) ++keep[(size_t) last_rows_[t]];
3710    return commit_slot_prefixes(keep.data(), err);
3711}
3712
3713bool Verifier::commit_slot_prefixes(const int *keep, std::string &err) try {
3714    const OnDevice on_device(device_);
3715    if (!last_batch_ || last_t_ < 1) { err = "verify: commit_slots without a batch window"; return false; }
3716    const int S = last_t_;
3717    const Clock::time_point t0 = Clock::now();
3718    const int64_t CB = 2 + max_t_;
3719    // One prefix per slot: rejected draft rows must not enter recurrent state.
3720    for (int t = 0; t < S;) {
3721        const int first = t;
3722        while (t < S && last_rows_[t] == last_rows_[first]) ++t;
3723        const int n = keep[last_rows_[first]];
3724        if (n < 1 || n > t - first) {
3725            err = "verify: accepted prefix is outside its slot group";
3726            return false;
3727        }
3728        int32_t* c = h_commitb_ + (size_t) last_rows_[first] * CB;
3729        c[0] = n;
3730        c[1] = n - 1;
3731        for (int j = 0; j < max_t_; ++j)
3732            c[2 + j] = j < n ? (int32_t) last_pos_b_[first + j] : -1;
3733    }
3734    std::atomic_thread_fence(std::memory_order_seq_cst);
3735    const dpct::err0 le = DPCT_CHECK_ERROR(
3736        (cs_)->ext_oneapi_graph(*commit_bm_[bkey(last_rows_, S, row_base_)]));
3737    /*
3738    DPCT1009: SYCL reports errors using exceptions and does not use error
3739    codes. Please replace the "get_error_string_dummy(...)" with a real
3740    error-handling function.
3741    */
3742    /*
3743    DPCT1001: The statement could not be removed.
3744    */
3745    /*
3746    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
3747    */
3748    if (le != 0) {
3749      err = std::string("verify: batch commit launch: ") +
3750            dpct::get_error_string_dummy(le);
3751      return false;
3752    }
3753    const dpct::err0 se = DPCT_CHECK_ERROR(cs_->wait());
3754    /*
3755    DPCT1009: SYCL reports errors using exceptions and does not use error
3756    codes. Please replace the "get_error_string_dummy(...)" with a real
3757    error-handling function.
3758    */
3759    /*
3760    DPCT1001: The statement could not be removed.
3761    */
3762    /*
3763    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
3764    */
3765    if (se != 0) {
3766      err = std::string("verify: batch commit: ") +
3767            dpct::get_error_string_dummy(se);
3768      return false;
3769    }
3770    if (ple_stage())
3771        for (int t = 0; t < S;) {
3772            const int first = t;
3773            while (t < S && last_rows_[t] == last_rows_[first]) ++t;
3774            SessionState& sx = *slots_[(size_t) last_rows_[first]];
3775            for (int u = first; u < first + keep[last_rows_[first]]; ++u) {
3776                sx.ple_prev[0] = sx.ple_prev[1];
3777                sx.ple_prev[1] = last_tokens_[u];
3778            }
3779        }
3780    ms_commit += ms_since(t0);
3781    return next_ == nullptr || next_->commit_slot_prefixes(keep, err);
3782}
3783catch (sycl::exception const &exc) {
3784  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
3785            << ", line:" << __LINE__ << std::endl;
3786  std::exit(1);
3787}
3788
3789bool Verifier::sample_rows(int S, std::string &err) try {
3790    bool any = false;
3791    constexpr int kSlotHistMax = 4096;   // serve's kPenaltyWindowCap
3792    std::vector<int32_t> hrows;
3793    std::vector<const int32_t*> tails(slots_.size(), nullptr);
3794    std::vector<int64_t> n_tails(slots_.size(), 0);
3795    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(); }
3796    for (int t = 0; t < S; ++t) {
3797        strata::kernels::SamplerParams sp = slot_sp_[(size_t) last_rows_[t]];
3798        const bool pen = sp.penalty_last_n > 0 && (sp.penalty_repeat != 1.0f || sp.penalty_freq != 0.0f || sp.penalty_present != 0.0f);
3799        if ((sp.greedy || sp.temperature <= 0.0f) && !pen) continue;   // a plain greedy slot keeps the window's argmax token untouched
3800        sp.counter = (uint64_t) last_pos_b_[t];   // Philox(seed, position): the solo window's draw for this position
3801        const int32_t* hist = nullptr;
3802        int hlen = 0;
3803        if (pen) {
3804            // the slot's reply tail plus its tokens in this window up to row t (slot_penalty_rows), staged on the device like a solo window's
3805            hlen = std::min(sp.penalty_last_n, kSlotHistMax);
3806            const size_t need = (size_t) S * (size_t) hlen;
3807            hrows.assign(need, -1);
3808            strata::kernels::slot_penalty_rows(last_rows_, last_tokens_, S, tails.data(), n_tails.data(), hlen, hrows.data());
3809            const OnDevice on_hist(device_);
3810            if (slot_hist_cap_ < need) {
3811                if (slot_hist_d_ != nullptr) sycl::free(slot_hist_d_, *cs_);
3812                slot_hist_d_ = sycl::malloc_device<int32_t>(need, *cs_);
3813                if (slot_hist_d_ == nullptr) { slot_hist_cap_ = 0; err = "verify batch: the penalty-history allocation failed"; return false; }
3814                slot_hist_cap_ = need;
3815            }
3816            cs_->memcpy(slot_hist_d_ + (size_t) t * (size_t) hlen, hrows.data() + (size_t) t * (size_t) hlen, (size_t) hlen * sizeof(int32_t)).wait();   // (waited: the host rows are rebuilt for the next row)
3817            hist = slot_hist_d_ + (size_t) t * (size_t) hlen;
3818        } else {
3819            sp.penalty_last_n = 0;
3820        }
3821        strata::kernels::sample_tokens(head_logits_ + (size_t) t * (size_t) n_vocab_, 1, (int) n_vocab_, hist, hlen, sp,
3822                                       m_out_ + t, cs_);
3823        any = true;
3824    }
3825    if (any && DPCT_CHECK_ERROR(cs_->wait()) != 0) {
3826      err = "verify batch: the row sampling failed"; return false;
3827    }
3828    return true;
3829}
3830catch (sycl::exception const &exc) {
3831  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
3832            << ", line:" << __LINE__ << std::endl;
3833  std::exit(1);
3834}
3835
3836bool Verifier::batch_launch(int base, int S, const int32_t *tokens,
3837                            const int64_t *pos, std::string &err) try {
3838    const OnDevice on_device(device_);
3839    if (b_running_) { err = "verify: batch_launch while this stage is busy"; return false; }
3840    int rows[8] = {};
3841    for (int t = 0; t < S && t < 8; ++t) rows[t] = base + t;
3842    if (!stage_batch(rows, S, base, tokens, pos, err)) return false;
3843    dpct::err0 le = DPCT_CHECK_ERROR(
3844        (cs_)->ext_oneapi_graph(*exec_bm_[bkey(rows, S, base)]));
3845    if (le == 0) le = DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*commit_bm_[bkey(
3846        rows, S, base)])); // right behind it: every row is kept
3847    /*
3848    DPCT1009: SYCL reports errors using exceptions and does not use error
3849    codes. Please replace the "get_error_string_dummy(...)" with a real
3850    error-handling function.
3851    */
3852    /*
3853    DPCT1001: The statement could not be removed.
3854    */
3855    /*
3856    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
3857    */
3858    if (le != 0) {
3859      err = std::string("verify: batch launch: ") +
3860            dpct::get_error_string_dummy(le);
3861      return false;
3862    }
3863    (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));
3864    if (ple_stage())   // the host's side of the commit (the hash's last two tokens)
3865        for (int t = 0; t < S; ++t) {
3866            SessionState& sx = *slots_[(size_t) rows[t]];
3867            sx.ple_prev[0] = sx.ple_prev[1];
3868            sx.ple_prev[1] = tokens[t];
3869        }
3870    b_running_ = true;
3871    b_k_ = 0;
3872    b_steps_ = le_ - lb_;
3873    b_last_ = Clock::now();
3874    return true;
3875}
3876catch (sycl::exception const &exc) {
3877  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
3878            << ", line:" << __LINE__ << std::endl;
3879  std::exit(1);
3880}
3881
3882int Verifier::batch_poll(PoolMultiFn pool, void *user, std::string &err) try {
3883    if (!b_running_) return 1;
3884    const OnDevice on_device(device_);
3885    volatile uint32_t* const seq = h_seq_;
3886    const int S = last_t_;
3887    // #646: an all-resident stage's graph raises no host doorbells (see run_slot_rows): nothing to serve per layer,
3888    // so the poll is just "has the graph finished" - except the PLE flag, which the graph's first wait reads and
3889    // only the host can raise (the same raise run_slot_rows makes).
3890    if (all_resident_ && ss_->ple.ready() && ple_stage()) {
3891        std::atomic_thread_fence(std::memory_order_seq_cst);
3892        _mm_sfence();
3893        *h_flag_ = 1;
3894    }
3895    while (!all_resident_ && b_k_ < b_steps_) {
3896        const uint32_t want = (uint32_t) (b_k_ + 1);
3897        if (*seq < want) {
3898            const auto now = Clock::now();
3899            if (now - b_last_ > std::chrono::milliseconds(2)) {
3900                const dpct::err0 q = cs_->ext_oneapi_empty() ? 0 : 1;
3901                if (q != 1 && *seq < want) {
3902                    err = "verify batch: layer " + std::to_string(lb_ + b_k_) +
3903                          " never rang (" +
3904                          /*
3905                          DPCT1009: SYCL reports errors using exceptions and
3906                          does not use error codes. Please replace the
3907                          "get_error_string_dummy(...)" with a real
3908                          error-handling function.
3909                          */
3910                          (q == 0
3911                               ? std::string("graph finished")
3912                               : std::string(dpct::get_error_string_dummy(q))) +
3913                          ")";
3914                    b_running_ = false;
3915                    return -1;
3916                }
3917                if (now - b_last_ > strata_ring_timeout()) {
3918                    err = "verify batch: timed out at layer " + std::to_string(lb_ + b_k_) + released_note(release_gpu_waits(5000));
3919                    b_running_ = false;
3920                    return -1;
3921                }
3922            }
3923            return 0;
3924        }
3925        const Clock::time_point b = Clock::now();
3926        cur_layer_ = want - 1;
3927        set_plan_slot(0);
3928        if (pool != nullptr) pool(user, h_x_, h_ids_, S, ss_->k, h_ymiss_, lb_ + b_k_);
3929        progress_tick();
3930        std::atomic_thread_fence(std::memory_order_seq_cst);
3931        _mm_sfence();
3932        if (*(volatile uint32_t*) h_flagA_ != want) {        // the pool did not publish a plan: an empty one
3933            sink_.counts[0] = 0;
3934            sink_.counts[1] = 0;
3935            sink_.counts[2] = 0;
3936            sink_.start[0] = 0;
3937            sink_.start2[0] = 0;
3938            std::atomic_thread_fence(std::memory_order_seq_cst);
3939            *(volatile uint32_t*) h_flagA_ = want;
3940            raise_flag(h_flagB_, want);
3941        }
3942        *(volatile uint32_t*) h_flag_ = want;
3943        ms_pool += ms_since(b);
3944        b_last_ = Clock::now();
3945        ++b_k_;
3946    }
3947    const dpct::err0 q = cs_->ext_oneapi_empty() ? 0 : 1;
3948    /*
3949    DPCT1001: The statement could not be removed.
3950    */
3951    /*
3952    DPCT1002: Special case error handling if-stmt was detected. You may need
3953    to rewrite this code.
3954    */
3955    if (q == 1) return 0;
3956    /*
3957    DPCT1009: SYCL reports errors using exceptions and does not use error
3958    codes. Please replace the "get_error_string_dummy(...)" with a real
3959    error-handling function.
3960    */
3961    /*
3962    DPCT1001: The statement could not be removed.
3963    */
3964    /*
3965    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
3966    */
3967    if (q != 0) {
3968      err = std::string("verify batch: ") + dpct::get_error_string_dummy(q);
3969      b_running_ = false;
3970      return -1;
3971    }
3972    const dpct::err0 qc = DPCT_CHECK_ERROR(
3973        ((copy_)->ext_oneapi_empty())); // no host function of this window may
3974                                        // raise flag B in the next
3975    /*
3976    DPCT1001: The statement could not be removed.
3977    */
3978    /*
3979    DPCT1002: Special case error handling if-stmt was detected. You may need
3980    to rewrite this code.
3981    */
3982    if (qc == 1) return 0;
3983    if (prof_on_) collect_profile();
3984    if (last_stage()) {
3985        if (!sample_rows(S, err)) { b_running_ = false; return -1; }
3986        for (int t = 0; t < S; ++t) b_out_[t] = ((volatile int32_t*) h_out_)[t];
3987    }
3988    ++windows;
3989    b_running_ = false;
3990    progress_beat();
3991    return 1;
3992}
3993catch (sycl::exception const &exc) {
3994  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
3995            << ", line:" << __LINE__ << std::endl;
3996  std::exit(1);
3997}
3998
3999bool Verifier::copy_logits(int t, float* host) const {
4000    if (next_ != nullptr) return next_->copy_logits(t, host);   // a layer split: the head is on the last stage
4001    if (head_logits_ == nullptr || host == nullptr || t < 0 || n_vocab_ <= 0) return false;
4002    try {
4003        cs_->memcpy(host, head_logits_ + (size_t) t * (size_t) n_vocab_, (size_t) n_vocab_ * sizeof(float)).wait();
4004    } catch (sycl::exception const&) {
4005        return false;
4006    }
4007    return true;
4008}
4009
4010// ================================ PIPELINED WINDOWS (see verify.hpp) ================================
4011//
4012// The window is run()'s, step for step: the same graph, the same staging, the same per-layer service (the PLE rows
4013// gathered while layer 0 is served, the zero-doorbell graph's one flag), the same commit graph.  Only the waits are
4014// split up: the host polls instead of spinning, so it can serve the other stage's window in between.
4015
4016namespace {
4017double now_ms() { return std::chrono::duration<double, std::milli>(Clock::now().time_since_epoch()).count(); }
4018}  // namespace
4019
4020void Verifier::diag_pipelined(std::FILE* f, const char* name) const {
4021    auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; };
4022    auto ev = [](dpct::event_ptr e) {
4023        try {
4024    if (e == nullptr) return "none";
4025        const dpct::err0 q = dpct::sycl_event_query(e);
4026        return q == 0 ? "done" : q == 1 ? "PENDING" : "error";
4027    }
4028    catch (sycl::exception const &exc) {
4029      std::cerr << exc.what() << "Exception caught at file:" << __FILE__
4030                << ", line:" << __LINE__ << std::endl;
4031      std::exit(1);
4032    }
4033    };
4034    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, "
4035                    "commit event %s (commit launched %d)\n", name, fl_active_ ? "IN FLIGHT" : "idle", last_t_,
4036                 (long long) last_pos0_, (long long) fl_k_, (long long) fl_total_, rd(h_seq_), rd(h_flag_), rd(h_flagA_),
4037                 rd(h_flagB_), ev(ev_done_), ev(ev_commit_), (int) commit_live_);
4038}
4039
4040bool Verifier::capture_all(std::string &err) try {
4041    const OnDevice on_device(device_);
4042    if (g_ == nullptr) { err = "verify: capture_all before init"; return false; }
4043    if (remote_opt_ != nullptr) { err = "verify: pipelined windows do not serve --remote-expert-opt"; return false; }
4044    if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }
4045    for (int T = 1; T <= max_t_; ++T)
4046        if (!capture(T, err)) return false;
4047    if (!capture_commit(err)) return false;
4048    if ((ev_done_ == nullptr &&
4049         DPCT_CHECK_ERROR(ev_done_ = new sycl::event()) != 0) ||
4050        (ev_commit_ == nullptr &&
4051         DPCT_CHECK_ERROR(ev_commit_ = new sycl::event()) != 0)) {
4052        err = "verify: event create failed";
4053        return false;
4054    }
4055    if (prof_on_ && prof_pin_ == nullptr &&
4056        /*
4057        DPCT1048: The original value cudaHostAllocDefault is not meaningful in
4058        the migrated code and was removed or replaced with 0. You may need to
4059        check the migrated code.
4060        */
4061        DPCT_CHECK_ERROR(prof_pin_ = (unsigned long long *)sycl::malloc_host(
4062                             prof_h_.size() * 8, dpct::get_in_order_queue())) !=
4063            0) {
4064        prof_pin_ = nullptr;   // the pipelined windows go unprofiled
4065                               /*
4066                               DPCT1026: The call to cudaGetLastError was removed because this
4067                               functionality is redundant in SYCL.
4068                               */
4069    }
4070    pl_ple_rows_.assign((size_t) strata::kernels::kVerifyMaxT * strata::kernels::PLE_N_HEADS, 0u);
4071    return true;
4072}
4073catch (sycl::exception const &exc) {
4074  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
4075            << ", line:" << __LINE__ << std::endl;
4076  std::exit(1);
4077}
4078
4079// The host staging of a pipelined window: run()'s (stage_inputs), and its PLE rows from `ple_prev` with their pages
4080// prefetched (they are gathered into the mapped rows when layer 0 is served, as run() does).
4081void Verifier::pl_stage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2]) {
4082    using namespace strata::kernels;
4083    stage_inputs(T, tokens, pos0);
4084    staged_ = false;   // a later run() stages its own window
4085    SessionState& ss = *ss_;
4086    fl_ple_ = ss.ple.ready() && ple_stage();
4087    if (fl_ple_) {
4088        int32_t prev[2] = {ple_prev[0], ple_prev[1]};
4089        for (int t = 0; t < T; ++t) {
4090            ngram_rows(&tokens[t], prev, 1, ss.ple.consts, pl_ple_rows_.data() + t * PLE_N_HEADS);
4091            prev[0] = prev[1];
4092            prev[1] = tokens[t];
4093            ss.ple.table->prefetch_rows(pl_ple_rows_.data() + t * PLE_N_HEADS);
4094        }
4095    }
4096    pl_prev_[0] = ple_prev[0];
4097    pl_prev_[1] = ple_prev[1];
4098}
4099
4100bool Verifier::prestage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2], std::string& err) {
4101    if (fl_active_) { err = "verify: a window is in flight on this verifier"; return false; }
4102    if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; }
4103    if (pl_ple_rows_.empty()) { err = "verify: pipelined window not prepared (capture_all)"; return false; }
4104    const Clock::time_point t0 = Clock::now();
4105    pl_stage(T, tokens, pos0, ple_prev);
4106    pl_prestaged_ = true;
4107    ms_host += ms_since(t0);
4108    return true;
4109}
4110
4111bool Verifier::pl_launch(int T, const int32_t *tokens, int64_t pos0,
4112                         std::string &err) try {
4113    const OnDevice on_device(device_);
4114    if (fl_active_) { err = "verify: a window is already in flight on this verifier"; return false; }
4115    if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; }
4116    if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; }
4117    SessionState& ss = *ss_;
4118    if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; }
4119    if (exec_[T] == nullptr || commit_exec_ == nullptr || ev_done_ == nullptr || pl_ple_rows_.empty()) {
4120        err = "verify: pipelined window not prepared (capture_all)";
4121        return false;
4122    }
4123    const Clock::time_point t0 = Clock::now();
4124    last_batch_ = false;
4125    bool staged = pl_prestaged_ && last_t_ == T && last_pos0_ == pos0;
4126    for (int t = 0; staged && t < T; ++t) staged = last_tokens_[t] == tokens[t];
4127    if (staged && ss.ple.ready() && ple_stage())
4128        staged = pl_prev_[0] == ss.ple_prev[0] && pl_prev_[1] == ss.ple_prev[1];
4129    pl_prestaged_ = false;
4130    if (!staged) pl_stage(T, tokens, pos0, ss.ple_prev);
4131    const int G = groups_[T] > 0 ? groups_[T] : 1;
4132    fl_T_ = T;
4133    fl_k_ = 0;
4134    fl_total_ = (le_ - lb_) * G;
4135    fl_prof_ = prof_on_ && G == 1 && prof_pin_ != nullptr;
4136    if (trace_h_ != nullptr) std::memset(trace_h_, 0, trace_n_ * 8);   // #649: this window's breadcrumbs only
4137    std::atomic_thread_fence(std::memory_order_seq_cst);
4138    trace_ev("WINDOW (pipelined)", -1, -1, pos0 * 16 + T);
4139    ms_host += ms_since(t0);
4140    const dpct::err0 le = DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*exec_[T]));
4141    trace_ev("LAUNCHED", -1, -1, (int64_t) le);
4142    /*
4143    DPCT1009: SYCL reports errors using exceptions and does not use error
4144    codes. Please replace the "get_error_string_dummy(...)" with a real
4145    error-handling function.
4146    */
4147    /*
4148    DPCT1001: The statement could not be removed.
4149    */
4150    /*
4151    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
4152    */
4153    if (le != 0) {
4154      err = std::string("verify: launch: ") + dpct::get_error_string_dummy(le);
4155      return false;
4156    }
4157    /*
4158    DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While
4159    the origin API might be synchronous, it depends on the type of operand
4160    memory, so you may need to call wait() on event return by memcpy API to
4161    ensure synchronization behavior.
4162    */
4163    if (fl_prof_) cs_->memcpy(prof_pin_, prof_, prof_h_.size() * 8);
4164    /*
4165    DPCT1024: The original code returned the error code that was further
4166    consumed by the program logic. This original code was replaced with 0. You
4167    may need to rewrite the program logic consuming the error code.
4168    */
4169    if (DPCT_CHECK_ERROR(dpct::sync_barrier(ev_done_, cs_)) != 0) {
4170      err = "verify: event record failed"; return false;
4171    }
4172    (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty())); // WDDM: submit now
4173    fl_active_ = true;
4174    fl_since_ms_ = fl_flush_ms_ = fl_launch_ms_ = now_ms();
4175    return true;
4176}
4177catch (sycl::exception const &exc) {
4178  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
4179            << ", line:" << __LINE__ << std::endl;
4180  std::exit(1);
4181}
4182
4183int Verifier::service(PoolMultiFn pool, void *user, std::string &err) try {
4184    if (!fl_active_) return 1;
4185    if (fl_k_ >= fl_total_) return 1;
4186    const OnDevice on_device(device_);
4187    const ModelGeometry& g = *g_;
4188    SessionState& ss = *ss_;
4189    const int T = fl_T_;
4190    // the PLE rows into the mapped staging (layer 1's pre() copies them once flag 1 is up), as run() does at k == 0
4191    auto gather_ple = [&]() -> bool {
4192        if (!fl_ple_) return true;
4193        const Clock::time_point tp = Clock::now();
4194        if (!ss.ple.table->gather_batch(pl_ple_rows_.data(), (size_t) T, h_ple_, err)) return false;
4195        std::atomic_thread_fence(std::memory_order_seq_cst);
4196        _mm_sfence();
4197        ms_host += ms_since(tp);
4198        return true;
4199    };
4200    if (all_resident_) {   // the zero-doorbell graph never rings: it waits only for flag 1 (stage 0's PLE rows)
4201        if (!gather_ple()) return -1;
4202        *(volatile uint32_t*) h_flag_ = 1;
4203        fl_k_ = fl_total_;
4204        progress_tick();
4205        return 1;
4206    }
4207    const int G = groups_[T] > 0 ? groups_[T] : 1;
4208    const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T};
4209    while (fl_k_ < fl_total_) {
4210        const int64_t l = lb_ + fl_k_ / G;
4211        const uint32_t want = (uint32_t) (fl_k_ + 1);
4212        if (*(volatile uint32_t*) h_seq_ < want) {
4213            const double now = now_ms();
4214            if (now - fl_flush_ms_ > 2.0) {   // flush WDDM and notice a dead graph, as run() does
4215                fl_flush_ms_ = now;
4216                const dpct::err0 q = dpct::sycl_event_query(ev_done_);
4217                if (q != 1 && *(volatile uint32_t *)h_seq_ < want) {
4218                    trace_ev("NEVER-RANG", fl_k_, l, (int64_t) q);
4219                    err = "verify: layer " + std::to_string(l) +
4220                          " never rang (" +
4221                          /*
4222                          DPCT1009: SYCL reports errors using exceptions and
4223                          does not use error codes. Please replace the
4224                          "get_error_string_dummy(...)" with a real
4225                          error-handling function.
4226                          */
4227                          (q == 0
4228                               ? std::string("graph finished")
4229                               : std::string(dpct::get_error_string_dummy(q))) +
4230                          ")";
4231                    return -1;
4232                }
4233                (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));
4234            }
4235            if (now - fl_since_ms_ > 20000.0) {   // #267: no spin kernel may outlive the engine
4236                trace_ev("TIMEOUT", fl_k_, l, 0);
4237                err = "verify: timed out at layer " + std::to_string(l) + released_note(release_gpu_waits(5000));
4238                return -1;
4239            }
4240            return 0;
4241        }
4242        const Clock::time_point b = Clock::now();
4243        ms_wait += now_ms() - fl_since_ms_;
4244        const int grp = (int) (fl_k_ % G);
4245        cur_layer_ = want - 1;
4246        set_plan_slot(grp);
4247        const int tb = gtb[grp], n = gte[grp] - gtb[grp];
4248        // the ring can arrive before its payload (elementwise.hpp): the pool must read a whole one
4249        if (!strata::kernels::doorbell_wait_payload(h_seq_, h_x_ + (size_t) tb * g.n_embd, (int64_t) n * g.n_embd,
4250                                                    h_ids_ + (size_t) tb * ss.k, h_w_ + (size_t) tb * ss.k,
4251                                                    (int64_t) n * ss.k, want)) {
4252            err = "verify: layer " + std::to_string(l) + " rang but its payload never arrived whole";
4253            return -1;
4254        }
4255        progress_at("verify window (pipelined): the CPU experts of layer", l);
4256        if (pool != nullptr)
4257            pool(user, h_x_ + (size_t) tb * g.n_embd, h_ids_ + (size_t) tb * ss.k, n, ss.k,
4258                 h_ymiss_ + (size_t) tb * ss.k * g.n_embd, l);
4259        if (g_trace) trace_ev(*(volatile uint32_t*) h_flagA_ == want ? "SERVED" : "SERVED-NO-PLAN-YET", fl_k_, l,
4260                              (int64_t) ms_since(b));
4261        progress_tick();
4262        std::atomic_thread_fence(std::memory_order_seq_cst);
4263        _mm_sfence();
4264        if (*(volatile uint32_t*) h_flagA_ != want) {        // the pool did not publish a plan: an empty one
4265            sink_.counts[0] = 0;
4266            sink_.counts[1] = 0;
4267            sink_.counts[2] = 0;
4268            sink_.start[0] = 0;
4269            sink_.start2[0] = 0;
4270            std::atomic_thread_fence(std::memory_order_seq_cst);
4271            *(volatile uint32_t*) h_flagA_ = want;
4272            raise_flag(h_flagB_, want);
4273        }
4274        if (fl_k_ == 0 && !gather_ple()) return -1;
4275        *(volatile uint32_t*) h_flag_ = want;
4276        ++fl_k_;
4277        ms_pool += ms_since(b);
4278        fl_since_ms_ = fl_flush_ms_ = now_ms();
4279    }
4280    return 1;
4281}
4282catch (sycl::exception const &exc) {
4283  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
4284            << ", line:" << __LINE__ << std::endl;
4285  std::exit(1);
4286}
4287
4288bool Verifier::done(std::string &err) try {
4289    if (!fl_active_ || fl_k_ < fl_total_) return false;
4290    const OnDevice on_device(device_);
4291    dpct::err0 q;
4292    try {
4293        q = (dpct::err0) dpct::sycl_event_query(ev_done_);
4294    } catch (std::exception const &e) {
4295        // a dead or foreign event used to read as the bare word "error"
4296        err = std::string("verify: the window's completion event could not be queried on device ") +
4297              std::to_string(device_) + ": " + e.what();
4298        return false;
4299    }
4300
4301    /*
4302    DPCT1009: SYCL reports errors using exceptions and does not use error
4303    codes. Please replace the "get_error_string_dummy(...)" with a real
4304    error-handling function.
4305    */
4306    /*
4307    DPCT1001: The statement could not be removed.
4308    */
4309    /*
4310    DPCT1000: Error handling if-stmt was detected but could not be
4311    rewritten.
4312    */
4313    if (q == 1) {
4314        // SYCL's "not complete" is CUDA's cudaErrorNotReady: the window is still running, which is not an error.
4315        // The DPCT migration dropped that branch, so the first poll of every pipelined window failed with
4316        // "verify: error" and --pipeline-windows never ran on this backend.  Same body as the CUDA original.
4317        const double now = now_ms();
4318        if (now - fl_flush_ms_ > 2.0) {
4319            fl_flush_ms_ = now;
4320            (void)DPCT_CHECK_ERROR(cs_->ext_oneapi_empty());
4321        }
4322        if (now - fl_since_ms_ > 20000.0)   // every layer served, and the graph still runs: #267 as above
4323            err = "verify: the window never finished" + released_note(release_gpu_waits(5000));
4324        return false;
4325    }
4326    if (q != 0) {
4327      err = std::string("verify: ") + dpct::get_error_string_dummy(q);
4328      return false;
4329    }
4330    if (copy_used_) {   // no host function of this window may raise flag B in the next one
4331        if (((copy_)->ext_oneapi_empty() ? 0 : 1) == 1) return false;
4332        copy_used_ = false;
4333    }
4334    return true;
4335}
4336catch (sycl::exception const &exc) {
4337  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
4338            << ", line:" << __LINE__ << std::endl;
4339  std::exit(1);
4340}
4341
4342bool Verifier::pl_finish(int32_t *out, std::string &err) try {
4343    using namespace strata::kernels;
4344    const OnDevice on_device(device_);
4345    const ModelGeometry& g = *g_;
4346    fl_active_ = false;
4347    if (fl_prof_) accumulate_profile(prof_pin_);
4348    ++windows;
4349    trace_ev("DONE (pipelined)", -1, -1, (int64_t) (now_ms() - fl_launch_ms_));
4350    if (le_ < g.n_layers) return true;   // an earlier stage: the hand-off is written
4351    const int T = fl_T_;
4352    const bool sampled = !sampling_.greedy && sampling_.temperature > 0.0f;
4353    if (head_sampling_ && (sampled || hist_d_ != nullptr)) {   // run()'s host-side sampling, Philox(seed, pos0 + t)
4354        SamplerParams sp = sampling_;
4355        sp.counter = (uint64_t) last_pos0_;
4356        sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_);
4357        if (DPCT_CHECK_ERROR(cs_->wait()) != 0) {
4358            err = "verify: the head sampling failed";
4359            return false;
4360        }
4361    }
4362    if (out != nullptr)
4363        for (int t = 0; t < T; ++t) out[t] = ((volatile int32_t*) h_out_)[t];
4364    progress_beat();
4365    return true;
4366}
4367catch (sycl::exception const &exc) {
4368  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
4369            << ", line:" << __LINE__ << std::endl;
4370  std::exit(1);
4371}
4372
4373bool Verifier::pl_commit_async(int n_keep, std::string &err) try {
4374    const OnDevice on_device(device_);
4375    if (n_keep < 1 || n_keep > last_t_) { err = "verify: commit count out of range"; return false; }
4376    // Debug: with a state dump requested, print what this commit is launched with, so a wrong count names
4377    // itself next to the verdict log (STRATA_PIPELINE_LOG).
4378    static const bool cdbg = std::getenv("STRATA_PIPELINE_DUMP") != nullptr;
4379    if (cdbg)
4380        std::fprintf(stderr, "strata commit: n_keep=%d T=%d pos0=%lld self_skip=%d\n", n_keep, (int) last_t_,
4381                     (long long) last_pos0_, (last_t_ == 1 && one_token_self_commit()) ? 1 : 0);
4382    if (commit_exec_ == nullptr || ev_commit_ == nullptr) { err = "verify: pipelined commit not prepared"; return false; }
4383    const Clock::time_point t0 = Clock::now();
4384    if (commit_live_) {   // its graph reads the words below when it starts: the previous one has (a window ago)
4385        dpct::err0 q;
4386        while ((q = dpct::sycl_event_query(ev_commit_)) == 1) _mm_pause();
4387        /*
4388        DPCT1009: SYCL reports errors using exceptions and does not use
4389        error codes. Please replace the "get_error_string_dummy(...)" with a
4390        real error-handling function.
4391        */
4392        /*
4393        DPCT1001: The statement could not be removed.
4394        */
4395        /*
4396        DPCT1000: Error handling if-stmt was detected but could not be
4397        rewritten.
4398        */
4399        if (q != 0) {
4400          err =
4401              std::string("verify: commit: ") + dpct::get_error_string_dummy(q);
4402          return false;
4403        }
4404    }
4405    // A one-token window advanced the GDN state itself (record_window), so the serial path's commit() skips the
4406    // commit graph for it.  The pipelined path ran the graph anyway and advanced the state twice per
4407    // single-token window; the first decode window is always one token, so the two paths' GDN states were
4408    // equal after the prompt and different after that window (STRATA_PIPELINE_DUMP), and the tokens diverged
4409    // at the fourth.  With this skip the pipelined windows are token-identical to the serial path.
4410    if (last_t_ == 1 && one_token_self_commit() && !self_commit_off_) {
4411        h_commit_[0] = n_keep;
4412        h_commit_[1] = n_keep - 1;
4413        for (int t = 0; t < max_t_; ++t) h_commit_[2 + t] = t < n_keep ? (int32_t) (last_pos0_ + t) : -1;
4414        if (ple_stage())
4415            for (int t = 0; t < n_keep; ++t) {
4416                ss_->ple_prev[0] = ss_->ple_prev[1];
4417                ss_->ple_prev[1] = last_tokens_[t];
4418            }
4419        ms_commit += ms_since(t0);
4420        return true;
4421    }
4422    h_commit_[0] = n_keep;
4423    h_commit_[1] = n_keep - 1;
4424    for (int t = 0; t < max_t_; ++t) h_commit_[2 + t] = t < n_keep ? (int32_t) (last_pos0_ + t) : -1;
4425    std::atomic_thread_fence(std::memory_order_seq_cst);
4426    const dpct::err0 le =
4427        DPCT_CHECK_ERROR((cs_)->ext_oneapi_graph(*commit_exec_));
4428    /*
4429    DPCT1009: SYCL reports errors using exceptions and does not use error
4430    codes. Please replace the "get_error_string_dummy(...)" with a real
4431    error-handling function.
4432    */
4433    /*
4434    DPCT1001: The statement could not be removed.
4435    */
4436    /*
4437    DPCT1000: Error handling if-stmt was detected but could not be
4438    rewritten.
4439    */
4440    if (le != 0) {
4441      err = std::string("verify: commit launch: ") +
4442            dpct::get_error_string_dummy(le);
4443      return false;
4444    }
4445    /*
4446    DPCT1024: The original code returned the error code that was further
4447    consumed by the program logic. This original code was replaced with 0. You
4448    may need to rewrite the program logic consuming the error code.
4449    */
4450    if (DPCT_CHECK_ERROR(dpct::sync_barrier(ev_commit_, cs_)) != 0) {
4451      err = "verify: event record failed"; return false;
4452    }
4453    (void)DPCT_CHECK_ERROR(((cs_)->ext_oneapi_empty()));
4454    commit_live_ = true;
4455    if (ple_stage())
4456        for (int t = 0; t < n_keep; ++t) {
4457            ss_->ple_prev[0] = ss_->ple_prev[1];
4458            ss_->ple_prev[1] = last_tokens_[t];
4459        }
4460    ms_commit += ms_since(t0);
4461    return true;
4462}
4463catch (sycl::exception const &exc) {
4464  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
4465            << ", line:" << __LINE__ << std::endl;
4466  std::exit(1);
4467}
4468
4469void Verifier::absorb_stats(Verifier& o) {
4470    ms_wait += o.ms_wait; ms_pool += o.ms_pool; ms_host += o.ms_host; ms_commit += o.ms_commit;
4471    windows += o.windows;
4472    o.ms_wait = o.ms_pool = o.ms_host = o.ms_commit = 0;
4473    o.windows = 0;
4474    for (int k = 0; k < 2; ++k)
4475        for (int i = 0; i < kProfPer; ++i) { prof_sum_[k][i] += o.prof_sum_[k][i]; o.prof_sum_[k][i] = 0; }
4476    prof_windows_ += o.prof_windows_;
4477    o.prof_windows_ = 0;
4478}
4479
4480void Verifier::set_expert_usage_counter(std::vector<float>* usage) {
4481    if (!expert_usage_counts_d_ || !usage || usage->size() != expert_usage_counts_h_.size())
4482        throw std::invalid_argument("mirror adaptive expert usage shape mismatch");
4483    expert_usage_counter_ = usage;
4484}
4485
4486}  // namespace strata::core